text:
Q: Set value to the first day of the month c# This void will set the value of the label text to the previous month.
For example: If today's date is 4/20/2017 the will set the label to 3/20/2017
What I am want to do is set the label text to first day of the previous month like this: 3/1/2017
Just not quite sure how to do that.
protected void PMonth_Click(object sender, EventArgs e)
{

    //Loads the hidden
    if (ViewState["datacountnm"] == null)
    { ViewState["datacountnm"] = 0; }
    ViewState["datacountnm"] = ((int)ViewState["datacountnm"]) - 1;

    lblSelectedDate.Text = DateTime.Now.AddMonths((int)ViewState["datacountnm"]).ToShortDateString();
}


text:
Q: MS Excel Forumla assistance I have a cell I need to split into 2 cells.
Data Sample:  Note: All Cells are formatted as TEXT

*

*"3851v61_18.005_ Have the anchors for all suspended scaffolding system suspension lines and separate vertical lifelines been verified? "

*Data Sample 2:  Parent_ID

Steps:

*

*Need to check to see  if the cell value starts with number.

*Also, If it contains a special character ("_") if may have more than 1.

*Display cell #1 = just the ID number containing the underscore(s).

*Display cell #2 - Just the text right of the underscore.  However, if the original cell only starts with Alpha characters then display the actual value. ie.  Parent_Id

*Strip off any erroneous underscores left hanging.

Expected results:
Cell #:

*

*"3851v61_18.005" (ID Number portion of the Text)

*"Have the anchors for all suspended scaffolding system suspension lines and separate vertical lifelines been verified?

This is what I have so far:  (If it does not start with a number, then return the value of the cell, else continue with the equation)
`=`IF(NUMBERVALUE(LEFT(C321,1))>=1,IFERROR(LEFT(C321, FIND("_",C321)-1), C321),FALSE)`

=IFERROR(RIGHT(C321,LEN(C321)-FIND("_",C321)), C321)`

If the Underscore count is more than one need to include it in the entire number and strip off the text after the last underscore in Cell 1. At the same for the right of the Underscore to display the text after underscore in Cell 2.
Thank you for any assistances offered.

A: I think I understand but am not 100% sure.
Try something like the below to get the full string (if it starts with something that isn't a number) or the string up to the last underscore (if it does start with a number):
=IF(NOT(ISNUMBER(NUMBERVALUE(LEFT($D1,1)))), $D1,
LEFT($D1, FIND("!!!", SUBSTITUTE($D1, "_", "!!!",
LEN($D1)-LEN(SUBSTITUTE($D1, "_", ""))))-1))

Then in a similar fashion try something like the below to get the full string (if it starts with something that isn't a number) or the string to right of the last underscore (if it does start with a number):
=IF(NOT(ISNUMBER(NUMBERVALUE(LEFT($D1,1)))), $D1,
RIGHT($D1, LEN($D1)-FIND("!!!", SUBSTITUTE($D1, "_", "!!!",
LEN($D1)-LEN(SUBSTITUTE($D1, "_", ""))))))

For example:

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to move the decimal point in the stem and leaf plot of R '''
df = BushApproval
x = df$Approval
x
[1] 53 53 58 52 52 53 52 50 58 57 59 59 60 65 66 64 65 65 71 66 60 55 57 59 63 65 65 68 60 66
 [31] 65 66 69 69 70 73 74 77 72 76 79 80 77 81 81 83 86 86 88 84 84 80 81 55 59 56 59 59 63 57
 [61] 56 61 55 46 49 53 59 60 63 56 55 50 51 54 53 56 55 50 52 59 60 58 59 62 61 63 62 64 66 69
 [91] 70 71 69 70 71 69 71 58 57 57 58 61 59 61 60 58 61 58 63 61 63 63 64 65 66 68 63 67 62 67
[121] 68 66 70 66 66 65 68 71 69 69 73 76 73 74 74 70 77 76 76 77 77 75 76 79 80 77 81 82 82 84
[151] 83 84 86 86 87 87 87 88 89 87 90 86 51 55 57 57 55 56 57 52 55 55 56 56 53 62 59 53 58 63
[181] 62 57 57 48 49 50 54 54 51 52 51 51 52 51 52 53 57 55 61 65 71 68 53 61 55 56 60 61 61 65
[211] 70 61 65 68 70 73 71 74 83 81 82 85 85 85 85 85 88 88 84 86 86 82 50 57 57 55 56 52 54 54
[241] 54 52 52 55 63 62 54 62 53 55 64 61 65 70 70 72 75 75 77 82 87 89 84 78 55 52 55 52 56 54
[271] 64 59 60 63 59 57 55 58 49 53 49 48 49 50 45 52 53 58 61 57 54 54 57 62 57 63 64 63 63 62
[301] 69 69 70 69 74 74 74 77 79 78 80 81 82 81 78 82 50 47 51 52 52 53 57
stem(x)
The decimal point is at the |
44 | 0
46 | 00
48 | 0000000
50 | 00000000000000
52 | 00000000000000000000000000000
54 | 000000000000000000000000000
56 | 0000000000000000000000000000
58 | 00000000000000000000000
60 | 000000000000000000000
62 | 00000000000000000000000
64 | 000000000000000000
66 | 00000000000
68 | 0000000000000000
70 | 00000000000000000
72 | 000000
74 | 0000000000
76 | 0000000000000
78 | 000000
80 | 00000000000
82 | 0000000000
84 | 00000000000
86 | 000000000000
88 | 000000
90 | 0
'''
The out is wrong. how do i move the decimal point? to get something like
x = c(91,92,93)
stem(x)
9|1,2,3

A: just add stem(x, scale = 0.5). I am so stupid.


text:
Q: Super Dev mode in GWT I'm new to gwt. I don't know how to start up Super Dev mode. I need the detailed explanation step by step.
I have tried editing gwt.xml file by adding
<add-linker name="xsiframe"/>
  <set-configuration-property name="devModeRedirectEnabled" value="true"/>
  <set-property name="compiler.useSourceMaps" value="true" />

but i cant get the idea about this.

A: I wrote a simple step by step guideline for hello world project debugging with super-dev-mode Here.
After reading through the step by step guideline with screenshots you cannot miss it.

Also, you can read up on the technology -
GWT SuperDevMode - Ray Cromwell Post and GWT Dev Guide
SourceMaps - GWT and Sourcemaps and HTML5 Sourcemaps

A: UPDATE: starting with GWT 2.7, DevMode will actually use Super Dev Mode automatically by default, so you just have to launch DevMode like you did previously, and the app will be (re)compiled automatically on page (re)load.
One difference is that a special .nocache.js is generated so you must ensure this specific file is loaded by the browser; to debug a remote server (like you could do previously with DevMode running with -noserver), you'll have to use the bookmarklets as described below though.
To run in Super Dev Mode, you must go through 2 preparatory steps:

*

*Super Dev Mode only works with the xsiframe linker, so make sure you have the following line in your .gwt.xml too:
<add-linker name="xsiframe" />

That linker is safe for production use (Google uses it everywhere, slightly customized), so feel free to turn it on for all your projects (it combines the best of the std linker –the default one– and the xs linker, without their downsides).
Note: that linker will be the default in 2.7
If you use a version of GWT before 2.6.0, you'll also have to enable Super Dev Mode in your .gwt.xml:
<set-configuration-property name="devModeRedirectEnabled" value="true" />

Otherwise, if you intend to use Super Dev Mode from a URL different from 127.0.0.1 or localhost, then you'll have to whitelist the host. This is done using a regexp, e.g.:
<set-configuration-property name="devModeUrlWhitelistRegexp" value="http://(mymachinename|192\.168\.5\.151)(:\d+)?/.*" />

See https://stackoverflow.com/a/21938574/116472

*compile and deploy your app to a web server near you (if you used a .gwt.xml file specific to Super Dev Mode, make sure you compile that one module: the xsiframe linker and devModeRedirectEnabled property are necessary for that compilation step!)
If you use GWT-RPC, set the system property gwt.codeserver.port to the port you'll run Super Dev Mode on (defaults to 9876) so your server can download RPC serialization policies right from the Super Dev Mode.
If you run them on different machines, you'll have to override getCodeServerPolicyUrl in all of your RemoteServiceServlets. Consider the security implications though, as noted in the javadoc
Once that's done you can start a Super Dev Mode session:

*

*Launch com.google.gwt.dev.codeserver.CodeServer with the same classpath that you'd launch DevMode with (i.e. gwt-user.jar, gwt-dev.jar and all your client-side dependencies: e.g. GXT, GIN+Guice, GWTEventBinder, etc.) but adding gwt-codeserver.jar; and passing the name of your module as argument.
It'll start by compiling your module to check that it can actually be compiled; you can skip this step by passing -noprecompile as argument.
If you never ran Super Dev Mode, go to http://localhost:9876 and add the Dev Mode On and Dev Mode Off links to your bookmarks (drag/drop them to your bookmarks bar).
Note: if you use Maven, you should be able to use mvn gwt:run-codeserver (note: there's a bug in the releases of the plugin up to 2.6.0 where you actually have to run mvn process-classes gwt:run-codeserver; this is fixed in 2.6.1).

*Open your app in your browser, then hit the Dev Mode On bookmarklet. Click the Compile button in the popup that opens. It should refresh the page and load the JS from the CodeServer rather than from your server. Your browser's development tools should also load the SourceMaps so you can see and debug (step by step) your Java code.

*When you want to test changes you made to your code, hit the Dev Mode On bookmarklet again. Contrary to DevMode, refreshing the page won't make it run the new code; the code has to be recompiled first, and this is done when clicking the Compile button after the Dev Mode On bookmarklet (note: you can also directly bookmark the Compile button to save a click, but note that it's bound to your module, so you'd need multiple bookmarks if you work on several modules).

*When you're done, hit Dev Mode Off to make sure you switch back to production mode, then shutdown the CodeServer process (CtrlC in the console should work).
Official documentation at http://www.gwtproject.org/articles/superdevmode.html
See also http://blog.ltgt.net/how-does-gwts-super-dev-mode-work/ for more information about how Super Dev Mode actually works.

A: Have a look to this video, could help
http://jeff-davis.blogspot.fr/2012/07/setting-up-gwt-25s-superdevmode.html

A: Follow these steps, you 'll definitely find the solution.

*

*Download the GWT 2.5 RC2, and put it somewhere...I put it in my eclipse/plugins directory. link

*In Eclipse, add GWT 2.5 to the Project -> Properties -> Google -> Web Toolkit -> Configure SDKs screen, and select the 2.5 version that you have added to the directory in the step above.

*Right click on the project in Eclipse, go to its Run Configurations window, and create a new "Java Application", name it something like "GWT Super Dev Mode".

*While in the Run Configurations window, do the following:

*

*Set the project based on your project name, and type in the main class as com.google.gwt.dev.codeserver.CodeServer

*On the Classpath tab, click user Entries, then click Add External JARs, navigate to the GWT 2.5 directory, and find the gwt-codeserver.jar, and click "Open" (and other external libraries).

*In the Arguments tab, add -src src/ *SOURCE PATH OF YOUR PROJECT* to Program arguments, and add optional -Xmx1024m to VM arguments.

*Click Apply, then go ahead and Run the project.

*After this you will get a URL like, localhost:9876/

*Goto that URL, and bookmark, Dev Mode ON and Dev MOde Off then run your code, remove the suffix gwt.codesvr=127.00.1:9997 in the URL. Now click Dev Mode ON...
Hope you get the solution...


text:
Q: How can I rotate map in OpenTTD? Is it possible to rotate the map?
Sometimes things are very difficult to select because they are behind buildings or other things.
The shorcut icon, key, etc. would be greatly appreciated

A: No, I do not believe this is possible. However, you can use x to "shadow" objects, which is very useful to solve the problem you are experiencing.


text:
Q: Strange DIV behaviour (in Chrome, IE, FF) Problem
I have the following mark-up:

1. Select Room

2. Choose Date

3. Confirm Order

4. Make Payment

The border it meant to surround all of the "steps", but instead cuts them in half, the only way I've found to solve is to explicitly set the height on this, although I thought the content inside would do this when not setting a height.

According to Chrome's Inspect Element, these are all of the CSS rules applied to it:
Progress Bar:
div#progress-bar {
    padding-top: 10px;
    padding-bottom: 10px;
    border: 1px solid black;
}

Individual Steps only have mark-up for font styling (text-shadow, font-size), as well as (Where step-x corresponds to step-1,step-2 etc.):
div#step-x {
    padding: 10px;
    width: 227.5px;
    float: left;
}

I did use a CSS reset, although I assumed the idea behind those was to remove all styling, so could that be an issue?
Any links to this specific problem elsewhere (further reading, if it's a known bug, perhaps a workaround) are welcome.

A: Use overflow: visible.
div#progress-bar {
    padding-top: 10px;
    padding-bottom: 10px;
    border: 1px solid black;
    overflow: visible;
}

Floating stuff does some non-intuitive stuff to wrapping elements.

A: try to add overflow:auto for the #progress-bar to clear the floats. Info http://www.quirksmode.org/css/clearing.html


text:
Q: Moving an Android Studio project causes an error I moved an Android Studio project that used Gradle from D:\old\file\path to D:\new\file\path and now I'm getting the following error:
Installation failed with message Invalid File: D:\old\file\path\app\build\intermediates\split-apk\debug\slices\slice_8.apk
I tried uninstalling the app from my phone and still got the same error. I also tried an emulator but that didn't work either.

A: I figured it out.
Build -> Clean Build worked

A: Close your project. Using your system file manager, delete all .iml files you have inside your project folder (probably this will be few files, two or three). This is the point where you instruct your A.S. to forget the older path.
Then import - not open - import your project on a brand new window of your Android Studio.
From the File menu, use Invalidate caches and restart. Clean Build and run again.


text:
Q: Material UI Card box-shadow being cut off While using Material UI's Card. I am having an issue I do not usually have.
box-shadow that is being cut off on the bottom and top hand side..
How can i fix this?
My code here:

import React, { Component } from 'react'
import './demo.css'
import { Card } from '@material-ui/core';

export default class MasonryLayout extends Component {
  render() {
    return (
      <div className="masonry">
        <Card className="item" style={{height:"120px"}} elevation={4}/>
        <Card className="item" style={{height:"190px"}} elevation={4}/>
        <Card className="item" style={{height:"220px"}} elevation={4}/>
        <Card className="item" style={{height:"130px"}} elevation={4}/>
        <Card className="item" style={{height:"140px"}} elevation={4}/>
      </div>
    )
  }
}
.masonry {
    column-count: 2;
    column-gap: 56px;
    margin: 50px;
}

.item {
    margin-bottom: 40px;
    break-inside: avoid;
}

screenshot blew:
screenshot

A: I had the same issue. I solved it by adding the "ENOUGH" margin to the bottom/side.
NOTE
Just adding 1-2 px is not enough depending on your elevation. For me I had to add m={1.25} for elevation 5. If you add only a small amount of margin, it the shadows do not look natural and will look like a shadow in a box. You just need to add more margin to make it look as anticipated.


text:
Q: How to repair invalid extension paths in devenvexe.config After reinstalling Oracle Developer Tools 12.1.0.1 the extension is broken, it cannot load Oracle.VsDevTools.15.0.dll. Fusion log reveals that Visual Studio 2017 is trying to load the dll from this path:
c:\program files (x86)\microsoft visual studio\2017\professional\common7\ide\extensions\51aotvmw.pue\
The directory 51aotvmw.pue is empty, but I can see that the dll exists in the directory jqxrgi52.s10 I cannot find any other occurrences of Oracle.VsDevTools.15.0.dll on my PC.
If I just copy the content from 51aotvmw.pue to jqxrgi52.s10, the dll still does not load and the IDE complains about a version mismatch.
I cannot finde any configuration of the path 51aotvmw.pue anywhere else than in devenvexe.cfg. But if I edit or remove the invalid path there, it will be changed back to the original values once I started the IDE.
<dependentAssembly>
  <assemblyIdentity name="Oracle.VsDevTools.15.0" publicKeyToken="89b483f429c47342" culture="neutral"/>
  <codeBase version="4.122.1.0" href="c:\program files (x86)\microsoft visual studio\2017\professional\common7\ide\extensions\51aotvmw.pue\Assemblies\Oracle.VsDevTools.15.0.dll"/>
</dependentAssembly>

I attempted several reinstalls of the Oracle Developer Tools and ran out of ideas.

A: simply get rid of this clunky and legacy Oracle Developer Tools, especially if you only need the Oracle managed Client.
simply reference the Oracle.ManagedDataAccess nuget package. This will also help a lot in case of consistency hell on build, test and production servers!
https://www.nuget.org/packages/Oracle.ManagedDataAccess/


text:
Q: Problem with connection.readln waiting for carriage return I'm facing problem with TCpindy connection.readln method , I had no control in the other side sending data , when using Readln method in server side application hang (because receiving data don't contain carrige return ) , i'm trying readstring method but without success
Is there any suggestion to encouter this problem , me be looking for other component rather than indy ,
I need to get data from other client (tcp connection ) without any information about size of receiving data and without carriage return at the end of each frame.

