text:
Q: Problema al unir chunks con PHP Tengo un problema, y es que al subir un archivo pesado a un input type="file", lo divido en chunks de 1MB y los mando al PHP, eso funciona correctamente.
El problema viene al tratar de unirlos, que no se hace. Se queda el archivo de pruebas que tengo (es de 7MB) en 7 trozos, y debería poderse unir todos en uno solo.
Aquí tengo el código que conseguí copiar de otra respuesta, con un par de modificaciones para que pueda funcionar (antes no leía y escribía contenido), pero no lo junta:
<?php

$target_path = 'archivos_aaron_pruebas/';
$tmp_name = $_FILES['file1']['tmp_name'];
$size = $_FILES['file1']['size'];
$name = $_FILES['file1']['name'];
$sports = $_GET['file'];
$part =(string)$_GET['num'];
//$part = split("/\=/", $part);
$target_file = $target_path .$part. $sports;

// Open temp file
$out = fopen($target_file, "w");

if ( $out ) {
    // Read binary input stream and append it to temp file
    $in = fopen($tmp_name, "r");
    if ( $in ) {
        while ( $buff = fread( $in, 1048576 ) ) {
            fwrite($out, $buff);
        }
    }
    fclose($in);
    fclose($out);
}

?>

A: Ya lo solucioné!
<?php
session_start();

$message = '';

$target_path = 'archivos_aaron_pruebas/';
$tmp_name = $_FILES['file1']['tmp_name'];
$size = $_FILES['file1']['size'];
$name = $_FILES['file1']['name'];
$fileType = $_FILES['file1']['type'];
$num = $_POST['num'];
$num_chunks = $_POST['chunks'];
$namae = $_POST['namae'];

move_uploaded_file($tmp_name, $target_path.$num.$name);

// count ammount of uploaded chunks
$chunksUploaded = 0;
for($i = 0; $i <= $num_chunks; $i++){
    if(file_exists($target_path.$i.$name)){
        ++$chunksUploaded;
    }
}

//avengers...
if($chunksUploaded == $num_chunks){

    //reassemble
    for($i = 0;$i <= $num_chunks; $i++){
        $file = fopen($target_path.$i.$name, 'rb');
        $buff = fread($file, 1048576);
        fclose($file);

        $final = fopen($target_path.$namae, 'ab');
        $write = fwrite($final, $buff);
        fclose($final);

        unlink($target_path.$i.$name);
    }
}
?>

Con este PHP consigo unir todos los chunks del file que suba al formulario, dentro de este lo que hago es subir cada chunk con un su numero correspondiente, en el PHP leerlos de forma binaria, y meter su contenido en un archivo nuevo llamado exactamente igual al original y después borrar todos los chunks con numero en su nombre:
function uploadFile(chunkFile, part, x, charged){
  //se ejecuta tantas veces esté dividido el archivo
  let xhr = new XMLHttpRequest();
  let fd = new FormData();
  let chunks = Math.max(Math.ceil(x.size / BYTES_PER_CHUNK), 1);
  //let bar = txt.getElementsByClassName('progressBar')[0];

  /*xhr.upload.addEventListener("progress",(event)=>{uploadProgress(event, bar, x, charged)}, false);
  xhr.addEventListener("error", uploadFailed, false);
  xhr.addEventListener("abort", uploadCanceled, false);*/

  fd.append("file1", chunkFile);//con esto consigo el blob
  fd.append("num", part);//el numero de la parte que corresponde
  fd.append("chunks", chunks);//el numero de chunks que hay
  fd.append("namae", x.name);//con esto consigo el nombre del archivo completo

  xhr.open("POST", "upload.php", true);
  xhr.send(fd);
}


text:
Q: Wordpress: Insert post id on publishing I am trying to insert post id on publish to custom table but it is not adding correct id but 0
here is my function
//get post id on publish
function get_publishing_id($post_id) {
  $post= get_post($post_id);
  if ($post->post_type == 'post'
      && $post->post_status == 'publish') {

        // insert data on publish
        global $wpdb;
        $wpdb->insert(
            $wpdb->prefix.'banner_views',
            array(
                'postid' => $post,
                'view_count' => 12,
            )
        );

  } // end if
} // end function
add_action('save_post','get_publishing_id');

Please help to solve this. Thanks a lot...

A: It's solved.
The mistake was not passing ID with $post like $post->ID
//get post id on publish
function get_publishing_id($post_id) {
  $post= get_post($post_id);
  if ($post->post_type == 'post'
      && $post->post_status == 'publish') {

        // insert data on publish
        global $wpdb;
        $wpdb->insert(
            $wpdb->prefix.'banner_views',
            array(
                'postid' => $post->ID,// here was the mistake
                'view_count' => 12,
            )
        );

  } // end if
} // end function
add_action('save_post','get_publishing_id');

So above code works for me.
Thanks a lot

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does including a scaler in sklearn's Pipeline scale the target variable? When using a scaling function in  sklearn's Pipeline utility, is the scalar applied to the target variable during training and prediction?
In other words, is my code below, which makes use of TransformedTargetRegressor redundant to the pipeline?
cowboy = Lasso(max_iter=10000, tol=.005)
climber = Ridge()
gymshorts = ElasticNet()
scaler = pre.RobustScaler()

models = [('xgb', xgb.XGBRegressor(**best_params)),
          ('ridge', make_pipeline(scaler, TransformedTargetRegressor(climber, scaler))),
          ('lasso', make_pipeline(scaler, TransformedTargetRegressor(cowboy, scaler))),
          ('enet', make_pipeline(scaler, TransformedTargetRegressor(gymshorts, scaler)))]

stack = ensemble.StackingRegressor(estimators=models)
stack = stack.fit(x_train, y_train)

A: In sklearn's Pipeline, the scaler isn't applied to the target. Only independent varibales (aka features) get scaled.
Thus, the use of TransformedTargetRegressor in your code is not redundant.


