text:
Q: Inserting data into table via Excel VBA I have an excel table and I am trying to automate the deletion of data and insertion of data into an excel table.
I am using this VBA code to remove my data from my table
Sub Macro2()
    Application.ScreenUpdating = False
    Sheets("Report").Select
    ActiveSheet.ListObjects("Report").HeaderRowRange.Select
    'Remove the filters if one exists.
    If ActiveSheet.FilterMode Then
    Selection.AutoFilter
    End If

    With Worksheets("Report").ListObjects("Engagement_report")
        .DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
        .DataBodyRange.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
    End With

End Sub

However, when i try to insert data(about 11 000 rows) into the same table it is very slow and my excel crashes. I am not sure if its because the resize function i does deletes all rows and hence when i insert data again, it is redoing the range and hence its slow.
Does anyone have any suggestions to help in this?
Appreciate your help

A: Public Sub addDataToTable(ByVal strTableName As String, _
   ByVal strData As String, ByVal col As Integer)

 ActiveSheet.Table(strTableName).Select
 If strTableName.Rows.Count = 1 Then
     strTableName(Row, col).Value = strData
 Else
     strTable(LastRow, col).Value = strData
 End If
End Sub

NB : I think this will be helpful to you.

A: This sample code will help you to insert multiple rows.
Sub InsrtRw2()
Dim c As Range, fst As Range, c2 As Range

Set c = Cells.Find("Test", MatchCase:=False, _
lookat:=xlWhole, LookIn:=xlValues)

If Not c Is Nothing Then
c(2).EntireRow.Resize(10).Insert

Set fst = c

again:

Set c2 = Cells.FindNext(c)

If Not c2 Is Nothing Then

If c2.Address <> c.Address _
And c2.Address <> fst.Address Then

c2(2).EntireRow.Resize(10).Insert

Set c = c2

GoTo again

End If
End If
End If

End Sub


text:
Q: ¿Hay alguna forma de hacer una subconsulta en un INSERT INTO SELECT , entre el SELECT y el FROM?
Se que una solución es esta:
insert into votos (usuario,cancion,fecha)select usuario,cancion,curdate()from votos where fecha="2022-10-03";

Pero quiero saber si hay alguna posibilidad de hacer subconsultas entre la SELECT y el FROM, tal que así(se que no es correcta la sintaxis siguiente pero para que me entendáis):
insert into votos (usuario,fecha,cancion)

select (select usuario from votos where fecha="2022-10-03"),curdate(),

 (select cancion from votos where fecha="2022-10-03") from votos;

A: Si es posible tienes que encerrar tu SELECT entre parentesis
SELECT
(SELLECT ....)

A: Hola puedes hacerlo asi
insert into votos (usuario,fecha,cancion) select usuario, curdate(), cancion  from votos where fecha="2022-10-03"

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to declare a type that matches any function in Standard ML? I'm trying to declare a record type that has two entries, one named id that is a string, and another named algorithm that can be any function.
According to what I've investigated, I need to use parametric polymorphism to declare the type of the algorithm entry in the record. Something like this:
type subject = {algorithm: 'a -> 'b, id: string}

But this yields the following error
subject.sml:1: error: 'a has not been declared in type declaration
subject.sml:1: error: 'b has not been declared in type declaration

How can one declare a function type that matches any function? Is using "alpha" and "beta" types the correct way to do this? If so, how does one refer to these types? If not, how is this achieved? Is there a type like bool or real that just means "all functions" or "any function"?

A: There's no type that means "any function"; for example, int -> real and string -> bool are completely separate types, and there's no way to create a type that's ambiguous between the two of them.
However, you can create a type function that takes two types and returns the appropriate record type:
type ('a, 'b) subject = {algorithm: 'a -> 'b, id: string}

After the above declaration, (int, real) subject (for example) will mean {algorithm: int -> real, id: string}.

Is using "alpha" and "beta" types the correct way to do this? If so, how does one refer to these types?

Yes — "alpha" and "beta" are just how you pronounce 'a and 'b, respectively. They're not a separate concept. :-)


text:
Q: What does the underscore mean in $this->_objectProperty? I have encountered an instance where object properties look like this:
$this->property

and this:
$this->_property

What does the _ mean before ->? What difference does it make in terms of coding?

A: Usually it is used for reminding the variable/function is private.


text:
Q: C:HTTP webserver - the image "http://localhost.... cannot be displayed because it contains errors It's my first time dabbling with socket programming and I stumbled upon this amazing code from https://dzone.com/articles/web-server-c.
WHAT WE NEED TO DO: implement a simple HTTP web server that uses the web browser(input from the user) as a client
Here it is:
 /*
 * WebServer.c
 *
 *  Created on: Nov 3, 2012
 *      Author: pavithra
 *
 * A web server in C language using only the standard libraries.
 * The port number is passed as an argument.
 *
 */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/sendfile.h>

#define EOL "\r\n"
#define EOL_SIZE 2

typedef struct {
 char *ext;
 char *mediatype;
} extn;

//Possible media types
extn extensions[] ={
 {"gif", "image/gif" },
 {"txt", "text/plain" },
 {"jpg", "image/jpg" },
 {"jpeg","image/jpeg"},
 {"png", "image/png" },
 {"ico", "image/ico" },
 {"zip", "image/zip" },
 {"gz",  "image/gz"  },
 {"tar", "image/tar" },
 {"htm", "text/html" },
 {"html","text/html" },
 {"php", "text/html" },
 {"pdf","application/pdf"},
 {"zip","application/octet-stream"},
 {"rar","application/octet-stream"},
 {0,0} };
//find webroot, add design
/*
 A helper function
 */
void error(const char *msg) {
 perror(msg);
 exit(1);
}

/*
 A helper function
 */
int get_file_size(int fd) {
 struct stat stat_struct;
 if (fstat(fd, &stat_struct) == -1)
  return (1);
 return (int) stat_struct.st_size;
}

/*
 A helper function
 */
void send_new(int fd, char *msg) {
 int len = strlen(msg);
 if (send(fd, msg, len, 0) == -1) {
  printf("Error in send\n");
 }
}

/*
 This function recieves the buffer
 until an "End of line(EOL)" byte is recieved
 */
int recv_new(int fd, char *buffer) {
 char *p = buffer; // Use of a pointer to the buffer rather than dealing with the buffer directly
 int eol_matched = 0; // Use to check whether the recieved byte is matched with the buffer byte or not
 while (recv(fd, p, 1, 0) != 0) // Start receiving 1 byte at a time
 {
  if (*p == EOL[eol_matched]) // if the byte matches with the first eol byte that is '\r'
    {
   ++eol_matched;
   if (eol_matched == EOL_SIZE) // if both the bytes matches with the EOL
   {
    *(p + 1 - EOL_SIZE) = '\0'; // End the string
    return (strlen(buffer)); // Return the bytes recieved
   }
  } else {
   eol_matched = 0;
  }
  p++; // Increment the pointer to receive next byte
 }
 return (0);
}

/*
 A helper function: Returns the
 web root location.
 */
char* webroot() {
 // open the file "kill.txt" for reading
 FILE *in = fopen("kill.txt", "rt");
 // read the first line from the file
 char buff[1000];
 fgets(buff, 1000, in);
 // close the stream
 fclose(in);
 char* nl_ptr = strrchr(buff, '\n');
 if (nl_ptr != NULL)
  *nl_ptr = '\0';
 return strdup(buff);
}

/*
 Handles php requests
 */
void php_cgi(char* script_path, int fd) {
 send_new(fd, "HTTP/1.1 200 OK\n Server: Web Server in C\n Connection: close\n");
 dup2(fd, STDOUT_FILENO);
 char script[500];
 strcpy(script, "SCRIPT_FILENAME=");
 strcat(script, script_path);
 putenv("GATEWAY_INTERFACE=CGI/1.1");
 putenv(script);
 putenv("QUERY_STRING=");
 putenv("REQUEST_METHOD=GET");
 putenv("REDIRECT_STATUS=true");
 putenv("SERVER_PROTOCOL=HTTP/1.1");
 putenv("REMOTE_HOST=127.0.0.1");
 execl("/usr/bin/php-cgi", "php-cgi", NULL);
}

/*
 This function parses the HTTP requests,
 arrange resource locations,
 check for supported media types,
 serves files in a web root,
 sends the HTTP error codes.
 */