A: You have to know how the data is being sent in order to read it properly.  TCP is a byte stream, the sender needs to somehow indicate where one message ends and the next begins, either by:

*

*prefixing each message with its
length

*putting unique delimiters in between
each message

*pausing in time between each message
Indy can handle all of these possibilities, but you need to identify which one is actually being used first.
Worse case scenerio, use the CurrentReadBuffer() method, which returns a String of whatever raw bytes are available at that moment.


text:
Q: Mathematica Integrate and Risch Algorithm Example I was looking at the integral described in this paper, which claims it is simple using the Risch algorithm and shows the result
$$\displaystyle \int \frac{x (x+1) \left(e^{2 x^2} x^2+2 e^{3 x^2} x \left(x-\left(2 x^3+2 x^2+x+1\right) \log (x+1)\right)-\log ^2(x+1)\right)}{\left((x+1) \log ^2(x+1)-\left(x^3+x^2\right) e^{2 x^2}\right)^2}~dx$$
I tried it with Mathematica (I thought that parts of the Risch algorithm were implemented), but to no avail with Windows10, x86, V13.
  Integrate[ x (x + 1) ((x^2 E^(2 x^2) - Log[x + 1]^2 +
  2 x E^(3 x^2) (x -
     1 (2 x^3 + 2 x^2 + x + 1) Log[x + 1])))/((x + 1) Log[
     x + 1]^2 - (x^3 + x^2) E^(2 x^2))^2, x]

I also tried to download and use the IntegrateAlgebraic, but didn't have any luck with it. Lastly, I was going to try in on FriCAS Online since it has most of the algorithm implemented, but couldn't get that to work.
Is there some way to coax MMA to solve this?

A: First, you do not need to download IntegrateAlgebraic anymore. It is integrated now in V 13 Integrate. By default, it is on
You can turn it off if you want, using the command
SetSystemOptions["IntegrateOptions" -> "UseIntegrateAlgebraic" -> False];

Mathematica has large parts of Risch implemented as far as I know, and it can indeed do this integral. After fixing typos you had from the paper.
ClearAll[x]
numer = x*(x + 1) *((x^2 *Exp[2*x^2] - Log[x + 1]^2)^2 +
    2 *x* Exp[3*x^2]*(x - (2 *x^3 + 2 *x^2 + x + 1)* Log[x + 1]))
denom = ((x + 1)*Log[x + 1]^2 - (x^3 + x^2) Exp[2 x^2])^2
Integrate[numer/denom, x]

Compare to the paper


text:
Q: Error in Installation of Module I'm trying to install the module zipline into Python 2.7 on Eclipse. I'm running the file with the following but the Error SyntaxError: invalid syntax results. I need help figuring this out.
import pip
pip install zipline

Edit: I have tried pip install zipline on the Command line as seen in the picture below but to no avail.

A: pip is a linux command, not a [tag: python] command. Thus, exit from the python interpreter and run the pip install in your Linux interpreter and it will run fine.
After installation, open your python interpreter and run
import zipline

And it should run fine.

A: You need to run pip install from the command line. Please note you also need to install numpy.

A: Run in command line
pip install zipline

OR
sudo pip install zipline

if any permission issues
Then in file, just import it
import zipline


text:
Q: Fire JavaScript event after synchronous Form POST? OK, so I think there isn't a way to do this, without using an iframe, or submitting my form via an ajax call, but anyways, I figured I'd ask.
Let's say I have a web server with the following config
public/
├── file.php
├── index.php
└── myfile.csv

On index.php I have a form. It is a POST form that has an action of file.php. Attached to that form is a JS event handler to insert some "Loading..." text into the DOM when it is submitted.
index.php
<!doctype html>

Reports

  <form action="file.php" id="my-form" method="post">
    <input type="submit" value="Generate and Download File" id="submit-button">
  </form>

Pretty simple. Now, file.php, imagine this is doing some heavy computations, and when it is done, it generates a .CSV file and serves it up for download.
Here is a sample that emulates what my script is doing:
file.php
<?php
// Dummy file
$file = 'myfile.csv';

// Simulate heavy calculations...
sleep(3);

if (file_exists($file)) {
    // Download the file
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}
?>

For completeness, here is myfile.csv:
myfile.csv
Hello,World

Now, here is my question:
After my file is served up, and the download starts, can I remove the "Loading..." text I inserted into the DOM?
Is there a JS event that can fire after a synchronous form gets POSTed?
Like I said, I don't think there is but I wanted to check around.

