text:
Q: Identify Clusters and group clusters in OpenCV I am using OpenCV to identify and deskew price tags from pictures.  I used Probabilistic Hough Transform function to identify the edges in the picture.  I am having trouble identifying the price tag quadlateral in the image.
I am attempting to group each edge/line by its slope and axis intercept.  Here is an example of the image and data.

In the image, shorter edges are drawn in red, edges of medium length are drawn in blue, and longer edges are drawn in green.  In the graph, the slope is plotted on the x-axis, intercept on the y-axis.  The left and right hand graphs are the same except the length of the line is represented by the area of the circle.
I am looking for a way to group these clutters and then determine average line represented by each cluster.  I hope to use the the groupings to identify the two most probable edges for both horizontal and vertical lines that bound the price tag.
Does anyone know an appropiate algorithm I could use to identify the groupings?
Thanks.

A: So after a bit of searching I decided to use the k-Means algorithm.  For anyone that may be curious, here are my results:
I ran the algorithm and split the lines into 9 clusters.  Although this is not exactly what I was looking for (I wanted to reject extreme outliers as opposed to forcing them in a cluster) the results are fine and will be manageable.
Here is a picture of the horizontal lines, extended and colored by cluster:

And here are the vertical lines:


text:
Q: NodeJS usb module issue on Linux I've just tried to install usb module for node via npm on Ubuntu (usb and then electron-usb) but it doesn't work because of the version (look at screenshot).
I've also installed sudo apt-get install build-essential libudev-dev and sudo apt-get install libudev-dev libusb-1.0-0-dev g++-multilib libudev-dev:i386 before module installation as written in the instructions.
How to make it work? Is there any other way to control usb ports with node?

A: I did some research and figured out that I can do the same with udev rules, so no usb module for node required. All you need to do is to listen bash commands from node as described in this post, so that you can add custom rule in rules.d/ folder and echo some data on any event and then make node listen to it. But this is a terrible way. 2017 and you can't just take control over usb ports with node out of the box, lol.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Undefined offset: 1 php google drive wp media WordPress plugin I'm using google drive WP media WordPress plugin for my WordPress site
but this plugin keep give this error on my nginx server, can someone can help me fix this code

[error] 4437#4437: *175114 FastCGI sent in stderr: "PHP message: PHP Notice:  Undefined offset: 1 in /var/www/myhost/htdocs/wp-content/uploads/gdwpm_images/index.php on line 4
PHP message: PHP Notice:  Undefined offset: 1 in /var/www/myhost/htdocs/wp-content/uploads/gdwpm_images/index.php on line 4
PHP message: PHP Notice:  Undefined offset: 1 in /var/www/myhost/htdocs/wp-content/uploads/gdwpm_images/index.php on line 4" while reading response header from upstream, client: 122.167.98.6, server: myhost, request: "GET /wp-content/uploads/gdwpm_images/0B73eY08zeFxawYUhGOTA.jpg HTTP/1.1", upstream: "fastcgi://127.0.0.1:9070", host: "myhost", referrer: "http://...

and here's the gdwpm_image/index.php code
<?php
if (isset($_GET['imgid'])){
    $gdwpm_ekst_gbr = explode('.', $_GET['imgid']);
    if($gdwpm_ekst_gbr[1] == 'png' || $gdwpm_ekst_gbr[1] == 'gif' || $gdwpm_ekst_gbr[1] == 'bmp'){
        header("Content-Type: image/" . $gdwpm_ekst_gbr[1]);
    }else{
        header("Content-Type: image/jpg");
    }
    $gdurl = "https://docs.google.com/uc?id=" . $gdwpm_ekst_gbr[0] . "&export=view";
    @readfile($gdurl);
}
?>

I tried to fix the code, but no changes.
Somebody can help to fix it?
Thanks!

A: After the following line...
$gdwpm_ekst_gbr = explode('.', $_GET['imgid']);

Check if $gdwpm_ekst_gbr has any array items before trying to access the [1] element.
The error message you posted occurs if the array item, at the index you are trying to access, is not present.


text:
Q: Refactor link to show/hide a table row I have a table with row which cab be hidden by user. It's implemented this way:
Markup:

                  Hide

                  Show

And jQuery code:

How to implement the same behavior with one, single link and one, probably, CSS class?
My idea - store somewhere a boolean variable and toggle controls visibility relatively to this variable. Are there more?

A: Use a toggle as mentioned in the above post but use a "tbody" instead of a "tr" so that rows can be hidden/shown as required.

A: Is the row hiding not working properly on IE? What is the version of jQuery and the browser which is troublesome?
I created an example using toggle as suggested by @Galen and it works on Chrome, Firefox, and Safari. I don't have access to IE.
Here's the code:
HTML

                  Hide

                  Show

        Some Data

Javascript
$(".toggle-stats").click(function() {
    $(".stats-hide, .stats-show").toggle();
});

A: You can use jquery's toggle to alternate between hiding and showing of objects with one link. You wont need to store any variables.


text:
Q: How to schedule a cronjob for a php file? I am working on Linux server and I have a group of php files each of them write to my database I write all the files directories in a bash file and I run this file manually using command line.
I want to make this automatically by using cronjob to run this file daily but I have two problems:
1.I should run the file 09:00GMT so I need to know what time does the cronjob work according to?Is it the server time? and if it is the server time how to know the server time region ?
2.how I could know the file directory exactly? I mean my file directory is: public_html/codes/myfile.sh
is it enough or I should write home/domainanem/.....
I am new on linux commands and cronjobs so please help me

A: *

*Times in crontabs are machine's local time. To get a GMT time in local's timezone, run: date -d '9:00 GMT'

*You need to include absolute paths in your crontab. Run readlink -f <relative_path_to_file>. this will output the (real) absolute path of the file.


text:
Q: How can I split text every 256 characters? I have some text and I want to add a paragraph or a page every 256 characters.
It would also be OK if I could limit the amount of characters for each line to 24 characters.
How can I achieve this?

A: Easiest tool for me is Notepad++ (Npp), with the TextFX plugin.

*

*Open the document or copy the text into a blank document.

*In any document, Npp or other, type 256, highlight it and copy it to clipboard with Ctrl-C.

*Open the TextFX menu, go to TextFX Edit and click on ReWrap text...


text:
Q: File upload Not Working with PHP So I have a form that allows a user to upload files. When they submit the file, I can get the file information such as name and tmp_name, yet the actually upload doesn't work. I don't get any PHP errors either. Below is my code, I think I just need another pair of eyes on it, as it was working a few days ago.
//Get the file name
$target_Dir = "temp/";

$tempName = $_FILES['file']['tmp_name'];

$target_file = $target_Dir . basename($_FILES["file"]["name"]);

$filename = pathinfo($target_file, PATHINFO_FILENAME);

//Get the password
$password = $_POST['password'];
//Store if the user wants the certificate to remain password protected
$passProtect = $_POST['passProtect'];
//upload the file to the server
move_uploaded_file($tempName, $target_file);

I need the file name without the extension for a later point in my code, in case you're wondering why I'm storing the file name without the extension.

A: I think you just did this mistake
$fileExtension = pathinfo($target_file, PATHINFO_FILENAME);

Try using this insted of that Code then only you will get the file name not the extention.

A: I had an unlink() further down in my script for some reason that I can't remember. It deleted the file that the user would upload right away.
Thanks for the extra set of eyes guys.


text:
Q: Mac brew arangodb delaying start log file path I have installed arangodb through brew. I am new to both mac and arangodb. Right after installation of arangodb I could start stop it through brew services. But since yesterday that didn't work. However arangod start worked. Today its taking really long time for the service to start up
$ arangod start
2018-04-30T07:40:32Z [3593] INFO ArangoDB 3.3.7 [darwin] 64bit, using jemalloc, build , VPack 0.1.30, RocksDB 5.6.0, ICU 58.1, V8 5.7.492.77, OpenSSL 1.0.2o  27 Mar 2018
2018-04-30T07:40:32Z [3593] INFO {authentication} Jwt secret not specified, generating...
2018-04-30T07:40:32Z [3593] INFO using storage engine mmfiles
2018-04-30T07:40:32Z [3593] INFO {cluster} Starting up with role SINGLE
2018-04-30T07:40:32Z [3593] INFO {syscall} file-descriptors (nofiles) hard limit is unlimited, soft limit is 8192
2018-04-30T07:40:32Z [3593] INFO {authentication} Authentication is turned on (system only), authentication for unix sockets is turned on
2018-04-30T07:40:32Z [3593] INFO running WAL recovery (1 logfiles)
2018-04-30T07:40:32Z [3593] INFO replaying WAL logfile '/Users/neel/start/journals/logfile-17009.db' (1 of 1)
2018-04-30T07:40:32Z [3593] INFO WAL recovery finished successfully
2018-04-30T07:40:33Z [3593] INFO using endpoint 'http+tcp://127.0.0.1:8529' for non-encrypted requests
2018-04-30T07:41:33Z [3593] WARNING {v8} giving up waiting for unused V8 context after 60.000000 s
2018-04-30T07:41:43Z [3593] WARNING {v8} giving up waiting for unused V8 context after 60.000000 s
2018-04-30T07:42:34Z [3593] WARNING {v8} giving up waiting for unused V8 context after 60.000000 s
2018-04-30T07:43:05Z [3593] INFO ArangoDB (version 3.3.7 [darwin]) is ready for business. Have fun!

I don't know where are the log files. So when I try to start with brew services start arangodb I can't check whether it has been started or not as it responds Successfully startedarangodb(label: homebrew.mxcl.arangodb) immediately. So my questions are why its delaying ? and where are the log files ?

A: The log files are located here: /usr/local/var/log/arangodb3
The delay above is caused by lack of available V8 contexts. You can adjust them by setting them in /usr/local/etc/arangodb3/arangod.conf. But the default value there is set to 0, which means that arangodb is to choose how many are running.


text:
Q: Database Schema For Task Reporting I have a task tracking application, which is very basic. It currently has a number of tasks and the progress is updated as the tasks get completed, from 0 to 100%.
The problem is, this data is all very transient and I want to add reporting over the top of the tasks, so things like:

*

*Number of tasks added between two dates

*Number of tasks completed between two dates

*Amount of effort (So this is the Total Effort against the task, divided by 100 and timesed by the change in percentage complete) between two dates

And so on.
How do you freeze data in time in order to allow this kind of reporting?
These are the ideas I've thought of so far:
Idea 1. Don't ever change the task definition, but add a "TaskProgress" table that contains the granular updates to progress for the task - you can then "sum them up" to get the current status or take the records between two dates to see how much progress was made between the two dates. The up-side is that this will survive a reasonable amount of change to the reporting requirements, the down-side is that getting the current progress of a task will require more query-effort.
Idea 2. Create a table to store progress changes. Each time a task is updated, also add a record that contains the calculated shift caused by the change. The reports are then just a case of selecting the records between the required dates and summing them up. The up side is that this won't greatly affect existing functionality and won't be too much query-effort, the down side is that you would have to change this table if it didn't contain information you wanted to add to a report.
Idea 3. Idea 3 would be to create the "TaskProgress" table from Idea 1, but still keep the totalled-up current progress against the task. It does mean that the sum of the task progress items is stored again as a total on the task itself, but it will be faster to read these values than calculate them and it gives more flexibility for changing reports later.
Any comments on these ideas, or better suggestions are very welcome.