text:
Q: Information gained from stream of correlated, normally-distributed symbols through a noisy channel I have the following problem:
I want to transmit a certain amount of information through a channel with Gaussian noise (random variable Z). The input distribution is likewise Gaussian (random variable X) such that (here, for the first symbol) I get Y_1 = X_1 + Z_1. The information gained through observing the first symbol is the mutual information of X_1 and Y_1 which is I(X_1;Y_1) = h(Y) - h(Z), where h is the differential entropy of the Gaussian distributions which is h = ln(σ √2πe).
Now the complication:
The following symbols (from the same distribution X) are correlated with each other with a known fixed (Pearson's) correlation ρ between neighboring symbols X_i and X_(i+1). The correlation between symbols further apart in the stream decreases accordingly.
Obviously, the information gained from observing the second, third, etc. symbol is smaller than that obtained from observing the first symbol. But how much is it?
I know that the mutual information between two consecutive (sent) symbols would be I = -0.5 ln(1-ρ), but that doesn't quite cut it.
Thank you very much for your help.


text:
Q: Can some one help me create a trigger for auto creating 5 child records when parent record stage is closed Hi I tired creating below trigger but it is giving me this error:

Loop variable must be of type CSM_Milestone__c

trigger CSMMilestone on CSM_Milestone__c (After insert, After update) {

     List<Opportunity> oppList = [select Id from Opportunity where StageName = 'Closed: Won'];

     list<CSM_Milestone__c> csmList = new list<CSM_Milestone__c>();
     for(Opportunity o : trigger.new)
     {
        CSM_Milestone__c csm = new CSM_Milestone__c ();
       // quote.Opportunity = o.id;
        csm.Name = 'CSM Milestone1';
        csmList.add(csm);
        if (o.StageName == 'Closed: Won'){
           for(Opportunity act: oppList){
              csm = new CSM_Milestone__c(Name='testName');
             // quote.Opportunity__c = o.Id;
              csmList.add(csm);
           }
        }
     }
     insert csmList;
}

A: This is sample code to create object in opportunity. In for loop you can give your logic to create your records same like opportunity
trigger CSMMilestone on Opportunity(After insert, After update) {

list<Opportunity> csmList = new list<Opportunity>();
 for(Opportunity o : trigger.new)
 {
    // if you want to create record in opportunity
    if (o.StageName == 'Closed: Won'){
    Opportunity csm = new Opportunity();
     csm.Name = 'CSM Milestone1';
    csmList.add(csm);
    }
 }
 insert csmList;
 }


text:
Q: Redirect every page to correct page My fist website was made on extension .be
Now my new website is on extension .com
When building my new website I've made sure that all the page names where the same as on my old site.
My old site has a pretty good listing on Google. But all the links on Google are pointing to my .be but as I deleted my site on .be I get all error 404.
I know how to redirect my homepage. But how do I redirect the other pages?
<?php
header( "Status: 301 Moved Permanently" );
header( "Location: https://www.example.com" );
exit(0);
?>

A: Friend
You can use .htaccess for redirect on particular page OR URL
Reference site: http://www.rapidtables.com/web/dev/htaccess-redirect.htm


text:
Q: How can I average two orthogonal spaces and retain orthonormality? Lets assume we have two "spaces" each characterised by a set of orthogonal basis functions. How can one "average" the spaces. That is to say find a third space, which is also orthogonal. I have considered the following:
vector space one with two basis.
$V^1_1, V^1_2$
These are orthonormal:
$V^1_1\cdot V^1_1 = 1$
$V^1_2\cdot V^1_2 = 1$
$V^1_2\cdot V^1_1 = V^1_1\cdot V^1_2 = 0$
We also consider a second vector space
$V^2_1, V^2_2$
These are orthonormal:
$V^2_1\cdot V^2_1 = 1$
$V^2_2\cdot V^2_2 = 1$
$V^2_2\cdot V^2_1 = V^2_1V^2_2 = 0$
Let us attempt to take the average of these vectors:
$V^3_1 = {1\over2}\left(V^1_1+V^2_1\right)$
$V^3_2 = {1\over2}\left(V^1_2+V^2_2\right)$
Then we consider the dot products of this new space:
$
\begin{align}
V^3_1 \cdot V^3_1 & = {1\over2}\left(V^1_1+V^2_1\right) \cdot {1\over2}\left(V^1_1+V^2_1\right) \\
& = {1\over4} \left( V^1_1 \cdot V^1_1 + V^2_1 \cdot V^2_1 + V^1_1 \cdot V^2_1 + V^2_1  \cdot  V^1_1\right) \\
& = {1\over2} \left(1+\text{cos}\theta_{V^2_1,V^1_1}\right) \\
\end{align}
$
By using the above orthogonalities and the cosine angle rule. Now to retain orthogonality one could weight $V^3_1$ by the square root of this. Next consider
$
\begin{align}
V^3_1 \cdot V^3_2 & = {1\over2}\left(V^1_1+V^2_1\right) \cdot {1\over2}\left(V^1_2+V^2_2\right) \\
& = {1\over4} \left( V^1_1 \cdot V^1_2 + V^2_1 \cdot V^2_2 + V^1_1 \cdot V^2_2 + V^2_1  \cdot  V^1_2\right) \\
& = {1\over4} \left( \text{cos}\theta_{V^2_1,V^1_2}+\text{cos}\theta_{V^1_1,V^2_2}\right) \\
\end{align}
$
This is however not zero unless $\theta_{V^2_1,V^1_2} = - \theta_{V^1_1,V^2_2}$. So how can I average two orthogonal spaces and retain orthonormality?


text:
Q: Load data into datatable where I don't know the columns I am creating a datatable by fetching data from database using AJAX response.
I am getting the following JSON data:
[
    {
        "id": "11105",
        "name": "Gummy Drop (iPhone, Free, ROW except CN, 72.3MB, w"
    },
    {
        "id": "11107",
        "name": "Gummy Drop (iPad, Free, ROW except CN, 72.3MB, w/ "
    },
    {
        "id": "4274",
        "name": "Z-Redirect Non-Targeted Traffic Dragon City Mobile"
    },
    {
        "id": "6484",
        "name": "Z-Redirect Non-Targeted Traffic Dragon City Mobile"
    }
]

The issue is, I may not know what data will be coming from AJAX response.
So I am extracting the keys of the JSON array so as to create the header, in which I am successful in doing so.
Here is my code:
$('#load').click(function()
    {
        var v = $('#drp_v').val();
        var cnt = $('#drp_cnt').val();
        var ctg = $('#drp_ctg').val();
        alert("version :"+v+" category :"+ctg+" country :"+cnt);
        $.post("ajax.php",{'version':v,'category':ctg,'country':cnt,'func':'show_datatable'},
                        function(data)
                        {
                            var aColumns = [];
                            var columns = [];
                            for(var i = 0; i < data.length; i++)
                            {
                                if(i>0)
                                    break;
                                keycolumns = Object.keys(data[i]);
                                for(j = 0; j < keycolumns.length; j++)
                                {
                                    alert(keycolumns[j]);
                                    if($.inArray(keycolumns[j],aColumns.sTitle)<=0)
                                    {
                                        aColumns.push({sTitle: keycolumns[j]}) //Checks if
                                        columns.push(keycolumns[j]) //Checks if
                                    }
                                }

                            }

                            var oTable = $('#jsontable').dataTable({
                                "columns":aColumns,
                                "sDom": 'T<"clear">lfrtip',
                                    "oTableTools": {
                                        "aButtons": [
                                            {
                                                    "sExtends": "csv",
                                                    "sButtonText": "CSV",
                                             }
                                        ]
                                    }
                            });
                            oTable.fnClearTable();
                            for(var i = 0; i < data.length; i++)
                            {
                                for(var c = 0; c < columns.length; c++)
                                {
                                    oTable.fnAddData([
                                            data[i].columns[c]]);
                                }
                            }
                        },'json');
    });

As you can see, var columns = []; actually contains the key of the JSON array I am getting. So the value of var columns is like this:
['id','name','description'];
So if we assume that id, name and description are three keys, then instead of using this code:
for(var i = 0; i < data.length; i++)
 {
    oTable.fnAddData([
                      data[i].id,
                      data[i].name,
                      data[i].description]);
}

I have used this code
for(var i = 0; i < data.length; i++)
 {
   for(var c = 0; c < columns.length; c++)
    {
        oTable.fnAddData([
                          data[i].columns[c]]);
    }
}

so that the data can be loaded as dynamic key values that are stored in var columns.
But I think I made some mistake. Where have I gone wrong?

A: Use this code :
var row = []
for(var i = 0; i < data.length; i++) {
    for(var c = 0; c < columns.length; c++) {
            row.push( data[i][columns[c]] ) ;
    }
    oTable.fnAddData(row);
    row = [];
}

A: It should be "data[i][columns[c]]", not "data[i].columns[c]".


text:
Q: laravel edit form checkbox values old input How do you use old('') for checkbox values. The problem with the code below is that it always is true and checked because of $baby_registry->reminder_email is true. So when you post the form without the checkbox being checked how do you test it in code if it's not there in the post request
@php
    $reminder_email = old('reminder_email', $baby_registry->reminder_email);
@endphp

<input type="checkbox" name="reminder_email" id="reminder_email" {{ $reminder_email ? 'checked' : '' }}>

I ended up having to do this for the code
@if($errors->any() && old('reminder_email') == 'on')
    <input type="checkbox" name="reminder_email" id="reminder_email" checked>
@elseif($errors->any() && !old('reminder_email'))
    <input type="checkbox" name="reminder_email" id="reminder_email">
@else
    <input type="checkbox" name="reminder_email" id="reminder_email" {{ $baby_registry->reminder_email ? 'checked' : false }}>
@endif

A: You can try this.
But I am not sure about what it is sending as there is no value attribute
<input type="checkbox" name="reminder_email" id="reminder_email" @if(old('reminder_email', $baby_registry->reminder_email))checked @endif >

A: Have you tried
@if(isset($reminder_email))
<input type="checkbox" name="reminder_email" id="reminder_email" checked>
@endif

A: Try This:
<input type="checkbox" name="reminder_email" id="reminder_email" value='1' {{ old('reminder_email', $baby_registry->reminder_email)? 'checked="checked"':null }}>

A: Check boxes inputs are not present in the $_POST global if they were not checked.
So i'll suggest you try this:
<input type="checkbox" name="reminder_email" id="reminder_email" {{ !$reminder_email ? "" : "checked" }} />


text:
Q: query explain output I have a table with many rows. And some queries are slow, they use indexes but the queries still cost a lot of time, how can I optimize these queries?
Cluster, temporary table ... ?
CREATE TABLE `fn_movim_finan` (
  `id` decimal(20,4) NOT NULL,
  `id_receber` decimal(15,4) DEFAULT NULL,
  `id_receberx` int(11) DEFAULT NULL,
  `documento` varchar(30) DEFAULT NULL,
  `data` date DEFAULT NULL,
  `pdesconto` decimal(5,2) DEFAULT NULL,
  `vdesconto` decimal(15,2) DEFAULT NULL,
  `pacrescimo` decimal(5,2) DEFAULT NULL,
  `vacrescimo` decimal(15,2) DEFAULT NULL,
  `credito` decimal(15,2) DEFAULT NULL,
  `historico` varchar(200) DEFAULT NULL,
  `id_movim_finan` decimal(15,4) DEFAULT NULL,
  `tipo_lanc` enum('M','P','R','D','C','AC','AF','T') DEFAULT NULL,
  `filial_id` int(11) DEFAULT NULL,
  `ultima_atualizacao` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `id_franquia_fn_movim_finam` varchar(30) DEFAULT NULL,
  `idx` bigint(20) DEFAULT NULL,
  `debito` decimal(15,2) DEFAULT NULL,
  `data_recebimento` date DEFAULT NULL,
  `id_conta` decimal(15,4) DEFAULT NULL,
  `id_automatico` int(11) NOT NULL AUTO_INCREMENT,
  `ultima_atualizacao_original` datetime DEFAULT NULL,
  `conciliado` enum('S','N') DEFAULT NULL,
  `conciliado_extrato` text,
  `conciliado_fn` mediumtext,
  `conta_` int(11) DEFAULT NULL,
  `id_fornecedor` int(11) DEFAULT NULL,
  `chave_recebimento_unico` varchar(70) DEFAULT NULL,
  `id_renegociacao` int(11) DEFAULT NULL,
  `id_movim_cheque` int(11) DEFAULT NULL,
  `id_operador` int(11) DEFAULT NULL,
  `id_ajuste_estoque` int(11) DEFAULT NULL,
  `id_motivo_desconto` int(11) DEFAULT NULL,
  `id_lote_retorno` int(11) DEFAULT NULL,
  `id_classe_financeira` int(11) DEFAULT NULL,
  `id_conta_class_finan_a` int(11) DEFAULT NULL,
  `id_conciliacao_lote` int(11) DEFAULT NULL,
  `id_grade_contabil` int(11) DEFAULT NULL,
  `cancelamento` varchar(1) DEFAULT NULL,
  `id_movimento_produto_comodato` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `id_receber` (`id_receber`),
  KEY `idx` (`idx`),
  KEY `ultima_atualizacao` (`ultima_atualizacao`),
  KEY `id_automatico` (`id_automatico`),
  KEY `ultima_atualizacao_original`
(`ultima_atualizacao_original`),
  KEY `filial_id` (`filial_id`),
  KEY `tipo_lan_data` (`tipo_lanc`,`data`),
  KEY `filial_idx` (`filial_id`,`idx`)
) ENGINE=InnoDB AUTO_INCREMENT=44539365 DEFAULT
CHARSET=latin1;

average row size: 550 bytes
number rows: 25.833.188
Query:
SELECT filial_id,
data,
YEAR(data) as ano,
MONTH(data) as mes,
IFNULL(sum(fn_movim_finan.vacrescimo -
fn_movim_finan.vdesconto), 0) as diferenca,
IFNULL(sum(fn_movim_finan.vacrescimo), 0) as acrescimo,
IFNULL(sum(fn_movim_finan.vdesconto), 0) as desconto
FROM fn_movim_finan
WHERE tipo_lanc = 'R'
AND data >= '2021-11-01' AND data <= '2022-10-31'
GROUP BY filial_id, ano, mes
ORDER BY filial_id ASC, data ASC;

runtime:1 minute
Explain output

A: (tipo_lanc,data) is a good index.  However, since the WHERE may be fetching most of the table, the index may not be used.  It is using that index.  The key_len=2 is deceptive; it is probably actually using both columns.  If the resultset really has 6M rows, then 1 minute is rather fast.
This one suggestion may speed up things.  Making the GROUP BY and ORDER BY compatible will eliminate a sort (of 6M rows):
GROUP BY  filial_id,     ano,     mes
ORDER BY  filial_id ASC, ano ASC, mes ASC

If I understand your query and the Spanish(?) words, changing ORDER BY will get exactly the same result.
Consider
      AND  data >= '2021-11-01'
      AND  data <= '2022-10-31'

-->
      AND  data >= '2021-11-01'
      AND  data  < '2021-11-01' + INTERVAL 1 YEAR

That will avoid computing leap days, etc.
26M rows in the table?  How many rows in the resultset?  How much RAM do you have?  What is the value of innodb_buffer_pool_size?  (There could be an issue here.)
More (based on Comment, below)

*

*Fetching 2.9M rows based on the index will take most of the time.

*Doing the SUM will take some time.

*The ORDER BY for the final 1K row at the end will take very little time.  (My suggestion of making GROUP BY and ORDER BY the same won't have much effect.)

The buffer_pool is big enough that running the query a second time may run faster.  (But that is probably a small consolation.)
There is no good solution for this type of query on this type of table.
If queries like this are common, then building and maintaining a Summary Table may be the best solution.  It would have subtotals for each tipo_lanc for each day.  Then summing the sums and further grouping and ordering will run much faster -- perhaps 5 to 10 times as fast.


text:
Q: Redirect not working for me I have the following line in my IsapiRewrite.ini file:
RewriteRule ^/test-url.asp$  http://www.google.co.uk/ [R=301,L]

But it doesn't do anything...
However, this DOES work:
RewriteRule ^/test-url.asp$  /

Is it a case of enabling Redirect or something like that? I would have thought that if the IsapiRewrite4.dll is running, the redirect would work?
Please can someone advise?

A: Try this (slightly modified to be case insensitive):
RewriteRule ^/test-url.asp$  http\://www\.google\.co\.uk/ [I, R=301,L]

A: Turns out to be the documentation on the Isapi Readme...
To do redirect, its not "RewriteRule", but instead "RedirectRule"... just tried it by chance. Ended up working. However, the above suggestions do work on .htaccess Linux servers.
Thanks guys.


text:
Q: why modifying *.cc files in ns2 isn't having any change after running 'make' command I have changed the RTT calculation in tcp.cc file in ns2-allinone > ns2.35 > tcp folder.
Then I have run the command 'make clean' and then ran 'make'
at this time while running the simulator, it will work with the updated it doesn't show any change.
I've again tried debugging with adding a printf() statement. But after doing make clean and then make the modification doesn't work when I run ns.

A: I found the solution.
I wrote in linux terminal, "whereis ns"
then it printed out some directory names.
I modified some files into ns2-allinone folder. But the ns2 that was running was in 'usr/bin' folder. The ns2 that was being executed was from 'usr/bin' folder.
So, I entered to that folder and opened the terminal. Then wrote'sudo rm ns2' and pressed enter.
Then I wrote ns in terminal. it showed error.
So, I went back to ns2-allinone> ns2.35 and then opened the terminal and wrote "make ns". After that my problems got solved.


text:
Q: lattice orthogonal complement Let $A\in \mathbb{Z}^{m\times n}$ ($m<n$) be a matrix with orthogonal rows. Further assume that the gcd of the coefficients in each row of $A$ is $1$.
Consider $\ker A\cap \mathbb{Z}^n = \{x\in\mathbb{Z}^n: Ax = 0\}$. How is $\det(\ker A\cap \mathbb{Z}^n)$ related to $A$? I tried a few small examples and it seems that $\det(\ker A\cap \mathbb{Z}^n)\cdot\det(A\mathbb{Z}^n) = \sqrt{\det(AA^T)}$. Is this generally true?
($\det(A\mathbb{Z}^n)$ is the determinant of $A\mathbb{Z}^n = \text{im} A \cap \mathbb{Z}^m$, an $m$-dimensional sublattice in $\mathbb{Z}^m$)

A: This does not have much to do with integrality (except that you want the "maximal" lattice), and, while classical (probably in Siegel, though I can't find it right now), it is discussed in my paper Surface area and other measures of ellipsoids. (English summary)
Adv. in Appl. Math.  39  (2007),  no. 4, 409–427 (also on arxiv.org) section 10 - it follows from fairly simple exterior algebra.


text: Q: Posting on facebook user wall a custom field Using facebook graph API and user access token(and cURL), I am posting message, photos to the user wall. Can anybody guide me, I want to post a photo, its description and along with this RATING(custom parameter/field). What I mean is, is there a way to add a custom field and publish/post on user's wall.


text:
Q: Как посчитать время, за которое отсортировался список? import timeit

import numpy as np

def bubble_sort(nums):
    # Устанавливаем swapped в True, чтобы цикл запустился хотя бы один раз
    swapped = True
    while swapped:
        swapped = False
        for i in range(len(nums) - 1):
            if nums[i] > nums[i + 1]:
                # Меняем элементы
                nums[i], nums[i + 1] = nums[i + 1], nums[i]
                # Устанавливаем swapped в True для следующей итерации
                swapped = True

a = list(np.random.permutation(100))
bubble_sort(a)
print(a)

Не понимаю как, надо воспользоваться модулем timeit, как?

A: Я всегда за то, что-бы искать наипростейшие и самые понятные решения задачи.
Поэтому в вашем случае можно, конечно, искать и более красивые решения, в можно и вот так, в лоб:
a = list(np.random.permutation(100))
start_time = timeit.default_timer()
bubble_sort(a)
print(timeit.default_timer() - start_time)

Результат:
0.0008262999999999465

Если очень хочется, то можно немного поизвращаться:
t1 = timeit.Timer("bubble_sort(list(np.random.permutation(100)))", "from __main__ import bubble_sort; import numpy as np")
print("Время выполнения:",t1.timeit(number=1), "миллисекунд")

Результат:
Время выполнения: 0.0009164999996755796 миллисекунд

А можно вообще обойтись библиотекой time (а timeit применять там, где ей место  -  при работе в консоли)
import time
start_time = time.clock()
bubble_sort(a)
stop_time=time.clock()
print(stop_time - start_time)

Результат:
0.0008161999999174441


text:
Q: Magento 2.4.1 disable Elasticsearch I want to use Magento 2.4.1 in a shared server, the problem is that the shared server is not support Elasticsearch. Is there any way to can remove the Elasticsearch or to disable the entire search functionality?
Thank you

A: As you want to remove entire Elastic search and Magento Search functionality so you can use below steps.
Recommend to install this module on development instance using Composer only.
This module won't work on app/code directory.
This may break website GraphQL/REST APIs endpoints as well after installation.
What module actually doing

*

*This module will remove modules mentioned in the replace property so it won't be there.

Based on this repo - I have listed down steps:
Register this module in your composer.json file:
composer require yireo/magento2-remove-search --no-update

Open up the composer.json file and add the following manually to your configuration:
"replace": {
    "magento/module-advanced-search": "*",
    "magento/module-catalog-search": "*",
    "magento/module-elasticsearch": "*",
    "magento/module-elasticsearch-6": "*",
    "magento/module-elasticsearch-7": "*",
    "magento/module-inventory-catalog-search": "*",
    "magento/module-inventory-elasticsearch": "*",
    "magento/module-search": "*",
    "elasticsearch/elasticsearch": "*"
}

Run composer update
If this fails, do the following(beware of its consequences).
rm -r vendor/ composer.lock
composer install

this is the only known workaround to get the composer replace trick working. Here you may face some consequences.
make sure to enable the module
php bin/magento module:enable Yireo_RemoveSearch
rm -r generated/ var/cache
php bin/magento cache:flush

Wipe out Redis if needed
redis-cli flushall

To make sure that everything is working or not, try to execute below commands:
php bin/magento setup:upgrade
php bin/magento setup:di:compile

For more detailed guide and before taking any action, visit README.md - https://github.com/yireo/Yireo_RemoveSearch#yireo_removesearch

A: As of Magento 2.4.x, it is required to use Elasticsearch for the search functionality as MySQL is no longer supported (please check the official release notes details regarding backward incompatible changes).
Please take into consideration that the category pages sorting and filtering also rely on Elasticsearch, so I don't quite imagine how you still have a functioning website without Elasticsearch, unless you do some heavy customizations.
Would it be maybe possible to install Elasticsearch on a different server and then connect Magento to that one?

A: If you can remove elastic search then require below extension and it's install using composer
https://github.com/zepgram/module-disable-search-engine
composer require zepgram/module-disable-search-engine --no-update

Sometimes it is also needed to remove the vendor/ folder and the composer. lock file. It is all needed to force composer to recalculate all dependencies.
Before enabling, check the composer.json file because this extension removed the below extension from the vendor.
magento/module-advanced-search
magento/module-inventory-elasticsearch
magento/module-elasticsearch
magento/module-elasticsearch-6

But We need the this module for search "magento/module-advanced-search"
After the module below, enable using the below command.
php bin/magento module:enable Zepgram_DisableSearchEngine

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f
php bin/magento setup:di:compile
php bin/magento cache:flush
php bin/magento cache:clean
php bin/magento indexer:reindex
sudo chmod -R 777 var/ generated/ pub/media/ pub/static/

After that you need the MYSQL Search engine for searching. So you can install from below the github URL and follow the installation step.
https://github.com/swissup/module-search-mysql-legacy
Also, you can install the following steps below.
composer require swissup/module-search-mysql-legacy

php bin/magento module:enable Swissup_SearchMysqlLegacy Swissup_Core

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f
php bin/magento setup:di:compile
php bin/magento cache:flush
php bin/magento cache:clean
php bin/magento indexer:reindex
sudo chmod -R 777 var/ generated/ pub/media/ pub/static/


text:
Q: How do I use request.META.get('HTTP_REFERER') within template? I'd like to use request.META.get('HTTP_REFERER') within template.
My template source:

{% extends "base.html" %}
{% block title %}django bookmark- login{% endblock %}
{% block head %}login{% endblock %}
{% block content %}
    {% if form.errors %}

try again!

    {% endif %}
    <form method="post" action=".">{% csrf_token %}

username:
        {{ form.username }}

password:
        {{ form.password }}

        <input type="hidden" name="next" value="/" />
        <input type="submit" value="login" />
    </form>
{% endblock %}

How what should I do?
urlpatterns = patterns('', (r'^login/$', 'django.contrib.auth.views.login'),

A: Add django.core.context_processors.request in your settings file in TEMPLATE_CONTEXT_PROCESSORS then you would be able to use the request in template without explicitly passing it in request context.
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.core.context_processors.request', # this one
)

the in template you could do {{request.META.HTTP_REFERER}}

A: Actually the preferred way is to use the next parameter as documented here
You can do in your template something like this:
<input type="hidden" name="next" value="{{  request.GET.next }}" />

A: There's no need for get.request.META is a dictionary, and as with all dictionaries, you can perform field lookup in the template using the dot notation: {{ request.META.HTTP_REFERER }}


text:
Q: How do I load gziped json data into table, using Spark SQL's CREATE TABLE Query I want to connect Apache Superset with Apache Spark (I have Spark 3.1.2) and Query the data on Superset's SQL Lab using Apache Spark SQL.
On spark's master, I started thrift server using this command spark-submit --class org.apache.spark.sql.hive.thriftserver.HiveThriftServer2.
Then I added Spark cluster as a database in Superset using SQLAlchemy URI hive://hive@spark:10000/. I am able to access Spark cluster on Superset.
I can load JSON data as table using this SQL
CREATE table IF NOT EXISTS test_table
USING JSON
LOCATION "/path/to/data.json"

and I am able to Query data using simple SQL statements like SELECT * FROM test_table LIMIT 10
BUT the problem is that json data is compressed as gzipped files.
So I tried
CREATE table IF NOT EXISTS test_table
USING JSON
LOCATION "/path/to/data.json.gz"

but it did not work. I want to know how do load gzipped json data into a table

A: Compressed JSON storage
If you have large JSON text you can explicitly compress JSON text using built-in COMPRESS function. In the following example compressed JSON content is stored as binary data, and we have computed column that decompress JSON as original text using DECOMPRESS function:
CREATE TABLE Person

( _id int identity constraint PK_JSON_ID primary key,

data varbinary(max),

value AS CAST(DECOMPRESS(data) AS nvarchar(max))

)

INSERT INTO Person(data)

VALUES (COMPRESS(@json))

COMPRESS and DECOMPRESS functions use standard GZip compression.
Another example:
CREATE EXTENSION json_fdw;
postgres=# CREATE SERVER json_server FOREIGN DATA WRAPPER json_fdw;

postgres=# CREATE FOREIGN TABLE customer_reviews
(
    customer_id TEXT,
    "review.date" DATE,
    "review.rating" INTEGER,
    "product.id" CHAR(10),
    "product.group" TEXT,
    "product.title" TEXT,
    "product.similar_ids" CHAR(10)[]
)
SERVER json_server
OPTIONS (filename '/home/citusdata/customer_reviews_nested_1998.json.gz');

Note: This example was taken from https://www.citusdata.com/blog/2013/05/30/run-sql-on-json-files-without-any-data-loads


text:
Q: Hola Buen día quisiera saber si me podrían asistir con la fecha de un proyecto que es en html y php Tengo que duplicar un proyecto en el cual a la hora de que este se duplique la fecha de inicio y termino se sumen 1 mes mi pregunta es como podría sumar el mes al nuevo proyecto les dejo como es mi código a continuación.
Les agradecería en verdad bastante si pueden ayudarme por favor

if($action == 'project_double'){
    $pname =$_POST['pname'];
    $location =$_POST['location'];
    $cost =$_POST['cost'];
    $deadline =$_POST['deadline'];
    $sdate = $_POST['sdate'];
    $tid =$_POST['tid'];
    $p_type =$_POST['p_type'];
    $file = "no_image.png";

    $query = mysqli_query($conn,"INSERT INTO projects (project,location,overall_cost,start_date,deadline,site_pic,tid,date_added,io,proposed_project)
        VALUES('$pname','$location','$cost','$sdate','$deadline','$file','$tid',now(),'1','$p_type')");
    $last_id = mysqli_insert_id($conn);
    if(isset($_POST['divs'])){

    $divs= $_POST['divs'];
    $cd = count($divs);
    for($i=0; $i < $cd; $i++){
        $query2 = mysqli_query($conn,"INSERT INTO project_partition (project_id,pd_id)
        VALUES('$last_id','$divs[$i]')");
    }
    }
    if($query && $query2){
        echo '<script>$("#suc_msg2").show("slidedown");
        var delay = 1500;
                    setTimeout(function(){  window.location = "index.php?page=project_detail&id='. $last_id.'&dattyp=new&stats=1";   }, delay);
        </script>';
    }else{
        echo $query;

    }
}

A: te recomiendo investigar mas sobre el tema de fechas aqui DateTime::add
Aqui te dejo un ejemplo de como agregar mas tiempo a tu fecha, suponiendo que utilizas, timestamp en tu base de datos
$deadline = date('Y-m-d H:i:s', strtotime($sdate. ' + 1 month'));
ya tu lo puedes ajustar a como lo manejes internamente!.
Saludos


text:
Q: error code ELIFECYCLE, npm start does not work I can't understand why npm start does not work in my project. Log:
0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'start'
1 verbose cli ]
2 info using npm@6.13.4
3 info using node@v12.16.1
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle react-routing@0.1.0~prestart: react-routing@0.1.0
6 info lifecycle react-routing@0.1.0~start: react-routing@0.1.0
7 verbose lifecycle react-routing@0.1.0~start: unsafe-perm in lifecycle true
8 verbose lifecycle react-routing@0.1.0~start: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\Users\Frogi\Desktop\Новая папка\React-IT-KAMASUTRA\node_modules\.bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Python36-32\Scripts\;C:\Program Files (x86)\Python36-32\;Y:\JDK\bin;E:\myWorkplace\sort\nodeJS\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\120\DTS\Binn\;C:\Program Files\dotnet\;C:\Program Files\nodejs\;C:\Qt\Qt5.8.0\Tools\mingw530_32\bin; C:\Qt\Qt5.8.0\5.8\mingw53_32\bin;C:\Users\Frogi\AppData\Roaming\npm;C:\Users\Frogi\AppData\Local\atom\bin
9 verbose lifecycle react-routing@0.1.0~start: CWD: C:\Users\Frogi\Desktop\Новая папка\React-IT-KAMASUTRA
10 silly lifecycle react-routing@0.1.0~start: Args: [ '/d /s /c', 'react-scripts start' ]
11 silly lifecycle react-routing@0.1.0~start: Returned: code: 1  signal: null
12 info lifecycle react-routing@0.1.0~start: Failed to exec start script
13 verbose stack Error: react-routing@0.1.0 start: `react-scripts start`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:311:20)
13 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:311:20)
13 verbose stack     at maybeClose (internal/child_process.js:1021:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5)
14 verbose pkgid react-routing@0.1.0
15 verbose cwd C:\Users\Frogi\Desktop\Новая папка\React-IT-KAMASUTRA
16 verbose Windows_NT 6.1.7601
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
18 verbose node v12.16.1
19 verbose npm  v6.13.4
20 error code ELIFECYCLE
21 error errno 1
22 error react-routing@0.1.0 start: `react-scripts start`
22 error Exit status 1
23 error Failed at the react-routing@0.1.0 start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

Project: https://github.com/DarkKeksik/React-IT-KAMASUTRA

A: I found the solution to my issue, solution is 'npm install react-scripts@2.1.8'.
create-react-app my-app
cd my-app
npm install react-scripts@2.1.8
npm start

A: Try doing the below-
npm install --registry=https://registry.npmjs.org/
npm install --registry=https://custom.npm.registry.com/

and then-
npm run start


text:
Q: Regex not working, following wrong path in argument I have a regex argument. that checks the content of a variable in this case the content is a time, in the format of HH:MM:SS but when running the line of code the system follows the path to show it has failed and doesn't meet the criteria.
!($11~/^(?:[01]?\d|2[0-3]):[0-5]\d:[0-5]\d|^$/) {print "11th field invalid";}
that's the aforementioned code and here is the contents of the variable "11:40:59".
now I want the code to carry on through the program if a time Is contained inside the variable . however if there is for example an alphabetic character inside the variable I want the program to print "11th field invalid" and exit the program.
also I check the regex argument in tester along with the variable and it matched

A: Awk doesn't support PCRE. As mentioned in the comment, the \d and ?: is not supported.
If you use GNU awk, an alternative to test if the time is correct is to use mktime function.
split($11, a, ":")
if(mktime("2019 1 1 " a[1] " " a[2] " " a[3]) == -1){
   print "11th field invalid"
}

The first line fills the array a with the hour, minute, second fields.
The function mktime returns -1 if the date creation fails.

A: Using an ERE as supported by awk this PCRE (if I understand it correctly):
!($11~/^(?:[01]?\d|2[0-3]):[0-5]\d:[0-5]\d|^$/)

would be:
!($11~/^([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]|^$/)

but you could write the expression instead as:
!($11~/^([01]?[0-9]|2[0-3])(:[0-5][0-9]){2}|^$/)

and it's still missing the terminating $ in the non-null part so it should actually be:
!($11~/^(([01]?[0-9]|2[0-3])(:[0-5][0-9]){2})?$/)

or:
$11 !~ /^(([01]?[0-9]|2[0-3])(:[0-5][0-9]){2})?$/


text:
Q: Repair a burned trace on a PCB I've got a PCB (from a multimeter) that apparently has 2 traces on the PCB burned away.
How they did it, I don't exactly know, but the traces are really gone completely.
The problem is however, that these traces disappeared up to a via they were connecting to...
So little graphical representation("=" = trace, "-" = disappeared trace, "o" = via) : =====-----o
Another complication: if I would solder a small wire through the via, it can't protrude at the other side, because the other side are the sliding contacts of the dial of this multimeter.
So, who's got the best option to repair these traces? Thanks!

A: Scrape any solder mask away from the via and solder to the via itself.  Use very thin wire, since this trace is acting as a fuse.  Or throw this meter in the trash before someone gets hurt.
There's probably something you can do with conductive glue, but I have no experience with it.
Where else does the trace go?  You can connect anywhere else on the circuit node and it should work.  (Not always.)

A: The burnt traces are a symptom. Something shorted out and caused them to burn. Unless you can find and fix the root cause, there is no sense in repairing the traces.

A: Can you place a piece of tinned copper foil on the dial side? You could solder a wire on it, feed it through the via, and solder it to the damaged trace.


text:
Q: Google Charts DataTable unknown I'm using Google Charts to print out some cool charts. It works great in all my browsers.
But the application that I'm building is a HbbTv app. In that enviroment Google Charts gives me an error when he tries to create a DataTable.
The google.visualization object exist, but arrayToTable doesn't exist...
When I try to use DataTable() (creating a new empty DataTable) I get an error dat new google.visualization.DataTable() isn't a constructor...
Somebody known how this could happen?
Some additional info:

*

*The google.visualisation is loaded (but it only count 3 elements instead of 51)

*The HbbTv enviroment is a Opera 9.8

Thanks!
Code:
//My code for creating a data table from an array
var dataTable = google.visualization.arrayToDataTable(data, false);

// My code for creating a DataTable with a new instance
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('string', 'Hour');
dataTable.addColumn('number', 'Amount');
dataTable.addColumn('number', 'Average');
dataTable.addRows(data);

A: The problem is fixed in the Google Visualization 1.1 (release canidate).
So very soon it will be fixed in the production version.


text:
Q: ¿Quiero hacer una consulta usando ajax en php,para que me muestre los datos según su categoría, pero solo traiga los datos dando click en un boton? Hago una consulta y paso el parámetro, según la categoría me liste los productos,
$GLOBALS["lista"]= $GLOBALS["productos"]->listaProductos("DOTACION");
La cual si le doy click en un botón, me traiga estos datos.
if(isset($_GET["dota-test"])){
    function lista(){
    $GLOBALS["lista"]= $GLOBALS["productos"]->listaProductos("DOTACION");
    echo 'si';
    }

    lista();
}

La tabla, esta oculta al darle click al botón, quiero que la tabla aparezca y mediante un ajax, llene la tabla.
$(function() {
              $(document).on('submit','#form-test',function(event) {
                  event.preventDefault();

                    $.ajax({
                      type: 'GET',
                      url: "../Controller/listaProductos.php",
                      data: $(this).serialize(),
                      success:function(response) {
                       console.log(response);
                       if(response=='si'){
                           $("#tabla1").show(1000);
                           $("#producto").show(2000);
                       }
                    }
                  });

            });
        });

En consola, me aparece los datos, pero en la pagina aparece la tabla vacía, ya intente de todo, entonces por favor si alguien sabe del tema me puede ayudar.

A: veo que estas mostrando la tabla cuando te llega el resultado desde tu llamado AJAX pero no estas llenando tu tabla con los datos obtenidos, para hacerlo puedes revisar el codigo que te dejo en este fiddle
Cualquier duda quedo a la orden.

A: Ya encontré la solución a mi problema.
Gracias por la ayuda.
Este es el código:
      $(function() {
          $(document).on('submit','#form-test',function(event) {
                event.preventDefault();

                $.ajax({
                  type: 'POST',
                  url: "../Controller/listaProductos.php",
                  dataType: 'json',
                  data: $(this).serialize(),
                  success:function(response) {
                   //console.log(response);

                   for (i = 0; i < response.length; i++){
                   $("#producto").append('
' +
                    '' +response[i]['descripcion'] + ''+
                    '' +response[i]['tipo'] + ''+
                    '' +response[i]['genero'] + ''+
                    '' +response[i]['TALLA'] + ''+
                    '' +response[i]['cargo'] + ''+
                    '' +response[i]['totalUsado'] + ''+
                    '' +response[i]['totalNuevo'] + ''+
                    '' + ''+'Edita'+''+  ''+
                    '
');
                    }
                    if(response[0]['categoria']=='SEGURIDAD'){

                      $("#genero").hide(1000);
                      $("#talla").hide(1000);
                      $("#cargo").hide(1000);
                      $(".genero").hide(1000);
                      $(".talla").hide(1000);
                      $(".cargo").hide(1000);
                   }
                   if(response[0]['categoria']=='DOTACION'){

                      $("#genero").show(1000);
                      $("#talla").show(1000);
                      $("#cargo").show(1000);
                      $(".genero").show(1000);
                      $(".talla").show(1000);
                      $(".cargo").show(1000);
                   }
                   $("#tabla1").show(1000);
                }
              });

        });
    });


text:
Q: How to find out with which language Telegram bot's API is written? Most of the Telegram bots has API behind them to interact with their users. Is there a way to recognize which programming language is used (PHP, Python, NodeJS, ...) for bot's API?
For example, this bot: @weatherman_bot

A: Most times some telegram (tg) bots have the code on github, you can just look through their code and from there know which language it was written in.
An example would be a todobot I made: @my_todos_bot the source code is available on github. By the way the bot is currently active and working.
But basically knowing the language doesn't really determine how to bot will function because tg supports lots of languages from which you can choose from. I personally make mine in Nodejs but you can do it in whichever you choose (and is supported by tg).


text:
Q: PHP Curl - Redirect after login I wanted to get data from a website with curl.
First I login like this:
$userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4";

$ch = curl_init("https://192.168.67.10/Appliance/index.jsp");

$username="***";
$password="***";
$submit = "userid=$username&pass=$password&submitted=true&rememberMe=0";

if(!$ch) {
    die(sprintf("Fehler[%d]: %s",
        curl_errno($ch), curl_error($ch)));
}
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookie.txt");
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $submit);

$data = curl_exec($ch);

if(!$data) {
    die(sprintf("Fehler [%d]: %s",
        curl_errno($ch), curl_error($ch)));

}

curl_close($ch);

echo $data;

How can I access another page now?
Login page: https://192.168.67.10/Appliance/HomePage/index.jsp
Page I want to access: https://192.168.67.10/Appliance/SystemsCenter/Encryption/CertificateStore/index.jsp
Thank you in advance.

A: if(!$data){
    //your existing code

}else{
    //it was successful
    curl_close($ch);
    //repeat process of instantiating curl here
}

A: I didn't see you using CURLOPT_POST. So please add this:
curl_setopt($ch, CURLOPT_POST, 1);

Also, use enable follow redirect, so that no stone keep unturned!
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);


text:
Q: laravel method in href link? I want to create a dropdown with two links. A 'Delete' and a 'Edit' link.
For the delete function I created a form.
                        {!! Former::horizontal_open()->method('DELETE')->action(action("Test\\TestController@destroythread", $comment->id)) !!}
                        {!! Former::danger_submit('Delete') !!}
                        {!! Former::close() !!}

The form works, that means my comment get's deleted, if I'm pressing the button.
No I decided to remove the delete button and do a dropdown with a delete link. So I need to get the logic of this form in my dropdown menu.
But I haven't got this in the dropdown.. The optical 'Delete' button is this part of the dropdown:

Delete

But I can't just put my controller function in that "href-link", cause without the 'DELETE'-Method, it won't work. I hope you all understand what I'm trying to say... my english isn't the best anyway.
Can somebody help me with this?
Thanks for any help!
I tried it like this before but this haven't worked either:

        {!! Former::horizontal_open()->method('DELETE')->action(action("Test\\TestController@destroythread", $comment->id)) !!}
        Delete
        {!! Former::close() !!}

my try linking directly to the route:

id) }}">Delete