int connection(int fd) {
 char request[500], resource[500], *ptr;
 int fd1, length;
 if (recv_new(fd, request) == 0) {
  printf("Receive Failed\n");
 }
 printf("%s\n", request);
 // Check for a valid browser request
 ptr = strstr(request, " HTTP/");
 if (ptr == NULL) {
  printf("NOT HTTP !\n");
 } else {
  *ptr = 0;
  ptr = NULL;

  if (strncmp(request, "GET ", 4) == 0) {
   ptr = request + 4;
  }
  if (ptr == NULL) {
   printf("Unknown Request ! \n");
  } else {
   if (ptr[strlen(ptr) - 1] == '/') {
    strcat(ptr, "test.html");
   }
   strcpy(resource, webroot());
   strcat(resource, ptr);
   char* s = strchr(ptr, '.');
   int i;
   for (i = 0; extensions[i].ext != NULL; i++) {
    if (strcmp(s + 1, extensions[i].ext) == 0) {
     fd1 = open(resource, O_RDONLY, 0);
     printf("Opening \"%s\"\n", resource);
     if (fd1 == -1) {
      printf("404 File not found Error\n");
      send_new(fd, "HTTP/1.1 404 Not Found\r\n");
      send_new(fd, "Server : Web Server in C\r\n\r\n");
      send_new(fd, "<title>404 Not Found</title>");
      send_new(fd, "
404 Not Found: The requested resource could not be found!
\r\n");
      //Handling php requests
     } else if (strcmp(extensions[i].ext, "php") == 0) {
      php_cgi(resource, fd);
      sleep(1);
      close(fd);
      exit(1);
     } else {
      printf("200 OK, Content-Type: %s\n\n",
    extensions[i].mediatype);
      send_new(fd, "HTTP/1.1 200 OK\r\n");
      send_new(fd, "Server : Web Server in C\r\n\r\n");
      if (ptr == request + 4) // if it is a GET request
    {
       if ((length = get_file_size(fd1)) == -1)
    printf("Error in getting size !\n");
       size_t total_bytes_sent = 0;
       ssize_t bytes_sent;
       while (total_bytes_sent < length) {
    //Zero copy optimization
    if ((bytes_sent = sendfile(fd, fd1, 0,
      length - total_bytes_sent)) <= 0) {
     if (errno == EINTR || errno == EAGAIN) {
      continue;
     }
     perror("sendfile");
     return -1;
    }
    total_bytes_sent += bytes_sent;
       }
//why is it not appearing up to 11:30
      }
     }
     break;
    }
    int size = sizeof(extensions) / sizeof(extensions[0]);
    if (i == size - 2) {
     printf("415 Unsupported Media Type\n");
     send_new(fd, "HTTP/1.1 415 Unsupported Media Type\r\n");
     send_new(fd, "Server : Web Server in C\r\n\r\n");
     send_new(fd, "<title>415 Unsupported Media Type</title>");
     send_new(fd, "
415 Unsupported Media Type!
");
    }
   }

   close(fd);
  }
 }
 shutdown(fd, SHUT_RDWR);
}

int main(int argc, char *argv[]) {
 int sockfd, newsockfd, portno, pid;
 socklen_t clilen;
 struct sockaddr_in serv_addr, cli_addr;

 if (argc < 2) {
  fprintf(stderr, "ERROR, no port provided\n");
  exit(1);
 }
 sockfd = socket(AF_INET, SOCK_STREAM, 0);
 if (sockfd < 0)
  error("ERROR opening socket");
 bzero((char *) &serv_addr, sizeof(serv_addr));
 portno = atoi(argv[1]);
 serv_addr.sin_family = AF_INET;
 serv_addr.sin_addr.s_addr = INADDR_ANY;
 serv_addr.sin_port = htons(portno);
 if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
  error("ERROR on binding");
 listen(sockfd, 5);
 clilen = sizeof(cli_addr);
 /*
  Server runs forever, forking off a separate
  process for each connection.
  */
 while (1) {
  newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
  if (newsockfd < 0)
   error("ERROR on accept");
  pid = fork();
  if (pid < 0)
   error("ERROR on fork");
  if (pid == 0) {
   close(sockfd);
   connection(newsockfd);
   exit(0);
  } else
   close(newsockfd);
 } /* end of while */
 close(sockfd);
 return 0; /* we never get here */
}

NOTE: the kill.txt contains the directory of the server, the files(jpegs, gifs, etc.: /home/user/Desktop)
PROBLEM:
1. After I compile the program and execute it on my web browser as "localhost:port number/file" this is what appears on my web browser:
 the image "http://localhost.... cannot be displayed because it contains errors.

And this is what appears on my terminal:
GET /sample5.gif HTTP/1.1
Opening "/home/user/Desktop/sample5.gif"
200 OK, Content-Type: image/gif

GET /favicon.ico HTTP/1.1
Opening "/home/user/Desktop/favicon.ico"
404 File not found Error

*

*How do I fix this? Any help/comment would be greatly appreciated! Thanks.

*Where is that favicon.ico bit coming from? /I looked this up and apparently having that favicon.ico bit is quite normal (can somebody please confirm this?)/

A:
… I stumbled upon this amazing code from …

It is indeed amazing how bad it is.

*

*At the end of the function int connection(int fd) there's:
   close(fd);
  }
 }
 shutdown(fd, SHUT_RDWR);
}

Browsers don't like the connection being reset by peer (due to close()) before it's tidily shut down. Move the close() after the shutdown().

*The program neglects to reap child processes, thus a zombie process remains after each request. #include <signal.h> and add sigignore(SIGCHLD); at the start of main().

If the action for the SIGCHLD signal is set to SIG_IGN, child
    processes of the calling processes will not be transformed into zombie
    processes when they terminate.


text:
Q: Пул коннектов к базе и сервлет Есть простой сервлет, выполняет post/get-запросы по нажатию на разные кнопки на JSP-страничке. Эти кнопки вызывают методы, которые взаимодействуют с базой данных (типа добавить/считать какие-то значения по ключам). В классе, где представлена реализация этих методов создается пул коннектов к базе (c3p0 DataSource).
Но при запуске севрлета и попытке просто считать значения ругается на этот самый пул коннектов. Т.е. пишет какие-то эксепшены типа - не могу создать пул коннектов и все в таком роде. Тоже самое ругается на логирование...
Нужно ли этот пул коннектов и логирование как-то указывать в web.xml? Есть ли какие-нибудь примеры, как это правильно делать для подобных проектов?