A: I'm not sure I understand your ideas, but if the problem is being able to report on transient data then why not use a copy of the database? We always report on a copy normally for performance reasons, but it would solve your problem. Backup the database then restore it to another database, do your reporting, then drop the database.


text:
Q: Implementing Android Google Map Search functionality V2
I want to implement search for the country/state/city or nearby places in my android map Application, I know this question has already been asked here but thought to raise it once more as I'm still struggling to find any elegant solution here on SO.I've also referred to this post but after reading some comments I lost hope.So if anyone has implemented places api in android??

A: The straightforward way is to use the Google Geocoding API. You can access it with
https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA
That will return you a JSON with the location data for that address including latitude and longitude. Here's some code snippets from what I've done:
               try{
                    JSONConnectorGet jget=new JSONConnectorGet(url);
                    returnval=jget.connectClient();
                    results=returnval.getJSONArray("results");
                    resultobj=results.getJSONObject(0);
                    System.out.println(resultobj.toString());
                    geometry=resultobj.getJSONObject("geometry");
                    location=geometry.getJSONObject("location");

                    lati=location.getDouble("lat");
                    longi=location.getDouble("lng");

                }
                catch(Exception e){
                    e.printStackTrace();
                }

                a=new LatLng(lati, longi);

Here JSONConnectorGet is a class I wrote that can be used to send a HttpGet request and receive back a JSONObject. returnval is a JSONObject I've declared. url is the URL given above with address replaced with whatever is searched.
Then you have to extract the LatLng from the JSONObject. The JSONObjects and JSONArrays I've used are declared outside the try-catch block. Now I have the Latitude and Longitude of my search place in a.
Now I simply move the camera to that location.
eventmap.animateCamera(CameraUpdateFactory.newLatLngZoom(a, 3.0f));

You can add a marker at that LatLng as well if you want.


text:
Q: Force a value of 0 for non-existing value Group, I am going to try and explain this as best I can, and I hope it makes (some) sense.  I am pulling data from a view I have created that tells me a "Sponsor's" customer types and how many of those accounts by CustomerType are inactive after 1 year, 2 years and 3 years.  For example:
SponsorID | CustomerType | ExpiredAfter | Total
1234        D              1 Year         5
1234        RA             1 Year         7
1234        CA             1 Year         3
1234        D              2 Years        2
1234        RA             2 Years        4
1234        CA             2 Years        1
1234        D              3 Years        8
1234        RA             3 Years        1
1234        CA             3 Years        6

The problem I am having is a SponsorID might not have any RA that ExpiredAfter 1 year, so nothing shows up in the data.  So instead of getting:
SponsorID | CustomerType | ExpiredAfter | Total
1235        D              1 Year         5
1235        RA             1 Year         0
1235        CA             1 Year         3

I get:
SponsorID | CustomerType | ExpiredAfter | Total
1235        D              1 Year         5
1235        CA             1 Year         3

Again, not sure if any of this makes any sense, but what I want to do is include all customer types for all ExpiredAfter regardless if there are values or not.  If there isn't a value I just want to force a 0 or Null.  I need that data row with 0 for reporting purposes.
Any suggestions?

A: It sounds like you need to use a LEFT JOIN instead of an INNER JOIN.

A: You may also have to use ISNULL(total, 0) or COALESCE(total, 0) depending on which DBMS you are using, and your query (as stated by womp)... because if TOTAL is calculated, then having a null value from a LEFT JOIN would still leave you without a 0 value.

A: Seems to me like you are seeking positive reporting.  Try using a cross join. Cross joins link all rows from one table to all rows in the other table thereby giving all possible results as output


text:
Q: paintComponent() conditional and here's my problem:
Traffic is a JTextArea where I insert text coming from a serial port and I did Implement a DocumentListener:
Java Code:
 Traffic.getDocument (). AddDocumentListener (new MyDocumentListener ());

