text:
Q: Son of Suckerfish Menu problem IE6 My menu dropdowns are 'hiding' behind content that appear below the dropdowns. The menu is working fine in Firefox, Opera, Safari, IE8, but not in IE6.
An example of this is on this page - http://marketplace.prettypollution.com/news-events , if you hover over 'Contact Us' in the top menu it is hidden behind the below content.
Any ideas?

A: The 'position: relative;' on the divs below the dropdown menu's were causing the problems (I dont know why though?). I removed them from the divs below and added them to other elements of the site (eg the right div form now has a position of relative rather than the div itself). It all seems to be working ok now.
Thanks

A: Explicitly set the z-index of both the content and the suckerfish, with the suckerfish having the higher value.


text:
Q: Visual Basic 6 - Any libraries exist to allow implementation of multithreading? Are there any libraries that I can import into a VB6 project to enable multi threaded support? I know that there are examples using the Windows API but I was wondering if there are any libraries that already exist that I can just import into my project to allow this functionality in VB6. I have inherited a very complex application in VB6 that one of its tasks is to control a multi-million dollar robotic arm. I need to take this application and make some changes that would benefit greatly if I can add multithreaded support. Converting this application to .NET would be an enormous undertaking (to us a good analogy would be the equivalent of a manned mission to Mars next year). The application includes several custom libraries that perform complex scientific calculations and data analysis. The code has been customized to deliver an impressive processing speed (this is VB6). It would take an enormous amount of resources to migrate to a .NET platform. Executive management indicates it could easily be 8 years before the system is upgraded. I would appreciate any responses.
Note: I did a search before submitting this question and I did see a similar question being asked but the answer to the question directs to the Windows API directly. My question is a bit different. I am asking about libraries that already include this functionality that I can use in this project. That is, libraries that have already done all this work of using the API.

A: There's no library for multithreading that I know of. But asynchronous processing does not necessarily require threads. Desaware have StateCoder, a library for state machines which helps with multi-tasking without multi-threading. A bit like the Aysnc CTP.
Alternatively here is a pretty standard scheme for asynchronous background processing in VB6. (For instance it's in Dan Appleman's book and Microsoft's VB6 samples.) You create a separate ActiveX EXE to do the work: that way the work is automatically on another thread, in a separate process (which means you don't have to worry about variables being trampled).

*

*The VB6 ActiveX EXE object should expose an event CheckQuitDoStuff(). This takes a ByRef Boolean called Quit.

*The client calls StartDoStuff in the ActiveX EXE object. This routine starts a Timer on a hidden form and immediately returns. This unblocks the calling thread. The Timer interval is very short so the Timer event fires quickly.

*The Timer event handler disables the Timer, and then calls back into the ActiveX object DoStuff method. This begins the lengthy processing.

*Periodically the DoStuff method raises the CheckQuitDoStuff event. The client's event handler checks the special flag and sets Quit True if it's necessary to abort. Then DoStuff aborts the calculation and returns early if Quit is True.

This scheme means that the client doesn't actually need to be multi-threaded, since the calling thread doesn't block while "DoStuff" is happening. The tricky part is making sure that DoStuff raises the events at appropriate intervals - too long, and you can't quit when you want to: too short, and you are slowing down DoStuff unecessarily. Also, when DoStuff exits, it must unload the hidden form.
If DoStuff does actually manage to get all the stuff done before being aborted, you can raise a different event to tell the client that the job is finished.
Disclaimer: direct copy of my answer on another question

A: You can certainly call the windows API to implement multi threading, and its not actually that complicated.  However,  the simplest solution would be to expose a .net Com object and implement multi threading through .net.  For complicated already existing functionality you can break the vb6 app into com libraries that can be called by by the multi threaded .net controller.

[Gui]  ┬> [ .net Com Mulit thread controller]  -> [Com exposed VB 6 utility]
       |
       └> [Com exposed VB 6 utility]

A: See the article Using Background Threads with Visual Basic 6 for an elegant answer to the problem.

A: There was a threading library made by elitevb in 2002 which is unfortunately closed now.
But there is an archive of elitevb articles on xtremevbtalk.
In the section System and devices there is a post at the bottom with the threading.dll and sample source code attached, which makes it very easy to implement threading. As far as I remember, there was the problem, that testing it in the IDE crashed the program, but there were no problems running the compiled program.
With the library, you could create threads pretty straitforward:
Dim ReadValuesThread As Thread

Private Sub Form_Load()
    Set ReadValuesThread = New Thread
    ReadValuesThread.StartThread "ReadValues", "None", Me
    ' Public Function StartThread(FunctionName As String, _
    '                             FunctionParameter As Variant, _
    '                             ParentObject As Object) As Long
End Sub

Private Sub ReadValues()
    ' do things
End Sub

Private Sub Form_Unload(Cancel As Integer)
    ' kill thread
    ReadValuesThread.EndThread
End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can i make chat bot appear as live chat using direct line API? <!DOCTYPE html>

    <link href="https://cdn.botframework.com/botframework-webchat/latest/botchat.css" rel="stylesheet" />

I have this code to embed a bot as a live chat using direct Line API instead of the usual iframe but when i put in my directline secrete key, the Bot is occupying the whole web page. I need it to appear by the bottom right of the web page and pop up as a life chat when a user clicks on it. Please someone should guide me in achieving  this. Thanks

A: Your problem is about the way you are displaying your div including the bot:

You can style this div to appear like you want; there are several samples provided on the bot Webchat Github project:

*

*For sidebar display: https://github.com/Microsoft/BotFramework-WebChat/blob/master/samples/sidebar/index.html

*For fullwindow : https://github.com/Microsoft/BotFramework-WebChat/tree/master/samples/fullwindow
I would highly suggest to take a look at the 1st sample which has a demo of narrow, normal and wide div

A: As Nicolas R suggested, you can style the container div
 to position it at bottom right corner of web page. I achieved same requirement in a project, the following sample code works for me, you can refer to it.
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title></title>
    <link href="https://cdn.botframework.com/botframework-webchat/latest/botchat.css" rel="stylesheet" />

Test result:


text:
Q: Access denied for user 'name'@'localhost' (using password: NO) I am trying to create a cron job in which it will send a mail when my inventory stocks are low. The email is just sending me the error code above, even though my database settings are accurate. So here is my code:
<?php

//I just renamed them, but you get the concept
$db_host = "mydbhost";
$db_username = "myusername";
$db_password = "mypassword";
$db_name = "mydatabase";

$conn = mysqli_connect($db_host,$db_username,$db_password,$db_name) or die ('MySQL Not found // Could Not Connect.');

$recipient = "email@email.com";

$result = mysql_query("SELECT prod_count, restock_level FROM mydatabase WHERE prod_count <= restock_level;");
if ($result) {
  $row = mysql_fetch_assoc($result);
  $count = $row['prod_count'];
  $restocklvl = $row['restock_level'];
  if ($count <= $restocklvl) {
    $msg = "Your inventory is currently low. Please restock.";
    mail($recipient, "Inventory check below threshold", $msg);
  }
}
else {
  $msg = "An error occurred while checking inventory: " . mysql_error();
  mail($recipient, "Inventory check error", $msg);
}
?>

What seems to go wrong? Thanks! Here is the image of the email

A: You are currently mixing up the mysqli and mysql querys.  When connecting via mysqli you cannot user functions like mysql_query.
Code should be something along the lines of as a quick example:
$conn = mysqli_connect($db_host,$db_username,$db_password,$db_name)
$result = $conn->query($sql);
$row = $result->fetch_assoc();

You'll have to change any mysql_ methods to the new mysqli in order for it to work correctly.

A:

<?php

//I just renamed them, but you get the concept
$db_host = "mydbhost";
$db_username = "myusername";
$db_password = "mypassword";
$db_name = "mydatabase";

$conn = mysqli_connect($db_host,$db_username,$db_password,$db_name) or die ('MySQL Not found // Could Not Connect.');

$recipient = "email@email.com";

$result = mysqli_query($conn,"SELECT prod_count, restock_level FROM mydatabase WHERE prod_count <= restock_level;");
if ($result) {
  $row = mysqli_fetch_assoc($result);
  $count = $row['prod_count'];
  $restocklvl = $row['restock_level'];
  if ($count <= $restocklvl) {
    $msg = "Your inventory is currently low. Please restock.";
    mail($recipient, "Inventory check below threshold", $msg);
  }
}
else {
  $msg = "An error occurred while checking inventory: " . mysqli_error($conn);
  mail($recipient, "Inventory check error", $msg);
}
?>

try this code.You mix mysql or mysqli code.


text:
Q: How to set default value for a field in Azure Logic Apps' trigger JSON Schema? I'm setting up an Azure Logic Apps Workflow with a trigger, but am currently unable to define default values for such trigger's fields in the JSON Schema.
I have enabled JSON Schema validation and Required fields as described here: https://www.danrigby.com/2018/08/27/enable-schema-validation-and-required-fields-in-logicapps/
My JSON Schema currently looks as follows:
{
    "anyOf": [
        {
            "required": [
                "delay"
            ]
        },
        {
            "required": [
                "startTime"
            ]
        }
    ],
    "properties": {
        "callbackUrl": {
            "type": "string"
        },
        "delay": {
            "default": 0,
            "minimum": 0,
            "type": "integer"
        },
        "startTime": {
            "type": "string"
        }
    },
    "required": [
        "callbackUrl"
    ],
    "type": "object"
}

I've also tried replacing default with defaultValue but without luck.
I expected delay to be populated as 0 when absent, instead it is interpreted as null within Azure Logic Apps Workflow, causing the failure of following boolean conditions such as delay is greater than 0 because they don't expect null values to get evaluated.

A: I believe the JSON Schema is just used for validation here, as it is in many scenarios. The default property is ignored by many implementations as mentioned in the official docs.
Instead, you can use this expression where you need the default value on null
if (equals(triggerBody()?['delay'], null), triggerBody()?['delay'], 0)


text:
Q: Seminorms: Locally Convex Space Problem
Given a vector space $\Omega$.
Consider a family of seminorms:
$$\mathcal{M}\subseteq\{\mu:V\to\mathbb{R}_+\}$$
Regard the local base:
$$\mathcal{B}_0:=\{[0,\varepsilon):\varepsilon>0\}$$
Denote the open cylinders by:
$$B_\mu(\varepsilon):=\mu^{-1}[0,\varepsilon)$$
Then it becomes a locally convex space by:
$$\mathcal{N}_0:=\mathcal{F}\left(\bigcup_{\mu\in\mathcal{M}}\mu^{-1}\mathcal{B}_0\right)$$
Moreover the seminorms become continuous:
$$\mu^{-1}\mathcal{T}(\mathbb{R}_+)\subseteq\mathcal{T}(\Omega)$$
How to prove this step by step?
Attempt
They set up a neighborhood system since:
$$a\in B_\mu(\varepsilon):\quad B_\mu(\varepsilon_a)+a\subseteq B_\mu(\varepsilon)\quad(\varepsilon_a:=\varepsilon-\mu(a)>0)$$
Also it is compatible with addition since:
$$\left\{B_\mu\left(\tfrac{\varepsilon}{2}\right)+a\right\}+\left\{B_\mu\left(\tfrac{\varepsilon}{2}\right)+b\right\}\subseteq B_\mu(\varepsilon)+(a+b)$$
But what about compatibility with multiplication?
$$$$
Moreover for the seminorms by construction:
$$\mu^{-1}\mathcal{N}_0(\mathbb{R}_+)\subseteq\mathcal{N}_0(V)\implies\mu^{-1}\mathcal{T}(\mathbb{R}_+)\subseteq\mathcal{T}(\Omega)$$
That is continuity at zero suffices!
Reference
This is the close-up!