and my Route looks like this:
Route::delete('/show/{id}', 'Test\\TestController@destroythread')->name('destroythread');

but this haven't worked for me..
all /show/ routes:
Route::get('/show/{id}', 'Test\\TestController@show');
Route::put('/show/{id}/edit', ['as' => 'editing', 'uses' => 'Test\\TestController@update']);
Route::get('/show/{id}/edit', 'Test\\TestController@edit')->name('edit');
Route::delete('/show/{id}', 'Test\\TestController@destroy')->name('destroy');

Route::delete('/show/{id}', 'Test\\TestController@destroythread')->name('destroythread');   // this is the route we are talking about

A: Laravel uses method spoofing to do 'DELETE', 'PUT', 'PATCH' form requests. Like @Jilson Thomas mentioned, you can just create a link directly to the route. I suspect you're using resourceful routes, thats why you're trying to post a DELETE request?
Have a look at this section in the routing docs, this may help you out: https://laravel.com/docs/master/controllers#restful-supplementing-resource-controllers
Based on your routes posted, I believe the following two routes are matching before it gets to your desired route.
Route::put('/show/{id}/edit', ['as' => 'editing', 'uses' => 'Test\\TestController@update']);
Route::delete('/show/{id}', 'Test\\TestController@destroy')->name('destroy');