A: What it seems like you are doing here is using the browsers "cache" to continue showing the page even though the browser has requested a different page which returned a file and not HTML to be interpretted.
In my Experience we used jquery Ajax to show/hide a "Loading" DIV.
(Scroll down for non-ajax solution)
$.ajax({
    url: script_url,
    cache: false,
    async: sync_type,
    type: "POST",
    data: form_data,
    dataType: "html",
    beforeSend: function(jqXHR, settings)
    {
        //BUILD LOADING HTML
        loading_html = '

';

        //SHOW LOADING
        switch(return_mode)
        {
            case 'append':
                $('#'+container_id).addClass('ajax-loading');
            break;

            case 'prepend':
                $('#'+container_id).addClass('ajax-loading');
            break;

            default:
                $('#'+container_id).html(loading_html);
            break;
        }//END SWITCH RETURN MODE

    },//END FUNCTION BEFORESEND
    success: function(html_returned, success_code, jqXHR_object)
    {
        switch(return_mode)
        {
            case 'append':
                //APPEND HTML RESPONSE
                $('#'+container_id).append(html_returned);

            break;

            case 'prepend':
                $('#'+container_id).prepend(html_returned);

            break;

            default:
                //REPLACE CONTAINER CONTENTS WITH HTML RESPONSE
                $('#'+container_id).html(html_returned);

            break;
        }//END SWITCH RETURN MODE

    },//END FUNCTION SUCCESS
    error: function(jqXHR, exception)
    {

        //SHOW ERRORS
        if (jqXHR.status === 0)
        {
            //alert('Not connect.\n Verify Network.');
        } else if (jqXHR.status == 404)
        {
            //alert('Requested page not found. [404]');
        } else if (jqXHR.status == 500)
        {
            //alert('Internal Server Error [500].');
        } else if (exception === 'parsererror')
        {
            //alert('Requested JSON parse failed.');
        } else if (exception === 'timeout')
        {
            //alert('Time out error.');
        } else if (exception === 'abort')
        {
            //alert('Ajax request aborted.');
        } else {
            //alert('Uncaught Error.\n' + jqXHR.responseText);
        }//END IF JQXHR.STATUS === 0
    },//END FUNCTION ERROR
    complete: function(jqXHR, textStatus)
    {
        //REMOVE LOADING CLASS
        $('#'+container_id).removeClass('ajax-loading');

    }

});
ALL of that being said, if you really cant use a jquery ajax call, then you may try looking at tricking the page with some CSS.  For example have a

 which displays your loading details (spinners, etc.)
When they click to submit your form then display the loading DIV.
getElementById('loading_div').css("display", "block");

Then at the bottom of your page, have a javascript section which states:

If your file.php script redirects the browers back to your page:
header("Location: my_page_url.php");

Then they will see this loading div until the file is handled out, then the page with reload (but the download dialog will remain)


text:
Q: Node.js client for a socket.io server I have a socket.io server running and a matching webpage with a socket.io.js client. All works fine.
But, I am wondering if it is possible, on another machine, to run a separate node.js application which would act as a client and connect to the mentioned socket.io server?

A: That should be possible using Socket.IO-client: https://github.com/LearnBoost/socket.io-client

A: Adding in example for solution given earlier. By using socket.io-client https://github.com/socketio/socket.io-client
Client Side:
//client.js
var io = require('socket.io-client');
var socket = io.connect('http://localhost:3000', {reconnect: true});

// Add a connect listener
socket.on('connect', function (socket) {
    console.log('Connected!');
});
socket.emit('CH01', 'me', 'test msg');

Server Side :
//server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

io.on('connection', function (socket){
   console.log('connection');

  socket.on('CH01', function (from, msg) {
    console.log('MSG', from, ' saying ', msg);
  });

});

http.listen(3000, function () {
  console.log('listening on *:3000');
});

Run :
Open 2 console and run node server.js and node client.js

A: const io = require('socket.io-client');
const socket_url = "http://localhost:8081";

let socket = io.connect(socket_url);

socket.on('connect', function () {
    socket.emit("event_name", {});
});

A: After installing socket.io-client:
npm install socket.io-client

This is how the client code looks like:
var io = require('socket.io-client'),
socket = io.connect('http://localhost', {
    port: 1337,
    reconnect: true
});
socket.on('connect', function () { console.log("socket connected"); });
socket.emit('private message', { user: 'me', msg: 'whazzzup?' });

Thanks alessioalex.

A: Yes you can use any client as long as it is supported by socket.io. No matter whether its node, java, android or swift. All you have to do is install the client package of socket.io.

A: Client side code: I had a requirement where my nodejs webserver should work as both server as well as client, so i added below code when i need it as client, It should work fine, i am using it and working fine for me!!!
const socket = require('socket.io-client')('http://192.168.0.8:5000', {
            reconnection: true,
            reconnectionDelay: 10000
          });

        socket.on('connect', (data) => {
            console.log('Connected to Socket');
        });

        socket.on('event_name', (data) => {
            console.log("-----------------received event data from the socket io server");
        });

        //either 'io server disconnect' or 'io client disconnect'
        socket.on('disconnect', (reason) => {
            console.log("client disconnected");
            if (reason === 'io server disconnect') {
              // the disconnection was initiated by the server, you need to reconnect manually
              console.log("server disconnected the client, trying to reconnect");
              socket.connect();
            }else{
                console.log("trying to reconnect again with server");
            }
            // else the socket will automatically try to reconnect
          });

        socket.on('error', (error) => {
            console.log(error);
        });

A: something like this worked for me
const WebSocket = require('ws');
const ccStreamer = new WebSocket('wss://somthing.com');

ccStreamer.on('open', function open() {
  var subRequest = {
    "action": "SubAdd",
    "subs": [""]
  };
  ccStreamer.send(JSON.stringify(subRequest));
});

ccStreamer.on('message', function incoming(data) {
  console.log(data);
});


text:
Q: How do I stop Chrome window from being always on top? Chrome suddenly started hogging the desktop.  Once it is open it does not allow any other app to be on top.  It is quite annoying.  I researched the problem and the suggestion to use alt+space+c key works only momentarily.
Other suggestions included going back to default settings, but that would erase the history (which I find very useful at times) and other settings.
Is there another solution?
Thanks for any ideas.

A: Alt+Space+c worked for me.  It closed all my open Google Chrome windows, but I just reopened, hit ctrl+shift+t to reopen the closed window and the problem seems to have gone away for now.


text:
Q: xamarin form: Custom View in listview on android screw up I found xamarin render ui is very difficult.
I have a custom view inside the listview which contain a list of small icons. Each item may have some visible icon showing. I realized when i scrolled down to bottom and scroll back to the top, the one supposed to have that icon to be shown was not shown. I passed in an object into the custom view to tell which one to be displayed.
Item in listview, local:ChildInfoIconsView is the custom view.
                                        <StackLayout Orientation="Vertical"
                                           Grid.Row="0"
                                           Grid.Column="1"
                                            VerticalOptions="Center"
                                            HorizontalOptions="Start">
                                            <Label AutomationId="aChildName" Style="{StaticResource MediumBoldFont}" x:Name="childName" Text="{Binding DisplayName}" HorizontalOptions="StartAndExpand" />
                                            <local:ChildInfoIconsView
                                                Child="{Binding .}"
                                                VerticalOptions="Fill">
                                            </local:ChildInfoIconsView>
                                        </StackLayout>

Main Code for custom view
public partial class ChildInfoIconsView : ContentView
{
    public static readonly BindableProperty OrientationProperty = BindableProperty.Create(nameof(Orientation), typeof(StackOrientation), typeof(StackOrientation), StackOrientation.Vertical, BindingMode.OneWay, null);
    public static readonly BindableProperty ShowClassroomProperty = BindableProperty.Create(nameof(ShowClassroom), typeof(bool), typeof(bool), true, BindingMode.OneWay, null);
    public static readonly BindableProperty ChildProperty = BindableProperty.Create(nameof(Child), typeof(ChildModel), typeof(ChildModel), null, BindingMode.OneWay, null);

    protected override void OnPropertyChanged(string propertyName = null)
    {
        base.OnPropertyChanged(propertyName);

        if (propertyName.Equals(nameof(Child)))
        {
            if (Child != null)
            {
                this.ImageUnauth.IsVisible = (Child.HasUnauthorized.HasValue) ? Child.HasUnauthorized.Value : false;
                this.ImageMedical.IsVisible = (Child.HasMedical.HasValue) ? Child.HasMedical.Value : false;
                this.ImageBirthday.IsVisible = Child.IsBirthday;
                this.ImageNewChild.IsVisible = !string.IsNullOrEmpty(Child.NewChildFlagImage);
                this.ImageClassroom.IsVisible = (!ShowClassroom) ? false : !string.IsNullOrEmpty(Child.Classroom);

                this.textClass.Text = Child.Classroom;
                this.textClass.IsVisible = (!ShowClassroom) ? false : !string.IsNullOrEmpty(Child.Classroom);
            }
        }
        else if (propertyName.Equals(nameof(ShowClassroom)))
        {
            this.ImageClassroom.IsVisible = ShowClassroom;
            this.textClass.IsVisible = ShowClassroom;
        }
        else if (propertyName.Equals(nameof(Orientation)))
        {
            this.layout.Orientation = Orientation;
        }
    }

    public ChildInfoIconsView()
    {
        InitializeComponent();
    }

    public StackOrientation Orientation
    {
        get
        {
            return (StackOrientation)GetValue(OrientationProperty);
        }
        set
        {
            SetValue(OrientationProperty, value);
        }
    }

    public bool ShowClassroom
    {
        get
        {
            return (bool)GetValue(ShowClassroomProperty);
        }
        set
        {
            SetValue(ShowClassroomProperty, value);
        }
    }

    public ChildModel Child
    {
        get
        {
            return (ChildModel)GetValue(ChildProperty);
        }
        set
        {
            SetValue(ChildProperty, value);
        }
    }

It work fine when using old version of xamarin.forms. When updated the package, this happen on android.


text:
Q: Pandas not updating all rows I know I'm doing something wrong but I can't figure it out.
What I'm trying to do is for every customer I want to check if they have some rows in the dataframe which meet some criteria. If that's true, then I want to update the rows for that customer, regardless if they are responsive to the original check with a 1 or 0. However, when I run the code below it only updates the rows where they were responsive to the original query:
temp = dfCustomers.loc[customer & activeCustomer & end_date_filter ]

What I'm assuming is happening is that dfCustomers is being narrowed down to the responsive rows, but I can't figure out. How to stop that from happening?
Bonus question, is there a better way to do this rather than looping?
dfCustomers = dfMerged.copy()

for cust in dfCustomers['Account Name'].unique():

    customer = dfCustomers['Account Name'] == cust
    activeCustomer = dfEngineCustomers['engine-customer'] == 1
    end_date_filter = dfEngineCustomers['correct-end-date'] >= pd.to_datetime('today')

    temp = dfCustomers.loc[customer & activeCustomer & end_date_filter ]