A: This answer is community wiki.
Denote for shorthand:
$$d:\mathbb{R}\to\mathbb{R}_+:d(x):=|x|$$
It is a neighborhood system as:
$$a\in B_\mu(\varepsilon):\quad B_\mu(\varepsilon_a)+a\subseteq B_\mu(\varepsilon)\quad(\varepsilon_a:=\varepsilon-\mu(a)>0)$$
Also it is compatible with addition since:
$$\left\{B_\mu\left(\tfrac{\varepsilon}{2}\right)+a\right\}+\left\{B_\mu\left(\tfrac{\varepsilon}{2}\right)+b\right\}=B_\mu\left(\tfrac{\varepsilon}{2}\right)+B_\mu\left(\tfrac{\varepsilon}{2}\right)+a+b\subseteq B_\mu(\varepsilon)+(a+b)$$
And similarly for multiplication since:
$$\{B_d(\delta)+\lambda\}\{B_\mu(\delta)+a\}=B_d(\delta)B_\mu(\delta)+B_d(\delta)a+\lambda B_\mu(\delta)+\lambda a\subseteq B_\mu(\varepsilon)+(\lambda a)$$
Moreover for the seminorm by construction:
$$\mu^{-1}\mathcal{N}_0(\mathbb{R}_+)\subseteq\mathcal{N}_0(V)\implies\mu^{-1}\mathcal{T}(\mathbb{R}_+)\subseteq\mathcal{T}(\Omega)$$
(See thread on: Continuity)