text:
Q: Visualize data for vector tiles in mbtiles format on private web server The question
I upoaded a mbtiles file to a private webserver, but can't get the data to visualize in a webbrowser. If I open the file, a download dialog appears. So what is missing is a renderer to create the tiles as webmap.
I am new to creating and serving vector tiles, so I probably miss something very basic. Apart from uploading the mbtiles file to a web server, what else is needed to view this data in a webmap?
What I tried
I have a vector layer I exported from QGIS with Write Vector Tiels (MBTiles). In the Browser Panel, I can then define a new Vector Tiles connection to the locally stoered mbtiles file to load the data to QGIS. This works well.
I then uploaded the mbtiles file to a personal web server and tried to connect to this, instead of [local_file_path]\filename.mbtiles using the URL like https://[myserver.tld]/filename.mbtiles This, however, does not work. I get an error message saying "The layer is not a valid layer an can not be added to the map". I can't open the file in a webbrowser, neither. So there seems to be missing something.
Where I'm stuck
I am a bit confused about the difference how raster and vector tiles work. Creating raster tiles with Generate XYZ Tiles (Directory) (see: https://gis.stackexchange.com/a/445566/88814), a separate html file is generated that brings together the separate tiles and allows to view the tiles directly in a webmap. This is implemented in Leaflet.
So I guess I need some kind of webmap renderer as well. Unfortunately, in the create vector tiles tools in QGIS, there is no such option to automatically create a webmap/renderer (the html file created by QGIS).
So how do I implement this?


text:
Q: So I'm having this problem with rejecting decimals from ((a % 1) != 0) So im having a problem with rejecting decimals, Im rejecting any characters but when it comes to decimals it just seems not to be working.  ((a % 1) != 0) was the equation i used
Also, I'm having a problem with the do loop, when the user inputs 'y' or 'Y' it seems to double the last value that was recorded from the previous test. I'm a freshman just trying to learn more so please help me out, guys.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int whatItDoes(int* a, int* b)
{
    int temp = *a;
    *a = *b * 10;
    *b = temp * 10;
    return *a + *b;
}

int main()
{

    int a;
    int b;
    bool input1 = false;
    bool input2 = false;
    double temp;
    char again;

    cout << "------------------" << endl;
    cout << "solovesa WELCOME " << endl;
    cout << "------------------" << endl;

    do
    {

            while (!input1)                                 //Validation
            {

                cout << "First integer: ";
                string line;
                cin >> line;
                istringstream is(line);
                char dummy = '\0';                           //null termination char marks end of string

                if (!(is >> a) || (is >> ws && is.get(dummy)))           //ws meaning
                {
                    cout << " " << endl;
                    cout << "WARNING: Characters are not allowed" << endl;
                    cout << " " << endl;
                }
                else
                    input1 = true;

 if ((a % 1) != 0)
                {
                    cout << " " << endl;
                    cout << "WARNING: Decimals are not allowed" << endl;
                    cout << " " << endl;

                }
                else
                    input1 = true;
            }

            while (!input2)                                  //Validation
            {

                cout << "Second integer: ";
                string line;
                cin >> line;
                istringstream is(line);
                char dummy = '\0';                           //null termination char marksd end of string
                if (!(is >> b) || (is >> ws && is.get(dummy)))           //ws meaning
                {
                    cout << "Characters are not allowed" << endl;;
                }
                else
                    input2 = true;
            }

            cout << "   " << endl;

            whatItDoes(&a, &b);
            cout << "Final: " << (a + b) << endl;
            cout << " " << endl;

            cin.clear();

            //repeat program prompt

            cout << "Would u like to do another set ? (Y/N)";               //ask user if they want to repeat
            cin >> again;
            //if they say no then exits program but if yes it repeats to top program

    }
    while (again == 'Y' || again == 'y');

    system("pause");
    return 0;
}
``````

A: Recommendation:
pass a and b by ref.
int whatItDoes(int* a, int* b) --> int whatItDoes(int& a, int& b)

Your Question:
if I understand your code correctly - an ascii character '.' translates to the numeric value of 46 (google Ascii table). So, 46 % 1 == 0.
You can explicitly check for the decimal, if( (a % 46) == 0 ), but be careful, as 0 % 46 == 0 (but character zero ('0') has a numeric value of 48 ).
Consider what I mentioned about the ASCII table and the numeric values of a char.


text:
Q: Manipulando valores de array em PHP Estou armazenando um array em uma session, mas não estou conseguindo manipulá-lo. Como eu faço para somar todos os valores do array?
eu tentei desta forma:
$item = $_SESSION['item'];
$total = 0;
foreach($item as $x) {
    $total += $x;
}
echo $total;
exit();

porém, o retorno é:
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\quiz_Acaro\final.php on line 70
0

A: Esse erro significa que você esta tentando iterar em um elemento que não é um array.
Primeiro voce precisa saber/garantir que o valir do item é um array
$item = $_SESSION['item'];
$total = 0;

if(is_array($item)){
    foreach($item as $x) {
        $total += $x;
    }
    echo $total;
}else{
    echo 'Ops! Esse item nao é um array';
}
exit();

A: O erro Invalid argument supplied for foreach() Acontece quando você passa no foreach um valor não iterável.
Sendo assim, você deveria ter uma verificação se realmente o valor $_SESSION['item'] pode ser iterado:
if (isset($_SESSION['item']) && is_array($_SESSION['item']) {

     // Resto do seu código aqui
}

Eu optei por usar isset, porque se você usar is_array diretamente, será emitido um E_NOTICE, caso o índice 'item' da array não exista.


text:
Q: Android Emulator boots up with flashy 'Android' but the application never starts up and I wont see any Home Screen Android Emulator  boots up with flashy 'Android' but the application never starts up and I wont see any Home Screen even after waiting for 30 min. I use PC of RAM 2 GB still I am unable to see the hOme screen on Emullator.. The Console is as
[2012-02-26 17:36:52 - SDK Manager] Created AVD 'GingerBread2.3.3' based on Android             2.3.3, ARM (armeabi) processor,
[2012-02-26 17:36:52 - SDK Manager] with the following hardware config:
[2012-02-26 17:36:52 - SDK Manager] hw.lcd.density=160
[2012-02-26 17:36:52 - SDK Manager] vm.heapSize=24
[2012-02-26 17:36:52 - SDK Manager] hw.ramSize=256
[2012-02-26 17:37:11 - test_ball_handler] New emulator found: emulator-5554
[2012-02-26 17:37:11 - test_ball_handler] Waiting for HOME ('android.process.acore') to   be launched...
[2012-02-26 17:42:00 - test_ball_handler] ------------------------------
[2012-02-26 17:42:00 - test_ball_handler] Android Launch!
[2012-02-26 17:42:00 - test_ball_handler] adb is running normally.
[2012-02-26 17:42:00 - test_ball_handler] Performing com.eg.a.Test_ball_handlerActivity activity launch
[2012-02-26 17:42:00 - test_ball_handler] Automatic Target Mode: using existing emulator 'emulator-5554' running compatible AVD 'GingerBread2.3.3'
[2012-02-26 17:42:00 - test_ball_handler] Uploading test_ball_handler.apk onto device 'emulator-5554'
[2012-02-26 17:42:01 - test_ball_handler] Installing test_ball_handler.apk...
[2012-02-26 17:44:15 - test_ball_handler] Failed to install test_ball_handler.apk on device 'emulator-5554!
[2012-02-26 17:44:15 - test_ball_handler] (null)
[2012-02-26 17:44:15 - test_ball_handler] Launch canceled!
[2012-02-26 17:47:56 - test_ball_handler] ------------------------------

A: Try changing the ADB connection timeout.
I think it defaults that to 5000ms and I changed mine to 10000ms to get rid of that problem. If you are in Eclipse, you can do this by going through Window -> Preferences and then it is in DDMS under Android.

A: It's not uncommon for an AVD to be born (or become) corrupt/misbehaving. The solution for that is to make a new AVD (with same settings) and delete the corrupt/misbehaving one.
Another possible problem is AVDs can eat up a lot of your CPU, so if your system is already in struggle-town, chances of AVD booting and running nicely is slim.


text:
Q: Can 'Bend Will' be used on people, animals, etc.? According to wikia:

The second word allows the will of people and animals to be controlled. It makes them temporary allies to the Dragonborn

I have the three words in the shout. Not tried it on dragons yet, but I have tried it on some enemies like Draugr and end bosses in ruins etc. It doesn't work.
Can it actually be done or am I wasting time trying it?

A: According to UESP, the 1st word will let you cleanse All-Maker Stones, the 2nd word will let you force NPCs and creatures to become your allies for 30 seconds, and the 3rd word will allow you to force dragons to be your allies and to ride them.
Draugrs aren't NPCs or creatures, they are animated inanimate objects lacking any will, so it's not surprising they cannot be controlled by the Bend Will shout. Additionally, it only seems to work on NPCs that are hostile and unnamed (guard, bandit).

A: In order for it to work on NPC, it has to be hostile ( don't really know that, its just somthing that has been repeated in sevreal websites ) and what it doesent tell you is that u must hold the shout butten. When u tap it ur avatar will only say the first word, same with unreailing force.


text:
Q: In Kotlin, what's the difference between the terms Coroutine and Continuation? It seems like these two terms are used interchangeably.  Yet, there also seems to be some difference that I'm struggling to put my finger on.  Is there a difference?

A: Coroutines are procedures that take turns doing their task and then suspend to give control to the other coroutines in the group, and resume task.
Continuation is the stack that controls the flow of the program, that allows it to skip into different parts of your program. You could use it to control the flow including coroutine like a global switch.

A: It's true, these two are quite closely related. To resume a coroutine, you actually call continuation.resume().
Each coroutine has its associated continuation object. Actually, you don't need anything else but that object, it contains the complete state of the coroutine.
To a certain degree, Kotlin uses "coroutine" to also include the coroutine dispatcher, which gives the coroutine the knowledge how exactly to suspend itself, where to keep the continuation while suspended, and how to resume (dispatch) it later. But you can also use the Unconfined dispatcher, which is almost as good as no dispatcher at all, and be in total control of resumption with nothing but the continuation object being preserved:
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlin.coroutines.Continuation
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

var continuation: Continuation<Unit>? = null

fun main(args: Array<String>) {
    GlobalScope.launch(Dispatchers.Unconfined) {
        println("Suspending")
        suspendCoroutine<Unit> { cont ->
            continuation = cont
        }
        println("Resumed!")
    }
    println("After launch")
    continuation!!.resume(Unit)
    println("After continuation.resume(Unit)")
}

Here you can see that we reproduced the whole suspend-resume scenario while keeping nothing but the Continuation object.
My conclusion is that, due to the features of Kotlin's coroutine design (especialy the fact that they are stackless), there's a blurry line between the concepts of "coroutine" and "continuation".


text:
Q: Web cam streaming in web application to java server I'm implementing a face based network authentication system and I'm looking for a good solution of how to  stream video over the network. I'd like to get audio&video from user's webcam, display webcam output in user's browser and stream media through (RTP/RTMP/web sockets ?) to my JAVA server (or extra - something supported by Tomcat. That would make things a lot easier).
After several hours of googling I'm really confused and have no idea what would be the cleanest and most effort minimizing solution, additionally supported by multiple browsers. I have no restrictions on which technology to use on client side.
I'm really open to all proposals and looking for opinions on that subject for any of you who has any experience in that subject.


text:
Q: Model binding not working for complex object Introduction
I'm working an an ASP.NET MVC application. I have a pair of controller actions for submitting data and a corresponding view:
RequestsController.cs
public class RequestsController : Controller
{
    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(ViewModel data)
    {
        return View(data);
    }
}

ViewModel.cs
public class ViewModel
{
    public int Data { get; set; }
}

Create.cshtml
@model Request

@{
    ViewBag.Title = "Create";
}

Create

@using (Html.BeginForm())
{
    @Html.ValidationSummary(excludePropertyErrors: true)

    <fieldset>
        <legend>Request</legend>

        @Html.EditorForModel()

            <input type="submit" value="Create" />

    </fieldset>
}

Problem
When the form is submitted with its fields populated, Create(ViewModel) is called with the data parameter set to null.

A: The problem turned out to be that the framework didn't like the parameter in Create being named the same as the property of ViewModel. This can be worked around by renaming the parameter or the property.


text:
Q: Passing mongo data to client in Express I have a form
<form action="/admin/getPublicKey" method="post">

        Contract
        <input type="text" class="form-control" name="publicAddress">

    <button type="submit" class="btn btn-primary">Submit</button>
</form>

and a corresponding route
router.post('/getPublicKey', function(req, res) {
    User.findOne({'local.publicAddress': req.body.publicAddress}, function(err, user) {
        if (err) {
            return done(err);
        } else {
            const publicKey = user.local.publicKey;
            res.send(publicKey);
        }
    });
});

I just want to click the button and get publicKey passed to the client-side. I investigated using res.redirect but realised that wouldn't work after reading answers here since I can't pass variables to it.
With res.send, I get the publicKey back but it changes the page I'm in to one with the publicKey only.
How can achieve this?


text:
Q: How to get native code of flink from apache beam build file? I defined a pipline of stream processing with Apache Beam and I build it for Fling runner.
I got a jar file, but when I extracted the java files, the java code is not a native Flink code.
Though I found some generated code in my classe:
 // $FF: synthetic method
 private static Object $deserializeLambda$(SerializedLambda lambda) {
  String var1 = lambda.getImplMethodName();
  byte var2 = -1;
  switch(var1.hashCode()) {
  case -30470307:
     if (var1.equals("lambda$main$fd9fc9ef$1")) {
        var2 = 1;
     }
     break;
  case -30470306:
     if (var1.equals("lambda$main$fd9fc9ef$2")) {
        var2 = 0;
     }
  }

Is there any generated file with Flink code?
Regards,
Ali


text:
Q: Jenkins master to slave error: Host key verification failed I'm setting up an automation test on Jenkins. I'm trying to run a script remotely from one Linux machine(master machine, same machine as my Jenkins server) and calling a bunch of other scripts on another Linux machine(slave machine). However I'm getting this error on my first ssh command
Host key verification failed.

I'm pretty sure there is no problem for the passwordless connection from master to slave because I've run other tests previously using the same master/slave machine.
I run the exact same command manually on my master and it successfully returned the expected result. I don't know why it just doesn't work for the automation test.
All I wanted to do in this command is to check if a package is already installed (my OS is CentOS 7 for both machines)
ssh ${USERNAME}@${IP_ADDR} 'rpm -qa | grep ${MY_PACKAGE}'

I'm just checking the existence of the package before I proceed to more commands specific to this package.

A: ssh_opts='-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null'

ssh $ssh_opts ${USERNAME}@${IP_ADDR} 'rpm -qa | grep ${MY_PACKAGE}'

Try this in your shell script. It disables the host key verification check for the hosts.

A: Eventually I figured what was wrong with it.
When I was exchanging ssh host key from the two machines, I didn't use root user. However, when the test was running through Jenkins, it was using "sudo" to run the target script on the slave test machine, which  means it was reading a ssh host key from the "known_hosts" file for root user, not the one I configured for the test user account (a non-root user account)!
I merged my two "known_hosts" files for both the test user and the root user, then the problem was fixed because now Jenkins master could access my slave test machine through root user or my test user account.


text:
Q: calloc call fails and code crashes I have a piece of C code as below which crashes at the calloc() call below:
... some code
free (ipl->fldptr);
ipl->fldptr = calloc (flds*4, sizeof(struct fldptr_type));
...some more code

I tried to gdb it and I get the below backtrace at crash:
Program received signal SIGSEGV, Segmentation fault.
0x0000003ade478f94 in _int_malloc () from /lib/libc.so.6
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.7.el6.x86_64 libgcc-4.4.4-13.el6.x86_64 libstdc++-4.4.4-13.el6.x86_64
(gdb) bt
#0  0x0000003ade478f94 in _int_malloc () from /lib/libc.so.6
#1  0x0000003ade4796d8 in calloc () from /lib/libc.so.6
#2  0x0000000000daf00d in myfunction (ipl=0x106f75f0, flds=11)
    at myfile.c:1286

As part of debugging I do following on gdb prompt:
frame 2 to go to that user code stack frame
and print values of variables(flds, pointers(ipl) and they seem ok. No NULL dereferencing apparently.
But still calloc() fails and it crashes there.  This piece of code is executed multiple times successfully previously , but it crashes later when the application has run for some time. (Mem leak ?? tryint to get valgrind run on it, but it so happens that when running under valgrind memcheck tool, behaviour of my code crash is not repeatable)
I am looking for some pointers to help me debug and fix this.
Some info relevant - gcc: 4.4.4 . Red Hat Enterprise Linux server 6.0 64 bit Linux

A: You probably have a corrupted heap, e.g. some memory which has been free-d too early (and still reused), or some buffer overflow (or invalid accesses like ptr[-3])
You should use valgrind to debug such issues.
You might also use Boehm's conservative garbage collector.
And you could also hunt such bugs manually, with gdb. Using the watch gdb command and disabling address space layout randomization should help.
I also suggest to always clear a pointer which you have free-d, so replace everywhere free(x)  with free(x), x=NULL in your code (so if x gets incorrectly dereferenced, you'll get a SIGSEGV immediately).
You might also use a more recent version of GCC (current version is 4.7) with its stack protector feature. See this question.


text:
Q: unsolved inclusion #include  The momentics IDe for BB10 has encountered a problem or at least I believe that al my inclusions appears as unsolved. when I compile the app it compile correctly and everything works pretty well.  But the problem is that I need to import some libraryes like #include  and as long as this libreries are shown as insolved inclusion I cannot declare any object of those types.
Does any one know what can be this and how to solve it.
Things done berofe:
I've tried cleaning the workspace and creating a new project and also the new project works perfectly, also I've tried going to configure add and and some libraries. this works but only works for specific libraries, not at all for  libraries.
Edit 1: As I saw on other posts, I've reinstalled the 10.1 sdk that is the one I need, but no luck

A: In the Workspace's Project Explorer pane, right click the project, and then select Build Configurations -> Set Active -> Simulator-Debug (Just to be sure.)
From menus, Window -> Preferences. In the Preferences dialog's left pane choose C/C++ -> Indexer.
To get intellisense to work when authoring well before making builds, under Indexer options, check boxes Index source files not included in the build, index unused headers, index source and header files opened in editor. And under indexing strategy check both boxes, automatic update and update after every file save.
Finally, under Build configuration for the indexer select the Use active build configuration option (Just to be sure.).
For class declaration in header file, the erratic feedback from IDE will disappear (as of Momentics 2.1.2) only after cpp file for implementation, that includes the header is saved.
If modifying header, after setting up as above, right-clicking on the project in Workspace pane -> Index -> Rebuild should work.


text:
Q: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 on CardView I am getting this error as I am not able to pass my parcelable to another activity. I would like to have the Image and the text from my cardView to be passed onto my new activity for each cardview. However, I am receiving thisd error called java.lang.IndexOutOfBoundsException: Index: 0, Size: 0. Can I please get some help? Thanks.
Here is the error code
    E/AndroidRuntime: FATAL EXCEPTION: main
    Process: android.com.example.weddingappfinale, PID: 12694
    java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
        at java.util.ArrayList.get(ArrayList.java:437)
        at android.com.example.weddingappfinale.MuaActivity$1.onItemClick(MuaActivity.java:55)
        at Adapters.MuaAdapter$MuaViewHolder$2.onClick(MuaAdapter.java:59)
        at android.view.View.performClick(View.java:7125)
        at android.view.View.performClickInternal(View.java:7102)
        at android.view.View.access$3500(View.java:801)
        at android.view.View$PerformClick.run(View.java:27336)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
I/Process: Sending signal. PID: 12694 SIG: 9

Here is my Adapter:

    package Adapters;

import android.com.example.weddingappfinale.MuaView;
import android.com.example.weddingappfinale.R;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class MuaAdapter extends RecyclerView.Adapter<MuaAdapter.MuaViewHolder> implements Filterable {
    private ArrayList<MuaView> mMuaView;
    private ArrayList<MuaView> mMuaViewFull;
    private OnItemClickListener mListener;

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        mListener = listener;
    }

    public static class MuaViewHolder extends RecyclerView.ViewHolder {
        public ImageButton mImageButton;
        public TextView mTextView1;

        public MuaViewHolder(@NonNull View itemView, final OnItemClickListener listener) {
            super(itemView);
            mImageButton = itemView.findViewById(R.id.mua_imageButton);
            mTextView1 = itemView.findViewById(R.id.mua_title);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        int position = getAdapterPosition();
                        if (position != RecyclerView.NO_POSITION) {
                            listener.onItemClick(position);
                        }
                    }
                }
            });

            mImageButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        int position = getAdapterPosition();
                        if (position != RecyclerView.NO_POSITION) {
                            listener.onItemClick(position);
                        }
                    }
                }
            });
        }
    }

    public MuaAdapter(ArrayList<MuaView> muaView) {
       mMuaView = muaView;
    }

    @Override
    public MuaViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.mua_view, parent, false);
        MuaViewHolder mvh = new MuaViewHolder(v, mListener);
        return mvh;
    }

    @Override
    public void onBindViewHolder(@NonNull MuaViewHolder holder, int position) {
        MuaView currentView = mMuaView.get(position);

        holder.mImageButton.setImageResource(currentView.getImageResource());
        holder.mTextView1.setText(currentView.getText1());
    }

    @Override
    public int getItemCount() {
        return mMuaView.size();
    }

    public Filter getFilter() {
        return MuaFilter;
    }

    private Filter MuaFilter = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            List<MuaView> filteredList = new ArrayList<>();

            if (constraint == null || constraint.length() == 0) {
                filteredList.addAll(mMuaViewFull);
            } else {
                String filterPattern = constraint.toString().toLowerCase().trim();

                for (MuaView item : mMuaViewFull) {
                    if (item.getText1().toLowerCase().contains(filterPattern)) {
                        filteredList.add(item);
                    }
                }
            }

            FilterResults results = new FilterResults();
            results.values = filteredList;

            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            mMuaView.clear();
            mMuaView.addAll((ArrayList) results.values);
            notifyDataSetChanged();

        }
    };
}