the JTextArea "Traffic" show me what I want and the programs runs  Without any problems.
Now what I want to do is to act upon what have been inserted (only on the event of insert) line by line (that's what the tests are for), I'll give an example:
==> When I recieve "ON-HOOK" I put an image in the JPanel of a phone on hook if I recieve "OFF-HOOK" I put an image in the JPanel of a phone off hook and the list goes ...
I did not undrestand how to do that, how to call paintComponent when i want and make it draw what I want since I can only do graphic operation in the paintComponent ().
And this is the class for the DocumentListener:
  protected class MyDocumentListener  extends JPanel implements javax.swing.event.DocumentListener
{
 @Override
   public void changedUpdate(javax.swing.event.DocumentEvent e) {
     // text has been altered in the textarea

     }

 @Override
  public void insertUpdate(javax.swing.event.DocumentEvent e)
  {
         // text has been added to the textarea
     try {

         if  (!Traffic.getText(Traffic.getLineStartOffset(Traffic.getLineCount()-1),Traffic.getLineEndOffset(Traffic.getLineCount()-1)-Traffic.getLineStartOffset(Traffic.getLineCount()-1)).contains(">>"))
         {

           if (Traffic.getLineCount()  == (lastreplace + 2) )
           {
               System.err.println(Traffic.getText(Traffic.getLineStartOffset(lastreplace),Traffic.getLineEndOffset(lastreplace) - Traffic.getLineStartOffset(lastreplace)));
            lastreplace +=1;

            }

          else
          {
            System.err.println(Traffic.getText(Traffic.getLineStartOffset(lastreplace),
                         Traffic.getLineEndOffset(lastreplace) -
                                 Traffic.getLineStartOffset(lastreplace)));
          }
       }
        Traffic.setCaretPosition(Traffic.getDocument().getLength());

     } catch (BadLocationException ex) {
         Logger.getLogger(TrafficSerialPort.class.getName()).log(Level.SEVERE, null, ex);
     }

 }

 @Override
 public void removeUpdate(javax.swing.event.DocumentEvent e) {
   // text has been removed from the textarea

 }

}

I tried to use a method called "PortArchitecture (..)" will draw what I want and I use getGraphics() but I was told that it should not be used paintComponent() and now I'm really stuck please help.

A: First of all, I wouldn't do that in a document listener. You already have some method which updates the JTextAea when a line is read from the serial port. I would change the displayed image in this same method:
private void lineReceivedFromSerialPort(String line) {
    traffic.append(line);
    updateImage(line);
}

And to change the image, I wouldn't use paintComponent() at all. Simply have a JLabel somwewhere in your panel, and when a line is received, load the appropriate image icon and set it to the label:
private void updatImage(String line) {
    ImageIcon iconToDisplay = null;
    if (line.equals("ON-HOOK")) {
        iconToDisplay = phoneOnIcon;
    }
    else if (line.equals("OF-HOOK")) {
        iconToDisplay = phoneOffIcon;
    }
    ...
    imageLabel.setIcon(iconToDisplay);
}


text:
Q: When I try to download PyAudio I just got this error message. This is so painful. Pls pleh C:\Users\lansz>pip install pyaudio
  Using cached PyAudio-0.2.11.tar.gz (37 kB)
Building wheels for collected packages: pyaudio
  Building wheel for pyaudio (setup.py) ... error
  ERROR: Command errored out with exit status 1:
   command: 'c:\users\lansz\appdata\local\programs\python\python39\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\lansz\\AppData\\Local\\Temp\\pip-install-ttc_7ppq\\pyaudio\\setup.py'"'"'; __file__='"'"'C:\\Users\\lansz\\AppData\\Local\\Temp\\pip-install-ttc_7ppq\\pyaudio\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\lansz\AppData\Local\Temp\pip-wheel-661td9fy'
       cwd: C:\Users\lansz\AppData\Local\Temp\pip-install-ttc_7ppq\pyaudio\
  Complete output (17 lines):
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib.win-amd64-3.9
  copying src\pyaudio.py -> build\lib.win-amd64-3.9
  running build_ext
  building '_portaudio' extension
  creating build\temp.win-amd64-3.9
  creating build\temp.win-amd64-3.9\Release
  creating build\temp.win-amd64-3.9\Release\src
  C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.16.27023\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -DMS_WIN64=1 -Ic:\users\lansz\appdata\local\programs\python\python39\include -Ic:\users\lansz\appdata\local\programs\python\python39\include -IC:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.16.27023\include -IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt -IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\shared -IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\um -IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\winrt -IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\cppwinrt /Tcsrc/_portaudiomodule.c /Fobuild\temp.win-amd64-3.9\Release\src/_portaudiomodule.obj
  _portaudiomodule.c
  c:\users\lansz\appdata\local\programs\python\python39\include\pyconfig.h(117): warning C4005: 'MS_WIN64': macro redefinition
  src/_portaudiomodule.c: note: see previous definition of 'MS_WIN64'
  src/_portaudiomodule.c(29): fatal error C1083: Cannot open include file: 'portaudio.h': No such file or directory
  error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\VC\\Tools\\MSVC\\14.16.27023\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2
  ----------------------------------------
  ERROR: Failed building wheel for pyaudio
  Running setup.py clean for pyaudio
Failed to build pyaudio
Installing collected packages: pyaudio
    Running setup.py install for pyaudio ... error
    ERROR: Command errored out with exit status 1:
     command: 'c:\users\lansz\appdata\local\programs\python\python39\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\lansz\\AppData\\Local\\Temp\\pip-install-ttc_7ppq\\pyaudio\\setup.py'"'"'; __file__='"'"'C:\\Users\\lansz\\AppData\\Local\\Temp\\pip-install-ttc_7ppq\\pyaudio\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\lansz\AppData\Local\Temp\pip-record-gaglivtc\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\lansz\appdata\local\programs\python\python39\Include\pyaudio'
         cwd: C:\Users\lansz\AppData\Local\Temp\pip-install-ttc_7ppq\pyaudio\
    Complete output (17 lines):
    running install
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.9
    copying src\pyaudio.py -> build\lib.win-amd64-3.9
    running build_ext
    building '_portaudio' extension
    creating build\temp.win-amd64-3.9
    creating build\temp.win-amd64-3.9\Release
    creating build\temp.win-amd64-3.9\Release\src
    C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.16.27023\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -DMS_WIN64=1 -Ic:\users\lansz\appdata\local\programs\python\python39\include -Ic:\users\lansz\appdata\local\programs\python\python39\include -IC:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.16.27023\include -IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt -IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\shared -IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\um -IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\winrt -IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\cppwinrt /Tcsrc/_portaudiomodule.c /Fobuild\temp.win-amd64-3.9\Release\src/_portaudiomodule.obj
    _portaudiomodule.c
    c:\users\lansz\appdata\local\programs\python\python39\include\pyconfig.h(117): warning C4005: 'MS_WIN64': macro redefinition
    src/_portaudiomodule.c: note: see previous definition of 'MS_WIN64'
    src/_portaudiomodule.c(29): fatal error C1083: Cannot open include file: 'portaudio.h': No such file or directory
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\VC\\Tools\\MSVC\\14.16.27023\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'c:\users\lansz\appdata\local\programs\python\python39\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\lansz\\AppData\\Local\\Temp\\pip-install-ttc_7ppq\\pyaudio\\setup.py'"'"'; __file__='"'"'C:\\Users\\lansz\\AppData\\Local\\Temp\\pip-install-ttc_7ppq\\pyaudio\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\lansz\AppData\Local\Temp\pip-record-gaglivtc\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\lansz\appdata\local\programs\python\python39\Include\pyaudio' Check the logs for full command output.
WARNING: You are using pip version 20.2.3; however, version 21.0.1 is available.
You should consider upgrading via the 'c:\users\lansz\appdata\local\programs\python\python39\python.exe -m pip install --upgrade pip' command.

============================================================
:c
I'm watching btw Tech With Tim's tutorial, the "Coronavirus Webscraper" video.
I don't know what to do with my life and I've been suffering with it for 5 hours.

A: This might help, since it is the same problem you are having:
pyAudio failed to install : Windows 10
Basically you are missing some components you need before download pyaudio, and those are included by pipwin before installing so you don't have to do it yourself.


text:
Q: IntelliJ: Add a Java SDK using JAVA_HOME variable On Windows the path of the JDK typically includes the version string. Therefore if you upgrade the JDK the path name changes. In IntelliJ this allyways means to manually update all locations where the JDK path is saved.
Therefore I want to add a SDK with an Java home path that use the JAVA_HOME variable as this is automatically set when installing an JDK and therefore would not require any updates later.

The main problem is that the Java home path text boy is not directly editable. One can only open a file/directory picker dialog that has an edit field but does not allow to use variables like $JAVA_HOME$ or %JAVA_HOME% (shows only an error message "Specified path can not be found").
How can I add an Java SDK using the JAVA_HOME environment variable that automatically updates whenever I upgrade the installed JDK?

A: You could always create a symbolic, or "soft" link pointing to whatever JDK you are using. Then you can set-up IntelliJ to use the symbolic link location and just update the symbolic link to point to whatever version of Java you are using.
So, for example in C:\Program Files\Java\ you could run the following:
mklink /D myJDK "C:\Program Files\Java\jdk1.8.0_112"

Then in IntelliJ you just add C:\Program Files\Java\myJDK as your SDK as this symbolic link is actually pointing to C:\Program Files\Java\jdk1.8.0_112
Windows does not support changing of the link (though there are some tools online which do), but the easiest would just be to delete the link and re-create it.
You could then also set-up your systems JAVA_HOME to point to this link as well.
Oh, when creating the symbolic link, you'll need to have administrative access.
The Complete Guide to Creating Symbolic Links (aka Symlinks) on Windows


text:
Q: TrigExpand for numerical multiples of angles After some calculations, Mathematica gives me a result which has in it a term Cos[2.x] (I cannot skip numerical computing, that's the reason for the 2. there). However, I want to expand this expression and only have something with only Cos[x], Sin[x] in it.
I try TrigExpand, but this results in  Cos[(2. + 0.i)x] instead of the expected Cos[x]^2 - Sin[x]^2.
Does anyone have any idea on how to work around this problem? I tried to substitute Cos[2θ] for Cos[2.θ] but that doesn't seem to work (I suspect Mathematica somehow interprets this as a new symbol).
Thanks a lot!

A: I'm skipping the part that tells you that you need to know what you are doing with your numerics. If you are sure your 2.0 is indeed a 2, you can use Rationalize to convert it
TrigExpand[Rationalize@Cos[2. x]]
(* Cos[x]^2 - Sin[x]^2 *)

This works in nested expressions as well
Sum[Cos[N[i] x], {i, 10}]
(* Cos[1. x] + Cos[2. x] + Cos[3. x] + Cos[4. x] + Cos[5. x] +
 Cos[6. x] + Cos[7. x] + Cos[8. x] + Cos[9. x] + Cos[10. x] *)

TrigExpand[Rationalize[%]]
(* Cos[x] + Cos[x]^2 + Cos[x]^3 + Cos[x]^4 + Cos[x]^5 +
 Cos[x]^6 + Cos[x]^7 + Cos[x]^8 + Cos[x]^9 + Cos[x]^10 - Sin[x]^2 -
 3 Cos[x] Sin[x]^2 - 6 Cos[x]^2 Sin[x]^2 - 10 Cos[x]^3 Sin[x]^2 -
 15 Cos[x]^4 Sin[x]^2 - 21 Cos[x]^5 Sin[x]^2 - 28 Cos[x]^6 Sin[x]^2 -
 36 Cos[x]^7 Sin[x]^2 - 45 Cos[x]^8 Sin[x]^2 + Sin[x]^4 +
 5 Cos[x] Sin[x]^4 + 15 Cos[x]^2 Sin[x]^4 + 35 Cos[x]^3 Sin[x]^4 +
 70 Cos[x]^4 Sin[x]^4 + 126 Cos[x]^5 Sin[x]^4 +
 210 Cos[x]^6 Sin[x]^4 - Sin[x]^6 - 7 Cos[x] Sin[x]^6 -
 28 Cos[x]^2 Sin[x]^6 - 84 Cos[x]^3 Sin[x]^6 - 210 Cos[x]^4 Sin[x]^6 +
  Sin[x]^8 + 9 Cos[x] Sin[x]^8 + 45 Cos[x]^2 Sin[x]^8 - Sin[x]^10 *)


text:
Q: How to derive the Aharonov-Bohm effect result? In the derivations of the Aharonov-Bohm phase, it is directly mentioned that due to the introduction of the vector potential $A$, an extra phase is introduced into the wavefunction for case $A\neq0$ i.e.
$$ \psi(A\neq0) = \exp(\iota\varphi)\psi(A=0),$$
where
$$    \varphi = \frac{q}{\hbar} \int_P \mathbf{A} \cdot d\mathbf{x}. $$
How to derive it from the following Schordinger equation $$ \left[\frac{1}{2m}(\frac{\hbar}{i}\triangledown-eA)^{2}+V(r)\right]\psi=\epsilon\psi. $$
I tried taking the terms containing $A$ on the right and treating the equation as an inhomogeneous equation but it just becomes tedious. What is the straightforward simple way?

A: First, I will set $e=1$ for simplicity.
Let $\psi_0$ denote the wave function that satisfies the free Schrodinger equation:
\begin{equation}
i \frac{\partial \psi_0}{\partial t} = -\frac{1}{2m}\mathbf{\nabla}^2 \psi_0 + V \psi_0 \tag{1}
\end{equation}
Furthermore, let $\psi$ be the wave function that obeys the Schrodinger equation for a non-vanishing vector potential $\mathbf{A}$:
\begin{equation}
i \frac{\partial \psi}{\partial t} = -\frac{1}{2m}(\mathbf{\nabla}-i\mathbf{A})^2 \psi+ V \psi \tag{2}
\end{equation}
Let us now write:
\begin{equation}
\psi=\exp \left( i \int_{\gamma} \mathbf{A} \cdot \mathrm{d} \mathbf{l} \right)\psi_0
\end{equation}
where $\gamma$ is a path from some arbitrary point $\mathbf{x}_0$ to some other point $\mathbf{x}_1$. We can then write:
\begin{equation}
\left( \mathbf{\nabla} -i \mathbf{A} \right)^2 \psi = \exp \left( i \int_{\gamma} \mathbf{A} \cdot \mathrm{d} \mathbf{l} \right)  \mathbf{\nabla}^2 \psi_0
\end{equation}
Substituting this expression into equation $(2)$ gives equation $(1)$. This implies that the wave function of an electrically charged particle travelling through space where $\mathbf{A} \neq 0$ will gain an additional phase.
We know that the wave function at the point $Q$ (see the figure below) is a result of quantum superposition, i.e. we can write:
\begin{equation}
\begin{aligned}
\begin{split}
\psi_{\scriptscriptstyle Q} & = \psi(\mathbf{x},\gamma_1) + \psi(\mathbf{x},\gamma_2) \\&
= \exp \left( i \int_{\gamma_1} \mathbf{A} \cdot \mathrm{d} \mathbf{l} \right)\psi_{0}(\mathbf{x},\gamma_1) + \exp \left( i \int_{\gamma_2} \mathbf{A} \cdot \mathrm{d} \mathbf{l} \right)\psi_{0}(\mathbf{x},\gamma_2) \\&
= \exp \left( i \int_{\gamma_2} \mathbf{A} \cdot \mathrm{d} \mathbf{l} \right) \left( \exp \left( i \int_{\gamma_1} \mathbf{A} \cdot \mathrm{d} \mathbf{l} - i \int_{\gamma_2} \mathbf{A} \cdot \mathrm{d} \mathbf{l} \right)\psi_{0}(\mathbf{x},\gamma_1) + \psi_{0}(\mathbf{x},\gamma_2) \right)
\end{split}
\end{aligned}
\end{equation}
We can use Stoke's theorem on the first term inside the brackets, because $\gamma_1-\gamma_2$ is a closed path:
\begin{equation}
\int_{\gamma_1} \mathbf{A} \cdot \mathrm{d} \mathbf{l} - \int_{\gamma_2} \mathbf{A} \cdot \mathrm{d} \mathbf{l} = \int \mathbf{B} \cdot \mathrm{d}\mathbf{S} = F
\end{equation}
where $F$ is the total magnetic flux due to the solenoid through a surface defined by the closed boundary $\gamma_2-\gamma_1$. The wave function at $Q$ can now be written as:
\begin{equation}
\psi_{\scriptscriptstyle Q}  = \exp \left( i \int_{\gamma_2} \mathbf{A} \cdot \mathrm{d} \mathbf{l} \right) \left( \exp \left( i F \right)\psi_{0}(\mathbf{x},\gamma_1) + \psi_{0}(\mathbf{x},\gamma_2) \right)
\end{equation}
This shows that the relative phase difference, and thus the interference pattern, is dependent on the magnetic flux due to the solenoid. This is the Aharonov-Bohm effect.

A: To simplify the problem, we may neglect the potential energy term $V(r)$, as it is simply irrelevant to our derivation. So we write the Hamiltonian as
$$H=\frac{1}{2}(-i\partial_x-A)^2.$$
The ground state is given by minimization of the energy. As the Hamiltonian is a square of $(-i\partial_x-A)$, so it is minimized when $(-i\partial_x-A)=0$. Which means on the ground state, we roughly have
$$(-i\partial_x-A)\psi=0.$$
If we only care about the phase configuration of the wave function, we may write $\psi\sim e^{i\phi}$, and substitute into the above equation,
$$(\partial_x\phi -A)e^{i\phi}=0,$$
which means $\partial_x\phi=A$, and its solution is $\phi=\int A \cdot\mathrm{d}x$.


text:
Q: Jquery .data keeps going undefined on draggable element in droppable area I been struggling with this all morning and I can't seem to figure out what the issue is.  On my page I have a draggable text field.  (It has a static ID for testing purposes when you first drag it to the canvas as "item-text-1")
When I first drag the item down in the console log you can clearly see a "1" being outputed from the $("#item-text-1").data("test")  however as you continue to drag it around a few times, it will start to go to "undefined" for some reason and I have absolutely no idea how to fix this.  I tried doing ui.helper.detached() then also removed that all together and I'm just lost at this point.

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />

Data Fields

Text Field

A: Ok, so here's why the current implementation is not working:
You have two droppable areas:
$(".pages").droppable({
...
and
$(".pagesWrapper").droppable({

*

*When you drag the element the first time, a clone is created by jquery ui and dropped into the page container. Let's say clone "no-id". Then in the page droppable, the "no-id" is again cloned by this
cloned = ui.helper.clone();
...
cloned.attr("id", "item-text-1");
Now you have on the dom two elements "no-id" and "item-text-1".
When you assign the data to the element by id "item-text-1" this data will be assigned to the single element with that id.
After this handler finishes, you have the second droppable handler, that will also perform his logic upon the "no-id" element and remove it from the dom.
ui.helper.remove();
Now you have only one clone remaining : "item-text-1".

*When you drag the remaining clone the second time you will create another clone because of the page droppable handler, and you will have two elements with the id "item-text-1".

When you display now the data in the "item-text-1" element, because byId will return the first occurrence, you will see the data set before, in the first drag. The second element has no data attached to it.
When the pagesWrapper droppable will be invoked, then first element with the id "item-text-1" will be removed, and you will only have the last element available in the dom, that does not have the data anymore.
And from here on the data is lost.
In order to preserve the data, you will need to assign it to the new object after you clone the source object:
cloned = ui.helper.clone();
cloned.data('test', ui.helper.data('test'));

In this way you will always have the data with you, but be aware that your text control is always a new one, not the original clone.


text:
Q: MySql PRIMARY KEY other than an int Im bulding a site that pulls links from twitter and counts the results from it. Ive been thinking about using the actual URL as the PRIMARY KEY instead of using an auto_increment integer. The url's being pulled will be unique and related to trend tracking. Is this a bad idea and should i stick with an integer?

A: As long as you can guarantee that they are unique you can definitely use the URL as the key.

A: Using URLs would not be an issue as controlfreak123 said. But if there is an performance vertical then you should stick to auto_increment int PK. cause comparision of EQUAL and like is different. Datatype and its processing differs.


text:
Q: Testing a RESTful API with POSTs from Python I'm trying to test a RESTful interface I'm working on (I'm using this one: codeigniter-restserver), and I'd like to use Python.
GETs seem to be working okay, but I'm having trouble with POSTs. I'm not asking about the ins & outs of this library, rather I'm just trying
to figure out how to test POSTing with Python. This is what I've got:
import httplib, urllib

params = urllib.urlencode({
    'sentence':     'esta es una frase',
    'translation':  'this is a sentence'
})

headers = {
    "Content-type": "application/x-www-form-urlencoded",
    "Accept":       "text/plain"
}

conn = httplib.HTTPConnection("localhost:80")
conn.request("POST", "/myapp/phrase", params, headers)

response = conn.getresponse()
print response.status, response.reason

data = response.read()
conn.close()

Is this script sufficient as a way to test POSTing? I've seen a lot of requests on SO about people looking for GUI tools to do this (Firefox plugins, etc)
but for me the whole point of building a RESTful app in the first place is to have an API I can script to to modify the db quickly. (Populate it with data
from a JSON file, whatever.)
Am I on the right track with this Python-based approach?
Thanks

A: writing directly to httplib is fine, but rather low level.
check out the Requests module.  It is a very simple and pythonic approach to crafting and sending http requests.
import requests

requests.post(url, data={}, headers={}, files={}, cookies=None, auth=None)

A: POST is usually done via higher level function urllib2.
headers = {'User-Agent': user_agent}

data = urllib.urlencode(values)
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)

A: There's also Nap which is just a wrapper for requests but makes it convenient to call e.g. HTTP APIs.
Example usage:
from nap.url import Url
api = Url('http://httpbin.org/')

response = api.post('post', data={'test': 'Test POST'})
print(response.json())

More examples: https://github.com/kimmobrunfeldt/nap#examples
Disclaimer: I wrote nap.


text:
Q: What is the difference between "git checkout" vs. "git restore" for reverting uncommitted file changes? Say I have a git repo with a modified file named readme.txt, and I want to undo the modifications I've made and set it back to the state of the most recent commit. It seems there are two commands to do this:
git checkout -- readme.txt

and
git restore readme.txt

Is there any difference between these two commands? I've noticed that git status offers the advice "(use "git restore <file>..." to discard changes in working directory)". Is this the canonical way to undo uncommitted modifications? Are both ways equally valid and popular?

A: I like the two answers on this at the time I write mine—both axiac's answer and kapsiR's, but the way I would put it is this:

*

*git checkout combines too many commands into one front end.  Some of these commands are "safe", in that if you have uncommitted work, they won't destroy it, and some of these are "unsafe", in that if you have uncommitted work and tell them destroy my uncommitted work, they will do that.

*git switch implements the "safe" subset.

*git restore implements the "unsafe" subset.
So far, there's no particular reason to favor either the old single command or the new pair of commands.  But we add one more item:

*

*git checkout name may execute either the unsafe one or the safe one, depending on something you might not even be thinking about!

Now, this last bullet point is fixed in the latest Git versions.  Suppose you have a remote-tracking origin/dev name and you'd like to create branch dev accordingly.  Normally, you could just run:
git checkout dev

Suppose, though, that your current (probably master) checkout has a directory named dev, and in that directory, you've done a bunch of work and have not yet committed it.  You just now remembered: I should commit all this work I just did on the dev branch, not the master branch.
Now, there's no existing dev branch at all, but there are dev/ files.  Here's what an old Git does:
sh-3.2$ git --version
git version 2.20.1
sh-3.2$ git branch -r
  origin/dev

(that is, origin/dev exists; branch dev doesn't and I'm on master here)
sh-3.2$ git status --short
 M dev/file
sh-3.2$ git diff
diff --git a/dev/file b/dev/file
index e69de29..c238a0b 100644
--- a/dev/file
+++ b/dev/file
@@ -0,0 +1 @@
+look at all this work I did

Adding that line took weeks of hard work! :-)
sh-3.2$ git checkout dev

Uh oh.  Why didn't it tell me about creating a branch named dev set up to track origin/dev?
sh-3.2$ git status
On branch master
nothing to commit, working tree clean

Gah!  My hard work is all gone!
The problem here is that git checkout ran the unsafe command.  I might have been expecting it to use the safe one ... but it didn't.
A more modern Git (2.24.0) will tell me that git checkout dev is ambiguous, which is good: it does not just clobber my file.  (I have not tested Git 2.23 itself, where the split-into-two-commands first went in.)
Anyway, using the new commands, you at least know, right as you type in the command, whether you will get the safe mode or the unsafe one.  If your habits are set and you keep using git checkout, or you're concerned about the note that says that these new commands are still experimental, you can still use the old one—and it no longer just wipes out work, in the ambiguous case.

A: As stated in the docs:

or you can restore both the index and the working tree (this the same as using git-checkout1)

It's a convenient way of doing the same thing. (first version in Git 2.23)
Blog post from GitHub about highlights of Git 2.23:

Git 2.23 brings a new pair of experimental commands to the suite of existing ones: git switch and git restore. These two are meant to eventually provide a better interface for the well-known git checkout. The new commands intend to each have a clear separation, neatly divvying up what the many responsibilities of git checkout, as we'll show below.

A: git restore is command introduced in Git 2.23 (August 2019) together with git switch. Their purposes are to simplify and separate the use cases of git checkout that does too many things.
git checkout can be used to switch branches (and also to create a new branch before switching to it). This functionality has been extracted into git switch.
git checkout can also be used to restore files to the state they were on a specified commit. This functionality has been extracted into git restore.
They can still be performed by git checkout but the new commands are easier to use and less confusing.
To summarize,
git restore readme.txt

is a new way to do what you used to do with:
git checkout -- readme.txt


text:
Q: What does the "verbosity" parameter of a random forest mean? (sklearn) One of the kwargs for building a random forest in sklearn is "verbose". The documentation says that it
Controls the verbosity of the tree building process

After searching online I am still not sure what this means.

A: Verbosity in keyword arguments usually means showing more 'wordy' information for the task.
In this case, for machine learning, by setting verbose to a higher number (2 vs 1), you may see more information about the tree building process.
Seeing the verbosity settings for another machine learning application may help to understand the principle.

A: In case of verbose=1 you get only the red logs (pretty rare in big models) with elapsed time, but changing verbose to 2 prints you the rest of information about building each tree:


text:
Q: I cant seem to return the result of inside the function I have created a basic rock paper scissors game and i cannot return the result inside the function.
I've been try everything
link console logging the compare and also putting it inside a variable..
console.log(compare) returns undefined for some reason.
Please help

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
var result;

if (computerChoice < 0.34) {
 computerChoice = "rock";
} else if(computerChoice <= 0.67) {
 computerChoice = "paper";
} else {
 computerChoice = "scissors";
} console.log("Computer's choice: " + computerChoice);
  console.log("Your choice: " + userChoice);
  console.log(computerChoice + " vs " + userChoice);

var compare = function(userChoice, computerChoice){
    if (userChoice === computerChoice){
        return    "The result is a tie!";
    } else if (userChoice ==="rock"){
       if(computerChoice ==="scissors"){
        return "rock wins!";
       }
       else {
         return "paper wins!";
       }
    } else if (userChoice === "paper") {
        if(computerChoice === "rock") {
        return "paper wins!";
        }
        else {
        return "scissors wins!";
        }
    } else if (userChoice === "scissors") {
        if(computerChoice === "rock") {
        return "rock wins!";
        }
        else {
        return "scissors wins!";
        }
    }

}

A:

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
var result;

if (computerChoice < 0.34) {
 computerChoice = "rock";
} else if(computerChoice <= 0.67) {
 computerChoice = "paper";
} else {
 computerChoice = "scissors";
} console.log("Computer's choice: " + computerChoice);
  console.log("Your choice: " + userChoice);
  console.log(computerChoice + " vs " + userChoice);

function compare(userChoice, computerChoice){
    if (userChoice === computerChoice){
        return    "The result is a tie!";
    } else if (userChoice ==="rock"){
       if(computerChoice ==="scissors"){
        return "rock wins!";
       }
       else {
         return "paper wins!";
       }
    } else if (userChoice === "paper") {
        if(computerChoice === "rock") {
        return "paper wins!";
        }
        else {
        return "scissors wins!";
        }
    } else if (userChoice === "scissors") {
        if(computerChoice === "rock") {
        return "rock wins!";
        }
        else {
        return "scissors wins!";
        }
    }

}
var Compare = compare(userChoice, computerChoice);
console.log(Compare);

A: You have syntax error here...
return  =  "The result is a tie!";

change this to:
return "The result is a tie!";

A: As Shinra tensei mentioned you had a = in line 18 that caused an error.
Here is a updated snipped. I also added an alert for the compare function.

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
var result;

if (computerChoice < 0.34) {
 computerChoice = "rock";
} else if(computerChoice <= 0.67) {
 computerChoice = "paper";
} else {
 computerChoice = "scissors";
} console.log("Computer's choice: " + computerChoice);
  console.log("Your choice: " + userChoice);
  console.log(computerChoice + " vs " + userChoice);

  alert(compare(userChoice,computerChoice));

 function compare (userChoice, computerChoice){
    if (userChoice === computerChoice){
        return  "The result is a tie!";
    } else if (userChoice ==="rock"){
       if(computerChoice ==="scissors"){
        return "rock wins!";
       }
       else {
         return "paper wins!";
       }
    } else if (userChoice === "paper") {
        if(computerChoice === "rock") {
        return "paper wins!";
        }
        else {
        return "scissors wins!";
        }
    } else if (userChoice === "scissors") {
        if(computerChoice === "rock") {
        return "rock wins!";
        }
        else {
        return "scissors wins!";
        }
    }

}

A: The main problem here is that you never executed the anonymous function you wrote. I made compare a normal function instead of an anonymous one, just to make it more similar to other languages. This is a good working code:
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
var result;

if (computerChoice < 0.34) {
    computerChoice = "rock";
} else if(computerChoice <= 0.67) {
    computerChoice = "paper";
} else {
    computerChoice = "scissors";
} console.log("Computer's choice: " + computerChoice);
  console.log("Your choice: " + userChoice);
  console.log(computerChoice + " vs " + userChoice);

function compare(userChoice, computerChoice){
    if (userChoice === computerChoice){
        return    "The result is a tie!";
    } else if (userChoice ==="rock"){
       if(computerChoice ==="scissors"){
        return "rock wins!";
       }
       else {
         return "paper wins!";
       }
    } else if (userChoice === "paper") {
        if(computerChoice === "rock") {
        return "paper wins!";
        }
        else {
        return "scissors wins!";
        }
    } else if (userChoice === "scissors") {
        if(computerChoice === "rock") {
        return "rock wins!";
        }
        else {
        return "scissors wins!";
        }
    }

}
console.log(compare(userChoice, computerChoice));


text:
Q: I need to add a space and newline in my code I am working on a homework problem and at the end it says "Note: 95 is followed by a space, then a newline".
Sample output for the given program with input: '90 92 94 95'
90 -> 92 -> 94 -> 95
Note: 95 is followed by a space, then a newline.
MY CODE:
user_input = input()
hourly_temperature = user_input.split()

for item in hourly_temperature:
    if item != hourly_temperature[len(hourly_temperature)-1]:
           print(item, end = " -> ")

I cannot figure out how to add the space and newline. I have tried numerous changes.

A: i'm not sure I understand the question. what is 95 referring to?
in python to print a new line print '\n' and it will print a new line, to print a space use a literal space
>>> print("This ends with a space then a newline \n")
This ends with a space then a newline

>>> print("This will show up \nas two lines")
This will show up
as two lines
>>>

A: Find the latest data in the array and print a new line if found :
if item == item[-1]:
  print("\n")
  print(item, end = " -> ")
else:
  print(item, end = " -> ")

A: I think you have a couple of issues, starting with your input:
>>> user_input = input()
90 92 94 95
>>> user_input
'90 92 94 95'
>>> user_input.split()
['90', '92', '94', '95']

This does not actually contain a newline character, but even if it is, you can quickly remove it like so:
hourly_temperature = user_input.split()[:-1]

Finally, it's probably easiest if you use join to print:
print(" -> ".join(hourly_temperature))

join() is a method on all strings that takes an array that says "Glue each item in this array together using the original string." So a quick way to glue together numbers with commas is: ", ".join([1,2,3]).
It may be that your instructions were saying you needed to include a space and newline at the end - it's unclear, but a input() call will not, on it's own, include this.
Another way to do this, if you need to add something to the end is to use f-strings:
printable_output = "{} \n".format(" -> ".join(hourly_temperature))
print(printable_output)

This results in:
>>> user_input = input()
90 92 94 95
>>> hourly_temperature = user_input.split()[:-1]
>>> printable_output = "{} \n".format(" -> ".join(hourly_temperature))
>>> print(printable_output)
90 -> 92 -> 94

>>>

(Note the last element is dropped because I'm dropping the last element on the line I split user_input. I don't think it's necessary to do that - and if not just remove the [:-1].)


text:
Q: load style css in codeigniter framework
Possible Duplicate:
CodeIgniter - Loading CSS

I try load css file and it's not work.
this is the link tag:
<link rel="stylesheet" type="text/css" href="application/styles/style.css" />

how i can do this?

A: Make a folder outside the application folder Eg: resources/css/style.css and link it like below.
Then the folder structure will be like this,
-application
-resources
-system
-index.php

<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>resources/css/styles/style.css" />


text:
Q: Iterative selection of features and export to shapefile using PyQGIS I'm working with QGIS 3.10 A Coruña on MacOS 10.13 environment.
I have a vector polygon layer and I need to select features with a given attribute value and export them as a new shapefile. I'm a newbie in these matters and haven't get any further than
layer = qgis.utils.iface.mapCanvas().currentLayer()
request = QgsFeatureRequest(QgsExpression("CODNUT2 = 'ES24'"))
features = layer.getFeatures(request)

*

*What should be the next steps to generate the shapefile with those selected features?

*How to make it an iterative process to generate new shapefiles for every value in the CODNUT2 attribute?

A: You can use the following script. Just change folder.
layer = qgis.utils.iface.mapCanvas().currentLayer()

field_name = "CODNUT2"
idx = layer.fields().indexOf(field_name)
unique_values = layer.uniqueValues(idx)

folder = "/path/to/folder"

for value in unique_values:
    file_path = f"{folder}/_{value}.shp"
    layer.selectByExpression(f"{field_name}='{value}'")

    QgsVectorFileWriter.writeAsVectorFormat(layer,
                                            file_path,
                                            'utf-8',
                                            layer.crs(),
                                            "ESRI Shapefile",
                                            onlySelected=True
                                            )

A: I would use two processing tools to achieve your problem: qgis:listuniquevalues to get the unique values and native:saveselectedfeatures to save the selected feature.
layer = iface.activeLayer()

# Find the unique values for the given field
res1 = processing.run("qgis:listuniquevalues",
                      {'INPUT': layer,
                       'FIELDS': ['CODNUT2'],
                       'OUTPUT': 'TEMPORARY_OUTPUT',
                       'OUTPUT_HTML_FILE': 'TEMPORARY_OUTPUT'})
distinct_value = res1['OUTPUT']

# Loop trough the unique values
for feat in distinct_value.getFeatures():
    attr_value = feat['CODNUT2']  # distinct value

    # Select the objects with the unique value
    layer.selectByExpression(f"CODNUT2='{attr_value}'")

    # Exported selected objects to shp
    processing.run("native:saveselectedfeatures",
                   {'INPUT': layer,
                    'OUTPUT': f'C:/Users/ncipa/Downloads/test_selectedtest_{attr_value}.shp'})

A: There is a better approach for what you want to do with processing and the native splitvectorlayer algorithm.
Just do :
import processing
params = {'INPUT':iface.activeLayer(),
'FIELD':'CODNUT2',
'FILE_TYPE':0,
'OUTPUT':'/path/to/folder'}
processing.run("native:splitvectorlayer", params)

Put 'FILE_TYPE':1 if you want shpfile
To get the help :
processing.algorithmHelp('native:splitvectorlayer') #in the console

A: You can use following code for obtaining a memory layer with your request:
qgis.utils.iface.mapCanvas().currentLayer()

request = QgsFeatureRequest().setFilterExpression (u"CODNUT2 = 'ES24'")

selected_feats = layer.getFeatures(request)

attr = [ feat.attributes() for feat in selected_feats ]
idx = [ ele[0] for ele in attr ]
val_req = [ ele[1] for ele in attr ]

iterator = layer.getFeatures(request)

feats = [ feat for feat in iterator ]

epsg = layer.crs().postgisSrid()

uri = "Polygon?crs=epsg:" + str(epsg) + "&field=id:integer""&field=CODNUT2:string""&index=yes"

mem_layer = QgsVectorLayer(uri,
                           'mem_layer',
                           'memory')

prov = mem_layer.dataProvider()

for i, feat in enumerate(feats):
    feat.setAttributes([idx[i], val_req[i]])
    mem_layer.addFeature(feat)

prov.addFeatures(feats)

QgsProject.instance().addMapLayer(mem_layer)

For testing it, I created 'CODNUT2' field in one shapefile and arbitrarily put in it some 'ES24' values and other different.
After running above code, result was as expected. Memory layer has features with desired request and corresponding ids.


text:
Q: Android print to network printer I want to include feature in my android app to print image from network printer through WiFi. I tried below code, posted on stackoverflow, but I am only able to print text :( What to do if I want to print images.
try
{
    Socket sock = new Socket("192.168.1.222", 9100);
    PrintWriter oStream = new PrintWriter(sock.getOutputStream());
        oStream.println("HI,test from Android Device");
        oStream.println("\n\n\n");
        oStream.close();
        sock.close();
    }
    catch (UnknownHostException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}


text:
Q: Meaning of the word "else"
"If anyone tells you that a certain person speaks ill of you, do not
  make excuses about what is said of you but answer, 'He was ignorant of
  my other faults, else he would have not mentioned these alone.'" –
  Epictetus

What does the word "else" mean? I think it means "otherwise". Is it correct?

A: Else used as shown is a conjunction, meaning 'otherwise'. It is common in, but not exclusive to, British English. Examples:

*

*We must repair the walls, else the roof will collapse.

*Hurry, else you will be late.

A: The phrasing is old fashioned, probably because you are reading a translation that was made in the ninteenth or early twentieth century. A modern writer of American English would likely write the two words or else instead of the one word else. Otherwise would be a good substitute, but again or otherwise would likely be more common.
One of the defects of the English lexicon is that there is no universally accepted way to distinguish between what mathematicians call the inclusive or and the exclusive or. The phrase A or B means A alone or B alone or both A and B: or alone is lexically inclusive (although logic may indicate that the meaning is exclusive). It is equivalent to the Latin vel. Latin had the form aut A aut B to mark the exclusive or: A or B but not both.
A else B is one old fashioned way to form an exclusive or. I prefer either A or else B, but the only way to be sure that every English speaker will grasp that you mean an exclusive or is to exclude the possibility of both A and B explicitly. The usage of else in your example to mean an exclusive or unfortunately did not catch on.


text:
Q: How to pass data into a component from a json file automatically? I'm trying to build a react website blog. I have a JSON file that has all my posts in. I want to pass the data to my blogSelction component. The goal is to have different cards and in each card have the data from the JSON. There will be a different blog post in a different div. I would like it so when I add to the JSON file it automatically makes a card post that you can click on.
I was just wondering what is the best way to go about making the code for it, I am a complete newbie so it might be really simple I'm just uneducated in the topic.
How I have tried to do it is useState and useEffect for the computer to know the directory; using it so the code knows where to look. After its in-state, I use the map call and try it get the posts but it doesn't seem to work.
import React, { useEffect, useState } from "react";
import "./style.css";
import { NavLink } from "react-router-dom";
import Card from "../../Card";
import blogPost from "../../../data/blog.json";

const BlogCards = (props) => {
  const [post, setpost] = useState([]);
  const [blogs, setblogs] = useState([
    {
      id: "",
      blogCategory: "",
      blogTitle: "",
      postedOn: "",
      author: "",
      blogImage: "",
      blogText: "",
      blogText2: "",
      blogText3: "",
      blogText4: "",
    },
  ]);

  useEffect(() => {
    const blogs = blogPost.data;
    setblogs(blogs);
  }, [blogs]);

  if (blogs.blogImage == "") return null;

  return (

        <Card>
          {blogs.map((blog) => {
            return (
              <NavLink key={blog.id} className="Link" to={`/post/${post.id}`}>

{blog.blogTitle}

{blog.blogText}

                  Posted on {blog.postedOn}

              </NavLink>
            );
          })}
        </Card>

  );
};

export default BlogCards;

{
    "data" : [
        {
            "id": 1,
            "blogCategory": "",
            "blogTitle" : ".",
            "postedOn" : "06/08/2020",
            "author": "Robert Lawson ",
            "blogImage" : "",
            "blogText" : "",
            "blogText2" : "",
            "blogText3" : "",
            "blogText4" : ""
        },
 {
            "id": 2,
            "blogCategory": "",
            "blogTitle" : ".",
            "postedOn" : "06/08/2020",
            "author": "Robert Lawson ",
            "blogImage" : "",
            "blogText" : "",
            "blogText2" : "",
            "blogText3" : "",
            "blogText4" : ""
        },
 {
            "id": 3,
            "blogCategory": "",
            "blogTitle" : ".",
            "postedOn" : "06/08/2020",
            "author": "Robert Lawson ",
            "blogImage" : "",
            "blogText" : "",
            "blogText2" : "",
            "blogText3" : "",
            "blogText4" : ""
        },
 {
            "id": 4,
            "blogCategory": "",
            "blogTitle" : ".",
            "postedOn" : "06/08/2020",
            "author": "Robert Lawson ",
            "blogImage" : "",
            "blogText" : "",
            "blogText2" : "",
            "blogText3" : "",
            "blogText4" : ""
        },
 {
            "id": 5,
            "blogCategory": "",
            "blogTitle" : ".",
            "postedOn" : "06/08/2020",
            "author": "Robert Lawson ",
            "blogImage" : "",
            "blogText" : "",
            "blogText2" : "",
            "blogText3" : "",
            "blogText4" : ""
        },
 {
            "id": 6,
            "blogCategory": "",
            "blogTitle" : ".",
            "postedOn" : "06/08/2020",
            "author": "Robert Lawson ",
            "blogImage" : "",
            "blogText" : "",
            "blogText2" : "",
            "blogText3" : "",
            "blogText4" : ""
        }
    ]
}

I've taken all the data out of the JSON because of the volume of writing.
---Not code related ---
While I'm posting on here I would also like to learn how to be more articulate in the programming field so I can express my self better posting on stack overflow + speaking to developers if you have any tips or advice it would be much appreciated.


text:
Q: Combining regular expressions in Javascript Is it possible to combine regular expressions in javascript.
For ex:
 var lower = /[a-z]/;
 var upper = /[A-Z]/;
 var alpha = upper|lower;//Is this possible?

ie. can i assign regular expressions to variables and combine those variables using pattern matching characters as
 we do in regular expressions

A: The answer is yes! You have to initialize the variable under the RegExp class:
var lower = new RegExp(/--RegexCode--/);
var upper = new RegExp(/--RegexCode--/);

hence, regex can be dynamically created. After creation:
"sampleString".replace(/--whatever it should do--/);

Then you can combine them normally, yes.
var finalRe = new RegExp(lower.source + "|" + upper.source);

A: If this is something you only need to do once or twice, I'd stick with doing it on a per-case basis as suggested by other answers.
If you need to do a lot, however, a couple of helper functions might improve readability. For example:
var lower = /[a-z]/,
    upper = /[A-Z]/,
    digit = /[0-9]/;

// All of these are equivalent, and will evaluate to /(?:a-z)|(?:A-Z)|(?:0-9)/
var anum1 = RegExp.any(lower, upper, digit),
    anum2 = lower.or(upper).or(digit),
    anum3 = lower.or(upper, digit);

And here's the code if you want to use those functions:
RegExp.any = function() {
    var components = [],
        arg;

    for (var i = 0; i < arguments.length; i++) {
        arg = arguments[i];
        if (arg instanceof RegExp) {
            components = components.concat(arg._components || arg.source);
        }
    }

    var combined = new RegExp("(?:" + components.join(")|(?:") + ")");
    combined._components = components; // For chained calls to "or" method
    return combined;
};

RegExp.prototype.or = function() {
    var args = Array.prototype.slice.call(arguments);
    return RegExp.any.apply(null, [this].concat(args));
};

The alternatives are wrapped in non-capturing groups and combined with the disjunction operator, making this a somewhat more robust approach for more complex regular expressions.
Note that you will need to include this code before calling the helper functions!

A: If regexps are not known beforehand,
var one = /[a-z]/;
var two = /[A-Z]/;

var one_or_two = new RegExp("(" + one.source + ")|(" + two.source + ")")

A: Based on Bry6n answer here's a solution I use:
const Regexes = {
  Empty: /^$/,
  Minus: /^[-]$/,
  DotAndNumber: /^\.\d+$/,
  NumberAndDot: /^\d+\.$/,
  Float: /^[-]?\d+(\.\d+)?$/,
};

const orRegex = (...regexes) =>
  new RegExp(regexes.map(r => r.source).join('|'));

const FloatInputRegex = orRegex(
  Regexes.Empty,
  Regexes.Minus,
  Regexes.DotAndNumber,
  Regexes.NumberAndDot,
  Regexes.Float,
);

A: alpha = new RegExp( lower.source + "|" + upper.source );
console.log( alpha );
// /[a-z]|[A-Z]/

A: use a general function:
const getComposedRegex = (...regexes) => new RegExp(regexes.map(regex => regex.source).join("|"))

Then call it with any number of Regexes.
const reg1 = /[w]{3}/i
const reg2 = /http/i

const composedReg = getComposedRegex(reg1, reg2)


text:
Q: How to integrate $\int{xe^{x}\sin{x}}~dx$ How to integrate
$$\int{xe^{x}\sin{x}}~dx$$
I tried taking $v=xe^{x}$ and using integration by parts, but that became lengthy and didn't work.

A: Hint 1: Use integration by parts, where $x = u$ and $y = e^x \sin(x)$.
Hint 2: The first hint may not be helpful, especially if you haven't already encountered the integral of $e^x \sin(x)$. Finding an antiderivative of that is a  nontrivial sub-problem that involves using integration by parts twice and solving an equation for the variable $\int e^x \sin(x) \, \textrm{d}x$.

A: Hint:
$x\mathrm e^x\sin x=\operatorname{Im}x\mathrm e^{(1+i)x}$, hence
$$\int x\mathrm e^x\sin x\,\mathrm dx=\operatorname{Im}\biggl(\int x\mathrm e^{(1+i)x}\,\mathrm dx\biggr).$$


text:
Q: Increment the patch in a version number I have a YAML file with semantic versioning number like this:
version: 1.0.1

I need to increment PATCH part of the version. Is it possible to do it with yq?
UPDATE:
The question is about mikefarah/yq implementation which is installed with brew install yq.

A: Please clarify which implementation of yq you are using. Apart from that, the general approach would be to split the string at the dots, convert the last item to a number and increment it, and then rejoin the array with dots.
Here's one way of doing it using the kislyuk/yq implementation:
.version |= (./"." | last |= tonumber + 1 | join("."))

And here's the same using the mikefarah/yq implementation:
.version |= (split(".") | .[-1] |= ((. tag = "!!int") + 1) | join("."))


text:
Q: Texteditor Like Khanacademy JavaScript I was wondering how I would go about making something like what Khanacademy has.
If you check out the link below they basically have a text box where you can input text and then depending what "keywords" you put it will highlight them, for example if you type function it will return with the word function in the colour blue. But if you do stuff like rect() it will draw a rectangle in the screen next to it. I want to do something like this but with HTML, so depending if you put certain keywords it would make it a certain colour and then it will output your code in the screen next to it as actual HTML. I'm guessing you could do something like an iFrame for the output but not sure about the rest.
Link: https://www.khanacademy.org/cs/programming/drawing-basics/p/intro-to-drawing
I checked out stuff online but can't find anything like this.
Another thing you could relate is the code editor on codecademy.com.
If you need more information let me know!
This is my last resort, I've been looking for 2 months D:

A: A good syntax hightlighter you can use is CodeMirror (http://codemirror.net/). It is very easy to implement and get text from it, change colors, etc.
I understand you also want to be able to allow for programming in the textbox. A simple way too allow this without creating your own code parser would be to use javascript code in your textbox. You can then use javascript's eval() function on the text in the textbox to execute this javascript.
The only thing you would have to do then is to code your own functions like rect() as javascript functions in your html page. For drawing functions like rect() and others you can already use the HTML5 canvas object (http://www.w3schools.com/tags/ref_canvas.asp). You could then draw this canvas in an iframe like you suggested or just simply in another div.
I hope this will give some inspiration or get you started.
EDIT: I have provided a small example: (you browser must support HTML5 for this to work)

<link rel=stylesheet href="http://codemirror.net/lib/codemirror.css">

<textarea id=code>
// Drawing test
Rect(20,20,100,100);
</textarea>

    <canvas id="canvas" width="500" height="400"></canvas>

<input type="button" onclick="eval(editor.getValue())" value="Run" />


text:
Q: spl_autoload_register() with multiple folders I'm using the below snippet to autoload classes from several folders:
// Check if the autoload configuration file exists
if(is_file("configuration/autoload")) {
    // Extract the listed folders from the configuration file
    $folders = explode("\n", file_get_contents("configuration/autoload"));
    // Prepend the base path to the extracted folder paths
    array_unshift($folders, get_include_path());
    // Configure the folders in which to attempt class autoloading
    set_include_path(implode(PATH_SEPARATOR, $folders));
    // Configure the file extensions that should be autoloaded
    spl_autoload_extensions(".php");
    // Administer the attempt to autoload classes
    spl_autoload_register();
}

The several folders are listed in a file like so:
core/utility
core/factory
core/modules
core/classes
core/classes/form
core/classes/form/fields
frontend

It works like charm locally, but I can't get it to work on my online server (I did CHMOD all files & folders involved). I guess things are going wrong while setting the include paths, but I can't seem to wrap my head around it.
Any ideas?
Thanks

A: I would reccomend to create your own autoload function i.e. my_autoloader. This way you have complete control for the folder handling.
function my_autoloader($className)
{
    $parts = explode('\\', $className); //split out namespaces
    $classname = strtolower(end($parts)); //get classname case insensitive (just my choice)

        //TODO: Your Folder handling which returns classfile

    require_once($loadFile);
}
spl_autoload_register(__NAMESPACE__ . '\my_autoloader');

Remember to handle different namespaces

A: This is how Magento eCommerce does it:
function __autoload($class)
{
    if (defined('COMPILER_INCLUDE_PATH')) {
        $classFile = $class.'.php';
    } else {
        $classFile = uc_words($class, DIRECTORY_SEPARATOR).'.php';
    }

    include($classFile);
}

Then you would have the following structure:
class Company_Category_Class{}

And the following stricture (assuming you have "lib" in your include path):
./lib/Company/Category/Class.php

Let me know if you have any questions.


text:
Q: Auto switch desktops Windows, 10 Like a slideshow I have a big screen that shows several monitoring applications but lacks enough to show all applications clearly on one desktop.  Is there a way to make use of Windows 10 multi desktops and get it auto switch between these desktops periodically.

A: Have you tried AutoIT? It's a scripting language designed for automating the Windows GUI and general scripting.
Fairly simple to use.


text:
Q: How many threads do we run in this code sample? Can anyone draw a flowchart of it? - (void)viewDidLoad {
    [super viewDidLoad];

    [self firstTest];
}

-(void)viewWillAppear:(BOOL)animated{
    [self secondTest];
}

-(void)viewDidAppear:(BOOL)animated{
    [self thirdTest];
}

- (void)firstTest {
    NSLog(@"=================1");

    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"=================2");
    });

    NSLog(@"=================3");
}

- (void)secondTest {
    NSLog(@"ViewWillAppear=============");

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"=================4");

        dispatch_sync(dispatch_get_main_queue(), ^{
            [NSThread sleepForTimeInterval:5.0f];

            NSLog(@"=================5");
        });

        NSLog(@"=================6");
    });

    NSLog(@"==========Main Thread Blocked");
}

- (void)thirdTest {
    NSLog(@"ViewDidAppear=============");

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"=================7");

        dispatch_sync(dispatch_get_main_queue(), ^{
            NSLog(@"=================8");
        });

        NSLog(@"=================9");
    });
}