text:
Q: MQL4: How to read a CSV from a URL I'm using this URL to fetch some content from a Quandl website:
https://www.quandl.com/api/v3/datasets/FRED/PAYEMS.csv?exclude_column_names=true&rows=1&api_key=my_api_key
The Quandl server returns in response to the above request a value of this:
2016-08-01, 144598.0
I need to use the value of 144598.0 within an MQL4 Script, so:
Q1. How do I fetch the content from the URL above to be used within an MQL4 Script?
A very helpful user from SO (https://stackoverflow.com/users/3666197/user3666197) provided the following script (original found at MQL4: Read single value from CSV) (a couple parts added in by myself) to help me achieve this, however, I couldn't get it to work:
// Code created with the help of Stack Overflow question
// https://stackoverflow.com/questions/39279634/mql4-read-single-value-from-csv/39284875#39284875
// Question by p.luck:
// https://stackoverflow.com/users/5551849/p-luck
// Answer by user3666197:
// https://stackoverflow.com/users/3666197/user3666197

void OnStart()
{
     string cookie = NULL,
            headers;
     char   post[],
            result[];
     int    res;

/*   TODO:                                                                             *
 *   Must allow MT4 to access the server URL,                                          *
 *   you should add URL "https://www.quandl.com/api/v3/datasets/FRED/PAYEMS.csv" *
 *   in the list of allowed URLs                                                       *
 *   ( MT4 -> Tools -> Options -> [Tab]: "Expert Advisors" ):                          */

     string aDataSOURCE_URL = "https://www.quandl.com/api/v3/datasets/FRED/PAYEMS.csv";
     string aDataSOURCE_API = "?exclude_column_names=true&rows=1&api_key=my_api_key";

     //-- Create the body of the POST request for API specifications and API-authorization
     ArrayResize( post,
                  StringToCharArray( aDataSOURCE_API, // string   text             |--> [in]  String to copy.
                                     post,            // uchar   &array[]       <--|    [out] Array of uchar type.
                                     0,               // int      start =  0       |--> [in]  Position from which copying starts. Default - 0.
                                     WHOLE_ARRAY,     // int      count = -1       |--> [in]  Number of array elements to copy. Defines length of a resulting string. Default value is -1, which means copying up to the array end, or till terminating '\0'. Terminating zero will also be copied to the recipient array, in this case the size of a dynamic array can be increased if necessary to the size of the string. If the size of the dynamic array exceeds the length of the string, the size of the array will not be reduced.
                                     CP_UTF8          // uint     cp    = CP_ACP   |--> [in]  The value of the code page. For the most-used code pages provide appropriate constants.
                                     )
                  - 1
                  );

//-- Reset the last error code
     ResetLastError();

//-- Loading a html page from Quandl
     int timeout = 5000;                                                //-- Timeout below 1000 (1 sec.) is not enough for slow Internet connection

     res = WebRequest( "POST",              // const string  method            |--> [in]  HTTP method.
                        aDataSOURCE_URL,    // const string  URL               |--> [in]  URL.
                        cookie,             // const string  cookie            |--> [in]  Cookie value.
                        NULL,               // const string  referrer          |--> [in]  Value of the Referer header of the HTTP request.
                        timeout,            //       int     timeout           |--> [in]  Timeout in milliseconds.
                        post,               // const char   &data              |--> [in]  Data array of the HTTP message body
                        ArraySize( post ),  //       int     data_size         |--> [in]  Size of the data[] array.
                        result,             //       char   &result         <--|    [out] An array containing server response data.
                        headers             //       string &result_headers <--|    [out] Server response headers.
                        );
//-- Check errors
     if ( res == -1 )
     {    Print( "WebRequest Error. Error code  = ", GetLastError() );  //-- Perhaps the URL is not listed, display a message about the necessity to add the address
          MessageBox( "Add the address '" + aDataSOURCE_URL + "' in the list of allowed URLs on tab 'Expert Advisors'", "Error", MB_ICONINFORMATION );
          }
     else //-- Load was successfull
     {
          PrintFormat( "The data has been successfully loaded, size = %d bytes.", ArraySize( result ) );

          //-- parse the content ---------------------------------------
          /*
              "2016-08-01, 144598.0"

          */
          //-- consume the content -------------------------------------
          //...

          }
     }

I have added the URL of https://www.quandl.com/api/v3/datasets/FRED/PAYEMS.csvto the list of allowed URLs in MT4.
If I enable AutoTrading and drag the script, named (tutorial7), on to a chart of USDCAD,M1,I get these messages within the Experts tab:

*

*Script tutorial7  USDCAD,M1: loaded successfuly

*tutorial7 USDCAD,M1: initialized

*tutorial7 USDCAD,M1: The data has been successfully loaded, size = 0 bytes

*tutorial7 USDCAD,M1: uninit reason 0
Surely if the "The data has successfully loaded" it shouldn't say "size = 0 bytes"?
Should this script work correctly if I just copy and paste it straight in to the MetaQuotes Language Editor and compile it?
Apart from adding the URL to the allowed URLs in MT4 and copying and pasting this code in to a script, is there anything else I must do?
If so, how?
I am running the above code as a Script not an Expert Advisor; is this okay?
Q2. Can I set the fetched value of 144598.0 as a variable within my script?
I need to make the value of 144598.0 a variable so that it can be compared to another value.
Would something like this work:
void OnStart()
{

... // above code which fetches the value from the .csv URL

double x = 155876.0     // value manually typed in
       y = 144598.0     // value fetched from the .csv URL using the above code
                        // ignores column 1 consisting of 2016-08-01
   if ( x > y ) {
                        // execute code
}

else {
                        // execute other code
}

}

A: A2: YES! This is the easiest part of the journey.A1: BUT!How does it work in practice? How does MetaTrader Terminal actually speak to Quandl, so to get it?
Let me first illustrate the issue of remote, HttpServer-side processing.
There is an easy to prototype program curl ( Linux & DOS versions available ) that will show right inside a terminal window ( or a Windows cmd window ) how the remote HttpServer at Quandl responds to various compositions of the locally assembled requests, communicated over the HTTP-protocol.
Notice, that the just retyped URL produces the whole history to be delivered.
C:\>curl https://www.quandl.com/api/v3/datasets/FRED/PAYEMS.csv
DATE,VALUE
2016-08-01,144598.0
2016-07-01,144447.0
...
..
.
1939-03-01,30280.0
1939-02-01,30101.0
1939-01-01,29923.0

Once we add further parameters to the plain URL, the remote-side ( the HttpServer ) changes the reply to just the one row we are interested in:
C:\>curl -G --data rows=1 --data exclude_column_names=true https://www.quandl.com/api/v3/datasets/FRED/PAYEMS.csv
2016-08-01,144598.0

Cool, looks great, almost the single value we want!
But here the magic comes.
The real interchange ( dialogue ) between the local process ( curl now, but MetaTrader Terminal later ) looks this way ( using a --verbose option in curl commandline ):
C:\>curl --verbose -G --data rows=1 --data exclude_column_names=true https://www.quandl.com/api/v3/datasets/FRED/PAYEMS.csv
*   Trying 54.174.87.84...
* Connected to www.quandl.com (54.174.87.84) port 443 (#0)
* schannel: SSL/TLS connection with www.quandl.com port 443 (step 1/3)
* schannel: checking server certificate revocation
* schannel: sending initial handshake data: sending 70 bytes...
* schannel: sent initial handshake data: sent 70 bytes
* schannel: SSL/TLS connection with www.quandl.com port 443 (step 2/3)
* schannel: failed to receive handshake, need more data
* schannel: SSL/TLS connection with www.quandl.com port 443 (step 2/3)
* schannel: encrypted data buffer: offset 4096 length 4096
* schannel: encrypted data length: 4017
* schannel: encrypted data buffer: offset 4017 length 4096
* schannel: received incomplete message, need more data
* schannel: SSL/TLS connection with www.quandl.com port 443 (step 2/3)
* schannel: encrypted data buffer: offset 4569 length 5041
* schannel: sending next handshake data: sending 318 bytes...
* schannel: SSL/TLS connection with www.quandl.com port 443 (step 2/3)
* schannel: encrypted data buffer: offset 51 length 5041
* schannel: SSL/TLS handshake complete
* schannel: SSL/TLS connection with www.quandl.com port 443 (step 3/3)
* schannel: incremented credential handle refcount = 1
* schannel: stored credential handle in session cache
> GET /api/v3/datasets/FRED/PAYEMS.csv?rows=1&exclude_column_names=true HTTP/1.1
> Host: www.quandl.com
> User-Agent: curl/7.45.0
> Accept: */*
>
* schannel: client wants to read 16384 bytes
* schannel: encdata_buffer resized 17408
* schannel: encrypted data buffer: offset 0 length 17408
* schannel: encrypted data got 653
* schannel: encrypted data buffer: offset 653 length 17408
* schannel: decrypted data length: 623
* schannel: decrypted data added: 623
* schannel: decrypted data cached: offset 623 length 16384
* schannel: encrypted data buffer: offset 0 length 17408
* schannel: decrypted data buffer: offset 623 length 16384
* schannel: schannel_recv cleanup
* schannel: decrypted data returned 623
* schannel: decrypted data buffer: offset 0 length 16384
< HTTP/1.1 200 OK
< Cache-Control: private
< Content-Disposition: attachment; filename=FRED-PAYEMS.csv
< Content-Transfer-Encoding: binary
< Content-Type: text/csv
< Date: Wed, 07 Sep 2016 12:47:20 GMT
< ETag: W/"adfdb97850c493cdd03e2036574bc404"
< Server: openresty
< Vary: Origin
< X-API-Version: 2015-04-09
< X-Content-Type-Options: nosniff
< X-Frame-Options: SAMEORIGIN
< X-Rack-CORS: preflight-hit; no-origin
< X-RateLimit-Limit: 50
< X-RateLimit-Remaining: 42
< X-Request-Id: c609e92d-22d2-40e7-b7d4-cacb07467c76
< X-Runtime: 0.023534
< X-XSS-Protection: 1; mode=block
< Content-Length: 20
< Connection: keep-alive
<
2016-08-01,144598.0
* Connection #0 to host www.quandl.com left intact

Notice the row GET /api/v3/datasets/FRED/PAYEMS.csv?rows=1&exclude_column_names=true
So the magic is to make MetaTrader Terminal to assemble the same, together with allowing the URL in the permitted list in the configuration ( that you have done already in the other post ).
Also might have noticed, that the HTTP GET sends just the <HttpServer_relative_part_of_the.URL>

The magic is in making MQL4 code send the same request as was seen above and get the data back.
WebRequest() has to use HTTP GET as the Quandl HttpServer does not respond to a HTTP POST version of the same request example, returning 0 bytes ( just omit the -G switch from the curl examples above ).
Meeting all the conditions at once should result in receiving 2016-08-01,144598.0 and using:
int    anAmountOfBytesRECVd   = 0;          // how many bytes Quandl sent
string headers_FromHttpSERVER;              // stores as a string
char   anAnswerFromHttpSERVER[];            // stores as a byte-array ( char[] )
double y_value = NULL;

anAmountOfBytesRECVd = WebRequest( "GET",   // MUST use HTTP GET <- Quandl tested
                                    ...
                                    anAnswerFromHttpSERVER,
                                    headers_FromHttpSERVER
                                    );

y_value = StrToDouble( CharArrayToString( anAnserFromHttpSERVER, // [2|0|1|6|-|0|8|-|0|1|,|1|4|4|5|98|.|0]
                                          11,                    //-----------------------^_______________( -1 == TILL EndOfSTRING )
                                          -1
                                          )
                       );


text:
Q: Convert a useReducer function into a hook - React Typescript I have a state updater using useReducer. I would like to make it a hook (strongly typed). Please advice.

interface IState {
  loading: boolean;
  name: string;
}

const initialState: IState = {
  loading: false,
  name: 'Arun'
}

const [state, setState] = useReducer(
  (state: IState, newState: Partial < IState > ) => ({
    ...state,
    ...newState,
  }),
  initialState
);

Please advise on wrapping this function into a hook that is strongly typed.
Thanks.


text:
Q: messages are being sent which I am not aware from my I phone leading to deduction of balance I am not sending smses but am being charged for the sms being sent to some ISD number from my I Phone 4s. The number and message text supposedly sent does not appear in the sent items. How to stop messages being automatically sent to this number from my phone?
Service provider IDEA in UP.
Can anyone help solve this issue please?

A: It's best to contact your carrier for information about charges. They will know the specifics of your contract and options as well as help you by asking some questions like

*

*What version of iOS are you running?

*Are you using iMessage?

Your first step might be disabling SMS on the iPhone and then contacting the carrier to get further instructions. It really depends upon what number is sending the SMS and if you opted in to any subscriptions or got crammed or signed in to SMS on a web service of some sort.


text:
Q: GIT SSL error persist despite recommended fix for Mac OS X Yosemite I continue to get the error: SSL: certificate verification failed (result: 5) (128) on Yosemite despite following all directions found online to fix it.
My current setup (HomeBrew) is:
$ php --version
PHP 5.5.20 (cli) (built: Jan 11 2015 20:00:36)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies

$ curl --version
curl 7.37.0 (x86_64-apple-darwin14.0.0) libcurl/7.37.0 OpenSSL/1.0.1k zlib/1.2.5
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smtp smtps telnet tftp

$ php -i | grep "SSL Version"
SSL Version => OpenSSL/1.0.1

Am I missing something? When I set sslVerify = false the error changes to SSL: CA certificate set, but certificate verification is disabled. I already have the certificate in Key Chain and I can access it in the brower without problems.
I also tried:
$ gnutls-cli -p 7990 **.***.**.**
- Status: The certificate is NOT trusted. The certificate issuer is unknown.
*** PKI verification of server certificate failed...
*** Fatal error: Error in the certificate.
*** Handshake has failed
GnuTLS error: Error in the certificate.

EDIT:
Note that I've also edited my .git > config file in the repo to include the certificate exported from Firefox as such:
[http]
    sslCAInfo=/link/to/certificate.pem

A: check your ~/.gitconfig file
I fixed my problem by temporarily removing the lines mentioning sslCAInfo and sslVerify.
then don't forget to add them later case the certificate is one that you are using it for something else.


text:
Q: Raspberry software protection I have a python script on raspberry pi 3 and I want to secure my script as much as possible. The user can only contact with the touch screen so there is no external hardware like keyboard, mouse etc. What should I take measure against stolen? For example disabling usb ports, encoding script...

A: Everything a Raspberry Pi 3 "knows" is on that little micro-SD card.  The only way to gain some security is to physically secure the device in an enclosure that prevents the user from getting the SD card.  And you need to make your software hard to break into -- difficult for an interpreted language like python -- but made a lot easier if there's no keyboard or other ports available.  Again, protected inside the enclosure.  If the users can literally only get to the touch screen, then I have a hard time imagining how they'd steal your software.


text:
Q: Firestore: cant delete document this is my function for deleting a document in my "files" collection
Future<void> deleteProgram(String id, String program) async {
    try {
      print(id + "----" + program);
      await firestoreInstance.collection("files").doc(program).delete();
      // await firestoreInstance.collection("programs").doc(id).delete();
      print("done");
    } catch (e) {
      print(e);
    }
  }

program is the id of the document, when i use this nothing gets deleted, even if i hardcode the ID.
this is what my collection looks like:

as you can see, each document in the files collection also has a subcollection called files
what am i doing wrong here?

A: The only way to delete a collection is to delete each individual document from it. There is no atomic operation to delete a collection.
In your screenshot the opleiding4 is shown in italic, meaning that this document doesn't really exist, and the Firebase console merely shows that name to be able to show its files subcollection.
Once you delete all files from the /files/opeleiding4/files subcollection both that collection and its parent document will disappear from the Firebase console too.
Also see:

*

*Firestore DB - documents shown in italics

*How to recursively delete collection in firestore?

*How to Delete all documents in collection in Firestore with Flutter


text:
Q: Chapter Name not appearing I wanted to style the chapter name. I referred the following link :
how-to-create-specific-chapter-style-in-book-documentclass
Here is my code:
%Template for Technical Document
\documentclass{book}
\usepackage[explicit]{titlesec}
\usepackage{titlesec}
% Can also use centering, or hcentering

\titleformat{\chapter}[display]
  {\bfseries\Large}
  {\filright\MakeUppercase{\chaptertitlename}\Huge\thechapter}
  {1ex}
  {\titlerule\vspace{1ex}\filleft}
  [\vspace{1ex}\titlerule]

\begin{document}
\chapter{Install Backtrack on an Android Device}
\section{What is Backtrack?}
BackTrack is a distribution designed by Jason Dennis based on the Ubuntu Linux distribution aimed at digital forensics and penetration testing use. BackTrack provides users with easy access to a comprehensive and large collection of security-related tools ranging from port scanners to Security Audit. Support for Live CD and Live USB functionality allows users to boot BackTrack directly from portable media without requiring installation, though permanent installation to hard disk and network is also an option.\par
\end{document}

I get the following output:

After using the explicit option in titlesec and numbering the chapter as per the solution given, I get this output:

A: You're loading the titlesec package twice- only the first instance actually counts, the second one is ignored.
When you use the explicit option for the titlesec package, you have to specify the heading title using #1.
As such, you could use, for example,
\titleformat{\chapter}[display]
  {\bfseries\Large}
  {\filright\MakeUppercase{\chaptertitlename}\Huge\thechapter}
  {1ex}
  {\titlerule\vspace{1ex}\filleft #1}
  [\vspace{1ex}\titlerule]

or else remove the explicit option and simply load the titlesec package using
\usepackage{titlesec}

in which case, you can stick with your original code.


text:
Q: Getting everything about the User that has specific skill, Many-to-Many filtering I am trying to filter users from a database based on their knowledge for example some users know C# others C++ but there are users that know both languages.
My models generate by Database first approach look as such
public partial class Entity
    {
        public Entity()
        {
            Knowledge = new HashSet<Knowledge>();
        }

        public string Username { get; set; }
        public string Passwd { get; set; }
        public string Email { get; set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public string Country { get; set; }
        public string City { get; set; }
        public string Street { get; set; }
        public int Apartment { get; set; }

        public virtual ICollection<Knowledge> Knowledge { get; set; }
    }

    public partial class Knowledge
    {
        public int KnowledgeId { get; set; }
        public string Username { get; set; }
        public string SkillName { get; set; }

        public virtual Skill SkillNameNavigation { get; set; }
        public virtual Entity UsernameNavigation { get; set; }
    }

    public partial class Skill
    {
        public Skill()
        {
            Knowledge = new HashSet<Knowledge>();
        }

        public string SkillName { get; set; }

        public virtual ICollection<Knowledge> Knowledge { get; set; }
    }

As mentioned trying to get for example users only know C# where skill is passed into Controller
                var l = ctx.Entity.Select(
                    c => new Entity()
                    {
                        Knowledge = (ICollection<Knowledge>)c.Knowledge.Where(s => s.SkillName == skill),
                        Username = c.Username,
                        City = c.City,
                        Country = c.Country,
                        Street = c.Street,
                        Email = c.Email,
                        Apartment = c.Apartment
                    }
                    ).ToList();

gives all the users in the database but for users that don't know C#, it returns an empty Knowledge list. The above code gives the same output as below
var l = ctx.Entity.Include(u => u.Knowledge.Where(k => k.SkillName == skill)).ToList();

so I thought maybe based on the latter one I can eliminate Users with Knowledge.Count == 0
var l = ctx.Entity.Include(u => u.Knowledge.Where(k => k.SkillName == skill)).Where(k => k.Knowledge.Count != 0).ToList();

But still, I get the same output, I see there are many posts created related to this problem I went through most of them yet I am still lost.
Thanks to anyone who takes their time to help.
Edit
Essentially SQL Query I am trying to write is as below but I couldn't make it work using FromSqlRaw method or by using LINQ
Edit Changed the query according to advice of @Ceemah Four
SELECT * FROM Entity
LEFT JOIN Knowledge ON Entity.Username = Knowledge.Username
LEFT JOIN Skill ON Knowledge.Skill_name = Skill.Skill_name
WHERE Entity.Username IN (SELECT Entity.Username FROM Entity
                        LEFT JOIN Knowledge ON Entity.Username = Knowledge.Username
                        LEFT JOIN Skill ON Knowledge.Skill_name = Skill.Skill_name
                        WHERE Skill.Skill_name IN ('C#'))


text:
Q: ODT File created from text file take long time to open (10 min) . I keep the file locked somewhere I think on ReadLine Hi I am reading for long time posts on here but first time that I post. I am struggling with an ODT file created that takes a lot to open. I've divided in small chunks and try debugging it but seems to be to the end of the patience.. After several hours of research I may believe that the issue is on reading the txt on ReadLine I am guessing . Your opinion is much appreciated. Here is the snippet of code:
public static void SolveLoadingTime(string path)
{

    string line;
    StreamReader sr = new StreamReader(path);
    line = sr.ReadLine();

... some other code here
    while ((line = sr.ReadLine()) != null)
    {
        entries = line.Split('#');
        string nl = Environment.NewLine;

        Cell cell1 = new Cell(colData1);
        Cell cell2 = new Cell(colData2);
        Cell cell3 = new Cell(colData3);
        Cell cell4 = new Cell(colData4);

        Cell[] cells = new Cell[] { cell1, cell2, cell3, cell4, cell5, cell6, cell7 };
        foreach (var cell in cells)
        {
            cell.Style = "CellStyle1";
        }

        Row row1 = new Row();
        row1.Cells.Add(cell1);
        row1.Cells.Add(cell2);
        row1.Cells.Add(cell3);
        row1.Cells.Add(cell4);
        table1.Rows.Add(row1);
    }


text:
Q: How to create a clone of a String variable? How can the clone of a string variable created?
There is a string variable say str
String str = row.getAttribute("Attribute");

So how can i copy the value of the attribute in the row to the string so that i can show the value even when the row has been erased from the memory.
Thanks.

A: You can do
String newString = new String(oldString);

But what's your reason to clone an immutable string ?
I do this only when I want to trim the extra hidden chars from the original strings when I got my string by using substring.
Regarding you edit :
If you do
String str = row.getAttribute("Attribute");

then str will still contain the exact same value even after you destroy row or you change the attribute "Attribute" of row. You don't need to clone it. The fact that you keep a reference (the variable str) to it keeps it safe from garbaging.

A: In Java the String object is immutable. That means it won't change under you and consequently you can safely use the same reference throughout your program.
If you amend a String (via appending, trimming etc.) then that creates a new, immutable object. So the concept of cloning is redundant in this scenario.


text:
Q: How to loop many objects inside array to collect a specific item? I have this object:
data: [
  {
    name: bed,
    price: [
      {
        id: 2,
        color: red
      },
      {
        id: 4,
        color: blue
      }
    ]
  },
  {
    name: lego,
    price: [
      {
        id: 5,
        color: red
      },
      {
        id: 6,
        color: blue
      }
    ]
  },
  {
    name: mouse,
    price: [
      {
        id: 7,
        color: red
      },
      {
        id: 9,
        color: blue
      }
    ]
  }
]

I want to collect the id prices of each object like this:
ids: [ [ 2, 4 ], [ 5, 6 ], [ 7, 9 ] ]

I tried this but it doesn't work:
ids() {
  const datas = this.data;
  let idPrices = null;
  let prices = [];

  for (let priceId in datas) {
    prices.push(priceId.price);
  }

  idPrices = prices.map((prices) => prices.map((price) => price.id));

  return idPrices;
}

A: Use Array.map:

const data=[{name:"bed",price:[{id:2,color:"red"},{id:4,color:"blue"}]},{name:"lego",price:[{id:5,color:"red"},{id:6,color:"blue"}]},{name:"mouse",price:[{id:7,color:"red"},{id:9,color:"blue"}]}];

const ids = data.map(e => e.price.map(f => f.id));
console.log(ids);

A: Maybe this one helps you? I think it's possible to do it more simple but this is the best i can do at 1:30AM. :)

const data = [
      {name: 'bed', price:[{id: 2 ,color: 'red'}, {id: 4, color: 'blue'}]},
      {name: 'lego', price:[{id: 5 ,color: 'red'}, {id: 6, color:'blue'}]},
      {name: 'mouse', price:[{id: 7 ,color: 'red'}, {id: 9, color: 'blue'}]}
      ]

let idPrices = [];
for (const i in data) {
    let prices = [];

 for (const j in data[i].price) {
  prices.push(data[i].price[j].id)

}
  idPrices.push(prices)

}
console.log(idPrices);


text:
Q: Derive $(1+ \tan^2x= \sec^2x )$ and $(1+\cot^2x = \text{cosec}^2x)$ geometrically.
This a circle through which you have to derive the above given identity.

A: Geometrically, use similar right triangles:

A: As @Ak19 hinted, Pythagoras gives $\sin^2x+\cos^2x=1$. Divide by $\cos^2x$ or $\sin^2x$.

A: Consider this, looking at the image you have provided $\cos x = a$ because the cosine of an angle is the side of the triangle adjacent to it divided by the hypotenuse (longest side).
Given the radius of the circle is $= 1, \cos x = a/1 = a$ using the similar identity of $\sin$ we come to the conclusion that $\sin x = b$.
So as mentioned by the comments and previous answer using the Pythagoras theorem the sum of squaring both a and b should equal to 1 as that is the longest side of the triangle. (the a and b we worked out in the previous step using the identities of sine and cosine)
Now that we have arrived at the conclusion that $\sin^2x+\cos^2x=1$, by dividing the entire equation by $(\cos x)^2$ or $(\sin x)^2$ gives the results $1+\tan^2x=\sec^2x$ and $1+\cot^2x=\operatorname{cosec}^2x$

A: Without words (use Pythagoras).


text:
Q: GeoServer GetCapabilities Not Working I am trying to learn how to use the OpenGeo suite by following the tutorials on the site. The one I'm currently trying to follow is http://workshops.opengeo.org/geoext/stores/capabilities.html.
Most of it works, but I can't get the grid to populate with the layers from GeoServer. This is my code:
<html>
    <head>
        <title>GeoExt Workshop Application</title>
        <link rel="stylesheet" type="text/css" href="ext/resources/css/ext-all.css">
        <script type="text/javascript" src="ext/adapter/ext/ext-base.js"></script>
        <script type="text/javascript" src="ext/ext-all.js"></script>
        <script src="openlayers/lib/OpenLayers.js"></script>
        <script type="text/javascript" src="geoext/lib/GeoExt.js"></script>

        <script type="text/javascript">

        Ext.BLANK_IMAGE_URL = "ext/resources/images/default/s.gif";
        var app, items = [], controls = [];

        Ext.onReady(function() {
            app = new Ext.Viewport({
                layout: "border",
                items: items
            });
        });

        items.push({
            xtype: "gx_mappanel",
            ref: "mapPanel",
            region: "center",
            map: {
                numZoomLevels: 19,
                controls: controls
            },
            extent: OpenLayers.Bounds.fromArray([
                -122.911, 42.291,
                -122.787,42.398
            ]),
            layers: [new OpenLayers.Layer.WMS(
                "Medford",
                "http://localhost:8080/geoserver/wms",
                {layers: "medford"},
                {isBaseLayer: false}
            )]
        });
        controls.push(
            new OpenLayers.Control.Navigation(),
            new OpenLayers.Control.Attribution(),
            new OpenLayers.Control.PanPanel(),
            new OpenLayers.Control.ZoomPanel()
        );

        items.push({
            xtype: "grid",
            ref: "capsGrid", // makes the grid available as app.capsGrid
            title: "Available Layers",
            region: "north",
            height: 150,
            viewConfig: {forceFit: true},
            store: new GeoExt.data.WMSCapabilitiesStore({
                url: "http://localhost:8080/geoserver/wms?SERVICE=WMS&REQUEST=GetCapabilities&VERSION=1.1.1&",
                autoLoad: true
            }),
            columns: [
                {header: "Name", dataIndex: "name", sortable: true},
                {header: "Title", dataIndex: "title", sortable: true},
                {header: "Abstract", dataIndex: "abstract"}
            ],

            bbar: [{
                text: "Add to Map",
                handler: function() {
                    app.capsGrid.getSelectionModel().each(function(record) {
                        var clone = record.clone();
                        clone.getLayer().mergeNewParams({
                            format: "image/png",
                            transparent: true
                        });
                        app.mapPanel.layers.add(clone);
                        app.mapPanel.map.zoomToExtent(
                            OpenLayers.Bounds.fromArray(clone.get("llbbox"))
                        );
                    });
                }
            }]
        });

        </script>
    </head>
    <body>
    </body>
</html>

I've been playing around on firebug to try to figure out what's going on, particularly on the request
http://localhost:8080/geoserver/wms?SERVICE=WMS&REQUEST=GetCapabilities&VERSION=1.1.1&

since this is the request that is supposed to get the layer info.
The request header it sends is below. The response for some reason is 0 bytes. I'm not very familiar with web development, but I thought this should be a GET request instead of an OPTIONS request.
OPTIONS /geoserver/wms?SERVICE=WMS&REQUEST=GetCapabilities&VERSION=1.1.1& HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: null
Access-Control-Request-Method: GET
Access-Control-Request-Headers: x-requested-with
Connection: keep-alive

Here is the response header:
HTTP/1.1 200 OK
Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS
Content-Length: 0
Server: Jetty(6.1.8)

What is going wrong? And how can I fix it?
EDIT: Here is part of the log file, which includes starting up OpenGeo and then loading the webpage I built in the tutorial. The rest is just the requests for the map tiles that look like
127.0.0.1 -  -  [23/Jan/2013:18:10:52 +0000] "GET /geoserver/wms?LAYERS=medford&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&EXCEPTIONS=application%2Fvnd.ogc.se_inimage&FORMAT=image%2Fjpeg&SRS=EPSG%3A4326&BBOX=-122.87109375,42.36328125,-122.8271484375,42.4072265625&WIDTH=256&HEIGHT=256 HTTP/1.1" 200 6993

I went over the character limit by including them so I took them out.
127.0.0.1 -  -  [23/Jan/2013:18:10:43 +0000] "HEAD /dashboard/version.ini HTTP/1.1" 200 0
127.0.0.1 -  -  [23/Jan/2013:18:10:43 +0000] "GET /geoserver/rest/workspaces.json HTTP/1.1" 200 685
127.0.0.1 -  -  [23/Jan/2013:18:10:43 +0000] "GET /geoserver/rest/workspaces/AENVTest/datastores.json HTTP/1.1" 200 155
127.0.0.1 -  -  [23/Jan/2013:18:10:43 +0000] "GET /geoserver/rest/workspaces/AENVTest/coveragestores.json HTTP/1.1" 200 21
127.0.0.1 -  -  [23/Jan/2013:18:10:43 +0000] "GET /geoserver/rest/workspaces/medford/datastores.json HTTP/1.1" 200 262
127.0.0.1 -  -  [23/Jan/2013:18:10:43 +0000] "GET /geoserver/rest/workspaces/medford/coveragestores.json HTTP/1.1" 200 178
127.0.0.1 -  -  [23/Jan/2013:18:10:43 +0000] "GET /geoserver/rest/workspaces/earth/datastores.json HTTP/1.1" 200 268
127.0.0.1 -  -  [23/Jan/2013:18:10:43 +0000] "GET /geoserver/rest/workspaces/earth/coveragestores.json HTTP/1.1" 200 166
127.0.0.1 -  -  [23/Jan/2013:18:10:43 +0000] "GET /geoserver/rest/workspaces/opengeo/datastores.json HTTP/1.1" 200 146
127.0.0.1 -  -  [23/Jan/2013:18:10:43 +0000] "GET /geoserver/rest/workspaces/opengeo/coveragestores.json HTTP/1.1" 200 21
127.0.0.1 -  -  [23/Jan/2013:18:10:43 +0000] "GET /geoserver/rest/workspaces/usa/datastores.json HTTP/1.1" 200 148
127.0.0.1 -  -  [23/Jan/2013:18:10:43 +0000] "GET /geoserver/rest/workspaces/usa/coveragestores.json HTTP/1.1" 200 21
127.0.0.1 -  -  [23/Jan/2013:18:10:43 +0000] "GET /geoserver/rest/workspaces/analytics/datastores.json HTTP/1.1" 200 138
127.0.0.1 -  -  [23/Jan/2013:18:10:44 +0000] "GET /geoserver/rest/workspaces/analytics/coveragestores.json HTTP/1.1" 200 21
127.0.0.1 -  -  [23/Jan/2013:18:10:44 +0000] "GET /geoserver/rest/workspaces/world/datastores.json HTTP/1.1" 200 252
127.0.0.1 -  -  [23/Jan/2013:18:10:44 +0000] "GET /geoserver/rest/workspaces/world/coveragestores.json HTTP/1.1" 200 21
127.0.0.1 -  -  [23/Jan/2013:18:10:44 +0000] "GET /geoserver/rest/layers.json HTTP/1.1" 200 3036
127.0.0.1 -  -  [23/Jan/2013:18:10:44 +0000] "GET /geoexplorer/maps/ HTTP/1.1" 200 556
127.0.0.1 -  -  [23/Jan/2013:18:10:45 +0000] "HEAD /dashboard/version.ini HTTP/1.1" 200 0
127.0.0.1 -  -  [23/Jan/2013:18:10:48 +0000] "HEAD /dashboard/version.ini HTTP/1.1" 200 0
127.0.0.1 -  -  [23/Jan/2013:18:10:50 +0000] "HEAD /dashboard/version.ini HTTP/1.1" 200 0
127.0.0.1 -  -  [23/Jan/2013:18:10:52 +0000] "OPTIONS /geoserver/wms?SERVICE=WMS&REQUEST=GetCapabilities&VERSION=1.1.1 HTTP/1.1" 200 0
127.0.0.1 -  -  [23/Jan/2013:18:10:53 +0000] "HEAD /dashboard/version.ini HTTP/1.1" 200 0
127.0.0.1 -  -  [23/Jan/2013:18:10:53 +0000] "GET /geoserver/rest/workspaces.json HTTP/1.1" 200 685
127.0.0.1 -  -  [23/Jan/2013:18:10:53 +0000] "GET /geoserver/rest/workspaces/AENVTest/datastores.json HTTP/1.1" 200 155
127.0.0.1 -  -  [23/Jan/2013:18:10:53 +0000] "GET /geoserver/rest/workspaces/AENVTest/coveragestores.json HTTP/1.1" 200 21
127.0.0.1 -  -  [23/Jan/2013:18:10:53 +0000] "GET /geoserver/rest/workspaces/medford/datastores.json HTTP/1.1" 200 262
127.0.0.1 -  -  [23/Jan/2013:18:10:53 +0000] "GET /geoserver/rest/workspaces/medford/coveragestores.json HTTP/1.1" 200 178
127.0.0.1 -  -  [23/Jan/2013:18:10:53 +0000] "GET /geoserver/rest/workspaces/earth/datastores.json HTTP/1.1" 200 268
127.0.0.1 -  -  [23/Jan/2013:18:10:53 +0000] "GET /geoserver/rest/workspaces/earth/coveragestores.json HTTP/1.1" 200 166
127.0.0.1 -  -  [23/Jan/2013:18:10:53 +0000] "GET /geoserver/rest/workspaces/opengeo/datastores.json HTTP/1.1" 200 146
127.0.0.1 -  -  [23/Jan/2013:18:10:53 +0000] "GET /geoserver/rest/workspaces/opengeo/coveragestores.json HTTP/1.1" 200 21
127.0.0.1 -  -  [23/Jan/2013:18:10:53 +0000] "GET /geoserver/rest/workspaces/usa/datastores.json HTTP/1.1" 200 148
127.0.0.1 -  -  [23/Jan/2013:18:10:53 +0000] "GET /geoserver/rest/workspaces/usa/coveragestores.json HTTP/1.1" 200 21
127.0.0.1 -  -  [23/Jan/2013:18:10:53 +0000] "GET /geoserver/rest/workspaces/analytics/datastores.json HTTP/1.1" 200 138
127.0.0.1 -  -  [23/Jan/2013:18:10:53 +0000] "GET /geoserver/rest/workspaces/analytics/coveragestores.json HTTP/1.1" 200 21
127.0.0.1 -  -  [23/Jan/2013:18:10:53 +0000] "GET /geoserver/rest/workspaces/world/datastores.json HTTP/1.1" 200 252
127.0.0.1 -  -  [23/Jan/2013:18:10:53 +0000] "GET /geoserver/rest/workspaces/world/coveragestores.json HTTP/1.1" 200 21
127.0.0.1 -  -  [23/Jan/2013:18:10:53 +0000] "GET /geoserver/rest/layers.json HTTP/1.1" 200 3036
127.0.0.1 -  -  [23/Jan/2013:18:10:53 +0000] "GET /geoexplorer/maps/ HTTP/1.1" 200 556
127.0.0.1 -  -  [23/Jan/2013:18:10:55 +0000] "HEAD /dashboard/version.ini HTTP/1.1" 200 0

A: Read up on the Same Origin Policy. If your OpenLayers script is not on http://localhost:8080/ and your browser or server does not support CORS, that is your problem.

A: There are 2 kinds of solution based on my experience:

*

*js problem: copy your code in jetty web app beside your GeoServer for solving js security problem

*GeoServer problem: after solving problem in 1, if does not work, your Layers in GeoServer is not complete. for example if one of your Layers does not have 'Style' your code does not work


text:
Q: How to generate an unordered list from database table data? hi i have an unordered list

I had made a table to fill the unordered list but how to fetch that data into li and ul
the table consists of home, organisation (with children as policy, employeesdetails), and so on..  How do i fill these ul and li's and children of li's with data from sqlserver2005 table?
I'm not supposed to use any asp.net built in controls like asp.net menu
foreach (DataRow row in dt.Rows)
        {
            int currentDepth =  Convert.ToInt32(row["Depth"]);
            if (lastDepth < currentDepth)
            {
                output.Append("
");
                numUL++ ;
            }
            else if (lastDepth > currentDepth)
            {
                output.Append("

");
                numUL--   ;
            }
            else if (lastDepth > -1)
            {
                output.Append("
");
            }
            output.AppendFormat("
{0}", row["ApplicationName"], currentDepth);
            lastDepth = currentDepth;
        }
        for (int i = 1;i <= numUL;i++)
        {
            output.Append("

");
        }
        Literal1.Text = output.ToString();

i have made the navigation bar based on above code
my navbar looks like this

Home|Organisation|Recruitment|Help|Issues

i am getting all the li's properly(like department and users under organisation)
i have one prolem how do i get the urls dynamically to the above code
my table looks like this

ApplicationID    ApplicationName  ParentKey  Depth  URL
1                 HOME             NULL      0      #
2                 Organisation     NULL      0      #
3                 Department       2         1      #
4                 User             2         1      #
5                 Issues           NULL      0      #
6                 issuestrack      5         1      #
7                 Help             NULL      0      #
8                 helpneeded       7         1      #

thanx in advance

A: Building a Database Driven Hierarchical Menu using ASP.NET and SooperFish Jquery Plugin

A: Try looking at the "for xml" clause for your select.  Since I agree that this looks like homework, you're going to have to do some digging yourself.  Good luck!


text:
Q: Silverlight media player position problem I'm facing a strange issue. My application plays movies from specific positions, so even a position mentioned in milliseconds matters for me. I'm assigning a position to a media element but it's showing the wrong frame. I don't know why media player is not playing from the position that I'm giving.
Here is some sample code:
 TimeSpan oTimeSpan = TimeSpan.FromMilliseconds(16800200); // This shows 04:40:00.2000000

 MediaPlayer.Position = oTimeSpan;      // But after assigning, value is 04:40:00.1990000

Here is a screenshot before and after assigning:

Can anybody tell me what I'm doing wrong here?

A: While you maybe concerned about the fractional milliseconds difference in this case, you have to remember that video is only going to have a frame every ~33 milliseconds or so (using standard NTSC 29.97 FPS). So unless you are doing forensics level analysis(in which case MediaPlayer is not the right tool), that is more accuracy than you should need.
Since a TimeSpan uses Int64 internally and therefore should not have any rounding issues, my guess is that MediaPlayer is snapping to the closest video frame available.

A: Although timespan exposes it's properties as ints I suspect that it's using a floating point value internally. Such issues are due to the way floating point values are stored.
Have you tried checking what you get from TimeSpan.Equals(MediaPlayer.Position, oTimeSpan)? I suspect this would indicate that they are equal.


text:
Q: React: How can I control a list of  with state? Here's a minimal working example of a component with a form of inputs created from a list, and one created from a single value:
import React from 'react';

export default class App extends React.Component {
  constructor(props) {
    super(props);
  }

  state = {
    value: 'single value',
    values: ['one', 'two'],
  }

  render() {
    let test = this.state.values.map( (v, i) => {
      return <input
        key={ v }
        value={ v }
        onChange={ (e) => {
          let values = this.state.values;
          values[i] = e.target.value;
          this.setState({ values });
        } }
      />;
    } )

    return

      <form>
        { test }
      </form>
      <form>
        <input
          value={ this.state.value }
          onChange={ (e) => this.setState({ value: e.target.value }) }
        />
      </form>

;
  }
}

Which produces this:

When the user edits the third input field ('single value'), everything is fine. The user types something, the state updates, everyone is happy.
When the user edits either of the first two input fields however, the cursor loses focus immediately after the state is updated. To edit this field, the user must click on the field after any letter has been put in.
How do I solve this? Is there a way to prevent the component from blurring the <input>, or is there a better way to solve this?
I don't know how to record my screen and make a GIF from it. If you did not understand what I mean I suggest you create a React app with npx create-react-app my-app and edit my-app/src/App.js to my code example.

A: The problem is that you are passing the value as a key, for each new value you get a new key which react "thinks" its a new element thus re-mount the element and you loose the focus
Read more about keys
let test = this.state.values.map( (v, i) => {
      return <input
        key={ v }
        value={ v }
        onChange={ (e) => {
          let values = this.state.values;
          values[i] = e.target.value;
          this.setState({ values });
        } }
      />;
    } )

Not sure if you can change the state structure, but i would go for a different approach and create a form object and give the name and key attributes according to the object's key.
Example:

class App extends React.Component {
  state = {
    form: {
      name: "",
      userName: "",
      age: ""
    },
    externalValue: ""
  };

  onFormInputChange = ({ target }) => {
    const { form } = this.state;
    this.setState({
      form: {
        ...form,
        [target.name]: target.value
      }
    });
  };

  onInputChange = ({ target }) => {
    this.setState({ [target.name]: target.value });
  };

  render() {
    const { form } = this.state;
    let test = Object.entries(form).map(([key, value]) => {
      return (
        <input
          key={key}
          name={key}
          placeholder={key}
          value={value}
          onChange={this.onFormInputChange}
        />
      );
    });

    return (

        <form>{test}</form>
        <form>
          <input
            name="externalValue"
            placeholder="externalValue"
            value={this.state.value}
            onChange={this.onInputChange}
          />
        </form>

    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

A: In render(), you are mapping the state 'values' to the <input>. React identifies the component by its key.
1. Initially you have ['one', 'two'] in 'values' state. And its corresponding keys will be ['one', 'two'].
2. If suppose you change the value of one of the input element as "one1". Then you will update the  states and while mapping you will have a new key as "one1" which is different from previous key "one", so React considers it as a new element and loses the focus.
You try with this code
let test = this.state.values.map( (v, i) => {
      return <input
        key={ `key${i}` }
        value={ v }
        onChange={ (e) => {
          let values = this.state.values;
          values[i] = e.target.value;
          this.setState({ values });
        } }
      />;
    } )

You can check the code here. https://stackblitz.com/edit/react-9lstyj


text:
Q: Graphql - How to include schema from other types Let us say I have the following type:
type Foo {
  id: ID!
  field1: String
}

Now, I wish to define another type, which includes the earlier type. Something like this:
type Bar {
  ...Foo,
  field2: String
}

How do I achieve the above in graphql? I want to basically first create a type, and then include that type in the definition of other types so that I don't have to type all the attributes multiple times.
I am using Amplify / AWS Appsync so if there's any special directive that I could use that would also be helpful

A: GraphQL has the concept interfaces for this.  Appsync, AWS's GraphQL implementation, supports interfaces.
[Edit:] GraphQL does not support "...spread" syntax for interfaces.  Fields are defined explicitly.  Spread syntax does figure in GraphQL, but in the form of Fragments, resuable units of fields for reducing repetition in queries.
interface Character {
  id: ID!
  name: String!
  friends: [Character]
  appearsIn: [Episode]!
}

type Human implements Character {
  id: ID!
  name: String!
  friends: [Character]
  appearsIn: [Episode]!
  starships: [Starship]
  totalCredits: Int
}

type Droid implements Character {
  id: ID!
  name: String!
  friends: [Character]
  appearsIn: [Episode]!
  primaryFunction: String
}

Amplify, which automagically creates AppSync schemas, resolvers and data sources, is apparently a more difficult story.  The amplify-cli repo has an open feature request, Does the GraphQL Transformer support interfaces?.  I am no Amplify expert, but a quick look at the loooong feature request comment thread suggests the answer for Amplify is "not out-of-the-box", but "maybe works in narrow circumstances or with advanced customization".


text:
Q: Is it good grammar to say or write "different to"? To me it seems natural to say something like:
"I am different from you." or "You can't marry him, he belongs to a different species than you do."
But recently it seems to be more and more common to read or hear on TV phrases like:
"...looked very different to..."
And that really annoys me and makes me want to zap the user with a lightening bolt or something.
So is it correct grammar or bad and annoying grammar to use the phrase "different to" instead of "different from or "different than"?

A: Dictionaries say, 'different to' is more typical for British English and that might be the reason why you find it not too natural.
Link
P.S. My humble hypothesis on the origin of 'different to': it could appear long ago as an abbreviation for 'different (compared) to'. Expressions with 'compared' have prepositional versions 'compared with' (for comparison of similar things) and 'compared to' (for comparison of less similar things, with emphasis on difference). So the co-existence of 'different from' and 'different to' ('different than' in AE) probably has similar reasons.

A: The Grammarist makes an interesting analysis  on pros and cos of using "to" and "than" instead of "from" after the adjective different. Note,however, that these  prepositions have been used for centuries.

*

*Some careful English speakers consider different to and different than problematic.  The argument is that things differ from each other, and they don't differ to or differ than each other, so different from is the only logical construction. But there are problems with the arguments against different to and different than, and the old prejudice against these phrases should be laid to rest.

*First, one point in favor of different to and different than is that these constructions are common and have been common for centuries.  They have appeared in works of great writers and can be found in books from editorially fastidious publishers, and no English speaker has trouble understanding them.

*Different than, which is especially common in the U.S. , appears about twice for every three instances of different from in 21st-century newswriting from the U.S. and is common (though less so) in American books from this century.

*Different to, meanwhile, is nearly as common as different from in recent U.K. newswriting and is easily found in U.K. writing of all kinds not just from this century but from as long ago as the 18th century.

*Plus, the argument against different than in particular is not well founded.  Granted, than typically follows comparative adjectives (e.g., brighter than, less easy than), of which different is not one. This is not a rule, though, and than would not be the first word in English to have multiple uses. But the than in different than doesn't even need to have its own definition. The word primarily means in comparison to or in contrast with, and these senses are perfectly in keeping with the word's use in different than.

*We could make similar arguments about different to . To, a versatile preposition, has numerous definitions (the Oxford dictionary lists a few dozen), several of which could be used to justify its use in making comparisons and drawing contrasts.
  Different than also aids concision. Consider the sentence, "He is different than he was yesterday." People who are very strict about these things might find fault with that sentence, yet it is more concise than the alternative, "He is different from how he was yesterday." Also consider the sentence, "The movie had a different meaning to me than to him." It would be possible to rephrase this sentence to use from instead of than, but all the alternatives would be wordy.

*No matter what we say, however, keep in mind that there are people who consider different than and different to unequivocally wrong, so it's a good idea to approach these phrases with caution in writing for work or school.

A: This is from the Chicago Manual of Style, 17th edition:

"The phrasing different from is generally considered preferable to different than {this company is different from that one}, but sometimes the adverbial phrase differently than is all but required {she described the scene differently than he did}. In British English, different to is not uncommon—but it is distinctively British English, whereas different from is standard everywhere." (The bolded words are my emphasis.)

And here is something from GMEU, known also as Garner's Modern English Usage:

"Different than is considered inferior to different from. The problem is that than should follow a comparative adjective (larger than, sooner than, etc.), and different is not comparative—though, to be sure, it is a word of contrast. Than implies a comparison, i.e., a matter of degree; but differences are ordinarily qualitative, not quantitative, and the adjective different is not strictly comparative. Hence writers should generally prefer different from. . . Still, it is indisputable that different than is sometimes idiomatic, and even useful, since different from often cannot be substituted for it—e.g.: 'This designer's fashions are typically quite different for men than for women.'
Also, different than may sometimes usefully begin clauses if attempting to use different from would be so awkward as to require another construction—e.g.:
'Life for Swann, who held out to sign a two-year, $7 million contract in August, is a lot different than it was for him in Lynn.' Steve Conroy, 'Ugly Duckling Becomes Swann,' Boston Herald, 13 Sept. 1996, at 104.
When from nicely fills the slot of than, however, that is the idiom to be preferred—e.g.:
' The spell checker it invokes is completely different than [read different from] that which the others share.' Paul Bonner, 'On Windows,' Computer Shopper, Oct. 1996, at 564."

Garner provided more examples; I just didn't list them all. He says the same as Chicago on different to being common in BrE. He adds that while than following differently is a common usage since the 17th century, if no independent clause immediately follows differently, from works well and is preferable. Here is the example he gives:

"Why should artists be treated any differently than [read differently from] scientists?" Roche Schulfer, "Defending NEA," Chicago Trib., 21 Sept. 1996, at 23.

A: It is in British English.  Using "to" after "different" instead of "from" or "than" is a Britishism.  It is unique to British English.  That doesn't mean that speakers of British English never say "different from" or "different than" but that "different to" is another choice.  That said, most of the time an American speaker says "different than," a British speaker would say "different to," instead.
Link

A: *

*A is different from B

*A is different than B

*A is different to B [meaning: comparison, not standard]

To is an operator (some call it a function word) and generally is used to link two parts of a sentence (some people call it a to-infinitive). "He likes to eat scones". There are many other functions as well.
It is also a preposition. "Go to the back of the room".
Its main uses are given in Merriam Webster definition of to
However,  none of the uses given there involve comparisons as in "A is different from B" or "A is different than B". Therefore, I would say it is not standard.


text:
Q: Failed to load main class while executing war I build my project using maven and generated a *.war file with the following content structure:
META-INF
- maven
-- net.avedo.spozz
--- Spozz-Webservice
---- pom.properties
---- pom.xml
- MANIFEST.MF
WEB-INF
- classes
-- net
--- avedo
---- spozz
----- Spozz.class
----- models
------ ...
----- services
------ ...
-- psql-custom.properties
- lib
-- ...
- web.xml

If I now try to run the generated war file using java -jar spozz.war, I get the following error:
Error: Could not find or load main class net.avedo.spozz.Spozz

What did I wrong? Please find the Manifest file and the definition of the maven-war-plugin in the pom.xml below.
MANIFEST.MF
Manifest-Version: 1.0
Built-By: awilhelm
Build-Jdk: 1.7.0_51
Class-Path: javax.servlet-api-3.1.0.jar jetty-webapp-9.1.3.v20140225.j
 ar jetty-xml-9.1.3.v20140225.jar jetty-servlet-9.1.3.v20140225.jar je
 tty-security-9.1.3.v20140225.jar jetty-server-9.1.3.v20140225.jar jet
 ty-servlets-9.1.3.v20140225.jar jetty-continuation-9.1.3.v20140225.ja
 r jetty-http-9.1.3.v20140225.jar jetty-io-9.1.3.v20140225.jar jetty-j
 sp-9.1.3.v20140225.jar jetty-schemas-3.1.M0.jar javax.servlet.jsp-api
 -2.3.1.jar javax.servlet.jsp-2.3.2.jar javax.servlet.jsp.jstl-1.2.0.v
 201105211821.jar javax.servlet.jsp.jstl-1.2.2.jar javax.el-3.0.0.jar
 org.eclipse.jdt.core-3.8.2.v20130121.jar jetty-util-9.1.3.v20140225.j
 ar jettison-1.3.5.jar stax-api-1.0.1.jar resteasy-jaxrs-3.0.6.Final.j
 ar scannotation-1.0.3.jar javassist-3.12.1.GA.jar jboss-annotations-a
 pi_1.1_spec-1.0.1.Final.jar activation-1.1.jar jcip-annotations-1.0.j
 ar resteasy-client-3.0.6.Final.jar async-http-servlet-3.0-3.0.6.Final
 .jar jaxrs-api-3.0.6.Final.jar resteasy-servlet-initializer-3.0.6.Fin
 al.jar log4j-1.2.17.jar slf4j-api-1.7.6.jar slf4j-log4j12-1.7.6.jar c
 ommons-io-2.4.jar ormlite-jdbc-4.48.jar ormlite-core-4.48.jar
Created-By: Apache Maven 3.2.1
Main-Class: net.avedo.spozz.Spozz
Archiver-Version: Plexus Archiver

Extract from pom.xml
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>${maven.war.plugin.version}</version>
    <configuration>
        <webXml>src\main\webapp\WEB-INF\web.xml</webXml>
        <archive>
            <manifest>
                <addClasspath>true</addClasspath>
                <mainClass>net.avedo.spozz.Spozz</mainClass>
            </manifest>
        </archive>
    </configuration>
</plugin>

A: The simplest way I know to launch a .war file as a Web application is with Jetty Runner:

*

*Download jetty-runner.jar

*Run java -jar jetty-runner.jar spozz.war

*Access your Web application at localhost:8080

A: A normal jar file has its class files in the jar file root. Your class files are in WEB-INF\classes which is the normal position for a war (web application).
You could use the already mentioned jetty approach or relayout your archive file.
Jar
     Myclass.class
     Mymain.class
     META-INF
            manifest

But maybe you do not want an executable war. Then you have to create a Jar using maven.


text:
Q: Vim: Warning: Output is not to a terminal while using vi and grep I am running the following command to view error log
vi mysite_com_error.log-2019060 | grep 'Jun 08:23'

but I am getting the following error:

Vim: Warning: Output is not to a terminal


text:
Q: PyQt Confirmation Finishing of Multiple QThreads I created a GUI tool with Qt Creator and Python. In the GUI the user would select types of the shapefile he/she wants to generate. The script stores the selection in a list. Generating of each type of shapefile is handled by separate QThreads. Each QThread would print some messages like "Processing AAA....". The "run" button function would then do:
if optionA in selection_list:
    QThreadA.start()
if optionB in selection_list:
    QThreadB.start()
if optionC in selection_list:
    QThreadC.start()

Now I am trying to have the GUI pop up a window when all QThreads finish. I found it here https://riverbankcomputing.com/pipermail/pyqt/2007-May/016026.html that QThread.wait() works the same as thread.join(), and I am trying to utilize it.
I cannot do
if optionA in selection_list:
    QThreadA.start()
if optionB in selection_list:
    QThreadB.start()
if optionC in selection_list:
    QThreadC.start()

QThreadA.wait()
QThreadB.wait()
QThreadC.wait()
print("All set")

Since sometimes not all QThreads would be running.
But if I do
if optionA in selection_list:
    QThreadA.start()
if optionB in selection_list:
    QThreadB.start()
if optionC in selection_list:
    QThreadC.start()

if optionA in selection_list:
    QThreadA.wait()
if optionB in selection_list:
    QThreadB.wait()
if optionC in selection_list:
    QThreadC.wait()
print("All set")

Not only does this look dumb, when I hit "run" button, I would also get
"All set"
"Processing AAA..."
"Processing BBB..."
"Processing CCC..."

The messages appear altogether when apparently everything finished, instead of what I was hoping to see:
"Processing AAA..."
some time passed...
"Processing BBB..."
some more time passed...
"Processing CCC..."
some more time passed...
"All set"

What is the order of the things that happen here? And this basically makes the messages useless as the user would only see them when everything finishes at last.
Could use some help on how to reconstruct the functions.
Edit: According to @Nimish Bansal's recommendation, I come up with this:
dict = {optionA: QThreadA, optionB: QThreadB, optionC: QThreadC}
for option in selection_list:
    dict[option].start()

to avoid the previous stupid "if"s, but I still have not found a effective way to conclude all the threads, since:
for options in selection_list:
    dict[option].wait()

does not seem to work, due to the .wait() would pause the for loop I guess?

A: def run_fun(a):
    print("processing",a)
    time.sleep(2)

import threading
A=threading.Thread(target=run_fun,args=('aaa',))
B=threading.Thread(target=run_fun,args=('bbb',))
C=threading.Thread(target=run_fun,args=('ccc',))

def join_threads(listi):
    for j in listi:
        j.join()
    print("ALL set","open your gui here")

A.start()
B.start()
C.start()
threading.Thread(target=join_threads,args=([A,B,C],)).start()

OUTPUT
processing aaa
processing bbb
processing ccc
ALL set open your gui here


text:
Q: Como sobrescrever uma classe de um projeto externo para chamar uma função Tenho uma solução onde contém 2 projetos.
Um deles é o projeto que puxei pelo github, então não quero modifica-lo pois toda vez que atualizar irei perder minhas configurações.
Nesse projeto tem uma classe chamada:
public class Cielo
{
        String sendHttpRequest (String message)
        {
//Quero q toda vez que o sistema chamar esse metódio chame um código meu, ex:
//var gravaXML = new SalvaXML();
//gravaXML.GravarFisicamente(message);
        }
}

Porém quero injetar essa função através do meu 2º projeto, Não quero modificar o projeto já pronto vindo do git.
Existe como?

A: Você quer criar a MyCielo que herda da classe Cielo original.
Nessa sua classe você pode alterar qualquer comportamento das funções virtuais e adicionar novos métodos sem problemas.
O que você não vai poder fazer é mexer nas variáveis e métodos privados. Se você conseguir fazer tudo o que precisa no sendHttpRequest usando a parte protegida e pública da classe está até fácil. :)

Passo a passo:
1) Adicione a biblioteca como referência.
No visual studio, por exemplo, você deve adicionar a lib gerada pelo projeto 1 na pasta correta do VS. (Pode ser "C:\Arquivos de Programas\Microsoft Visual Studio 14.0\VC\include" para o VS2015).
Ali você cria uma pasta para o projeto com todo o código. E incluir ele como referência no References, clicando com o botão direito e passando a biblioteca.
2) Crie a classe nova.
No topo você adiciona o arquivo que aponta para a classe que você quer estender.
using Cielo;

E nesse arquivo você cria a classe com todas as funções que você precisa.
public class MyCielo : Cielo
{
        String sendHttpRequest (String message)
        {
//Quero q toda vez que o sistema chamar esse metódio chame um código meu, ex:
//var gravaXML = new SalvaXML();
//gravaXML.GravarFisicamente(message);
        }
}


text:
Q: Accelerated pixel array rendering in Java I have been working on a game that uses a BufferedImage to render to the screen. The BufferedImage is created from an array of hexadecimal colors. So rendering a rectangle to the screen might look like this:
public void renderRectangle (int xl, int yl, int rWidth, int rHeight, int color, double dist) {
    for (int x = xl; x < xl + rWidth; x++) {
        for (int y = yl; y < yl + rHeight; y++) {
            pixels [x + y * WIDTH] = color; //set pixel's color.
            zBuffer [x + y × WIDTH] = dist; //set pixel's distance from camera.
        }
    }
}

Unfortunately, after doing these calculations, especially when rendering in 3d, it gets pretty laggy.
But games such as doom  (which also don't use the gpu) run fine.
So how can I render these graphics without opengl and without lag?

A: the above code itself is not going to be your performance problem. sure, you could optimize drawing that rectangle in some way (e.g. have rectangles you need often precalculated) but this is not going to  affect performance.
could you probably show some excerpts of how your rendering method (do you create a new buffered image for every frame you render? --> that would be your performance problem then). also are you sure that the problem is really with the rendering and not with triggering the repaints of the screen?
in terms of doom (1), please also consider that it was VGA (320x200 pixels only) and had a very simplified 3d engine, that was based on doing simple matrix transformation on rectangles. also the engine had a lot of logic to decide which areas of the world map were actually visible on screen (and not behind the camera or hidden behind another wall) and only rendered these parts.
given the little information in you question, i hope that this will guide you in the right direction.

A: For the 2D methods like the one you provided, not much can be done; only a little micro-optimization.
public void renderRectangle(int xl, int yl, int rWidth, int rHeight, int color) {
    if (rWidth <= 0 || rHeight <= 0) {
        return;
    }
    int pos = xl + yl * WIDTH;
    for (int i = pos, i2 = pos + rWidth; i != i2; i++) {
        pixels[i] = color;
    }
    int pos2 = pos;
    for (int y = 1; y != rHeight; y++) {
        pos2 += WIDTH;
        System.arraycopy(pixels, pos, pixels, pos2, rWidth);
    }
}

To improve performance you can try e.g.:

*

*Precheck that everything is actually visible on screen to avoid useless process

*Make lookup tables for everything that can be precalculated (if you limit colors, can be done even for them)

*Also precalculate  things such as shading


text:
Q: Pandas : Create dummy variables based on conditions in 2 dataframes I am trying to create a dataframe of dummy variables (0/1) based on conditions in two different dataframes, df and dfLag.  Both df and dfLag have the same columns / dimensions.
Consider the following dataframe and it's lag:
import pandas as pd

df = pd.DataFrame({
    'a':(0,0,0,0,14,15,16,17),
    'b':(20,21,22,23,24,25,26,27),
    'c':(30,31,32,0,34,35,36,37),
    'd':(40,41,42,43,44,0,0,47),
})

dfLag = df.shift(1)

I would like to create a new dataframe dummies that is 1 if the corresponding element in both df and dfLag is greater than 0, and 0 otherwise.
Below illustrates the expected output.  I have no idea how to go about this...


text:
Q: Not able to clear Html Elements from document fragment While investigating a memory leak in IE11, using the developer tools I found some DOM Detach elements.
After doing further investigation, inside I found Document fragment sections where some HTML nodes were still retaining memory and not being garbage collected.
Here's code from the BlockUI plugin
var s = "Some Div tags"
var lyr2 = $(s);

$() is adding in document fragment
I am using jquery 1.7.2 version, assistance appreciated
Please find line numbers .
https://github.com/malsup/blockui/blob/master/jquery.blockUI.js#L293-L326


text:
Q: Why does the GCC Compiler allows us to declare zero length strings (directly) and negative length strings (indirectly)? /*implementation of strrev i.e. string reverse function*/

#include<stdio.h>
#include<string.h>

/*length of the string i.e. cells in the string*/
static const unsigned int MAX_LENGTH = 100;
//static const int MAX_LENGTH = -100;

/*reverses the string*/
void reverseString(char[]);
/*swaps the elements in the cells of a string*/
void swap(char[], int, int);

/*runs the program*/
int main()
{
    char string[MAX_LENGTH];
    //char string[0];  //no error!
    //char string[-1]; //error!

    gets(string);
    reverseString(string);
    printf("\n%s", string);

    return 0;
}

void reverseString(char string[])
{
    int i;
    for(i = 0; i < (strlen(string) / 2); i++)
    {
        swap(string, i, (strlen(string) - 1 - i));
    }
}

void swap(char string[], int i, int j)
{
    int temp = string[i];
    string[i] = string[j];
    string[j] = temp;
}

Look at the main function. If you replace the first line "char string[MAX_LENGTH];" with "char string[-1];", the compiler shows error. (because string of negative length makes no sense). However, if you replace the 7th line of this code (where I declared const MAX_LENGTH) with the code written in comments in line 8 (in which MAX_LENGTH is assigned a -ve value), there is no compilation error. Why?
Also, why there is no error in declaring zero length string. How does zero length string makes sense to compiler but not a negative length string?

A: Because it's not the same thing.

*

*In the first case, you're defining an array, using a fixed, compile-time size

*In the second case, you're defining a variable length array or VLA.

The compiler does the allocation at run time in the second case (with this -100 value it isn't going to end well), because the const isn't really a constant in C, it just tells the compiler you aren't to change the value (and also allows some optimizations). So the result is undefined behaviour (more here: Declaring an array of negative length)
If you want the same behaviour use a #define
 #define MAX_LENGTH -100    // will raise a compilation error

or as suggested in comments, an enumerated constant:
enum { MAX_LENGTH = -100 };    // will raise a compilation error

If you want to protect your declarations, use assert
assert(MAX_LENGTH > 0);
char string[MAX_LENGTH];

As for the zero-length element, no need to repeat what's already been answered: What's the need of array with zero elements? (in a nutshell, it's useful at the end of a structure to be able to have varying length)


text:
Q: Laurent series for $\cot (z)$ I'm looking for clarification on how to compute a Laurent series for
$\cot z$
I started by trying to find the $\frac{1}{\sin z}$. I've found multiple references that go from an Taylor expansion for $\sin z$ directly to an expression for $\frac{1}{\sin z}$ but I am unable to follow how they got there. This thread Calculate Laurent series for $1/ \sin(z)$ started to answer my question but I do not understand how to use the given formulas to "iteratively compute" the coefficients, and the example given has several coefficients in place and I'm not sure how they were obtained.

A: If you are looking for a trucated series, you could start from $$\tan(z)=z+\frac{z^3}{3}+\frac{2 z^5}{15}+\frac{17 z^7}{315}+\frac{62
   z^9}{2835}+O\left(z^{11}\right)$$ which makes $$\cot(z)=\frac 1{z+\frac{z^3}{3}+\frac{2 z^5}{15}+\frac{17 z^7}{315}+\frac{62
   z^9}{2835}+O\left(z^{11}\right)}=\frac 1z \frac 1{1+\frac{z^2}{3}+\frac{2 z^4}{15}+\frac{17 z^6}{315}+\frac{62
   z^8}{2835}+O\left(z^{10}\right)}$$ and perform long division to get $$\cot(z)=\frac{1}{z}-\frac{z}{3}-\frac{z^3}{45}-\frac{2
   z^5}{945}-\frac{z^7}{4725}+O\left(z^9\right)$$ If you want the infinite series consider that $$\cot(z)=\frac 1 {\tan(z)}=f(z)=\sum_{i=0}^\infty a_iz^{i-1}$$ what you can rewrite as $$1=\tan(z)\sum_{i=0}^\infty a_iz^{i-1}$$ that is to say $$1=\left(\sum^{\infty}_{n=1} \frac{B_{2n} (-4)^n (1-4^n)}{(2n)!} z^{2n-1}\right)\times \sum_{i=0}^\infty a_iz^{i-1}$$ For simplicity, let us define $$b_n=\frac{B_{2n} (-4)^n (1-4^n)}{(2n)!}$$ in order to solve $$1=\sum^{\infty}_{n=1}b_nz^{2n-1} \times \sum_{i=0}^\infty a_iz^{i-1}$$ Developing, we get
$$1=a_0 b_1+a_1 b_1 z+ (a_2 b_1+a_0 b_2)z^2+ (a_3 b_1+a_1 b_2)z^3+ (a_4
   b_1+a_2 b_2+a_0 b_3)z^4+ (a_5 b_1+a_3 b_2+a_1 b_3)z^5+ (a_6
   b_1+a_4 b_2+a_2 b_3+a_0 b_4)z^6+(a_7 b_1+a_5 b_2+a_3 b_3+a_1
   b_4)z^7 +\cdots$$ Now,we need to solve, for the $a_i$'s the equations $$a_0 b_1=1$$ $$a_1 b_1=0$$ $$a_2 b_1+a_0 b_2=0$$ $$a_3 b_1+a_1 b_2=0$$ $$a_4
   b_1+a_2 b_2+a_0 b_3=0$$ $$a_5 b_1+a_3 b_2+a_1 b_3=0$$ $$a_6
   b_1+a_4 b_2+a_2 b_3+a_0 b_4=0$$ $$a_7 b_1+a_5 b_2+a_3 b_3+a_1
   b_4=0$$ This does not make much problem (using successive eliminations for example).
This leads to the infinite series
$$\cot(z)=\sum_{n=0}^\infty (-1)^n\frac{ 2^{2 n}\, B_{2 n} }{(2 n)!}z^{2 n-1}$$


text:
Q: WCF + Singleton + File transfer + Multithreading I have a file transfer service written using WCF. It recieves a file sent by the client.
The client inturn sends across the file using FileStream + MessageContract. I have made the WCF file transfer service as singleton using the following attributes
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,
 ConcurrencyMode = ConcurrencyMode.Multiple)]

I try to use multiple threads in the client itself.
Each thread creates an instance of channelfactory + proxy.CreateChannel and sends across one distinct file to the service. I do not have any locks on the service side which allows only one file to be transferred at a time, nor on the client side. The code is kind of pass through code with no state persistance.
The problem I am facing is, as such I do not see multiple threads trying to send multiple files. Each time I try to transfer multiple files using multiple threads, the service kind of does not accept multiple files at the same instance. This results in the file getting transferred sequentially instead of in parallel. I feel from the client side the file is sent but at service side its kind of just gets held up.
I tried using ServiceThrottling attributes, but still I do not find any difference.
Is there something wrong which I am doing or is this kind of approach not valid?
One client can only send one file across one channel? Can many threads NOT send many files to the same service ? Can someone please help me.
thanks
Sandeep

A: I hate to admit the silly mistakes I have encountered during this series, but I admit, how silly I was.

*

*Reason for single thread execution.
As I had put a lock right away at the beginning of the service entry, only one thread was allowed while rest waited.

*Reason for couple of threads getting executed instead of many.
Since bandwidth is only 2MBPS, and I am trying to transfer 10 files each of 10MB, I am assuming network is getting choked. When I try with 10 files each of 100KB multithreading works like a charm also I am able to control inlet of threads using maxConcurrentCalls.
Cheers, everyone, and thanks YK1
btw. in case I am wrong, please correct my assumption about network bandwidth being culprit.

A: try setting property ServicePointManager.DefaultConnectionLimit to value greater than 2 in your client.


text:
Q: Centered Text inside a button with an icon in Flutter I'm having issues where I want to make a button (any kind to achieve this) that has an icon that is always in the same position at the start of the button, and that the text of the button is always centered compared to the text below it and always centered in the button itself, even if the text is dynamic. This is what I want to achieve:

The button text is centered according to the text below(that stays the same) and it is centered with the above button, but if the button text changes dynamically, then I have these issues:

Or like this one:

Any ideas how to solve this problem?
I tried with the Expanded widget and adding the flex properties but failed. I tried some other stuff too but failed also... Here is the button code:
TextButton(
                              style: ButtonStyle(
                                  backgroundColor:
                                      MaterialStateProperty.all(Colors.blue)),
                              onPressed: () {},
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  Expanded(
                                    flex: 1,
                                    child: Icon(
                                      Icons.keyboard_arrow_right_sharp,
                                      color: Colors.white,
                                    ),
                                  ),
                                  Expanded(
                                    flex: 4,
                                    child: Center(
                                      child: Text(
                                        "SOME TEXT",
                                        style: TextStyle(color: Colors.white),
                                      ),
                                    ),
                                  )
                                ],
                              ),
                            ),