Here is my Activity:
    package android.com.example.weddingappfinale;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.inputmethod.EditorInfo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

import Adapters.MuaAdapter;
import CustomerActivities.CustomerActivity;

public class MuaActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private MuaAdapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private ArrayList<MuaView> mMuaView = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mua_list);

        getSupportActionBar().setTitle("Make Up Artists");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        ArrayList<MuaView> muaView = new ArrayList<>();
        muaView.add(new MuaView(R.drawable.mua_image, "Shima Matin Bridal Services"));
        muaView.add(new MuaView(R.drawable.photography_image, "Aake Up Artist Pte Ltd"));
        muaView.add(new MuaView(R.drawable.mua_image, "Lake Up Artist 3Pte Ltd"));
        muaView.add(new MuaView(R.drawable.mua_image, "f Up Artist Pte Ltd"));

        // ArrayList

        mRecyclerView = findViewById(R.id.recycler_view_list);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mAdapter = new MuaAdapter(muaView);

        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new MuaAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(MuaActivity.this, CustomerActivity.class);
                intent.putExtra("Customer's Details", mMuaView.get(position));
                startActivity(intent);
            }

        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.search, menu);

        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) searchItem.getActionView();

        searchView.setImeOptions(EditorInfo.IME_ACTION_DONE);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                mAdapter.getFilter().filter(newText);
                return false;
            }
        });
        return true;
    }
}

Here is my NewActivity:
    package CustomerActivities;

import android.com.example.weddingappfinale.MuaView;
import android.com.example.weddingappfinale.R;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class CustomerActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer);
        Intent intent = getIntent();
        MuaView muaView = intent.getParcelableExtra("Customer's Details");

        int imageRes = muaView.getImageResource();
        String line1 = muaView.getText1();

        ImageButton imageButton = findViewById(R.id.image_customer);
        imageButton.setImageResource(imageRes);

        TextView textView1 = findViewById(R.id.title_customer);
        textView1.setText(line1);

    }
}

Here is my Parcelable:
    package android.com.example.weddingappfinale;

import android.os.Parcel;
import android.os.Parcelable;

public class MuaView implements Parcelable {
    private int mImageResource;
    private String mText1;

    public MuaView(int imageResource, String text1) {
        mImageResource = imageResource;
        mText1 = text1;
    }

    protected MuaView(Parcel in) {
        mImageResource = in.readInt();
        mText1 = in.readString();
    }

    public static final Creator<MuaView> CREATOR = new Creator<MuaView>() {
        @Override
        public MuaView createFromParcel(Parcel in) {
            return new MuaView(in);
        }

        @Override
        public MuaView[] newArray(int size) {
            return new MuaView[size];
        }
    };

    public int getImageResource() {
        return mImageResource;
    }

    public String getText1() {
        return mText1;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(mImageResource);
        dest.writeString(mText1);
    }
}

A: for adapter you have given muaView array, which has 4 elements in it.
 mAdapter = new MuaAdapter(muaView);

But in this onClick() you are trying to get element from mMuaView, which is yet empty:
        public void onItemClick(int position) {
            Intent intent = new Intent(MuaActivity.this, CustomerActivity.class);
            intent.putExtra("Customer's Details", mMuaView.get(position));
            startActivity(intent);
        }

so, use same arrayList for initializing adapter and getting data from array when you perform click.


text:
Q: Getting only ONE URL from a "data-srcset" attribute with PHP Simple HTML DOM I'm trying to scrape an image URL from an external website, to use as the src attribute in an image element on my own website.
The issue is, that on the external website, the image URL is nested inside a
picture element, in a source element, where it is then iterated in the "data-srcset" attribute in different sizes. Example:
<picture><source data-srcset="https://imageurl.com 640w, https://imageurl.com 720w, https://imageurl.com 860w"></picture>

I can target the specific element with PHP Simple HTML DOM's find() and store it in a variable. This variable is called $imageselector. I can further target the actual attribute by creating a variable for the data-srcset as such:
$srcset = 'data-srcset';

My final output then looks like the following:
<?php echo $imageselector->$srcset; ?>