Try moving your desired route above these and see what happens.
Edit

id) }}">Delete

That will produce a GET request, therefore it will not match Route::delete(...). The previous method was posting a form to the route. Also, wrapping an entire form in an anchor tag is invalid markup.

A: So, as per the discussion in the comments, you'll have to use ajax request to do a delete request from an anchor tag.
$.ajax({
    url: '/show/'+$('#testId').attr('value'),
    type: 'DELETE',
    success: function(data){ if(data.success) alert('Deleted'); },
    error: function() {}
});

and in your route:
Route::delete('/show/{id}', ['as'=>'destroy', 'uses'=>'Test\\TestController@destroy']);

HTML

id}}">Delete

A: Alternative way, try 'Laravel Collective' Html Helper.
HTML
{!! Form::open('delete',
    'method' => 'delete,
    'route'  => ['show.destroy', $comment->id]
) !!}

     {!! Form::submit('Submit') !!}

{!! Form::close() !!}

routes.php
Route::delete('show/{show}', [
  'uses' => 'TestController@destroy',
  'as' => 'show.destroy'
]);

A: Try this:
The form with method dont show and you can call a route / url with method POST/PUT/DELETE ...
Logout

<form id="logout-form" action="{{ route('item/delete',) }}" method="POST" style="display: none;">
    @csrf