Thanks in advance for your help!

A: There are a couple of options to do that. I'm going to assume the size of the text could change so you want a flexible solution.
The first option is the most obvious of the two, but will break if the text is too long. The trick is to add an empty sizedBox at the end of the button, so the text can be centered in an expanded widget.
TextButton(
  style: ButtonStyle(
    backgroundColor: MaterialStateProperty.all(Colors.blue),
  ),
  onPressed: () {},
  child: Row(
    children: [
      Icon(
        Icons.keyboard_arrow_right_sharp,
          color: Colors.white,
          size: 24,
      ),
      Expanded(
        child: Center(
          child: Text(
            "SOME TEXT",
            style: TextStyle(
              color:Colors.white,
            ),
          ),
        ),
      ),
      SizedBox(
        width: 24, // width of the icon
      ),
    ],
  ),
);

The other option is using a stack widget. This way, if the text is too long it will overlap with the icon but it's less probable that it will overflow the button.
TextButton(
  style: ButtonStyle(
    backgroundColor: MaterialStateProperty.all(Colors.blue),
  ),
  onPressed: () {},
  child: Stack(
    children: [
      Positioned(
        left: 0,
        child: Icon(
          Icons.keyboard_arrow_right_sharp,
          color: Colors.white,
          size: 24,
        ),
      ),
      Center(
        child: Text(
          "SOME TEXT",
          style: TextStyle(
            color:Colors.white,
          ),
        ),
      ),
    ],
  ),
);

