I'm trying to save only 2 items when persisting through redux-persist .
I'm perplexed why the following code won't work..
(it seems to save more than 2 items)
const myTransform = createTransform(
(inboundState, key) => {
let { openforum_threads } = inboundState
if (!openforum_threads) {
return inboundState
}
let { allIds } = openforum_threads
let STORE_NUM = 2
let storeIds = allIds.slice(0, STORE_NUM)
console.log('saving', storeIds)
let { byId } = openforum_threads
let storeById = {}
storeIds.map((id) => {
storeById[id] = byId[id]
})
openforum_threads = {
...openforum_threads,
allIds: storeIds,
byId: storeById
}
return { ...inboundState, openforum_threads}
},
(outboundState, key) => {
// convert mySet to an Array.
return outboundState
}
)
Related
We have a table with a large amount of data and I do not want to load it at once for my dxDataGrid.
I want to implement paging with Skip / Take which is supplied from the dxDataGrid's DataSourceLoadOptions.
This is my controller:
[HttpGet]
public async Task<Object> GetSalesOrdersWithTotals(DataSourceLoadOptions loadOptions)
{
try
{
var results = await SalesOrderService.GetSalesOrdersWithTotals(loadOptions.Skip, loadOptions.Take, 40);
loadOptions.Skip = 0;
loadOptions.Take = 0;
return DataSourceLoader.Load(results, loadOptions);
}
catch (Exception ex)
{
return Json(new { code = "422", success = false, message = "Unable to fetch sales orders with totals - " + ex.ToString() });
}
}
This is the service that returns the data:
public async Task<IEnumerable<SalesOrderWithTotals>> GetSalesOrdersWithTotals(int skip, int take, int defaultPageSize)
{
if (take == 0)
{
//Fix for passing a 0 take
take = defaultPageSize;
}
var salesOrderWithTotals =
from o in _context.SalesOrder
select new SalesOrderWithTotals
{
SalesOrderId = o.SalesOrderId,
Net = _context.SalesOrderItem.Where(it => it.SalesOrderId == o.SalesOrderId).Select(it => it.Qty == null ? 0 : it.Qty.Value * it.UnitPrice == null ? 0 : it.UnitPrice.Value).Sum(),
Tax = _context.SalesOrderItem.Where(it => it.SalesOrderId == o.SalesOrderId).Select(it => it.Qty == null ? 0 : it.Qty.Value * it.UnitPrice == null ? 0 : it.UnitPrice.Value).Sum() * (o.Tax.Percentage /100),
Gross = _context.SalesOrderItem.Where(it => it.SalesOrderId == o.SalesOrderId).Select(it => it.Qty == null ? 0 : it.Qty.Value * it.UnitPrice == null ? 0 : it.UnitPrice.Value).Sum() + _context.SalesOrderItem.Where(it => it.SalesOrderId == o.SalesOrderId).Select(it => it.Qty == null ? 0 : it.Qty.Value * it.UnitPrice == null ? 0 : it.UnitPrice.Value).Sum() * (o.Tax.Percentage / 100),
Name = o.Customer.Name,
CustomerOrderNumber = o.CustomerOrderNumber,
Contact = o.Contact,
OrderDate = o.OrderDate
};
return await salesOrderWithTotals.Skip(skip).Take(take).ToListAsync();
}
Looking at SQL profiler, this takes the first 40 records but of course the dxDataGrid is not aware of the total count of records so pagination is not available.
What would be the best method to achieve what I want in this case?
Many thanks
You must do an extra query to get the count of your SalesOrder and keep it in for example salesOrderCount. Then keep the Load method return data as bellow.
LoadResult result = DataSourceLoader.Load(results, loadOptions);
LoadResult has a parameter called totalCount so set it with the real count of your data:
result.totalCount = salesOrderCount;
and then
return result;
Now the dxDataGrid is aware of the total count of records.
In my application i want to open gmail attachment with my application, i used intent filter for that,
I am getting URI and i want to use that and copy that attachment to my local device and want to display that with my application .
url = {content://com.google.android.gm.sapi/abc#gmail.com/message_attachment_external/%23thread-f%3A1610966348228029097/%23msg-f%3A1610966348228029097/0.1?account_type=com.google&mimeType=application%2Foctet-stream&rendition=1}
After a days of research and implementation, Here is a final solution for gmail attachment file , to view and down load in our application.
[IntentFilter(new string[] { Intent.ActionView }, Categories = new string[] { Intent.CategoryDefault, Intent.CategoryBrowsable }, DataScheme = "content", DataMimeType = "application/octet-stream")]
Stream inputsTream = resolver.OpenInputStream(url);
fs = File.Create(fileName);
byte[] buffer = new byte[32768];
int count;
int offset = 0;
while ((count = inputsTream.Read(buffer, offset, buffer.Length)) > 0)
{
fs.Write(buffer, 0, count);
}
fs.Close();
inputsTream.Close();
private fun deepLinkAcceptor(){
var ins: InputStream? = null
var os: FileOutputStream? = null
var fullPath: String? = null
var file: File;
try {
val action = intent.action
if (Intent.ACTION_VIEW != action) {
return
}
val uri = intent.data
val scheme = uri!!.scheme
var name: String? = null
if (scheme == "content") {
val cursor = contentResolver.query(
uri!!, arrayOf(
MediaStore.MediaColumns.DISPLAY_NAME
), null, null, null
)
cursor!!.moveToFirst()
val nameIndex = cursor!!.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
if (nameIndex >= 0) {
name = cursor!!.getString(nameIndex)
}
} else {
return
}
if (name == null) {
return
}
val n = name.lastIndexOf(".")
val fileName: String
val fileExt: String
if (n == -1) {
return
} else {
fileName = name.substring(0, n)
fileExt = name.substring(n)
}
// create full path to where the file is to go, including name/ext
fullPath = ""
val filenm = fileName + fileExt
file = File(cacheDir, filenm)
ins = contentResolver.openInputStream(uri!!)
os = FileOutputStream(file.getPath())
val buffer = ByteArray(4096)
var count: Int
while (ins!!.read(buffer).also { count = it } > 0) {
os!!.write(buffer, 0, count)
}
os!!.close()
ins!!.close()
println("===onfile path: " + file.getAbsolutePath())
println("===onFile name: " + file.readText())
} catch (e: Exception) {
if (ins != null) {
try {
ins.close()
} catch (e1: Exception) {
}
}
if (os != null) {
try {
os.close()
} catch (e1: Exception) {
}
}
if (fullPath != null) {
val f = File(fullPath)
f.delete()
}
}
}
I have a method which has anonymous type and after it I add parameters to viewmodel.
public void ConvertirBono(List<Bono> ParamBonos,List<Empleado> ParamEmpleado)
{
Bonos = new List<BonoVM>();
var bonos2 = ParamBonos.Where(x => x.mdEstatusRegistro)
.Join(ParamEmpleado, x => x.EmpleadoID, y => y.ID, (x, y) => new
{
empleadoCompleto = y.nCodigoEmpleado.ToString() + y.vNombreEmpleado,
}).ToList();
foreach (var p in ParamBonos)
{
Bonos.Add(new BonoVM()
{
EmpleadoId = p.EmpleadoID,
vEmpleado = empleadoCompleto,
nBono1 = p.nBono1,
nBono2 = p.nBono2
});
}
}
What I want to do is to insert anonymous type empleadoCompleto when I add into ViewModel(foreach clause) but it always comes null. I try to declare that variable outside but it still comes null.
public void ConvertirBono(List<Bono> ParamBonos,List<Empleado> ParamEmpleado)
{
Bonos = new List<BonoVM>();
string empleadoCompleto = null;
var bonos2 = ParamBonos.Where(x => x.mdEstatusRegistro)
.Join(ParamEmpleado, x => x.EmpleadoID, y => y.ID, (x, y) => new
{
empleadoCompleto = y.nCodigoEmpleado.ToString() + y.vNombreEmpleado,
}).ToList();
foreach (var p in ParamBonos)
{
Bonos.Add(new BonoVM()
{
EmpleadoId = p.EmpleadoID,
vEmpleado = empleadoCompleto,
nBono1 = p.nBono1,
nBono2 = p.nBono2
});
}
}
What am I doing wrong?
From your code, it looks like all you are trying to do it merge the two list objects together and create a list of view models. There's no need to create anonymous types here at all, you can do it all with one line of code. This may not be quite right as your question is unclear, but it should at least get you on the right track.
public void ConvertirBono(List<Bono> ParamBonos,List<Empleado> ParamEmpleado)
{
Bonos = ParamBonos.Where(x => x.mdEstatusRegistro)
.Join(ParamEmpleado,
x => x.EmpleadoID,
y => y.ID,
(x, y) => new BonoVM
{
EmpleadoId = x.EmpleadoID,
vEmpleado = y.nCodigoEmpleado.ToString() + y.vNombreEmpleado,
nBono1 = x.nBono1,
nBono2 = x.nBono2
})
.ToList();
}
I am trying to figure find why my api is taking ~5 secs working on 1000 records,is that good or bad?I want to know what tools are there in asp.net webapi to figure out which piece of code or where its consuming time and fine tune the performance
CODE:-
List<LookaheadRunInfo> lookaheadRunsInfo = new List<LookaheadRunInfo>();
List<lookahead_run> lookaheadRunData = new List<lookahead_run>();
if (!filterCriteria.labeled)
{
lookaheadRunData = bitDB.lookahead_run.Where(x => x.lookahead_run_status == null && x.submission_time != null).OrderByDescending(x => x.submission_time).Skip(filterCriteria.PageNumber * filterCriteria.PageSize).Take(filterCriteria.PageSize).ToList();
}
else
{
lookaheadRunData = bitDB.lookahead_run.OrderByDescending(x => x.submission_time).Skip(filterCriteria.PageNumber * filterCriteria.PageSize).Take(filterCriteria.PageSize).ToList();
}
foreach (var lookaheadRunRow in lookaheadRunData)
{
var lookaheadRunInfo = new LookaheadRunInfo();
var lookaheadRunId = lookaheadRunRow.lookahead_run_id;
lookaheadRunInfo.ECJobLink = lookaheadRunRow.ec_job_link;
lookaheadRunInfo.UserSubmitted = lookaheadRunRow.submitted_by;
lookaheadRunInfo.SubmittedTime = lookaheadRunRow.submission_time.ToString();
lookaheadRunInfo.RunStatus = lookaheadRunRow.lookahead_run_status;
var completionTime = lookaheadRunRow.completion_time;
if (completionTime == null)
{
lookaheadRunInfo.ElapsedTime = (DateTime.UtcNow - lookaheadRunRow.submission_time).ToString();
}
else
{
lookaheadRunInfo.ElapsedTime = (lookaheadRunRow.completion_time - lookaheadRunRow.submission_time).ToString();
}
List<String> gerrits = new List<String>();
List<string> lookaheadRunChangeListIds = new List<string>();
if (!filterCriteria.labeled)
{
lookaheadRunChangeListIds = (from lrcl in bitDB.lookahead_run_change_list
join cl in bitDB.change_lists on lrcl.change_list_id equals cl.change_list_id
where lrcl.lookahead_run_id == lookaheadRunId
//and cl.change_list_id not in (select clcl.change_list_id from component_labels_change_lists as clcl)
//where !(from clcl in bitDB.component_labels_change_lists select clcl.change_list_id).Contains(cl.change_list_id)
where !bitDB.component_labels_change_lists.Any(clcl => clcl.change_list_id == cl.change_list_id)
select cl.change_list.ToString()).ToList();
}
else
{
lookaheadRunChangeListIds = (from lrcl in bitDB.lookahead_run_change_list
join cl in bitDB.change_lists on lrcl.change_list_id equals cl.change_list_id
where lrcl.lookahead_run_id == lookaheadRunId
select cl.change_list.ToString()).ToList();
}
//bitDB.Log = Console.Out;
//lookaheadRunInfo.gerrits = gerrits;
lookaheadRunInfo.gerrits = lookaheadRunChangeListIds;
if (lookaheadRunChangeListIds.Count != 0 && filterCriteria.labeled == false)
{
lookaheadRunsInfo.Add(lookaheadRunInfo);
}
else if (filterCriteria.labeled == true)
{
lookaheadRunsInfo.Add(lookaheadRunInfo);
}
}
return lookaheadRunsInfo;
I am using PHPExcel 1.8.0
I have read the posts regarding circular references, such as this one, but I am still running into issues.
If a spreadsheet contains one circular ref. formula, PHPExcel's calculations do not match MS Excel.
If a spreadsheet contains more than one circular ref, then PHPExcel goes into an infinite loop.
Here are the details of what I've done so far.
Assume a spreadsheet where A1 = B1 and B1 = A1+1, and Excel is set to 100 iterations. Here is my code:
// create reader
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true);
// load workbook
$objPHPExcel = $objReader->load($this->_path);
// set iterative calculations max count
PHPExcel_Calculation::getInstance($objPHPExcel)->cyclicFormulaCount = 100;
// calculate
$objWorksheet = $objPHPExcel->getSheetByName('Testing');
$data = $objWorksheet->rangeToArray('A1:B1');
echo '<pre>';
print_r ($data);
echo '</pre>';
// release resources
$objPHPExcel->disconnectWorksheets();
unset($objPHPExcel);
MSExcel results in A1 = 99, B1 = 100. My code produces this:
Array
(
[0] => Array
(
[0] => #VALUE!
[1] => #VALUE!
)
)
Further to that, if I add A2 = B2 and B2 = A2+1, and attempt to calculate (A1:B2), it goes into an infinite loop and eventually crashes:
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 24 bytes) in C:\xampp\htdocs\cgc\bulldog\application\third_party\PHPExcel\Calculation.php on line 2837
Here is what I've done so far. In _calculateFormulaValue in Calculation.php:
Line 2383: $cellValue = ''; - this is the cause of the #Value! error. I changed that to $cellValue = 0;
Line 2400:
} elseif ($this->_cyclicFormulaCell == '') {
$this->_cyclicFormulaCell = $wsTitle.'!'.$cellID;
This is the cause of the infinite loop. $this->_cyclicFormulaCell does not get re-set to '' after the formula in row 1 is done, so this condition does not work for the formula in row 2.
I fixed this as follows, starting from Line 2389:
if (($wsTitle{0} !== "\x00") && ($this->_cyclicReferenceStack->onStack($wsTitle.'!'.$cellID))) {
if ($this->cyclicFormulaCount <= 0) {
return $this->_raiseFormulaError('Cyclic Reference in Formula');
} elseif (($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) &&
($this->_cyclicFormulaCell == $wsTitle.'!'.$cellID)) {
// Olga - reset for next formula
$this->_cyclicFormulaCell = '';
return $cellValue;
} elseif ($this->_cyclicFormulaCell == $wsTitle.'!'.$cellID) {
++$this->_cyclicFormulaCount;
if ($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) {
// Olga - reset for next formula
$this->_cyclicFormulaCell = '';
return $cellValue;
}
} elseif ($this->_cyclicFormulaCell == '') {
$this->_cyclicFormulaCell = $wsTitle.'!'.$cellID;
if ($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) {
// Olga - reset for next formula
$this->_cyclicFormulaCell = '';
return $cellValue;
}
}
After these fixes, if I run $data = $objWorksheet->rangeToArray('A1:B2');, I get the following result:
Array
(
[0] => Array
(
[0] => 100 // should be 99
[1] => 100
)
[1] => Array
(
[0] => 100 // should be 99
[1] => 100
)
)
As you can see, the results from PHPExcel are not consistent with MS Excel. Why is this happening and how can I get around this?
Ok, I managed to debug this. My spreadsheet was very complicated, lots of circular refs. The most challenging is a scenario where A depends on B, B depends on both A and C, and C depends on B.
I also added a maxChange parameter, so the thing works like Excel. Otherwise it takes too long on my spreadsheet.
Anyway, here is a usage example:
$objPHPExcel = PHPExcel_IOFactory::load($path);
$objCalc = PHPExcel_Calculation::getInstance($objPHPExcel);
$objCalc->cyclicFormulaCount = 100;
$objCalc->maxChange = 0.001;
The two files that were modified are: Calculation.php and CalcEngine/CyclicReferenceStack.php
Here is the code (sorry Mark, I can't afford more time to submit it to git properly).
Calculation.php
add these to class properties:
private $_precedentsStack = array();
public $maxChange = 0;
replace _calculateFormulaValue() function with this:
public function _calculateFormulaValue($formula, $cellID=null, PHPExcel_Cell $pCell = null) {
$this->_debugLog->writeDebugLog("BREAKPOINT: _calculateFormulaValue for $cellID");
// Basic validation that this is indeed a formula
// We simply return the cell value if not
$formula = trim($formula);
if ($formula{0} != '=') return self::_wrapResult($formula);
$formula = ltrim(substr($formula,1));
if (!isset($formula{0})) return self::_wrapResult($formula);
// initialize values
$pCellParent = ($pCell !== NULL) ? $pCell->getWorksheet() : NULL;
$wsTitle = ($pCellParent !== NULL) ? $pCellParent->getTitle() : "\x00Wrk";
$key = $wsTitle.'!'.$cellID;
$data = array(
'i' => 0, // incremented when the entire stack has been calculated
'j' => 0, // flags the formula as having been calculated; can only be 0 or 1
'cellValue' => $pCell->getOldCalculatedValue(), // default value to start with
'precedents' => array(),
'holdValue' => FALSE // set to TRUE when change in value is less then maxChange
);
// add this as precedent
$this->_precedentsStack[] = $key;
// if already been calculated, return cached value
if (($cellID !== NULL) && ( $this->getValueFromCache($wsTitle, $cellID, $cellValue))) {
return $cellValue;
}
$this->_cyclicReferenceStack->getValueByKey($key, $data);
extract($data);
$this->_debugLog->writeDebugLog("iteration # $i");
// if already calculated in this iteration, return the temp cached value
if ($i >= $this->cyclicFormulaCount || $j == 1) {
return $cellValue;
}
// on stack, but has not yet been calculated => return default value
if (($wsTitle{0} !== "\x00") && ($this->_cyclicReferenceStack->onStack($key))) {
if ($this->cyclicFormulaCount <= 0) {
return $this->_raiseFormulaError('Cyclic Reference in Formula');
}
return $cellValue;
}
// calculate value recursively
$this->_cyclicReferenceStack->push($key);
$cellValue = $this->_processTokenStack($this->_parseFormula($formula, $pCell), $cellID, $pCell);
$this->_cyclicReferenceStack->pop();
// everything in precedent stack after the current cell is a precedent
// and every precedent's precedent is a precedent (aka a mouthfull)
while ( $this->_precedentsStack[ count($this->_precedentsStack) - 1 ] != $key ){
$data['precedents'][] = array_pop($this->_precedentsStack);
}
$data['precedents'] = array_unique($data['precedents']);
// check for max change
$oldValue = $this->_extractResult($data['cellValue']);
$newValue = $this->_extractResult($cellValue);
$data['cellValue'] = $cellValue;
$data['holdValue'] = (abs($oldValue - $newValue) < $this->maxChange);
// flag as calculated and save to temp storage
$data['j'] = 1;
$this->_cyclicReferenceStack->setValueByKey($key, $data);
// if this cell is a precedent, trigger a re-calculate
$tempCache = $this->_cyclicReferenceStack->showValues();
foreach ($tempCache as $tempKey => $tempData) {
if ( $tempData['holdValue'] == TRUE && ( in_array($key, $tempData['precedents'])) ) {
$tempData['holdValue'] = FALSE;
}
$this->_cyclicReferenceStack->setValueByKey($tempKey, $tempData);
}
// at the end of the stack, increment the counter and flag formulas for re-calculation
if (count($this->_cyclicReferenceStack->showStack()) == 0) {
$i++;
$this->_precedentsStack = array();
$tempCache = $this->_cyclicReferenceStack->showValues();
foreach ($tempCache as $tempKey => $tempData) {
$tempData['i'] = $i;
if ( ! $tempData['holdValue'] ) $tempData['j'] = 0;
$this->_cyclicReferenceStack->setValueByKey($tempKey, $tempData);
}
$this->_debugLog->writeDebugLog("iteration # $i-1 finished");
}
if ($i < $this->cyclicFormulaCount) {
$cellValue = $this->_calculateFormulaValue($pCell->getValue(), $cellID, $pCell);
} elseif ($cellID !== NULL) {
// all done: move value from temp storage to cache
$this->saveValueToCache($wsTitle, $cellID, $cellValue);
$this->_cyclicReferenceStack->removeValueByKey($key);
}
// Return the calculated value
return $cellValue;
} // function _calculateFormulaValue()
add this helper function:
private function _extractResult($result) {
if (is_array($result)) {
while (is_array($result)) {
$result = array_pop($result);
}
}
return $result;
}
CyclicReferenceStack.php
add a property:
private $_values = array();
add a bunch of functions:
public function setValueByKey($key, $value) {
$this->_values[$key] = $value;
}
public function getValueByKey($key, &$value) {
if (isset($this->_values[$key])) {
$value = $this->_values[$key];
return true;
}
return false;
}
public function removeValueByKey($key) {
if (isset($this->_values[$key])) {
unset($this->_values[$key]);
}
}
public function showValues() {
return $this->_values;
}