text stringlengths 7 3.69M |
|---|
import React, { Component } from 'react';
import Modal from '../components/Modal/Modal';
import { Backdrop } from '../components/Backdrop/Backdrop';
export const withModal = (ComponentToRender) => (
class extends Component {
state = {
open: false,
modalTitle: undefined,
modalContent: null,
canConfirm: undefined,
canCancel: undefined,
onConfirm: undefined,
onCancel:undefined
}
showModal = (title, content, canConfirm, onConfirm, canCancel, onCancel) => this.setState({
modalTitle: title,
modalContent: content,
open: true,
canCancel,
onCancel,
canConfirm,
onConfirm
});
closeModal = () => this.setState({ open: false });
renderModal = () => {
const { open, modalTitle, modalContent, canConfirm, canCancel, onConfirm } = this.state;
if (open) {
return (
<React.Fragment>
<Backdrop onClose={this.closeModal} />
<Modal
title={modalTitle}
canCancel={canCancel}
canConfirm={canConfirm}
onConfirm={onConfirm}
onCancel={this.closeModal}
>
{modalContent}
</Modal>
</React.Fragment>
);
} else {
return null;
}
}
render () {
return (
<React.Fragment>
{ this.renderModal() }
<ComponentToRender
{...this.props}
onShowModal={this.showModal}
onCloseModal={this.closeModal}
/>
</React.Fragment>
);
}
}
); |
import diff from '../src';
const flatResult = `{
host: hexlet.io
+ timeout: 20
- timeout: 50
- proxy: 123.234.53.22
+ verbose: true
}`;
test('flat json files', () => {
const config1 = '__tests__/__fixtures__/before.json';
const config2 = '__tests__/__fixtures__/after.json';
expect(diff(config1, config2)).toMatch(flatResult);
});
test('flat yaml files', () => {
const config1 = '__tests__/__fixtures__/before.yml';
const config2 = '__tests__/__fixtures__/after.yml';
expect(diff(config1, config2)).toMatch(flatResult);
});
test('flat ini files', () => {
const config1 = '__tests__/__fixtures__/before.ini';
const config2 = '__tests__/__fixtures__/after.ini';
expect(diff(config1, config2)).toMatch(flatResult);
});
const recursiveResult = `{
common: {
setting1: Value 1
- setting2: 200
setting3: true
- setting6: {
key: value
}
+ setting4: blah blah
+ setting5: {
key5: value5
}
}
group1: {
+ baz: bars
- baz: bas
foo: bar
}
- group2: {
abc: 12345
}
+ group3: {
fee: 100500
}
}`;
test('recursive json files', () => {
const config1 = '__tests__/__fixtures__/before-recursive.json';
const config2 = '__tests__/__fixtures__/after-recursive.json';
expect(diff(config1, config2)).toMatch(recursiveResult);
});
test('recursive yaml files', () => {
const config1 = '__tests__/__fixtures__/before-recursive.yml';
const config2 = '__tests__/__fixtures__/after-recursive.yml';
expect(diff(config1, config2)).toMatch(recursiveResult);
});
test('recursive ini files', () => {
const config1 = '__tests__/__fixtures__/before-recursive.ini';
const config2 = '__tests__/__fixtures__/after-recursive.ini';
expect(diff(config1, config2)).toMatch(recursiveResult);
});
const plainResult = `Property 'common.setting2' was removed
Property 'common.setting6' was removed
Property 'common.setting4' was added with value: blah blah
Property 'common.setting5' was added with complex value
Property 'group1.baz' was updated. From 'bas' to 'bars'
Property 'group2' was removed
Property 'group3' was added with complex value
`;
test('recursive json files - plain', () => {
const config1 = '__tests__/__fixtures__/before-recursive.json';
const config2 = '__tests__/__fixtures__/after-recursive.json';
expect(diff(config1, config2, 'plain')).toMatch(plainResult);
});
const jsonResult = '[{"name":"host","oldValue":"hexlet.io","newValue":"hexlet.io","type":"unchanged"},{"name":"timeout","oldValue":50,"newValue":20,"type":"changed"},{"name":"proxy","oldValue":"123.234.53.22","type":"removed"},{"name":"verbose","newValue":true,"type":"added"}]';
test('flat json => json', () => {
const config1 = '__tests__/__fixtures__/before.json';
const config2 = '__tests__/__fixtures__/after.json';
expect(diff(config1, config2, 'json')).toMatch(jsonResult);
});
|
//this is the source file for the FieldTaskPartReturnController
var js = new Class.create();
js.prototype = {
statusInfo: {}, //holds the worktype specific status info
WHHolderId: '', //the selected warehouse holder html id
requestData: {
ftId: {},
pt: {}, //the part type
pis: {}, //the list of the part instances
whId: '', //the warehouse id of part instances
po: {
id: '', //the purchase order Id
pId: '' //the purchase order part id
}
},
aliasTypes: {}, //the alias type translator: id => name
callbackIds: {
registerPI: '', // handler for registering PI
selectPT: '', // handler for selecting the part type
checkWH: '', // handler for checking WH
checkSN: '' // handler for checking serial number existence
},
//constructor
initialize: function (WHHolderId, searchFieldTaskCallback, updateTaskStatusCallback, searchReturnedPartCallback, balancePartsCallback) {
this.callbackIds.searchFieldTask = searchFieldTaskCallback;
this.callbackIds.updateTaskStatus = updateTaskStatusCallback;
this.callbackIds.searchReturnedPart = searchReturnedPartCallback;
this.callbackIds.balanceParts = balancePartsCallback;
this.WHHolderId = WHHolderId;
},
//functions
searchFieldTask: function() {
var tmp = {};
if ($F('txtTaskNo') === '')
{
return alert('Please enter a Task No / Client Ref!');
}
bsuiteJs.postAjax(this.callbackIds.searchFieldTask, {'txtTaskNo': $F('txtTaskNo')}, {
'onLoading': function() {
Modalbox.show('loading', {beforeLoad: function(){Modalbox.deactivate();}, 'title': 'finding field task, please be patient...'});
},
'onComplete': function (sender, param) {
try {tmp.result = bsuiteJs.getResp(param, false, true);}
catch(e) {
alert(e);
Modalbox.hide();
return;
}
if (tmp.result.ft.id === undefined || tmp.result.ft.id === null) {
alert('System Error: field task information missing!');
Modalbox.hide();
return;
}
if (tmp.result.ft.errMsg != undefined || tmp.result.ft.errMsg != null) {
alert(tmp.result.ft.errMsg);
Modalbox.hide();
return;
}
//set the hidden value to see if we update the ftp at the end of it all
if (tmp.result.ft.updateFieldTaskPropertyOnFinish != undefined && tmp.result.ft.updateFieldTaskPropertyOnFinish == true)
{
$('updateFieldTaskPropertyOnFinish').value = 1;
}
$('ftId').value = tmp.result.ft.id;
$('currentStatus').value = tmp.result.ft.status;
$('nextStatuses').value = tmp.result.ft.nextStatuses.join();
$('statusInfo').value = Object.toJSON(tmp.result.ft.statusInfo);
this.statusInfo = $F('statusInfo').evalJSON();
pageJs.bindStatusList(tmp.result.ft.nextStatuses);
$('resetPanel').removeClassName('hidden');
$('searchTaskDiv').removeClassName('currentRow').addClassName('row');
//its in RECD@LOGISTICS, so show the serial field, otherwise we show the status field
if ($('currentStatus').value == this.statusInfo.scan)
{
$('taskStatusDiv').removeClassName('hidden');
$('serialNoDiv').removeClassName('row').removeClassName('hidden').addClassName('currentRow');
$('txtSerialNo').focus();
}
else
{
$('taskStatusDiv').removeClassName('row').removeClassName('hidden').addClassName('currentRow');
$('btnUpdateStatus').focus();
}
$('txtTaskNo').disabled = true;
$('btnTaskNo').disabled = true;
$('btnUpdateStatus').disabled = true;
Modalbox.hide();
}
});
},
bindStatusList: function(statuses) {
var html = '';
if (Object.prototype.toString.call(statuses) === '[object Array]') {
statuses.each(function(status) {
html += '<option value="' + status + '" ' + '>' + status + '</option>';
});
}
$('taskStatusList').update(html);
},
updateStatusChange: function() {
$('btnUpdateStatus').disabled = true;
if ($F('taskStatusList') != $F('currentStatus'))
{
$('btnUpdateStatus').disabled = false;
}
},
updateStatus: function() {
var tmp = {};
tmp.taskNotes = '';
if ($F('ftId') === '')
{
return alert('Invalid Field Task ID');
}
this.statusInfo = $F('statusInfo').evalJSON();
tmp.failed = false;
//we're changing to the failed status, so we need to generate the notes to add to the task
if ($F('taskStatusList') == this.statusInfo.fail)
{
tmp.failed = true;
tmp.taskNotes = "";
//we had a parent match, so never got to do the parts matching
if ($('parentStatusImg').src.indexOf('redbutton') != -1)
{
tmp.taskNotes += "\n\nThe returned part type, did not match the field task part type";
}
else
{
tmp.recipe = $('recipe').value.evalJSON();
for (var i=0; i<tmp.recipe.length; i++)
{
if (tmp.recipe[i].passed == false)
{
tmp.taskNotes += "\n----------------------------------------------------------------------";
tmp.taskNotes += "\nKit Part: " + tmp.recipe[i].pc + " ::: " + tmp.recipe[i].name;
if (tmp.recipe[i].serialised)
{
tmp.taskNotes += "\nReceived: " + tmp.recipe[i].found.ptInfo;
tmp.taskNotes += "\nSerial No: " + tmp.recipe[i].found.serialNo + " (" + tmp.recipe[i].found.status + ")";
}
else
{
tmp.taskNotes += "\nExpecting: " + tmp.recipe[i].qty +
"\nReceived : " + (parseInt(tmp.recipe[i].found.good) + parseInt(tmp.recipe[i].found.notGood)) + " (Good: " + tmp.recipe[i].found.good + ", Not Good: " + tmp.recipe[i].found.notGood + ")";
}
if (i == tmp.recipe.length-1)
{
tmp.taskNotes += "\n----------------------------------------------------------------------";
}
}
}
}
if (tmp.taskNotes != '')
{
tmp.taskNotes = "The task has failed the BOM TEST for the following reason(s);\n\n" + "Returned Part: " + $('parentPiInfo').value + tmp.taskNotes;
alert(tmp.taskNotes);
}
}
else if ($F('taskStatusList') == this.statusInfo.finish || $F('taskStatusList') == this.statusInfo.fail || $F('taskStatusList') == this.statusInfo.cancel)
{
//we're either passing or failing the test, so we need to update the returned part instance to the field task property
tmp.updateFtpPiId = false;
if (($F('taskStatusList') == this.statusInfo.finish || $F('taskStatusList') == this.statusInfo.fail) && $F('updateFieldTaskPropertyOnFinish') == 1)
{
tmp.updateFtpPiId = $F('parentPiId');
}
if (!confirm("Are you sure you want to update the status to " + $F('taskStatusList') + "?"))
return;
}
bsuiteJs.postAjax(this.callbackIds.updateTaskStatus, {'ftId': $F('ftId'), 'status': $F('taskStatusList'), 'piId': $F('parentPiId'), 'taskNotes': tmp.taskNotes, 'updateFtpPiId': tmp.updateFtpPiId, 'failed': tmp.failed}, {
'onLoading': function() {
Modalbox.show('loading', {beforeLoad: function(){Modalbox.deactivate();}, 'title': 'updating task status, please be patient...'});
},
'onComplete': function (sender, param) {
try {tmp.result = bsuiteJs.getResp(param, false, true);}
catch(e) {
alert(e);
Modalbox.hide();
return;
}
if (tmp.result.ft.id === undefined || tmp.result.ft.id === null) {
alert('System Error: field task information missing!');
Modalbox.hide();
return;
}
if (tmp.result.ft.errMsg != undefined || tmp.result.ft.errMsg != null) {
alert(tmp.result.ft.errMsg);
Modalbox.hide();
return;
}
$('currentStatus').value = tmp.result.ft.status;
$('nextStatuses').value = tmp.result.ft.nextStatuses.join();
pageJs.bindStatusList(tmp.result.ft.nextStatuses);
this.statusInfo = $F('statusInfo').evalJSON();
if (tmp.result.ft.status == this.statusInfo.scan) //this is the first step, so show the serial number field
{
$('taskStatusDiv').removeClassName('currentRow').addClassName('row');
$('serialNoDiv').removeClassName('row').removeClassName('hidden').addClassName('currentRow');
$('taskStatusList').disabled = true;
$('btnUpdateStatus').disabled = true;
$('txtSerialNo').focus();
}
else if (tmp.result.ft.status == this.statusInfo.test) //now we start the test
{
$$('.partsMatchDiv').each(function(el) {
el.removeClassName('hidden');
});
$('taskStatusDiv').removeClassName('currentRow').addClassName('row');
$('recipeDiv').removeClassName('row').removeClassName('hidden').addClassName('currentRow');
$('taskStatusList').disabled = true;
$('btnUpdateStatus').disabled = true;
if ($('btnFinishTest') && $('parentStatusImg').src.indexOf('redbutton') != -1)
if ($('btnFinishTest'))
{
$('btnFinishTest').disabled = false;
}
}
else if ($F('taskStatusList') == this.statusInfo.fail || $F('taskStatusList') == this.statusInfo.finish || $F('taskStatusList') == this.statusInfo.cancel)
{
tmp.alertMsg = '';
if (tmp.result.ft.alertMsg != undefined || tmp.result.ft.alertMsg != '')
{
tmp.alertMsg = tmp.result.ft.alertMsg + "\n\n";
}
alert(tmp.alertMsg + "This task (" + $F('ftId') + ") can no longer be edited from this page, as the status is: " + $F('taskStatusList') + "\n\nThe page will now reload...");
location.reload(true);
}
else
{
$('taskStatusDiv').removeClassName('currentRow').addClassName('row');
$('serialNoDiv').removeClassName('row').removeClassName('hidden').addClassName('currentRow');
$('taskStatusList').disabled = true;
$('btnUpdateStatus').disabled = true;
$('btnSerialNo').focus();
}
Modalbox.hide();
}
});
},
searchReturnedPart: function() {
var tmp = {};
if ($F('txtSerialNo') === '')
{
return alert('Please enter a serial no to search...');
}
bsuiteJs.postAjax(this.callbackIds.searchReturnedPart, {'ftId': $F('ftId'), 'txtSerialNo': $F('txtSerialNo')}, {
'onLoading': function() {
Modalbox.show('loading', {beforeLoad: function(){Modalbox.deactivate();}, 'title': 'finding part instance, please be patient...'});
},
'onComplete': function (sender, param) {
$('registerEditPanel').addClassName('hidden');
$('registerEditLink').stopObserving('click');
try {tmp.result = bsuiteJs.getResp(param, false, true);}
catch(e) {
alert(e);
Modalbox.hide();
if (e.indexOf('Unable to find a matching part instance for serial no') != -1)
{
$('registerEditLink').observe('click', function() {window.open('/registerparts'); return false;});
$('registerEditLink').update("Register Part Instance");
$('registerEditPanel').removeClassName('hidden');
}
else if (e.indexOf('Multiple part instances found for serial no') != -1)
{
$('registerEditLink').observe('click', function() {window.open('/reregisterparts'); return false;});
$('registerEditLink').update("Edit Part Instance");
$('registerEditPanel').removeClassName('hidden');
}
return;
}
if (tmp.result.ft.id === undefined || tmp.result.ft.id === null) {
alert('System Error: field task information missing!');
Modalbox.hide();
return;
}
if (tmp.result.ft.recipe === undefined || tmp.result.ft.recipe === null) {
alert('System Error: recipe information missing!');
Modalbox.hide();
return;
}
Modalbox.hide();
$('recipe').value = Object.toJSON(tmp.result.ft.recipe); //save the recipe for final stages later
if (tmp.result.ft.parentMatch == false) //we didn't have a part type match on the task
{
$('parentStatusImg').src = $('parentStatusImg').src.replace("greenbutton","redbutton");
$('parentStatusImg').observe('mouseover', function(e) {bsuiteJs.showTooltip(e, 'toolTip', "FAILED: " + tmp.result.ft.errMsg);});
}
else
{
for (var i=0; i<tmp.result.ft.recipe.length; i++)
{
var ingredient = tmp.result.ft.recipe[i];
var hpImg = ' ';
if (ingredient.hp)
{
hpImg = '<img src="/themes/images/red_flag_16.png" onmouseover="bsuiteJs.showTooltip(event, \'toolTip\', \'This is a high priority part...\')"/>';
}
var sImg = ' ';
if (ingredient.serialised)
{
sImg = '<img src="/themes/images/s.gif" onmouseover="bsuiteJs.showTooltip(event, \'toolTip\', \'This is a serialised part...\')"/>';
}
tmp.html = '<div class="recipeDisplayDiv">';
tmp.html += '<table border="0" width="100%;" style="text-align:center; vertical-align:middle;">';
tmp.html += '<tr>';
tmp.html += '<td style="width:26px;">' + hpImg + '</td>';
tmp.html += '<td style="width:56px; font-weight:bold;"><div class="partCode">' + ingredient.pc + '</div></td>';
tmp.html += '<td style="width:26px;">' + sImg + '</td>';
tmp.html += '<td style="text-align:center; padding-right:10px;" class="partName"><div>' + ingredient.name + '</div></td>';
tmp.html += '<td style="width:30px;"><img src="/themes/images/bluebutton.png" class="statusImg" onclick="pageJs.showCapturePanel(this, ' + i + ');" onmouseover="bsuiteJs.showTooltip(event, \'toolTip\', \'Click here to verify returned part...\')"/></td>';
tmp.html += '<tr>';
tmp.html += '</table>';
tmp.html += '</div>';
tmp.html += "<input type=\"hidden\" value='" + Object.toJSON(ingredient) + "' />";
if (ingredient.serialised)
{
tmp.html += '<div class="recipeCaptureDiv hidden">';
tmp.html += '<table border="0" style="width:100%; text-align:center; vertical-align:middle;">';
tmp.html += '<tr>';
tmp.html += '<td style="width:26px;">' + hpImg + '</td>';
tmp.html += '<td style="width:56px; font-weight:bold;"><div class="partCode">' + ingredient.pc + '</div></td>';
tmp.html += '<td style="width:26px;">' + sImg + '</td>';
tmp.html += '<td style="width:220px; text-align:right;"><b>Serial No:</b> <input type="text" class="serialCapture" style="width:100px;" onkeydown="pageJs.keyPressInput(event, this);" onkeyup="pageJs.keyUpInput(event, this);"/></td>';
tmp.html += '<td style="text-align:right; padding-right:20px;"><b>Status:</b> <select onchange=""><option value="1">Good</option><option value="2">Not Good</option></select></td>';
tmp.html += '<td style="width:30px;"><input type="button" value="Go" disabled onclick="pageJs.validateRecipePart(this);" /></td>';
tmp.html += '<tr>';
tmp.html += '</table>';
tmp.html += '</div>';
}
else
{
tmp.html += '<div class="recipeCaptureDiv hidden">';
tmp.html += '<table border="0" style="width:100%; text-align:center; vertical-align:middle;">';
tmp.html += '<tr>';
tmp.html += '<td style="width:26px;">' + hpImg + '</td>';
tmp.html += '<td style="width:56px; font-weight:bold;"><div class="partCode">' + ingredient.pc + '</div></td>';
tmp.html += '<td style="width:26px;">' + sImg + '</td>';
tmp.html += '<td style="width:220px; text-align:right;"><b>Good Qty:</b> <input type="text" style="width:50px;" class="qtyCapture" onkeydown="pageJs.keyPressInput(event, this);" onkeyup="pageJs.keyUpInput(event, this);" /></td>';
tmp.html += '<td style="text-align:right; padding-right:20px;"><b>Not Good Qty:</b> <input type="text" style="width:50px;" class="qtyCapture" onkeydown="pageJs.keyPressInput(event, this);" onkeyup="pageJs.keyUpInput(event, this);"/></td>';
tmp.html += '<td style="width:30px;"><input type="button" value="Go" disabled onclick="pageJs.validateRecipePart(this); "/></td>';
tmp.html += '<tr>';
tmp.html += '</table>';
tmp.html += '</div>';
}
$('recipeDiv').insert({bottom: new Element('div', {'class':'partsMatchDiv roundedCorners hidden'}).update(tmp.html)});
}
}
$('recipeDiv').insert({bottom: new Element('div', {}).update('<div style="text-align:right; padding:2px 22px 0 0;"><input type="button" id="btnFinishTest" value="Finish Test" disabled onclick="pageJs.finishTest();"/></div>')});
$('recipeDiv').removeClassName('hidden');
for (var piId in tmp.result.ft.parentInfo)
{
$('parentPiId').value = piId;
var split = tmp.result.ft.parentInfo[piId].split(':::');
$('parentLbl').update(split[0] + '<br />' + split[1]);
$('parentPiInfo').value = "(" + $F('txtSerialNo') + ") " + split[0] + ' ::: ' + split[1];
break;
}
if (tmp.result.ft.bomMatch == false)
{
$('bomMatchImg').removeClassName('hidden');
}
$('serialNoDiv').insert({after: $('taskStatusDiv').remove()}); //move the status box down
$('scanKitMsg').addClassName('hidden');
$('txtSerialNo').disabled = true;
$('btnSerialNo').disabled = true;
$('serialNoDiv').removeClassName('currentRow').addClassName('row');
$('taskStatusDiv').removeClassName('row').addClassName('currentRow');
$('taskStatusList').disabled = false;
$('taskStatusList').focus();
/*
if (tmp.result.ft.recipe.length == 0)
{
$('btnFinishTest').disabled = false;
$('taskStatusList').disabled = true;
$('btnUpdateStatus').disabled = true;
$('recipeDiv').removeClassName('row').addClassName('currentRow');
$('btnFinishTest').focus();
}
else
{
$('taskStatusDiv').removeClassName('row').addClassName('currentRow');
$('taskStatusList').disabled = false;
$('taskStatusList').focus();
}
*/
}
});
},
toggleIndicatorBtn: function(img, pass) {
if (pass)
{
img.src = "/themes/images/greenbutton.png";
}
else
{
img.src = "/themes/images/redbutton.png";
}
},
validateRecipePart: function(el) {
var tmp = {};
tmp.pass = true;
tmp.msg = "PASSED...";
tmp.img = el.up(4).previous('div').down(3).next(3).down('img');
tmp.ingredient = el.up(4).previous('input').value.evalJSON();
tmp.recipe = $('recipe').value.evalJSON();
for (var i=0; i<tmp.recipe.length; i++)
{
if (tmp.recipe[i].ptId == tmp.ingredient.ptId)
{
tmp.recipeIndex = i;
}
}
tmp.recipe[tmp.recipeIndex].found = {};
if (!tmp.ingredient.serialised) //we don't have to post any AJAX, just do the validation here
{
tmp.good = el.up().previous(1).down('input');
tmp.notGood = el.up().previous().down('input');
if (tmp.ingredient.qty > (parseInt(tmp.good.value) + parseInt(tmp.notGood.value))) //ie we are missing some parts
{
//if (tmp.ingredient.hp) //it is a high priority part
{
tmp.pass = false;
tmp.msg = "FAILED: The quantities do not add up...";
}
}
tmp.recipe[tmp.recipeIndex].passed = tmp.pass;
tmp.img.observe('mouseover', function(e) {bsuiteJs.showTooltip(e, 'toolTip', tmp.msg);});
pageJs.toggleIndicatorBtn(tmp.img, tmp.pass); //the indicator light img
pageJs.hideCapturePanels();
tmp.recipe[tmp.recipeIndex].found.good = tmp.good.value;
tmp.recipe[tmp.recipeIndex].found.notGood = tmp.notGood.value;
$('recipe').value = Object.toJSON(tmp.recipe);
pageJs.validateTestPass();
}
else //serialised
{
var serialNo = el.up().previous(1).down('input').value;
if (serialNo === '')
{
return alert('Please scan/enter serial no...');
}
bsuiteJs.postAjax(this.callbackIds.searchReturnedPart, {'ftId': $F('ftId'), 'txtSerialNo': serialNo, 'matchPartTypeId': tmp.ingredient.ptId}, {
'onLoading': function() {
Modalbox.show('loading', {beforeLoad: function(){Modalbox.deactivate();}, 'title': 'matching part instance, please be patient...'});
},
'onComplete': function (sender, param) {
$('registerEditPanel').addClassName('hidden');
$('registerEditLink').stopObserving('click');
try {tmp.result = bsuiteJs.getResp(param, false, true);}
catch(e) {
alert(e);
Modalbox.hide();
if (e.indexOf('Unable to find a matching part instance for serial no') != -1)
{
$('registerEditLink').observe('click', function() {window.open('/registerparts'); return false;});
$('registerEditLink').update("Register Part Instance");
$('registerEditPanel').removeClassName('hidden');
}
else if (e.indexOf('Multiple part instances found for serial no') != -1)
{
$('registerEditLink').observe('click', function() {window.open('/reregisterparts'); return false;});
$('registerEditLink').update("Edit Part Instance");
$('registerEditPanel').removeClassName('hidden');
}
return;
}
if (tmp.result.pi.id === undefined || tmp.result.pi.id === null) {
alert('System Error: part instance information missing!');
Modalbox.hide();
return;
}
Modalbox.hide();
if (tmp.result.pi.errMsg != undefined || tmp.result.pi.errMsg != null) {
tmp.pass = false;
tmp.msg = "FAILED: " + tmp.result.pi.errMsg;
}
tmp.img.observe('mouseover', function(e) {bsuiteJs.showTooltip(e, 'toolTip', tmp.msg);});
pageJs.toggleIndicatorBtn(tmp.img, tmp.pass); //the indicator light img
pageJs.hideCapturePanels();
tmp.recipe[tmp.recipeIndex].found.piId = tmp.result.pi.id;
tmp.recipe[tmp.recipeIndex].found.ptInfo = tmp.result.pi.ptInfo;
tmp.recipe[tmp.recipeIndex].found.statusId = el.up().previous().down('select').value;
tmp.sel = el.up().previous().down('select');
tmp.recipe[tmp.recipeIndex].found.status = tmp.sel[tmp.sel.selectedIndex].text;
tmp.recipe[tmp.recipeIndex].found.serialNo = tmp.result.pi.serialNo;
tmp.recipe[tmp.recipeIndex].found.piId = tmp.result.pi.id;
tmp.recipe[tmp.recipeIndex].passed = tmp.pass;
$('recipe').value = Object.toJSON(tmp.recipe);
pageJs.validateTestPass();
}
});
}
},
balanceParts: function() {
var tmp = {};
if ($F($(this.WHHolderId)) === '')
{
return alert('Please select a warehouse location!');
}
bsuiteJs.postAjax(this.callbackIds.balanceParts, {'whId': $F($(this.WHHolderId)), 'ftId': $F('ftId'), 'piId': $F('parentPiId'), 'recipe': $F('recipe')}, {
'onLoading': function() {
Modalbox.show('loading', {beforeLoad: function(){Modalbox.deactivate();}, 'title': 'balancing part(s), please be patient...'});
},
'onComplete': function (sender, param) {
try {tmp.result = bsuiteJs.getResp(param, false, true);}
catch(e) {
alert(e);
Modalbox.hide();
return;
}
if (tmp.result.ft.id === undefined || tmp.result.ft.id === null) {
alert('System Error: field task information missing!');
Modalbox.hide();
return;
}
if (tmp.result.ft.errMsg != undefined || tmp.result.ft.errMsg != null) {
alert(tmp.result.ft.errMsg);
Modalbox.hide();
return;
}
Modalbox.hide();
alert('Successfully balanced, task notes added, please update the status accordingly...');
//pageJs.bindStatusList(tmp.result.ft.nextStatuses);
$('treePanel').addClassName('hidden');
$('taskStatusDiv').removeClassName('row').removeClassName('hidden').addClassName('currentRow');
$('btnUpdateStatus').disabled = false;
$('btnUpdateStatus').focus();
}
});
},
showCapturePanel: function (el, index) {
pageJs.hideCapturePanels(); //hides all first then shows below
el.up('div').up('div').addClassName('currentPartsMatchDiv');
el.up('div').addClassName('hidden');
el.up('div').next('div').removeClassName('hidden');
el.up('div').next('div').down('input').focus();
$('registerEditPanel').style.top = Element.cumulativeOffset(el.up('div').up('div')).top - 294 + 'px';
$('registerEditPanel').addClassName('hidden');
},
hideCapturePanels: function () {
$$('.recipeCaptureDiv').each(function(el) {
el.addClassName('hidden');
el.up('div').removeClassName('currentPartsMatchDiv');
el.previous('div').removeClassName('hidden');
});
},
validateTestPass: function () {
var disabled = false;
$$('.recipeDisplayDiv').each(function(el) {
if (el.down(3).next(3).down('img').src.indexOf('bluebutton') != -1)
{
disabled = true;
}
});
$('btnFinishTest').disabled = disabled;
},
finishTest: function () {
var confirmAlert = true;
var msg = "The test has PASSED, please select a location from the tree and click 'Balance Parts'";
var passed = true;
$('registerEditPanel').addClassName('hidden');
//check if the parent part match was a fail
if ($('parentStatusImg').src.indexOf('redbutton') != -1)
{
passed = false;
msg = "The test has FAILED, please update the task status accordingly.\n\nThe additional task notes will be appended to reflect the test results.";
}
else //check each of the recipe parts
{
$$('.recipeDisplayDiv').each(function(el) {
if (el.hasClassName('hidden') == false)
{
if (el.down(3).next(3).down('img').src.indexOf('redbutton') != -1)
{
passed = false;
msg = "The test has FAILED, please update the task status accordingly.\n\nThe additional task notes will be appended to reflect the test results.";
}
else if (el.down(3).next(3).down('img').src.indexOf('bluebutton') != -1)
{
alert('The test is not COMPLETED, please continue until all BLUE buttons are either RED or GREEN...');
confirmAlert = false
}
}
else
{
alert('The test is not COMPLETED, please continue until all BLUE buttons are either RED or GREEN...');
confirmAlert = false;
}
});
}
if (confirmAlert == true)
{
if (confirm("Are you sure you want to finish the test?\n\n" + msg))
{
$('btnFinishTest').disabled = true;
if (passed) //we need to display the tree
{
$('treePanel').removeClassName('hidden').removeClassName('row').addClassName('currentRow');
$('balancePanel').removeClassName('row').addClassName('currentRow');
$('taskStatusDiv').removeClassName('currentRow').addClassName('row');
$('taskStatusList').disabled = false;
$('taskStatusList').focus();
}
else //display the task status div
{
$('recipeDiv').insert({after: $('taskStatusDiv').remove()}); //move the status box down
$('taskStatusDiv').removeClassName('row').addClassName('currentRow');
$('taskStatusList').disabled = false;
$('taskStatusList').focus();
}
$('recipeDiv').removeClassName('currentRow').addClassName('row');
$$('.recipeDisplayDiv').each(function(el) {
el.down(3).next(3).down('img').cursor = 'default';
el.down(3).next(3).down('img').onclick = null;
});
}
}
},
keyPressInput: function (event, el) {
//if it's not a enter key, then return true;
if(!((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)))
{
return true;
}
if (el.id == 'txtTaskNo') //task number input
{
if (el.value == '')
{
alert('Please enter a Task No / Client Ref!')
return;
}
$('btnTaskNo').click();
}
else if (el.id == 'txtSerialNo') //this is the part returned serial field
{
if (el.value == '')
{
alert('Please scan/enter a serial no...');
return;
}
$('btnSerialNo').click();
}
else if (el.hasClassName("serialCapture")) //we're scanning a serialised part in the parts list
{
if (el.value == '')
{
alert('Please scan/enter a serial no...');
return;
}
el.up().next(1).down('input').click();
}
else if (el.hasClassName("qtyCapture")) //we're entering a non-serialised qty in the parts list
{
if (!el.value.match(/^[0-9][0-9]*$/))
{
alert('Please enter a valid quantity...');
return;
}
var btn = el.up().next().down('input');
if (btn && btn.type == 'button') //this means we are on the Not Good Qty
{
btn.click(); //click the button
}
else //we're on the Good Qty
{
el.up().next().down('input').focus(); //so focus to the Not Good
}
}
},
keyUpInput: function (event, el) {
if(!((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13))) //if it's not a enter key
{
if (el.hasClassName("serialCapture")) //we're in the serialised part field
{
if (el.value == '')
{
el.up().next(1).down('input').disabled = true;
}
else
{
el.up().next(1).down('input').disabled = false;
}
}
else if (el.hasClassName("qtyCapture")) //we're in the non-serialised qty
{
var btn = el.up().next().down('input');
if (btn && btn.type == 'button') //this means we are on the Not Good Qty
{
var good = el.up().previous().down('input');
var notGood = el;
}
else //we're on the Good Qty
{
var good = el;
var notGood = el.up().next().down('input');
var btn = el.up().next(1).down('input');
}
if (good.value.match(/^[0-9][0-9]*$/) && notGood.value.match(/^[0-9][0-9]*$/))
{
btn.disabled = false;
}
else
{
btn.disabled = true;
}
}
}
},
modal: function () {
var tmp = {};
tmp.html = '<div process="header">Processing: <span process="currIndex">1</span> / <span process="total">dszhgxdgh</span> part instance(s)</div>';
tmp.html += '<div process="errors" style="height: 400px;overflow: auto;">';
tmp.html += '<table class="DataList">';
tmp.html += '<thead><tr><td>Barcode</td><td>Error</td></tr></thead><tbody></tbody>';
tmp.html += '</table>';
tmp.html += '</div>';
Modalbox.show(new Element('div').update(tmp.html), {beforeLoad: function(){},
afterLoad: function(){},
transitions: false,
'title': '<b class="manD">Processing Part Instances, please DO NOT close or REFRESH the browser!</b>'
});
},
resetPage: function() {
if (confirm("Are you sure you want to reload the page, all data will be lost?"))
{
location.reload();
}
}
}; |
export function setCookie(days, name, value) {
const expires = new Date(Date.now() + days * 864e5).toUTCString()
const path = "/"
document.cookie = `${name}=${encodeURIComponent(value)}; expires=${expires}; path=${path}`
}
export function getCookie(name) {
let cookie = {};
document.cookie.split(";").forEach(function(el) {
let [k, v] = el.split("=");
cookie[k.trim()] = v;
})
return cookie[name];
}
export function truncate(element, limit, after) {
var trailing = element.length > limit ? after : ''
return element.substring(0, limit) + trailing
}
|
var request = require('request-promise');
module.exports = function(event) {
return request({
uri: 'https://yourwebapp.com/webhook/incoming-invoice',
data: event.payload,
json: true
})
.catch(function(err) {
return Hoist.log(err.message);
});
};
|
import React, { Component } from "react";
import axios from "axios";
import "./App.css";
import SearchBar from "./SearchBar.js";
import SearchResults from "./SearchResults.js";
import DidYouMean from "./DidYouMean.js";
class App extends Component {
constructor(props) {
super(props);
this.state = {
searchTerm: "",
valid: false,
searchSubmitted: false,
loading: false,
data: null,
places: null
};
}
handleSearch = searchTerm => {
this.setState({ searchSubmitted: false });
this.setState({ searchTerm, loading: true }, () => {
axios
.get(
`https://www.metaweather.com/api/location/search/?query=${searchTerm}`
)
.then(
res => {
if (res.data && res.data.length === 1) {
this.setState({
searchSubmitted: true,
places: res.data,
valid: true
});
this.requestWeather(res.data[0]);
} else if (res.data && res.data.length > 1) {
this.setState({
loading: false,
searchSubmitted: true,
places: res.data,
valid: true
});
} else {
this.setState({
searchSubmitted: true,
places: null,
valid: false,
loading: false
});
}
},
err => {
console.log(err);
}
);
});
};
requestWeather = place => {
this.setState({ loading: true, places: [place] });
return axios
.get(`https://www.metaweather.com/api/location/${place.woeid}`)
.then(res => {
console.log(res);
if (res.data) {
this.setState({
loading: false,
data: res.data
});
}
});
};
render() {
const {
valid,
searchTerm,
searchSubmitted,
loading,
data,
places
} = this.state;
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">WeatherDNA</h1>
<SearchBar search={this.handleSearch} />
</header>
<main>
{!valid &&
searchTerm.length >= 1 &&
searchSubmitted && (
<p style={{ color: "red", fontWeight: "bold" }}>
Location not found for your query <i>{searchTerm}</i>
</p>
)}
{loading && <p>Loading...</p>}
{!loading &&
places &&
places.length === 1 &&
data && (
<div className="App--results">
<p>Your 7 day forecast for {places[0].title}</p>
<SearchResults
results={data.consolidated_weather}
searchTerm={searchTerm}
/>
</div>
)}
{!loading &&
places &&
places.length > 1 &&
data && (
<div className="App--results">
<DidYouMean
searchTerm={searchTerm}
results={places}
onClickItem={this.requestWeather}
/>
</div>
)}
</main>
</div>
);
}
}
export default App;
|
var mongoose = require('mongoose');
var passportLocalMongoose = require('passport-local-mongoose');
var schema = new mongoose.Schema(
{
username: {type: String, unique: true},
password: String,
email: {type: String, unique: true},
}
);
schema.plugin(passportLocalMongoose);
module.exports = mongoose.model('User', schema, 'users'); |
'use strict';
angular.module('crm')
.controller('transactionReportCtrl', function ($scope, $state, ReportsSetup, $rootScope) {
$scope.portletHeaderOptions2 = {title: $rootScope.translate('reports.transactionreport.transactionreport.controller.list-of-transactions')};
$scope.goToCustomer = function (id) {
$state.go('main.customer', { cuid : id });
};
$scope.expandRow = function (row, expand) {
row.expanded = expand;
};
ReportsSetup.commonOptions($scope, 'transaction', 'TransactionReport');
ReportsSetup.transactionOptions($scope);
});
|
const express=require('express')
const route=express.Router();
const multer=require('multer')
const theauth=require('../middelware/check')
const store=multer.diskStorage({
destination:function(req,file,cb)
{
cb(null,'./img/')
},
filename:function(req,file,cb){
var dat=Date.now();
console.log(dat)
cb(null,dat +file.originalname)
}
})
const filefilter=(req,file,cb)=>{
if(file.mimetype=='image/jpeg'||file.mimetype=='image/jpg'||file.mimetype=='image/png')
{
cb(null,true)
}
else{
cb(null,false)
}
}
const upload=multer({ storage:store,limits:{
fileSize:1024*1024*2},fileFilter:filefilter})
const products=require('../model/productcol')
route.get('/',async(req,res)=>{
const find=await products.find()
.select("name price productimg")
.then((data)=>{
const ans={
count:data.length,
product:data,
}
res.status(200).json({ message:ans});
})
.catch((err)=>{res.status(404).json({ message:err});})
})
route.post('/',theauth,upload.single('productimage'),async(req,res)=>{
console.log(req.file)
try{
const obj={
name:req.body.name,
price:req.body.price,
productimg:req.file.path
}
const insert= await new products(obj).save()
.then((data)=>{
const ans={
count:data.length,
product:data,
details:{
url:'http://localhost:4000/product/'+data.id
}
}
res.status(200).json({ message:ans});
})
.catch((err)=>{res.status(404).json({ message:err});})
// console.log(insert)
// const post=await products.create(obj).then((doc)=>{console.log(doc)}).catch((err)=>{console.log(err)})
// const post=await insert.save()
// console.log("post"+insert)
res.status(200).json({ "message":insert});
}
catch(err){
console.log("err"+err)
}
console.log("inserted")
})
route.get('/:id',async(req,res)=>{
var id=req.params.id;
const find=await products.findById(id,'name price productimg')
.then((data)=>{
if(data){
res.status(200).json({ message:data});
}
else{
res.status(404).json({ message:"not valid id"});
}
})
.catch((err)=>{res.status(404).json({ message:err});})
res.status(200).json({ message:find});
})
route.patch('/:id',theauth,async(req,res)=>{
var id=req.params.id;
console.log("update")
const updates={};
for(const op of req.body)
{
updates[op.uname]=op.value;
}
const update=products.update({_id:id},{$set:updates})
.then((data)=>{
res.status(200).json({ message:"product patch byid",ans:data});
})
.catch((err)=>{res.status(404).json({ message:err});})
})
route.delete('/:id',theauth,async(req,res)=>{
var id=req.params.id;
console.log("delete")
const del=await products.findByIdAndDelete(id)
res.status(200).json({ message:"product delete byid",delete:del});
})
module.exports=route;
|
var keypress = require('keypress');
var arDrone = require('ar-drone');
var client = arDrone.createClient();
keypress(process.stdin);
var keys = {
'space': function(){
console.log('Takeoff!');
client.takeoff();
},
'l': function(){
console.log('Land!');
client.stop();
client.land();
},
'up': function(){
console.log('Move Forward!');
client.front(0.1);
},
'down': function(){
console.log('Move Backwards!');
client.back(0.1);
},
'right': function(){
console.log('Move Left!');
client.right(0.1);
},
'left': function(){
console.log('Move Right!');
client.left(0.1);
},
'pageup': function(){
console.log('Move Down!');
// client.up(0.5);
},
'pagedown': function(){
console.log('Move Up!');
client.down(0.3);
}
}
var quit = function(){
console.log('Quitting');
process.stdin.pause();
client.stop();
client.land();
client._udpControl.close();
}
process.stdin.on('keypress', function (ch, key) {
// console.log('got "keypress"', key.name);
if(key && keys[key.name]){ keys[key.name](); }
if(key && key.ctrl && key.name == 'c') { quit(); }
});
process.stdin.setRawMode(true);
process.stdin.resume();
|
import { getCookieByName } from './getCookieByName';
import { setCookie } from './setCookie';
import { eraseCookie } from './eraseCookie';
export const Utils = {
getCookieByName,
setCookie,
eraseCookie,
}; |
import React from 'react';
import MemeForm from './components/MemeForm/MemeForm';
import Flexlayout from './components/Flexlayout/Flexlayout';
import {REST_ADR_SRV} from './config/config';
import Memeviewer from './components/Memeviewer/Memeviewer';
import FlowLayout from './components/FlowLayout/FlowLayout';
import Header from './components/Header/Header';
import Footer from './components/Footer/Footer';
import Navbar from './components/Navbar/Navbar';
import store, {initialState, globalInitialState} from './store/store'
import {
BrowserRouter as Router,
Link,
Route,
Switch,
useHistory,
withRouter
} from 'react-router-dom'
import MemePreview from './components/MemePreview/MemePreview';
/**
* Composant principale de notre application
*/
class App extends React.Component{
//counter = 0;
constructor(props){
super(props);
this.state={
...initialState,
...globalInitialState
};
}
componentDidMount(){
this.setState({...store.getState().meme, ...store.getState().datas});
store.subscribe(()=>{
console.log('Etat de app mis a jour par subscribe');
this.setState({...store.getState().meme, ...store.getState().datas});
});
fetch(`${REST_ADR_SRV}/images`)
.then(flux=>flux.json())
.then(arr=>this.setState({images:arr}));
}
componentDidUpdate(){
console.log(arguments);
console.log(this.state);
}
render(){
return <>
<Header />
<Navbar />
<div className="App">
<Switch>
<Route path="/" exact>Racine</Route>
<Route path="/thumbnail">
<FlowLayout>
{this.state.memes.map((elem,i)=>
<Link to={"/view/"+elem.id} ><Memeviewer key={'meme-'+i} meme={{
...elem,
image: this.state.images.find(e => e.id === elem.imageId)
}} />
</Link>)}
</FlowLayout>
</Route>
<Route path="/new">
<Flexlayout>
<div>
<Memeviewer meme={{...this.state.current, image:this.state.images.find(e => e.id===this.state.current.imageId)}}></Memeviewer>
</div>
<MemeForm onSubmit={formState => this.setState({current: formState})} images={this.state.images}>
</MemeForm>
</Flexlayout>
</Route>
<Route path="/edit/:memeId">
<Flexlayout>
<div>
<Memeviewer meme={{...this.state.current, image:this.state.images.find(e => e.id===this.state.current.imageId)}}></Memeviewer>
</div>
<MemeForm onSubmit={formState => this.setState({current: formState})} images={this.state.images}>
</MemeForm>
</Flexlayout>
</Route>
<Route path="/view/:memeId">
<Flexlayout>
<div>
<MemePreview></MemePreview>
</div>
</Flexlayout>
</Route>
</Switch>
</div>
<Footer />
</>;
}
}
export default withRouter(App);
// {this.state.maChaine} Voici le compteur : {this.state.counter}
// <Button bgcolor="green" clickAction={argument=>{
// this.setState({counter: this.state.counter + 1});
// console.log('Depuis App : ' + argument + ' compteur : ' + this.state.counter);
// }}>
// <img src="https://cdn1.iconfinder.com/data/icons/science-technology-outline/91/Science__Technology_23-256.png" alt ="click" />
// Hello
// </Button> |
'use strict';
const express = require('express');
const router = new express.Router();
const util = require('util');
const pem = require('pem');
const Packer = require('zip-stream');
const punycode = require('punycode/');
const removeDiacritics = require('diacritics').remove;
router.get('/keys', serveKeys);
router.post('/keys', handleKeys);
function serveKeys(req, res) {
res.render('index', {
pageTitle: 'Võtmete genereerimine',
page: '/keys'
});
}
function handleKeys(req, res) {
Object.keys(req.body).forEach(key => {
req.body[key] = req.body[key].trim();
if (key === 'commonName') {
req.body[key] = punycode.toASCII(
req.body[key]
.replace(/^https?:\/+/i, '')
.split('/')
.shift()
.toLowerCase()
.trim()
);
}
if (key === 'hash') {
if (['sha1', 'md5', 'sha256'].indexOf(req.body[key].toLowerCase()) < 0) {
req.body[key] = 'sha1';
}
}
if (key === 'keyBitsize') {
req.body[key] = Number(req.body[key].trim()) || 1024;
if ([1024, 2048, 4096].indexOf(req.body[key]) < 0) {
req.body[key] = 1024;
}
}
if (key === 'emailAddress') {
req.body[key] = req.body[key].replace(/@(.*)$/, (o, domain) => '@' + punycode.toASCII(domain.split('/').shift().toLowerCase().trim()));
}
if (typeof req.body[key] === 'string') {
req.body[key] = removeDiacritics(req.body[key]);
}
});
pem.createCSR(req.body, (err, keys) => {
if (err) {
req.flash('error', (err && err.message) || err);
res.render('index', {
pageTitle: 'Võtmete genereerimine',
page: '/keys'
});
return;
}
let archive = new Packer({
comment: 'Generated by https://pangalink.net/'
}),
chunks = [];
archive.on('error', err => {
req.flash('error', (err && err.message) || err);
res.render('index', {
pageTitle: 'Võtmete genereerimine',
page: '/keys'
});
});
archive.on('data', chunk => {
if (chunk && chunk.length) {
chunks.push(chunk);
}
return true;
});
archive.on('end', chunk => {
if (chunk && chunk.length) {
chunks.push(chunk);
}
res.status(200);
res.set('Content-Description', 'File Transfer');
res.set('Content-Type', 'application/octet-stream');
res.set('Content-Disposition', util.format('attachment; filename="%s"', 'banklink.zip'));
res.send(Buffer.concat(chunks));
});
archive.entry(
keys.clientKey,
{
name: 'private_key.pem'
},
err => {
if (err) {
req.flash('error', (err && err.message) || err);
res.render('index', {
pageTitle: 'Võtmete genereerimine',
page: '/keys'
});
return;
}
archive.entry(
keys.csr,
{
name: 'csr.pem'
},
err => {
if (err) {
req.flash('error', (err && err.message) || err);
res.render('index', {
pageTitle: 'Võtmete genereerimine',
page: '/keys'
});
return;
}
archive.finish();
}
);
}
);
});
}
module.exports = router;
|
// @flow
import * as React from 'react';
import { AsyncStorage, View } from 'react-native';
import { ManageMyBookingPackage } from '@kiwicom/mobile-manage-my-booking';
import { type NavigationType } from '@kiwicom/mobile-navigation';
import { Translation } from '@kiwicom/mobile-localization';
import { StyleSheet, type DimensionType } from '@kiwicom/mobile-shared';
import Config from '../../../config/application';
type Props = {|
+navigation: NavigationType,
+dimensions: DimensionType,
+onNavigationStateChange: () => void,
|};
type State = {|
token: string | null,
bookingId: number | null,
simpleToken: string | null,
|};
export default class MMBPackageWrapper extends React.Component<Props, State> {
static navigationOptions = {
header: null,
};
state = {
token: '',
bookingId: null,
simpleToken: null,
};
willFocusSubscription: { remove: () => void };
componentDidMount() {
this.willFocusSubscription = this.props.navigation.addListener(
'willFocus',
() => {
this.fetchToken();
},
);
this.fetchToken();
}
componentWillUnmount() {
this.willFocusSubscription.remove();
}
fetchToken = async () => {
const token = await AsyncStorage.getItem('mobile:MMB-Token');
const simpleTokenData = await AsyncStorage.getItem(
'mobile:MMB-Simple-Token',
);
if (simpleTokenData) {
const { bookingId, simpleToken } = JSON.parse(simpleTokenData);
this.setState({ bookingId, simpleToken, token });
} else {
this.setState({ token, simpleToken: null, bookingId: null });
}
};
render() {
if (
!this.state.token &&
(!this.state.bookingId && !this.state.simpleToken)
) {
return (
<View style={styles.loginMessageContainer}>
<Translation passThrough="You are not logged in, go to profile and log in" />
</View>
);
}
if (this.state.bookingId && this.state.simpleToken) {
return (
<ManageMyBookingPackage
onNavigationStateChange={this.props.onNavigationStateChange}
dimensions={this.props.dimensions}
currency="EUR"
bookingId={this.state.bookingId}
simpleToken={this.state.simpleToken}
version="rn-development"
dataSaverEnabled={false}
googleMapsAPIKey={String(Config.apiKey.googleMaps)}
/>
);
}
if (this.state.token) {
return (
<ManageMyBookingPackage
onNavigationStateChange={this.props.onNavigationStateChange}
dimensions={this.props.dimensions}
currency="EUR"
accessToken={this.state.token}
version="rn-development"
dataSaverEnabled={false}
googleMapsAPIKey={String(Config.apiKey.googleMaps)}
/>
);
}
return null;
}
}
const styles = StyleSheet.create({
loginMessageContainer: {
marginTop: 60,
},
});
|
import React, { useState, useCallback, useContext } from "react"
import Img from "gatsby-image"
import { CartContext } from "../context/CartContext"
import Layout from "../components/layout"
import SEO from "../components/seo"
import Checkout from "../components/Checkout"
import styles from "./index.module.scss"
import { formatPrice } from "../utils/format"
import {
cartSubtotal,
cartTotal,
shouldPayShipping,
SHIPPING_RATE,
} from "../utils/cartTotals"
const CartPage = () => {
const [, updateState] = useState()
const forceUpdate = useCallback(() => updateState({}), [])
const [showCheckout, setShowCheckout] = useState(false)
const { cart, addToCart } = useContext(CartContext)
return (
<Layout>
<SEO title="Cart" />
<h2 className={styles.title}>Your Cart</h2>
{cart && cart.length > 0 && (
<>
{" "}
<table>
<thead>
<tr className={styles.title}>
<th>Product </th>
<th>Price</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
{cart.map(product => (
<tr>
<td>
<Img
style={{
width: "100px",
height: "100px",
verticalAlign: "middle",
}}
fixed={product.thumbnail.childImageSharp.fixed}
/>
<span style={{ marginLeft: "15px", whiteSpace: "nowrap" }}>
{product.name}
</span>
</td>
<td>{formatPrice(product.price_in_cent)}</td>
<td style={{ textAlign: "center" }}>
{product.qty}
<div>
<span
className={styles.smbutton}
onClick={() => {
addToCart(product, -1)
forceUpdate()
}}
>Less
</span>
<span
className={styles.smbutton}
onClick={() => {
addToCart(product)
forceUpdate()
}}
>More
</span>
</div>
</td>
</tr>
))}
</tbody>
</table>
<h3 className={styles.title} >SubTotal: {formatPrice(cartSubtotal(cart))} </h3>
{shouldPayShipping(cart) && (
<h3 className={styles.title}>Shipping: {formatPrice(SHIPPING_RATE)} </h3>
)}
{!shouldPayShipping(cart) && <h3 className={styles.title} >Shipping: Free</h3>}
<h3 className={styles.title}>Total: {formatPrice(cartTotal(cart))} </h3>
</>
)}
{cart && cart.length > 0 && (
<div>
<button
className={styles.button}
onClick={() => setShowCheckout(true)}
>
Checkout
</button>
</div>
)}
{showCheckout && <Checkout cart={cart} />}
</Layout>
)
}
export default CartPage
|
#!/usr/bin/env node
"use strict";
var pckg = require('./../package.json');
var chalk = require('chalk');
var clear = require('clear');
var figlet = require('figlet');
var path = require('path');
var commander = require('commander');
var reactApp = require('./react-app');
commander
.version(pckg.version)
.arguments('<projectName>')
.description("Create React client app with Datacom cli")
.action(function (projectName, c) {
reactApp.createApp(projectName);
})
.parse(process.argv);
|
/* global calculateLength, calculateRadians, define */
window._wires = [];
function Wire(a, b) {
this.a = a;
this.b = b;
// TODO: Check if this can be removed
this.uuid = 'wire#' + a.uuid + '/' + b.uuid;
window._wires.push(this);
}
Wire.prototype.getElement = function() {
if (this.wireElem) return this.wireElem;
let wireElem = document.createElement('div');
wireElem.uuid = this.uuid;
wireElem.className = 'wire';
wireElem.addEventListener('click', this.clicked.bind(this));
this.wireElem = wireElem;
this.applyElement();
return wireElem;
};
Wire.prototype.clicked = function(event) {
if (event.ctrlKey) {
this.destroy();
}
};
Wire.prototype.applyElement = function() {
// a should always be left from b
if (this.a.x > this.b.x) {
// swap a and b
let _ = this.b;
this.b = this.a;
this.a = _;
}
// Process gate coordinates
let ax = this.a.x,
ay = this.a.y,
bx = this.b.x,
by = this.b.y;
// Check coordinates
if (isNaN(ax + ay + bx + by)) {
console.error("Failed to create wire: invalid coordinates", ax, ay, bx, by);
return;
}
// Convert top left to center coordinates
ax += this.a.port_width / 2;
ay += this.a.port_width / 2;
bx += this.b.port_width / 2;
by += this.b.port_width / 2;
// Calculate length
let length = calculateLength(ax, ay, bx, by);
this.wireElem.style.height = length + 'px';
// Calculate position
let x = ax + window.WIRE_WIDTH / 2,
y = ay + window.WIRE_WIDTH / 2;
this.wireElem.style.left = x + 'px';
this.wireElem.style.top = y + 'px';
// Calculate rotation
let rotation = calculateRadians(ax, ay, bx, by) - Math.PI / 2;
this.wireElem.style.transform = 'rotate(' + rotation + 'rad)';
this.wireElem.style.transformOrigin = 'top left';
}
Wire.prototype.draw = function(circuitElem) {
circuitElem.appendChild(this.getElement());
};
Wire.prototype.destroy = function() {
if (this.wireElem) this.wireElem.parentNode.removeChild(this.wireElem);
// Remove from global wires list
let uuid = this.uuid;
// NOTE: `delete` leaves an empty spot in the array, so filter it
window._wires = window._wires.filter(wire => wire.uuid != uuid);
};
Wire.prototype.redraw = function(circuitElem) {
if (! this.wireElem) this.getElement();
this.applyElement();
this.draw(circuitElem);
};
function redrawAllWires() {
let circuitElem = document.getElementById('circuit');
window._wires.forEach(wire => {
wire.redraw(circuitElem);
});
}
define(() => Wire);
|
import React from 'react';
import { Link } from 'react-router-dom';
import { Navbar ,Nav } from 'react-bootstrap';
import logo from './../../images/logo.png';
import './Header.css';
const Header = () => {
return (
<div className="navBar">
<Navbar bg="dark" variant="dark">
<Nav className="mr-auto">
<div>
<img className="img" src={logo} />
</div>
<div>
<Link className="p-5 navStyle" to="/home">Home</Link>
<Link className="p-5 navStyle" to="/login">Login</Link>
<Link className="p-5 navStyle" to="/destination">Destination</Link>
</div>
</Nav>
</Navbar>
</div>
);
};
export default Header; |
class ClientProfile {
constructor(name, age, cpf,cep,birth,gender) {
this.name = name;
this.age = age;
this.gender = gender;
this.cpf = cpf;
this.cep = cep;
this.birth = birth;
this.state = '';
this.city ='';
}
}
module.exports.ClientProfile = ClientProfile;
|
import React from "react";
import {offerTypes} from "../../mocks/offers.proptypes";
import PropertyReviews from "../property-reviews/property-reviews";
import Map from "../map/map";
import PlaceCard from "../place-card/place-card";
const Offer = (props) => {
const {offer} = props;
return (
<div className="page">
<header className="header">
<div className="container">
<div className="header__wrapper">
<div className="header__left">
<a className="header__logo-link" href="/">
<img className="header__logo" src="/img/logo.svg" alt="6 cities logo" width="81"
height="41"/>
</a>
</div>
<nav className="header__nav">
<ul className="header__nav-list">
<li className="header__nav-item user">
<a className="header__nav-link header__nav-link--profile" href="#">
<div className="header__avatar-wrapper user__avatar-wrapper">
</div>
<span className="header__user-name user__name">Oliver.conner@gmail.com</span>
</a>
</li>
</ul>
</nav>
</div>
</div>
</header>
<main className="page__main page__main--property">
<section className="property">
<div className="property__gallery-container container">
<div className="property__gallery">
{
offer.images.map((img, i)=>{
return <div key={i} className="property__image-wrapper">
<img className="property__image" src={`/${img}`} alt="Photo studio"/>
</div>;
})
}
</div>
</div>
<div className="property__container container">
<div className="property__wrapper">
{(offer.properties.mark !== undefined) &&
<div className="property__mark">
<span>Premium</span>
</div>}
<div className="property__name-wrapper">
<h1 className="property__name">
{offer.properties.name}
</h1>
<button className="property__bookmark-button button" type="button">
<svg className="property__bookmark-icon" width="31" height="33">
<use xlinkHref="#icon-bookmark"/>
</svg>
<span className="visually-hidden">To bookmarks</span>
</button>
</div>
<div className="property__rating rating">
<div className="property__stars rating__stars">
<span style={{width: `${Math.round(offer.ratingStars * 20)}%`}}/>
<span className="visually-hidden">Rating</span>
</div>
<span className="property__rating-value rating__value">4.8</span>
</div>
<ul className="property__features">{
Object.keys(offer.features).map((featureName, i)=>(
<li key={i} className={`property__feature property__feature--${featureName}`}>
{offer.features[featureName]}
</li>)) }
</ul>
<div className="property__price">
<b className="property__price-value">{offer.price.currency}{offer.price.value}</b>
<span className="property__price-text"> {offer.price.period}</span>
</div>
<div className="property__inside">
<h2 className="property__inside-title">What's inside</h2>
<ul className="property__inside-list">
{
offer.insideList.map((inside, i)=>(
<li key={i} className="property__inside-item">{inside}</li>
))
}
</ul>
</div>
<div className="property__host">
<h2 className="property__host-title">Meet the host</h2>
<div className="property__host-user user">
<div
className={offer.host.isPro
? `property__avatar-wrapper property__avatar-wrapper--pro user__avatar-wrapper`
: `property__avatar-wrapper property__avatar-wrapper user__avatar-wrapper`}>
<img className="property__avatar user__avatar" src={offer.host.avatar}
width="74" height="74" alt="host avatar"/>
</div>
<span className="property__user-name">{offer.host.userName}</span>
</div>
<div className="property__description">{
offer.description.map((text, i)=>(<p key={i} className="property__text">{text}</p>))
}
</div>
</div>
<PropertyReviews reviews={[]}/>
</div>
</div>
<section className="property__map map">
<Map placesList={[]}/>
</section>
</section>
<div className="container">
<section className="near-places places">
<h2 className="near-places__title">Other places in the neighbourhood</h2>
<div className="near-places__list places__list">
{
[].map((placeCard)=>(
<PlaceCard type={`near-places__card`} key={placeCard.offerId}
card={placeCard}
moveHandler={()=>null} />
))
}
</div>
</section>
</div>
</main>
</div>
);
};
Offer.propTypes = {
offer: offerTypes
};
export default Offer;
|
import React from 'react';
import { UserContext } from 'Contexts';
import { Button } from 'Elements';
const User = () => (
<UserContext.Consumer>
{value => (
<div>
<h1>User Info</h1>
<h3>{value.user.name}</h3>
<Button onClick={value.logout}>Logout</Button>
<Button onClick={value.login}>Login</Button>
</div>
)}
</UserContext.Consumer>
);
export default User;
|
define(["ex1/Place"], function(Place) {
"use strict";
function Shop(title, latitude, longitude, whatDoTheySell, openHours) {
Place.apply(this, arguments);
this.whatDoTheySell = whatDoTheySell;
this.openHours = openHours;
}
Shop.prototype = Object.create(Place.prototype);
Shop.prototype.toString = function() {
var s = Place.prototype.toString.call(this);
return s + ", What do they sell: " + this.whatDoTheySell + ", Opening hours: " + this.openHours;
}
return Shop;
}); |
import Ember from 'ember';
export default Ember.Component.extend({
actions:{
onChange(value,id){
this.sendAction('radioChange',value,id);
}
}
});
|
import axios from 'axios';
import * as firebase from 'firebase';
export async function retrieveIdToken() {
const user = await firebase.auth().currentUser;
if (user) {
const idToken = await user.getIdToken();
return idToken;
} else {
throw new Error('Could not retrieve user from firebase');
}
}
export async function fetchMentor(userUid) {
const idToken = await retrieveIdToken();
const response = await axios.get(`${process.env.REACT_APP_ENV}/mentor`, {
headers: {
Authorization: 'Bearer ' + idToken,
},
});
const {mentors} = response.data;
return mentors;
}
export async function updateMentor(userUid, mentorData) {
const idToken = await retrieveIdToken();
const response = await axios.put(`${process.env.REACT_APP_ENV}/mentor`, mentorData, {
headers: {
Authorization: 'Bearer ' + idToken,
},
});
const {mentors} = response.data;
return mentors;
}
export async function allMentorsRawData() {
const idToken = await retrieveIdToken();
let response = await axios.get(`${process.env.REACT_APP_ENV}/mentors`, {
headers: {
Authorization: 'Bearer ' + idToken,
},
});
const {data} = response;
return data;
}
|
var mapFunction = function() {
if (this.PLACES != null){
for (var i = 0; i < this.PLACES.length; i++) {
var key = this.PLACES[i];
var value = {
subtotal: 1//count(this.PLACES[i])
}
/* Función emit para agregar un valor a la clave */
emit(key, value);
}
}
};
var reduceFunction = function(id, countObjVals) {
reducedVal = { total: 0 };
for (var i = 0; i < countObjVals.length; i++) {
reducedVal.total += countObjVals[i].subtotal;
}
return reducedVal;
};
db.reuterCollection.mapReduce(
mapFunction,
reduceFunction,
{out:'map1'}
);
//C:\Users\ulirp\OneDrive - Estudiantes ITCR\Cursos TEC\Primer Semestre 2021\Bases de atos II\Proyectos\TPR3\2021-1 TP3 - Noticias Reuters - MongoDB\Parseo\jsonMiedo2.json
|
var assert = require("assert");
var createTemplate = require("../");
var Crypto = require("crypto");
var execFile = require("child_process").execFile;
var File = require("fs");
describe("Passbook", function() {
before(function() {
this.template = createTemplate("coupon", {
passTypeIdentifier: "pass.com.example.passbook",
teamIdentifier: "MXL"
});
this.template.keys(__dirname + "/../keys", "secret");
this.fields = {
serialNumber: "123456",
organizationName: "Acme flowers",
description: "20% of black roses"
}
});
describe("from template", function() {
before(function() {
this.passbook = this.template.createPassbook();
});
it("should copy template fields", function() {
assert.equal(this.passbook.fields.passTypeIdentifier, "pass.com.example.passbook");
});
it("should start with no images", function() {
assert.deepEqual(this.passbook.images, {});
});
it("should create a structure based on style", function() {
assert(this.passbook.fields.coupon);
assert(!this.passbook.fields.eventTicket);
});
});
describe("without serial number", function() {
it("should not be valid", function() {
var passbook = this.template.createPassbook(cloneExcept(this.fields, "serialNumber"));
try {
passbook.validate();
assert(false, "Passbook validated without serialNumber");
} catch(ex) {
assert.equal(ex.message, "Missing field serialNumber");
}
});
});
describe("without organization name", function() {
it("should not be valid", function() {
var passbook = this.template.createPassbook(cloneExcept(this.fields, "organizationName"));
try {
passbook.validate();
assert(false, "Passbook validated without organizationName");
} catch(ex) {
assert.equal(ex.message, "Missing field organizationName");
}
});
});
describe("without description", function() {
it("should not be valid", function() {
var passbook = this.template.createPassbook(cloneExcept(this.fields, "description"));
try {
passbook.validate();
assert(false, "Passbook validated without description");
} catch(ex) {
assert.equal(ex.message, "Missing field description");
}
});
});
describe("without icon.png", function() {
it("should not be valid", function() {
var passbook = this.template.createPassbook(this.fields);
try {
passbook.validate();
assert(false, "Passbook validated without icon.png");
} catch(ex) {
assert.equal(ex.message, "Missing image icon.png");
}
});
});
describe("without logo.png", function() {
it("should not be valid", function() {
var passbook = this.template.createPassbook(this.fields);
passbook.icon("icon.png");
try {
passbook.validate();
assert(false, "Passbook validated without logo.png");
} catch(ex) {
assert.equal(ex.message, "Missing image logo.png");
}
});
});
describe("generated", function() {
before(function(done) {
var passbook = this.template.createPassbook(this.fields);
passbook.loadImagesFrom(__dirname + "/resources");
passbook.generate(function(error, buffer) {
if (error)
done(error);
else
File.writeFile("/tmp/passbook.pkpass", buffer, done);
})
});
it("should be a valid ZIP", function(done) {
execFile("unzip", ["-t", "/tmp/passbook.pkpass"], function(error, stdout) {
if (error)
error = new Error(stdout);
done(error);
})
});
it("should contain pass.json", function(done) {
unzip("/tmp/passbook.pkpass", "pass.json", function(error, buffer) {
assert.deepEqual(JSON.parse(buffer), {
passTypeIdentifier: 'pass.com.example.passbook',
teamIdentifier: 'MXL',
serialNumber: '123456',
organizationName: 'Acme flowers',
description: '20% of black roses',
coupon: {},
formatVersion: 1
});
done();
});
});
it("should contain a manifest", function(done) {
unzip("/tmp/passbook.pkpass", "manifest.json", function(error, buffer) {
assert.deepEqual(JSON.parse(buffer), {
"pass.json": "bcb463e9d94298e2d9757cea4a1af501fe5b45ae",
"icon.png": "e0f0bcd503f6117bce6a1a3ff8a68e36d26ae47f",
"icon@2x.png": "10e4a72dbb02cc526cef967420553b459ccf2b9e",
"logo.png": "abc97e3b2bc3b0e412ca4a853ba5fd90fe063551",
"logo@2x.png": "87ca39ddc347646b5625062a349de4d3f06714ac",
"strip.png": "e199fc0e2839ad5698b206d5f4b7d8cb2418927c",
"strip@2x.png": "ac640c623741c0081fb1592d6353ebb03122244f"
});
done();
});
});
it("should contain a signature", function(done) {
execFile("signpass", ["-v", "/tmp/passbook.pkpass"], function(error, stdout) {
assert(/\*\*\* SUCCEEDED \*\*\*/.test(stdout), stdout);
done();
})
});
it("should contain the icon", function(done) {
unzip("/tmp/passbook.pkpass", "icon.png", function(error, buffer) {
assert.equal(Crypto.createHash("sha1").update(buffer).digest("hex"),
"e0f0bcd503f6117bce6a1a3ff8a68e36d26ae47f");
done();
});
});
it("should contain the logo", function(done) {
unzip("/tmp/passbook.pkpass", "logo.png", function(error, buffer) {
assert.equal(Crypto.createHash("sha1").update(buffer).digest("hex"),
"abc97e3b2bc3b0e412ca4a853ba5fd90fe063551");
done();
});
});
});
});
// Clone all the fields in object, except the named field, and return a new
// object.
//
// object - Object to clone
// field - Except this field
function cloneExcept(object, field) {
var clone = {};
for (var key in object) {
if (key !== field)
clone[key] = object[key];
}
return clone;
}
function unzip(zipFile, filename, callback) {
execFile("unzip", ["-p", zipFile, filename], { encoding: "binary" }, function(error, stdout) {
if (error) {
callback(new Error(stdout));
} else {
callback(null, new Buffer(stdout, "binary"));
}
});
}
|
const fs = require('fs');
const cors = require('cors');
const https = require('https');
const helmet = require('helmet');
const geoip2 = require('geoip2');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const isProduction = (process.env.NODE_ENV === 'production');
const ipValidation = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/;
const sslOptions = {
cert: isProduction ? fs.readFileSync('ssl/cert.pem') : '',
key: isProduction ? fs.readFileSync('ssl/privkey.pem') : '',
ca: isProduction ? fs.readFileSync('ssl/fullchain.pem') : ''
};
app.use(cors());
app.use(helmet());
app.use(bodyParser.json());
app.disable('x-powered-by');
app.use('/assets', express.static('resources/flags'));
geoip2.init('./resources/GeoLite2-City.mmdb');
const getIp = ip => {
return new Promise((resolve, reject) => {
if (!ipValidation.test(ip)) {
return resolve(null);
}
geoip2.lookupSimple(ip, (err, result) => {
if (err) {
return reject(err);
}
return resolve(result);
});
});
}
app.options('/*', (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
res.send(200);
});
app.post('/ip', async (req, res) => {
const ipList = req.body.ip;
try {
if (!Array.isArray(ipList)) {
res.sendStatus(400);
}
const resolvedIPList = await Promise.all(ipList.map(ip => getIp(ip) || ''));
const flagList = resolvedIPList.map(ip => {
if (!ip || !ip.country) {
return { imagePath: 'assets/unknown.png', locationName: '未知' };
}
const imagePath = `assets/${ip.country.toLowerCase()}.png`;
const locationName = ip.city ? `${ip.city}, ${ip.country}` : ip.coutry;
return { imagePath, locationName };
});
res.json(flagList);
} catch (ex) {
console.error(ex);
res.sendStatus(500);
}
});
if (isProduction) {
https.createServer(sslOptions, app).listen(9977, () => {
console.log('App listening on port', 9977);
});
} else {
app.listen(9977, () => console.log('App listening on port 9977!'));
}
|
'use strict';
/**
* @ngdoc function
* @name quiverCmsApp.controller:SubscriptionCtrl
* @description
* # SubscriptionCtrl
* Controller of the quiverCmsApp
*/
angular.module('quiverCmsApp')
.controller('UserSubscriptionCtrl', function ($scope, subscriptionRef, pages, assignments, $stateParams, $localStorage, moment, NotificationService) {
/*
* Subscription
*/
$scope.subscription = subscriptionRef.$asObject();
$scope.isExpired = function (subscription) {
return moment().unix() > moment(subscription.expiration).unix();
};
$scope.startSubscription = function (subscription) {
subscription.expiration = moment().add(subscription.subscriptionDays, 'days').format();
subscription.$save();
};
$scope.checkSubscription = function (subscription) {
if (subscription.subscriptionType === 'content') {
if (!subscription.expiration) {
subscription.expiration = moment().add(subscription.subscriptionDays, 'days').format();
subscription.$save();
} else if ($scope.isExpired(subscription)) {
NotificationService.notify('Subscription Expired');
return $scope.redirect();
}
}
};
$scope.subscription.$loaded().then(function(subscription) {
$scope.checkSubscription(subscription);
});
/*
* Pages
*/
$scope.pages = pages.pages;
/*
* Assignments
*/
$scope.assignments = assignments.assignments;
});
|
var Matrix3 = require('./KTMatrix3');
function Matrix4(){
if (arguments.length != 16) throw "Matrix 4 must receive 16 parameters";
var c = 0;
for (var i=0;i<16;i+=4){
this[c] = arguments[i];
this[c+4] = arguments[i+1];
this[c+8] = arguments[i+2];
this[c+12] = arguments[i+3];
c += 1;
}
this.__ktm4 = true;
return this;
}
module.exports = Matrix4;
Matrix4.prototype.identity = function(){
var params = [
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
];
var c = 0;
for (var i=0;i<16;i+=4){
this[c] = params[i];
this[c+4] = params[i+1];
this[c+8] = params[i+2];
this[c+12] = params[i+3];
c += 1;
}
return this;
};
Matrix4.prototype.multiplyScalar = function(number){
var T = this;
for (var i=0;i<16;i++){
T[i] *= number;
}
return this;
};
Matrix4.prototype.multiply = function(matrix4){
if (matrix4.__ktm4){
var A1 = [this[0], this[1], this[2], this[3]];
var A2 = [this[4], this[5], this[6], this[7]];
var A3 = [this[8], this[9], this[10], this[11]];
var A4 = [this[12], this[13], this[14], this[15]];
var B1 = [matrix4[0], matrix4[4], matrix4[8], matrix4[12]];
var B2 = [matrix4[1], matrix4[5], matrix4[9], matrix4[13]];
var B3 = [matrix4[2], matrix4[6], matrix4[10], matrix4[14]];
var B4 = [matrix4[3], matrix4[7], matrix4[11], matrix4[15]];
var dot = function(col, row){
var sum = 0;
for (var j=0;j<4;j++){ sum += row[j] * col[j]; }
return sum;
};
this[0] = dot(A1, B1); this[1] = dot(A1, B2); this[2] = dot(A1, B3); this[3] = dot(A1, B4);
this[4] = dot(A2, B1); this[5] = dot(A2, B2); this[6] = dot(A2, B3); this[7] = dot(A2, B4);
this[8] = dot(A3, B1); this[9] = dot(A3, B2); this[10] = dot(A3, B3); this[11] = dot(A3, B4);
this[12] = dot(A4, B1); this[13] = dot(A4, B2); this[14] = dot(A4, B3); this[15] = dot(A4, B4);
return this;
}else if (matrix4.length == 4){
var ret = [];
var col = matrix4;
for (var i=0;i<4;i+=1){
var row = [this[i], this[i+4], this[i+8], this[i+12]];
var sum = 0;
for (var j=0;j<4;j++){
sum += row[j] * col[j];
}
ret.push(sum);
}
return ret;
}else{
throw "Invalid constructor";
}
};
Matrix4.prototype.transpose = function(){
var T = this;
var values = [
T[0], T[4], T[8], T[12],
T[1], T[5], T[9], T[13],
T[2], T[6], T[10], T[14],
T[3], T[7], T[11], T[15],
];
for (var i=0;i<16;i++){
this[i] = values[i];
}
return this;
};
Matrix4.prototype.copy = function(matrix4){
if (!matrix4.__ktm4) throw "Can only copy a Matrix4 into this matrix";
for (var i=0;i<16;i++){
this[i] = matrix4[i];
}
return this;
};
Matrix4.prototype.clone = function(){
var T = this;
return new Matrix4(
T[0], T[4], T[8], T[12],
T[1], T[5], T[9], T[13],
T[2], T[6], T[10], T[14],
T[3], T[7], T[11], T[15]
);
};
Matrix4.prototype.toFloat32Array = function(){
var T = this;
return new Float32Array([
T[0], T[1], T[2], T[3],
T[4], T[5], T[6], T[7],
T[8], T[9], T[10], T[11],
T[12], T[13], T[14], T[15]
]);
};
Matrix4.prototype.toMatrix3 = function(){
var T = this;
return new Matrix3(
T[0], T[1], T[2],
T[4], T[5], T[6],
T[8], T[9], T[10]
);
};
Matrix4.getIdentity = function(){
return new Matrix4(
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
);
};
Matrix4.getXRotation = function(radians){
var C = Math.cos(radians);
var S = Math.sin(radians);
return new Matrix4(
1, 0, 0, 0,
0, C, S, 0,
0, -S, C, 0,
0, 0, 0, 1
);
};
Matrix4.getYRotation = function(radians){
var C = Math.cos(radians);
var S = Math.sin(radians);
return new Matrix4(
C, 0, S, 0,
0, 1, 0, 0,
-S, 0, C, 0,
0, 0, 0, 1
);
};
Matrix4.getZRotation = function(radians){
var C = Math.cos(radians);
var S = Math.sin(radians);
return new Matrix4(
C, S, 0, 0,
-S, C, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
);
};
Matrix4.getTranslation = function(vector3){
if (!vector3.__ktv3) throw "Can only translate to a vector 3";
var x = vector3.x;
var y = vector3.y;
var z = vector3.z;
return new Matrix4(
1, 0, 0, x,
0, 1, 0, y,
0, 0, 1, z,
0, 0, 0, 1
);
};
Matrix4.getScale = function(vector3){
if (!vector3.__ktv3) throw "Can only scale to a vector 3";
var sx = vector3.x;
var sy = vector3.y;
var sz = vector3.z;
return new Matrix4(
sx, 0, 0, 0,
0, sy, 0, 0,
0, 0, sz, 0,
0, 0, 0, 1
);
};
Matrix4.getTransformation = function(position, rotation, scale, stack){
if (!position.__ktv3) throw "Position must be a Vector3";
if (!rotation.__ktv3) throw "Rotation must be a Vector3";
if (scale && !scale.__ktv3) throw "Scale must be a Vector3";
if (!stack) stack = 'SRxRyRzT';
var ss = (stack.indexOf("S") != -1);
var rx = (stack.indexOf("Rx") != -1);
var ry = (stack.indexOf("Ry") != -1);
var rz = (stack.indexOf("Rz") != -1);
var tt = (stack.indexOf("T") != -1);
var scale = (scale && ss)? Matrix4.getScale(scale) : Matrix4.getIdentity();
var rotationX = Matrix4.getXRotation(rotation.x);
var rotationY = Matrix4.getYRotation(rotation.y);
var rotationZ = Matrix4.getZRotation(rotation.z);
var translation = Matrix4.getTranslation(position);
var matrix;
matrix = scale;
if (rx) matrix.multiply(rotationX);
if (ry) matrix.multiply(rotationY);
if (rz) matrix.multiply(rotationZ);
if (tt) matrix.multiply(translation);
return matrix;
};
Matrix4.clearToSphericalBillboard = function(matrix4){
if (!matrix4.__ktm4) throw "Can only transform a matrix 4";
var ret = matrix4.clone();
for (var i=0;i<3;i++){
for (var j=0;j<3;j++){
ret[i * 4 + j] = 0;
}
}
ret[0] = 1;
ret[5] = 1;
ret[10] = 1;
return ret;
};
|
function hydrate(s) {
var array = s.split(" ");
console.log(array);
function filterNum(value){
if(isNaN(value) === false) {
return value;
}
}
var num = array.filter(filterNum);
//console.log(typeof num[0]);
var sum = 0;
for (var i =0;i<num.length;i++){
sum = sum + Number(num[i]);
}
console.log(sum);
if (sum == 1) {
return sum + " glass of water";
}
else if (sum > 1) {
return sum + " glasses of water";
}
} |
import Home from '../views/home'
export default [
{ path : '/', name : 'home', component : Home },
{ path : '/portfolio',
name : 'portfolio',
component: () => import(/* webpackChunkName: "teachers" */ '../views/Portfolio.vue')
},
{ path : '/portfolio/:id',
name : 'portfolio-name',
component: () => import(/* webpackChunkName: "teacher" */ '../views/PortfolioItem.vue')
},
{ path : '/logofolio',
name : 'logofolio',
component: () => import(/* webpackChunkName: "teacher" */ '../views/Logofolio.vue')
},
{ path : '/blog/',
name : 'blog-posts',
component: () => import(/* webpackChunkName: "teacher" */ '../views/BlogPost.vue')
},
{ path : '/blog/:id',
name : 'blog-post',
component: () => import(/* webpackChunkName: "teacher" */ '../views/BlogPosts.vue')
},
{ path: '*', component: () => import(/* webpackChunkName: "notfound" */ '../views/NotFound.vue')}
]
|
alert('注意してください!!');
|
/* begin copyright text
*
* Copyright © 2018 PTC Inc., Its Subsidiary Companies, and /or its Partners. All Rights Reserved.
*
* end copyright text
*/
/* jshint node: true */
/* jshint strict: global */
/* jshint camelcase: false */
/* jshint esnext: true */
'use strict';
const debug = require('debug')('vxs:fixtimer');
class FixedStartIntervalTimer {
constructor(dayTimeAsDate, intervalMs) {
if (!(dayTimeAsDate instanceof Date)) {
throw new Error("'dayTimeAsDate' parameter type must be Date");
}
if (Number.isNaN(+dayTimeAsDate)) {
throw new Error("'dayTimeAsDate' value is Invalid Date");
}
if (!Number.isInteger(intervalMs) || intervalMs <= 0) {
throw new Error("'intervalMs' parameter must be a positive integer");
}
this.dayTimeAsDate = dayTimeAsDate;
this.intervalMs = intervalMs;
this.runs = 0;
var now = +this.now();
this._firstRunTime = FixedStartIntervalTimer.combineDateAndTime(new Date(now + 100), this.dayTimeAsDate);
if (+this._firstRunTime < now) {
this._firstRunTime = new Date(+this._firstRunTime + msOf24hours);
}
this.cancel = this.clearTimer;
}
now() { return new Date(); }
firstRunTime() { return this._firstRunTime; }
clearTimer() {
if (this.intervalTimer) {
clearInterval(this.intervalTimer);
this.intervalTimer = undefined;
} else if (this.timeoutTimer) {
clearInterval(this.timeoutTimer);
this.timeoutTimer = undefined;
}
}
onError(err) {
debug("Job error", err);
}
run(callback) {
if (typeof(callback) !== 'function') {
throw new Error("callback must be a function");
}
let invoke = () => {
this.runs++;
try {
callback();
} catch(e) {
this.onError(e);
}
};
var self = this;
this.timeoutTimer = setTimeout(function() {
debug("In the first invokation");
self.timeoutTimer = null;
self.intervalTimer = setInterval(invoke, self.intervalMs);
invoke();
}, self._firstRunTime - self.now() - 1);
}
}
const msOf24hours = 24*60*60*1000;
FixedStartIntervalTimer.combineDateAndTime = function combineDateAndTime(dateSource, timeSource) {
var date = +dateSource;
var time = +timeSource;
return new Date(date - date % msOf24hours + (time % msOf24hours));
};
module.exports = FixedStartIntervalTimer;
|
(function(){
describe('MerchantsCtrl', function () {
var formCtrl, fakeUser, apiService, scope, formValidator, notifyService;
beforeEach(function(){
formCtrl = quickmock({
providerName: 'MerchantsCtrl',
moduleName: 'crm',
useActualDependencies: true,
mockModules: ['QuickMockDemoMocks']
});
fakeUser = {name: 'Bob'};
apiService = formCtrl.$mocks.APIService; // local aliases for $mocks can be useful
scope = formCtrl.$mocks.$scope; // if you are referencing them often
formValidator = formCtrl.$mocks.UserFormValidator;
notifyService = formCtrl.$mocks.NotificationService;
});
it('should retrieve the user data when initialized', function(){
expect(scope.portletHeaderOptions).toEqual({title: 'Settings'}); // $scope.user should be null
});
});
})();
|
'use strict';
app.controller('SeoCtrl', function ($scope, factSeo, factDomains, $timeout, $q) {
console.log ('SeoCtrl');
function loadDomains() {
var deferred = $q.defer();
// load existing domains and show them
factDomains.getAll().then(function(data) {
$scope.allDomains = data;
console.log('SeoCtrl: $scope.allDomains: ' + JSON.stringify(data));
$scope.showSuccess = true;
$scope.alertSuccessMessage = "domains successfully loaded!";
$timeout(function() {
$scope.showSuccess = false;
$scope.alertSuccessMessage = '';
}, 3000);
deferred.resolve(true);
}, function(error) {
$scope.allDomains = [];
console.log('SeoCtrl: ERROR fetching Domains $scope.allDomains: ' + JSON.stringify(error));
$scope.showError = true;
$scope.alertErrorMessage = "error while laoding domains from the server!";
$timeout(function() {
$scope.showError = false;
$scope.alertErrorMessage = '';
}, 3000);
deferred.reject(false);
});
return deferred.promise;
}
$scope.seoWordlistUpdate = function () {
console.log('seoWordlistUpdate: started "startJob"');
factSeo.updateWordlist().then(function(status) {
console.log('SeoCtrl: seoWordlistUpdate. SUCCESS: status: ' + JSON.stringify(status));
$scope.showSuccess = true;
$scope.alertSuccessMessage = "job successfully sent to the server!";
$timeout(function() {
$scope.showSuccess = false;
$scope.alertSuccessMessage = '';
}, 3000);
}, function (error) {
console.log('SeoCtrl: seoWordlistUpdate. ERROR: error: ' + JSON.stringify(error));
$timeout(function() {
$scope.showError = false;
$scope.alertErrorMessage = '';
}, 3000);
$scope.showError = true;
$scope.alertErrorMessage = "error while sending job to the server!";
});
console.log('SeoCtrl: ended "seoWordlistUpdate"');
};
loadDomains();
});
|
/**
* The example data is structured as follows:
**/
export default [
{
img: require('Assets/img/gallery-1.jpg'),
title: 'Gallery 1',
author: 'author',
cols: 1.3,
},
{
img: require('Assets/img/gallery-2.jpg'),
title: 'Gallery 2',
author: 'author',
cols: .7,
},
{
img: require('Assets/img/gallery-3.jpg'),
title: 'Gallery 3',
author: 'author',
cols: .66,
},
{
img: require('Assets/img/gallery-4.jpg'),
title: 'Gallery 4',
author: 'author',
cols: .66,
},
{
img: require('Assets/img/gallery-5.jpg'),
title: 'Gallery 5',
author: 'author',
cols: .66,
},
{
img: require('Assets/img/gallery-6.jpg'),
title: 'Gallery 6',
author: 'author',
cols: .8,
},
{
img: require('Assets/img/gallery-7.jpg'),
title: 'Gallery 7',
author: 'author',
cols: .6,
},
{
img: require('Assets/img/gallery-8.jpg'),
title: 'Gallery 8',
author: 'author',
cols: .6,
},
{
img: require('Assets/img/gallery-9.jpg'),
title: 'Gallery 9',
author: 'author',
cols: .5,
},
{
img: require('Assets/img/gallery-10.jpg'),
title: 'Gallery 10',
author: 'author',
cols: .5,
}
];
|
import { combineReducers } from 'redux'
// importing the reducer
import archives from './archives'
import users from './users'
export default combineReducers({
// all the reducers we have
archives,
users
}); |
var msg = require('./a').msg;
console.log(msg); |
import React from 'react';
import { createStackNavigator, createBottomTabNavigator } from 'react-navigation';
import TabBarIcon from '../components/TabBarIcon';
import AddOrder from '../features/add-order';
import MyHome from '../features/home';
import Review from '../features/review';
import Signature from '../features/signature';
import Profile from '../features/profile';
import EditProfile from '../features/edit-profile';
import Help from '../features/help';
import Orders from '../features/orders';
import Notifications from '../features/notifications';
import Chat from '../features/chat';
import Messages from '../features/messages';
import Rate from '../features/rate';
import OrderDetail from '../features/order-detail';
import OrderTracking from '../features/order-tracking';
import Payment from '../features/payment';
import OrderCancel from '../features/order-cancel';
import Reputation from '../features/reputation';
import AnswerQuestion from '../features/answer-question';
const HomeStack = createStackNavigator(
{
MyHome,
OrderDetail,
OrderCancel,
OrderTracking,
Signature,
AnswerQuestion,
Reputation,
Chat
},
{
initialRouteName: 'MyHome'
}
);
HomeStack.navigationOptions = {
tabBarIcon: ({ focused, tintColor }) => (
<TabBarIcon focused={focused} name="md-home" color={tintColor} />
)
};
const OrderStack = createStackNavigator(
{
Orders,
Signature,
OrderDetail,
...AddOrder,
OrderTracking,
Rate,
Payment,
OrderCancel,
AnswerQuestion,
Reputation,
Chat
},
{
initialRouteName: 'Orders'
}
);
OrderStack.navigationOptions = {
tabBarIcon: ({ focused, tintColor }) => (
<TabBarIcon focused={focused} name="ios-archive" color={tintColor} />
)
};
const ProfileStack = createStackNavigator(
{
Profile,
EditProfile,
Review,
Help,
Rate,
Reputation
},
{
initialRouteName: 'Profile'
}
);
ProfileStack.navigationOptions = {
tabBarIcon: ({ focused, tintColor }) => (
<TabBarIcon focused={focused} name="md-person" color={tintColor} />
)
};
const NotificationStack = createStackNavigator(
{
Notifications,
Chat,
Messages,
OrderTracking,
OrderDetail,
OrderCancel,
Profile,
Rate,
Reputation
},
{
initialRouteName: 'Notifications'
}
);
NotificationStack.navigationOptions = {
tabBarIcon: ({ focused, tintColor }) => (
<TabBarIcon focused={focused} name="md-notifications" color={tintColor} />
)
};
export const CarrierTabNavigator = createBottomTabNavigator(
{
HomeStack,
OrderStack,
NotificationStack,
ProfileStack
},
{
tabBarOptions: {
showLabel: false,
activeTintColor: '#665EFF',
inactiveTintColor: '#959DAD'
}
}
);
export const ClientTabNavigator = createBottomTabNavigator(
{
OrderStack,
NotificationStack,
ProfileStack
},
{
tabBarOptions: {
showLabel: false,
activeTintColor: '#665EFF',
inactiveTintColor: '#959DAD'
}
}
);
|
var appRunner = require('./utils/app-runner');
var login = require('./utils/login');
describe('Titles', function() {
var loginUrl;
function createTitle(browser, name, price) {
return openNewTitleModal(browser)
.setValue('input[label=Nimi]', name)
.selectByVisibleText('select[label=Tuoteryhmä]', 'Puutavara')
.setValue('input[label=Yksikkö]', 'kpl')
.selectByVisibleText('select[label=ALV-prosentti]', '24%')
.setValue('input[label="Hinta (sis. alv)"]', price)
.setValue('[label=Kommentti]', 'Testikommentti vain :)')
.click('button=Tallenna');
}
function openNewTitleModal(browser) {
return browser.url(loginUrl)
.waitForVisible('=Tuotteet')
.click('=Tuotteet')
.getText('h1=Tuotteet').should.eventually.be.ok
.waitForVisible('*=Uusi tuote')
.click('*=Uusi tuote')
.waitForVisible('h4=Uusi tuote');
}
before(appRunner.run);
beforeEach(function(done) {
login('pekka.paallikko@roihu2016.fi', function(err, url) {
loginUrl = url;
done(err);
});
});
it('should be validated before saving', function() {
return openNewTitleModal(browser)
.click('button=Tallenna')
.waitForVisible('.alert-danger')
.waitForVisible('li=Syötä nimi')
.waitForVisible('li=Valitse tuoteryhmä')
.waitForVisible('li=Syötä yksikkö')
.waitForVisible('li=Valitse ALV-prosentti')
.waitForVisible('li=Syötä hinta, joka on vähintään 0 €')
.click('button=Peruuta');
});
it('should be possible to add', function() {
return createTitle(browser, 'Testituote', '100')
.waitForVisible('span=Testituote');
});
it('should be possible to edit', function() {
return createTitle(browser, 'Muokattava tuote', '15') //TODO Use price with comma
.waitForVisible('span=Muokattava tuote')
// Newly-created item should be first in the list
.click('.edit')
.waitForVisible('h4=Muokkaa tuotetta')
.getValue('input[label=Nimi]').should.eventually.equal('Muokattava tuote')
.setValue('input[label=Nimi]', 'Uusi nimi')
.click('button=Tallenna')
.waitForVisible('span=Uusi nimi');
});
it('should be possible to delete', function() {
return createTitle(browser, 'Poistettava tuote', '55')
.waitForVisible('span=Poistettava tuote')
.click('.delete')
.waitForVisible('h4=Poista tuote')
.click('button=Kyllä')
.waitForExist('span=Poistettava tuote', 10000, true);
});
afterEach(function() {
return browser
.click('=Kirjaudu ulos')
.waitForVisible('.btn*=Kirjaudu sisään');
});
after(function(done) {
this.timeout(20000);
appRunner.resetDatabase(done);
});
after(appRunner.halt);
});
|
function fullSentence() {
var part1 = "I have ";
var part2 = "made this ";
var part3 = "into a complete ";
var part4 = "sentence.";
var wholeSentence = part1.concat(part2, part3, part4);
document.getElementById('concat').innerHTML = wholeSentence;
}
function sliceMethod() {
var Sentence = "All work and no play makes Johnny a dull boy.";
var Section = Sentence.slice(27,33);
document.getElementById("Slice").innerHTML = Section;
}
function toUpper() {
var string = "hello world!";
var upper = string.toUpperCase();
document.getElementById("test").innerHTML = upper;
}
function searchFunction () {
var hello = "hello world";
var search = hello.search("world");
document.getElementById("search").innerHTML = search;
}
function stringMethod() {
var x = 182;
document.getElementById("numbers").innerHTML = x.toString();
}
function precisionMethod() {
var y = 12938.3012987376112;
document.getElementById("precision").innerHTML = y.toPrecision(10);
}
function getMoney() {
var money = 2934.5594;
document.getElementById("money").innerHTML = money.toFixed(2);
}
function valOf() {
var hello = "Hello World!";
var val = hello.valueOf();
document.getElementById("value").innerHTML = val;
} |
function average (x, y) {
return (x + y) / 2
}
let result = average(6, 7)
console.log(result)
|
let data1 = {
photo: 'images/pic1.jpg',
title: 'Coffee',
description: 'A kávé egyszerre jelenti azon termékeket, melyeket bizonyos kávéfajok magvainak feldolgozásával állít elő a mezőgazdaság és az ipar, valamint azt az italt, amelyet az előbb említett termékekből készítenek, s amely világszerte népszerű élvezeti cikk.'
};
let data2 = {
photo: 'images/pic2.jpg',
title: 'Smartwatch',
description: 'Az okosóra egy számítógépesített karóra, amely az idő mutatásán kívül számos funkcióval bír, és gyakran hasonlítják a PDA-khoz. Míg a korai modellek még csak olyan alapfunkciókkal rendelkeztek, mint a számológép, a fordítás vagy játékok, a modern okosórák már egyfajta hordható számítógépként funkcionálnak.'
};
let data3 = {
photo: 'images/pic3.jpg',
title: 'Smartphone',
description: 'Okostelefonnak (angolul smartphone) nevezzük a fejlett, gyakran PC-szerű funkcionalitást nyújtó mobiltelefonokat. Nincs egyértelmű meghatározás arra, hogy mi az okostelefon.[1][2] Egyesek szerint okostelefon az a mobil, aminek teljes értékű operációs rendszere szabványosított interfészeket és platformot nyújt az alkalmazásfejlesztők számára.'
};
let data4 = {
photo: 'images/pic4.jpg',
title: 'Laptop',
description: 'A notebook és a laptop angol eredetű szó, az informatikában a hordozható személyi számítógépeket takarják. Ezek teljes értékű PC-k, az asztali változatokhoz képest a lényegi különbség a kompakt formai kivitelezésben és a hordozhatóságban rejlik. Ugyanazokat a funkciókat betöltő alkatrészekből épülnek fel, azonban jellemzően kisebb méretűek, könnyebbek, kevesebb hőt termelnek, és kevesebb energiát is fogyasztanak, mint az asztali PC-kben megtalálható megfelelőik. '
};
let data5 = {
photo: 'images/pic5.jpg',
title: 'Code',
description: 'In communications and information processing, code is a system of rules to convert information—such as a letter, word, sound, image, or gesture—into another form, sometimes shortened or secret, for communication through a communication channel or storage in a storage medium. An early example is an invention of language, which enabled a person, through speech, to communicate what they thought, saw, heard, or felt to others.'
};
let data6 = {
photo: 'images/pic6.jpg',
title: 'Earth',
description: 'Earth is the third planet from the Sun and the only astronomical object known to harbor life. About 29% of Earth'
};
let data7 = {
photo: 'images/pic7.jpg',
title: 'Lobby',
description: 'A lobby is a room in a building used for entry from the outside.[1] Sometimes referred to as a foyer, reception area or an entrance hall, it is often a large room or complex of rooms (in a theatre, opera house, concert hall, showroom, cinema, etc.) adjacent to the auditorium. It may be a repose area for spectators, especially used before performance and during intermissions, but also as a place of celebrations or festivities after performance. '
};
let data8 = {
photo: 'images/pic8.jpg',
title: 'Argument',
description: 'In logic and philosophy, an argument is a series of statements (in a natural language), called the premises or premisses (both spellings are acceptable), intended to determine the degree of truth of another statement, the conclusion.[1][2][3][4][5] The logical form of an argument in a natural language can be represented in a symbolic formal language, and independently of natural language formally defined "arguments" can be made in math and computer science. '
};
let currentPhoto = 0;
let imagesData = [data1,data2,data3,data4,data5,data6,data7,data8];
$('#photo').attr('src', imagesData[currentPhoto].photo);
let loadPhoto = (photoNumber) => {
$('#photo').attr('src', imagesData[photoNumber].photo);
$('#photo-title').text(imagesData[photoNumber].title);
$('#photo-description').text(imagesData[photoNumber].description);
console.log(currentPhoto);
}
console.log(imagesData.length);
loadPhoto(currentPhoto);
$('#right-arrow').click(() => {
if(currentPhoto+1>imagesData.length-1){
currentPhoto=0;
}else{
currentPhoto++;
}
console.log(currentPhoto);
loadPhoto(currentPhoto);
console.log(currentPhoto);
})
$('#left-arrow').click(() => {
if(currentPhoto===0){
currentPhoto=imagesData.length-1;
}else{
currentPhoto--;
}
console.log(currentPhoto);
loadPhoto(currentPhoto);
console.log(currentPhoto);
})
imagesData.forEach((item, index) => {
index++;
let temp=1;
$('#thumbnails').append(`<img class="box" data-index="${index}" src="images/pic${index}.jpg" alt="pic" id="${index}"></img><div class="title" id="c_${index}">${item.title}</div>`);
$('.box').click((event) => {
let indexClicked = $(event.target).attr('data-index');
// indexClicked is now a string! if you need it as a number you have to change it
// because for example "1" + 1 is going to be "11" and not 2
let numberIndex = parseInt(indexClicked);
// now numberIndex is a number
$('#photo').attr('src', imagesData[numberIndex-1].photo);
$('#photo-title').text(imagesData[numberIndex-1].title);
$('#photo-description').text(imagesData[numberIndex-1].description);
$('.box').removeClass("active");
$(`#${numberIndex}`).addClass("active");
});
});
$('#thumbnails .box').hover(function() {
console.log(this.id);
let temp = document.getElementById(`c_${this.id}`);
//temp.attr("style","display:block");
temp.style.display ="block";
}, function() {
let temp = document.getElementById(`c_${this.id}`);
//temp.attr("style","display:block");
temp.style.display ="none";
}
); |
'use strict';
(function () {
var TIMEOUT_VALUE = 3000;
var serverUrl = {
download: 'https://js.dump.academy/keksobooking/data',
upload: 'https://js.dump.academy/keksobooking'
};
var messageError = {
'ERROR_LOAD': 'Произшла ошибка соединения',
'TIMEOUT': 'Запрос выполняется слишком долго'
};
function createXhr(method, URL, onLoad, onError) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.timeout = TIMEOUT_VALUE;
xhr.addEventListener('load', function () {
if (xhr.status === 200) {
onLoad(xhr.response);
} else {
onError('Cтатус ответа: ' + xhr.status + ' ' + xhr.statusText);
}
});
xhr.addEventListener('error', function () {
onError(messageError.ERROR_LOAD);
});
xhr.addEventListener('timeout', function () {
onError(messageError.TIMEOUT);
});
xhr.open(method, URL);
return xhr;
}
// Запрос на сервер
function download(onLoad, onError) {
createXhr('GET', serverUrl.download, onLoad, onError).send();
}
// Отпарвляет на сервер
function upload(onLoad, onError, data) {
createXhr('POST', serverUrl.upload, onLoad, onError).send(data);
}
window.backend = {
download: download,
upload: upload
};
})();
|
/**
* Created by Tomasz Jodko on 2016-06-04.
*/
app.factory('companyFactory', ['$http', function ($http) {
var urlBase = '/projektzespolowy/companies';
var companyFactory = {};
companyFactory.getCompanies = function (callback) {
return $http.get(urlBase + '/getAll').then(function (response) {
if (response.data.error) {
return null;
} else {
companyFactory.returnedData = response.data;
callback(companyFactory.returnedData);
}
});
};
companyFactory.getCompany = function (id, callback) {
return $http.get(urlBase + '/getById/' + id).then(function (response) {
if (response.data.error) {
return null;
} else {
companyFactory.returnedData = response.data;
callback(companyFactory.returnedData);
}
});
};
companyFactory.getCompaniesInProject= function (id, callback) {
return $http.get(urlBase + '/getCompaniesInProject/' + id).then(function (response) {
if (response.data.error) {
return null;
} else {
companyFactory.returnedData = response.data;
callback(companyFactory.returnedData);
}
});
};
companyFactory.getCompaniesNotInProject= function (id, callback) {
return $http.get(urlBase + '/getCompaniesNotInProject/' + id).then(function (response) {
if (response.data.error) {
return null;
} else {
companyFactory.returnedData = response.data;
callback(companyFactory.returnedData);
}
});
};
companyFactory.saveCompany = function (wrapper, callback) {
return $http.post(urlBase + '/saveCompany', wrapper).then(function (response) {
if (response.data.error) {
return null;
} else {
companyFactory.returnedData = response.data;
callback(companyFactory.returnedData);
}
});
};
companyFactory.deleteCompany = function (id) {
return $http.put(urlBase + '/deleteById/' + id);
};
return companyFactory;
}]); |
// detail.js
var Util = require('../../utils/util.js');
var Api = require('../../utils/api.js');
Page({
data: {
title: '我的',
user: {},
logged: false
},
goLogin: function (e) {
var url = '../login/login';
wx.navigateTo({
url: url
})
},
onMySold: function () {
var url = '../mySold/mySold';
wx.navigateTo({
url: url
})
},
onMyBought: function () {
var url = '../myBought/myBought';
wx.navigateTo({
url: url
})
},
onMyPublish: function () {
var url = '../myPublish/myPublish';
wx.navigateTo({
url: url
})
},
fetchDetail: function(id) {
},
touchStartElement: function (e) {
console.log("start", e);
var id = e.currentTarget.id;
this.setData({
activeHoverIndex: id
})
},
touchEndElement: function (e) {
console.log("end", e);
var that = this;
setTimeout(function () {
that.setData({
//warnning undefined==""=="0"==0
activeHoverIndex: "none"
})
}, 500)
},
touchMoveElement: function (e) {
console.log("move", e);
this.setData({
activeHoverIndex: "none"
})
},
popLogin: function (e) {
var that = this;
wx.login({
success: function (res) {
console.log(res);
if (res.code) {
var jscode = res.code
console.log("start....")
wx.getUserInfo({
withCredentials: true,
fail: function(res) {
console.log(res);
},
success: function (res) {
var objz = {};
console.log("sssss....")
console.log(res); objz.avatarUrl = res.userInfo.avatarUrl;
objz.nickName = res.userInfo.nickName;
//console.log(objz);
// wx.setStorageSync('userInfo', objz);//存储userInfo
var params = {};
params["code"] = jscode
params["encrypt"] = res.encryptedData
params["iv"] = res.iv
var l = getApp().config.host +'/jscode_to_secrets';
getApp().doRequest({
url: l,
data: params,
method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
// header: {}, // 设置请求的 header
success: function (res) {
console.log("jscode_to_secrets....")
console.log(res);
var obj = {};
that.setData({
user: res.data.data
})
obj.openid = res.data.openid;
obj.expires_in = Date.now() + res.data.expires_in;
//console.log(obj);
wx.setStorageSync('user', res.data.data);//存储openid
}
});
}
});
} else {
console.log('获取用户登录态失败!' + res.errMsg)
}
} });
},
onLoad: function (options) {
this.fetchUserInfo();
// if (gUser.id>0) {
// this.setData({
// user: gUser
// })
// } else {
// this.popLogin()
// }
},
fetchUserInfo: function () {
var that = this;
getApp().doRequest({
url: getApp().config.host + "/get_user_info",
method: "GET",
header: {
"Content-Type": "application/x-www-form-urlencoded",
"token": getApp().globalData.userInfo.token
},
success: function (res) {
that.setData({
user: res.data.data.user
})
}
})
},
onShow: function() {
if (getApp().globalData.needRefreshHome) {
getApp().globalData.needRefreshHome = false;
this.fetchUserInfo();
} else if (getApp().globalData.userInfo.id>0 &&this.data.user.id>0==false) {
this.fetchUserInfo();
} else {
}
},
goEditUser: function () {
var url = '../editUser/editUser';
wx.navigateTo({
url: url
})
},
onMyAccount: function () {
var url = '../myAccount/myAccount';
wx.navigateTo({
url: url
})
}
})
|
(function () {
"use strict";
// Keeps track of the blank square
var blankSquare = {
xPosition: 300,
yPosition: 300,
id: "3and3"
};
// Checks if the puzzle is being shuffled
var shuffling = false;
// Sets up shuffle and creates the puzzle when page loads
window.onload = function () {
document.querySelector("#controls").onclick = shuffle;
createPuzzle();
};
// This method creates the puzzle and sets up the image area
// accordingly
function createPuzzle() {
var puzzle = document.querySelector("#puzzlearea");
var x = -1;
var y = -1;
for (var i = 0; i < 15; i++) {
var piece = document.createElement("div");
x++;
if (i % 4 == 0) {
x = 0;
}
if ((i + 1) % 4 == 1) {
y++;
}
piece.id = x + "and" + y;
piece.style.backgroundPosition = getPosition(x, y);
piece.style.top = y * 100 + "px";
piece.style.left = x * 100 + "px";
piece.innerHTML = i + 1;
piece.classList.add("puzzlepiece");
piece.onclick = swap;
piece.onmouseenter = color;
piece.onmouseout = unColor;
puzzle.appendChild(piece);
}
}
// This method returns the background position
function getPosition(x, y) {
x *= -100;
y *= -100;
return x + "px " + y + "px";
}
// This method shuffles the puzzle u by repeatedly moving
// pieces into the blank square over and over
function shuffle() {
shuffling = true;
document.querySelector("#output").innerHTML = "";
for (var i = 0; i < 1000; i++) {
var positions = blankSquare.id.split("and");
var row = positions[0];
var col = positions[1];
var neighbors = getNeighbors(row, col);
var size = neighbors.length;
var rand = Math.floor(Math.random() * size);
move(neighbors[rand]);
}
}
// This method returns all the valid neighbors of the blank square
function getNeighbors(row, col) {
var neighbor1 = document.getElementById((parseInt(row) + 1) + "and"+ col);
var neighbor2 = document.getElementById((parseInt(row) - 1) + "and"+ col);
var neighbor3 = document.getElementById(row + "and" + (parseInt(col) + 1));
var neighbor4 = document.getElementById(row + "and" + (parseInt(col) - 1));
var neighbors = [neighbor1, neighbor2, neighbor3, neighbor4];
// Remove the squares that don't exist
for (var i = 0; i < 4; i++) {
// if it is null, remove the first element
if (!neighbors[0]) {
neighbors.shift();
} else { // not null, move it to the end of the array
neighbors.push(neighbors.shift());
}
}
return neighbors;
}
// This method returns true if a given square is movable
// and false otherwise. A square is movable if it directly
// neighbors the blank square.
function isMovable(piece) {
var left = parseInt(window.getComputedStyle(piece).left);
var top = parseInt(window.getComputedStyle(piece).top);
return (Math.abs(left - blankSquare.xPosition) === 100 &&
top - blankSquare.yPosition === 0) ||
(Math.abs(top - blankSquare.yPosition) === 100 &&
left - blankSquare.xPosition === 0);
}
// This method swaps the current square with the blank suare when
// clicked.
function swap() {
shuffling = false;
var display = document.querySelector("#output");
if (isMovable(this)) {
move(this);
}
if (isSolved()) {
display.innerHTML = "Congrats, kid. ur a winner! (not really)";
} else {
display.innerHTML = "";
}
}
// This function moves the piece to the blank square
function move(piece) {
var oldX = parseInt(window.getComputedStyle(piece).left);
var oldY = parseInt(window.getComputedStyle(piece).top);
var positions = piece.id.split("and");
var oldRow = positions[0];
var oldCol = positions[1];
piece.id = blankSquare.id;
piece.style.top = blankSquare.yPosition + "px";
piece.style.left = blankSquare.xPosition + "px";
blankSquare.xPosition = oldX;
blankSquare.yPosition = oldY;
blankSquare.id = oldRow + "and" + oldCol;
}
// This method highlights the border and text of a movable piece
// when user hovers over it
function color() {
if (isMovable(this)) {
this.classList.add("movable");
}
}
// This method removes the red bordering and text olor of a movable
// piece when user stops hovering over it
function unColor() {
this.classList.remove("movable");
}
// This method returns true if the puzzle is in a solved state
// and false otherwise
function isSolved() {
var pieces = document.querySelectorAll("#puzzlearea div");
var x = -1;
var y = -1;
for (var i = 0; i <pieces.length; i++) {
x++;
if (i % 4 == 0) {
x = 0;
}
if ((i + 1) % 4 == 1) {
y++;
}
if (pieces[i].id !== x + "and" + y && !shuffling) {
return false;
}
}
return true;
}
})(); |
var mysql=require('mysql')
var con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password'
})
con.connect(function(err){
if(err) throw er;
console.log("Connected to Local MySql Database!")
})
//build database
//add user score
//remove user score
//rank user scores
|
'use strict';
var util = require('gulp-util'),
through2 = require('through2'),
rsync = require('rsync'),
argv = require('yargs').argv,
config = require('./config');
function generateError(message, previous) {
throw new util.PluginError('gulp-deploy', message, previous);
}
module.exports = function (options) {
options = config(options);
var env = argv.env || options.default;
if (!env) {
generateError('Please define an env using --env to deploy your application');
}
if (!options.env[env]) {
generateError(
'The obtained env "' + env + '" is not defined ' +
'(available envs: ' + (Object.keys(options.env).join(', ')) + ')'
);
}
env = options.env[env];
return through2.obj(function (file, encoding, callback) {
if (file.isNull()) {
return callback(null, file);
}
var dest = file.path.replace(process.cwd(), '');
console.log(file, dest);
callback(null, file);
});
}; |
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import FormGasto from "../animals/FormGasto";
import {Link} from 'react-router-dom'
import {Select, Form, message, Divider, Card, List, Button} from 'antd';
import MainLoader from "../../common/Main Loader";
import * as animalGastoActions from '../../../redux/actions/ganado/gastoAnimalActions';
import * as animalActions from '../../../redux/actions/ganado/animalsActions';
import * as lotesActions from '../../../redux/actions/ganado/lotesActions';
import FormAnimalLote from '../animals/FormLote';
import {AreteCard} from '../eventos/AreteCard'
import { ReporteCard } from './ReporteCard';
import {ResumenCard} from './ResumenCard';
import './reportes.css'
const FormItem = Form.Item;
const {Option, OptGroup } = Select;
class ReportesPage extends Component {
state = {
aretes:[],
aretesId:[],
areteRancho:'',
areteId:{},
lote:'',
loteId:'',
modo:'',
loading:false,
multiple:[],
mIds:[]
};
handleSearch=(a)=>{
//let basePath = 'http://localhost:8000/api/ganado/animals/?q=';
let basePath = 'https://rancho.davidzavala.me/api/ganado/animals/?q=';
let url = basePath+a;
this.props.animalActions.getAnimals(url);
};
handleChange=(a)=>{
//let basePath = 'https://rancho.fixter.org/api/ganado/animals/?q=';
this.setState({areteRancho:a});
};
deleteFromMultiple=(a)=>{
let {mIds} = this.state;
mIds = mIds.filter(i=>{return i.arete_siniga!== a})
this.setState({mIds})
console.log(mIds)
}
onSelectLote=(value, b)=>{
console.log(b, value);
this.setState({lote:value})
};
saveId=(id)=>{
this.setState({areteId:id});
console.log(id)
};
saveIds=(id)=>{
let {mIds}=this.state;
mIds.push(id)
this.setState({mIds});
console.log(mIds)
};
saveLoteId=(id)=>{
this.setState({loteId:id});
console.log(id)
};
handleSearchLote=(a)=>{
let basePath = 'https://rancho.davidzavala.me/api/ganado/lotes/?q=';
let url = basePath+a;
this.props.lotesActions.getLotes(url);
};
handleChangeLote=(a)=>{
//let basePath = 'https://rancho.fixter.org/api/ganado/animals/?q=';
this.setState({lote:a});
};
handleMultiple=(a)=>{
this.setState({multiple:a});
}
saveGasto=(gasto)=>{
gasto['animal'] = this.state.areteId.id;
this.props.animalGastoActions.saveAnimalGasto(gasto)
.then(r=>{
message.success('Gasto agregado con éxito');
this.setState({areteRancho:'', areteId:'', modo:''});
this.handleSearch('')
}).catch(e=>{
for (let i in e.response.data){
message.error(e.response.data[i])
}
})
};
print=()=>{
window.print()
}
saveMultiplesGastos=(gasto)=>{
this.setState({loading:true});
let {mIds} = this.state;
console.log(mIds)
let parcialAmount = gasto.costo/mIds.length;
parcialAmount = parcialAmount.toFixed(2);
let parcialQuantity = gasto.cantidad/mIds.length;
parcialQuantity = parcialQuantity.toFixed(2);
for(let i in mIds){
let animalId = mIds[i].id;
gasto['animal']=animalId;
gasto['costo']=parcialAmount;
if(gasto.cantidad)gasto['cantidad']=parcialQuantity;
let toSend = Object.assign({}, gasto);
this.props.animalGastoActions.saveAnimalGasto(toSend)
.then(r=>{
}).catch(e=>{
for (let i in e.response.data){
message.error(e.response.data[i])
}
})
}
this.setState({lote:'', loteId:'', modo:'', loading:false, mIds:[]});
message.success('Gasto agregado con éxito')
};
saveLoteGastos=(gasto)=>{
this.setState({loading:true});
let {loteId} = this.state;
//let keys = this.state.selectedRowKeys;
let parcialAmount = gasto.costo/loteId.animals.length;
parcialAmount = parcialAmount.toFixed(2);
let parcialQuantity = gasto.cantidad/loteId.animals.length;
parcialQuantity = parcialQuantity.toFixed(2);
for(let i in loteId.animals){
let animalId = loteId.animals[i].id;
gasto['animal']=animalId;
gasto['costo']=parcialAmount;
if(gasto.cantidad)gasto['cantidad']=parcialQuantity;
let toSend = Object.assign({}, gasto);
this.props.animalGastoActions.saveAnimalGasto(toSend)
.then(r=>{
}).catch(e=>{
for (let i in e.response.data){
message.error(e.response.data[i])
}
})
}
this.setState({lote:'', loteId:'', modo:'', loading:false});
message.success('Gasto agregado con éxito')
};
changeSingleLote=(animal)=>{
animal['id']= this.state.areteId.id
let toSend = Object.assign({}, animal);
this.props.animalActions.editAnimal(toSend)
.then(r => {
message.success('Modificado con éxito');
}).catch(e => {
console.log(e)
})
};
changeLoteLote=(animal)=>{
let {loteId} = this.state
for(let j in loteId.animals){
animal['id']=loteId.animals[j].id;
let toSend = Object.assign({}, animal);
console.log(toSend)
this.props.animalActions.editAnimal(toSend)
.then(r => {
message.success('Modificado con éxito');
}).catch(e => {
for (let i in e.response.data){
message.error(e.response.data[i])
}
})
}
};
changeMultiplesLote=(animal)=>{
let {mIds} = this.state;
for(let j in mIds){
animal['id']=mIds[j].id;
let toSend = Object.assign({}, animal);
this.props.animalActions.editAnimal(toSend)
.then(r => {
message.success('Modificado con éxito');
}).catch(e => {
for (let i in e.response.data){
message.error(e.response.data[i])
}
})
}
};
handleChangeMode=(a)=>{
//let basePath = 'https://rancho.fixter.org/api/ganado/animals/?q=';
this.setState({modo:a, mIds:[], areteId:{}, aretes:[], areteRancho:'', areteId:'', lote:'', loteId:{}, multiple:[]});
};
handleChangeEvent=(a)=>{
//let basePath = 'https://rancho.fixter.org/api/ganado/animals/?q=';
this.setState({event:a});
};
render() {
let {fetched, animals, lotes} = this.props;
let {modo, loading, event, multiple, areteId, mIds, loteId} = this.state;
if(!fetched)return(<MainLoader/>);
return (
<div>
<div style={{marginBottom:10, color:'rgba(0, 0, 0, 0.65)' }}>
Ganado
<Divider type="vertical" />
Eventos
</div>
<div style={{display:'flex', justifyContent:'space-around'}}>
<div style={{width:'40%'}} >
<h2>Generador de Reportes</h2>
<FormItem label={'Modo'}>
<Select
value={modo}
onChange={this.handleChangeMode}
style={{width:'100%'}}
>
<Option value={'individual'}>Individual</Option>
<Option value={'lote'}>Por Lote</Option>
<Option value={'multiple'}>Multiple</Option>
</Select>
</FormItem>
{modo==='lote'?
<FormItem label={'Lote'}>
<Select
value={this.state.lote}
mode="combobox"
style={{width:'100%'}}
onSelect={this.onSelectLote}
onChange={this.handleChangeLote}
placeholder="ingresa el nombre del lote"
filterOption={true}
>
{lotes.map((a, key)=><Option value={a.name} key={key}>
<div onClick={()=>this.saveLoteId(a)}>
<span style={{color:'gray', fontSize:'.8em'}}>Corral: {a.corral.no_corral}</span><br/>
<span >Lote: {a.name}</span>
</div>
</Option>)}
</Select>
</FormItem>:modo==='individual'?
<FormItem label={"Arete"}>
<Select
value={this.state.areteRancho}
mode="combobox"
style={{width:'100%'}}
onSelect={this.onSelect}
onSearch={this.handleSearch}
onChange={this.handleChange}
placeholder="ingresa el arete de rancho, o siniga para buscarlo"
filterOption={false}
>
{animals.map((a, key)=><Option value={a.arete_siniga} key={key}>
<div onClick={()=>this.saveId(a)}>
<span style={{color:'gray', fontSize:'.8em'}}>Rancho: {a.arete_rancho}</span><br/>
<span >Siniga: {a.arete_siniga}</span>
</div>
</Option>)}
</Select>
</FormItem>:modo==='multiple'?
<FormItem label="Multiples Aretes">
<Select
mode="tags"
value={multiple}
placeholder="Please select"
defaultValue={[]}
onSearch={this.handleSearch}
onDeselect={this.deleteFromMultiple}
onChange={this.handleMultiple}
style={{ width: '100%' }}
>
{animals.map((a, key)=><Option value={a.arete_siniga} key={key}>
<div onClick={()=>this.saveIds(a)}>
<span>S: {a.arete_siniga}</span><br/>
<span style={{color:'gray', fontSize:'.8em'}}>R: {a.arete_rancho}</span>
</div>
</Option>)}
</Select>
</FormItem>:'Elige un Modo* '}
{/*Forms de los reportes*/}
<div id="print" className="toprint">
<ResumenCard
aretes={modo==='individual'?[areteId]:
modo==='multiple'?mIds:
modo==='lote'?loteId.animals?loteId.animals.filter(a=>a.status==true):[]:[]}/>
</div>
<Button type="primary" onClick={this.print}>Print</Button>
</div>
<div style={{width:'50%', }}>
<Card style={{width:'100%', height:'80vh', overflowY:'scroll' ,padding:'0%'}}
title={'Aretes Seleccionados'}>
<List
style={{width:'100%', padding:0}}
itemLayout="horizontal"
dataSource={modo==='individual'?[areteId]:
modo==='multiple'?mIds:
modo==='lote'?loteId.animals?loteId.animals.filter(a=>a.status==true):'':''}
renderItem={item => (
<List.Item>
<ReporteCard {...item}/>
</List.Item>
)}
/>
</Card>
</div>
</div>
</div>
);
}
}
function mapStateToProps(state, ownProps) {
return {
animals:state.animals.list,
lotes: state.lotes.list,
fetched:state.animals.list!==undefined && state.lotes.list!==undefined
}
}
function mapDispatchToProps(dispatch) {
return {
animalGastoActions: bindActionCreators(animalGastoActions, dispatch),
animalActions:bindActionCreators(animalActions, dispatch),
lotesAction:bindActionCreators(lotesActions, dispatch),
}
}
ReportesPage = connect(mapStateToProps, mapDispatchToProps)(ReportesPage);
export default ReportesPage;
|
import { LABELS, RESULT_KEY } from '@/athleteTests/Caliperometry/constants';
export const INPUTS = [
{
id: RESULT_KEY.UNDER_SHOULDER_BLADE,
label: LABELS[RESULT_KEY.UNDER_SHOULDER_BLADE]
},
{
id: RESULT_KEY.TRICEPS,
label: LABELS[RESULT_KEY.TRICEPS]
},
{
id: RESULT_KEY.BICEPS,
label: LABELS[RESULT_KEY.BICEPS]
},
{
id: RESULT_KEY.FOREARM,
label: LABELS[RESULT_KEY.FOREARM]
},
{
id: RESULT_KEY.WRIST,
label: LABELS[RESULT_KEY.WRIST]
},
{
id: RESULT_KEY.CHEST,
label: LABELS[RESULT_KEY.CHEST]
},
{
id: RESULT_KEY.BELLY,
label: LABELS[RESULT_KEY.BELLY]
},
{
id: RESULT_KEY.ILIAC,
label: LABELS[RESULT_KEY.ILIAC]
},
{
id: RESULT_KEY.HIP_UP,
label: LABELS[RESULT_KEY.HIP_UP]
},
{
id: RESULT_KEY.HIP_MID,
label: LABELS[RESULT_KEY.HIP_MID]
},
{
id: RESULT_KEY.SHIN,
label: LABELS[RESULT_KEY.SHIN]
},
{
id: 'height',
label: 'Рост, см'
},
{
id: 'weight',
label: 'Вес, кг'
}
];
export const CALIPEROMETRY_SAVE_FORM = `athleteTests/CalipereomtryInputForm/CALIPEROMETRY_SAVE_FORM`;
export const CALIPEROMETRY_SAVE_FORM_ERROR = `athleteTests/CaliperometryInputForm/CALIPEROMETRY_SAVE_FORM_ERROR`;
export const CALIPEROMETRY_SAVE_FORM_SUCCESS = `athleteTests/CaliperometryInputForm/CALIPEROMETRY_SAVE_FORM_SUCCESS`;
|
import React, { useContext, useState } from 'react';
import {categoriasContext} from '../context/categoriasContext';
import {tragosContext} from '../context/tragosContext';
import Alerta from './alerta';
import {TextField, Select, MenuItem, InputLabel, FormControl, Button} from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles((theme) => ({
FormControl: {
margin: theme.spacing(1),
minWidth: 120,
}
}));
function Formulario () {
const {categorias} = useContext(categoriasContext);
const {setBusqueda} = useContext(tragosContext);
const [alerta, setAlerta] = useState(false);
const [datos, setDatos] = useState({ingrediente:'', cat: ''});
const {ingrediente, cat} = datos;
function validarForm (e) {
e.preventDefault();
if ((ingrediente || cat).trim() === '') {
return setAlerta(true);
}
setBusqueda(datos);
}
function guardarValores (e) {
setDatos({
...datos, [e.target.name] : e.target.value
});
}
const classes = useStyles();
return (<>
<form onSubmit={validarForm} style={{display:'flex', justifyContent:'center', alignItems:'center', marginTop:30}}>
<TextField label="Ingrediente" variant="outlined" name='ingrediente' onChange={guardarValores} value={ingrediente} style={{backgroundColor:'white'}}/>
<FormControl className={classes.FormControl} variant="outlined">
<InputLabel id="demo-simple-select-outlined-label">Categoria</InputLabel>
<Select labelId="demo-simple-select-outlined-label" id="demo-simple-select-outlined" label="Categoria" name='cat' value={cat} onChange={guardarValores} style={{backgroundColor:'white'}}>
{categorias.map((categoria, index) => {
return <MenuItem value={categoria.strCategory} key={index}>{categoria.strCategory}</MenuItem>
})}
</Select>
</FormControl>
<Button type='submit' variant="contained" style={{backgroundColor:'#2167d9', color:'white', fontWeight:'bold'}}> Buscar </Button>
</form>
{alerta ? <Alerta setAlerta={setAlerta}/> : null}
</>
)
}
export default Formulario;
|
import React from 'react';
import { shallow } from 'enzyme';
import Card from './Card';
import { mockDate, clearMock } from '../../../../test/utils/mock-date';
describe('Card', () => {
beforeAll(() => {
mockDate();
});
afterAll(() => {
clearMock();
});
it('renders without crash', () => {
const card = shallow(<Card data={{}}/>);
expect(card).toMatchSnapshot();
});
});
|
'use strict'
class Storage {
get (key) {
const data = window.localStorage.getItem(key)
return data ? JSON.parse(data) : data
}
set (key, data) {
window.localStorage.setItem(key, JSON.stringify(data))
}
del (key) {
window.localStorage.removeItem(key)
}
}
module.exports = Storage
|
var nrImg = 6; // the number of img , I only have 6
var Vect = []; // picture array
var mytime; // timer
var IntSeconds = 10; //the seconds between the imgs ** Basic value
window.onload = function Load() {
imgVisible = 0; //the img visible
Vect[0] = document.getElementById("Img1");
Vect[0].style.visibility = "visible";
document.getElementById("S" + 0).style.visibility = "visible";
for (var i = 1; i < nrImg; i++) {
Vect[i] = document.getElementById("Img" + (i + 1));
document.getElementById("S" + i).style.visibility = "visible";
}
document.getElementById("S" + 0).style.backgroundColor = "rgba(255, 255, 255, 0.90)";
document.getElementById("SP" + imgVisible).style.visibility = "visible";
mytime = setInterval(Timer, IntSeconds * 1000);
document.addEventListener('keydown', function(event) {
if (event.keyCode === 37) {
prev();
}
if (event.keyCode === 39) {
next();
}
});
}
function Timer() {
imgVisible++;
if (imgVisible == nrImg)
imgVisible = 0;
Effect();
}
function next() {
imgVisible++;
if (imgVisible == nrImg)
imgVisible = 0;
Effect();
clearInterval(mytime);
mytime = setInterval(Timer, IntSeconds * 1000);
}
function prev() {
imgVisible--;
if (imgVisible == -1)
imgVisible = nrImg - 1;
Effect();
clearInterval(mytime);
mytime = setInterval(Timer, IntSeconds * 1000);
}
function Effect() {
for (var i = 0; i < nrImg; i++) {
Vect[i].style.opacity = "0"; //to add the fade effect
Vect[i].style.visibility = "hidden";
document.getElementById("S" + i).style.backgroundColor = "rgba(0, 0, 0, 0.70)";
document.getElementById("SP" + i).style.visibility = "hidden";
}
Vect[imgVisible].style.opacity = "1";
Vect[imgVisible].style.visibility = "visible";
document.getElementById("S" + imgVisible).style.backgroundColor = "rgba(255, 255, 255, 0.90)";
document.getElementById("SP" + imgVisible).style.visibility = "visible";
}
function userTime() {
var usrInput = document.getElementById('bottom-input').value;
if (!isNaN(usrInput) && usrInput != '') {
IntSeconds = usrInput;
clearInterval(mytime);
mytime = setInterval(Timer, IntSeconds * 1000);
} else {
document.getElementById('bottom-input').value = 'Please enter number';
}
}
function clearInput() {
document.getElementById('bottom-input').value = '';
}
|
import React from 'react';
import {BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import {Root} from './temp/components/Root';
import {Home} from './temp/components/Home';
import {User} from './temp/components/User';
class App extends React.Component{
render(){
return(
<Router>
<Root>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/user/:id" component={User} />
</Switch>
</Root>
</Router>
)
}
}
export default App |
// todo isolate in default environment
// NOTE
// first in-order exec plugins
// then reverse exec presets
const resolver = [
'module-resolver',
{
alias: {
'~graphql': './src/graphql',
'~env': './.env.general.js',
},
},
]
const provides = [
'provide-modules',
{
chalk: 'chalk',
lodash: [
{ filter: '_filter' },
{ flow: '_flow' },
{ pick: '_pick' },
{ slice: '_slice' },
{ sortBy: '_sortBy' },
{ isEmpty: '_isEmpty' },
{ get: '_get' },
{ values: '_values' },
],
},
]
const stages = [
// Stage 0
'@babel/plugin-proposal-function-bind',
// Stage 1
'@babel/plugin-proposal-export-default-from',
'@babel/plugin-proposal-logical-assignment-operators',
['@babel/plugin-proposal-optional-chaining', { loose: false }],
['@babel/plugin-proposal-pipeline-operator', { proposal: 'minimal' }],
['@babel/plugin-proposal-nullish-coalescing-operator', { loose: false }],
'@babel/plugin-proposal-do-expressions',
// Stage 2
['@babel/plugin-proposal-decorators', { legacy: true }],
'@babel/plugin-proposal-function-sent',
'@babel/plugin-proposal-export-namespace-from',
'@babel/plugin-proposal-numeric-separator',
'@babel/plugin-proposal-throw-expressions',
// Stage 3
'@babel/plugin-syntax-dynamic-import',
'@babel/plugin-syntax-import-meta',
['@babel/plugin-proposal-class-properties', { loose: false }],
'@babel/plugin-proposal-json-strings',
]
// const cherryPick = [
// ['import', { libraryName: 'lodash', libraryDirectory: '', camel2DashComponentName: false }, 'lodash'],
// // ['import',
// // { libraryName: 'graphql-tools', libraryDirectory: 'dist', camel2DashComponentName: false }, "graphql-tools"],
// ]
const cherryPick = [
'transform-imports',
{
lodash: {
transform: 'lodash/${member}',
preventFullImport: true,
},
},
]
const plugins = [resolver, 'macros', cherryPick, provides, ...stages]
const presets = [
[
'@babel/env',
{
targets: { node: true }, // ='current'
// modules: 'commonjs', // default
corejs: '3',
useBuiltIns: 'usage',
},
],
]
// The env key will be taken from process.env.BABEL_ENV,
// when this is not available then it uses process.env.NODE_ENV
// if even that is not available then it defaults to "development".
const env = {
production: {
plugins,
// https://github.com/babel/minify/tree/master/packages/babel-preset-minify#1-1-mapping-with-plugin
// presets: [...presets, 'babel-preset-minify'],
presets,
},
}
module.exports = { plugins, presets, env }
|
// webpackBootstrap
(function (modules) {
debugger;
// 模块缓存
var installedModules = {};
// require函数
function __webpack_require__(moduleId) {
// 检查模块是否在缓存中
if (installedModules[moduleId]) {
return installedModules[moduleId].exports; // 存在缓存中直接返回
}
// 创建一个新模块,并将它放入缓存中
var module = installedModules[moduleId] = {
i: moduleId,
l: false, // 模块是否已加载
exports: {}
};
// 执行模块函数
modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
// 标记模块为已加载
module.l = true;
// 返回模块的exports
return module.exports;
}
// 暴露 所有的模块对象到__webpack_require__函数上
__webpack_require__.m = modules;
// 暴露 模块缓存对象
__webpack_require__.c = installedModules;
// 为exports定义get函数
__webpack_require__.d = function(exports, name, getter) {
if (!__webpack_require__.o(exports, name)) {
Object.defineProperty(exports, name, { enumerable: true, get: getter });
}
}
// 在exports上定义__esModule
__webpack_require__.r = function(exports) {
if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
}
Object.defineProperty(exports, '__esModule', { value: true });
}
// Object.prototype.hasOwnProperty.call 判断对象的某个属性是否属于自己的属性
__webpack_require__.o = function (object, property) { return Object.prototype.hasOwnProperty.call(object, property); }
// 加载入口模块,并返回exports
return __webpack_require__(__webpack_require__.s = './src/index.js');
})({
'../../node_modules/css-loader/dist/runtime/api.js': (function (module, __webpack_exports__, __webpack_require__) {
'use strict';
}),
'./src/index.js': (function (module, __webpack_exports__, __webpack_require__) {
'use strict';
__webpack_require__.r(__webpack_exports__);
var _main_css_WEBPACK_IMPORTED_MODULE_0 = __webpack_require__('./src/main.css');
console.log(_main_css_WEBPACK_IMPORTED_MODULE_0);
}),
'./src/main.css': (function (module, __webpack_exports__, __webpack_require__) {
}),
'./src/role.js': (function (module, __webpack_exports__, __webpack_require__) {
})
});
|
/**
* gameanalytics-node-sdk
* Copyright (c) 2018, GoldFire Studios, Inc.
* https://goldfirestudios.com
*/
/**
* Default event validation data.
*/
module.exports = {
v: {
type: 'number',
required: true,
minimum: 2,
maximum: 2,
},
user_id: {
type: 'string',
required: true,
},
ios_idfa: {
type: 'string',
required: false,
},
ios_idfv: {
type: 'string',
required: false,
},
google_aid: {
type: 'string',
required: false,
},
android_id: {
type: 'string',
required: false,
},
googleplus_id: {
type: 'string',
required: false,
},
facebook_id: {
type: 'string',
required: false,
},
limit_ad_tracking: {
type: 'boolean',
enum: [true],
required: false,
},
logon_gamecenter: {
type: 'boolean',
enum: [true],
required: false,
},
logon_googleplay: {
type: 'boolean',
enum: [true],
required: false,
},
gender: {
type: 'string',
required: false,
enum: [
'male',
'female',
],
},
birth_year: {
type: 'number',
pattern : /^[0-9]{4}$/,
required: false,
},
custom_01: {
type: 'string',
maxLength : 32,
required: false,
},
custom_02: {
type: 'string',
maxLength : 32,
required: false,
},
custom_03: {
type: 'string',
maxLength : 32,
required: false,
},
client_ts: {
type: 'number',
pattern: /^([0-9]{10,11})$/,
required: false,
},
sdk_version: {
type: 'string',
required: true,
pattern: /^(((ios|android|unity|unreal|corona|marmalade|xamarin|gamemaker|flash|cocos2d|javascript|tvos|uwp|wsa|buildbox|defold|cpp|mono|lumberyard|stingray|frvr|air|uwp_cpp|tizen|construct|godot|stencyl|fusion|nativescript) [0-9]{0,5}(\.[0-9]{0,5}){0,2})|rest api v2)$/,
},
engine_version: {
type: 'string',
required: false,
pattern: /^(unity|unreal|corona|marmalade|xamarin|xamarin.ios|xamarin.android|xamarin.mac|gamemaker|flash|cocos2d|monogame|stingray|cryengine|buildbox|defold|lumberyard|frvr|construct|godot|stencyl|fusion|nativescript) [0-9]{0,5}(\.[0-9]{0,5}){0,2}$/,
},
os_version: {
type: 'string',
pattern: /^(ios|android|windows|windows_phone|blackberry|roku|tizen|nacl|mac_osx|tvos|webplayer|ps4|xboxone|uwp_mobile|uwp_desktop|uwp_console|uwp_iot|uwp_surfacehub|webgl|xbox360|ps3|psm|vita|wiiu|samsung_tv|linux|watch_os) [0-9]{0,5}(\.[0-9]{0,5}){0,2}$/,
required: true,
},
manufacturer: {
type: 'string',
maxLength : 64,
required: true,
},
device: {
type: 'string',
maxLength : 64,
required: true,
},
platform: {
type: 'string',
required: true,
enum: [
'ios',
'android',
'windows',
'windows_phone',
'blackberry',
'roku',
'tizen',
'nacl',
'mac_osx',
'tvos',
'webplayer',
'ps4',
'xboxone',
'uwp_mobile',
'uwp_desktop',
'uwp_console',
'uwp_iot',
'uwp_surfacehub',
'webgl',
'xbox360',
'ps3',
'psm',
'vita',
'wiiu',
'samsung_tv',
'linux',
'watch_os',
],
},
session_id: {
type: 'string',
pattern: /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,
required: true,
},
build: {
type: 'string',
maxLength : 32,
required: false,
},
session_num: {
type: 'number',
minimum: 1,
required: true,
},
connection_type: {
type: 'string',
enum: ['offline', 'wwan', 'wifi', 'lan'],
required: false,
},
jailbroken: {
type: 'boolean',
enum: [true],
required: false,
},
};
|
import React from 'react'
import { Statistic } from 'semantic-ui-react'
const HomeStatistic = ({ size, tiny, title, value, unit }) => (
<div>
<Statistic size={tiny? 'tiny': null} color="teal">
{ title? <Statistic.Label>{title}</Statistic.Label>: null}
{ value.toString().length? <Statistic.Value>{value}</Statistic.Value>: null}
{ unit? <Statistic.Label>{unit}</Statistic.Label>: null}
</Statistic>
</div>
)
export default HomeStatistic
|
const fs = require("fs");
const [, , source, dtsAndJs, dest] = process.argv;
const sourceDir = `./bazel-bin/${source}`;
const destDir = `./${dest || source}`;
let check = (object) => object.endsWith(".ts") && !object.endsWith(".spec.ts") && !object.endsWith(".d.ts");
if ( dtsAndJs ) {
check = (object) => object.endsWith(".js");
}
function sync(sourceDir, destDir) {
const objects = fs.readdirSync(sourceDir);
for (const object of objects) {
const sourcePath = `${sourceDir}/${object}`;
const targetPath = `${destDir}/${object}`;
if (fs.statSync(sourcePath).isDirectory() && !/.runfiles/.test(sourcePath)) {
sync(sourcePath, targetPath)
} else if (check(object)) {
fs.writeFileSync(targetPath, fs.readFileSync(sourcePath));
}
}
}
sync(sourceDir, destDir); |
//Display model
//check how to apply style object in item values. -- TODO
App.OperatorBtns = DS.Model.extend({
value: DS.attr('string'),
width: DS.attr('string'),
height: DS.attr('string'),
className: DS.attr('string'),
type: DS.attr('string')
})
/*Ember Data makes it easy to use a Model to retrieve records from a server,
cache them for performance, save updates back to the server, and
create new records on the client.*/
App.OperatorBtns.FIXTURES = [{
id: '200',
value: '.',
className: 'OperatorBtnClass',
type: 'operator',
},{
id: '201',
value: '*',
className: 'OperatorBtnClass',
type: 'operator',
}, {
id: '202',
value: '/',
className: 'OperatorBtnClass',
type: 'operator',
}, {
id: '203',
value: '+',
className: 'OperatorBtnClass',
type: 'operator',
}, {
id: '204',
value: '-',
className: 'OperatorBtnClass',
type: 'operator',
}, {
id: '205',
value: '=',
className: 'equalBtnClass',
type: 'equal',
}, {
id: '206',
value: 'c',
className: 'ClearBtnClass',
type: 'clear',
}]
|
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
var ageLimit = document.getElementById('ageLimit');
var buttons = Array.prototype.slice.call(document.getElementsByClassName('agelimit-button'));
var acceptButton = buttons[0];
acceptButton.addEventListener('click', function(){
setCookie('clicklink', 'yes', 30);
document.documentElement.classList.remove('overflow-hidden');
ageLimit.classList.add('invisible');
setTimeout(function() {
ageLimit.classList.add('d-none');
}, 500);
});
var cookieString = getCookie("clicklink");
if (cookieString == "yes") {
document.documentElement.classList.remove('overflow-hidden');
ageLimit.classList.add('d-none');
};
/* ---- particles.js config ---- */
particlesJS("particles-js", {
"particles": {
"number": {
"value": 60,
"density": {
"enable": true,
"value_area": 1000
}
},
"shape": {
"type": "image",
"image": {
"src": "img/wir2-herz.png",
"width": 100,
"height": 100
}
},
"opacity": {
"value": 1,
"random": true,
"anim": {
"enable": false,
"speed": .5,
"opacity_min": 0.1,
"sync": true
}
},
"size": {
"value": 30,
"random": true,
"anim": {
"enable": true,
"speed": 5,
"size_min": 0.1,
"sync": false
}
},
"line_linked": {
"enable" : false,
},
"move": {
"enable": true,
"speed": 4,
"direction": "none",
"random": false,
"straight": false,
"out_mode": "out",
"bounce": false,
"attract": {
"enable": false,
"rotateX": 600,
"rotateY": 1200
}
}
},
"interactivity": {
"detect_on": "canvas",
"events": {
"onhover": {
"enable": false,
"mode": "repulse"
},
"onclick": {
"enable": true,
"mode": "push"
},
"resize": true
},
"modes": {
"grab": {
"distance": 800,
},
"bubble": {
"distance": 800,
"size": 80,
"duration": 2,
"opacity": 0.8,
"speed": 3
},
"repulse": {
"distance": 400,
"duration": 0.4
},
"push": {
"particles_nb": 4
},
}
},
"retina_detect": true
});
|
+(function($) {
'use strict';
// Start of Plugin
$.fn.offscreenMenu = function( options ) {
var defaultSettings = {
menuWidth : 320,
openMaster: '.oc-open',
closeMaster: '.oc-close',
position: 'left',
animationDuration: 300
}
$.extend(defaultSettings, options);
var _this = this;
return this.each(function(){
_this.css( 'width', defaultSettings.menuWidth + 'px');
$(defaultSettings.openMaster).on('click', function(){
_this.toggleClass(defaultSettings.openMaster.replace('.', ''));
_this.css(defaultSettings.position, 0);
$(defaultSettings.closeMaster).toggleClass('show');
$('body').addClass('oc-overlay');
});
$(defaultSettings.closeMaster).on('click', function(){
_this.toggleClass(defaultSettings.openMaster.replace('.', ''));
_this.css(defaultSettings.position, '-' + defaultSettings.menuWidth + 'px');
$(this).toggleClass('show');
$('body').removeClass('oc-overlay');
});
$('li:has(> ul)').addClass('hassubmenu');
// if(hasdropdown.has('> ul')){
// hasdropdown.has('> ul').prepend('<span class="hasSub close"></span>');
// hasdropdown.children('ul').addClass('hide');
// $('.hasSub').siblings('ul').addClass('hide');
// $('.hasSub').on('click', function(e){
// var selected = $(this);
// if(selected.siblings('ul').hasClass('hide')){
// selected.siblings('ul').addClass('hide').removeClass('show');
// selected.siblings('ul').removeClass('hide').addClass('show');
// }
// else{
// selected.siblings('ul').addClass('hide').removeClass('show');
// }
// selected.toggleClass('open');
// selected.next('a').toggleClass('active');
// });
// };
});
}
}(jQuery)); |
import React, { Fragment, useContext } from 'react';
import Button from "./Button";
import LanguageContext from '../contexts/LanguageContext';
const LoginPage = () => {
// const {data} = useContext(LanguageContext);
return(
<Fragment>
<div>Log In</div>
<Button/>
</Fragment>
)
};
export default LoginPage; |
import {
LOAD_PRODUCT_LIST
} from '@/web-client/actions/constants';
const initialState = [];
const productList = (state = initialState, {type, payload}) => {
if (type === LOAD_PRODUCT_LIST)
{
return Array.isArray(payload) ? payload : [];
}
return state;
};
export default productList; |
import React, { Component } from "react";
import { Map, GoogleApiWrapper } from "google-maps-react";
import "./mainPage.css";
class mainPage extends Component {
state = {
distance: 0,
error: false,
Supermarkets: false,
schools: false,
churches: false,
Community: false,
Libraries: false,
cafe: false,
Dance: false,
Gyms: false,
Swimming: false,
Playgrounds: false,
Parks: false,
resaltState: false
};
handleSupermarketsCheckboxChange = event =>
this.setState({ Supermarkets: event.target.checked});
handleSchoolsCheckboxChange = event =>
this.setState({ checked: event.target.checked });
handleChurchesCheckboxChange = event =>
this.setState({ checked: event.target.checked });
handleCommunityCheckboxChange = event =>
this.setState({ checked: event.target.checked });
handleLibrariesCheckboxChange = event =>
this.setState({ checked: event.target.checked });
handleCafeCheckboxChange = event =>
this.setState({ checked: event.target.checked });
handleDanceCheckboxChange = event =>
this.setState({ checked: event.target.checked });
handleGymsCheckboxChange = event =>
this.setState({ checked: event.target.checked });
handleSwimmingCheckboxChange = event =>
this.setState({ checked: event.target.checked });
handlePlaygroundsCheckboxChange = event =>
this.setState({ checked: event.target.checked });
handleParksCheckboxChange = event =>
this.setState({ checked: event.target.checked });
// function to be implamented
/**
* when button is pressed it will call the function error catch
* then based on the resalts will convert state to a JSON then
* send that info to the dack end.
* once a respons ie receved send that JSON object to
* the plot function.
*/
buttonClick = () => {
this.setState({resaltState: false});
};
errorButtonClick = () => {
this.setState({error: false});
}
errorCheck = () => {
/*if( === false){
this.setState({error: true})
}*/
};
optionClick = () =>{
if (this.state.resaltState === true){this.setState({resaltState: false});}
else{this.setState({resaltState: false})};
};
ERROR = () =>{
return(
<div>
ERROR:<br></br>
Pleae make sure that all of the search bars are filed <br></br>
<button onClick = {this.errorButtonClick}>
Okay
</button>
</div>
)
}
render() {
return (
<div>
<div className="tittle">
<font style={{ color: "white" }}>NAME OF WEBPAGE</font>
</div>
<body className="body">
<div className="map">
<Map
google={this.props.google}
zoom={8}
style={this.state.map}
initialCenter={{ lat: 37.7510, lng: -97.8220 }}
/>
</div>
<div className="resalt">
<div className="menu">
<view style={{ flex: 1 }}>
<text style={{ textAlign: "right" }}>
<font style={{ color: "white" }}>Reslats</font>
</text>
</view>
<br></br>
</div>
</div>
<div className="option">
<div className="menu" onClick={() => this.optionClick({})}>
<view style={{ flex: 1 }}>
<text style={{ textAlign: "right" }}>
<font style={{ color: "white" }}>MENU</font>
</text>
</view>
<br></br>
</div>
enter address or zip
<form action="/action_page.php">
address and streat:
<input type="text" name="fname"></input>
<br></br>
</form>
state:
<select>
<option selected value="grapefruit">
select one
</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="DC">District Of Columbia</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>
city:
<input type="text" name="fname"></input>
<br></br>
zipcode:
<input type="text" name="fname"></input>
<br></br>
<div>
distance:
<input
type="range"
min="1"
max="25"
style={{ height: "25px", verticalAlign: "middle" }}
></input>
</div>
options: <br></br>
<div>
<input
type="checkbox"
style={this.checkboxStyle}
checked={this.state.checked}
onChange={this.handleCheckboxChange}
/>
Supermarkets
<br></br>
<input
type="checkbox"
checked={this.state.checked}
onChange={this.handleCheckboxChange}
/>
Schools
<br></br>
<input
type="checkbox"
checked={this.state.checked}
onChange={this.handleCheckboxChange}
/>
Churches
<br></br>
<input
type="checkbox"
checked={this.state.checked}
onChange={this.handleCheckboxChange}
/>
Community Buildings
<br></br>
<input
type="checkbox"
checked={this.state.checked}
onChange={this.handleCheckboxChange}
/>
Libraries
<br></br>
<input
type="checkbox"
checked={this.state.checked}
onChange={this.handleCheckboxChange}
/>
Cafe
<br></br>
<input
type="checkbox"
checked={this.state.checked}
onChange={this.handleCheckboxChange}
/>
Dance schools
<br></br>
<input
type="checkbox"
checked={this.state.checked}
onChange={this.handleCheckboxChange}
/>
Gyms
<br></br>
<input
type="checkbox"
checked={this.state.checked}
onChange={this.handleCheckboxChange}
/>
Swimming pools
<br></br>
<input
type="checkbox"
checked={this.state.checked}
onChange={this.handleCheckboxChange}
/>
Playgrounds
<br></br>
<input
type="checkbox"
checked={this.state.checked}
onChange={this.handleParksCheckboxChange}
/>
Parks
<br></br>
</div>
<div>
<button
type="button"
onClick={() => this.buttonClick({})}
style={{
backgroundColor: "MediumSeaGreen"
}}
>
search
</button>
</div>
</div>
</body>
</div>
);
}
}
export default GoogleApiWrapper({
apiKey: "AIzaSyDjxQG1nLTRjlCFbVB4mq_jMtu40GMR5D4"
})(mainPage);
//export default Test69M;
|
import React, { Component } from 'react';
import {Redirect,Link} from "react-router-dom";
export class Bridefather extends Component
{
constructor(props) {
super(props);
this.state = {
name: "React",
showHideDemo1: false,
};
const {value:{bridefatherlivingstatus,bridefatherreligion,bridebridefatherchooseaddress,Street3,Village3,Taluk3,District3,
State3,Country3,Pincode3,Street4,Village4,Taluk4, District4,State4,Country4,Pincode4}}=this.props;
if(bridefatherlivingstatus==="1")
{
if(bridebridefatherchooseaddress==="1")
{
this.state = {
showHideDemo1: true,
Street:Street3,
Village:Village3,
Taluk:Taluk3,
District:District3,
State:State3,
Country:Country3,
Pincode:Pincode3,
};
}
else
{
this.state = {
showHideDemo1: true,
Street:Street4,
Village:Village4,
Taluk:Taluk4,
District:District4,
State:State4,
Country:Country4,
Pincode:Pincode4,
};
}
}
else
{
this.state = {
showHideDemo1: false,
};
}
}
state={
bridefathererror:"",
bridefatherageerror:"",
bridefatherreligionerror:"",
bridefatheroccupationerror:"",
bridefatherlivingstatuserror:"",
Pincode4error:"",
}
continue=e=>{
e.preventDefault();
const isValid=this.validateForm();
if(isValid){
this.props.nextStep();
}
};
validateForm() {
let isValid = true;
const {value:{bridefather,bridefatherage,bridefatherlivingstatus,bridefatherreligion,bridebridefatherchooseaddress,Street4,Village4,Taluk4,District4,State4,Country4,Pincode4}}=this.props;
let bridefathererror="";
let bridefatherageerror="";
let bridefatherlivingstatuserror="";
let Pincode4error="";
let bridefatherreligionerror="";
if(bridefather===""||bridefather===undefined)
{
bridefathererror="Please enter father name";
isValid=false;
}
else{
if(!bridefather.match(/^[a-zA-Z ]*$/))
{
bridefathererror="Please enter alphabet characters only";
isValid=false;
}
}
// if(bridefatherage===""||bridefatherage===undefined)
// {
// bridefatherageerror="Please enter father age";
// isValid=false;
// }
if(bridefatherlivingstatus===""||bridefatherlivingstatus===undefined)
{
bridefatherlivingstatuserror="Please enter father living status";
isValid=false;
}
this.setState({bridefathererror,bridefatherageerror,bridefatherlivingstatuserror,Pincode4error,bridefatherreligionerror})
return isValid;
}
back = e => {
e.preventDefault();
this.props.prevStep();
};
onMenuItemClicked = () => {
this.setState({showHideDemo1: !this.state.showHideDemo1});
}
onMenuItemClickedvalue = () => {
const showHideDemo1=false;
this.setState({showHideDemo1: showHideDemo1});
}
myFunction=e=> {
const {value:{Street3,Village3,Taluk3,District3,
State3,Country3,Pincode3}}=this.props;
var checkBox = document.getElementById("bridebridefatherchooseaddress");
if (checkBox.checked === true){
document.getElementById("bs_name").value=Street3;
document.getElementById("bv_name").value=Village3;
document.getElementById("bd_name").value=District3;
document.getElementById("bt_name").value=Taluk3;
document.getElementById("bst_name").value=State3;
document.getElementById("bc_name").value=Country3;
document.getElementById("bp_name").value=Pincode3;
} else {
document.getElementById("bs_name").value="";
document.getElementById("bv_name").value="";
document.getElementById("bd_name").value="";
document.getElementById("bt_name").value="";
document.getElementById("bst_name").value="";
document.getElementById("bc_name").value="";
document.getElementById("bp_name").value="";
}
}
closeform=e=>
{
window.localStorage.clear();
this.setState({referrer: '/sign-in'});
}
render()
{
const {referrer} = this.state;
if (referrer) return <Redirect to={referrer} />;
var fname=localStorage.getItem('firstname');
var lname=localStorage.getItem('lastname');
const { showHideDemo1} = this.state;
const {value,inputChange}=this.props;
const {value:{bridefather,bridefatherreligion,bridefatherlivingstatus,bridefatherage,bridefatheroccupation,bridebridefatherchooseaddress,
Street4,Village4,Taluk4,District4,State4,Country4,Pincode4}}=this.props;
return(
<div >
<div class="header_design w-100">
<div class="row float-right m-3" style={{marginRight:"20px"}}> <b style={{marginTop: "7px"}}><label >Welcome {fname }</label></b> <button style={{marginTop: "-7px"}} className="btn btn-primary" onClick={() => this.closeform()} style={{marginToptop: "-7px"}}>logout</button></div>
<div class="text-black">
<div class="text-black">
<div class="border-image p-4"></div> </div>
</div> </div>
<div class="body_UX">
<div class="body_color_code m-4">
<div className="img_logo"></div>
<br></br>
<br></br><br></br>
<div class="box m-4">
<div className="form-container ">
<br></br>
<h1>Details of Bride Father </h1>
<br></br>
<div class="row">
<div class="col-md-3">
<label>Father's Name<span style={{color:"red"}}> *</span></label>
<input type="text" className="input" name="bridefather" value={value.bridefather} onChange={inputChange('bridefather')} />
<p style={{color:"red"}}>{this.state.bridefathererror}</p>
</div>
<div class="col-md-3">
<label>Father's Relegion<span style={{color:"red"}}> *</span></label>
<input type="text" className="input" name="bridefatherreligion" value={value.bridefatherreligion} onChange={inputChange('bridefatherreligion')} />
<p style={{color:"red"}}>{this.state.bridefatherreligionerror}</p>
</div>
<div class="col-md-3">
<label>Living Status<span style={{color:"red"}}> *</span></label>
<div className="form-group">
<input type="radio" id="alive" name="bridefatherlivingstatus" value="1" onClick={() => this.onMenuItemClicked()} checked={value.bridefatherlivingstatus==="1"} onChange={inputChange('bridefatherlivingstatus')}/>
<label > Alive </label>
<input type="radio" id="dead" name="bridefatherlivingstatus" value="2" onClick={() => this.onMenuItemClickedvalue()} checked={value.bridefatherlivingstatus==="2"} onChange={inputChange('bridefatherlivingstatus')}/>
<label > Dead</label>
<p style={{color:"red"}}>{this.state.bridefatherlivingstatuserror}</p>
</div>
</div>
</div>
<br></br>
<br></br>
{ this.state.showHideDemo1 &&
<div id="div3">
<div class="row">
<div class="col-md-3">
<label>Father's Age</label>
<input type="number" className="input" name="bridefatherage" value={value.bridefatherage} onChange={inputChange('bridefatherage')} />
<p style={{color:"red"}}>{this.state.bridefatherageerror}</p>
</div>
<div class="col-md-3">
<div id="div2" >
<label>Father's Occupation</label>
<input type="text" className="input" name="bridefatheroccupation" value={value.bridefatheroccupation} onChange={inputChange('bridefatheroccupation')} />
</div>
</div>
</div>
<br></br>
<div class="row"><div class="col-md-12"> <label >Father's Address</label></div></div>
<div class="row">
<br></br>
<div class="col-md-3">
<br></br>
<input type="checkbox" id="bridebridefatherchooseaddress" name="bridebridefatherchooseaddress" value="1" onClick={this.myFunction} checked={value.bridebridefatherchooseaddress==="1"} onChange={inputChange('bridebridefatherchooseaddress')}/>
<label > Address same as Daughter </label>
</div>
<div class="col-md-3" >
<label>Street</label>
<input type="text" className="input" id="bs_name" name="Street4" value={this.state.Street} onChange={inputChange('Street4')} />
</div>
<div class="col-md-3" >
<label>Village</label>
<input type="text" className="input" id="bv_name" name="Village4" value={this.state.Village} onChange={inputChange('Village4')} />
</div>
<div class="col-md-3">
<label>Taluk</label>
<input type="text" className="input" id="bt_name" name="Taluk4" value={this.state.Taluk} onChange={inputChange('Taluk4')} />
</div>
</div>
<br></br>
<div class="row">
<div class="col-md-3">
<label>District</label>
<input type="text" className="input" id="bd_name" name="District4" value={this.state.District} onChange={inputChange('District4')} />
</div>
<div class="col-md-3">
<label>State</label>
<input type="text" className="input" id="bst_name" name="State4" value={this.state.State} onChange={inputChange('State4')} />
</div>
<div class="col-md-3">
<label>Country</label>
<input type="text" className="input" id="bc_name" name="Country4" value={this.state.Country} onChange={inputChange('Country4')} />
</div>
<div class="col-md-3">
<label>Pincode</label>
<input type="number" className="input" id="bp_name" name="Pincode4" value={this.state.Pincode} onChange={inputChange('Pincode4')} />
<p style={{color:"red"}}>{this.state.Pincode4error}</p>
</div>
</div>
<br></br>
<br></br>
</div>
}
<br></br>
<br></br>
<br></br>
</div>
</div>
<div className="row">
<div className="col-md-6">
<button className="pev m-4" onClick={this.back}>Previous</button>
</div>
<div className="col-md-6">
<div className="text-right">
<button className="next m-4" onClick={this.continue}>Next</button>
</div>
</div>
</div>
<br></br><br></br> <br></br><br></br> <br></br>
</div>
</div></div>
)
}
}
export default Bridefather |
module.exports = {
root: true,
env: {
browser: true,
node: true
},
parser: "vue-eslint-parser",
parserOptions: {
"parser": 'babel-eslint',
"sourceType": "module",
"ecmaVersion": 2018,
"ecmaFeatures": {
"globalReturn": false,
"impliedStrict": false,
"jsx": false
}
},
extends: [
'plugin:prettier/recommended',
'prettier',
'prettier/vue'
],
plugins: [
'prettier',
'gridsome'
],
// add your custom rules here
rules: {
"gridsome/format-query-block": "error"
},
ignorePatterns:[
"service-worker.js"
]
}
|
const navContent = document.getElementById('navbar-links');
function toggleMobileMenu() {
navContent.classList.toggle('navbar-content');
} |
export default function sketch (p5) {
const _aryInitRot = []
let _myObject
const numParts = 300
const slowliness = 8
const minThicknessWidthRatio = 3// bigger = thinner ; 1 to 10
const maxThicknessWidthRatio = 1.5// bigger = thinner ; 1 to 10
const expansionProbability = 0.9// 0.1 to 1
p5.setup = () => {
let canvasSize
if (p5.windowWidth >= p5.windowHeight) {
canvasSize = p5.windowWidth * 0.975// 2.5% margin because sometimes the value is slghtly bigger than the actual dimension
} else {
canvasSize = p5.windowHeight * 0.975
}
p5.createCanvas(canvasSize, canvasSize, p5.WEBGL)
// document.getElementsByTagName('main')[0].style.margin = 0
p5.setAttributes('premultipliedAlpha', true)
p5.frameRate(40)
p5.noStroke()
for (let i = 0; i < 3; i++) {
_aryInitRot[i] = [p5.random(2 * p5.PI), p5.random([-1, 1])]
}
_myObject = new Parts(numParts)
}
p5.draw = () => {
p5.ortho(-p5.width / 2, p5.width / 2, -p5.width / 2, p5.width / 2, 0, p5.width * 2)
p5.background(0)
p5.ambientLight(150)
const ang = _aryInitRot[1][0] + p5.frameCount / 100
p5.directionalLight(255, 255, 255, -p5.sin(ang), 1, -p5.cos(ang))
const c = (p5.height / 2) / p5.tan(p5.PI / 6)
p5.camera(c * p5.sin(ang), 0, c * p5.cos(ang), 0, 0, 0, 0, 1, 0)
p5.rotateZ(p5.PI / 4)
_myObject.update()
}
function drawPart (startX, startY, startZ, endX, endY, endZ, w, col) {
const angAxisZ = p5.atan2(endY - startY, endX - startX)
const distXY = p5.dist(startX, startY, endX, endY)
const angAxisY = -p5.atan2(endZ - startZ, distXY)
const distXYZ = p5.dist(0, startZ, distXY, endZ)
p5.push()
p5.translate(startX, startY, startZ)
p5.rotateZ(angAxisZ)
p5.rotateY(angAxisY)
p5.translate(distXYZ / 2, 0, 0)
p5.ambientMaterial(col)
p5.box(distXYZ + w, w, w) // length + w
p5.pop()
}
class Part {
constructor (startX, startY, startZ, endX, endY, endZ, w, totalTime, partCount, maxW) {
this.startX = startX
this.startY = startY
this.startZ = startZ
this.endX = endX
this.endY = endY
this.endZ = endZ
this.w = w
this.totalTime = totalTime
this.currentTime = 0
this.direction = true // true -> extend, false -> shrink
this.erase = false
this.col = p5.color(255)
}
update () {
let currentX
let currentY
let currentZ
if (this.direction) { // extend
const ratio = (this.currentTime / this.totalTime) ** 0.5
currentX = this.startX + (this.endX - this.startX) * ratio
currentY = this.startY + (this.endY - this.startY) * ratio
currentZ = this.startZ + (this.endZ - this.startZ) * ratio
if (this.currentTime < this.totalTime) { this.currentTime++ }
drawPart(this.startX, this.startY, this.startZ, currentX, currentY, currentZ, this.w, this.col)
} else { // shrink
const ratio = (1 - (this.currentTime - this.totalTime) / this.totalTime) ** 0.5
currentX = this.endX + (this.startX - this.endX) * ratio
currentY = this.endY + (this.startY - this.endY) * ratio
currentZ = this.endZ + (this.startZ - this.endZ) * ratio
this.currentTime++
if (this.currentTime > this.totalTime * 2) { this.erase = true }
drawPart(this.endX, this.endY, this.endZ, currentX, currentY, currentZ, this.w, this.col)
}
}
}
class Parts {
constructor (numPart) {
this.maxArea = p5.width / 3.4
this.maxW = p5.width / 10
this.t = slowliness
this.maxL = this.maxArea
this.parts = []
const w = p5.max(p5.width / (minThicknessWidthRatio * 100), this.maxW / maxThicknessWidthRatio * p5.random() ** (12 / expansionProbability))
// let w = max(width / 300, this.maxW * p5.random() ** 12)
const startX = -this.maxArea / 2
const startY = -this.maxArea / 2
const startZ = -this.maxArea / 2
let aryEndXYZ = this.randomDirection(startX, startY, startZ)
while (p5.abs(aryEndXYZ[0]) > this.maxArea || p5.abs(aryEndXYZ[1]) > this.maxArea || p5.abs(aryEndXYZ[2]) > this.maxArea) {
aryEndXYZ = this.randomDirection(startX, startY, startZ)
}
const endX = aryEndXYZ[0]
const endY = aryEndXYZ[1]
const endZ = aryEndXYZ[2]
this.partCount = p5.int(p5.random(1000))
this.parts.push(new Part(startX, startY, startZ, endX, endY, endZ, w, this.t, this.partCount, this.maxW))
this.numPart = numPart
this.isGenerate = false
}
update () {
for (let i = 0; i < this.parts.length; i++) {
this.parts[i].update()
}
if (this.parts[this.parts.length - 1].currentTime >= this.parts[this.parts.length - 1].totalTime) {
this.isGenerate = true
}
if (this.isGenerate === true && this.parts.length < this.numPart) {
const w = p5.max(p5.width / (minThicknessWidthRatio * 100), this.maxW / maxThicknessWidthRatio * p5.random() ** (12 / expansionProbability))
const startX = this.parts[this.parts.length - 1].endX
const startY = this.parts[this.parts.length - 1].endY
const startZ = this.parts[this.parts.length - 1].endZ
let aryEndXYZ = this.randomDirection(startX, startY, startZ)
while (true) {
const lastPart = this.parts[this.parts.length - 1]
const vecLast = p5.createVector(lastPart.endX - lastPart.startX, lastPart.endY - lastPart.startY, lastPart.endZ - lastPart.startZ)
const vecCurr = p5.createVector(aryEndXYZ[0] - startX, aryEndXYZ[1] - startY, aryEndXYZ[2] - startZ)
const dotProduct = vecLast.dot(vecCurr)
// console.log(p5.Vector.normalize(vecCurr))
// console.log(p5.Vector.normalize(vecLast))
// console.log("dot" + dotProduct)
// try to avoid opposite
if (dotProduct > -1) { break }
aryEndXYZ = this.randomDirection(startX, startY, startZ)
}
while (p5.abs(aryEndXYZ[0]) > this.maxArea || p5.abs(aryEndXYZ[1]) > this.maxArea || p5.abs(aryEndXYZ[2]) > this.maxArea) {
aryEndXYZ = this.randomDirection(startX, startY, startZ)
}
const endX = aryEndXYZ[0]
const endY = aryEndXYZ[1]
const endZ = aryEndXYZ[2]
this.partCount++
this.parts.push(new Part(startX, startY, startZ, endX, endY, endZ, w, this.t, this.partCount, this.maxW))
this.isGenerate = false
}
if (this.parts.length >= this.numPart) {
this.parts[0].direction = false
}
if (this.parts[0].erase === true) { this.parts.shift() }
}
randomDirection (startX, startY, startZ) {
let endX = startX
let endY = startY
let endZ = startZ
const direction = p5.random(['-x', 'x', '-y', 'y', '-z', 'z'])
switch (direction) {
case '-x':
endX = startX + this.maxL * p5.random(-1, 0)
break
case 'x':
endX = startX + this.maxL * p5.random(0, 1)
break
case '-y':
endY = startY + this.maxL * p5.random(-1, 0)
break
case 'y':
endY = startY + this.maxL * p5.random(0, 1)
break
case '-z':
endZ = startZ + this.maxL * p5.random(-1, 0)
break
case 'z':
endZ = startZ + this.maxL * p5.random(0, 1)
break
}
return [endX, endY, endZ]
}
}
}
|
import React from 'react';
import {Text, View} from 'react-native';
import ProgressCircle from 'react-native-progress-circle';
import {styles} from './styles';
// const propStyle = percent => {
// const base_degrees = -135;
// const rotateBy = base_degrees + percent * 3.6;
// return {
// transform: [{rotateZ: `${rotateBy}deg`}],
// };
// };
const CircularProgress = props => {
console.log(props.percent);
return (
<View style={styles.container}>
<ProgressCircle
percent={props.percent}
radius={50}
borderWidth={8}
color="#3399FF"
// shadowColor="#999"
bgColor="#fff">
<Text style={styles.textstyle}>{props.percent}%</Text>
</ProgressCircle>
</View>
);
};
export default CircularProgress;
|
/*
* AppController
*
* Created at: 07/23/2014
* Updated at: 07/29/2014
*
*/
define(
[
//bootstrap
'eventHandler',
// libs
'jquery', 'bootstrap',
// utils
'anima', 'audio', 'cssBuilder',
// controllers
'./chat.js',
'./clock.js',
// views
App.path.view + 'common/header.html',
App.path.view + 'common/footer.html',
App.path.view + 'hello.html',
//App.path.views+ '',
],
function ( evtHandler, $, B, Anima, Audio, CSS, cChat, cClock, vHeader, vFooter, vHello ) {
var status = 'undefined'
function init () {
if ( status !== 'undefined' )
return status
$('title').append(App.title)
$('body')
.append(vHeader)
.append(vHello)
.append(vFooter)
CSS.load('bootstrap.min')
.load('bootstrap-responsive.min')
.load('default')
// .unload('bootstrap.min')
Audio
.init()
.playSound('menu')
//.playSound('all') // playSound('a')
//.stopSound('menu') // stopSound('all')
cChat
.init()
.selfTest()
cClock.init()
// eventHandler.attach('newEvent', function() {})
// evtHandler.trigger('newEvent')
// Animation example (LOA INTRO):
Anima.init('autoplay', {
duration: 0.1,
interval: 0.1,
})
return status = 'started'
}
return { init: init }
}
) |
import React from 'react';
import {
Card,
CardMedia,
CardActions,
CardHeader,
Avatar,
} from '@material-ui/core';
import { Link } from 'react-router-dom';
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles((theme) => ({
cardMedia: {
height: 0,
paddingTop: '100%',
'&:hover': {
cursor: 'pointer',
},
},
card: {
maxWidth: 345,
borderRadius: 30,
},
cardHeader: {
height: 15,
},
avatar: {
'&:hover': {
cursor: 'pointer',
},
},
avatarnull: {
'&:hover': {
cursor: 'pointer',
},
backgroundColor: theme.palette.secondary.main,
},
}));
const PhotoCard = ({ photo }) => {
const classes = useStyles();
return (
<Card className={classes.card}>
<CardMedia
className={classes.cardMedia}
image={photo.image}
title={photo.name}
/>
<CardActions>
<CardHeader
avatar={
photo.user.image ? (
<Avatar
alt="Remy Sharp"
src={photo.user.image}
className={classes.avatar}
component={Link}
to="/profile/meganli"
/>
) : (
<Avatar className={classes.avatarnull}>
{photo.user.name.split(' ')[0].charAt(0)}
</Avatar>
)
}
title={
<Link to="/profile/meganli" style={{ color: 'black' }}>
{photo.user.name}
</Link>
}
subheader={photo.time}
className={classes.cardHeader}
/>
</CardActions>
</Card>
);
};
export default PhotoCard;
|
//sample passing test
describe('My First Test', () => {
it('Does not do much!', () => {
expect(true).to.equal(true)
})
})
//sample failing test
describe('My First Test', () => {
it('Does not do much!', () => {
expect(true).to.equal(false)
})
}) |
$('#ver_detalle').on('show.bs.modal', function(event) {
let button = $(event.relatedTarget);
$("#procesoventa_id").val(button.data('proceso_venta_id'));
$("#producto_descripcion").val(button.data('producto'));
$("#producto_kilogramos").val(button.data('kilogramos'));
$("#fechasolicitud").val(button.data('fechacreacion'));
$.ajax({
url : "/transportista/subastas/detalle",
data : {
proceso_venta_id : button.data('proceso_venta_id')
},
dataType : "json",
success : function(data) {
$('#tabla_dinamica_ver_detalle').empty();
var trHTML = '';
$.each(data, function(i, item) {
trHTML += '<tr><td>'
+ item.productor.razonsocial
+ '</td><td>'
+ item.kilogramosocupados
+ '</td><td>'
+ item.productor.direccion
+ '</td><td>'
+ item.productor.comuna
+ '</td></tr>';
});
$('#tabla_dinamica_ver_detalle').append(trHTML);
}
});
});
$('.btn_ofertar').click(function (e) {
e.preventDefault();
$('.btn_ofertar').prop('disable', true);
const valor_ofertado = parseInt($('#precio_a_ofertar').val(), 10);
if(isNaN(valor_ofertado) || valor_ofertado <= 0){
MENSAJE_ERROR('','Ingresa un valor de oferta válido para esta subasta.');
return;
}
Swal.fire({
title: '',
text: "¿Realmente desea ofertar a la subasta con el precio ofrecido?",
type: 'warning',
showCancelButton: true,
confirmButtonText: "Ofertar",
confirmButtonColor: '#28a745',
cancelButtonText: 'Cerrar',
cancelButtonColor: '#6c757d'
}).then((result) => {
if (result.value) {
respuestaOferta(valor_ofertado);
}else{
$('.btn_ofertar').prop('disable', false);
}
})
const respuestaOferta = function(valor_ofertado){
$.ajax({
url : "/transportista/subasta/ofertar",
data : {
proceso_venta_id : $('#procesoventa_id').val(),
valoroferta: valor_ofertado
},
dataType : "json",
success : function(data) {
if (data === -2) {
MENSAJE_ERROR('','Sólo los usuarios transportistas pueden ofertar a una subasta.');
}
if (data === -1) {
MENSAJE_ERROR('','No se ha podido ofertar a la subasta, favor contacta al administrador.');
}else if(data === 1){
MENSAJE_SUCCESS('',
'Se ha ofertado satisfactoriamente a la subasta actual',
'Cerrar',
'transportista/subastas');
}else {
MENSAJE_ERROR('','Hubo un problema en el sistema, favor contacta con el administrador si ves este mensaje (COD: 10501).');
}
$('.btn_ofertar').prop('disable', false);
}
});
}
}); |
import React, { useState, useRef } from 'react'
import { Redirect } from 'react-router-dom'
import iconAdd from './icon-add.png'
const minAno = 2019
const maxAno = 2022
const AddMonths = () => {
const anos = []
const meses = []
const [redir, setRedir] = useState('')
const refAno = useRef()
const refMes = useRef()
for(let i = minAno; i <= maxAno; i++){
anos.push(i)
}
for(let i = 1; i<=12; i++){
meses.push(i)
}
const zeroPad = num => {
if(num < 10){
return '0' + num
}
return num
}
const verMes = () => {
setRedir(refAno.current.value + '-' + refMes.current.value)
}
if(redir!==''){
return <Redirect to={'/moves/'+ redir} />
}
return (
<div className='div-add'>
<h3><img src={iconAdd} className='icon'/>Adicionar mês</h3>
<select ref={refAno}>
{anos.map(ano => <option key={ano} value={ano}>{ano}</option> )}
</select>
<select ref={refMes}>
{meses.map(zeroPad).map(mes => <option key={mes} value={mes}>{mes}</option> )}
</select>
<button className='btn btn-primary' onClick={verMes}>NOVO MÊS</button>
</div>
)
}
export default AddMonths |
$(document).delegate('.box_available li', 'click', function() {
$item_id = $(this).attr('data-id');
$html = '<li>';
$html += $(this).html();
$html += ' <input type="hidden" name="items[]" value="' + $item_id + '" />';
$html += ' <i class="fa fa-close"></i>';
$html += '</li>';
$('.box_selected ul').append($html);
$(this).remove();
update_package_items();
});
$(document).delegate('.box_selected .fa-close', 'click', function() {
$(this).parents('li').remove();
update_package_items();
});
$(document).delegate('.box_selected input', 'keyup', function() {
$query = $(this).val();
if(!$query) {
$('.box_selected li').show();
return true;
}
$('.box_selected li').each(function() {
if($(this).text().indexOf($query) !== -1) {
$(this).show();
} else {
$(this).hide();
}
});
});
$(document).delegate('.box_available input', 'keyup', function() {
$query = $(this).val();
if(!$query) {
$('.box_available li').show();
return true;
}
$('.box_available li').each(function() {
if($(this).text().indexOf($query) !== -1) {
$(this).show();
} else {
$(this).hide();
}
});
});
function update_package_items() {
$.post($('#update_item_url').val(), $('#package_items').serialize());
} |
import styled from 'styled-components'
const Search = ({value,onType,...rest}) => {
return (
<StyledSearch
placeholder="Search ..."
value={value}
onChange={onType}
name="search"
type="search"
autoComplete="false"
{...rest}
/>
)
}
const StyledSearch = styled.input`
outline: none;
background-color: var(--input-bg);
color:inherit;
font-family: inherit;
border-radius: 12px;
border: 1px solid var(--input-ph);
padding: .5em .7em;
font-size:1rem;
transition: border .3s;
:focus{
border: 2px solid var(--primary);
}
`
export default Search
|
import React from 'react';
function Footer(){
return(
<div className="footer">
<ul>
<li className="listhead">CORPORATE INFORMATION</li>
<li><button>About Us</button></li>
<li><button>Careers</button></li>
<li><button>Franchise Opportunities</button></li>
</ul>
<ul>
<li className="listhead">BUYING GUIDE</li>
<li><button>FAQs</button></li>
<li><button>How To Buy</button></li>
<li><button>Size Guide</button></li>
<li><button>Payment Methods</button></li>
<li><button>Shipping And Delivery</button></li>
<li><button>Cash On Delivery Checker</button></li>
<li><button>Returns And Exchanges</button></li>
<li><button>Cancellation</button></li>
<li><button>General Information</button></li>
<li><button>Data Privacy</button></li>
</ul>
<ul>
<li className="listhead">SUPPORT</li>
<li><button>Contact Us</button></li>
<li><button>Bank Payment Confirmation</button></li>
<li><button>Life Style Card</button></li>
<li><button>BDO Bench/Mastercard</button></li>
<li><button>Order Tracker</button></li>
</ul>
<div>
<p>Keep In Touch</p>
<p>Facebook</p>
<p>Twitter</p>
<p>Instagram</p>
</div>
</div>
)
}
export default Footer; |
(function () {
'use strict';
function CampsService(APP_CONFIG, $http, Messaging) {
var CampsService = {
campaignName:'2015 Birthday Deal',
totalSold:0,
events: {
getCampByDateInRegionSuccess: '_EVENT_CAMPS_SERVICE_GET_CAMP_BY_DATE_IN_REGION_SUCCESS',
getCampByDateInRegionError: '_EVENT_CAMPS_SERVICE_GET_CAMP_BY_DATE_IN_REGION_ERROR',
getCampScoreboardSuccess: '_EVENT_CAMPS_SERVICE_GET_CAMP_SCOREBOARD_SUCCESS',
getCampScoreboardError: '_EVENT_CAMPS_SERVICE_GET_CAMP_SCOREBOARD_ERROR'
},
getCampByDateInRegion: function (date, regionID) {
$http.get(APP_CONFIG.API_ENDPOINT + 'camps/campbydate',
{
params: {'regionID': regionID, 'date': date}
, withCredentials: false
}
).then(function ($data) {
var camp = $data.data.data;
Messaging.publish(CampsService.events.getCampByDateInRegionSuccess, [camp]);
}, function (err) {
Messaging.publish(CampsService.events.getCampByDateInRegionError, [err]);
});
},
getScoreboard: function () {
$http.get(APP_CONFIG.API_ENDPOINT + 'reports/campaignscoreboard',
{
params: {'campaignName': CampsService.campaignName}
, withCredentials: false
}
).then(function ($data) {
var scoreboard = $data.data.data;
CampsService._setTotalSold(scoreboard);
Messaging.publish(CampsService.events.getCampScoreboardSuccess, [scoreboard]);
}, function (err) {
Messaging.publish(CampsService.events.getCampScoreboardError, [err]);
});
},
_setTotalSold:function(scoreboard){
CampsService.totalSold = 0;
angular.forEach(scoreboard,function(key,val){
CampsService.totalSold += key.totalSold;
});
console.log(CampsService.totalSold);
}
};
return CampsService;
};
angular.module('cg7App').service('CampsService', CampsService);
})(); |
import "./App.css";
import RTE from './RTE'
//showcases the global quill object in te browser, which is imported by react-quill-2
const r1 = new RTE()
const r2 = new RTE()
console.log(r1.quill === r2.quill)
function App() {
return (
<div className="App">
<RTE/>
</div>
);
}
export default App;
|
import React from 'react';
import ToDoList from './ToDoList'
import NewToDo from './NewToDo'
import ApplicationContext from './ApplicationContext'
import { useState } from 'react';
function App() {
// const handleChange(event){
// ({
// currentItem: {
// name: event.target.value
// }
// })
// }
// const handleSubmit(event) {
// this.setState({
// todos: this.state.todos.concat(this.state.currentItem),
// currentItem: {
// name: ''
// }
// })
// event.preventDefault()
// }
const[ todos, addTodos ] = useState([
{ name: 'laundry' },
{ name: 'buy groceries' },
{ name: 'mow lawn' }
] );
const [ currentItem, updateItem ] = useState({name: ""});
return (
<ApplicationContext.Provider value={{
todos,
addTodos,
currentItem,
updateItem
}}>
<div className="App">
<ToDoList />
<NewToDo />
</div>
</ApplicationContext.Provider>
);
}
export default App;
|
var app = angular.module('textSupport');
app.service('supportService', function($http){
this.postReply = function(message){
return $http({
method: 'POST',
url: 'http://localhost:8787/support/messages',
data: message
})
}
}); |
import { combineReducers } from 'redux';
import bubbleReducer from './bubble';
import marketReducer from './market';
import communitiesReducer from './communities';
export const rootReducer = combineReducers({
bubble: bubbleReducer,
market: marketReducer,
communities: communitiesReducer,
// tweetsReducer,
});
|
const mongo = require('mongoose');
const CacambaSchema = mongo.Schema({
cod_cacamba:{type:Number, required:true},
valor:{type:Number, required:true},
residuo:{type:String, required:true},
tamanho:{type:String, required:true},
});
module.exports = mongo.model('Cacamba', CacambaSchema, 'cacamba') |
// Copyright (c) 2016-2018, BuckyCloud, Inc. and other BDT contributors.
// The BDT project is supported by the GeekChain Foundation.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the BDT nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"use strict";
let BDTPackageSender = require('../../bdt/package').BDTPackageSender;
const originInit = BDTPackageSender.prototype.init;
const originPostPackage = BDTPackageSender.prototype.postPackage;
const originSockets = new Set();
function applyNat() {
let portMap = {};
BDTPackageSender.prototype.init = function() {
let socket = this.m_udpSocket;
let nat = portMap[socket.address().port];
if (!nat) {
nat = {};
portMap[socket.address().port] = nat;
}
if (!(originSockets.has(socket))) {
originSockets.add(socket);
socket.__originListeners = socket.listeners('message');
socket.removeAllListeners('message');
socket.on('message', (message, remote)=>{
if (nat[remote.port]) {
for (let listener of socket.__originListeners) {
listener(message, remote);
}
}
});
}
};
BDTPackageSender.prototype.postPackage = function(encoder) {
let nat = portMap[this.m_udpSocket.address().port];
if (!nat) {
nat = {};
portMap[this.m_udpSocket.address().port] = nat;
}
nat[this.m_remote.port] = true;
originPostPackage.call(this, encoder);
};
}
function applyDelay(delayFilter) {
const prePostPackage = BDTPackageSender.prototype.postPackage;
BDTPackageSender.prototype.postPackage = function(encoder) {
let delay = delayFilter(encoder);
if (delay) {
setTimeout(()=>{prePostPackage.call(this, encoder);}, delay);
} else {
prePostPackage.call(this, encoder);
}
};
}
function applyLoss(lossFilter) {
const prePostPackage = BDTPackageSender.prototype.postPackage;
BDTPackageSender.prototype.postPackage = function(encoder) {
if (!lossFilter(encoder)) {
prePostPackage.call(this, encoder);
}
};
}
function clear() {
BDTPackageSender.prototype.init = originInit;
BDTPackageSender.prototype.postPackage = originPostPackage;
for (let socket of originSockets) {
let originListeners = socket.__originListeners;
delete [socket.__originListeners];
socket.removeAllListeners('message');
for (let listener of originListeners) {
socket.addListener('message', listener);
}
}
originSockets.clear();
}
module.exports.applyNat = applyNat;
module.exports.applyDelay = applyDelay;
module.exports.applyLoss = applyLoss;
module.exports.clear = clear;
|
/* eslint-disable eol-last */
/* eslint-disable no-unused-vars */
/* eslint-disable indent */
'use strict';
// this fuction will ask the user to enter his name and will show the user's name in the welcome message.
function welcome(){
var name = prompt('Hello there! what\'s your name?');
var message = 'Welcome, '+name.toLocaleUpperCase();
return document.write('<h1>'+message+'</h1>');
}
var scrore = 0;
//this fuction will ask yes or no question to the user
function YesAndNoQuestion(){
alert('nswer the following question by yes,y or no,n');
var answer =prompt('I\'m under 26 years old');
answer = answer.toLowerCase();
var response;
if (answer === 'yes' || answer === 'y'){
response = 'that\'s correct!';
scrore++;
}else if( answer === 'no' || answer === 'n'){
response = 'I\'m actually 25 years old :(';
}else{
response = 'you did not answer that question preoprely please make sure to answer the next question by yes,y or no,n';
}
alert(response);
answer = prompt('I was born in Cameroon');
answer = answer.toLowerCase();
if (answer === 'yes' || answer === 'y'){
response='that\'s right! in central Africa';
scrore++;
}else if( answer === 'no' || answer === 'n'){
response='I actually was :( ';
}else{
response = 'you did not answer tht question preoprely please make sure to answer the next question by yes,y or no,n';
}
alert(response);
answer = prompt ('I\'m a single child');
answer = answer.toLowerCase();
if (answer === 'yes' || answer === 'y'){
response='come on man! I\'m Africain... I have 5 sublings';
}else if( answer === 'no' || answer === 'n'){
response='yep! you got it right! I have 5 sublings';
scrore++;
}else{
response = 'you did not answer tht question preoprely please make sure to answer the next question by yes,y or no,n';
}
alert(response);
answer=prompt('I have a pet');
answer = answer.toLowerCase();
if (answer === 'yes' || answer === 'y'){
response='you got it! his name is Symba!';
scrore++;
}else if( answer === 'no' || answer === 'n'){
response='you wrong!! ;)';
}else{
response = 'you did not answer tht question preoprely please make sure to answer the next question by yes,y or no,n';
}
alert(response);
answer=prompt('I\'m a Christian');
answer = answer.toLowerCase();
if (answer === 'yes' || answer === 'y'){
response='that\'s correct! I love Jesus :)';
scrore++;
}else if( answer === 'no' || answer === 'n'){
response='I am! born and raise ;)';
}else{
response = 'you did not answer that question preoprely but it\' fine you will get the chance to take a look at my web site';
}
alert(response);
}
function highLow(){
var question = Number(prompt('How many borthers I\'ve got?'));
var answer = 5;
var attempt = 1;
while(attempt < 4){
attempt++;
if(question < answer ){
alert('too low');
question = Number(prompt('How many borthers I\'ve got?'));
}else if(question > answer){
alert('too high');
question = Number(prompt('How many borthers I\'ve got?'));
}else {
attempt = 5;
alert('that\'s right!');
scrore++;
}
if(question !== answer && attempt === 4){
alert('5 is the right answer!');
}
}
}
function cities(){
var ArrayCities = ['seattle', 'san fransisco', 'new york','toulous'];
var question = prompt('what\'s one of my favorit cities?').toLowerCase();
var numtried = 1;
var attempt = 6;
while(numtried < attempt){
for(var i=0; i<ArrayCities.length ; i++){
if(question === ArrayCities[i]){
alert('yep! that\'s one of them');
scrore++;
numtried = attempt;
}
}
if(numtried !== attempt){
alert('that wasn\'t it');
question = prompt('what\'s one of my favorit cities?').toLowerCase();
numtried++;
}
if(question !== ArrayCities[i] && numtried === attempt){
var message ='';
for (var j =0 ; j<ArrayCities.length-1 ; j++){
message += ArrayCities[j]+', ';
}
message+= ArrayCities[ArrayCities.length-1]+'.';
alert('Here are all of the correct answer : '+message);
}
}
alert('out of all the question, you answer '+ scrore+' correctly');
} |
/* eslint-disable react-native/no-inline-styles */
import 'react-native-gesture-handler';
import React from 'react';
import {View} from 'react-native';
import AppNavigator from './src/navigation/AppNavigator';
import codePush from 'react-native-code-push';
import {Provider} from 'react-redux';
import store from './src/store/configStore';
const App = () => {
return (
<Provider store={store}>
<View style={{flex: 1}}>
<AppNavigator />
</View>
</Provider>
);
};
const codePushOptions = {
checkFrequency: codePush.CheckFrequency.ON_APP_START,
};
export default codePush(codePushOptions)(App);
|
import React from 'react';
const Select =({studentI,onInputChange,studentsData,classRoom})=>{
return (
<div className="selecte">
<label htmlFor={`student${studentI}`}>{`Student${studentI}`}</label>
<select
onChange={onInputChange}
name={`student${studentI}Id`}
defaultValue={classRoom[`student${studentI}Id`]?classRoom[`student${studentI}Id`]:"0"}
>
<option value="0" disabled={true}>
student
</option>
{studentsData.map((student) => {
return (
<option
key={student.id}
disabled={student.grade !== classRoom.grade}
value={student.id}
>
{`${student.firstName} ${student.lastName}`}
</option>
);
})}
</select>
</div>
);
}
export default Select; |
/**
* HOMER - Responsive Admin Theme
* Copyright 2015 Webapplayers.com
*
*/
(function () {
angular.module('homer', [
'ui.router', // Angular flexible routing
'ui.bootstrap', // AngularJS native directives for Bootstrap
'angular-flot', // Flot chart
'angles', // Chart.js
'angular-peity', // Peity (small) charts
'cgNotify', // Angular notify
'angles', // Angular ChartJS
'ngAnimate', // Angular animations
'ui.map', // Ui Map for Google maps
'ui.calendar', // UI Calendar
'summernote', // Summernote plugin
'ngGrid', // Angular ng Grid
'ui.select', // Angular ui-select
'vcRecaptcha' // Angular recaptcha
])
})();
|
/**
* @author Ignacio González Bullón - <nacho.gonzalez.bullon@gmail.com>
* @since 21/12/15.
*/
(function () {
'use strict';
angular.module('corestudioApp.admin')
.controller('PassTypeModalController', PassTypeModalController);
PassTypeModalController.$inject = ['$uibModalInstance', 'passType', 'Activity', '$scope'];
function PassTypeModalController($uibModalInstance, passType, Activity, $scope) {
var vm = this;
vm.dismiss = dismiss;
vm.savePassType = savePassType;
activate();
function activate() {
if(passType) {
vm.title = 'Editar tipo de abono';
vm.passType = passType;
} else {
vm.title = 'Nuevo tipo de abono';
vm.passType = {};
}
Activity.query({}, function (response) {
vm.activities = response.content;
if(vm.passType.activity) {
var index = -1;
for (var i = 0; i < vm.activities.length; i++) {
if(vm.activities[i].activity.id === vm.passType.activity.id) {
index = i;
break;
}
}
vm.passType.activity = vm.activities[index].activity;
}
});
}
function dismiss() {
$uibModalInstance.dismiss('CANCEL');
}
function savePassType() {
$scope.$broadcast('show-errors-check-validity');
if ($scope.passTypeForm.$valid) {
if(vm.passType.id) {
$uibModalInstance.close({action: 'UPDATE', passType: vm.passType});
} else {
$uibModalInstance.close({action: 'SAVE', passType: vm.passType});
}
}
}
}
})();
|
export const GRID_INIT = 'ACTION_GRID_INIT';
export const GRID_INSERT_SHAPE = 'ACTION_GRID_INSERT_SHAPE';
export const GRID_CLEAR = 'ACTION_GRID_CLEAR';
export const GRID_TOGGLE_CELL = 'ACTION_TOGGLE_CELL';
export const GRID_N_COLS = 50;
export const GRID_N_ROWS = 30;
export default {
GRID_INIT,
GRID_INSERT_SHAPE,
GRID_CLEAR,
GRID_TOGGLE_CELL,
};
|
$(document).ready(function() {
$('.feedback-love-num li').click(function () {
$('.feedback-love-num li').removeClass('acrive');
$(this).addClass('acrive');
})
}); |
import surveys from './surveyReducer'
import user from './userReducer'
import myInfo from './myInfoReducer'
import {combineReducers} from 'redux';
const rootReducer = combineReducers({
surveys,
user,
myInfo,
});
export default rootReducer; |
import React, { Component } from 'react'
import Loader from '../layout/Loader'
import axios from '../api/init'
import ReactTable from 'react-table'
import 'react-table/react-table.css'
import moment from 'moment'
const pdfLogo = require('../../img/pdf.png')
class AllSop extends Component {
state = {
sops: [],
loaded: false,
}
componentDidMount() {
axios.get('/sops/allforuser')
.then((response) => {
this.setState({
sops: response.data,
loaded: true
})
})
.catch((error)=>{
console.log(error);
})
}
render() {
if (!this.state.loaded) { return(<Loader/>)}
return (
<div>
<div className="solid-heading d-flex justify-content-between">All SOPs</div>
<ReactTable
data={this.state.sops}
columns={[
{
Header: "Title",
accessor: "title",
Cell: (data) => (
<a href={`${process.env.REACT_APP_BACKEND_URL}/sops/download/${data.original.awsPath}`} target="_blank" rel="noopener noreferrer"><span><img alt="pdf logo" src={pdfLogo} /> {data.value} </span></a>
)
},
{
Header: "Latest Version",
accessor: "version",
className: "table-center"
},
{
Header: "Department",
accessor: "department"
},
{
Header: "Author",
accessor: "author"
},
{
id: "createdAt",
Header: "Created",
accessor: d => {
return moment(d).format('DD MMM YYYY')
}
},
{
Header: "Read",
accessor: "read",
Cell: data => (
<span>{ data.value ? "Read" : "Not Read"}</span>
)
}
]}
className="-striped -highlight"
minRows={1}
filterable={true}
/>
</div>
)
}
}
export default AllSop |
import {MasteredSkill} from '../models';
import {ClientCurriculumCtrl} from '../controllers';
import APIError from '../lib/APIError';
import httpStatus from 'http-status';
import Constants from '../lib/constants';
import * as _ from 'lodash';
/**
* Load masteredSkill and append to req.
*/
function load(req, res, next, id) {
MasteredSkill.get(id)
.then((masteredSkill) => {
req.masteredSkill = masteredSkill;
return next();
})
.catch(e => next(e));
}
/**
* Get masteredSkill
* @returns {masteredSkill}
*/
function get(req, res) {
return req.masteredSkill;
}
let dateKeys = ['startDate', 'endDate'];
let clientCurriculumKeys = ['client'];
/**
* Checks if user exists with same email as masteredSkill. If not, it creates a new User with the email provided and a default password. Then creates the masteredSkill to reside in the new user
* @returns {masteredSkill}
*/
function create(req, res, next) {
//properties from the request still need to be filled out.
let query = {query:{client:req.body.client,curriculum:req.body.curriculum}};
return ClientCurriculumCtrl.list(query,res,next).then(clientCurriculums => {
if(clientCurriculums && clientCurriculums.length > 0){
let masteredSkill = {
curriculum: req.body.curriculum,
client: req.body.client,
skill: req.body.skill,
//start date is the date of the first clientCurriculum
started: clientCurriculums[0].createdAt,
numberOfTrials: clientCurriculums.length * parseInt(req.body.numberOfTrials)
};
return new MasteredSkill(masteredSkill)
.save()
.then(savedmasteredSkill => savedmasteredSkill)
.catch(e => next(e));
}else{
return next(new APIError(`There's been an issue trying to master this skill`, httpStatus.BAD_REQUEST, true));
}
})
.catch(e => next(e));
}
/**
* Update existing masteredSkill
* @returns {masteredSkill}
*/
function update(req, res, next) {
const masteredSkill = req.masteredSkill;
for(let prop in req.body){
masteredSkill[prop] = req.body[prop];
}
return masteredSkill.save()
.then(savedmasteredSkill => savedmasteredSkill)
.catch(e => next(e));
}
/**
* Get masteredSkill list.
* @property {number} req.query.skip - Number of masteredSkills to be skipped.
* @property {number} req.query.limit - Limit number of masteredSkills to be returned.
* @returns {masteredSkill[]}
*/
function list(req, res, next) {
const { limit = 20, skip = 0 } = req.query;
delete req.query.limit;
delete req.query.skip;
let queryArray = buildQueryObj(req);
// let queryObj = buildQuery(req);
return MasteredSkill.find(queryArray.length > 0 ? {$or: queryArray} : {})
.sort({ createdAt: -1 })
.populate({path:'skill', populate: {path:'targetType dttType'}})
.populate('client curriculum')
.skip(skip)
.limit(limit)
.then(masteredSkills => masteredSkills)
.catch(e => next(e));
}
function buildQueryObj(req){
if(Object.keys(req.query).length === 0)
return [];
let array = [];
for(let key in req.query){
if(_.indexOf(dateKeys, key) > -1){
if(key == 'startDate'){
array.push({createdAt: {$gt: req.query[key]}});
}
if(key == 'endDate')
array.push({createdAt: {$lt: req.query[key]}});
}
else{
let obj = {};
obj[key] = req.query[key];
array.push(obj);
}
}
return array;
}
function buildQuery(req){
if (Object.keys(req.query).length === 0) return [];
var array = [];
for (var key in req.query) {
// if (_.indexOf(dateKeys, key) > -1) {
// if (key == 'startDate') {
// array.push({ createdAt: { $gt: req.query[key] } });
// }
// if (key == 'endDate') array.push({ createdAt: { $lt: req.query[key] } });
// } else {
var obj = {};
obj[key] = req.query[key];
array.push(obj);
// }
}
return array;
}
/**
* Delete masteredSkill.
* @returns {masteredSkill}
*/
function remove(req, res, next) {
const masteredSkill = req.masteredSkill;
return masteredSkill.remove()
.then(deletedmasteredSkill => deletedmasteredSkill)
.catch(e => next(e));
}
export default { load, get, create, update, list, remove };
|
import React from "react";
import User from "../entity/User";
function TrUser(props) {
let { className } = props;
let { user } = props;
let { isChecked } = props;
let { onChange } = props;
if (user instanceof User) {
return (
<tr className={className}>
<td>
<input type="checkbox" onChange={onChange} checked={isChecked} />
</td>
<td>{user.id}</td>
<td>{user.name}</td>
<td>{user.email}</td>
<td>{user.dateRegistaration && user.dateRegistaration.toDateString()}</td>
<td>{user.dateLogin && user.dateLogin.toDateString()}</td>
<td>{user.status}</td>
</tr>
);
} else return <tr></tr>;
}
export default TrUser; |
const {ObjectID} = require('mongodb');
const {mongoose} = require('./../server/db/mongoose');
const {Todo} = require('./../server/models/Todo');
const {User} = require('./../server/models/User');
var id = '5a5cf16869bf7be02ef797eb';
var invalidId = '5a5cf16869bf7be02ef797eb11';
var userId = '5a5c07e546c103a018b66e2d';
var nonExistUserId = '6a5c07e546c103a018b66e2d';
var invalidUserId = '5a5c07e546c103a018b66e2d11';
User.findById(userId).then((user) => {
if (!user) {
return console.log('Ya shmucked up');
}
console.log(user);
}, (e) => {
console.log('There was an error!');
});
User.findById(nonExistUserId).then((user) => {
if (!user) {
return console.log('Ya shmucked up');
}
console.log(user);
}, (e) => {
console.log('There was an error!');
});
User.findById(invalidUserId).then((user) => {
if (!user) {
return console.log('Ya shmucked up');
}
console.log(user);
}, (e) => {
console.log('There was an error!');
});
// Todo.find({
// _id: id
// }).then((todos) => {
// console.log('Todos', todos);
// });
//
// Todo.findOne({
// _id: id
// }).then((todos) => {
// console.log('Todo', todos);
// });
//
// Todo.findById(id).then((todos) => {
// if (!todos) {
// return console.log('SHMUCK!');
// }
// console.log('Todo by ID', todos);
// });
//
// if (!ObjectID.isValid(invalidId)) {
// return console.log('Id not valid, shmass hole');
// };
//
// Todo.findById(invalidId).then((todos) => {
// if (!todos) {
// return console.log('SHMUCK!');
// }
// console.log('Todo by ID', todos);
// }).catch((e) => {
// console.log(e);
// });
|
import { filter, get } from 'lodash'
import { map } from 'lodash'
import { parseData } from '../lib/util'
import Azul from './azul'
import Avianca from './avianca'
import Gol from './gol'
import Latam from './latam'
import * as schema from './schema'
const sources = { Avianca, Azul, Gol, Latam }
export const findLowestFares = async (origin, destination, date) => {
const data = await parseData({ origin, destination, date }, schema.search)
const responses =
await Promise.all(map(sources, async ({ Api, Parser }, sourceName) => {
try {
const response =
await Api.search(data.origin, data.destination, data.date)
const lowestFare = Parser.getLowestFare(response)
return { sourceName, lowestFare }
} catch (err) {
return { sourceName, error: err.message }
}
}))
const validResponses = filter(responses, r => r.lowestFare)
const lowestFare = (validResponses.length === 0)
? -1
: validResponses.reduce((a, v) => Math.min(v.lowestFare, a), Infinity)
return { sources: responses, lowestFare }
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.