A: Let's discuss about you code :
using row with a mainaxisalignment from start make the element start from the available area. then i suggest to use the SizedBox to make some of spacing between the elements as you want and play with the width of it.
TextButton(
                          style: ButtonStyle(
                              backgroundColor:
                                  MaterialStateProperty.all(Colors.blue)),
                          onPressed: () {},
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start, // here the issue
                            children: [
                              Expanded(
                                flex: 1,
                                child: Icon(
                                  Icons.keyboard_arrow_right_sharp,
                                  color: Colors.white,
                                ),
                              ),
                             SizedBox(width: MediaQuery.of(context).size.width * 0.08, // change this value as you want 0.08 or 0.1 ...etc
      ),
                              Expanded(
                                flex: 4,
                                child: Center(
                                  child: Text(
                                    "SOME TEXT",
                                    style: TextStyle(color: Colors.white),
                                  ),
                                ),
                              )
                            ],
                          ),
                        ),

for more read this documentation


text:
Q: Power of 2, trying to reach 2^1000, Segmentation fault I am building a program which will multiply by 2, and reach long accurate numbers.
Here I build a program in which each digit is stored in a different variable.
When I compile the program, and I type 2^63, It gives me the correct answer.
But when I type 2^64,  I get a "Segmentation fault".
What is it? What can I do?
#include <stdio.h>
int main(void)
{
  printf("2^n, enter n: ");
  int n, array = 1;

  scanf("%d", &n);
  int num[array];

  num[0] = 2;
  int remainder = 0;
  if (n > 1) {
    int counter = 0;
    int counter3 = 1;

    for (counter3 = 1; counter3 < n; counter3++) {
      remainder = 0;

      for (counter = 0; counter < array; counter++) {
        num[counter] *= 2;
        num[counter] += remainder;
        remainder = 0;

        if (num[counter] / 10 != 0) {
          remainder = num[counter] / 10;
          num[counter] -= remainder * 10;
          if (counter+1 >= array) {
            array++;
            num[counter+1] = remainder;
            remainder = 0;
            break;
          }
        }
      }
    }
  }

  int counter2;
  for (counter2 = array - 1; counter2 >= 0; counter2--)
    printf("%d", num[counter2]);

  putchar('\n');
  return 0;
}