</form>


text:
Q: I got this error when pressing search button in home activity it should open search activity ! any idea please?

package com.app.mycare.screens.search

import android.os.Bundle
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android_mvvm.custom.ui.BaseActivity
import android_mvvm.mvvm.ViewModel
import com.app.mycare.R
import com.app.mycare.databinding.ActivitySearchBinding

class SearchActivity : BaseActivity(), SearchCallback {

    private var filtersShown = false

    override fun createViewModel(): ViewModel {
        return SearchViewModel(this)
    }

    override fun getLayoutId() = R.layout.activity_search

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val myBinding = this.binding as ActivitySearchBinding
        val filterSection = myBinding.searchFilterSection

        val slideUp = AnimationUtils.loadAnimation(this, R.anim.slide_up)
        slideUp.setAnimationListener(object: Animation.AnimationListener{
            override fun onAnimationRepeat(p0: Animation?) {}
            override fun onAnimationStart(p0: Animation?) {}
            override fun onAnimationEnd(p0: Animation?) {
                filterSection.visibility = View.GONE
            }
        })

        val slideDown = AnimationUtils.loadAnimation(this, R.anim.slide_down)
        slideDown.setAnimationListener(object: Animation.AnimationListener{
            override fun onAnimationRepeat(p0: Animation?) {}
            override fun onAnimationStart(p0: Animation?) {
                filterSection.visibility = View.VISIBLE
            }
            override fun onAnimationEnd(p0: Animation?) {}
        })

        filterSection.visibility = View.GONE

        myBinding.searchFilter.setOnClickListener {
            if(filtersShown) {
                //myBinding.searchFilterSection.startAnimation(slideUp)
                filterSection.visibility = View.GONE
                filtersShown = false
            } else {
                filterSection.visibility = View.VISIBLE
                myBinding.searchFilterSection.startAnimation(slideDown)
                filtersShown = true
            }
        }
    }

    override fun hideFilters() {
        if(filtersShown){
            (this.binding as ActivitySearchBinding).searchFilter.performClick()
        }
    }
}

interface SearchCallback{
    fun hideFilters()
}

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.app.mycare, PID: 7838
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.mycare/com.app.mycare.screens.search.SearchActivity}: kotlin.UninitializedPropertyAccessException: lateinit property resources has not been initialized
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: kotlin.UninitializedPropertyAccessException: lateinit property resources has not been initialized
at android_mvvm.mvvm.ViewModel.getResources(ViewModel.kt:18)
at com.app.mycare.screens.search.SearchViewModel.(SearchViewModel.kt:27)
at com.app.mycare.screens.search.SearchActivity.createViewModel(SearchActivity.kt:17)
at android_mvvm.mvvm.MvvmActivity.onCreate(MvvmActivity.java:42)
at android_mvvm.custom.ui.BaseActivity.onCreate(BaseActivity.kt:33)
at com.app.mycare.screens.search.SearchActivity.onCreate(SearchActivity.kt:23)
at android.app.Activity.performCreate(Activity.java:6876)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)

A: Your onCreate is calling super.onCreate(savedInstanceState), which is the onCreate in BaseActivity. That is calling the onCreate in MvvmActivity (I'm guessing it's BaseActivity's superclass), and that is calling createViewModel in SearchActivity (I'm reading the stacktrace bottom-up here, btw)
The constructor / init for SearchViewModel is calling getResources() on some ViewModel (some property in the superclass maybe?) - and that hasn't been initialised yet, which is why you're getting a crash.
I'm not familiar with the android_mvvm library you're using, so that's all I can tell you! Look into what you're supposed to do to initialise things in those ViewModel classes it provides


text:
Q: trying to make a simple grid-class, non-lvalue in assignment I'm implementing a simple C++ grid class. One Function it should support is accessed through round brackets, so that I can access the elements by writing mygrid(0,0). I overloaded the () operator and i am getting the error message: "non-lvalue in assignment".
what I want to be able to do:
//main

cGrid<cA*> grid(5, 5);

grid(0,0) = new cA();

excerpt of my implementation of the grid class:
template
class cGrid
{
private:
    T* data;
    int mWidth;
    int mHeight;

public:
    cGrid(int width, int height) : mWidth(width), mHeight(height) {
        data = new T[width*height];
    }

    ~cGrid() { delete data; }

    T operator ()(int x, int y)
    {
        if (x >= 0 && x <= mWidth) {
            if (y >= 0 && y <= mHeight) {
                return data[x + y * mWidth];
            }
        }
    }

    const T &operator ()(int x, int y) const
    {
        if (x >= 0 && x <= mWidth) {
            if (y >= 0 && y <= mHeight) {
                return data[x + y * mWidth];
            }
        }
    }

The rest of the code deals with the implementation of an iterator and should not be releveant.

A: What does this template:
 T &operator ()(int x, int y) const
{
    if (x >= 0 && x <= mWidth) {
        if (y >= 0 && y <= mHeight) {
            return data[x + y * mWidth];
        }
    }
}

do if x & y are out of range? You should raise an exception. And how are you allocating memory to the grid in the constructor? As regards constness, you need to supply two versions of this operator -  a const one that returns a const reference, and a non-const one that returns a non-const reference.
Edit: You also have an off-by one error in the operator. This compiles and runs:
template <typename T>
struct Grid {
    Grid( int x, int y ) : mX(x), mY(y), mData(0) {
      mData = new T[ x * y ];
    }

    ~Grid() {
      delete [] mData;
    }

    T &operator ()(int x, int y)  {
        if (x >= 0 && x < mX) {
            if (y >= 0 && y < mY) {
                return mData[x + y * mX];
            }
        }
    throw "out of range" ;;
    }