This, however, attempts to print everything inside the attribute (of course), which won't be very useful to me.
Does anyone have any ideas of how to only get, say the first URL in the attribute?
(Adding a max-length won't do much good either, since the length of the URL could change at any point)

A: You could take $imageselector->$srcset, split its contents into an array and filter as needed.
$longString = $imageselector->$srcset;
$pics = explode(",", $longString)

Now you have an array containing things such as "https://imageurl.com 640w" so now you can take [1] for example.
$toUse = explode(" ", $pics[1]);
$toUse = $toUse[0]; //to get the useful part of the item

Alternatively, you can also pre-filter the entire array
function getLink($string) {
    return substr($string, 0, strpos($string, " "));
}
//Once you already have the exploded string
$pics = array_filter($pics, "getLink");


text:
Q: Wifi Connection Problems I'm having a WiFi sharing problem.
I'm using my ipad air as a hotspot for my mac osx leporad (which has a airport card). My mac recognizes my ipad but when I click on it nothing happens. so I went to system presences and tried to add a network there and when I get to enter your password, I do that and it says connection timed out or password invaild......(Which I know the password it right)
If my mac can detect my ipad hotspot why won't my mac connect to it?????
Anyone please help me! Also I have a Mac OS X 10.5
Thankx

A: To set up a hot spot on your iPad, start by opening Settings and navigating to General > Network. (Note: you will need to have the Cellular Data connection turned on.)
You can set up your personal hot spot by tapping on the giant setup button, which will check with your carrier to see if the feature is supported, and if it is, allow you to turn the hot spot on. If your carrier doesn't support it, you'll get an alert telling you as much.
Enter a password that has to be minimum 8 characters long.


text:
Q: VBA for Excel WorkSheet_Calculate method with Add-In Solver creates infinite loop I have an excel sheet with a set of about 300 filled out cells: about half data and about half calculations. In cells C5, C6, C7, C8, C9 and C10 I have formulas. If the result in those changes (i.e., if they are recalculated) then I need to run the solver add-in with a particular set of values depending which cell it is. Below is my working code so you see what I mean (I've included the first 2/6 as examples):
Private Sub Worksheet_Calculate()
    Static oldVal
    Static oldVal2
    Static oldVal3
    Static oldVal4
    Static oldVal5
    Static oldVal6

    If Range("C5").Value <> oldVal Then
        oldVal = Range("C5").Value
        SolverOk SetCell:="$F$5", MaxMinVal:=3, ValueOf:=0.1075, ByChange:="$G$5", _
        Engine:=1, EngineDesc:="GRG Nonlinear"
        SolverSolve True
    End If

    If Range("C6").Value <> oldVal2 Then
        oldVal2 = Range("C6").Value
        SolverOk SetCell:="$F$6", MaxMinVal:=3, ValueOf:=0.1075, ByChange:="$G$6", _
        Engine:=1, EngineDesc:="GRG Nonlinear"
        SolverSolve True
    End If

    '...
    '...

End sub

I have two problems. First is that it doesn't seem to only run solver if the cell (i.e., C5) was changed. It runs all of them no matter what is calculated in the workbook. The second and much bigger problem is that when it gets to solver and goes to run it, solver immediately seems to trigger the Worksheet_Calculate method again and so it gets stuck in an infinite loop and crashes.
Any smart workarounds for this?
Thanks so much in advance!

A: Answer found from Tim Williams' answer (https://stackoverflow.com/users/478884/tim-williams): The typical way to handle this is to use Application.EnableEvents = False before doing anything which would trigger a recalculation. don't forget to re-enable events before exiting the procedure.


text:
Q: Schedule several instances of the same action with cron I have a simple cron job set up in wordpress:
add_action( 'event_hook', 'do_this_function');
wp_schedule_single_event( time() + 300, 'event_hook', array('testvariable') );

I use the function do_this_function() to send an email to a user two weeks after they have done a thing.
However, I realize now that 'event_hook' can only be in the cron job queue ONCE at the same time! I need multiple two week count downs to be running at the same time. I am a bit lost on how this can be done.
What is the workaround to this limitation? The only thing that comes to my mind is:
1 Schedule the "event_hook" to run once per day or so.
2 Call a function that will look at the arguments of the "event_hook" cron job. I would put user emails, time when email must be sent and other info in a multidimensional array
3 Iterate the multidimensional array, send email if two weeks have passed, then delete same information from the cron job array
4 Use a separate function for adding the new information from new users to the cron job array when users trigger need for email in two weeks.
Would this work?

A: Uh, I'm really developing a habit of answering my own questions.
Turns out, you CAN queue multiple instaces for the same hook in WP-cron. The data that WP cron uses to separate the instances is the ARGUMENTS. They cannot be the same, or WP refuses to create the new cron job.


text:
Q: Wrong Date value if day or month properties are one digit I am getting wrong date when the value of either day or month properties are less than 2 digits(less than 10) since I have applied Date formatting in Global Asax file as "dd-mm-yyyy" .But i found day,month and year properties are correct for the date object .
Am i missing anything here ?
Thanks in advance
Subin

A: Try "dd-MM-yyyy"
instead of "dd-mm-yyyy"
Lower case mm means minutes. Upper case for months.


text:
Q: Cropping UI images I have a SceneKit view that fills my screen. My goal is to let the user take snapshots of that scene, but the snapshots are not the whole screen, but an inset portion in a UIImageView which is slightly smaller than the screen. Ideally, the user should not notice, the image on top should be identical to the scene behind it.
I have coded this up using snapshot and cropped, but as you can see in the image, the scale ends up way off - see the width of the yellow line, and the size of the windows? It's also not positioned correctly, it's somewhat down and to the left from where it should be - the upper left should be below the line of windows, but you can see it is at the roofline above them. I can't see the original snapshot because the debugger QuickLook refuses to show it.

There's not much code to it, anyone see the problem:
    let background = sceneView.snapshot().cgImage!
    let cropped = background.cropping(to: overlayView.frame)
    UIGraphicsBeginImageContextWithOptions(overlayView.frame.size, false, 1.0)
    let context = UIGraphicsGetCurrentContext()
    context!.setAlpha(0.50)
    context!.draw(cropped!, in: overlayView.bounds)
    let transparent = context!.makeImage();
    UIGraphicsEndImageContext()
    overlayView.image = UIImage.init(cgImage: transparent!, scale: 1.0, orientation: .downMirrored)

I have tried various scales and rects to no avail. I assume this is something very easy.
UPDATE: after several tries I was able to get quicklook to work. The snapshot is indeed the entire background as I would expect. But it is much larger than I would expect too - its 640, 998 while the cropped version is 228, 304. That explains the "zooming". This leads me to believe that the frame size of the inset view is NOT a direct relationship to the image size. Does that ring any bells? Is there some other rect I should be using rather than overlayView.frame?

A: So I assume the problem is that the frame coordinates are in one set of units and the image coordinates are in another. I was able to solve the problem this way:
    let croprect = CGRect(x: overlayView.frame.origin.x * 2, y: overlayView.frame.origin.y * 2 - 45, width: overlayView.frame.width * 2, height: overlayView.frame.height * 2)
    let drawrect = CGRect(x: 0, y: 0, width: overlayView.frame.width * 2, height: overlayView.frame.height * 2)
    let background = sceneView.snapshot()
    let cropped = background.cgImage!.cropping(to: croprect)
    UIGraphicsBeginImageContextWithOptions(drawrect.size, false, 0.0)
    let context = UIGraphicsGetCurrentContext()
    context!.setAlpha(0.50)
    context!.draw(cropped!, in: drawrect)
    let transparent = context!.makeImage();
    UIGraphicsEndImageContext()

I'm extremely curious why I had to adjust the Y starting point to get them to line up, anyone have an idea?


text:
Q: CSS strange div shift Hello I'm trying to develop a status bar for i3wm using electron.
Electronjs is using chromium render engine so my webpage should render as in Chrome.
I want to design UI but i came across strange behavior when one div is placed properly the second one is shifted verticaly.
Why it do this and how to fix it?
Here is my code:
HTML:

        power_settings_new

            settings_backup_restore
             Restart

            power_settings_new
             Wyłącz

CSS:
* {
  user-select: none;
  box-sizing: border-box;
}

body {
  color: #ccc;
  font-family: 'Open Sans', sans-serif;
  font-size: 15px;
  font-weight: 300;
  overflow: hidden;
  padding: 0;
  margin: 0;
  background-color: #181818;
}

p {
  margin: 0;
}

a {
  text-decoration: none;
  color: #ccc;
}

a:hover {
  color: #fff;
}

.module {
  height: 50px;
  position: absolute;
  display: inline-block;
  box-sizing: border-box;
  background-color: green;
}

.slide .hover-icon {
  display: inline-block;
  padding: 13px;
  height: 50px;
  width: 50px;
  background-color: blue;
}

.slide .slider {
  display: inline-block;
  height: 50px;
  background-color: red;
}

https://codepen.io/bulion121/pen/vbBaJM

A: There are two issues here:
1) The browser interprets and sequence of whitespace as a single space character. That is, when the browser sees this:

  a

  b

...it's going to insert a ' ' between those two divs. There are several ways to fix this, including setting font-size: 0 on the parent container, using a float, using a flexBox, and writing your HTML like this:

  a

  b

Personally, I'd go with a flexbox.
2) Because #hover-icon and #slider are inline-blocks, they are affected by vertical-align. On the parent div, set vertical-align: top.


text:
Q: Remove items from array of documents in Spring+Mongo I have a collection of documents like this in a mongo db :
"_id" : ObjectId("592bc37c339e7a23788b4c7c"),
"trips" : [
    {
        "tripGcsId" : "5937f86e339e7a2a58ac3186",
        "tripCounter" : NumberLong(1283),
        "tripRef" : "hjkhjk"
    },
    {
        "tripGcsId" : "5937f914339e7a2a58ac318b",
        "tripCounter" : NumberLong(1284),
        "tripRef" : "fjh"
    }
]

and a method on the server side (Spring+Mongo):
public List<String> removeTripObject( List<String> tripIds )
{
    Query query = Query.query( Criteria.where( "trips" ).elemMatch( Criteria.where( "tripGcsId" ).in( tripIds ) ) );

    Update update = new Update().pullAll( "trips.tripGcsId", new Object[] { tripIds } );
    getMongoTemplate().updateMulti( query, update, "ORDER" );
    return updatedOrders;
}

The parameter tripIds is a list of tripGcsIds to be removed from trips array. The method above gives me the error: Write failed with error code 16837 and error message 'cannot use the part (trips of trips.tripGcsId) to traverse the element.
When I try with the $ operator, as described in other SO answers like this:
public List<String> removeTripObject( List<String> tripIds )
{
    Query query = Query.query( Criteria.where( "trips" ).elemMatch( Criteria.where( "tripGcsId" ).in( tripIds ) ) );

    Update update = new Update().pullAll( "trips.$.tripGcsId", new Object[] { tripIds } );
    getMongoTemplate().updateMulti( query, update, "ORDER" );
    return updatedOrders;
}

i got this error: Write failed with error code 16837 and error message 'Can only apply $pullAll to an array.
I'm not sure how should this pullAll command look like on the server side.

A: You need to use $pull update operator which takes the query to match and delete all the matching rows in embedded array.
Something like
public List<String> removeTripObject( List<String> tripIds ) {
    Query query = Query.query( Criteria.where( "tripGcsId" ).in( tripIds ) );
    Update update = new Update().pull("trips", query );
    getMongoTemplate().updateMulti( new Query(), update, "ORDER" );
    return updatedOrders;
}

Reference
https://docs.mongodb.com/manual/reference/operator/update/pull/#remove-items-from-an-array-of-documents


text:
Q: Sitecore ECM - Unsubscribe from newsletter i'm using Sitecore ECM to handle the newsletter subscribtion, what i want to know are if there are a way to unsubscribe a user from the newsletter through the code -not the unsubscribe link on the sent email-.
i found this function from Sitecore.EmailCampaign.dll
ClientApi.Unsubsribe(string campaignEventId)

