text:
Q: Save file to specific folder with curl command In a shell script, I want to download a file from some URL and save it to a specific folder. What is the specific CLI flag I should use to download files to a specific folder with the curl command, or how else do I get that result?

A: it works for me:
curl http://centos.mirror.constant.com/8-stream/isos/aarch64/CentOS-Stream-8-aarch64-20210916-boot.iso --output ~/Downloads/centos.iso

where:
--output allows me to set up the path and the naming of the file and extension file that I want to place.

A: Use redirection:
This works to drop a curl downloaded file into a specified path:
curl https://download.test.com/test.zip > /tmp/test.zip

Obviously "test.zip" is whatever arbitrary name you want to label the redirected file- could be the same name or a different name.
I actually prefer @oderibas solution, but this will get you around the issue until your distro supports curl version 7.73.0 or later-

A: The --output-dir option is available since curl 7.73.0:
curl --create-dirs -O --output-dir /tmp/receipes https://example.com/pancakes.jpg

A: For powershell in Windows, you can add relative path + filename to --output flag:
curl -L  http://github.com/GorvGoyl/Notion-Boost-browser-extension/archive/master.zip --output build_firefox/master-repo.zip

here build_firefox is relative folder.

A: I don't think you can give a path to curl, but you can CD to the location, download and CD back.
cd target/path && { curl -O URL ; cd -; }

Or using subshell.
(cd target/path && curl -O URL)

Both ways will only download if path exists. -O keeps remote file name. After download it will return to original location.
If you need to set filename explicitly, you can use small -o option:
curl -o target/path/filename URL

A: curl doesn't have an option to that (without also specifying the filename), but wget does. The directory can be relative or absolute. Also, the directory will automatically be created if it doesn't exist.
wget -P relative/dir "$url"

wget -P /absolute/dir "$url"

A: Use wget
wget -P /your/absolut/path "https://jdbc.postgresql.org/download/postgresql-42.3.3.jar"

A: Here is an example using Batch to create a safe filename from a URL and save it to a folder named tmp/. I do think it's strange that this isn't an option on the Windows or Linux Curl versions.
@echo off
set url=%1%

for /r %%f in (%url%) do (
    set url=%%~nxf.txt
    curl --create-dirs -L -v -o tmp/%%~nxf.txt %url%
)

The above Batch file will take a single input, a URL, and create a filename from the url. If no filename is specified it will be saved as tmp/.txt. So it's not all done for you but it gets the job done in Windows.

A: For Windows, in PowerShell, curl is an alias of the cmdlet Invoke-WebRequest and this syntax works:
curl "url" -OutFile file_name.ext

For instance:
curl "https://airflow.apache.org/docs/apache-airflow/2.2.5/docker-compose.yaml" -OutFile docker-compose.yaml

Source: https://krypted.com/windows-server/its-not-wget-or-curl-its-iwr-in-windows/


text:
Q: Visual Studio 2008 Create Custom templates for Graph Theme and Fonts Our company is requiring specific custom colors for report manager reports including, text boxes and all charts / graphs.  Can we create a custom graph template so each time we create a new graph, we use the template with our custom fonts as our base to start from?

A: Hmmm, hard to do without having a default graph on every new report, that's customised in the item template.
The templates for new reports are stored ZIP files in the "Program Files" directory, under Microsoft Visual Studio XX -> Common*XX* -> IDE -> ItemTemplates -> Visual Basic/CSharp -> Reporting ->  e.g. 1033. A good start might be this article on MSDN: http://msdn.microsoft.com/en-us/library/6db0hwky%28v=VS.90%29.aspx
Alternatively you could provide a template to your developers that they would cut-and-paste from when developing new reports.
I think you'll still need to create a "style guide" as I don't believe there's a way to customise the toolbox when developers add a new textbox or graph.

redpajama_set_name: RedPajamaStackExchange


text:
Q: why tests fails when testing python-glanceclients? i am using python 2.6.6, why run_tests tried to find python 2.7?
(os)mirror0@lab:~/tmp/python-glanceclient$ ./run_tests.sh
GLOB sdist-make: /home/mirror0/tmp/python-glanceclient/setup.py
py27 create: /home/mirror0/tmp/python-glanceclient/.tox/py27
ERROR: InterpreterNotFound: python2.7
___________________________________ summary ____________________________________
ERROR:   py27: InterpreterNotFound: python2.7
(os)mirror0@lab:~/tmp/python-glanceclient$ python -V
Python 2.6.6

A: You need to install python 2.7 for these tests to pass.


text:
Q: Identify Checked checkboxes in jquery I create Multiple checkBox under the one div with data-role="controlgroup" Now i want to check that after click on specific button which check boxes are checked using JQuery so what is the best way for do it

A: Try something like this...
if ($("div[data-role='controlgroup'] input[type='checkbox']").first().prop("checked")) {
    // ...
}

That's a pretty hefty selector, and it'll only fetch the first <input type="checkbox" /> that's inside a <div data-role="controlgroup">. You should tweak it to make it more specific to your project.
In short, jQuery's .prop() method with "checked" as the argument will return a Boolean true or false depending on whether a checkbox is checked.

A: use :checked
$("div[data-role='controlgroup'] :checkbox :checked")// by this you get all checked checkbox

A: try like this.
$("div[data-role='controlgroup'] input:checkbox :checked")

A: Using this you can get all of your checked ckeckboxes
code from here
var selected = new Array();
$('#checkboxes input:checked').each(function() {
    selected.push($(this).attr('name'));
});


text:
Q: bash 4.2 / 4.3: Different behavior in C-style loop bash 4.2 show the assumed correct behavior in a C-style for loop:
me@server:/some/dir# TIMES=30; for (( n=0; n<$(shuf -i ${TIMES}-$(expr ${TIMES} + 20) -n 1); n++ )); do echo $n; done
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
me@server:/some/dir# bash --version
GNU bash, Version 4.2.25(1)-release (x86_64-pc-linux-gnu)
(...)
me@server:/some/dir#