    int mX, mY
    T * mData;
};

int main() {
    Grid <int> g(2,3);
    g(0,0) = 42;
}

A: As Bill remarked, the operator shouldn't be const.  I believe this is the reason for the compilation error (even if the error reported seems different).  The compiler only encounters the error at the assignment line because it is a template class.
To be clear, you can't have a const method return a reference to a non-const.  I.e., the
problem is that the declaration T &operator... const is illegal.  It should be either T &operator... or const T &operator... const.  Of course you can have both.
Edit:  Removing the const doesn't help because now both methods have the same signature (the return type is not considered part of the signature for purposes of resolving the call).  The method being called is the one returning T, not T &.  Get rid of it (or replace it with a const method returning a const reference.)


text:
Q: Using wildcards in SQL IN operator Structure:
table
c1 c2
1  test
1  test2
2  test
2  test3
3  test4

SQL:
SELECT c1 FROM table WHERE c2 in ("test3","test4")

What I want:
SELECT c1 FROM table WHERE c2 in ("%3","%st4")

How can I do this?

A: SELECT c1 FROM table WHERE (c2 like "%3") or (c2 like "%st4")

A: Here is my approach just to follow the logic you have in your question:
http://sqlfiddle.com/#!9/aca65e/2
SELECT *
FROM `table`
WHERE c2 REGEXP '.*3$|.*st4$';

But keep in mind that solution
SELECT c1 FROM table WHERE (c2 like "%3") or (c2 like "%st4")

provided by @splash58 could be much faster if c2 column is indexed.


text:
Q: Run explorer.exe elevated/as Administrator user within Windows 10 How can explorer.exe be run elevated/with full admin token/permissions in windows 10?

A: Via task manager:

*

*Kill all instances of explorer.exe

*File > Run new task

*explorer /nouaccheck

*Create this task with administrative privileges

*OK

Source 1 (in the comments)
Source 2


text:
Q: Spring Data map results I use Spring Data and I can't find a way to map a @Query results into a DTO. E.g on the query
@Query("select f.a f.b from Foo f")
List<FooStripped> find();

where
public class FooStripped {
   String a;
   String b;
   ...
}

I want all the results to be mapped to a list of FooStripped an Object[] is returned.

A: You can see an example for this in Is there a way to transform objects that spring data repositories return?
But I would not do that to be honest. I would advice you do to this manually in the service/controller level. You can use for this the following framework http://modelmapper.org/ or any other object mapping framework.


text:
Q: Dynamic DropDownMenu in extjs I have a 2 DropDownBoxes, where 1 of the drop box value is depanded on the selected value of the first.
How do i create a dynamic store in the second DropDownBoxes.
This is the code:
{
                            xtype: 'combobox',
                            displayField: 'vendor_name',
                            typeAhead: true,
                            mode: 'local',
                            triggerAction: 'all',
                            emptyText:'Choose vendor...',
                            selectOnFocus:true,
                            fieldLabel: 'Vendor Name',
                            margin: 10,
                            id: 'txtBidVendor',
                            labelWidth: 100,
                            store:  Ext.create('Ext.data.Store', {
                                fields:[
                                    {name: 'vendor_name'}
                                ],
                                proxy: {
                                    type: 'ajax',
                                    timeout: 120000,
                                    url: 'GetVendors.jsp',
                                    reader: {
                                        type: 'json',
                                        root: 'data',
                                        successProperty: 'success'
                                    }
                                },
                                autoLoad: true
                            })
                        },
                        {
                            xtype: 'combobox',
                            displayField: 'rate_desc',
                            typeAhead: true,
                            mode: 'local',
                            triggerAction: 'all',
                            emptyText:'Choose Quality...',
                            selectOnFocus:true,
                            fieldLabel: 'Vendor Quality',
                            margin: 10,
                            id: 'txtBidVendorQuality',
                            labelWidth: 100,
                            store:  Ext.create('Ext.data.Store', {
                                fields:[
                                    {name: 'rate_desc'}
                                ],
                                proxy: {
                                    type: 'ajax',
                                    timeout: 120000,
                                    url: 'GetVendorQuality.jsp?' + Ext.urlEncode({'bid_vendor': Ext.getCmp('txtBidVendor').value}),
                                    reader: {
                                        type: 'json',
                                        root: 'data',
                                        successProperty: 'success'
                                    }
                                },
                                autoLoad: true
                            })
                        },

I get the error: "Cannot read property 'value' of undefined " ,in the line where i try getting "Ext.getCmp('txtBidVendor').value"

A: About what you are trying to accomplish here I have two considerations:

*

*The error here is that you are trying to access to the txtBidVendor component at definition time (it doesn't exists), when you send a configuration object (like these two comboboxes here) you are not actually creating them, but just setting the initial configuration  that will be used by its parent for later instantiation.

*What I think you are trying to do is to change the query parameter value for the store, when the selection changes on txtBidVendor combobox. To accomplish that, you must listen for the selection event of the first combobox and then modify and reload the store of the second one. Something like this:

{
    xtype: 'combobox',
    displayField: 'vendor_name',>
    emptyText: 'Choose vendor...',
    selectOnFocus: true,
    fieldLabel: 'Vendor Name',
    id: 'txtBidVendor',
    store: vendorStore,
    listeners: {
        select: function (combo, records, eOpts) {
            var record = records[0]; // just want the first selected item

            rateStore.getProxy().extraParams.bid_vendor = record.get('vendor_name');
            alert('Store will load now with bid_vendor =' + record.get('vendor_name'));
            rateStore.load();
        }
    }
}

For sake of readability it will be good idea to take store definition out of the components definition itself also.  Here you can find a working sample of it.
Hope it helps.


text:
Q: Как найти строки в файлах и изменить их с помощью python?
Подскажите, есть файлы с логами app.log.gz, которые лежат в /2022/месяц/год/,
в логе нужно найти запись 'PASS" => '(3 случайных числа)', как пример 'PASS' => '564', нужно заменить случайные трехзначные числа на *** , чтобы получилось так 'PASS' => '***'
скрипт должен пробежаться по всем файлам в папках
в Python не силен, сделал начало скрипта, но застрял на re.search() как через него найти 'PASS' => '3 случайных числа', так же попробовал задать re.search(r'[0-9][0-9][0-9]' выводится только одна запись в логе
import os.path
import gzip
import re

for root, dirs, files in os.walk("2022"):
    for file in files:
        if file.endswith('app.log.gz'):
            path_file = os.path.join(root, file)
            with gzip.open(path_file, 'rb') as oldfile:
                oldfile = str(oldfile.read())
                data = re.search(r'[0-9][0-9][0-9]', str(oldfile))
                print(data)
                вывод <re.Match object; span=(16, 19), match='202'>

                #with gzip.open(path_file + 'new', 'w') as newfile:
                #    newfile.write(oldfile).


text:
Q: UICollectionView Getting indexPath in prepareForSegue For my collection view I use didSelectItemAt to call performSegue. My problem is that the sender is my vc and not the cell itself. So in prepareForSegue, I get an error, because I can't convert the vc to my cell type.
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
   performSegue(withIdentifier: "collectionSegue", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if let destinationVC = segue.destination as? ImageViewController {
      let cell = sender as! ImageCollectionViewCell
      let indexPath = imageCollectionView.indexPath(for: cell)
      destinationVC.buttonTag = indexPath?.row
   }
}

A: You can set sender as anything you want. This may help:
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
       let cell = collectionView!.cellForItemAtIndexPath(indexPath) as! ImageCollectionViewCell
       performSegue(withIdentifier: "collectionSegue", sender: cell)
    }

A: try this
var currentIndex = 0
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
   self.currentIndex = indexPath.row
   performSegue(withIdentifier: "collectionSegue", sender: self)
   //let cell = sender as! ImageCollectionViewCell
   //performSegue(withIdentifier: "collectionSegue", sender: cell)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if segue.identifier == "collectionSegue" {
    if let destinationVC = segue.destination as? ImageViewController {
        //let indexPath = imageCollectionView.indexPath(for: cell)
        //let indexPath = imageCollectionView.indexPath(for: sender as! ImageCollectionViewCell)
        destinationVC.buttonTag = self.currentIndex
    }
  }
}


text:
Q: How to get upstream/downstream performance for Atmosphere channel within Vaadin Flow 14? We use Jetty embedded for Vaadin Flow application. I need to log or visualize Push Atmosphere channel performance for Vaadin web application. I is useful for diagnostic internet connection speed and quality for our external clients. How can i do that?
In one word, i need to measure internet connection over websocket channel, in both directions. I want to use it for connection quality indicator on application page.


text:
Q: VBA coding Copy Paste I want to copy data from two xls files, Rahul.xls and Rohit.xls and paste them in a master file "Macro.xls"
The code is copy pasting Rahul.xls but when pasting Rohit.xls it is overlapping the data, resulting that all the data from Rahul.xls is gone and i can only see the data from Rohit.xls.
Second, is that it is not closing the source files after copy-pasting.
Can anyone help me in amending this code so that

*

*Rohit's data will come after Rahul's data

*after copy pasting Rahul's data the sheet will close automatically
Sub OpenCopyPaste()

' open the source workbook and select the source sheet

    Workbooks.Open Filename:="C:\Rahul.xls"

    Sheets("Case Tracker").Select

    ' copy the source range

    Sheets("Case Tracker").Range("A:J").Select

    Selection.Copy

    ' select current workbook and paste the values starting at A1

    Windows("Macro.xls").Activate

    Sheets("Sheet1").Select

    Sheets("Sheet1").Range("A1").Select

    ActiveSheet.Paste

    Application.CutCopyMode = False

    ActiveWorkbook.Save

    Workbooks.Open Filename:="C:\Rohit.xls"

    Sheets("Case Tracker").Select

    ' copy the source range

    Sheets("Case Tracker").Range("A:J").Select

    Selection.Copy

    ' select current workbook and paste the values starting at A1

    Windows("Macro.xls").Activate

    Sheets("Sheet1").Select

    Sheets("Sheet1").Range("A1").Select

    ActiveSheet.Paste

    Application.CutCopyMode = False

    ActiveWorkbook.Save

End Sub

A: The code is overwriting the data in Sheet1 range starting at A1 after it opens the second file. Think of a way to find the end of the range and start the new data there.
    Workbooks.Open Filename:="C:\Rohit.xls"

    Sheets("Case Tracker").Select

    ' copy the source range

    Sheets("Case Tracker").Range("A:J").Select
    Selection.Copy

    ' select current workbook and paste the values starting at A1

    Windows("Macro.xls").Activate

    Sheets("Sheet1").Select

    ' the code is overwriting the data in Sheet1 range starting at A1
    Sheets("Sheet1").Range("A1").Select

    ActiveSheet.Paste

    Application.CutCopyMode = False

    ActiveWorkbook.Save

For closing a workbook, I believe it is just as simple as:
    Workbooks(fileName).Close