    if len(temp) > 0:
        dfCustomers.loc[(dfCustomers['Account Name'] == cust),'active-customer'] = 1
    else:
        dfCustomers.loc[(dfCustomers['Account Name'] == cust) & (dfCustomers['customer'] == 1) ,'active-customer'] = 0

A: Regarding you for loop, you might wanna look at pandas.DataFrame.groupby
for customer, df_customer in dfCustomers.groupby('Account Name'):
...

A: So I think I figured this out, I don't actually know why this works but the line:
dfCustomers.loc[(dfCustomers['Account Name'] == cust),'active-customer'] = 1

should be:
dfCustomers.loc[dfCustomers['Account Name'] == cust,'active-customer'] = 1

No brackets.
Anybody know why this makes a difference, I'm coming from Java/PHP?


text:
Q: Delete all files with no name but variable extension How do I create a batch command that will recursively go through my folders and remove all files that:

*

*Have no name before the extension

*The extension begins with ._
For example, ._Icon or ._Public
This script has to run on boot and preferably hides in the background but I can probably figure that out once I have a batch script.
The directory in question is D:\Dropbox
Can this be done with batch scripting or do I need something else?
Thanks!

A: @echo off
pushd d:\dropbox
del /s ._*
popd

You can establish this .bat as a scheduled task, which will run on boot.


text:
Q: AFNetworking not supporting DWG files? I have an In-house Ipad App that opens files that are stored elsewhere on the network through filters, menus, etc.
The Main Formats for the Images are Tiff or PDF, so I convert them to a PDF (if TIFF) using a web-service.
Users are asking to include DWG files and I downloaded a DWG viewer on the Ipad. I would like to use AFNetworking to download the DWG file from the server to the Ipad but it doesn't seem to work.
The same code works great for PDF files:
urlString = [urlString stringByAppendingString:strFile];

NSURL *url = [NSURL URLWithString:urlString];

NSURLRequest *req = [NSURLRequest requestWithURL:url];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
                                     initWithRequest:req];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,    NSUserDomainMask, YES);
NSString *outputPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:strFile];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:outputPath append:NO];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Successfully downloaded file to %@", outputPath);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

[operation start];

Thanks,
Shai

A: From what I understand, AFNetworking can download any file. The problem here was on the Web Server settings, more specifically the Mime settings for .DWG files were missing.


text:
Q: Median and mode in excel using multiple columns I am working on a spreadsheet for my statistics class. It contains a column filled with a quantity and a column filled with a frequency for each quantity. Using these two columns and several formulas, the mean, mode, median, coefficient variation, quartiles, interquartile range, minimum and maximum values and standard deviation can be found.
The issue is that to shorten the list of quantities, the use of the frequencies column comes in. Take the quantity list of : 10, 12, 14, 15, 18, 18, 10.
Notice that 18 and 10 have been repeated. Instead of repeating those quantities in my quantities column, I increment the frequency of that quantity from 1 to 2. The reason for doing it this way is due to very large lists of quantity data. Meaning I might have 5000 quantities that could potentially be reduced to 20 quantities where each quantity will have a larger frequency.
The issue is that the built-in Median and Mode function use only 1 column or row and do not account for the frequency of each quantity.
My question is this: Is there a way to use both columns to calculate the median and mode? Below is an example of what I was explaining. Additionally, my column containing quantities and frequencies may not be filled from start to end, meaning there maybe empty entries.
Quantity  |  Frequency
  10      |     4
  12      |     6
  11      |     3
  15      |     1
  18      |     10

VS.

Quantity
10
10
10
10
12
12
12
12
12
12
11
11
11
15
18
18
18
18
18
18
18
18
18
18

A: If one has Office 365 with the dynamic array formula use:
=MEDIAN(INDEX(A2:A6,MATCH(SEQUENCE(SUM(B2:B6),,0),SUMIF(OFFSET(B1,0,,ROW(B2:B6)-MIN(ROW(B2:B6))+1,),"<>"))))

and
=MODE.SNGL(INDEX(A2:A6,MATCH(SEQUENCE(SUM(B2:B6),,0),SUMIF(OFFSET(B1,0,,ROW(B2:B6)-MIN(ROW(B2:B6))+1,),"<>"))))

If not then this array formula:
=MEDIAN(INDEX(A2:A6,MATCH(ROW($ZZ1:INDEX($ZZ:$ZZ,SUM(B2:B6)))-1,SUMIF(OFFSET(B1,0,,ROW(B2:B6)-MIN(ROW(B2:B6))+1,),"<>"))))

and
=MODE.SNGL(INDEX(A2:A6,MATCH(ROW($ZZ1:INDEX($ZZ:$ZZ,SUM(B2:B6)))-1,SUMIF(OFFSET(B1,0,,ROW(B2:B6)-MIN(ROW(B2:B6))+1,),"<>"))))

Being array formula, then need to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.

A: Assuming that each Quantity only appears once alongside its Frequency, then you could use an INDEX MATCH on the MAX Frequency to find the Mode:
=INDEX(A2:A6,Match(Max(B2:B6), B2:B6, 0))

This will, of course, only return the first number should there be multiple Quantities which share the same maximum frequency (such as if Quantity 12 also occurred with Frequency 10)
Further assuming that your Quantities are in Ascending Order, you can use Matrix Multiplication (MMULT) to calculate the running total for each row, and use AGGREGATE to get the smallest row where the running total greater-than-or-equal-to half the overall total.  This is the Median:
=AGGREGATE(15, 6, A2:A6/(MMULT(--(TRANSPOSE(ROW(B2:B6))<=ROW(B2:B6)), B2:B6)>=0.5*SUM(B2:B6)), 1)

(For reference, MMULT(--(TRANSPOSE(ROW(B2:B6))<=ROW(B2:B6)), B2:B6) is the bit which works out the Running total)


text:
Q: matplotlib subplots in a column with common horizontal colorbar I have seen those nice solutions for making multiple subplots maintaining the aspect ratio "equal" of each subplot:
Matplotlib 2 Subplots, 1 Colorbar
https://stackoverflow.com/a/23953487/10659110
...but with a different geometry.
I wave 3 "square" plots (3 colormaps with the same x and y ranges) and I want to arrange them in a vertical column, with a single horizontal colorbar at the top or bottom.
Here an example:
#!/usr/bin/env python3

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show

Nlatt  = 200
Lrange = 20

# Create grid values first.
xs = np.linspace(-Lrange, Lrange, Nlatt,  endpoint=True)
ys = np.linspace(-Lrange, Lrange, Nlatt , endpoint=True)
X,Y = meshgrid(xs, ys)         # grid of point

Zx = np.sin(Y-X)*np.sin(Y+X)
Zy = np.cos(Y)*np.sin(X)
ZZ = np.sqrt( Zx**2 + Zy**2 )

fig = plt.figure()  #e.g. "2,3,4" means "2x3 grid, 4th subplot"
ax1 = fig.add_subplot(3,1,1, aspect = "equal")
ax2 = fig.add_subplot(3,1,2, aspect = "equal")
ax3 = fig.add_subplot(3,1,3, aspect = "equal")

im1 = ax1.pcolor( X , Y , Zx , cmap='bwr' ,vmin=-2.5, vmax=2.5)
im2 = ax2.pcolor( X , Y , Zy , cmap='bwr' ,vmin=-2.5, vmax=2.5)
im3 = ax3.pcolor( X , Y , ZZ , cmap='bwr' ,vmin=-2.5, vmax=2.5)

plt.tight_layout()

plt.show()

I want to add the common horizontal colorbar at the top (or at the bottom) and share the x-axis, so that the label "x" and the x-coordinate numbers appear only on the bottom of the third plot. in practice, the desired output is the one described in Matplotlib shared horizontal colorbar aligned with bottom axis in subplots , but it is not very clear to me how this solution works. Moreover, I also want a single label and numbers for the x-axis at the bottom. Thank you for every hint.


text:
Q: Fabrication has_many though with validation I'm just getting into testing and I have many models that utilize a has_many though relationship. In each case, one model requires that the other be present at the time of save. I've run into a wall with every testing system I've tried (FactoryGirl, Fixtures, and now Fabrication) where I can not figure out how to set up the tests correctly to replicate this behavior.
I followed this GIST as an example but changed the after_build to before_save as the models are requiring the "though" model at that time. Am I approaching this the wrong way? How does one test this relationship/functionality?
I've created a GIST that is hopefully easier to use/read.

A: I changed this
Fabricator(:brand) do
  title "Coca Cola"

  before_save do |brand|
    styles Fabricate(:brand_style, :brand => brand, :style => Fabricate(:style))
  end
end

to this
Fabricator(:brand) do
  title "Coca Cola"

  styles(count: 3) { Fabricate(:style) }
end

and now the test is passing. However, I'm not sure if this is the correct way of setting this up, so if anyone has any additional insight it would be appreciated.


text:
Q: ASP.Net MVC @Url.Action() routing to the wrong controller I'm newbie to MVC. I could integrate MVC 5.2 to my existing web forms Visual Studio 2012 Update 4 project. I created my first controller and all worked as expected. Even I was able to  leverage the windows forms authentication from my existing project when accessing the MVC view. But when created my second controller it began messing up.
It is my route mapping:
public static class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.EnableFriendlyUrls();

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

I have two controllers both located in ~/Controllers. My first controller is:
public class HomeController : Controller
{
    //
    // GET: /Home/
    public ActionResult Index()
    {
        //return View();
        return Redirect("~/Default.aspx");
    }

    public ActionResult CloseSession()
    {
        return Redirect("http://www.yahoo.com");
    }
}

The second controller:
public class CajaWebController : Controller
{
    //
    // GET: /CajaWeb/
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult CloseSession()
    {
        return Redirect("http://www.cnn.com");
    }
}

I don't know is it relevant to the problem but I'll include how the MVC view is reached. My VS2012 start url is
http://localhost/Fortia/CajaWeb.

Fortia is my app name. Because I declared Web Forms authentication and
<location path="CajaWeb">
  <system.web>
    <authorization>
      <allow roles="Fortia" />
      <deny users="*" />
    </authorization>
  </system.web>
</location>

when starting to debug the old WebForms app authentication mechanism is called, the old WebForms login page invoked and after a successful login finally my CajaWebController, Index() action is called. Before creating CajaWebController it was the HomeController who was called, but I assume MVC now deduces the correct controller is CajaWeb because of the  targeted url being
http://localhost/Fortia/CajaWeb.

The invoked view contains the following code:
Close session

The problem is when clicking the generated link the MVC calls HomeController.Index() action despite I explicitly set CajaWebController.CloseSession() in the @Url.Action...
I looked at the generated link and it looks wrong:

it encoded the parameter separator & into & But anyway I tried handcoding the href as
http://localhost/Fortia/__FriendlyUrls_SwitchView?action=CloseSession&controller=CajaWeb

but the result was the same.
What is wrong?

A: I think the problem is that the route
http://localhost/Fortia/CajaWeb
doesn't match any routes so it ends up going to the default route specified in RouteConfig.  You need to configure a route or create an area in your app called "Fortia".