A: Each of the dispatch_async(dispatch_get_global_queue(...)) may be run on a worker thread managed by the global queue, so you're potentially looking at three threads, but it's also possible that the first dispatch to the global queue may finish before the second starts, so you may actually end up using two threads, but given that you dispatch synchronously in secondTest, you'll almost certainly use three threads.
So the main thread will run 1, 3, 2, 5, and 8, a worker thread invoked by the global queue in secondTest will run 4 and 6, and a worker thread in thirdTest will run 7 and 9.

For what it's worth, Xcode 8's updated activity tracing makes this sort of analysis a little easier. For example, I can replace the NSLog statements with kdebug_signpost statements:
#import <sys/kdebug_signpost.h>

@interface ViewController ()
@property (nonatomic, strong) dispatch_group_t group;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    kdebug_signpost_start(1, 0, 0, 0, 1);

    // create a group that will call notify block when three `dispatch_group_leave` calls happen
    // by having an alert show up when all three tests are done, I can terminate the instruments
    // session at the appropriate time

    self.group = dispatch_group_create();

    dispatch_group_enter(self.group);
    dispatch_group_enter(self.group);
    dispatch_group_enter(self.group);

    dispatch_group_notify(self.group, dispatch_get_main_queue(), ^{
        UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil message:@"Done" preferredStyle:(UIAlertControllerStyleAlert)];
        [controller addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:controller animated:true completion:nil];
    });

    // now carry on doing the tests

    [self firstTest];

    kdebug_signpost_end(1, 0, 0, 0, 1);
}