A: Try something like this. Hopefully it's what you need, but if not I hope that it at least can get you on the path to the answer. Cheers.
    Workbooks.Open Filename:="C:\Rahul.xls"

    Sheets("Case Tracker").Select

    ' copy the source range

    Sheets("Case Tracker").Range("A:J").Select

    Selection.Copy

    ' select current workbook and paste the values starting at A1

        Windows("Macro.xls").Activate

        Sheets("Sheet1").Select

        Sheets("Sheet1").Range("A1").Select

        ActiveSheet.Paste

        Application.CutCopyMode = False

        ActiveWorkbook.Save

        workbooks("Rahul.xls").close workbooks("Rahul.xls").saved=true

        Workbooks.Open Filename:="C:\Rohit.xls"

        Sheets("Case Tracker").Select

        ' copy the source range

        Sheets("Case Tracker").Range("A:J").Select
        Selection.Copy

        ' select current workbook and paste the values starting at A1

        Windows("Macro.xls").Activate

        Sheets("Sheet1").Select

        'Sheets("Sheet1").Range("A1").Select-take this bit and replace it with the following

     emptyrow=worksheetfunction.counta(sheets("sheet1").range("A")) 'you can use any column to reference, one with continuous data is the best
     sheets("Sheet1").cells(emptyrow,1).select

        ActiveSheet.Paste

        Application.CutCopyMode = False

        ActiveWorkbook.Save

        workbooks("Rohit.xls").close workbooks("Rohit.xls").saved=true

        End Sub

A: You could use a variable to define the last used Row in the destination Sheet and addedd plus one at the desire Range :
    Sub CopySheets()
    Workbooks.Open Filename:="C:\Rahul.xls"
    'Variable to the last available row
    Dim lLastRow As Long

    Sheets("Case Tracker").Range("A:J").Copy Destination:=Windows("Macro.xls").Sheets("Sheet1").Range("A1")

    Application.CutCopyMode = False

    Workbooks.Open Filename:="C:\Rohit.xls"

    'Retrieve the last used row in the destination
    lLastRow = Workbooks("Macro").Worksheets("Sheet1").Cells(Workbooks("Macro").Worksheets("Sheet1").Rows.Count, "A").End(xlUp).Row

    'Use the Lastrow variable aded to the range of the destination + 1 (the next empty row)
    Sheets("Case Tracker").Range("A:J").Copy Destination:=Windows("Macro.xls").Sheets("Sheet1").Range("A" & lLastRow + 1)

    Application.CutCopyMode = False

    Workbooks("Macro").Save
    Workbooks("Macro").Close

    End Sub

meanwhile in your urgency, you could only use the
Dim lLastRow As Long
and the other line
lLastRow = Workbooks("Macro").Worksheets("Sheet1").Cells(Workbooks("Macro").Worksheets("Sheet1").Rows.Count, "A").End(xlUp).Row
and only add the variable modifying the second destination like this:
Sheets("Sheet1").Range("A" & lLastRow + 1)
in your original code


text:
Q: EclipseLink all attributes are displayed as JSON I have the following JPQL in Entity class
select new test.entity.Emp(o.empNo, o.empName) from Emp o

and in Service layer
@GET
@Path("/results")
@Produces(MediaType.APPLICATION_JSON)
public List<Emp> findAll() {
    Query query =             getEntityManager().createNamedQuery("Emp.findAll");
    List<Emp> result = query.getResultList();
    return result;
}

However when I run, all attributes are getting displayed in JSON result instead of empNo and EmpName.
What could be the reason?

A: Your query returns new Emp objects (constructed only by empNo and empName), so this would be the result of your JSON string - whole Emp objects.
Create a class like this:
public class EmpDTO {
    private String empNo; //or whatever datatype you use...
    private String empName;

    public EmpDTO(String empNo, String empName) {
        this.empNo = empNo;
        this.empName = empName;
    }

    //getters and setters
}

Then edit your query to use this class in the constructor expression (change the package from test.dto to whatever you created your class in):
select new test.dto.EmpDTO(o.empNo, o.empName) from Emp o

Finally edit your code:
...
public List<EmpDTO> findAll() {
    Query query = getEntityManager().createNamedQuery("Emp.findAll");
    return query.getResultList();
}

BTW: Emp.findAll is not an ideal name for your namedQuery.


text:
Q: convert html to json in PHP Im trying to do request in php but the answer is in HTML, how can i convert it in json ?
case 'getzipcode':
$CITY= @$_POST['city'];

$STREET= @$_POST['street'];

$Q= "https://www.israelpost.co.il/zip_data.nsf/SearchZip?OpenAgent&Location=".$CITY."&Street=".$STREET ;

$results = file_get_contents($Q);

$results= json_encode($results, JSON_UNESCAPED_UNICODE);

print($results);

For the moment i got this :
"\n\n\n\nRES84623000\n\n\n"
thank you in advance,

A: I completly agree with Magnus in the comments, that you should contact the API providers, and ask them for an JSON endpoint..
But if that is not possible, you could do something like this :
<?php
$theFile = file_get_contents('https://www.israelpost.co.il/zip_data.nsf/SearchZip?OpenAgent&Location=%25u05EA%25u05DC%20%25u05D0%25u05D1%25u05D9%25u05D1%20-%20%25u05D9%25u05E4%25u05D5&POB=&Street=%25u05D3%25u05D9%25u05D6%25u05E0%25u05D2%25u05D5%25u05E3&House=99&Entrance=');

libxml_use_internal_errors(true); //Prevents Warnings, remove if desired
$dom = new DOMDocument();
$dom->loadHTML($theFile);
$body = "";
foreach($dom->getElementsByTagName("body")->item(0)->childNodes as $child) {
    $body .= $dom->saveHTML($child);
}
echo $body;

This will get the content of the body tag for you.
This example will output RES86439611 - whatever that means to you


text:
Q: Using Stax2 to escape special characters in Scala I am trying to use stax2 in order to write xml files with escaping special characters for the attributes.
When I am trying to achieve is an exact output like this:
<elem1 att1="This
 That" />
But when I use the usual XMLStreamWriter is this:
<elem1 att1="This &#x0A; That" />
So I tried the following with stax2 :
import org.codehaus.stax2.{XMLOutputFactory2}
import org.scalatest.funsuite.AnyFunSuite
import java.io.{File, FileOutputStream}
import javax.xml.stream.{XMLOutputFactory, XMLStreamWriter}

class testStreamXML extends AnyFunSuite{
  val file = new File("stax2test.xml")
  val fileOutputStream = new FileOutputStream(file)
  val outputFactory: XMLOutputFactory2 = XMLOutputFactory.newInstance().asInstanceOf[XMLOutputFactory2]
  //outputFactory.setProperty(XMLOutputFactory2.P_ATTR_VALUE_ESCAPER, true)

  val writer= outputFactory.createXMLStreamWriter(fileOutputStream)

  writer.writeStartDocument()
  writer.writeStartElement("elem1")
  writer.writeAttribute("att1", "This
 That")
  writer.writeEndElement()
  writer.writeEndDocument()
}

And whenever i try to set the property P_ATTR_VALUE_ESCAPER to true or false,I receive this error:
An exception or error caused a run to abort: class java.lang.Boolean cannot be cast to class org.codehaus.stax2.io.EscapingWriterFactory (java.lang.Boolean is in module java.base of loader 'bootstrap'; org.codehaus.stax2.io.EscapingWriterFactory is in unnamed module of loader 'app')
java.lang.ClassCastException: class java.lang.Boolean cannot be cast to class org.codehaus.stax2.io.EscapingWriterFactory (java.lang.Boolean is in module java.base of loader 'bootstrap'; org.codehaus.stax2.io.EscapingWriterFactory is in unnamed module of loader 'app')
    at com.ctc.wstx.api.WriterConfig.setProperty(WriterConfig.java:401)
    at com.ctc.wstx.api.CommonConfig.setProperty(CommonConfig.java:100)
    at com.ctc.wstx.stax.WstxOutputFactory.setProperty(WstxOutputFactory.java:153)
    at testStreamXML3.<init>(testStreamXML3.scala:10)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
    at java.base/java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:128)
    at java.base/jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:350)
    at java.base/java.lang.Class.newInstance(Class.java:645)
    at org.scalatest.tools.Runner$.genSuiteConfig(Runner.scala:1402)
    at org.scalatest.tools.Runner$.$anonfun$doRunRunRunDaDoRunRun$8(Runner.scala:1199)
    at scala.collection.immutable.List.map(List.scala:246)
    at org.scalatest.tools.Runner$.doRunRunRunDaDoRunRun(Runner.scala:1198)
    at org.scalatest.tools.Runner$.$anonfun$runOptionallyWithPassFailReporter$24(Runner.scala:993)
    at org.scalatest.tools.Runner$.$anonfun$runOptionallyWithPassFailReporter$24$adapted(Runner.scala:971)
    at org.scalatest.tools.Runner$.withClassLoaderAndDispatchReporter(Runner.scala:1480)
    at org.scalatest.tools.Runner$.runOptionallyWithPassFailReporter(Runner.scala:971)
    at org.scalatest.tools.Runner$.run(Runner.scala:798)
    at org.scalatest.tools.Runner.run(Runner.scala)
    at org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.runScalaTest2or3(ScalaTestRunner.java:38)
    at org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.main(ScalaTestRunner.java:25)

Any suggestion how to use resolve this? or to achieve my goal of escaping special characters in attribute?

A: The property you are referring to does require a class of EscapingWriterFactory. Here are the docs:

Property that can be set if a custom output escaping for attribute value content is needed. The value set needs to be of type
EscapingWriterFactory. When set, the factory will be used to create a
per-writer instance used to escape all attribute values written, both
via explicit XMLStreamWriter.writeAttribute(java.lang.String,
java.lang.String) methods, and via copy methods
(XMLStreamWriter2.copyEventFromReader(org.codehaus.stax2.XMLStreamReader2,
boolean)). [1]

Regarding your question of how to achieve an 'individual' escaping an implementation of this factory would do the job. Here is a simple implementation (inspired by [2]) using the given writer without applying any escaping - this might be your starting point for any special use case you want to address:
class CustomXmlEscapingWriterFactory extends EscapingWriterFactory{
  override def createEscapingWriterFor(writer: Writer, s: String): Writer =
    new Writer(){
      override def write(cbuf: Array[Char], off: Int, len: Int): Unit =
        writer.write(cbuf, off, len)
      override def flush(): Unit = writer.flush()
      override def close(): Unit = writer.close()
    }

  override def createEscapingWriterFor(outputStream: OutputStream, s: String): Writer =
    throw IllegalArgumentException("not supported")
}

class TestStreamXML extends AnyFunSuite{
  val file = new File("stax2test.xml")
  val fileOutputStream = new FileOutputStream(file)
  val oprovider: OutputFactoryProviderImpl  = new OutputFactoryProviderImpl()
  val outputFactory: XMLOutputFactory2 = oprovider.createOutputFactory()
  // your factory implementation goes here as property
  outputFactory.setProperty(XMLOutputFactory2.P_ATTR_VALUE_ESCAPER, CustomXmlEscapingWriterFactory())

  val writer= outputFactory.createXMLStreamWriter(fileOutputStream)