The same under bash 4.3 throws an error:
me@server:/some/dir# TIMES=30; for (( n=0; n<$(shuf -i ${TIMES}-$(expr ${TIMES} + 20) -n 1); n++ )); do echo $n; done
-bash: syntax error near unexpected token `newline'
me@server:/some/dir# bash --version
GNU bash, Version 4.3.30(1)-release (x86_64-pc-linux-gnu)
(...)

Yet the part to find a random number between ${TIMES} and ${TIMES}+20 works:
me@server:/some/dir# shuf -i 20-50 -n 1
26
me@server:/some/dir#

So does inserting the numeral directly instead of $()-subshell'ing it:
me@server:/some/dir# TIMES=30; for (( n=0; n<26; n++ )); do echo $n; done
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
me@server:/some/dir#

What's going on here? Any ideas why the subshell is not executed correctly under bash 4.3?

A: If you replace $(expr with $((, it starts to work:
TIMES=30
for (( n=0; n < $(shuf -i $TIMES-$((TIMES + 20)) -n 1); n++ )) ; do
    echo $n
done


text:
Q: Does list.index() implement caching In Python, does the list.index() method implement caching?
In other words, If I do
myList = [3,5,4,7]
print myList.index(5)
print myList.index(5)

Does the second invocation of the method have to iterate over the array, or is the method smart enough to know that it already has an answer for the input: 5?
obviously, any time the array is modified the cache would be invalidated and would thus have to be cleared

A: You can find out by doing a simple profiling.
import cProfile,random
def scrambled(orig): # scramble list
    dest = orig[:]
    random.shuffle(dest)
    return dest

myList = scrambled(range(0,10000000))

cProfile.run('print myList.index(1)') #3 func, same amount of time
cProfile.run('print myList.index(1)') #3 func, same amount of time

thus no.


text:
Q: Nginx with Node.js as backend server always returns status code 200 instead of 404 I am using Nginx as a reverse proxy, with a Node.js Express server as the backend.
When trying to load a custom-made 404 page on Express, Nginx always returns a 200 status code, even though Express correctly sends back to Nginx a 404 status code.
What is the problem with the configuration?
I'm also using EJS as the template engine, however, I don't think it contributes to the problem. I am using PM2 as the process manager to run the server. I have tested without using Nginx as a reverse proxy, and everything in Express seems to work fine, i.e. Express correctly returns a 404 status code.
Here's my Express code:
const path = require('path')

const express = require('express')

const app = express()

const port = process.argv[2] || 3000

// Define paths for Express config
const publicDirPath = path.join(__dirname, '../public')
const viewsPath = path.join(__dirname, '../templates/views')

// Set EJS engine and views location
app.set('view engine', 'ejs')
app.set('views', viewsPath)

// Set static files location
app.use(express.static(publicDirPath))

app.get('/testing404', (req, res) => {
    res.status(404).render('404', {
        title: '404 error',
        content: 'This is a 404 error page.'
    })
})

app.listen(port, () => {
    console.log('Server started at port ' + port + '!')
})

Here's my relevant Nginx configuration:
upstream nthreads {
    ip_hash;
    server localhost:3000;
}

server {

        root /var/www/[XXXXX]/html;
        index index.html index.htm index.nginx-debian.html;

        server_name [XXXXX] www.[XXXXX];

        location / {
                proxy_pass http://nthreads;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
        }

}

As explained, I expected a 404 status code to be returned from Nginx through the Node.js Express backend server, but I'm getting a 200 status code instead, what's the problem then?

A: Nginx is correctly returning 200 because you asked for a document that exists. You would only get a 404 if you requested a document that does not exist. Try doing that instead. (And whether such a document exists on some other server is completely irrelevant.)
when you're pulling your 404 page at it's genuine place, it will return a 200, because you've requested a page that does exist.
for Ngnix server you can Configure NGINX to point to that page for genuine 404 errors. Once that's done, when you want to redirect your app in places just redirect them to a bogus page

A: Turns out everything was working correctly. I have forgotten to reload the server process, and it was running an old code without the 404 status code. Nginx does indeed correctly forward the 404 status code returned by the backend Node.js Express server.


text:
Q: Android application data implementation / passing data between activities I have looked, but can't find a question here or anywhere that is quite the same as mine. I'm also new to android development, so I'm trying to find out the best way to solve this programming problem.
I will give an example of what I am trying to do.
I define a container object that contains some sort of data structure (say an arrayList) of objects of a different class. The main activity displays a listView of all the objects in the arrayList. When the user picks an item from the list, I need to open a new activity that displays the fields for that object, which the user can edit. The user changes the fields, presses save, and is redirected to the first activity.
In order for this to work, I would need to pass the second activity the object. I understand that I can use Serializable or Parcelable to pass the object, but I need to be able to edit the object and send it back. My C++ brain says to just use pass-by-reference, but my understanding is that that is not available in Java.
I took a look here: http://developer.android.com/guide/faq/framework.html#3 , but I don't think any of the solutions offered here solve my problem.
I am sorry I am new to Android and Java; most of my experience is in C++. Am I just thinking about the problem wrong?
Thanks for taking the time to read!

A: You intuition is right. The correct way to do what you are describing is (1) implement the Parcelable interface in the objects that you want to pass between activities; (2) pass the clicked on object via an Intent to the next Activity or Fragment; (3) reload/refresh the list.
First step is implementing Parcelable. The android docs are pretty straight forward and if you look around there are a lot of examples on how to get this done.
You will most likely be displaying your ArrayList of objects in a ListView. You can do this as a standalone view, by adding a ListView to the layout of an Activity or by using a ListFragment which extends Fragment. In both cases there are methods that can tell you which item in the list is clicked. For the ListView you can implement an onItemClick listener which will give you the position in your list that was clicked on. In the ListFragment there is an onListItemClicked method that will do roughly the same thing. You should check out the documentation for these classes.
Once you know the position that is clicked on you can get the object that was click and pass it via Intent to the next Activity (or send it via an argument in a Bundle if you are starting a new fragment).
Intent intent = new Intent(context, ActivityYouWantToStart.class);
intent.putExtra("KEY", object);
startActivity(intent)

This will send the object to the next activity (ActivityYouWantToStart). To retrieve it, you can implement the following in your Activity's onCreate method
Bundle stuffYouSent = getIntent().getExtras();
if(stuffYouSent != null){
     Object o = stuffYouSent.getParcelable("KEY");
     //do something
}

Naturally you can change the class from object to whatever you sent just cast your result accordingly.
To get the object back to the original activity you essentially repeat this process in reverse. Make your edits and when you're done pass by intent back. When the object is received you can re-add it to the list or reload the entire list depending on how the list view was implemented.
Edit - startActivityForResult
Instead of simply starting the next activity you can use startActivityForResult when you know you will be returning back to the first activity. You can see one example here but in your context:
Intent intent = new Intent(context, ActivityYouWantToStart.class);
intent.putExtra("KEY", object);
startActivityForResult(intent, REQUEST_CODE);

Here you are still passing the object to the next activity but specifying a "REQUEST_CODE" that indicates the action to perform when the intent is received. When the intent starts the second activity you handle the intent as you normally would. When you're finished you pass the data back to the first activity as follows
Intent returnIntent = new Intent();
returnIntent.putExtra("result", result);
setResult(RESULT_OK, returnIntent);
finish();

Here the RESULT_OK indicates that the action is completed. This time, instead of starting the activity like you did before, a special method will be called:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    //do something
}

Be sure to override this method in your first activity and handle the result. It will return the the extra to your first activity where you can then update the list. The result code and request code can be used to switch functions if multiple activities are returning data.


text:
Q: How to increase numbers of cpu cores and their usage in python I've written a python script with heavy computational costs. After running the code in a remote linux server(via putty), it takes one week to get finished.
Our remote server has 32 cpu cores and 64 GB of Ram memory. I need to run my script in a shorter time by using more numbers of cpu cores but I don't know exactly how to increase using more numbers of cpu cores for my script.
I would like to know if there is any python code to add at the first or end part of my python script for adding numbers of cpu cores, memory usage and etc to be able to run the script in a shorter time. I also need to return to the default state after getting my script result.
Is there any way to achieve this in Python?

A: You can take a look on multiprocessing lib (https://docs.python.org/2/library/multiprocessing.html) but you will have to manage data to share between processes.
You can also take a look on threading lib (https://docs.python.org/2/library/threading.html) which may be efficient if you have lot of I/O.
Finally you use asyncio lib (python 3.4+ https://docs.python.org/3/library/asyncio.html) which is, in my opninion, more complicated to implement but give you more ability to manage explicitly the behavior of your code.
Edit: This is a large question, you may find lot of documentation on this issue. It really depends on what your code really do, you should better give a snippet of your code.

A: Rewrite your script to do things in parallel. Since threads don't use more than one CPU in CPython, you should use https://docs.python.org/2/library/multiprocessing.html.
See also: Does python support multiprocessor/multicore programming?


text:
Q: unexpected EOF while looking for matching `"' while trying to print a quoted line in Shell bash I want to print the following line but I need this line:
export PATH=/local/Miniconda3/bin:$PATH >> ~/.bashrc; /local/Miniconda3/bin/python3 scripts/DNAscan.py ${var}