-(void)viewWillAppear:(BOOL)animated{
    kdebug_signpost_start(2, 0, 0, 0, 2);

    [super viewWillAppear:animated];

    [self secondTest];

    kdebug_signpost_end(2, 0, 0, 0, 2);
}

-(void)viewDidAppear:(BOOL)animated{
    kdebug_signpost_start(3, 0, 0, 0, 3);

    [super viewDidAppear: animated];

    [self thirdTest];

    kdebug_signpost_end(3, 0, 0, 0, 3);
}

- (void)firstTest {
    dispatch_async(dispatch_get_main_queue(), ^{
        kdebug_signpost_start(4, 0, 0, 0, 1);
        [NSThread sleepForTimeInterval:1];
        kdebug_signpost_end(4, 0, 0, 0, 1);

        dispatch_group_leave(self.group);
    });
}

- (void)secondTest {
    dispatch_queue_t queue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0);

    dispatch_async(queue, ^{
        kdebug_signpost_start(5, 0, 0, 0, 2);

        dispatch_sync(dispatch_get_main_queue(), ^{
            kdebug_signpost_start(6, 0, 0, 0, 2);
            [NSThread sleepForTimeInterval:5.0f];
            kdebug_signpost_end(6, 0, 0, 0, 2);

            dispatch_group_leave(self.group);
        });

        kdebug_signpost_end(5, 0, 0, 0, 2);
    });
}