  writer.writeStartDocument()
  writer.writeStartElement("elem1")
  writer.writeAttribute("att1", "This
 That")
  writer.writeEndElement()
  writer.writeEndDocument()
}

The resulting output looks like this:
<?xml version='1.0' encoding='UTF-8'?><elem1 att1="This
 That"/>

[1] https://fasterxml.github.io/stax2-api/javadoc/4.0.0/org/codehaus/stax2/XMLOutputFactory2.html#P_ATTR_VALUE_ESCAPER
[2] Escaping quotes using jackson-dataformat-xml


text:
Q: Errors fitting a Penalized Linear Model in R I am trying to reproduce the results from this answer in CrossValidated with no luck. I keep getting an error when calling:
print("Fitting Penalized Linear Model")
GLMmodel <- train(X,Y,method='glmnet',trControl=myCtrl,tuneLength=10)

Here is the error:
[1] "Fitting Penalized Linear Model"
Error in { :
  task 1 failed - "arguments imply differing number of rows: 1264, 736"
In addition: There were 50 or more warnings (use warnings() to see the first
 50)

The full code is below:
#Setup
rm(list = ls(all = TRUE))
set.seed(1)

#Generate an input matrix with 10,000 values
#2,000 rows, 5 columns
X <- data.frame(replicate(5, rnorm(2000)))

#Construct Y using X
Y <- runif(1)*X[,1]*X[,2]^2+runif(1)*X[,3]/X[,4]

#Convert Y to binary
Y <- as.factor(ifelse(sign(Y)>0,'X1','X0'))

#Create bootstrap samples for fitting models
library(caret)
print("Creating bootstrap samples")
tmp <- createResample(Y,times = 25)
myCtrl <- trainControl(method = "boot", index = tmp, timingSamps = 10)

#Fit models
print("Fitting Random Forests")
RFmodel <- train(X,Y,method='rf',trControl=myCtrl,tuneLength=1)

print("Fitting SVM")
SVMmodel <- train(X,Y,method='svmRadial',trControl=myCtrl,tuneLength=3)

print("Fitting Penalized Linear Model")
GLMmodel <- train(X,Y,method='glmnet',trControl=myCtrl,tuneLength=10)

print("Fitting Nearest neighbors")
KNNmodel <- train(X,Y,method='knn',trControl=myCtrl,tuneLength=10)

print("Fitting Neural Network")
NNmodel <- train(X,Y,method='nnet',trControl=myCtrl,tuneLength=3, trace = FALSE)

#Assess re-sampled (out of sample) accuracy
print("Assessing re-sampled (OOB) accuracy")
resamps <- resamples(
        list(   RF = RFmodel,
                SVM = SVMmodel,
                GLMnet = GLMmodel,
                KNN = KNNmodel,
                NN = NNmodel
                ))
print("Summarizing resamps")
summary(resamps)

print("Plotting accuracy")
dotplot(resamps, metric = "Accuracy")

#Assess run-time (in seconds)
print("Assessing timings")
resamps$timings

I am relatively new to R so I can't tell what's wrong with that line. Did the package GLM change since the time of that post? Is this a possible bug with GML?
For reference. I am running the latest version of R (2.15.2) with the latest stable version of caret (5.15-052)

A: I was missing the package glmnet. The error message:

Error in { :
  task 1 failed - "arguments imply differing number of rows: 1264, 736"
In addition: There were 50 or more warnings (use warnings() to see the first
 50)

misled me to think there was problem with the input, not that I was missing a package.


text:
Q: List> to iterate through WebElement variables I am using a cucumber datatable:
When I populate a field with a new value
      | FieldName  | FieldValue |
      | Name | Joe Blogs |
      | Email address | jblogs@gmail.com |
      | Phone 1 | 04 555 6666 |
      | Phone 2 | 0800 123 4567 |
      | SMS Phone | 023 222 333 |
      | Fax number | 09 888 9999 |
      | Location | Bermuda Triangle |

With the following java class:
@When("^I populate a field with a new value$")
    public void ShouldPopulateFieldsWithValues(DataTable arg1) throws Throwable {
        List<Map<String,String>> data=arg1.asMaps(String.class,String.class);
        //Declare a string variable for NAME and assign it's value
        String profileNameTextboxValue = data.get(0).get("FieldValue");
        //Find the profile NAME text box
        WebElement profileNameTextbox = driver.findElement(By.id("name"));
        //Clear the value from the profile NAME text box
        profileNameTextbox.clear();
        //Send the string value to the profile NAME text box
        profileNameTextbox.sendKeys(profileNameTextboxValue);

        //Declare a string variable for EMAIL and assign it's value
        String profileEmailValue = data.get(1).get("FieldValue");
        //Find the profile EMAIL text box
        WebElement profileEmailTextbox = driver.findElement(By.id("email"));
        //Clear the value from the profile EMAIL text box
        profileEmailTextbox.clear();
        //Send the string value to the profile EMAIL text box
        profileEmailTextbox.sendKeys(profileEmailValue);

        //Declare a string variable for PHONE1 and assign it's value
        String profilePhone1Value = data.get(2).get("FieldValue");
        //Find the profile PHONE1 text box
        WebElement profilePhone1Textbox = driver.findElement(By.id("phone"));
        //Clear the value from the profile PHONE1 text box
        profilePhone1Textbox.clear();
        //Send the string value to the profile PHONE1 text box
        profilePhone1Textbox.sendKeys(profilePhone1Value);

        //Declare a string variable for PHONE2 and assign it's value
        String profilePhone2Value = data.get(3).get("FieldValue");
        //Find the profile PHONE2 text box
        WebElement profilePhone2Textbox = driver.findElement(By.id("phone2"));
        //Clear the value from the profile PHONE2 text box
        profilePhone2Textbox.clear();
        //Send the string value to the profile PHONE2 text box
        profilePhone2Textbox.sendKeys(profilePhone2Value);

        //Declare a string variable for SMS Phone and assign it's value
        String profileSMSValue = data.get(4).get("FieldValue");
        //Find the profile sms phone text box
        WebElement profileSMSTextbox = driver.findElement(By.id("sms_phone"));
        //Clear the value from the profile sms phone text box
        profileSMSTextbox.clear();
        //Send the string value to the profile sms phone text box
        profileSMSTextbox.sendKeys(profileSMSValue);

        //Declare a string variable for Fax Number and assign it's value
        String profileFaxValue = data.get(5).get("FieldValue");
        //Find the profile fax text box
        WebElement profileFaxTextbox = driver.findElement(By.id("fax"));
        //Clear the value from the profile fax text box
        profileFaxTextbox.clear();
        //Send the string value to the profile fax text box
        profileFaxTextbox.sendKeys(profileFaxValue);

        //Declare a string variable for Location and assign it's value
        String profileLocationValue = data.get(6).get("FieldValue");
        //Find the profile Location text box
        WebElement profileLocationTextbox = driver.findElement(By.id("location"));
        //Clear the value from the profile Location text box
        profileLocationTextbox.clear();
        //Send the string value to the profile Location text box
        profileLocationTextbox.sendKeys(profileLocationValue);
}

The above code works, but surely there is a more efficient way to write the java class?
I was hoping that I could find a way to iterate through the WebElement variables with the different values from the datatable. Is there anyway to do this?
I found two examples of code, which I will try and adapt but not quite sure how to put it all together..
1st example:
for (Map.Entry<String, String> entry : countries.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        // ...
        }

2nd example :
List<Map<String, Object>> list; // this is what you have already

    for (Map<String, Object> map : list) {
    for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    }
    }

Note: I am new to java / coding, any critique on the code would be helpful..
@homaxto, Taking instruction, I have created the following bean class Person..
public class Person implements java.io.Serializable {

    // Properties
        private String Username;
        private String Name;
        private String Email;
        private String Phone1;
        private String Phone2;
        private String SMS;
        private String Fax;
        private String Location;
        private String Address;
        private String Zip;
        private String PayPal;

    // Getters
        public String getUsername() { return Username; }
        public String getName() { return Name; }
        public String getEmail() { return Email; }
        public String getPhone1() { return Phone1; }
        public String getPhone2() { return Phone2; }
        public String  getSMS() { return SMS; }
        public String getFax() { return Fax; }
        public String getLocation() {return Location; }
        public String getAddress() { return Address; }
        public String getZip() { return Zip; }
        public String getPaypalEmail() { return PayPal; }

    // Setters
    public void setUsername() { this.Username = Username; }
    public void setName() { this.Name = Name; }
    public void setEmail() { this.Email = Email; }
    public void setPhone1() { this.Phone1 = Phone1; }
    public void setPhone2() { this.Phone2 = Phone2; }
    public void setSMS() { this.SMS = SMS; }
    public void setFax() { this.Fax = Fax; }
    public void setLocation() {this.Location = Location; }
    public void setAddress() { this.Address = Address; }
    public void setZip() { this.Zip = Zip; }
    public void setPaypalEmail() { this.PayPal = PayPal; }
}

My datatable is as follows:
Feature: Update my personal details
  As a Property Manager
  I want to update my personal details
  So that I can be reached by my customers

  @wip
  Scenario: Update my personal details
    Given I am logged in to my account
    Given I have navigated to the change profile tab
    When I populate a field with a new value
    | Username | Name        | Email         | Phone1     | Phone2       | SMS   | Fax  | Location         | Address        | Zip  | PayPal |
    | testy    | Test Logger | testerslog1@gmail.com | 04 555 6666 | 0800 123 4567 | 029 295 495 | 04 888 9999 | Bermuda Triangle | 5 Pokemon Lane | 9999 | testersLog1@gmail.com |
    Then I click save

A: I would do something like the following. For this to work you will have to use the ID of the input elements as the value in the first column.
If you have to have less dependencies in your datatable you could map this in your step implementation and look it up before using it.
Also you do not need a header row, and keeping you just need to skip the first row.
@When("^I populate a field with a new value$")
    public void ShouldPopulateFieldsWithValues(DataTable dataTable) throws Throwable {
        List<List<String>> rows = dataTable.asLists(String.class);
        // Either quit having a header in your datatable or remove the first row
        rows.remove(0);
        for (List<String> row : rows) {
            String fieldName = row.get(0);
            String fieldValue = row.get(1);

            // Use the IDs as name in your datatable
            WebElement profileNameTextbox = webdriver.findElement(By.id(fieldName));
            profileNameTextbox.clear();
            profileNameTextbox.sendKeys(fieldValue);
        }
    }

Another way going around this problem could be by turning around the table having the fieldnames as column names.
When I populate a field with a new value
  | Name      | Email address    | Phone 1     | Phone 2       | SMS Phone   | Fax number  | Location         |
  | Joe Blogs | jblogs@gmail.com | 04 555 6666 | 0800 123 4567 | 023 222 333 | 09 888 9999 | Bermuda Triangle |

With this design you can create a bean class "Person" with getters and setters for each column. Cucumber will do the camel-casing and automatically call a method called setEmailAddress() etc. So if the header column is called "Email address" then Cucumber will call a method called setEmailAddress with the value jblogs@gmail.com.
This will give you the following implementation signature
@When("^I populate a field with a new value$")
    public void iPopulateAFieldWithANewValue(List<Person> persons) throws Throwable {
    for (Person p : persons) {
        ...
    }
}

As you might see this easily allows many rows of data.
Which one is best in your situation is entirely up till you, I just wanted to show the other option you have which is not as well documented.


text:
Q: How to pass current location coordinates to the Geo-point that denotes source address in android application I am working on my android project - a GPS based one ???
Actually I got the information of current location, a location marker as the destination address.
Now i want to know how to map this current location as in location address/coordinates to the Geo point functionality in android. The current location would be the source address
and create a route between these two points (source and destination).
Can anyone help me on this???
Thanks