but it's asking for a campaign event id which i'm not sure where to find. Looking into the Sitecore ECM documentation also does not provide this information. And i would prefer i don't have to query the database directly to get the id
I'm sure there's much easier way to do this..

A: Try TargetAudience.Unsubscribe().


text:
Q: I try to ftrace open system call but trace record is all about SyS_read I tried to trace the open() system call using this code.
#include <stdio.h>
#include <fcntl.h>

int main()
{
    char *path = "/home/[my account]/text.txt";

    int fd;
    fd = open(path, O_RDWR);

    return 0;
}

And I compiled it with
gcc -o open open.c

And started to Ftrace.
echo SyS_open > set_graph_function

echo SyS_read >> set_graph_function

sh -c 'echo $$ > set_ftrace_pid; echo 1 > tracing_on;
exec /home/[my account]/open'

And what I got with cat trace is only about SyS_read.. There is nothing related to SyS_open..
(I check with cat set_graph_function like below :
root@[server name]:/sys/kernel/debug/tracing# cat set_graph_function
SyS_read
SyS_open

And confirm that SyS_open is not missed.)
# CPU  DURATION                  FUNCTION CALLS
# |     |   |                     |   |   |   |
 17)               |  SyS_read() {
 17)               |    __fdget_pos() {
 17)   0.137 us    |      __fget_light();
 17)   1.285 us    |    }
 17)               |    vfs_read() {
 17)               |      rw_verify_area() {
 17)               |        security_file_permission() {
 17)               |          apparmor_file_permission() {
 17)               |            common_file_perm() {
 17)   0.041 us    |              aa_file_perm();
 17)   0.493 us    |            }
 17)   0.934 us    |          }
 17)   0.040 us    |          __fsnotify_parent();
 17)   0.042 us    |          fsnotify();
 17)   2.843 us    |        }
 17)   3.194 us    |      }
 17)               |      __vfs_read() {
 17)               |        new_sync_read() {
 17)               |          ext4_file_read_iter() {
 17)               |            generic_file_read_iter() {
 17)               |              _cond_resched() {
 17)   0.040 us    |                rcu_all_qs();
 17)   0.387 us    |              }
 17)               |              pagecache_get_page() {
 17)   0.225 us    |                find_get_entry();
 17)   0.573 us    |              }
 17)   0.046 us    |              mark_page_accessed();
 17)               |              _cond_resched() {
 17)   0.040 us    |                rcu_all_qs();
 17)   0.393 us    |              }
 17)               |              touch_atime() {
 17)               |                __atime_needs_update() {
 17)               |                  current_time() {
 17)   0.042 us    |                    current_kernel_time64();
 17)   0.039 us    |                    timespec_trunc();
 17)   0.972 us    |                  }
 17)   1.321 us    |                }
 17)   1.692 us    |              }
 17)   4.990 us    |            }
 17)   5.351 us    |          }
 17)   5.766 us    |        }
 17)   6.161 us    |      }
 17)   0.039 us    |      __fsnotify_parent();
 17)   0.045 us    |      fsnotify();
 17) + 10.735 us   |    }
 17) + 13.187 us   |  }

Why there is only SyS_read even though I write a code with open() ?
I tried to drop caches and did it again but the result was exactly the same.
And also I have know idea why SyS_read showed up despite the fact that I only used open().


text:
Q: Wifi network not discoverable - neighbours' wifi networks seen I'm running into a problem where my wifi adapter occasionally fails to discover my home wifi network. My other devices are able to discover the home wifi network successfully. I also checked that SSID broadcast is enabled on the router.
I'm running a Windows 10 machine with a Realtek 802.11n 2.40 GHz wireless adapter. Rebooting the router helps sometimes, but not always. Rebooting the computer, uninstalling/reinstalling network drivers won't help.
After several weeks of search, I was able to figure out the problem. I thought I'll document the issue and the solution, as it might help others.

A: The problem seems to be with the wifi channel that the router picks to broadcast. My wifi adapter only searches for wifi on channels 1 to 11, but my router was configured to pick channels automatically. If the channels 12 or 13 were picked, the adapter wouldn't be able to discover the network. Changing the router channel to 1 fixed the problem.


text:
Q: F# types or System types with ASP.NET MVC? While building a F# ASP.NET MVC 4 app with the C#/F# template from the VisualStudio gallery, a doubt assaulted me. I have the following model class:
namespace MyApp.Models

open System
open System.ComponentModel.DataAnnotations
open System.Collections.Generic

type Product() =
    [<Key>] member val Id = Guid.NewGuid() with get, set
    [<Required>] member val Name = "" with get, set
    member val Iban = "" with get, set
    member val Categories = new List<ProductCategory>() with get, set

As F# has its own types, in cases like the last one, should we use an F# equivalent (an F# list, a sequence...) or should we use System types? If so, what would be the reasoning?
Thank you very much!

A: As a rule of thumb, I'd go by what language(s) is(are) consuming your models. If it's F# all the way down, go for it. If it's mixed you'll need to be more judicious. As an aside, Option<> and List<> play pretty well with C# (though I find I need type aliases to "clean up" some of the code). Also an F# sequence is just an IEnumerable<>, so no worries there. Also, there's nothing wrong with using arrays and ResizeArray<> (aka System.Collections.Generic.List<>) in F# -- you just have to be mindful of state mutation.


text:
Q: In Django, how to code else statement to reload same page and trigger error message pop-up? I am writing a Django view that should allow users to export selected records to Excel by selecting the records they'd like to export, then clicking an Export button on the Django Admin change list page. I have an if/else statement for this and I'd like my else: to basically reload the same change list page, but trigger a popup window error message if the user clicks "Export" without having selected any records to export. Something like "No records selected to export. Please try again." How would I accomplish this? TIA!

A: You should take a look at the messages documentation. Basically, you should add something like this to your template:
{% if messages %}

    {% for message in messages %}

{% if "html_safe" in message.tags %}{{ message|safe }}{% else %}{{ message }}{% endif %}

    {% endfor %}

{% endif %}

And in your views.py, you could do something like this:
messages.error(request, "This is an error message")
return HttpResponseRedirect(instance.get_absolute_url())

Take the html with a mountain of salt, I'm not good as a frontender/designer.


text:
Q: About builtin command puzzle [root@MGWSDT_FEWS bin]# type cd
cd is a shell builtin
[root@MGWSDT_FEWS bin]# which cd
/usr/bin/which: no cd in (.:/usr/expect/bin:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/real/RealPlayer:/root/bin)

It says that because cd is a builtin command, so 'which cd' failed.
'pwd' is also a builtin command, why 'which pwd' can get its location?
[root@MGWSDT_FEWS ~]# type pwd
pwd is a shell builtin
[root@MGWSDT_FEWS ~]# which pwd
/bin/pwd

A: Understand that for sudo or any other command that is not a shell builtin, when the command terminates, the shell picks up where it left off before the command was run (of course, the shell's current working directory won't change). As such, cd must be a shell builtin; otherwise, when cd terminates, the shell is back to the same old current working directory. In other words, a child process (i.e. an external command) can't change the working directory of the parent process (i.e. the shell).
Courtesy: https://bbs.archlinux.org/viewtopic.php?id=127225

A: cd command is bash's command. (bash built in command)
You can find cd's usage in "man bash & find cd"
Contrary, pwd is standalone command.