A: It would seem the ASP.NET Friendly Urls package you're using is interfering with the urls MVC is generating. The library seems to be meant for WebForms anyway
If it works without, then leave it like that as MVC's urls are already quite SEO-friendly when controller and action names are meaningful to their content.


text:
Q: Hide twitter bootstrap popover Following is my jquery code which i  am using to display popover .  What i wanna do is when a user click anywhere on the screen or on any  then it hides the current opened popover and show a new popover on which the user clicks on.
As You can see below span which contains class="pover" are being poped up by the following jquery kindly let me know how can i hide the opened popup and display a new one accordingly
Currently, all the popover are getting displayed on click event.
$(document).ready(function() {
    $('.pover').each(function() {
        //$('#close').popover( "hide" );
        $(this).popover({
            title: $(this).attr('abc'),
            content: $(this).attr('data-content'),
            delay: "show",
            trigger: "click"
        });
    });
});

A: Found this great solution:
Exactly what I am seeking to do.
https://github.com/lecar-red/bootstrapx-clickover
http://www.leecarmichael.com/bootstrapx-clickover/examples.html


text:
Q: List comprehension with dictionaries for models I have a class of Post I would like to be able to key into the comments whoms value is a list comprehension of a to_dict() method for every comment, my question is how do I key into each object in this list to get that comments data?
Post model
class Post(db.Model):
tablename = 'posts'
id = db.Column(db.Integer, primary_key=True)
caption = db.Column(db.String, nullable=False)
picture_url = db.Column(db.String(255), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
timestamp = db.Column(db.DateTime, default=datetime.now)

users = db.relationship("User", back_populates="posts")
comments = db.relationship("Comment", back_populates="posts")
postLikes = db.relationship("User", secondary=likes, back_populates="userLikes")
def to_dict(self):
    user = User.query.filter(User.id == self.user_id).first()

    return {
        "id": self.id,
        "caption": self.caption,
        'picture_url': self.picture_url,
        "user_id": self.user_id,
        "timestamp": self.timestamp,
        "user": user.to_dict(),
        "post_comments": [comment.to_dict() for comment in self.comments],
        "post_likes": [user.id for user in self.postLikes],
        "likes_count": len(self.postLikes),
        "comments_count": len(self.comments)
    }

Comment model
class Comment(db.Model):
    __tablename__ = 'comments'

    id = db.Column(db.Integer, primary_key=True)
    comment = db.Column(db.String(255), nullable=False)
    post_id = db.Column(db.Integer, db.ForeignKey("posts.id"))
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    createdAt = db.Column(db.DateTime(timezone=True),
                        server_default=func.now())
    updatedAt = db.Column(db.DateTime(timezone=True), onupdate=func.now())

    users = db.relationship('User', back_populates='comments')
    posts = db.relationship('Post', back_populates='comments')

    def to_dict(self):
        return {
            "id": self.id,
            "user": self.users.username,
            "user_pic": self.users.profile_picture,
            "comment": self.comment,
            "post_id": self.post_id,
            "createdAt": self.createdAt,
            "updatedAt": self.updatedAt
        }

**Mapping over a list of posts, for every post : **
 {post?.post_comments.map(comm => {
                                        <div>{comm.user_pic}</div>
                                    })}

what posts looks like
{
"posts": [
    {
        "caption": "Hammy's got the crazy eyes. Get ready to be pounced…",
        "comments_count": 2,
        "id": 1,
        "likes_count": 0,
        "picture_url": "https://celebritypets.net/wp-content/uploads/2017/03/Hamilton-the-Hipster-Cat-instagram.jpg",
        "post_comments": [
            {
                "comment": "comment example",
                "createdAt": "Thu, 02 Sep 2021 14:04:43 GMT",
                "id": 1,
                "post_id": 1,
                "updatedAt": null,
                "user": "hamilton_this_hipster_cat",
                "user_pic": "https://i.insider.com/5654a4c0c2814477008b51d8?width=750&format=jpeg&auto=webp"
            },
            {
                "comment": "comment on first post again",
                "createdAt": "Thu, 02 Sep 2021 14:04:43 GMT",
                "id": 2,
                "post_id": 1,
                "updatedAt": null,
                "user": "DogtorLoki",
                "user_pic": "https://photos.bringfido.com/posted/2020/08/04/849663/loki-1.jpg"
            }
        ],
        "post_likes": [],
        "timestamp": "Wed, 01 Sep 2021 16:16:58 GMT",
        "user": {
            "biography": "Mustache Cat. Yes, it's real. San Francisco, CA. #AdoptDontShop",
            "email": "hamilton@aa.io",
            "id": 1,
            "profile_picture": "https://i.insider.com/5654a4c0c2814477008b51d8?width=750&format=jpeg&auto=webp",
            "username": "hamilton_this_hipster_cat"
        },
        "user_id": 1
    },
    {
        "caption": "If dogs are good for your health, then two unicorns must be MAGICAL",
        "comments_count": 1,
        "id": 2,
        "likes_count": 0,
        "picture_url": "https://static.onecms.io/wp-content/uploads/sites/20/2021/01/05/dogtor-2.jpg",
        "post_comments": [
            {
                "comment": "comment on second post",
                "createdAt": "Thu, 02 Sep 2021 14:04:43 GMT",
                "id": 3,
                "post_id": 2,
                "updatedAt": null,
                "user": "hamilton_this_hipster_cat",
                "user_pic": "https://i.insider.com/5654a4c0c2814477008b51d8?width=750&format=jpeg&auto=webp"
            }
        ],
        "post_likes": [],
        "timestamp": "Wed, 01 Sep 2021 16:16:58 GMT",
        "user": {
            "biography": "A Baltimore Pup+MedStudent Mom, AMC Top Dog Honoree",
            "email": "dogtorloki@aa.io",
            "id": 2,
            "profile_picture": "https://photos.bringfido.com/posted/2020/08/04/849663/loki-1.jpg",
            "username": "DogtorLoki"
        },
        "user_id": 2
    }
]

}

A: Turns out I wasn't accessing the keys the correct way ehh...['key']


text: Q: How to know the version of PCIe of motherboard? I have a laptop that I want to upgrade its SDD drive. How can I figure out what version of PICe is supported by the motherboard? (through Windows and not by opening up the laptop).


text:
Q: How can I search through a string a get only an specific part of it JS? I'd like to search only a specific piece of a string and show it using nothing more than JS or Jquery.
For example, (It just looks like a JSON, but it's not, it's just brackets some stuff ;) ):
var data =
 [{"name":"node1","id":1,"is_open":true,"children":
   [
     {"name":"child2","id":3},
     {"name":"child1","id":2}
   ]
 }];

I'd like to pick up only the ID numbers:
The "code" below is not a language, it's just an example to help understanding what I'd like to do on JS/jQuery

var IDs = [searchThrough] data [where there is] "id": [getContent] after : and before , or } alert("IDs: "+IDs);

It allows me to:
1 - set a parameter of what I want from a string find "id": on data.
2 - set the start and end for getting the content after : and before , or }
How can I do it?
Thanks in advance.
"Beam me up Scotty!"

A: If I understand you, you want to search a String that represents the data. In this case, you could use a regular expression like the following:
var matcher = /"id":([^,\}]*/g, // capture all characters between "id" and , or }
    match, IDs = [];

while (match = matcher.exec(data)) {
  IDs.push(match[1]);
}

alert(IDs);

A: I am no regex guru,but this is my try.
var data = '[{"name":"node1","id":1,"is_open":true,"children":[{"name":"child2","id":3},{"name":"child1","id":2}]}]';
var arrays=[];
var t1=data.match(/"id":[0-9]+(,|})*/g);
for(var x=0;x<t1.length;x++)
{
  arrays.push(t1[x].match(/\d+/));

}
alert(arrays);

A: If we take the assumption that you are dealing with a string, we can pull out the data using regular expression:

var str = '[{"name":"node1","id":1,"is_open":true,"children":\n   [\n     {"name":"child2","id":3},\n     {"name":"child1","id":2}\n   ]\n }];';
var regex = /"id":([0-9]*)/g;
var match = regex.exec(str);

var res = new Array();

while (match != null) {
  res.push(match[1]);
  match = regex.exec(str);
}

var ids = res.join();

alert("IDs: " + ids);

This demo will give you an alert box with the content "IDs: 1,3,2"


text:
Q: iphone json parser and NsmutableDictionary I got the Response string
{"status":200,"response":
 {"data":
  [{"category_name":"Clubs","items":
     [{"id":"4ee097a59f39d00308000004","name":"Item B","image":"/uploads/item/image/4ee097a59f39d00308000004 /thumb_cyber.png","description":"Thuudd","price":90,"monentary_type":1
     }]
   }],
 "message":"List of all the items"}}

This is my string I just Parse
pro_Catagory        =   [jsonDictionary objectForKey:@"status"];

I got the 200
But The following is not working
Its pointing to Null
pro_Status  =   [jsonDictionary objectForKey:@"response.data.category_name"];

How can i get other values help me...

A: you should use like this:
pro_status = [[[[jsonDictionary valueForKey:response] valueForKey:data] objectAtIndex:1] valueForKey:@"category_name];


text:
Q: How to slide the ActionBar along with the NavigationDrawer What I want to do is slide the ActionBar along with the NavigationDrawer when the drawer is opened. I am currently not using any third party libraries and if at all possible I want to keep it that way. All i need is an implementation of method like: getActionBarView.slide(dp);
This is the code I currently use to create the NavigationDrawer:
mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {

    public void onDrawerClosed(View view) {
        invalidateOptionsMenu();

        // calling onPrepareOptionsMenu() to hide action bar icons
    }

    @Override
    public void onDrawerSlide(View drawerView, float slideOffset) {
        if (getDeviceType(getApplicationContext()) == DEVICE_TYPE_PHONE) {
            drawerLayout.setScrimColor(Color.parseColor("#00FFFFFF"));
            float moveFactor = (listView.getWidth() * slideOffset);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                all_menu_container_parent.setTranslationX(moveFactor);
            } else {
                TranslateAnimation anim = new TranslateAnimation(lastTranslate, moveFactor, 0.0f, 0.0f);
                anim.setDuration(0);
                anim.setFillAfter(true);
                all_menu_container_parent.startAnimation(anim);

                lastTranslate = moveFactor;
            }
        }
    }

    public void onDrawerOpened(View drawerView) {
        // calling onPrepareOptionsMenu() to hide action bar icons
    }
};
drawerLayout.setDrawerListener(mDrawerToggle);

But it doesn't do what I want, it produces this:

What I want to achieve is this:

A:
PLEASE NOTE: This answer was originally written when Android 4.4 (KitKat) was still pretty new. Since Android 5.0 and especially
  because of the introduction of the ToolBar this answer cannot be
  considered up-to-date anymore! But from a technical perspective and for
  those of you who want to learn about the inner workings of Android
  this answer might still hold a lot of value!