A: I think your problem is
int num[array];

This is a static array, once its size is declared to be size of 1 (array=1 only a few lines above) then thats the size of the array.
Big number libraries are very complicated and best left up to a 3rd party library.
Try taking a look at GMP
If you must do it yourself, try using a dynamic array class like std::vector

A: Thats because to store 2^n you need an n bit type - which is generally available for n < 64, but not for numbers higher than this.
What you'll need is a general purpose 3rd party large integer library.

A: num can only contain 1 integer.
You were lucky that int num[1] was on a page (?) which provided space for 64 integers (256 bytes), before the access to num[64] caused the segmentation fault.
You could use a int* and reallocate it as necessary to store new bits...

A: Other people have more-or-less answered the question, so I'm going to do something a little different: I'm going to paste here a complete revision of your program.  I fixed the bug you were asking about, but I also made a whole lot of other changes.  I want you to read the revised program carefully and think about why I changed certain things.
// Note: This program uses C99 features; must be compiled with e.g.
// -std=c99 (for GCC).  Nonetheless it is C, not C++.

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

static void
printdigits(const int num[], int top)
{
  for (int i = top - 1; i >= 0; i--) {
    assert(0 <= num[i] && num[i] < 10);
    putchar('0' + num[i]);
  }
  putchar('\n');
}