to be quoted. I used \" in order to achieve that but I'm getting this error:
unexpected EOF while looking for matching `"'

This is the command:
"${comand} bash -c  \"export PATH=/local/Miniconda3/bin:$PATH >> ~/.bashrc; /local/Miniconda3/bin/python3 scripts/DNAscan.py ${var}\""

A: I'm not sure what is going wrong with your command but would like to note that the variables 'comand' and 'var' are both being resolved, if this was not your intention consider using single quotes ' ' or escaping the '$' signs in your string with backslashes '\'.


text:
Q: My Wifi wont work on my Debian laptop Some Questions from someone new to Debian:

*

*I have tried to install some wifi detecting programs,but i don't think the driver is installed... How do i find and install the driver?

*I have tried to follow the instructions on Debian's website but
could not find the answer there, it was too confusing for me.

*I'm also looking for help in installing the packages...

As requested, here are my network drivers...
sudo lspci | grep controller
01:00.0 Ethernet controller: Qualcomm Atheros AR8162 Fast Ethernet (rev 10)

02:00.0 Network controller: Realtek Semiconductor Co., Ltd. RTL8188EE Wireless Network Adapter (rev 01)

When i do iwconfig I get the output
lo        no wireless extensions.

eth0      no wireless extensions.

Update
I have followed all the things eyoung100 has told me to do in his answer. He has some of the research in there as well. I still do not have the WIFI working yet.

A: *

*Install the pciutils package.  Use the command lspci. Post the output of lspci in your question using the Edit Link, and I'll help you install the driver after we know what it is.

*Read this Beginner's Guide to Debian

*Read the Official Debian Manual on Aptitude, the Debian Package Manager.  You might want to do this one first, even though you asked it last.

Although this answer is quite direct, here is the best piece of advice I can give you.  Now that you've switched to Linux, you'll find varying degrees of expertise, but people in all those levels will expect you to do something that is unheard of in the Windows World.  All installed Linux Commands come with a man page.  To use it, type man and the command you'd like to learn about.  Some great examples include:

*

*man ls

*man apt

*man man
Update
According to lspci, this is your Wireless Card:

02:00.0 Network controller: Realtek Semiconductor Co., Ltd. RTL8188EE
  Wireless Network Adapter (rev 01)

and now that you've read the Official Debian Manual on Aptitude, you should be able to follow this post also on U&L.  Skip over adding the testing branch while reading the post from user30349.


text:
Q: Hadoop handling compression transparently, but not splitting LZO it looks as if Hadoop handles compression transparently (when was this introduced, I don't remember it on 0.20.203) when using TextInputFormat.  Unfortunately, when using LZO compression, Hadoop doesn't use the LZO index file to make the file splittable.  However, if I set the input format to com.hadoop.mapreduce.LzoTextInputFormat, the file is split.
Is it possible to configure Hadoop to decompress LZO files and split them when using TextInputFormat?

A: I'm just running into a similar issue, and here's my understanding:
You want to use LzoTextInputFormat in your code. If you want to process a mix of lzo and non-lzo files, you should set lzo.text.input.format.ignore.nonlzo to false. In this case, LzoTextInputFormat will be used for all lzo files, but it will default to TextInputFormat for other files (It's smart enough to ignore the index files).
This feature may not have been around when this question was first asked, so you might already be aware of this solution.
Please see (there's a comment about ignore.nonlzo):
https://github.com/twitter/hadoop-lzo/blob/master/src/main/java/com/hadoop/mapreduce/LzoTextInputFormat.java


text:
Q: Library header not found if CONFIGURATION_BUILD_DIR is set with xcodebuild My iOS project uses RestKit as a static library (in a GIT submodule).
When I do:
xcodebuild -project myproject.xcodeproj -configuration Debug

Everything goes well. However, when I change the output directory with:
xcodebuild -project myproject.xcodeproj -configuration Debug CONFIGURATION_BUILD_DIR=build

xcodebuild can't find my library header file:
/path/to/my/project/file.m:9:9: fatal error: 'RestKit/RestKit.h' file not found
#import <RestKit/RestKit.h>
        ^
1 error generated.

What happens here ?

Edit
After some investigations, I found out that when adding CONFIGURATION_BUILD_DIR=build, xcodebuild doesn't copy headers from RestKit at all.
Without using CONFIGURATION_BUILD_DIR:
CpHeader Code/RestKit.h ...

Using CONFIGURATION_BUILD_DIR: nothing.


text:
Q: Coding lines appear after each closed div. (only in DOM inspector) I had some very strange annoying results while working on my 'project'.
To loop through MySQL results I used a while loop.
One of the lines echo'ed in the while loop now keeps appearing after every closed div.
This is only visible in firebug or another DOM inspector and not in the source code.
I have no idea what is causing it, so any help is appreciated.
Underneath I included all the code involved.
Thanks,
Sam
Btw. This is still in early development so please take that into consideration.
Code:
Firebug:

This page was loaded succesfully :D

Php File:
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="author" content="Sam Kool">
<title>Admin panel</title>
<link rel="stylesheet" href="../css/bootstrap.css"/>
<link rel="stylesheet" href="../css/bootstrap-responsive.css"/>
<link rel="stylesheet" href="../css/style.css"/>

<?php
session_start();
if(!isset($_SESSION['name'])){
    header('Location: http://localhost/CMS/Admin/');
}
include ('../config.php');

?>

            <?php
            $conn = mysql_connect($config['db_host'], $config['db_user'], $config['db_pass']);
            $conn = mysql_select_db($config['db_db']);
            $mysql['sql'] = " SELECT *
                        FROM admin_layout
                        WHERE enabled = '1' and type = 'quickstats'
                        ";
            $mysql['query'] = mysql_query($mysql['sql']);
            while($row = mysql_fetch_array($mysql['query'])){
                echo '
   '.$row["title"].'
';
            }
            mysql_close();
            ?>

              <?php
              $i = 1;
              $conn = mysql_connect($config['db_host'], $config['db_user'], $config['db_pass']);
              $conn = mysql_select_db($config['db_db']);
              $mysql['sql'] = " SELECT *
                          FROM admin_components
                          WHERE enabled = '1'
                          ";
              $mysql['query'] = mysql_query($mysql['sql']);
              while($row = mysql_fetch_assoc($mysql['query'])){
                  echo '
';
                  echo '';
                  echo ''.$row["title"].'';
                  echo ''.$row["description"].'
';
                  $i ++;

              }
              mysql_close();
              ?>

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Loading....

A: The DOM inspector is almost always correct, your HTML source is wrong. When things like this happen, it usually indicates you forgot to close a tag, or that you closed them in the wrong order.
This is an extremely easy mistake to make when echoing out html, because you dont usually have indentation or IDE color coding to help you out.
In your second while loop, it appears you opened an a tag and didnt echo out the closing tag.
echo '
';
//OPENED AN A TAG HERE
echo '';
echo ''.$row["title"].'';
echo ''.$row["description"].'
';
//OOPS, ENDED LI WITHOUT ENDING A


text:
Q: Flutter: Using image instead of icon I have a sample code for a radiostream player.
The code provides for an icon to represent its state (paused or playing).
I would like to show an image instead of the icon.
Being a newby/noob with flutter im stuck.
Can sonebody push me in the right direction?
Here is the current code:
...........
default:
                        return Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              IconButton(
                                  onPressed: () async {
                                    print("button press data: " +
                                        snapshot.data.toString());
                                    await _flutterRadioPlayer.playOrPause();
                                  },
                                  icon: snapshot.data ==
                                          FlutterRadioPlayer
                                              .flutter_radio_playing
                                      ? Icon(Icons.pause)
                                      : Icon(Icons.play_arrow))
                            ]);
                        break;
                    }
...............

So in short, i want to use an image, "pause.png" for Icons.pause and "play.png" for Icons.play_arrow.

A: the icon is of type Widget so you can pass for example Image.asset([path to asset]) instead Icon()

A: Remove that IconButton thing and use this as a child of Future Builder
and the future builder will return this
Image.asset('pause.png'):Image.asset('play.png')

A: here is the example
return Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.center,

                            // replace Icon button to this custom button and wrap with Inkwell
                            children: <Widget>[
                              InkWell(
                                  onTap: () async {
                                    print("button press data: " +
                                        snapshot.data.toString());
                                    await _flutterRadioPlayer.playOrPause();
                                  },
                                  child : snapshot.data ==
                                          FlutterRadioPlayer
                                              .flutter_radio_playing
                                      ? Image.asset("image path")
                                      : Image.asset("image path "))
                            ]);
                        break;
                    }


text:
Q: CentOS httpd running as both root and apache user I have an Apache httpd server running on my CentOS server, but apparently it both runs a httpd-process as root and one as the apache user.
See this screenshot of top:

User and group are set to apache in the configuration file, so I'm kind of lost here.
Do any of you know what starts the "root" process, and why it's running?

A: The one running as "apache" is the worker process.  The one running as "root" is the master process.  This is completely normal.
The master process will spawn workers as necessary (with whatever constraints are specified in the configuration file) to handle incoming traffic.  It typically will need to be root in order to bind to low ports 80 and 443.  After it binds, it will drop privileges to the apache user.
Workers will be reaped from time to time.  The long-running process is the one running as root.  If you look at httpd.conf, you'll see a block that looks something like:
StartServers       1
MinSpareServers    1
MaxSpareServers    5
ServerLimit      256
MaxClients       256
MaxRequestsPerChild  4000

So, the master process will spawn one worker in this example on startup.  If there's more traffic, it will spawn more workers.  Once workers serve 4000 requests, the worker will die, and the master process may spawn new worker processes, depending on traffic.

A: I don't know the why's or the how's but it would seem that the root process is the parent process and the apache owned processes are the children.
I ran pstree -Acp | grep httpd and compared it to ps aux | grep httpd


text:
Q: Speech recognition is not working in Android Chrome I have just implemented speech recognition in React.js application using JS vanilla code in the function. In desktop Chrom I tested it successfully, but in Android chrome it didn't work. Any ideas?
setSpeechRecognition(true);
 var recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
                recognition.lang = 'en-US';
                recognition.interimResults = false;
                recognition.maxAlternatives = 5;
                recognition.start();
                recognition.onresult = function (event: any) {
                    clickHandler(event.results[0][0].transcript);
                    console.log('You said: ', event.results[0][0].transcript);
                };


text:
Q: Visualforce State and Country Picklists - Standard Fields Question
Can a Visualforce Page be built so it displays the actual picklist values and dependencies for fields which incorporate State and Country Picklists? I tried using Field Sets as well as hard-coded field references, and either way it just displays a text input.
MVR Markup
<apex:page standardController="Account">
    <apex:form>
        <apex:pageBlock>
            <apex:pageBlockSection>
                <apex:inputField value="{!Account.BillingStreet}" />
                <apex:inputField value="{!Account.BillingCity}" />
                <apex:inputField value="{!Account.BillingState}" />
                <apex:inputField value="{!Account.BillingPostalCode}" />
                <apex:inputField value="{!Account.BillingCountry}" />
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Screenshot

The edit page displays the picklist as expected:

A: Using the corresponding code field in the Visualforce e.g. {!Account.BillingStateCode} instead of {!Account.BillingState}will present the picklist values.


text:
Q: Need assistance getting a Spring form to work I'm in the middle of writing a Spring webapp and things were going well. I'm trying to write a form that allows an admin to change some basic user details. However, on submission of the form I keep getting an HTTP 400 error saying the request sent by the client was "Syntactically Incorrect". It doesn't offer any actual useful info though and I've really looked over everything and have no idea what I could be doing wrong. Here is the JSP:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="s" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags"%>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>

<s:url value="/admin/access" var="access_url" />
<sf:form method="POST" modelAttribute="user" dojoType="dijit.form.Form">

    Username:

        <sf:input path="username" dojoType="dijit.form.ValidationTextBox" trim="true" required="true"/>

    Password:

        <sf:input path="password" type="password" dojoType="dijit.form.ValidationTextBox" required="true"/>

    Enabled:

        Yes<sf:radiobutton path="enabled" value="true" dojoType="dijit.form.RadioButton"/>
        No<sf:radiobutton path="enabled" value="false" dojoType="dijit.form.RadioButton"/>

    Admin:

        Yes<sf:radiobutton path="isAdmin" value="true" dojoType="dijit.form.RadioButton"/>
        No<sf:radiobutton path="isAdmin" value="false" dojoType="dijit.form.RadioButton"/>

        <button dojoType="dijit.form.Button" type="submit">Submit</button>

</sf:form>

Here is the method that will end up being called in the Controller, though it's not getting that far:
@RequestMapping(value="/admin/editUser", method=RequestMethod.POST)
public String submitEditUser(@RequestParam("user") NFIUser nfiUser) {

And here is the GET mapping from the same controller, though the form displays perfectly with all values being mapped properly into the form so I don't know that there is any issue here:
@RequestMapping(value="/admin/editUser", method=RequestMethod.GET)
public void showEditUser(Model model, @RequestParam("username") String username) {
    ....
    model.addAttribute("user", user);
}

Anyway, if anyone has any thoughts please let me know. I've been successfully solving errors all I'm encountering all day but I can't seem to see any issue with this one. Thanks.

A: try to remove the @reqiestParam fotm the submitEditUser method.

A: Turns out the answer was a combination of what everyone left here. Normally for Spring you don't need an action method on a form but in this case it turned out, due to how I was loading the form one ended up being needed in the end to overwrite the action that was being loaded by Spring.
Also removing the @RequestParam("user") bit solved the problem of the 400 error. Because I was using spring form tags this time so that everything was bound nicely I guess I didn't need the RequestParam bit. Clearly I don't yet have the best understanding of when those are and aren't needed.
Anyway, I marked up people's answers, but technically none of them was the full solution so I posted this. Thanks all.


text:
Q: These PDF seems identical in VSCode but different in PDF viewver I have two PDF generated by an api using the same route.
The first one is saved from Postman and its size is 1.7 Mo and is good in PDF viewver.
The second one is saved from chrome and its size is 3.1 Mo and is white in PDF viewer.
When i open these two files in Visual Studio Code and i compare them, the only différence is the creation date :
First file :  /CreationDate (D:20200120202232)
Second file : /CreationDate (D:20200120201345)
So I can think that these two files are identical but not
Finaly if i save the first file in VSCode the new file size is 3.1 Mo and the file is white in pdf viewer like the second.
I don't understand what's happend... Someone understands something about this issue ?


text: Q: Plotly: Draw a horizontal line on a chart when you press it (Jupyter Notebook) How can I draw a horizontal line on a plotly chart (Jupyter notebook) at the y value where I pressed the chart? I have been trying to use fig_widget, but can't get it to work properly.


text:
Q: Form Submission - No Refresh/Hide Div after submit When I submit the form it redirects me back to the same page using this code
PHP
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n Email: $email_address \n Message \n $message";

$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";

mail($to,$email_subject,$email_body,$headers);

//redirect to the 'thank you' page
header('Location: index.html');
}

What I want it to do is stay on the same page without refreshing and then hide the div..
HTML

                <form method="POST" name="contactform" action="contact-form-handler.php" class="NewsLetter" class="NL__field NL__email">

                Your Name:

                <input type="text" name="name" class="NL__field NL__email">

                Email Address:

                <input type="text" name="email">

                Message:

                <input type="text" name="message">

                <input type="submit" value="Submit">

                </form>

JQuery
        $('form').submit(function(){
        $('#containerfooter').hide();
    });

A: Forms vs AJAX
Forms allow you to take user-entered data and send it to another PHP file for processing. However, when the form is submitted, navigation moves to the other PHP page (the one specified in the action="" attribute on the form tag:
<form method="POST" name="contactform" action="contact-form-handler.php" class="NewsLetter" class="NL__field NL__email">

In above tag, upon clicking submit button, the browser navigates to contact-form-handler.php
AJAX was invented to solve that, allowing you to send the data to the second PHP file, and (optionally) receive different data/html back without changing or refreshing the current page
Here is an SO post with some very simple examples of AJAX. It is not difficult - just copy the examples to your server and make them work on your server. Play with them a bit. The fifteen minutes you spend doing that will save you hours.
AJAX request callback using jQuery
Note: In this day and age, it is almost never necessary to use FORMs. Everything can be done via AJAX - and it's so simple, why wouldn't you?
Note2: When using AJAX with <form></form> tags, you must use e.preventDefault() to keep the form tag from navigating you away from the current page (the form tag's default action):
$('myButton').submit(function(evt){
    evt.preventDefault();
    //the rest of your js code, including ajax code block


text:
Q: Time to access list position v. check pertenence to set I needed to make an index of ASCII letters so was checking if making an adhoc index with a list was faster than doing it checking pertenence to set. Surprisingly the list accessing is slower than checking set pertenence when measuring times for the codes beneath. Even replacing the ord() by a literal the code is still slower. Whats the explaination for this behaviour?
lista = [1,0,0,0,0,0,0,0,1,1,1,1]
lset = set(['a','i','j','k','l'])
t1 = time.time()
for i in range(10000000):
    if lista[ord('k')-97] == 1:
        pass
t2 = time.time() - t1
print(t2)

t1 = time.time()
for i in range(10000000):
    if 'k' in lset:
       pass
t2 = time.time() - t1
print(t2)


text:
Q: How to aggregate on first value in postgres sql? In this postgres query
SELECT
    q.*,
    q.user_id = 1 mine,
    first(u.username) username,
    sum(case when v.answer=0 then 1 else 0 end) no_count,
    sum(case when v.answer=1 then 1 else 0 end) yes_count
FROM question q
JOIN "user" u ON q.user_id=u.id
JOIN vote v ON v.question_id=q.id
GROUP BY q.id
ORDER BY q.date_created desc
LIMIT 20
OFFSET 0

It says I need an aggregate on username. In this case, I am getting questions, and each question is created by some user. I join on votes, but group by the question id, so before grouping the username field will be the same for each unique question. So that means when aggregating, really I can pick any value since it's all the same. However I can't find any aggregate function to use. I tried random, first, last, any, but none work or even defined.
Does anyone know how to handle this?

A: Ok, so problem is that sql engine doesn't know that username will be always the same. In other words it can't tell relation one-to-one from one-to-many between guestions and users. You could use string_agg() with DISTINCT like string_agg(DISTINCT u.username, ','::text). What that functions does is it's aggragetes text values into one big string seperated by specified delimiter (in my case comma). When you add DISTINCT it takes only unique values. Since you've said theres always only one username per question the output will be that single value.
The whole query:
SELECT
    q.*,
    q.user_id = 1 mine,
    string_agg(DISTINCT u.username, ','::text) username,
    sum(case when v.answer=0 then 1 else 0 end) no_count,
    sum(case when v.answer=1 then 1 else 0 end) yes_count
FROM question q
JOIN "user" u ON q.user_id=u.id
JOIN vote v ON v.question_id=q.id
GROUP BY q.id
ORDER BY q.date_created desc
LIMIT 20;

Footnote: I dropped the OFFSET 0 because it's default value for LIMIT.

A: From the box postgresql do not allow or cant do such operations, but there is workaround.
You can extend aggregate functions First/Last by this method: https://wiki.postgresql.org/wiki/First/last_(aggregate)
There is plugin and portable sql version for postgresql.


text:
Q: jQuery - How to select the first parent of an element and add a new class "testclass"

            First Name

Given element 'element_1', how to select its first parent with tag name as li?
Thank you

A: $('#element_1').closest('li').addClass('testclass');

A: $('#element_1').closest('li').addClass('testclass');

assuming you're using jQuery 1.3+ and element_1 is an ID.
jQuery < 1.3 should look like
$('#element_1').parents('li').addClass('testclass');

Reference: .closest(), .parents()


text:
Q: fadeOut - запустить 2-й раз, пока не погас Накалякал функцию c ajax запросом, при успешном выполнении её появляется скрытый ранее div с возвращаемыми из php скрипта данными data - появляется шустро, исчезает медленно с эффектом fadeOut. Проблема в том, что функцию эту можно запустить со страницы чаще чем успевает скрыться div (функция отвечает за включение/выключение объявлений) и при этом он не появляется заного, а продолжает скрываться, если не успел, а после полного скрытия если запустить функцию - отрабатывает заново как надо.

В div ничего необычного, он один такой, вот подумал сейчас назначить каждому объявлению такой со своим id, но может быть есть другой выход?

A: $('#message_box').stop(true, true).show().text(data).fadeOut(2000);

Документация по stop


text:
Q: Why is the Raleway font not working on my site? Raleway font was being used on this site and I tried to change it to Lato.  Lato didn't work for some reason - it ended up looking like Times Roman - so I want to change it back to Raleway.  I have changed the CSS and the enqueue fonts script back to the original but when I look at the site and inspect element Lato still shows up.  Here is the enqueue script:
// add Google Fonts//
function wpse_google_webfonts() {
$protocol = is_ssl() ? 'https' : 'http';
$query_args = array(
    'family' => 'Raleway',
    'subset' => 'latin,latin-ext',
);

wp_enqueue_style('google-webfonts',
    add_query_arg($query_args, "$protocol://fonts.googleapis.com/css?
family=Raleway" ),
    array(), null);
}
add_action( 'wp_enqueue_scripts', 'wpse_google_webfonts' );

Is something wrong with this?  It is the original script that was being used.  If you want to look at the site it is https://www.classtechtips.com and you can see all the font is Lato.  How do I get this to change? It says it is still in the CSS but I changed it and for some reason it is not being picked up.

A: I just visited the site with Firefox inspector, and I see the CSS style enqueued correctly and the Raleway font being downloaded.
Checking the css for body I can see that the app.css, for the body tag, still specifies Lato as the font.
Perhaps you missed changing that back, or if using a cache plugin, perhaps you need to flush it.
By the way next time add Wordpress to the question's tags


text:
Q: Post to multiple accounts on twitter using API. getting duplicate status error. Trying to post to twitter using laravel and this twitter API package. Im using a foreach loop to grab each of the account tokens and post but I keep getting the error Duplicate status because it seems like its not changing the tokens before its posting to twitter. I've tried to refresh the page and the break the connection, still getting the error.
here is my foreachloop
foreach ($post['accountsToPost'] as $accountToPost) {
            $uniqueProfile= DB::table('profiles')->where('social_media_id', $accountsToPost)->first();
            $new_token = [
                'oauth_token'        => $uniqueProfile_test->oauth_token,
                'oauth_token_secret' => $uniqueProfile_test->oauth_secret,
                'x_auth_expires'     => $uniqueProfile_test->x_auth_expires,
            ];

            Session::forget('access_token');
            Session::put('access_token', $new_token);
            Twitter::postTweet(['status' => $post['post_text'], 'format' => 'json']);
            Session::flash('flash_message', 'Success! Your post has been sent.');
        }

Into the foreach loop im passing in
1. The social media I.D
2. The Oauth, secret tokens
3. The content to post
When I track the tokens using echo it seems to be getting all the right tokens but just not when posting to twitter. Could it be a connection issue? thats its not refreshing the connection for each account?

A: Figured it out. For anyone else that has the same problem with the package. Don't use session:: commands in the foreach loop. Use the Twitter::reconfig method. Not sure why but on post the session wasn't changing the tokens while in the foreach loop no matter what I tried. Using the reconfig method solved all the token issues.


text:
Q: how to overcome the limitation of IN cause in sql query I have written an sql query like :
select field1, field2 from table_name;

The problem is this query will return 1 million records/ or more than 100k records.
I have a directory in which I have input files (around 20,000 to 50,000 records) that contain field1 . This is the main data I am concerned with.
Using perl script, I am extracting  from the directory.
But , if I write a query like :
select field1 , field2 from table_name
where field1 in (need to write a query to take field1 from directory);

If I use IN cause then it has limitation of processing 1000 entries, then how should I overcome the limitation of IN cause?

A: In any DBMS, I would insert them into a temporary table and perform a JOIN to workaround the IN clause limitation on the size of the list.
E.g.
CREATE TABLE #idList
(
    ID INT
)
INSERT INTO #idList VALUES(1)
INSERT INTO #idList VALUES(2)
INSERT INTO #idList VALUES(3)

SELECT *
FROM
    MyTable m
    JOIN #idList AS t
    ON m.id = t.id

In SQL Server 2005, in one of our previous projects, we used to convert this list of values that are a result of querying another data store (lucene index) into XML and pass it as XML variable in the SQL query and convert it into a table using the nodes() function on XML data types and perform a JOIN with that.
DECLARE @IdList XML
SELECT @idList = '
<Requests>
    <Request id="1" />
    <Request id="2" />
    <Request id="3" />
</Requests>'

SELECT *
FROM
    MyTable m
    JOIN (
            SELECT id.value('(@id)[1]', 'INT') as 'id'
            FROM @idList.nodes('/Requests/Request') as T(id)
         ) AS t
    ON m.id = t.id

A: Vikdor is right, you shouldn't be querying this with an IN() clause, it's faster and more memory efficient to use a table to JOIN.
Expanding on his answer I would recommend the following approach:

*

*Get a list of all input files via Perl

*Think of some clever way to compute a hash value for your list that is unique and based on all input files (I'd recommend the filenames or similar)

*This hash will serve as the name of the table that stores the input filenames (think of it as a quasi temporary table that gets discarded once the hash changes)

*JOIN that table to return the correct records

For step 2. you could either use a cronjob or compute whenever the query is actually needed (which would delay the response, though). To get this right you need to consider how likely it is that files are added/removed.
For step 3. you would need some logic that drops the previously generated tables once the current hash value differs from last execution, then recreate the table named after the current hash.
For the quasi temporary table names I'd recommend something along the lines of
input_files_XXX (.i.e. prefix_<hashvalue>)

which makes it easier to know what stale tables to drop.

A: You could split your 50'000 ids in 50 lists of 1000 ids, do a query for each such list, and collect the result sets in perl.

A: Oracle wise, the best solution with using a temporary table - which without indexing won't give you much performance is to use a nested tabled type.
CREATE TYPE my_ntt is table of directory_rec;
Then create a function f1 that returns a variable of my_ntt type and use in the query.
select field1 , field2 from table_name where field1 in table (cast (f1 as my_ntt));


text:
Q: Cite in the caption of a graphic but not in \listoffigures? Sometimes I'd like to cite the reference in the caption of a graphic. But I want to avoid that this citation is displayed in the \listoffigures. How can I achieve that?
Fore example with this code:
\begin{figure}[htb]
\centering
\includegraphics{overview_pyramid.png}
\caption{Overview pyramid \cite{LM2010}}\label{fg:overview_pyramid}
\end{figure}

A: Why not simply use
\caption[Overview pyramid]{Overview pyramid \cite{LM2010}}\label{fg:overview_pyramid}


text:
Q: C# WinForms, ComboBox with 2 DataSources, differentiated by sorting / colored text? Can a C# ComboBox have two DataSources?
And then have them differentiated by:
- sorting (one source's entries at the top) and/or
- text color (one source's entries colored blue for instance)?

A: What i would do is combine them as one datasource, sorting it as you please, adding a property that indicates the color and then you could bind the text to one property and the color to another.

A: You can query from different datasource and dump it in a single collection type and bind to combobox.
Here is a sample code, you can do something similar to this
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Drawing;
    using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        List<Item> items;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Let's say we are getting items from two different datasources and putting them in a same collection
            items = new List<Item>();
            //Getting pens from dataSource1
            items.Add (new Pen("Parker",Color.Blue ));
            items.Add(new Pen("Paper Mate", Color.Blue));
            //Adding Books from dataSource2
            items.Add(new Book("Programming in C", Color.Red));
            items.Add(new Book("Design Patterns", Color.Red));
            //Data binding
            comboBox1.DataSource = items;
            comboBox1.DisplayMember = "Name";
            comboBox1.ValueMember = "Color";
            this.comboBox1.DrawMode = DrawMode.OwnerDrawFixed; //Do not forget this
        }

        private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            e.DrawBackground();
            int index = e.Index;
            Item   item = comboBox1.Items[index] as Item  ;
            if (item.Color.Equals ( Color.Red))
                e.Graphics.DrawString(item.Name, this.Font , Brushes.Red, new Point(e.Bounds.X, e.Bounds.Y));
            else if  (item.Color.Equals ( Color.Blue))
                e.Graphics.DrawString(item.Name, this.Font, Brushes.Blue, new Point(e.Bounds.X, e.Bounds.Y));
            else
                e.Graphics.DrawString(item.Name, this.Font, Brushes.Black, new Point(e.Bounds.X, e.Bounds.Y));
        }
    }

    public abstract class  Item
    {
        string name;
        Color  color;
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }

        public Color Color
        {
            get
            {
                return color;
            }
            set
            {
                color = value;
            }
        }
    }

    public class Book:Item
    {
        public Book(string name, Color color){
            this.Name  = name;
            this.Color = color;
        }
    }

    public class Pen : Item
    {
        public Pen(string name, Color color){
            this.Name  = name;
            this.Color  = color;
        }
    }
}

A: Yes.
I would achieve this by doing two separate queries and inserting in to an array with their specified properties (eg. text color, id etc.), and then "binding" the combobox to the array.
Sorry, no code samples as I am not that good at c#, but this is how I would achieve the goal in my language of choice.


text:
Q: How to add id and title in php url I have the url which is working fine with sub_id but now i want to modify the url and i want to show 'sub_categories_name' along with 'sub_id'. But, 'sub_categories_name' is just like dummy i.e it is of no use, if a person search only with 'sub_id' then it will show the result.
I have tried something like this but the page is not showing any data
<?php
  $categories_name = $_GET['categories_name'];
  $result = "SELECT * FROM sub_categories where
    categories_name='$categories_name'";
    $data =mysqli_query ($conn, $result);
    while ($row = mysqli_fetch_array($data))
    {

      $sub_categories_name = $row['sub_categories_name'];
      $sub_id = $row['sub_id'];

        $sub_categories_name  = urldecode($sub_categories_name );
        $sub_categories_name = str_replace(' ', '-', $sub_categories_name);

        $url = '/classified/' . urlencode($sub_id) . '-' . urlencode($sub_categories_name);

    ?>

<?php echo $sub_categories_name;?>

<?php }?>

When my url is like  'http://localhost/classified/1', it is showing the data but when my url is like 'http://localhost/classified/1-Health-and-Beauty', it is not showing any data. I just want to show data on this also.
here is my {DOCUMENT_ROOT}/classified/.htaccess
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ category-classifieds.php?sub_id=$1 [L]

actually generated source code snippet of the HTML links. (browser view source) is like

Health and Beauty

Thanks in advance, Please help me out.

A: As already mentioned in comments, somewhere in your project you must have a decision on $_GET['sub_id']. If you use intval($_GET['sub_id']) instead, everything after the number will be cut off.
Based on mod_rewrite you could alter your rule to
RewriteRule ^(\d+) category-classifieds.php?sub_id=$1 [L]

meaning 1 or more digits at the begin of the current URL part based on the folder, ignoring anything which follows after the digits.


text:
Q: PHP code is not executed after specific statement after years I have started again with PHP and I have now a very stupid problem where I don't know how to solve it.
In each php script, after '->' the code is no longer excecuted, it is just shown in the browser.
I use Apache with PHP Version 8.1.10. Is there anything I have to configure?
Example (script taken from W3):
 <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

....
?>

Code is only parsed until 'if ($conn->' after the -> statement, the code is visible in the browser:
Show Code in Browser
Has anyone an idea what I'm doing wrong? I have no idea anymore..
Thanks,
Best regads
I tried multiple online examples, copy-pasted them 1:1, changed the browser, re-installed XAMPP.. Always the same behaivor


text:
Q: Count all divs in a component having 'ng-show' attribute I have a component <row/> containing multiple <cell/> components.
Some of the cells have ng-hide attr and some cells have a keyword 'mutate' :
<row>
   <cell> </cell>
   <cell ng-hide = "cond"> </cell>
   <cell mutate> </cell>
</row>

Using $element.find("cell"), I'm able to get the count of all <cell/> within a <row/>.
But, I want to find the the number of cells with "mutate" attr or number of cells with "ng-hide" attr. Finding either will do.
Can someone please help me out here?

A: The idea behind angular (and angularjs) is the HTML mirrors the data structure(s). Rather than count HTML elements to find out how many are hidden with ng-hide='cond', you would just query the data structure, maybe something like
let cond='foobar', numHides = $scope.dataArray.filter(f => f.cond == cond).length;
console.log(numHides);

However, angularjs does have an element method, so you could do a direct DOM element count, once you're sure your data has parsed into the HTML:
let numMutates = angular.element(document.querySelectorAll('[mutate]'));


text:
Q: Primitive pattern matching in R I have become confused over the following lines of code:
test1 = c(0.3, 0.1)
test1 = test1 - 0.1
test2 = c(0.2, 0.0)
test1 == test2
# [1] FALSE  TRUE

I think it is quite self explaining why this seems very weird. If anybody could give some insight into what is happening here it would be highly appreciated.


text:
Q: Remoting into Windows 7 computer wipes out PATH When I remote into my Windows 7 computer (local admin user), weird things are happening.
I had RDC (mstsc) and Windows Explorer icon on my Task Bar, clicked on them then "cannot find item" error, Visual Studio 2010-2013 wouldn't open with an "Exception has been thrown by the target of an invocation" dialog. all went haywire. Wasn't able to run my Python scripts from the command line unless I go to the python directory. Ah, a clue...
Fired up cmd, typed path... (null).  What?!
Remotely rebooted my computer, waited for it to come back up before logging in again, all is fine.
Happens all the time.  Any ideas?
One idea is that my user profile is corrupted and I should just wipe it out.  Want to be sure that is the case before I engage in this effort.

A: Your path is probably longer than 2048.  That is a published limit, and reducing your path below that will probably solve your problem.
I'm not sure why RDP triggers it.  My path is over 2048 when I first boot up, and it doesn't seem to matter... until I access the my workstation remotely using RDP.


text:
Q: jQuery(document).on("keydown",...) works, but not document.addEventListener("keydown",...) I thought I should see how much I really need jQuery now. So I started by replacing
jQuery(document).on("keydown.", function(e){...})

with
document.addEventListener("keydown", function(e){...})

I believed that one was easy, but to my surprise the event was no longer fired. To investigate this a bit I entered the second version in the console. Now it worked. ;-)
That is a bit impractical, of course. I would prefer that I did not have to enter it in the console...
In the code the event listener is added right after some changes to the DOM, i e some additions. I guess the trouble might be related to this, but I have no idea what to do.
Any suggestions?
EDIT: Thanks everyone for the comments. In this particular case it would be good to get rid of jQuery (but otherwise it is no problem using jQuery of course).
I should have said that some DOM elements are added long after the page is loaded so window.onload etc is not useful here.
I should maybe also have said that I am testing this in the latest version of Chrome and for this I am not interested in backward compatibility (it is too complicated anyway in this case so I have just dropped that... ;-) ).
UPDATE: Someone asked for code. Here is an example I just tested:
    document.addEventListener("keydown.test", function(e){
        console.log("doc.addEL test keydown, e=", e)
    });

Looking in Chrome Dev Tools at the properties of the HTML element I can see the event listener there (with the code above). It is just not fired. Seems like it is just time to write yet another bug report then. ;-)

A: My bad. I misread the news that event handlers now can be removed using standard syntax. They can, but the syntax is that you give the event+handler function to removeEventListener.
The syntax I used above for the event, "keydown.test", is not a valid syntax (if you are not using jQuery).
Sorry for wasting your time. Hope someone can use the answer.


text:
Q: twitter sharing using sharekit crashing in ios 5 Hi I'm trying to a share images using sharekit on twitter,from app. I have added a twitter icon and when clicked I call this function
 -(void)shareTwitter
{
    SHKItem *itemshare = [SHKItem image:imgView.image title:projectname];
    [SHK setRootViewController:self.navigationController];
    [SHKTwitter shareItem:itemshare];
}

after this function is executed the app crashes saying exec_bad_access in sharekit code.
I have added the piece of line below where it occurs.
iOS5twitter.completionHandler = ^(TWTweetComposeViewControllerResult result) ;

I tried to reproduce the same issue with the demoapp provided by sharekit.The app runs fine and even posts image.
The crash appears before login authentication. can someone  guide me thru this and help me fix this issue
thanks


text:
Q: How to redirect the output of a command into a txt file? I want to place  the output of the following command into a file called log.txt the command is the following
readlink -f var > log.txt
I basically just need to be able to put the file location into that file but it has to be done through code not through the terminal
delete () {  #deletes all files in the arguments and places it in the recycle bin

shift
for var in "$@"
do
mv $var ~/RecycleBin
echo $var > log.txt
readlink -f var > log.txt
done

 }

for some reason its not writing anything into the file file remains blank.
I changed it to this
for var in "$@"
do
mv $var ~/RecycleBin
echo $var >> log.txt
readlink -f $var >> log.txt
done

}

A: Use $var to access content of  a variable, not var.
Use >> to append content to a file. > overwrites an existing file.
Quote variables with double quotes: "$var"


text:
Q: Undefined symbol: _swift_getOpaqueTypeConformance - React Native & SwiftUI I'm trying to port a SwiftUI view into react native following this guide. It build fine in swift project but not in a react native project.
I'm getting the following error:
Undefined symbols for architecture x86_64:
  "_swift_getOpaqueTypeConformance", referenced from:
      lava.ColorWheelView.body.getter : some in ColorWheelView.o
      closure #2 (SwiftUI.GeometryProxy) -> <<opaque return type of lava.ColorWheelView.makeView(SwiftUI.GeometryProxy) -> some>>.0 in lava.ColorWheelView.body.getter : some in ColorWheelView.o
      associated type witness table accessor for SwiftUI.View.Body : SwiftUI.View in lava.ColorWheelView : SwiftUI.View in lava in ColorWheelView.o
      l_get_witness_table qd0__7SwiftUI4ViewHD3_AaBPAAE7gesture_9includingQrqd___AA11GestureMaskVtAA0F0Rd__lFQOyAA15ModifiedContentVyAA6ZStackVyAA05TupleC0VyAJyAA06_ShapeC0VyAA9RectangleVAA5ColorVGAA12_FrameLayoutVG_AJy4lava010GuitarPickC0VAA13_OffsetEffectVGtGGAA09_PositionP0VG_AA06_EndedF0VyAA0f5StateF0VyAA08_ChangedF0VyAA04DragF0VGSo7CGPointVSgGGQo_HO in ColorWheelView.o
      associated type witness table accessor for SwiftUI.View.Body : SwiftUI.View in lava.TrianglePath : SwiftUI.View in lava in GuitarPickView.o
      associated type witness table accessor for SwiftUI.View.Body : SwiftUI.View in lava.GuitarPickView : SwiftUI.View in lava in GuitarPickView.o
  "_swift_getTypeByMangledNameInContextInMetadataState", referenced from:
      ___swift_instantiateConcreteTypeFromMangledNameAbstract in ColorWheelView.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

To reproduce I made this Github repo
Copy those files in a react native project and try to build. Make sure to replace the header file import with your test project name "<Replace This>-Swift.h"
My build target is iOS 13.5 iPhone 11 Pro Max simulator.


text:
Q: using handsoap or Savon I created wsdl server with soap4r but facing unicode problems with it.
so thought of trying savon or handsoap.
Is there any resource where i can find how to define services and
start a server(may be thin or something similar) with them?

A: Here's the official documentation for both libraries:

*

*Savon Documentation

*Handsoap Wiki

A: Those are both client side libraries, so they won't be overly useful for your case.


text:
Q: php mktime gives different results for same date? the following code:
    // settings 1st alternative
    $season = 2011;
    $startweek = 36;

    // calculation, 1st alternative
    // in any case Jan 1st is in 1. week
    $firstweekuniversal = mktime(0,0,0,1,4,$season);
    // I'd like to calculate monday 0:00 of the given week.
    // date(...) computes to monday of the calculated week.
    $startday1 = $firstweekuniversal + 86400 * (7*($startweek-1) - date('w', $firstweekuniversal)+1);

    // settings 2nd alternative
    $StartingDate = "KW36 - 5.09.2011 (Mo)";

    // calculation, 2nd alternative
    $firstparts = explode(" ", $StartingDate);
    $secparts = explode(".", $firstparts[2]);
    $startday2 = mktime(0,0,0,intval($secparts[1]),intval($secparts[0]),intval($secparts[2]));

    // Output
    echo "Start: \$startday1=".$startday1.", Timestamp=\"".date("d.m.Y - H:i:s", $startday1)."\"
\n";
    echo "Start: \$startday2=".$startday2.", Timestamp=\"".date("d.m.Y - H:i:s", $startday2)."\"
\n";

leads to this output:
Start: $startday1=1315177200, Timestamp="05.09.2011 - 01:00:00"
Start: $startday2=1315173600, Timestamp="05.09.2011 - 00:00:00"

where is the 1h difference coming from? It can't be summertime issues, in that case the 1h had to be the other way round, or am I wrong?
There's no difference, when I'm trying with my environment (localhost), but on the server of my prvider there is.
Can anyone explain this to me? I'm totally puzzled here.
Thanks in advance,

A: My understanding of daylight savings is that at a certain point between winter and summer the sun is starting to rise earlier, so at 8am it would feel like it should be 9am ... and that's exactly what the clock does, it moves forward making it later (by one hour typically). This is also why it's such a good excuse for being late at school :)
In any case, the timezone setting of your local php is probably UTC (or some other "neutral" timezone) but the server timezone setting honors daylight savings.


text:
Q: Power BI embed code throws 403 forbidden error from server The embedded power BI dashboard is rendered fine at localhost domain, but on another domain it renders some time and not always, which is on server throws a error.
errorlog image1 and errorlog image2
I am calling the powerbi rest api's from my server[PHP laravel] end and i am returning the embedtoken,reportid,embedurl to the client side[Angular4]. I use angular2-powerbi npm package for embedding the report on ui.
Please, some one help me on this. It's been a long time i am trying to fix this.
Early solution is appreciated.
Thanks in advance

A: Based on "errorlog image2", your token has expired.
Here is a example how to get a new token: https://github.com/Microsoft/PowerBI-JavaScript/wiki/Refresh-token-using-JavaScript-SDK-example


text:
Q: Why does std::sort appears to alternate the values in the vector The below code snippet shows that std::sort is alternating the values in the vector which is quite confusing.
std::vector<int> a;
std::vector<std::string> b;
std::vector<std::pair<int&, std::string&>> p;

a.push_back(1);
a.push_back(3);
a.push_back(2);
b.push_back("hi 1");
b.push_back("hi 3");
b.push_back("hi 2");

p.push_back(std::pair<int&, std::string&>(a[0],b[0]));
p.push_back(std::pair<int&, std::string&>(a[1],b[1]));
p.push_back(std::pair<int&, std::string&>(a[2],b[2]));

std::sort(p.begin(),p.end());

std::cout << a[0] << " " << a[1] << " " << a[2] <<  std::endl;
std::cout << b[0] << " " << b[1] << " " << b[2] <<  std::endl;

I am expecting it to print
1 2 3
hi 1 hi 2 hi 3

but instead it prints
1 3 3
hi 1 hi 3 hi 3

Why? My compiler is gcc 4.9.3.
I am trying to sort two vectors together and using vector of pairs of references is suggested in https://stackoverflow.com/a/37929675/3667089.

A: I would say std::pair<int&, std::string&> is not swappable. std::swap seems to work though, but if you think in a naive swap, it won't work with references
std::pair<int&, std::string&> pair0(a[0],b[0]);
std::pair<int&, std::string&> pair1(a[1],b[1]);

std::pair<int&, std::string&> tmp(pair0);
pair0 = pair1;
pair1 = tmp;

then pair0 gets overwritten by pair1.
References in general won't work with STL containers.

A: The problem is in the insertion sort implementation. Since there are less number of elements, sort decides to perform an insertion sort.
Problematic code:
template<typename _RandomAccessIterator>
    void
    __unguarded_linear_insert(_RandomAccessIterator __last)
    {
      typename iterator_traits<_RandomAccessIterator>::value_type
        __val = _GLIBCXX_MOVE(*__last);
      _RandomAccessIterator __next = __last;
      --__next;
      while (__val < *__next)
        {
          *__last = _GLIBCXX_MOVE(*__next); <<< PROBLEMATIC Code
          __last = __next;
          --__next;
        }
      *__last = _GLIBCXX_MOVE(__val);
    }

Now it goes inside the while loop for the index 2 and index 3 case. Before going into the while loop, __val has the value 2 and hi 2. But after doing the first move inside the while, __val also changes to 3 and hi 3 and outside the while last is set to 3 and hi 3, which is incorrect.
UPDATE: libc++
Code in libc++ for this is pretty straightforward and boils down to comparing just 3 values in __sort3. libc++ uses swap instead of move unlike libstd++ and hence works.
So, seems like moving on reference types is not good as it overwrites the data when the moved element is assigned with new value. Perhaps the same would be the result in libc++ also if we use more than 3 or 4 elements in which case it will also use move under a generic insertion sort routine.
UPDATE 2:
Checking more into it, libc++ always uses swap at least for insertion_sort, so no trouble there.
To quote from standard on why references are not good to be stored in container:
(Section 23.2)

Containers are objects that store other objects. They control
  allocation and deallocation of these objects through constructors,
  destructors, insert and erase operations.

And the table beneath that has this requirement:

X::value_type - T Requires: T is compile time type Destructible

Though I am not sure if reference type is destructible or not. If not, we should better get compile time errors for storing references in STL containers.

A: It's possibly a bug in libstdc++. I added a "debug" comparator to see the sort in action for both libstdc++ and libc++:
std::sort(p.begin(), p.end(), [&] (const auto& ap, const auto& bp)
{
    std::cout << "Debug: " << ap.first << " " << bp.first << " | ";
    for (auto e : a)
        std::cout << e << " ";
    std::cout << " | ";
    for (auto e : b)
        std::cout << e << " ";
    std::cout << "\n";
    return ap.first < bp.first;
});

And this is the output:
Debug: 1 1 | 1 3 2  | hi 1 hi 3 hi 2
Debug: 3 1 | 1 3 2  | hi 1 hi 3 hi 2
Debug: 3 1 | 1 3 2  | hi 1 hi 3 hi 2
Debug: 2 1 | 1 3 2  | hi 1 hi 3 hi 2
Debug: 2 3 | 1 3 2  | hi 1 hi 3 hi 2
Debug: 3 1 | 1 3 3  | hi 1 hi 3 hi 3
1 3 3
hi 1 hi 3 hi 3
--------------------------
Debug: 3 1 | 1 3 2  | hi 1 hi 3 hi 2
Debug: 2 3 | 1 3 2  | hi 1 hi 3 hi 2
Debug: 2 1 | 1 2 3  | hi 1 hi 2 hi 3
1 2 3
hi 1 hi 2 hi 3

For some reason the 2 element gets overwritten by a 3.
The other possibility is that std::pair<int&, std::string&> does not meet the definition of ValueSwappable. That is, when the actual swapping of elements occur in the sort function, you are experiencing undefined behavior.


text:
Q: How can I format external hard disk that is not initialized and only detected in disk management? My external hard disk has got some problem with GPT/MBR initialization. This says "The request could not be performed because of an I/O device error". No problem. Let it go.
Is there any way to format and make it usable?


text:
Q: How to use the output of a function in another function? I created a function to get date from the user and convert it into datetime format using strptime. The function is called Obtaindate(). This will go as input into another function Getdata(). Now, in the second function Getdata() I need to subtract the date from Obtaindate() with timedelta. But I get the error TypeError: unsupported operand type(s) for -: 'NoneType' and 'datetime.timedelta'.
What should I do to get the date from the 1st function to work in the second function?
Here is the code sample:
def ObtainDate():

    isValid=False

    while not isValid:

        userin = str(input("Type Date ddmmyy: "))

        try:
            dt = datetime.datetime.strptime(userin, '%d%m%y')
            print('You have selected {}'.format(datetime.date.strftime(dt, '%d-%b-%Y')))
            break
        except:
            print("Incorrect format...try again!")
            continue

            return dt

ObtainDate()

def Getdata():

    date1 = ObtainDate() - datetime.timedelta(1)
    date2 = datetime.datetime.today()
    delta = datetime.timedelta(1)

    while date1 < date2:

        print('Download in progress...')

A: Try this - comments inlne to show add.mmove/delete
The except isn't very nice - better to catch the specific exception(s)

def ObtainDate():

    isValid=False

    while not isValid:

        userin = str(input("Type Date ddmmyy: "))

        try:
            dt = datetime.datetime.strptime(userin, '%d%m%y')
            print('You have selected {}'.format(datetime.date.strftime(dt, '%d-%b-%Y')))

            return dt    ####### moved here
        except:
            print("Incorrect format...try again!")
            continue

# REMOVED        return dt

def Getdata(adate): # ADDED PARAMETER

    date1 = adate- datetime.timedelta(1) # USE PARAMETER
    date2 = datetime.datetime.today()
    delta = datetime.timedelta(1)

    while date1 < date2:

        print('Download in progress...')
        # ADDED SAVING DATA
        data_for_this_date = …

    # ADDED RETURN
    return data_for_this_date

# ADDED SAVING VALUE OF FUNCTION CALL
theday = ObtainDate()
# ADDED PASSING the result from Obtaindate()
# AND ADDED store result returned by Getdata in a variable
data = Getdata( theday )


text:
Q: Android: how to create a button with image and text that are both centred I got stuck in an odd issue with Android - I want to have a button that looks like this:
 |-----------------------------------------------------------------------|
 |                   [icon] <5px> [text text text]                       |
 |-----------------------------------------------------------------------|

and the group ([icon] <5px> [text text text]) should be centred. Note that 5px is used just as a placeholder for any padding you want to have between the icon and the text
I found some answers here that were more or less graviting around either setting a background (which I don't want to do because I have another background) or using the android:drawableLeft property to set the icon.
However looks like the documentation of the setCompoundDrawablesWithIntrinsicBounds method is a bit misleading (see here). It states that the image is placed on the left/right/top/bottom side of the TEXT wich is not true. The icon is placed on the corresponding side of the BUTTON. For example:
Setting the android:drawableLeft property puts the icon on the most left position and gets me this (with gravity CENTER):
 |-----------------------------------------------------------------------|
 | [icon]                     [text text text]                           |
 |-----------------------------------------------------------------------|

or this  (with gravity LEFT):
 |-----------------------------------------------------------------------|
 | [icon] [text text text]                                               |
 |-----------------------------------------------------------------------|

Both are ugly as hell :(
I found a workaround that looks like this:
public static void applyTextOffset(Button button, int buttonWidth) {
    int textWidth = (int) button.getPaint().measureText(button.getText().toString());
    int padding = (buttonWidth / 2) - ((textWidth / 2) + Constants.ICON_WIDTH  + Constants.ICON_TO_TEXT_PADDING);
    button.setPadding(padding, 0, 0, 0);
    button.setCompoundDrawablePadding(-padding);
}

And it works more or less but I don't find it to my liking for following reasons:

*

*it requires to know the button width. With auto-sized buttons it will not be known until the actual layout is done. Google recommend using a listener to learn the actual width after the rendering is done but this immensely complicates the code.

*I feel like I'm taking over the layout responsibility from the Android layout engine

Isn't there a more elegant solution?

A: You can use the following Button subclass to achieve this effect.

*

*Paste this class into your project and tweak the package name if desired.

    package com.phillipcalvin.iconbutton;

    import android.content.Context;
    import android.content.res.TypedArray;
    import android.graphics.Rect;
    import android.graphics.Paint;
    import android.graphics.drawable.Drawable;
    import android.util.AttributeSet;
    import android.widget.Button;

    public class IconButton extends Button {
      protected int drawableWidth;
      protected DrawablePositions drawablePosition;
      protected int iconPadding;

      // Cached to prevent allocation during onLayout
      Rect bounds;

      private enum DrawablePositions {
        NONE,
        LEFT,
        RIGHT
      }

      public IconButton(Context context) {
        super(context);
        bounds = new Rect();
      }

      public IconButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        bounds = new Rect();
      }

      public IconButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        bounds = new Rect();
      }

      public void setIconPadding(int padding) {
        iconPadding = padding;
        requestLayout();
      }

      @Override
      protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);

        Paint textPaint = getPaint();
        String text = getText().toString();
        textPaint.getTextBounds(text, 0, text.length(), bounds);

        int textWidth = bounds.width();
        int contentWidth = drawableWidth + iconPadding + textWidth;

        int contentLeft = (int)((getWidth() / 2.0) - (contentWidth / 2.0));
        setCompoundDrawablePadding(-contentLeft + iconPadding);
        switch (drawablePosition) {
        case LEFT:
          setPadding(contentLeft, 0, 0, 0);
          break;
        case RIGHT:
          setPadding(0, 0, contentLeft, 0);
          break;
        default:
          setPadding(0, 0, 0, 0);
        }
      }

      @Override
      public void setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top, Drawable right, Drawable bottom) {
        super.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);
        if (null != left) {
          drawableWidth = left.getIntrinsicWidth();
          drawablePosition = DrawablePositions.LEFT;
        } else if (null != right) {
          drawableWidth = right.getIntrinsicWidth();
          drawablePosition = DrawablePositions.RIGHT;
        } else {
          drawablePosition = DrawablePositions.NONE;
        }
        requestLayout();
      }
    }

2. Modify your layout to use this new subclass instead of plain Button:
    <com.phillipcalvin.iconbutton.IconButton
        android:id="@+id/search"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/search"
        android:text="@string/search" />

3. If you want to add padding between the drawable and the text, add the following to your activity's onCreate:
    // Anywhere after setContentView(...)
    IconButton button = (IconButton)findViewById(R.id.search);
    button.setIconPadding(10);

This subclass also supports drawableRight. It does not support more than one drawable.
If you want more features, such as the ability to specify the iconPadding directly in your layout XML, I have a library that supports this.

A: You may also consider using a custom view to create a custom button.
This could be anywhere from easy to extremely complex.
It would be easy if all you need to do is override onDraw(). It will be more complex if you need to lay out multiple views.

A: Simply way is to write Button in LinearLayout. Something like this
 <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center">

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:drawableLeft="@drawable/ic_left"
                android:drawablePadding="5dp"
                android:duplicateParentState="true"
                android:text="Button text"/>

        </LinearLayout>

A: I tried this in eclipse and it spouted no errors:
<Button android:id="@+id/test"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent" >
<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:gravity="center"
    android:background="@android:color/transparent" >

    </LinearLayout>
    </Button>

Therefore, I suppose you could add an image and text views in a layout, itself inside a button, and center the layout.
Best regards.


text:
Q: Project Status Table derivation SQL logic Just sample entries

proj    stat   Inact
----------------------
PROJ1   I0002
PROJ1   I0001
PROJ2   I0042   X
PROJ3   I0046   X
PROJ3   I0045
PROJ4   I0001   X
PROJ5   I0001   X
PROJ6   I0001   X

*

*If any of I0001 OR I0002 OR I0042 is Active ( Inact = blank), then it
is OPEN.

*If any of I0045 OR I0046 is Active( means Inact = blank or
entry doesnt exist), then it is CLOSED.

*Both 1 and 2 condition should satisfy

*Also If the above 5 status doesnt exists for any particular
Proj then also it is OPEN by default

How can i derive the Project status (OPEN,CLOSE)?Please help.
proj    stat are the primary keys.

A: You seem to want aggregation with conditional logic:
select proj,
       (case when sum(case when stat in ('I0001', 'I0002', 'I0042') and inact is null then 1 else 0 end) > 0
             then 'open'
             when sum(case when stat in ('I0045', 'I0046') and inact is null then 1 else 0 end) > 0
             then 'closed'
             else 'open'
        end) as status
from t
group by proj


text:
Q: How to constantly check GPS Signal strength I want to display GPS Signal Strength in the form of image like:

But I can't find any documentation about this or example.
I have tried this:
if (self.locationManager.location.horizontalAccuracy < 0)
        {
            ...@"No"];
        }
        else if (self.locationManager.location.horizontalAccuracy > 163)
        {
            ...@"Poor"];
        }
        else if (self.locationManager.location.horizontalAccuracy > 48)
        {
            ...@"Average"];
        }
        else
        {
            ...Full
        }

But it seams that this code does nothing.
How can I monitor GPS signal strength, is it possible?

A: Where is this code located? Your code should be in the delegate callback:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
       fromLocation:(CLLocation *)oldLocation

or iOS 6.0 and above:
- (void)locationManager:(CLLocationManager *)manager
 didUpdateLocations:(NSArray *)locations


text:
Q: Will files created under source directory after running `cp` be copied? Suppose I use cp to copy a directory to another place. If the process takes long, and I create a new file under the source directory, will it be copied, or does it depend on something?

A: If you create a new file while cp is operating, it's likely that it won't be picked up. That might depend on the cp implementation: some gather a list of files when they start, others do it by chunks. If it's a recursive copy, all the cp implementations I've seen work directory by directory, so if you add the file to a directory that cp hasn't traversed yet, it will be copied.
If you add a file midway and you want to copy it, run rsync afterwards (after the copy is finished and the new file is fully written). Rsync will only copy the added file.
You can run rsync from the start (use rsync -a to do a recursive copy and preserve metadata). Rsync can do pretty much everything cp can do and much more, so you can ignore cp and always use rsync if you like (except on embedded systems that don't have rsync).


text:
Q: Mobile Network Settings in Android 4.1 My app should open Mobile Network Settings activity. Everything works fine except devices with Android 4.1 which crash after attempt to open Settings
Intent intent = new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
final ComponentName cName = new ComponentName("com.android.phone", "com.android.phone.Settings");
intent.setComponent(cName);
startActivity(intent);

Stack trace after crashing:
java.lang.SecurityException: Permission Denial: starting Intent { act=android.settings.DATA_ROAMING_SETTINGS cmp=com.android.phone/.Settings } from ProcessRecord{41b83198 ...

Any ideas? Could it be because of the manifest?
UPDATE:
Seem that the problem was solved here:
Android - Mobile network settings menu (Jelly Bean)
The thing is to change "com.android.phone.Settings" to "com.android.phone.MobileNetworkSettings"

A: I think you have to try
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
startActivity(intent);

This thing is working for me in android 4.1.2,
might be they fixed this issue in 4.1.2


text:
Q: Using eval is bad but how else can I do this? I'm creating a json data source for Grafana in Python. It will grab information from JIRA and present is as a table to Grafana. I want the creation of the table to be dynamic so I want to be able to dynamically assign the fields I grab. The only way I've found that works so far is using eval()...
Can someone point me to a better solution? I've looked at getattr and setattr but either I don't understand how to use it or it doesn't do what I need..
Below example uses it only for priority:
priority = 'issue.fields.priority.name'

for issue in self.jira.search_issues(jql, maxResults=False):
    if issue.fields.assignee:
        issuelist.append([issue.key, issue.fields.assignee.displayName, eval(priority)])
    else:
        issuelist.append([issue.key, 'Unassigned', eval(priority)])

A: IIUC, you could use getattr in the following way:
Setup
class Priority:

    def __init__(self, name):
        self.name = name

class Fields:

    def __init__(self, priority):
        self.priority = priority

class Issue:

    def __init__(self, fields):
        self.fields = fields

Code
from functools import reduce

priority = 'issue.fields.priority.name'
issue = Issue(Fields(Priority("high")))

print(eval(priority))
print(reduce(getattr, priority.split('.')[1:], issue))

Output
high
high

So in your code you could change:
issuelist.append([issue.key, 'Unassigned', eval(priority)])

to:
issuelist.append([issue.key, 'Unassigned', reduce(getattr, priority.split('.')[1:], issue)])


text:
Q: How to check if matching text is found in a string in Lua? I need to make a conditional that is true if a particular matching text is found at least once in a string of text, e.g.:
str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
    print ("The word tiger was found.")
else
    print ("The word tiger was not found.")

How can I check if the text is found somewhere in the string?

A: There are 2 options to find matching text; string.match or string.find.
Both of these perform a regex search on the string to find matches.

string.find()
string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.
The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.
Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).
You will likely use this in combination with string.sub
Example
str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

string.match()
string.match(s, pattern, optional index)

Returns the capture groups found.
Example
str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end


text:
Q: TypeError: undefined is not a function on mobile (but no error on desktop) This line: var welcome_message = $('.alert-info').text().includes("signed up") is causing the error:

TypeError: undefined is not a function (evaluating '$(".alert-info").text().includes("signed up")')

I'm having trouble identifying what the issue is since it works perfectly when I'm running it on desktop.


text:
Q: I am getting error on stream controller on flutter When I open the app it opens, when I click on the image it opens but when I press back n again click on the image it throws an exception saying

"Stream has already listened to".

Here is my code:
    StreamSubscription<T> _subscribe(void onData(T data), Function onError,
      void onDone(), bool cancelOnError) {
    if (!_isInitialState) {
      throw new StateError("Stream has already been listened to."); //here I get the exception
    }
    _ControllerSubscription<T> subscription = new _ControllerSubscription<T>(
        this, onData, onError, onDone, cancelOnError);

    _PendingEvents<T> pendingEvents = _pendingEvents;
    _state |= _STATE_SUBSCRIBED;


text:
Q: Floating point inexact result exception in TFDTable Component in Delphi I am using TFDTable component in Delphi Seattle. I have kept this table component at design time.
While executing
TFDTable(Compo).Open
I get error while debugging (Ctrl +F7) "Floating point inexact result at 0042F353"
I googled, but got the reason but didn't get exactly what it is.
Any suggestions?
Reference URL:
http://www.delphigroups.info/2/e8/524771.html

Floating Point inexact result
This exception suggests that you have
the "loss of precision" mask   bit in the FPU turned OFF.  It is
normally ON.  Look for the $0020   bit in the system variable
Default8087CW and try ORing in $0020 into   the control word with a
Set8087CW(Default8087CW or $0020) statement.

http://www.umiacs.umd.edu/~resnik/ling645_sp2002/cmu_manual/node19.html

A: There is a well known issue that Default8087CW as a global variable can be misused by libraries or even your own code and be changed at any time in ways that cause unexpected results of FP calculations or unexpected exceptions to occur. The six lowest bits of the 8087 FPU Control word are the exception mask bits, meaning that if a bit is set, corresponding exception is masked, that is prevented from being raised.
The "loss of precision" mask bit that John Herbster is talking about is one of those bits, in Delphis TArithmeticException enum called exPrecision. Further he suggests to assure this bit is set by calling the Set8087CW(Default8087CW or $0020). Since you are using Delphi 10 Seattle, it is recommended to use the SetExceptionMask() function (from the System.Math unit) instead, since it handles equally also the corresponding SSE mask on 64 bit hw:
var
  OldExceptionMask: TArithmeticExceptionMask;
...
OldExceptionMask := SetExceptionMask(GetExceptionMask + [exPrecision]);

Calling the above before TFDTable(Compo).Open should solve your problem.
The function takes and returns a TArithmeticExceptionMask (set of TArithmeticException). All other exception enums and FPU/SSE related functions are in the documentation.


text:
Q: Natural phenomena with cubic behaviour I'd like to know which natural phenomena (in planet earth) may be described with a cubic function/polynomial? or is there not any.
Accelerated movement is quadratic. Work, is also quadratic. the movement of a spring is trigonometric. radioactive decay is exponatial, etc... which is cubic?
Or put in another way, please refresh me on which SI-Units contain a variable cubic power of the elementary units (m, kg, s, C, ...)

A: The first few that come to mind are...
Any volume density (of mass, energy, etc.) involves a length cubed.
Kepler's Third Law relates the square of the period of an orbit to the cube of its semimajor axis.
The low-frequency limit of Planck's Law for blackbody radiation is cubic in the frequency.
The evaporation time of a black hole due to Hawking radiation is proportional to the cube of its mass.


text:
Q: Strange include path in Eclipse CDT + GNU ARM After tinkering with some project settings, namely changing the FPU type, some strange entries appeared in the includes, eg.:

project/#undef __ARM_NEON

These are not shown at any of the usual places where includes can be specified (C/C++ build -> Settings -> tool settings -> compiler xy -> Includes.
This obviously invalid include path creates an annoying warning message at the "problems" tab.
Sometimes tinkering more with the FPU settings will make these entries disappear, or cause more similar entries to appear, but I could not see any logical behavior here. Is this a bug?
Screenshot

A: Please see: http://blog.bachi.net/?m=201409 for the solution.
workspace.metadata.pluginsorg.eclipse.cdt.coreROME2_P1_A2.language.settings.xml
Remove:
<entry kind="includePath" name="/${ProjName}/#undef __ARM_FP">
    <flag value="BUILTIN|READONLY|VALUE_WORKSPACE_PATH"/>
</entry>
<entry kind="includePath" name="/${ProjName}/#undef __ARM_FEATURE_FMA">
    <flag value="BUILTIN|READONLY|VALUE_WORKSPACE_PATH"/>
</entry>
<entry kind="includePath" name="/${ProjName}/#undef __ARM_NEON__">
    <flag value="BUILTIN|READONLY|VALUE_WORKSPACE_PATH"/>
</entry>
<entry kind="includePath" name="/${ProjName}/#undef __ARM_NEON">
    <flag value="BUILTIN|READONLY|VALUE_WORKSPACE_PATH"/>
</entry>

Add:
<language id="org.eclipse.cdt.core.g++">
    <entry kind="includePath" name="C:/Program Files (x86)/GNU Tools ARM Embedded/6 2017-q1-update/arm-none-eabi/include/c++/6.3.1">
        <flag value="BUILTIN|READONLY"/>
    </entry>
    <entry kind="includePath" name="C:/Program Files (x86)/GNU Tools ARM Embedded/6 2017-q1-update/arm-none-eabi/include/c++/6.3.1/arm-none-eabi/thumb/v8-m.main">
        <flag value="BUILTIN|READONLY"/>
    </entry>
    <entry kind="includePath" name="C:/Program Files (x86)/GNU Tools ARM Embedded/6 2017-q1-update/arm-none-eabi/include/c++/6.3.1/backward">
        <flag value="BUILTIN|READONLY"/>
    </entry>
    <entry kind="includePath" name="C:/Program Files (x86)/GNU Tools ARM Embedded/6 2017-q1-update/lib/gcc/arm-none-eabi/6.3.1/include">
        <flag value="BUILTIN|READONLY"/>
    </entry>
    <entry kind="includePath" name="C:/Program Files (x86)/GNU Tools ARM Embedded/6 2017-q1-update/lib/gcc/arm-none-eabi/6.3.1/include-fixed">
        <flag value="BUILTIN|READONLY"/>
    </entry>
    <entry kind="includePath" name="C:/Program Files (x86)/GNU Tools ARM Embedded/6 2017-q1-update/arm-none-eabi/include">
        <flag value="BUILTIN|READONLY"/>
    </entry>
</language>

A: Ok found it: workspace/.metadata/.plugins/org.eclipse.cdt.core/{NAME_OF_PROJECT}.language.settings.xml
but I prefer to delete it than touch and next time I open eclipse and build all went OK