The NavigationDrawer was specifically designed to be situated below the ActionBar and there is no way to implement the NavigationDrawer to make the ActionBar move with it - unless maybe looking for the View which makes up the ActionBar and animating it alongside the NavigationDrawer, but I would never recommend something like this as it would be difficult and error prone. In my opinion you only have two options:

*

*Using a library like the SlidingMenu

*Implementing a custom sliding menu

Since you said that you don't want to use a library implementing a custom sliding menu is your only option, fortunately this is really not that hard once you know how to do it.

1) Basic Explanation
You can move the whole content of the Activity - I mean everything including the ActionBar - by putting a margin or a padding on the View which makes up the Activity. This View is the parent of the View with the id android.R.id.content:
View content = (View) activity.findViewById(android.R.id.content).getParent();

On Honeycomb (Android version 3.0 - API level 11) or above - in other words after the ActionBar was introduced - you need to use margins to change the Activities position and on previous versions you need to use a padding. To simplify this I recommend creating helper methods which perform the correct action for each API level. Let's first look at how to set the position of the Activity:
public void setActivityPosition(int x, int y) {
    // With this if statement we can check if the devices API level is above Honeycomb or below
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // On Honeycomb or abvoe we set a margin
        FrameLayout.LayoutParams contentParams = (FrameLayout.LayoutParams) this.content.getLayoutParams();
        contentParams.setMargins(x, y, -x, -y);
        this.content.setLayoutParams(contentParams);
    } else {
        // And on devices below Honeycomb we set a padding
        this.content.setPadding(x, y, -x, -y);
    }
}

Notice that in both cases there is either a negative margin or a negative padding on the opposite sides. This is to essentially increase the size of the Activity beyond its normal bounds. This prevents the actual size of the Activity to change when we slide it somewhere.
We additionally need two methods to get the current position of the Activity. One for the x position, one for the y position:
public int getActivityPositionX() {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // On Honeycomb or above we return the left margin
        FrameLayout.LayoutParams contentParams = (FrameLayout.LayoutParams) this.content.getLayoutParams();
        return contentParams.leftMargin;
    } else {
        // On devices below Honeycomb we return the left padding
        return this.content.getPaddingLeft();
    }
}

public int getActivityPositionY() {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // On Honeycomb or above we return the top margin
        FrameLayout.LayoutParams contentParams = (FrameLayout.LayoutParams) this.content.getLayoutParams();
        return contentParams.topMargin;
    } else {
        // On devices below Honeycomb we return the top padding
        return this.content.getPaddingTop();
    }
}

It is also very simple to add animations. The only important thing here is a bit of math to animate it from its previous position to its new position
// We get the current position of the Activity
final int currentX = getActivityPositionX();
final int currentY = getActivityPositionY();

// The new position is set
setActivityPosition(x, y);

// We animate the Activity to slide from its previous position to its new position
TranslateAnimation animation = new TranslateAnimation(currentX - x, 0, currentY - y, 0);
animation.setDuration(500);
this.content.startAnimation(animation);

You can display a View at the location which is revealed by sliding away the Activity by adding it to the parent of the View:
final int currentX = getActivityPositionX();

FrameLayout menuContainer = new FrameLayout(context);

// The width of the menu is equal to the x position of the `Activity`
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(currentX, ViewGroup.LayoutParams.MATCH_PARENT);
menuContainer.setLayoutParams(params);

ViewGroup parent = (ViewGroup) content.getParent();
parent.addView(menuContainer);

And that is pretty much all you need to create a basic sliding menu that works on most if not all devices above Eclair (Android 2.1 - API level 7).

2) Animating the Activity
The first part of creating a sliding menu is making the Activity move out of the way. As such we should first try to move the Activity around like this:

To create this we just have to put the code above together:
import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;

public class ActivitySlider {

    private final FragmentActivity activity;
    private final View content;

    public ActivitySlider(FragmentActivity activity) {
        this.activity = activity;

        // Here we get the content View from the Activity.
        this.content = (View) activity.findViewById(android.R.id.content).getParent();
    }

    public void slideTo(int x, int y) {

        // We get the current position of the Activity
        final int currentX = getActivityPositionX();
        final int currentY = getActivityPositionY();

        // The new position is set
        setActivityPosition(x, y);

        // We animate the Activity to slide from its previous position to its new position
        TranslateAnimation animation = new TranslateAnimation(currentX - x, 0, currentY - y, 0);
        animation.setDuration(500);
        this.content.startAnimation(animation);
    }

    public void setActivityPosition(int x, int y) {
        // With this if statement we can check if the devices API level is above Honeycomb or below
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // On Honeycomb or above we set a margin
            FrameLayout.LayoutParams contentParams = (FrameLayout.LayoutParams) this.content.getLayoutParams();
            contentParams.setMargins(x, y, -x, -y);
            this.content.setLayoutParams(contentParams);
        } else {
            // And on devices below Honeycomb we set a padding
            this.content.setPadding(x, y, -x, -y);
        }
    }

    public int getActivityPositionX() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // On Honeycomb or above we return the left margin
            FrameLayout.LayoutParams contentParams = (FrameLayout.LayoutParams) this.content.getLayoutParams();
            return contentParams.leftMargin;
        } else {
            // On devices below Honeycomb we return the left padding
            return this.content.getPaddingLeft();
        }
    }

    public int getActivityPositionY() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // On Honeycomb or above we return the top margin
            FrameLayout.LayoutParams contentParams = (FrameLayout.LayoutParams) this.content.getLayoutParams();
            return contentParams.topMargin;
        } else {
            // On devices below Honeycomb we return the top padding
            return this.content.getPaddingTop();
        }
    }
}

You can use the ActivitySlider class like this:
ActivitySlider slider = new ActivitySlider(activity);

// This would move the Activity 400 pixel to the right and 100 pixel down
slider.slideTo(400, 100);

3) Adding the sliding menu
Now we want to reveal a menu when the Activity moves out of the way like this:

As you can see it also pushes the ActionBar to the side.
The ActivitySlider class does not need to be modified that much to create a sliding menu, basically we just add two methods, showMenu() and hideMenu(). I will stick to best practices and use a Fragment as the sliding menu. The first thing we need need is a View - for example a FrameLayout - as a container for our Fragment. We need to add this View to the parent of the View of the Activity:
// We get the View of the Activity
View content = (View) activity.findViewById(android.R.id.content).getParent();

// And its parent
ViewGroup parent = (ViewGroup)  content.getParent();

// The container for the menu Fragment is a FrameLayout
// We set an id so we can perform FragmentTransactions later on
FrameLayout menuContainer = new FrameLayout(this.activity);
menuContainer.setId(R.id.flMenuContainer);

// The visibility is set to GONE because the menu is initially hidden
menuContainer.setVisibility(View.GONE);

// The container for the menu Fragment is added to the parent
parent.addView(menuContainer);

Since we set the visibility of the container View to VISIBLE only when the sliding menu is actually open we can use the following method to check if the menu is open or closed:
public boolean isMenuVisible() {
    return this.menuContainer.getVisibility() == View.VISIBLE;
}

To set the menu Fragment we add a setter method that performs a FragmentTransaction and adds the menu Fragment to the FrameLayout:
public void setMenuFragment(Fragment fragment) {
    FragmentManager manager = this.activity.getSupportFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.replace(R.id.flMenuContainer, fragment);
    transaction.commit();
}

I also tend to add a second setter which instantiates the Fragment from a Class for convenience:
public <T extends Fragment> void setMenuFragment(Class<T> cls) {
    Fragment fragment = Fragment.instantiate(this.activity, cls.getName());
    setMenuFragment(fragment);
}

There is one additional important thing to consider when it comes to the menu Fragment. We are operating much further up in the View hierarchy than normally. As such we have to take things like the height of the status bar into account. If we didn't account for this the top of the menu Fragment would we be hidden behind the status bar. You can get the height of the status bar like this:
Rect rectangle = new Rect();
Window window = this.activity.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectangle);
final int statusBarHeight = rectangle.top;

We have to put a top margin on the container View of the menu Fragment like this:
// These are the LayoutParams for the menu Fragment
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(width, ViewGroup.LayoutParams.MATCH_PARENT);

// We put a top margin on the menu Fragment container which is equal to the status bar height
params.setMargins(0, statusBarHeight, 0, 0);
menuContainer.setLayoutParams(fragmentParams);

Finally we can put all this together:
import android.graphics.Rect;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import at.test.app.R;
import at.test.app.helper.LayoutHelper;

public class ActivitySlider {

    private final FragmentActivity activity;
    private final View content;
    private final FrameLayout menuContainer;

    public ActivitySlider(FragmentActivity activity) {
        this.activity = activity;

        // We get the View of the Activity
        this.content = (View) activity.findViewById(android.R.id.content).getParent();

        // And its parent
        ViewGroup parent = (ViewGroup) this.content.getParent();

        // The container for the menu Fragment is added to the parent. We set an id so we can perform FragmentTransactions later on
        this.menuContainer = new FrameLayout(this.activity);
        this.menuContainer.setId(R.id.flMenuContainer);

        // We set visibility to GONE because the menu is initially hidden
        this.menuContainer.setVisibility(View.GONE);
        parent.addView(this.menuContainer);
    }

    public <T extends Fragment> void setMenuFragment(Class<T> cls) {
        Fragment fragment = Fragment.instantiate(this.activity, cls.getName());
        setMenuFragment(fragment);
    }