int
main(int argc, char **argv)
{
  if (argc != 2) {
    fprintf(stderr, "usage: %s n\ncomputes 2^n\n", argv[0]);
    return 1;
  }

  char *eptr;
  long n = strtol(argv[1], &eptr, 10);
  if (eptr == argv[1] || *eptr != '\0') {
    fprintf(stderr, "%s: '%s' is not a number\n", argv[0], argv[1]);
    return 1;
  }

  if (n < 1) {
    fputs("n must be at least 1\n", stderr);
    return 1;
  }

  unsigned int num[n]; // could be short or even char, but memory is not tight
  int top = 1;
  num[0] = 2;

  for (int i = 1; i < n; i++) {
    int carry = 0;
    for (int j = 0; j < top; j++) {
      num[j] = num[j] * 2 + carry;
      carry = 0;

      if (num[j] >= 10) {
        assert(num[j] < 20); // largest possible is 2*9+1 = 19
        carry = 1;
        num[j] -= 10;

        if (j+1 >= top) {
          assert(top < n);
          num[j+1] = carry;
          top++;
          break;
        }
      }
    }

#ifndef NDEBUG
    printf("Iteration %d: top=%d num=", i, top);
    printdigits(num, top);
#endif
  }

#ifndef NDEBUG
  putchar('\n');
#endif
  printdigits(num, top);
  return 0;
}

A: Even though your solution is in C you can use other languages to work problems considering project euler is language agnostic. I use C for a lot of the problems and when it comes to large integer problems I tend to use python because it deals well with large number operations/manipulation/calculations.
Edit
Specified the example code in the question as C rather than C++.


text:
Q: ScrollController in StatelessWidget Is it ok to use a ScrollController for a ListView within a StatelessWidget. If so, how can the controller be disposed?

A: If you are using a ScrollController, I think that you probably has a State (to change or maintain) in your widget.
In that case you need to go for a StatefulWidget.
I would just change to a StatefulWidget and use the dispose() method to clean memory.
But first of all, think if you controller has a purpose to exist in the first place. Maybe in your case makes sense.
Check this answer too --> Do stateless widgets dispose on their own?