A: Builtin commands are internal commands in the shell and has a higher priority over external commands (files). And builtin commands also have lower priority than functions so builtin is actually helpful if you have a function with the same name as the builtin command like this:
function cd {
    if [[ $# -gt 0 ]]; then
        echo "Changing directory to $1."
        builtin cd "$1"
    else
        echo "Changing to default directory."
        builtin cd
    fi
}

cd "/some/where"

As a summary functions gets called first before builtins, and builtins gets called first before binary commands or files. The type command I think would also follow that order when interpreting an argument.

A: There are several instances where "commands" are duplicated, but of course this will depend on your installation.  If you have a shell built-in called pwd then that will be used, but there might be shells (csh) that do not have pwd as a built-in.
printf is a shell built-in for bash and ksh93 but not for ksh88 or csh.
Another (weirder) example is [, which is a shell built-in but (on some systems) a symbolic link to test (which might also be a shell built-in).
Your installation is there to support many shells and other programs, not just bash.

A: cd has to be shell-built-in, because it were a separate process, then the effect of the command would have vanished, after the command exits. (See Sakthi Kumar's answer.)
On the other hand, some other commands like pwd, test are available as binaries, like /bin/pwd, /usr/bin/test... However, for optimization, shell has also implementation of these binaries within /bin/bash itself, so that the overhead of creating a separate process is avoided.
when you call pwd, shell calls its own pwd implementation. You can call the binary /bin/pwd using command pwd instead of just pwd.

A: Commands such as pwd and echo are bash-builtins and also available as external commands.  You can use enable to enable/disable shell builtins.
The following example iillustrates how pwd can be invoked either as a shell-builtin or as external command i.e. /bin/pwd.
$ type pwd
pwd is a shell builtin
$ which pwd
/bin/pwd
$ enable -n pwd
$ type pwd
pwd is /bin/pwd
$ which pwd
/bin/pwd
$ enable pwd
$ type pwd
pwd is a shell builtin
$ which pwd
/bin/pwd


text:
Q: Do jagged contours indicate more spatial variability in a data set? A general question when working with contours, do jagged lines indicate more spatial variability in a data set?
A short background of my problem and objective: I would like to delineate neighborhoods based on historical home prices to create homogenous markets for actively listed homes. I have used the GA extension and chosen the covariance variable and circular model. My data set contains nearly 600 points and returned a regression function of 0.81 with a mean prediction of 1137 or so for home price. I am exporting my filled contour prediction map to GA Contours.

A: A common cause for this is using the wrong resample method when translating your DEM to a different coordinate system.  Nearest Neighbor will produce the effect you describe.  Cubic is a better option for continuous data.


text:
Q: I/O error on GET "Connection refused" during unit test of custom Spring endpoint that hits a default swagger endpoint in a Spring controller I have an endpoint that comes from a gradle dependency, lets say its /v3/doc
I needed to expose an endpoint, lets call it, /v1/info that hits /v3/doc internally, massages, some of the data that comes out, then returns that piece of data to whomever called /v1/info
I wrote the code for it (below i am omitting the massaging part for simplicity), but the unit tests throw the error described during test execution.
My endpoint looks like this:
@RestController
public class MyController {

    @GetMapping("v1/info")
    public @ResponseBody SomePojo swag(HttpServletRequest request) {
        String s = retrieve(request
                                .getRequestURL()
                                .toString()
                                .split("v1")[0] // get the base URL and tack on what i need
                                .concat("v3/doc")
                        );

        return new Gson().fromJson(s, SomePojo.class)
    }

    private String retrieve(String url) {
        return new RestTemplate()
            .getForEntity(url, String.class)
            .getBody();
    }
}

unit test looks like:
@WebMvcTest(MyController.class)
@ActiveProfiles(profiles = "local")
public class MyControllerTest {

@Autowired
private MockMvc mockMvc;

@Test
public void testEndpoint() throws Exception {
    mockMvc.perform(get("/v1/info")
            .contentType(MediaType.APPLICATION_JSON)
            .characterEncoding("utf-8"))
            .andExpect(status().isOk());
}
}

error looks like:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost/v3/doc": Connection refused (Connection refused); nested exception is java.net.ConnectException: Connection refused (Connection refused)
im wondering if it has something to do with the port?? because when i run the app on 8001 i can hit /v3/doc and /v1/info no problem. But as you can see when the unit tests run, there is no port, just localhost. I didnt think that mattered though. Will i have to create some kind of fake mvc stub?

A: You could try not autowiring the MockMvc and instead instantiate it in the setup like:
@Autowired
private WebApplicationContext context;

@Before
public void setUp() {
  mockMvc = MockMvcBuilders
                .webAppContextSetup(context)
                .build();
}

A: Your test context created only around @WebMvcTest(MyController.class). Thats means no another endpoints as well as applications server also did not running in this case. And when you call restTemplate it fails.
In case of you wanna test you should move RestTemplate creation outside method and made @Autowirible for example. After you can easily mock it in your test.
Or in case of your third party service is always available you got error because the port is not defined, but it is look conceptually incorrect for unit test.


text:
Q: How to avoid empty instantiating of custom classes? I'm making a chess program, and I'm trying to optimize my code, wherein I have an abstract base class ChessPiece which has the basic properties Board, Color, and StartPosition. Now in this base class constructor is where I add the instantiated specific piece. Here is that part:
    // ChessPiece.cs
    protected ChessPiece(Square startPosition, PieceColor color, Board board)
    {
        this.StartPosition = startPosition;
        this.CurrentPosition = startPosition;
        this.Color = color;
        this.Board = board;
        this.Board[startPosition] = this;
        // ↑
        // I add the pieces inside the indexer assignment (e.g. pieces.Add(piece)...)
    }

Here is how I add the pieces in the Board class:
    //  Board.cs
    public ChessPiece this[Square square]
    {
        get { ... }
        set
        {
            //  simplified version of how I add pieces
            this._pieces.Add(value);
        }
    }

Now, I setup my board this way:
    // Game.cs
    private void PopulateBoard()
    {
        this.CreateStandardPieces(PieceColor.White);
        this.CreateStandardPieces(PieceColor.Black);
    }

    private void CreateStandardPieces(PieceColor color)
    {
        //  rook
        new Rook(aSquare, color, this.Board);
        //  more initializations here
    }

The sample instantiation new Rook(...) looks weird to me, like it is an empty instantiation. Whereas what actually happens is whenever I instantiate a piece, it is automatically added to the board, as opposed to looking an "empty instantiation".
Now my question is, how should I improve my design as to avoid instantiations to look like this?
Or, is this design accepted as a good OOP design?
EDIT:
added code on how I add the pieces

A: You can see the board as one system and the pieces on it as sub systems. Its strange separation of concerns and coupling to let the subsystem know about the parent system and even mutate its state.
A cleaner way in my opinion is that the board adds the pieces (Or a system above the board).
Read up on Separations of concerns and High cohesion – Low coupling
edit: The piece should only hold info on how it can move on the board. Its up to the board or a system above the board to actually move it


text:
Q: Send file by notification: Pushbullet & Python I was wondering if it was possible to send a file (a photo in my case) by notification using Pushbullet? I have a python script and a photo on my computer, and I'd like for my script to send the image to my phone via notification.
NOTE: I found this previous answer from 7 years ago, but I was wondering if there's an easier/more efficient way of doing it now. Any help is appreciated, thank you.


text:
Q: Mingw error starting process. cannot run program c:\users\desktop\file\c: launching failed I just installed eclipse to program in C, I can't run any program, it gives me the following error:
Error starting process.
Cannot run program "C: \ Users \ Francesco \ Desktop \ File \ FrancescoLomazzo \ Esercitazione_2_21_Ottobre.c": Launching failed
Error in final launch sequence.
While if I try to debug a program it gives me the following error:
Failed to execute MI command:
-file-exec-and-symbols C:/Users/Francesco/Desktop/File/FrancescoLomazzo/Esercitazione_2_21_Ottobre.c
How do I solve this problem? Thank you so much.


text:
Q: Difference between SAM and anonymous functions I have recently stumbled upon SAM (single abstract method) concept in Java.
I program in Scala and to me, they look the same as anonymous functions (or lambdas), however my IntelliJ suggests me to either use SAM or lambdas in different scenarios.
Example 1:
val x = new Function1[Int, Int] { // here usage of lambda is suggested
  override def apply(x: Int): Int = x * 2
}

Here lambda usage is suggested.
Example 2:
val event: EventHandler[ActionEvent] = new EventHandler[ActionEvent]() { // here usage of SAM is suggested
  override def handle(e: ActionEvent): Unit = {
    println("hi")
  }
}

I struggle to see the difference in syntax between an anonymous function and a SAM. Are there any conceptual or functional differences between the two?

A: The FunctionN types are special in scala, in that an anonymous function is inferred to be of that type automatically. val twice = (x: Int) => x * 2 is inferred to be a Function1[Int, Int], not any other type, unless the expected type is a (different) SAM interface.
If the expected type is a SAM interface -- an interface with a single abstract method -- it will get converted to that type.

A: The syntax is almost the same, the difference is the context.
Function are interfaces supported by language, which allows things like combining 2 functions into one function, are supported by collections etc.
Single Abstract Method is any trait or class which has only one method to implement, and so it would be unambiguous to take this method's signature, turn it into function's signature and let the compiler rewrite such function into an anonymous class instance.
Noticeable differences:

*

*compiler is only able to rewrite function into SAM when you provide types that would make it obvious that you don't want to have a function there instead

*SAM won't be extending function interface, so you won't be able to do e.g. sam1 andThen sam2 unless you somehow add these methods there yourself

*you cannot just take function returned by something and use it as SAM - function syntax has to be used to initialize SAM object, in place it is created

I guess you can think of both of them as the same concept - some trait/class with exactly one abstract method initialized using function syntax - where some FunctionX interface would be the "default" and compiler would inter to it, and some other implementations would require explicit type ascription and be called SAM.
Whether we see SAM as reuse of function syntax, of function as special case of SAM doesn't change the fact that SAM are NOT lambdas/closures/anonymous functions. This name is used only for things intended to be used as functions, that is implementations of function interfaces (Function1, Function2, ..., PartialFunction, etc).


text:
Q: Add rows without overwrite (Python) Colleagues, I have the following excel file. But, when I compile the program again, my data is overwritten. I'd like to put each results of the next compilations in a row. I've seen some examples with append, but I can not make it work. Could someone help me, please? !!
writer = pd.ExcelWriter('output.xlsx')

df = pd.DataFrame({'Function':[Output],'Circuit':[gates],'Cost':[cost]},)

df.to_excel(writer,'Sheet1')

writer.save()

A: I guess there is no direct way to append rows to existing excel
Try this code, it may help
read your excel as dataframe
df1 = pd.read_excel('output.xlsx')

and your defined dataframe
df2 = pd.DataFrame({'Function':[Output],'Circuit':[gates],'Cost':[cost]})

then write both dataframe to excel
df1.to_excel(writer,startrow=0,index=False)
df2.to_excel(writer,startrow=len(df1)+1,header=False,index=False)


text:
Q: celery==5.2.7 rabbitmq:3.11.4 celery stop unexpectedly if apply_async is called with eta set celery==5.2.7
rabbitmq:3.11.4
Python 3.9.16
i am upgrading the 3PP software for my project,   from celery4.x.x to celery 5.2.7
celery stop unexpectedly if apply_async is called with eta set
    @app.task(bind=True)
    def healthcheck_exec(self,**parm):
        ......

    healthcheck_exec.apply_async(None, parm,eta=next_planed_exec_datetime)

i turn on the debug log, no error detail in the log,  only bellows
   [2023-02-03 05:45:07,941: DEBUG/MainProcess] Canceling task consumer...
   [2023-02-03 05:45:09,545: DEBUG/MainProcess] Canceling task consumer...
   [2023-02-03 05:45:09,545: DEBUG/MainProcess] Closing consumer channel...
   [2023-02-03 05:45:09,550: DEBUG/MainProcess] removing tasks from inqueue until task handler finished

i suspect there is a compatibility issue between rabbitmq and celery. no sure anybody met the issue?


text:
Q: .NET: Is it possible to change the format used by double.ToString()? I have some third party code, that invokes double.ToString(). My problem, is that the default double.ToString() implementation replaces the decimal dot with a comma, like so:
49.99.ToString() == "49,99"

This happens, because the default double.ToString() uses CultureInfo.CurrentCulture whereas I need it to be CultureInfo.InvariantCulture. Indeed, observe:
49.99.ToString(CultureInfo.InvariantCulture) == "49.99"
49.99.ToString(CultureInfo.CurrentCulture) == "49,99"

Is there a way to change the current culture to be the invariant one, so that double.ToString() work as I need it to?
I would like to avoid as much as possible tinkering with the third party code, so please, do not suggest me just using the ToString(IFormatProvider) overload instead of the default ToString().
Thanks.

A: You could set the culture info of the current thread which is what is used by default:
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

and if this is a web application you could set the culture and uiCulture attributes of the <globalization> element in your web.config.


text:
Q: How to change change images when click button in sencha I am very new in sencha. So i want display , when click button then change images of previous images.
More about picture:
In this picture, when laod file, then red button present, I want to click Ok button change red to green in same place.

Here is the my code in Main.js: but unable to change:
 {
        xtype: 'image',
        width:33,
        height:33,
        src:'resources/images/online.png'

      },
      {
        xtype: 'button',
        text:'Go Online?',
        cls: 'messagesBtn',
        pressedCls: 'x-button-pressed'
      listeners: {
                tap: function (button, e, eOpts) {

                  //console.log('hello');
                  if (!Ext.device.Connection.isOnline()) {
                      console.log('Connected (' + Ext.device.Connection.getType() + ')');
                      .wishlogbtn
                   {
                   background-image: url('resources/images/Online.png') !important;
                   }

                      }

                else {
                      console.log('Offline');
                      button.setText('Go Offline?');

                    .wishlogbtn
                   {
                   background-image: url('resources/images/Offline.png') !important;
                   }

                              }
                }

      }

In app.css file:
.messagesBtn {
   background: url(resources/images/online.png) no-repeat;
 }

 .messagesBtn.x-button-pressing {
     background: url(../images/offline.png) no-repeat;
 }

I got this error on console:
    Uncaught SyntaxError: Unexpected identifier Main.js:132
Uncaught Error: The following classes are not declared even if their files have been loaded: 'test.view.Main'. Please check the source code of their corresponding files for possible typos: 'app/view/Main.js

A: Have you tried Ext.Img.setSrc()?
Also as a side note I would suggest putting your logic (listeners) into a controller and your css into your scss file. It will make your application much easier to manage over the long haul. There are some really good videos sencha has put together.

A: Use the function addCls
try with this:
button.addCls('your_cls');

or
button.el.addCls('your_cls');

I don't remember very well.
EDIT:
in Sencha api addCls, we can read:

I have : Step -1 in tollbar as
{xtype:'toolbar',items:[{xtype:'label',html:'Step -1'}]}
There is a button somewhere in mypage and when I am clicking on that
  button I am trying to apply this class as follows:
Ext.get("linkid").addCls("inactive"); But its not working at all.
if I am using applyStyles({}) its working. Where is the problem
Thanks Aswini

No answer for this question...


text:
Q: Do we need to know/find/analyze every case {Best, Average and Worst...all} scenarios of an algorithm? In the books about data-structures and algorithms, we often see that they do not analyze every case scenarios of all algorithms.
Some algorithms are discussed along with average case, some are with average and worst case and others are all of best, average and worst.
Why they tend to do that?
Why don't we need to know all cases for all algorithms?

A: Worst case analysis is usually the most useful way to spend a moderate amount of effort analysing an algorithm. Average case is more complicated, because the average case usually depends on how likely different inputs are, so you have to say what the average case is in terms of what the probability is in terms of different inputs. Best case is not very useful because a hope that my program might complete in 1 second does not allow me to plan some activity that will take too long if my program actually takes 3 hours. Knowing that, no matter what, it will complete in five minutes, is much more useful.
Best case also has a problem with programs that store a small number of pre-prepared inputs and outputs, then check the input they get against the pre-prepared inputs. If they get a match, then they respond with the pre-prepared output without doing anything else and so get great - but meaningless - best case behaviour.
There are some cases where worst case analysis is not what you want. Somebody designing an encryption algorithm might want a guarantee that nobody can break it in less than 10 years (unfortunately, typically such guarantees don't exist).

A: Best case is generally useless unless you control the inputs. (i.e. best case is usually an anomalous case). Unless it's easy to compute, it's not worth wasting your time.
Average case: it's what can you expect in general.  Assuming you work with a large range of inputs, this is usually the most useful thing to consider.
Worst case: a decent tie breaker for two algorithms with the same average case, if you deal with arbitrary inputs (especially if they're untrusted - i.e. you're accepting inputs from people on the web).  Also something to consider in design in general - this will come up occasionally.  In general, if you have two algorithms that are O(n) average case, but one is O(n lg n) worst case, and one is O(n^2) - it may influence your decision on which to go with.  Or it may influence your algorithm design.
Example: quick sort v. merge sort. Both are O(n lg n)  Quicksort's worst case is O(n^2), merge sort is (IIRC) still O(n lg n) - but in general, Quicksort tends to be faster if data fits in memory.  Even though it has a costlier worst case, since we KNOW it has a costlier worst case, we can try to mitigate it (median-of-three instead of just a random partition, etc.) and take advantage of the fact that it usually is faster than mergesort.


text:
Q: Switching between tab using activity group it want to  display last activity My question is switching between tab using activity group it want to  display last activity.
I want to show last open/visited screen when we navigate the tab.My one is go to first screen:
This is my maninActivity'
    public class MainActivity extends TabActivity {
    int selectedTab;
    TabHost tabHost ;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tabview);

        TabHost t = getTabHost();
        tabHost = (TabHost)findViewById(android.R.id.tabhost);
        Resources res = getResources();
        TabSpec firstTabSpec = tabHost.newTabSpec("tid1");
        TabSpec secondTabSpec = tabHost.newTabSpec("tid1");
        TabSpec thirdTabSpec = tabHost.newTabSpec("tid1");
        TabSpec fouthTabSpec = tabHost.newTabSpec("tid1");
        /** TabSpec setIndicator() is used to set name for the tab. */
        /** TabSpec setContent() is used to set content for a particular tab. */
        firstTabSpec.setIndicator("Sales",res.getDrawable(R.drawable.ic_tab_artists_grey)).setContent(new Intent(this,SalesActivityGroup.class));
        secondTabSpec.setIndicator("Admin",res.getDrawable(R.drawable.admin)).setContent(new Intent(this,SettingActivityGroup.class));
        thirdTabSpec.setIndicator("Setting",res.getDrawable(R.drawable.ic_tab_artists_grey)).setContent(new Intent(this,SettingActivityGroup.class));
        fouthTabSpec.setIndicator("Inquiry",res.getDrawable(R.drawable.ic_tab_artists_grey)).setContent(new Intent(this,SettingActivityGroup.class));

        tabHost.addTab(firstTabSpec);
        tabHost.addTab(secondTabSpec);
        tabHost.addTab(thirdTabSpec);
        tabHost.addTab(fouthTabSpec);
        tabHost.setCurrentTab(0);
        tabHost.setMinimumHeight(18);
        tabHost.setFadingEdgeLength(5);

    }

    public void onTabChanged(String arg0) {
            selectedTab = tabHost.getCurrentTab();

    }
}

This is my SalesActivityGroup
    public class SalesActivityGroup extends ActivityGroup {

    public static SalesActivityGroup group;
    private ArrayList<View> history;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.history = new ArrayList<View>();
        group = this;

        View view = getLocalActivityManager().startActivity("Sales",
                new Intent(this, SalesRouteActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
                .getDecorView();

        replaceView(view);

    }

    public void replaceView(View v) {
        history.add(v);
        setContentView(v);

    }

    public void back() {
        if (history.size() > 0) {
            history.remove(history.size() - 1);
            if (history.size() > 0) {
                setContentView(history.get(history.size() - 1));
            } else {
                finish();
            }
        } else {
            finish();
        }
    }

    public void backToFirst() {
        int size = history.size();
        while (size > 1) {
            history.remove(size - 1);
            size = history.size();
        }
        setContentView(history.get(0));
    }

    @Override
    public void onBackPressed() {
        SalesActivityGroup.group.back();
        return;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    //  super.onActivityResult(requestCode, resultCode, data);
        Log.i("****" , "requestCode" + requestCode);
        Bundle bundle = data.getExtras();
        String roteCode = bundle.getString("RouteCode");
        Intent intent = new Intent(SalesActivityGroup.this,ListRetailerActivity.class);
        bundle.putString("RouteCode", roteCode);
        intent.putExtras(bundle);
        View view = SalesActivityGroup.group.getLocalActivityManager()
                .startActivity("",intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();
        SalesActivityGroup.group.replaceView(view);
        }

}

This is my calling part in SalesRouteActivity
Intent intent = new Intent(SalesRouteActivity.this, ListRetailerActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("RouteName", keyword);
                        intent.putExtras(bundle);
            View view = SalesActivityGroup.group.getLocalActivityManager().startActivity("", intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();
            SalesActivityGroup.group.replaceView(view);

Same like above code , i have Setting ActivityGroup for next tab
public class SettingActivityGroup extends ActivityGroup {

    // Keep this in a static variable to make it accessible for all the nested
    // activities, lets them manipulate the view
    public static SettingActivityGroup group;

    // Need to keep track of the history if you want the back-button to work
    // properly, don't use this if your activities requires a lot of memory.
    private ArrayList<View> history;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.history = new ArrayList<View>();
        group = this;

        // Start the root activity withing the group and get its view
        View view = getLocalActivityManager().startActivity(
                "Setting",
                new Intent(this, SettingScreenActivity.class)
                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
                .getDecorView();

        // Replace the view of this ActivityGroup
        replaceView(view);

    }

    public void replaceView(View v) {
        // Adds the old one to history
        history.add(v);
        // Changes this Groups View to the new View.
        setContentView(v);

    }

    public void back() {
        if (history.size() > 0) {
            history.remove(history.size() - 1);
            if (history.size() > 0) {
                setContentView(history.get(history.size() - 1));
            } else {
                finish();
            }
        } else {
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        SettingActivityGroup.group.back();
        return;
    }

}

I pasted my code here.
http://pastebin.com/D4fvkGBx
I am facing trouble on this...
Please help me
Where is wrong in my code?
Thanks in advance

A: You need to override
onBackPressed

and set what you want to do by handling the back press button. You can for instance show a previous tab when user presses back or some default tab which you want.

A: in the metoth on create save the tab you using :)
int lastTab;
@Override public void onBackPressed() {
        tabHost.setCurrentTab(lastTab);
        tabHost.setMinimumHeight(18);
        tabHost.setFadingEdgeLength(5);return; }

A: There were some issue in my MainActivity class
  tabHost = getTabHost();
    TabHost.TabSpec spec;
    Intent intent;

    intent = new Intent().setClass(this, SalesActivityGroup.class);
    spec = getTabHost().newTabSpec("Sales").setIndicator("Sales",getResources().getDrawable(R.drawable.sales )).setContent(intent);
    tabHost.addTab(spec);

    intent = new Intent().setClass(this, SettingActivityGroup.class);
    spec = getTabHost().newTabSpec("Admin").setIndicator("Admin",getResources().getDrawable(R.drawable.admin1)).setContent(intent);
    tabHost.addTab(spec);

    intent = new Intent().setClass(this, SettingActivityGroup.class);
    spec = getTabHost().newTabSpec("Setting").setIndicator("Setting",getResources().getDrawable(R.drawable.maintenance)).setContent(intent);
    tabHost.addTab(spec);

    intent = new Intent().setClass(this, SettingActivityGroup.class);
    spec = getTabHost().newTabSpec("Inquiry").setIndicator("Inquiry",getResources().getDrawable(R.drawable.inquiry)).setContent(intent);
    tabHost.addTab(spec);

    tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundResource(R.drawable.selected_tab);

    tabHost.setCurrentTab(0);
    tabHost.setMinimumHeight(18);
    tabHost.setFadingEdgeLength(5);
    tabHost.setFocusable(true);
    tabHost.requestFocus();
    tabHost.setFadingEdgeLength(5);

No need to call findById() here.
Here was wrong  tabHost = (TabHost)findViewById(android.R.id.tabhost);