    public void setMenuFragment(Fragment fragment) {
        FragmentManager manager = this.activity.getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.flMenuContainer, fragment);
        transaction.commit();
    }

    public boolean isMenuVisible() {
        return this.menuContainer.getVisibility() == View.VISIBLE;
    }

    // We pass the width of the menu in dip to showMenu()
    public void showMenu(int dpWidth) {

        // We convert the width from dip into pixels
        final int menuWidth = LayoutHelper.dpToPixel(this.activity, dpWidth);

        // We move the Activity out of the way
        slideTo(menuWidth, 0);

        // We have to take the height of the status bar at the top into account!
        Rect rectangle = new Rect();
        Window window = this.activity.getWindow();
        window.getDecorView().getWindowVisibleDisplayFrame(rectangle);
        final int statusBarHeight = rectangle.top;

        // These are the LayoutParams for the menu Fragment
        FrameLayout.LayoutParams fragmentParams = new FrameLayout.LayoutParams(menuWidth, ViewGroup.LayoutParams.MATCH_PARENT);

        // We put a top margin on the menu Fragment container which is equal to the status bar height
        fragmentParams.setMargins(0, statusBarHeight, 0, 0);
        this.menuContainer.setLayoutParams(fragmentParams);

        // Perform the animation only if the menu is not visible
        if(!isMenuVisible()) {

            // Visibility of the menu container View is set to VISIBLE
            this.menuContainer.setVisibility(View.VISIBLE);

            // The menu slides in from the right
            TranslateAnimation animation = new TranslateAnimation(-menuWidth, 0, 0, 0);
            animation.setDuration(500);
            this.menuContainer.startAnimation(animation);
        }
    }

    public void hideMenu() {

        // We can only hide the menu if it is visible
        if(isMenuVisible()) {

            // We slide the Activity back to its original position
            slideTo(0, 0);

            // We need the width of the menu to properly animate it
            final int menuWidth = this.menuContainer.getWidth();

            // Now we need an extra animation for the menu fragment container
            TranslateAnimation menuAnimation = new TranslateAnimation(0, -menuWidth, 0, 0);
            menuAnimation.setDuration(500);
            menuAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    // As soon as the hide animation is finished we set the visibility of the fragment container back to GONE
                    menuContainer.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            this.menuContainer.startAnimation(menuAnimation);
        }
    }

    public void slideTo(int x, int y) {

        // We get the current position of the Activity
        final int currentX = getActivityPositionX();
        final int currentY = getActivityPositionY();

        // The new position is set
        setActivityPosition(x, y);

        // We animate the Activity to slide from its previous position to its new position
        TranslateAnimation animation = new TranslateAnimation(currentX - x, 0, currentY - y, 0);
        animation.setDuration(500);
        this.content.startAnimation(animation);
    }

    public void setActivityPosition(int x, int y) {
        // With this if statement we can check if the devices API level is above Honeycomb or below
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // On Honeycomb or above we set a margin
            FrameLayout.LayoutParams contentParams = (FrameLayout.LayoutParams) this.content.getLayoutParams();
            contentParams.setMargins(x, y, -x, -y);
            this.content.setLayoutParams(contentParams);
        } else {
            // And on devices below Honeycomb we set a padding
            this.content.setPadding(x, y, -x, -y);
        }
    }

    public int getActivityPositionX() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // On Honeycomb or above we return the left margin
            FrameLayout.LayoutParams contentParams = (FrameLayout.LayoutParams) this.content.getLayoutParams();
            return contentParams.leftMargin;
        } else {
            // On devices below Honeycomb we return the left padding
            return this.content.getPaddingLeft();
        }
    }

    public int getActivityPositionY() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // On Honeycomb or above we return the top margin
            FrameLayout.LayoutParams contentParams = (FrameLayout.LayoutParams) this.content.getLayoutParams();
            return contentParams.topMargin;
        } else {
            // On devices below Honeycomb we return the top padding
            return this.content.getPaddingTop();
        }
    }
}

I use a static helper method in showMenu() to convert dip to pixels. Here is the code of this method:
public static int dpToPixel(Context context, int dp) {
    float scale = getDisplayDensityFactor(context);
    return (int) (dp * scale + 0.5f);
}

private static float getDisplayDensityFactor(Context context) {
    if (context != null) {
        Resources res = context.getResources();
        if (res != null) {
            DisplayMetrics metrics = res.getDisplayMetrics();
            if(metrics != null) {
                return metrics.density;
            }
        }
    }
    return 1.0f;
}

You can use this new version of the ActivitySlider class like this:
ActivitySlider slider = new ActivitySlider(activity);
slider.setMenuFragment(MenuFragment.class);

// The menu is shown with a width of 200 dip
slider.showMenu(200);

...

// Hide the menu again
slider.hideMenu();

4) Conclusion & Testing
Doing something like this is surprisingly easy when you know that you can simply put a margin or a padding on the View of the Activity. But the difficulty is in making it work on a lot of different devices. Implementations can change a lot across multiple API Levels and that can have considerable influence on how this behaves. Having said that any code I posted here should work on most if not all devices above Eclair (Android 2.1 - API level 7) without any problems.
Of course the solution I posted here is not complete, it could use a little extra polishing and cleaning up, so feel free to improve the code to suit your needs!
I have tested everything on the following devices:

HTC

*

*One M8 (Android 4.4.2 - KitKat): Working

*Sensation (Android 4.0.3 - Ice Cream Sandwich): Working

*Desire (Android 2.3.3 - Gingerbread): Working

*One (Android 4.4.2 - KitKat): Working

  Samsung

*

*Galaxy S3 Mini (Android 4.1.2 - Jelly Bean): Working

*Galaxy S4 Mini (Android 4.2.2 - Jelly Bean): Working

*Galaxy S4 (Android 4.4.2 - KitKat): Working

*Galaxy S5 (Android 4.4.2 - KitKat): Working

*Galaxy S Plus (Android 2.3.3 - Gingerbread): Working

*Galaxy Ace (Android 2.3.6 - Gingerbread): Working

*Galaxy S2 (Android 4.1.2 - Jelly Bean): Working

*Galaxy S3 (Android 4.3 - Jelly Bean): Working

*Galaxy Note 2 (Android 4.3 - Jelly Bean): Working

*Galaxy Nexus (Android 4.2.1 - Jelly Bean): Working

  Motorola

*

*Moto G (Android 4.4.2 - KitKat): Working

  LG

*

*Nexus 5 (Android 4.4.2 - KitKat): Working

  ZTE

*

*Blade (Android 2.1 - Eclair): Working

I hope I could help you and if you have any further questions or anything else is unclear please feel free to ask!


text:
Q: Use wget to get a csv I am using Ubuntu and have a known URL which I need to download/save as a CSV. The URL is based on a parameter and changes often for a project, so I want to write a script which does the download, so that I don't have to manually save it every single time.
I was trying to use wget to get the file, but the website displays the contents as CSV, while the file itself is an HTML. How can I save the content of the page as a pure csv?
wget -O my.csv [url]

Can anyone help?

A: It seems the only HTML in the file is
 at the end of each line. To remove it, you can just
wget -O- "$URL" | sed 's#
$##' > my.csv


text:
Q: Where can I ask for algorithm recommendations? I recently asked this question on Stack Overflow, now moved to Software Recommendations.
Where can I ask about algorithm recommendations? Because there are two algorithms for what I'm trying to do, and both have a very high error rate, at least for my case. It seems that Stack Overflow is not the right place for algorithm recommendations.

A: Software Recommendations would be the best choice. Asking for an algorithm recommendation would be on-topic, as long as you do everything here when asking your question. There's an algorithms tag that would be perfect for your question.


text:
Q: Recovering data from NAS I have a Synology disk station, mounted with 2 disks (12TB each) running in mirror mode. I have also setup user directory for everyone in my family, meaning there are
I was told if in any event I need to expand my disk space, I can just buy a HD with bigger capacity, take out one of the mirrored HD, plug in the new HD and it will do mirror by itself. Then I just need to repeat this once more with another HD with larger capacity and it will be done.
I am just wondering will the file/directory ownership still presist after the HD switch?? I assume yes as long as I am using the same disk station.
But what if I need to swtich to another NAS, will those file ownership still presist? My disk station is getting old and I am doing some planning to swtich to better and faster NAS. I am also worring what if my NAS crashes one day and I am able to retrieve the files inside the HD if there is file ownership associated with the files.

A: A lot of NAS-es these days (like synology) are based on Linux. File and directory ownership are stored in the inodes of the filesystem as numbers.
So if you build a new NAS, just give your family members the same user-IDs on the new NAS as on the old one (assuming you can do that), and it should be fine.
If you cannot choose the user-id for you family members, log in on the NAS as root, and execute the command chown -R owner:group <dir> with the proper new user- and group IDs.
If you have root access to the NAS, you will be able to read all files, regardless of their permissions.


text:
Q: How to left/right-align custom UITableView cell I'm coding a "chatbot" app, and to hold the message bubbles I have a UITableView and a custom message-bubble shaped cell. Here's what it looks like so far:

All the cells will look the same, except I'd like every other cell to be, say, half the width of the table and alternating right/left aligned. How could I do this programmatically?

A: The better way - to create two classes InMessageCell, OutMessageCell, and add all properties (like aligning of all elements) hide inside of this cell. Both cell will have the same width, but all bubbles will be moved on one or other side. It may inheritance from the main class MessageCell, so all logic may stay in main class, but UI part - splitted up.

A: Two straightforward ways of achieving this by using custom table view cells:

*

*Have two different cell classes. They can share much of their implementation (e.g. by class heritage), but differ in their layout (one is left aligned, one right aligned). For each row in your table, decide which cell you need to use, and dequeue the appropriate one.

*Have one cell class whose layout can be toggled when it's being dequeued. (How exactly this toggle looks like depends of course on how you chose to layout your cell. It could e.g. be that you exchange the constant to an autolayout constraint you reference via @IBOutlet, the switching of a background image, or changing the alignment property of a stack view, among many others.)

Both ways depend on making a decision which cell flavor to use in your UITableViewDataSource's tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) function.
Here is a slightly abstract example using the first method. In your UITableViewDataSource:
enum ChatCellAlignment {
    case left
    case right
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cellAlignment: ChatCellAlignment = self.cellAlignmentForIndexPath(indexPath) // you need to implement something like this
        var identifier = "Default"

        switch cellAlignment {
            case .left:
                identifier = "LeftAlignedBubbleCell"
            case .right:
                identifier = "RightAlignedBubbleCell"
        }

        let cell = self.tableView.dequeueReusableCell(withIdentifier: identifier)

        if let cell = cell as? ChatBubbleCell { // assuming your custom cell classes all inherit from a "ChatBubbleCell"
            cell.set(text: self.textForIndexPath(indexPath))
            ... // whatever setup you need to do on your custom cell
        }

        return cell
    }

A: You can give the table view cell a value to know it. Then you can use autolayout (SnapKit) to make it align left or right