- (void)thirdTest {
    dispatch_queue_t queue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0);

    dispatch_async(queue, ^{
        kdebug_signpost_start(7, 0, 0, 0, 3);

        dispatch_sync(dispatch_get_main_queue(), ^{
            kdebug_signpost_start(8, 0, 0, 0, 3);
            [NSThread sleepForTimeInterval:1.0f];
            kdebug_signpost_end(8, 0, 0, 0, 3);

            dispatch_group_leave(self.group);
        });

        kdebug_signpost_end(7, 0, 0, 0, 3);
    });
}

@end

I use the first parameter to indicate the task I'm interested in tracing, and I use the fourth parameter to indicate the color in "system trace". I can then specify names to associate with these unique identifiers as outlined in System Trace in Depth so that they show up as "regions" in the "Points of Interest" section. You can then use the "System Trace" tool in Instruments, and you can see what's going on. There's not perfect correlation between these named regions and their associated threads, but it makes it quite easy to verify yourself (e.g. control-click on one of the named kdebug regions on the bottom to filter the timeline for just that part of the app's operation; etc.).

There's no way I can give this its due in this short answer, but I might suggest watching that video, which shows you how to associate activities in your code to activity on threads, cpus, etc. It admittedly takes a little playing around with this tool to become familiar with it (e.g. filtering down to just the process in question, learning to identify your threads versus other threads that the OS creates, etc), but it can helpful in identifying blocked threads, etc.