text:
Q: Filter users using position in react native I have an app in react-native where I have a list of users and I want to filter them, when I click on a button in the header, using their actual position. How can I do it ?
Thanks in advance!
Edit:
export default data = [
   {
      id:1,
      name:"Anastasia",
      photo_path: "https://www.one-voyance.fr/media/cache/slider/images/voyants/anastasia/anastasia.jpg",
      age: "23",
      pratique: "Trans.",
      distance: "200m",
      connected: 1,
      description:"Anastasia, medium pure sans support.Mon don héréditaire me vient de mes grands parents. Prête à vous servir, je m'appuie de mes guides pour vous guider dans votre chemin de vie.Je suis compétente dans tous les domaines. La vie est faite de détours, en connaitre les recoins permet d'avancer sereinement sans se poser de questions. Je vous attends pour une voyance claire et de qualité.",
      //numero:"06 01 02 03 04"
   }

A: You can use the filter method provided by an Array to filter the data. A solution would be something like this:
let tempResults = data.filter(element => element.position === 'Some position')
For the Button, you'll have to add an onPress event handler, something like below:
<Button onPress={this.handleButtonPress} />
And define the handler function as something like:
handleButtonPress = () => {
 let tempResults = this.state.data.filter(element => element.position === 'Some position')
 this.setState({dataToBeRendered: tempResults})
}

Hope this will give you an idea.

A: Check out the docs for getting the Geolocation with React Native. Then you can do whatever you want from your data based on the user's geolocation.

A: You should setParams and pass the function and filter value to the header and perform the operation with function received in params as shown below
this.state = {
 position: "",
 result: []
}

static navigationOptions = ({ navigation }) => {
    const params = navigation.state.params || {};
return {
headerTitle: {params.position}
headerLeft: <View/>
headerRight: <View><Button onPress={params.handleFilter("200")}>Filter</Button> </View>
}}

componentWillMount() {
    this.props.navigation.setParams(
      Object.assign({}, this.props.navigation.state.params, {
        handleFilter: this.handleFilter,
        position: this.state.position
      })
    );
  }

handleFilter = position => {
  this.setState({ position: position })
  result.filter(data => Number(data.position) < Number(position))

}


text:
Q: Running Go Program which uses OpenVINO & OpenCV - /usr/bin/ld: cannot find -lXXX I am trying to write a program in Go Programming Language that is using OpenVINO DNN models in order to perform inference. In order to do that I've followed instructions from this GITHUB link: https://github.com/hybridgroup/gocv/tree/master/openvino
I have installed OpenVINO and 3rd party libraries that go with it, this includes OpenCV which is located in ~/intel/openvino_{version}/opencv directory.
Thing is whenever I try to execute following command:
go run -tags openvino ./cmd/version/main.go

I get this output:
 runtime/cgo
/usr/bin/ld: cannot find -lHeteroPlugin
/usr/bin/ld: cannot find -lMKLDNNPlugin
/usr/bin/ld: cannot find -lmyriadPlugin
/usr/bin/ld: cannot find -linference_engine
/usr/bin/ld: cannot find -lclDNNPlugin
/usr/bin/ld: cannot find -lopencv_pvl
collect2: error: ld returned 1 exit status

So I tried to set my CGO_LDFLAGS like this:
CGO_LDFLAGS=-L/opencv/lib -L/deployment_tools/inference_engine/lib/intel64 -lpthread -ldl -ldliaPlugin -lHeteroPlugin -lMKLDNNPlugin -lmyriadPlugin -linference_engine -lclDNNPlugin -lopencv_core -lopencv_pvl -lopencv_videoio -lopencv_imgproc -lopencv_highgui -lopencv_imgcodecs -lopencv_objdetect -lopencv_features2d -lopencv_video -lopencv_dnn -lopencv_calib3d

But when I do that I am getting:
bash: -L/deployment_tools/inference_engine/lib/intel64: No such file or directory

Even though ~/intel/openvino/deployment_tools/inference_engine/lib/intel64 does exitst on my system.

A: Updated (Feb/25/2020)
As of 2019 R3.334, OpenVINO SDK started supporting GoCV again.

Old message
Check this out:
https://github.com/hybridgroup/gocv/issues/491
The recent version of openvino dropped the support of pvl so that there is no libpvl or something like that.
You can try one older version of it but there is no future.


text:
Q: Why are so many Star Wars species so similar in external anatomy? There are so many different species in the Star Wars universe yet many of the sentient ones have the same general humanoid appearance: Two arms, two legs on a torso with a head on top. I'm not saying there aren't intelligent species that vary from this, I'm just wondering why there aren't more?
I thought it might be the most "naturally selected" evolutionary development, but that seems unlikely since planets can be so vastly different. There are some that are almost completely water, others that don't have oxygen and still others that all forests. Why would they all develop the same shape of intelligent life? For example Manaan (Legends Canon) is all one big sea with the exception of a few space ports for foreigners, yet the Selkath are bipedal and not entirely fish like.

A: Canon:
I couldn't find any in-universe reference. Convergent evolution is a convinient hypothesis, but has no canon evidence.
EU/Legends:
Many, though not all, of those "near-human" species seems to be genetically descended from humans, according to what pretty much passes for an expert (Caminoans):

"Above all else, humans are adaptable — adaptable in terms of physiology, mentality and society. Their genome is remarkably elastic: Selection pressures need a few millennia at most to engage new genes and reshape their bodies in response to environmental changes, as the galaxy's countless near-human populations attest."
("Star Wars: The Essential Guide to Warfare Author's Cut" - published on starwars.com; so there's a chance it may be Disney canon)


text:
Q: Prove or Disprove: Subspaces, and Bases Prove or disprove:
If U is a subspace of a finite dimensional vector space V and B = {v1, . . . ,vn} is a basis
for V, then some subset of B is a basis for U.
So far, I don't know where to start. I could assume that since B is a basis, it is linearly independent, and thus, some subset of B, containing less vectors than B, could potentially be a basis for U, since U is a subspace of V, but I don't know how to go about proving this.
Thanks

A: It's not true.  Suppose $V=\mathbb R^2$  Let the basis be $(0,1),(1,0)$ and the subspace be generated by $(1,1)$

A: Hint: if this statement is generally true, then it is true in the case $U$ is a one-dimensional subspace, i.e. it is just the span of a single vector.
If a subset of $B$ is then a basis for $U$, what does this tell you about the vectors in $B$?


text:
Q: Angular 1.5, response status on error is always -1 I'm facing an issue when calling API, let me explain architecture first.
Whole font-end application os AngularJS 1.5 based, hosted on domains like below:
app1.mydomain.com, app2.mydomain.com, appN.mydomain.com
I have an API (Symfony2 based - FOS Rest) which is on:
api.mydomain.com
Server is Nginx, php5 (fpm), CORS open.
Now, lets describe problem:
Im calling an API endpoint for some data:
    var data = {someProperty: someValue};
    var $p = $resource($rootScope.apiDomain + '/some/endpoint', {}, {
        get: {
            method: 'GET'
        }
    }).get(data).$promise;
    var request = $q.all({request: $p});

    return request
        .then(function (response) {
            // code on success
        }, function (error) {
            // code on error
        });

Now let's say that server's response is ANY of 400's or 500's, then in ResponseError (interceptor) i've should get this code as an 'status' value
responseError: function (response) {
    if (403 === response.status) {
        // something on 403
    }
    // do something on other codes
    return $q.reject(response);
}

No matter which response code is sent back from backend server, the response object contains following:
Object {data: null, status: -1, config: Object, statusText: ""}

However... i've seen THIS ANSER and this is basically what i do have now...
So:

*

*Is there any way to solve such issue (i have, let's say full possibility in configuration of both back&front in any way)

*If it's not "solvable" easily, then how to?

A: Well...
I've finally managed to make this working - nginx.opencors config
Solution:
(before)
add_header 'Access-Control-Allow-Origin' "*";
ResponseObject: {data: Object, status: -1, config: Object, statusText: ""}
(after)
add_header 'Access-Control-Allow-Origin' "*" always;
ResponseObject: {data: Object, status: 403, config: Object, statusText: "Forbidden"}


text:
Q: Formatting all date properties in C# object list I'm having huge issues with formatting the DateTime of each date property within a list of objects. Here's a few examples of what I've tried so far:
var data = vulnerabilityList.Skip(skip).Take(pageSize).ToList()
    .Select(v => { v.PublishedDate =
    v.PublishedDate.ToString("dd/MM/yyyy"); return v; });

and
var data = vulnerabilityList.Skip(skip).Take(pageSize).ToList()
    .Select(v => { v.PublishedDate =
        DateTime.ParseExact(v.PublishedDate.ToString(), "dd/MM/yyyy",
            CultureInfo.CurrentCulture); return v; });

Ultimately I want the format as 31/12/2017 and it'll be returned as JSON so it seems the data annotations on the vulnerability class are ignored. The first example doesn't compile as obviously it's trying to set a DateTime as a string, but I included it as an example of what I'm looking to do.
Thanks

A: A datetime is a representation of a date and time using a number, and it doesn't have an inherent format. It's intended for you to format it how you want it when you read it or display it to users. So doing something like this:
v.PublishedDate = (DateTime)v.PublishedDate.ToString("dd/MM/yyyy")

Is only going to set the publish date to dd/MM/yy 00:00:00 (if it did work).
I believe what you'll need to do is either change how you're parsing your JSON in the end, or store the DateTime as a string in a new property for reading.


text:
Q: Need to push javascript objects ( not from collections ) asynchronously for a specific user from server to client on meteor Any user (client) making a research on my meteor app would call a meteor method that will send asynchronously results to this client when it founds something ( could be by searching many different external apis for exemple ) and possibly would inject it in a client-side only (none persistent) collection. how ?

A: From the server methods, you can pass error or results and they don't have to be from a collection.
Inside methods:
methodName: function (arg1, arg2){
    if(arg1 !== 'something'){
        throw new Meteor.Error(400, 'Error text.')
    }

    //do something if there is no error here. You don't have to check if there are no errors here as Meteor doesn't jump to DB actions/return a result if there is an error.
    return 'result you want to show. Could be an object, string, a document from the DB etc.'
}

Your call on the client side
Meteor.call('methodName', arg1, arg2, function (err, res){
    if(err){
        //do something with the err
    } else {
        //do something with the result
    }
});

Next time, please check the documentation before asking something. Cheers.


text:
Q: What is the difference between "although that is" and "although it is"? Currently I'm writing a thesis. I came over the although sentence several times. After reading through time after time my head started to hurt :P I tried to google it but didn't find any help.
So the sentence goes like this:

Although that/it is true, it is not insensible since one rule alone cannot classify the entire data.

What comes before Although is a sentence trying to explain the bad results from a program shown in a table.
What is the difference? Is it possible to use both? If so, why?
Also the part with "it is not insensible since" sounds fishy to me. Is this one correct?

A: It is impossible to be sure without more context, but either that or it is likely to be acceptable: both are syntactically pronouns here and refer to a previously stated proposition.
Insensible is almost certainly wrong. The word may mean

*

*"incapable of sensory perception, unconscious" or

*"incapable of being sensed or perceived by the senses"
and it is difficult to conceive an entity which might be described as both true/false and sensible/insensible. Your author may mean something like detectable or discernible.
Alternatively: Since sensible has as one of its meanings "characterized by good sense, reasonable", it is also possible that your author, working from a bilingual dictionary, may have employed insensible as the equivalent of a word in their own language with a range of meanings including both "unreasonable" and "irrelevant" or "inconclusive"—either of those words would fit the context.

A: I'm inclined to suggest that either is acceptable and it's a matter of personal style. Clearly either that or it is referring to what has just been said/written previously.
Personally, I think that that is more grammatically correct in referring to what has just been said, but I think it is probably more common these days.
I can't really explain why - it's just a 'gut feeling'.
(This is from a British perspective.)


text:
Q: Problems with including QWebView in QT application I am using qt creator. I wanted to show a webpage inside QWebView, but my projet doesn't compile. When i want to include QWebView, editor says "no such file or directory".
My code:
#include <QApplication>
#include <QUrl>
#include <QWebView>

int main(int argc, char *argv[])
 {
QApplication a(argc, argv);

QWebView view;
view.showMaximized();

return a.exec();

}

A: Did you add in your Project_name.pro file in Qt Creator line like this: QT += core gui webkit ?