text:
Q: Google tag manager error with anonymous function I have a issue after integration Google-tag-manager code to my web site: "GET https://www.googletagmanager.com/gtm.js?id=GTM-XXXXXX  (index):336(anonymous function) (index):336(anonymous function)".
We suppose it is related that this script is not directly specified https protocol, and therefore the browser interprets the request as unsafe. This issue happend only Google Chrome. On FireFox everything ok. How it can be fixed?
I have read that issue can occur due to AdBlock, but when I off if, issue wasn't resolved.

A: As stated in Setup and installation you may try to verify or troubleshoot your installation with:

*

*Tag Manager's Preview Mode

*Tag Assistant Chrome extension


text:
Q: orginal image resolution estimate I'm looking for an image analyzing algorithm that estimates the "original" resolution of a picture after is has been scaled up.
I understand the result would depend a lot on image motive, focus, noise and post effects, but getting a rough estimate of a minimum size image that has the same information content would be quite interesting.
Is there something like this out there already, maybe even an existing tool/plugin?

A: (assuming this is a practical problem, as opposed to a theoretical question).
Have you looked at metadata? A lot of image processing software leaves the EXIF headers untouched, or appends helpful information to them...


text:
Q: Automate removing users from group if not in OU Earlier today, I got help adding members to a group if they are not a member of it.
$group = 'CN=Group1,OU=SomeOU,DC=domain,DC=local'
Get-ADUser -LDAPFilter "(!memberof=$group)" -SearchBase "DC=domain,DC=local" |
Add-ADPrincipalGroupMembership -MemberOf $group

Now I want to reverse that and remove members from the group if they are not in the specific OU I used as the -SearchBase. Does this look correct?
$group = 'CN=Group1,OU=SomeOU,DC=domain,DC=local'

Get-ADGroupMember -Identity $group |
Where-Object { $_.DistinguishedName -notlike "*DC=domain,DC=local" } |
Remove-ADPrincipalGroupMembership -MemberOf $group

A: To reverse the order would mean to query the Group's Member attribute and filter those DistinguishedNames not containing the base DistinguishedName. -notlike can act as a filter on collection of values hence:
$group = 'CN=Group1,OU=SomeOU,DC=domain,DC=local'
$base  = 'DC=domain,DC=local'
(Get-ADGroup $group -Properties member).member -notlike "*$base" |
    Remove-ADPrincipalGroupMembership -MemberOf $group


text:
Q: compatibility issue with contourArea in openCV 3 I am trying to do a simple area calculation of contours I get from findContours.
My openCv version is 3.1.0
My code is:
cc = cv2.findContours(im_bw.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.contourArea(cc[0])

error: 'C:\\builds\\master_PackSlaveAddon-win32-vc12-static\\opencv\\modules\\imgproc\\src\\shapedescr.cp...: error: (-215) npoints >= 0 && (depth == CV_32F || depth == CV_32S) in function cv::contourArea\n'

Cant seem to solve it, I have a feeling its just typecasting altough I expect the findContours result to match the type of contourArea
Thanks :)
EDIT: turns out I need to take the 2nd argument of findContours
 im2, cc, hierarchy = cv2.findContours(im_bw.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

A: In Opencv 3 API version the cv2.findContours() returns 3 objects

*

*image

*contours

*hierarchy

So you need to rewrite your statement as:
image, contours, hierarchy = cv2.findContours(im_bw.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

A: Depending on the OpenCV version, cv2.findContours() has varying return signatures.
In OpenCV 3.4.X, cv2.findContours() returns 3 items
image, contours, hierarchy = cv.findContours(image, mode, method[, contours[, hierarchy[, offset]]])

In OpenCV 2.X and 4.1.X, cv2.findContours() returns 2 items
contours, hierarchy = cv.findContours(image, mode, method[, contours[, hierarchy[, offset]]])

You can easily obtain the contours regardless of the version like this:
cnts = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

A: This problem is caused by the different return value of cv2.findContours in different OpenCV versions.
In OpenCV 4.0.0, this error may looks like cv2.error: OpenCV(4.0.0) C:\projects\opencv-python\opencv\modules\imgproc\src\convhull.cpp:137: error: (-215:Assertion failed) total >= 0 && (depth == CV_32F || depth == CV_32S) in function 'cv::convexHull'
You can find a detailed explanation and solutions here: How to use `cv2.findContours` in different OpenCV versions?

A: Thanks for @ZdaR;
By the way,  you can do the following in OpenCV 4.1:
contours, hierarchy = cv2.findContours(im_bw.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)


text:
Q: Create a triangle with just one print function There are some restrictions:

*

*You can not just build the whole triangle with string then print.

*Code must be using loops.

The output I want to create:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

This was our exam question but I couldn't find the solution after hours of thinking.

A: Here is a version with parameters:
print '\n'.join(' '.join(str(j + 1) for j in range(5 - abs(i))) for i in range(-5, 6))

or in Python 3:
print('\n'.join(' '.join(str(j + 1) for j in range(5 - abs(i))) for i in range(-5, 6)))

A: This can be done easily by using the "\n" for line breaks:
print "1\n1 2\n1 2 3\n1 2 3 4\n1 2 3 4 5\n1 2 3 4\n1 2 3\n1 2\n1"

..or in 3.x
print("1\n1 2\n1 2 3\n1 2 3 4\n1 2 3 4 5\n1 2 3 4\n1 2 3\n1 2\n1")


text:
Q: How to get the sObject type from a controller? I have an extension class that I want to share between tasks and events to route the user to the right page.  In my contstructor, I want to determine the sObject type of the controller how do to i do that?

A: There are a couple of approaches you can use for this, one is using SObjectType, the other is using the 'instanceof' feature in Apex. Using 'instanceof' is more natural from an OOP perspective, and thus Java and C# developers will understand it more than the SObjectType approach. The first depends if you plan to do any Apex Describe type work after, thus the SObjectType is the place to start if so.
     SObjectType sObjectType = controller.getRecord().getSObjectType();
     if(sObjectType == Opportunity.sObjectType)
     {
        // This is a Opportunity record
        Opportunity opp = (Opportunity) controller.getRecord();
     }
     else if(sObjectType == Account.sObjectType)
     {
        // This is a Account record
        Account acc = (Account) controller.getRecord();
     }

     SObject record = controller.getRecord();
     if(record instanceof Opportunity)
     {
        // This is a Opportunity record
        Opportunity opp = (Opportunity) controller.getRecord();
     }
     else if(record instanceof Account)
     {
        // This is a Account record
        Account acc = (Account) controller.getRecord();
     }

A: Easy!!
public YourExtension(ApexPages.StandardController controller) {
  String sObjectType = String.valueOf(controller.getRecord().getSObjectType());
}

A: try:
public class myControllerExtension {

    public myControllerExtension(ApexPages.StandardController stdController) {
        String type = stdController.getRecord().getSObjectType().getDescribe().getName();

    }
}

You can't get the object type from sObjectType as an string. Try by using  getDescribe().getName();

Apex provides two data structures for sObject and field describe
  information:

*

*Token—a lightweight, serializable reference to an sObject or a field that is validated at compile time.

*Describe result—an object that contains all the describe properties for the sObject or field. Describe result objects are not
  serializable, and are validated at runtime.

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_describe_objects_understanding.htm


text:
Q: "Never saw" versus "didn't ever see" Do these sentences have different meanings?

*

*I never saw such a thing.
I didn't ever see such a thing.

*I never saw him dancing.
I didn't ever see him dancing.

My questions:

*

*Are both usages correct?

*Is there a difference in meaning?

A: Ah, Negative Polarity again.
(BTW, I am informed that there is now an NPI tag, which anyone is allowed to use to mark questions with. Feel free.)
Whenever you see a negative (like never) in a sentence, you know you've got trouble. Especially if you see more than one, or if there's a modal in the sentence as well. Luckily, that's not the case here.
First, NPIs. The word ever means at any time, i.e, *anywhen. But people don't say *anywhen (the asterisk means it's ungrammatical); they say ever instead, the same way they don't say *all two,
but rather  say both instead.
The interesting thing about the word ever is that it's a Negative Polarity Item (NPI), like any; indeed, it's just a variant of any. NPIs can't occur outside a negative context, which is why it sounds so awful to say

*

**I have ever been there.
That's why there's a not in

*

*I have not ever been there.
Never is just a contraction of not ever, the same way none is a contraction for not one.

*

*I have never been there.
Both of those are fine, because they're negative. One is a contraction of the other, so there's no meaning difference.
As for such a thing, it's an idiom, in this case a pretty frozen one, which indicates surprise at the extreme nature of whatever the "thing" is sposta be. So you get to express surprised indignation at the same time you deny experience of extremes. Pretty useful phrase.

A: Both usages are correct.
They mean the same thing.
However, the scope of the first is more comprehensive.  "I never" implies "in my whole life."  "I didn't ever" implies "while I was there at that event we're discussing."
Both are mere implications; unless stated, either scope can be understood.

A: I think there's a subtle difference in meaning, at least in my dialect:  "I didn't ever..." often has more force/emphasis than "I never.."  One may say, "I never saw him do that".  The emphasis is on "saw" and the implication could be that he may have done it for all I know, but I didn't see it.  But if I say, "I didn't ever see him do that", then the emphasis is on "ever", which gives an implication is more along the lines of I don't think it ever happened.
As I said, it's not 100% consistent, but there often is that distinction.  You have to rely on context for full clarity.

A: In everyday speech, most people use "I didn't..." and "I never..." interchangeably. However, there is a subtle difference. The use of "never" can be used to imply that something is no longer possible, or is very unlikely to happen. For example:

*

*"I didn't see that Broadway musical." - this simply means you did not see the show, and does not imply anything about the future.

*"I never saw that Broadway musical." - this could be used to refer to a show that is no longer playing, so it would no longer be possible to see it.


text:
Q: Extract one hot encoding from a file into a dataset I have a dataset images and corresponding labels, where to each image file there is a .txt file which contains the one hot encoding:
0
0
0
0
1
0

My code looks something like this:
imageString = tf.read_file('image.jpg')
imageDecoded = tf.image.decode_jpeg(imageString)

labelString = tf.read_file(labelPath)
# decode csv string

but labelString looks like this:
tf.Tensor(b'0\n0\n0\n0\n1\n', shape=(), dtype=string)

Is there a way to transform this into an array of numbers inside tensorflow?

A: Here is a function to do that.
import tensorflow as tf

def read_label_file(labelPath):
    # Read file
    labelStr = tf.io.read_file(labelPath)
    # Split string (returns sparse tensor)
    labelStrSplit = tf.strings.split([labelStr])
    # Convert sparse tensor to dense
    labelStrSplitDense = tf.sparse.to_dense(labelStrSplit, default_value='')[0]
    # Convert to numbers
    labelNum = tf.strings.to_number(labelStrSplitDense)
    return labelNum

A test case:
import tensorflow as tf

# Write file for test
labelPath = 'labelData.txt'
labelTxt = '0\n0\n0\n0\n1\n0'
with open(labelPath, 'w') as f:
    f.write(labelTxt)
# Test the function
with tf.Session() as sess:
    label_data = read_label_file(labelPath)
    print(sess.run(label_data))

Output:
[0. 0. 0. 0. 1. 0.]

Note the function, as I wrote it, uses some of the new-ish API endpoints, you can also write it as below for more backwards compatibility, with almost the same meaning (there are slight differences between tf.strings.split and tf.string_split):
import tensorflow as tf

def read_label_file(labelPath):
    labelStr = tf.read_file(labelPath)
    labelStrSplit = tf.string_split([labelStr], delimiter='\n')
    labelStrSplitDense = tf.sparse_to_dense(labelStrSplit.indices,
                                            labelStrSplit.dense_shape,
                                            labelStrSplit.values, default_value='')[0]
    labelNum = tf.string_to_number(labelStrSplitDense)
    return labelNum

A: You can use basic python commands and convert it to a tensor.  Try...
with open(labelPath) as f:
    lines = f.readlines()
    lines = [int(l.strip()) for l in lines if l.strip()]
labelString = tf.convert_to_tensor(lines, dtype='int32')


text:
Q: Excel Macro - Add new range to existing Formula Office 2010 My macro inserts 8 lines of a new job to a Summary Spreadsheet.  These lines link to a different file name and has a subtotal included as a =sum() formula (for each job).  My Grand total now does not include this new subtotal range in my previous 4 job summary.  There will be more jobs added later so it has to keep working relative to the future jobs being potentially added.  Looking for an easy way to add this new range to my existing formula within the Grand Totals Cell.  Thanks for the help.
Right now the Cell contains this formula: =G37+G29+G21+G13  (these are my for job summary subtotals)
After adding my 8 new rows of a new job I will have to add the Cell "G45" to the above formula within the macro and if I add another job it will be "G53".  The Cell to add is always 3 rows above the formula I want to add it to but the formulas has to continue to work as the jobs will be updated daily or at least weekly.  Thanks for your help.

A: just append the range to the sum function.
=SUM(A1:A6)

say now I want to add in cells C1 through C6
=SUM(A1:A6:C1:C6)

say now I want to add in cell D5
=SUM(A1:A6:C1:C6,D5)

say now I want to add in cells E1 through E6
=SUM(A1:A6:C1:C6,D5,E1:E6)


text:
Q: How to configure proguard properly in android? I am already enabling proguard by help of this link http://developer.android.com/tools/help/proguard.html but not reduce apksize and also get code from apk in reverse engineering process,so how to configure.
Thanks in advance


text:
Q: Problem with using CSS I am trying to include a simple css components as in below,
<apex:stylesheet value="https://www.w3schools.com/w3css/4/w3.css"/>
    <apex:form >

Do not change the Column Header

    </apex:form>

This is working fine, but sidebar and header fonts become very larger.. Whats the reason for this?

A: I looked at the issue and looks like your css isn't scoped to apply just for your content.
You can do the following things
a. turn off standard stylesheets completely by disabling your header and sidebar for your page using
  <apex:page standardStylesheets="false" showHeader="false" sidebar="false" >
  ...
  </apex:page>

b. improve your stylesheet to scope to your div
Stylesheet
.mycustom { font-size: 15px; }
.mycustom .w3-panel {... }

<apex:page>

       <apex:form >

Do not change the Column Header

        </apex:form>

</apex:page>

I would suggest b.
FYI: Upon inspecting the css I observed that the font size of body was being set to 15px, which probably caused the zoom issue. w3.css is setting a different font size from salesforce standard.


text:
Q: How to add endorsed directory to runnable jar I am using endorsed directory for some jar which can be used from command line.
Now I want to make jar as runnable with endorsed directory so that user can just click the runnable jar file to run the application.
I am using Eclipse Helios and Java 6.
Can anyone tell me how to do the above mentioned task.
Regards,
Ashish

A: From Eclipse

*

*Right Click the project and select "Export"

*Select Runnable JAR File

*Select output direct

*Press Next

*Press Next

*Press Finish

Once it is exported it ,let say in C:\
Run Command prompt and change it to c: and run
java -jar XXXX.jar

thats it.
Packaging JAR as EXE.
Download Launch4J here.
Screenshots
Click here


text:
Q: Get a specific id/class (typescript) Get the ion-label textContent and add it to an ion-input value.
Clicking a specific id or class adds the textContent to an input value
    <ion-item>
        <ion-input type="text" id="item" ></ion-input>
    </ion-item>
    <ion-item *ngFor="let item of toDoList, index as i, let x = index">
        <ion-label id="{{i+0}}" class="element-" [ngClass]="'element-'+x" (click)="doit()">{{item.getX}}</ion-label>
        <ion-button expand="full" (click)="remove(item.getX)">
            <ion-icon name="trash-outline" color="danger"></ion-icon>
        </ion-button>
    </ion-item>

doit() {
    let id = (<HTMLLabelElement>document.getElementById('0')).textContent;
    (<HTMLInputElement>document.getElementById('item')).value = id;
  }