text:
Q: I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? I have a Windows 10 PC and I want to install pyaudio to use it with my chatbot, powered by chatterbot.
I tried 2 different ways to install pyaudio.
The first way is doing this on the command prompt:
python -m pip install PyAudio

This is the result:
   C:\Users\Waaberi>python -m pip install PyAudio
Collecting PyAudio
  Using cached https://files.pythonhosted.org/packages/ab/42/b4f04721c5c5bfc196ce156b3c768998ef8c0ae3654ed29ea5020c749a6b/PyAudio-0.2.11.tar.gz
Installing collected packages: PyAudio
  Running setup.py install for PyAudio ... error
    Complete output from command C:\Users\Waaberi\AppData\Local\Programs\Python\Python37-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Waaberi\\AppData\\Local\\Temp\\pip-install-e5le61j0\\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\Waaberi\AppData\Local\Temp\pip-record-adj3zivl\install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_py
    creating build
    creating build\lib.win32-3.7
    copying src\pyaudio.py -> build\lib.win32-3.7
    running build_ext
    building '_portaudio' extension
    error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

    ----------------------------------------
Command "C:\Users\Waaberi\AppData\Local\Programs\Python\Python37-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Waaberi\\AppData\\Local\\Temp\\pip-install-e5le61j0\\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\Waaberi\AppData\Local\Temp\pip-record-adj3zivl\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\Waaberi\AppData\Local\Temp\pip-install-e5le61j0\PyAudio\

The second way is entering this command:
python pip install python-pyaudio

and it does nothing.

A: For some reason pip does not work,
instead you could try first installing "pipwin" if you don't already have it
Open a cmd and paste this:
pip install pipwin

and then install PyAudio using:
pipwin install pyaudio

It should work. But if you don't want to use pipwin.. just install it and then uninstall it afterwards by simply using:
pip uninstall pipwin

A: The problem is pyaudio does not have wheels for python 3.7 just try some lower version like 3.6
then install pyaudio
It works

A: If you have anaconda install than you just need to use command: conda install PyAudio.
In order to execute this command you must set thePYTHONPATH environment variable in anaconda.

A: You should install python 3.6 version because python 3.7 version doesn't support pyaudio
1 step : Then download the .whl file
according to your python version and the configuration of your machine in your python folder which is newly installed. For me it is python 3.6 and 64 bit machine. Download the file from here
(https://www.lfd.uci.edu/~gohlke/pythonlibs/)
2 step : run your cmd and type " pip install your downloaded file name here  "

A: There is no wheel (prebuilt package) for Python 3.7 on Windows (there is one for Python 2.7 and 3.4 up to 3.6) so you need to prepare build environment on your PC to use this package. Easier would be finding the wheel for 3.7 as some packages are quite hard to build on Windows.
Christoph Gohlke (University of California) hosts Windows wheels for most popular packages for nearly all modern Python versions, including latest PyAudio. You can find it here: https://www.lfd.uci.edu/~gohlke/pythonlibs/ (download can be quite slow). After download, just type pip install <downloaded file here>.
There is no difference between python -m pip install, and pip install as long as you're using default installation settings and single python installation. python pip actually tries to run file pip in the current directory.
Edit. See the pipwin comment for automated way of using Mr Gohlke's libs . Note that I've not used it myself and I'm not sure about selecting different package flavors like vanilla and mkl versions of numpy.

A: Seems PyAudio is supported by Python 2.7, 3.4, 3.5, and 3.6.  Refer https://people.csail.mit.edu/hubert/pyaudio/
Please suggest if there is any alternate way to install PyAudio on Python 3.8.2

A: The answer by Agalin is already great and I just want to explain it in a step by step format for a novice like myself:

*

*find your Python version by python --version mine is 3.7.3 for example

*the easiest way to check either you have 64 or 32 Python just open it in the terminal:

*

*find the appropriate .whl file from here, for example mine is PyAudio‑0.2.11‑cp37‑cp37m‑win_amd64.whl, and download it.

*go to the folder where it is downloaded for example cd C:\Users\foobar\Downloads

*install the .whl file with pip for example in my case:

pip install PyAudio-0.2.11-cp37-cp37m-win_amd64.whl

A: Use Conda instead of pip.
It works perfectly
conda install PyAudio

A: First run your IDE or CMD as Administrator and run the following commands:
pip install pipwin
pipwin install pyaudio

A: you may need to try
pip install --upgrade setuptools

you may also need to install Visual Studio 2015, and remember to choose to install Visual C++ 14.0
https://visualstudio.microsoft.com/visual-cpp-build-tools/

A: You should just install python 3.6. I tried it and it worked. Just install that version of python and just do the normal download process (pip install pyaudio).

A: Here's how I solved this damn problem on Linux Fedora-36.
sudo dnf install portaudio-devel

After that, portaudio, portaudio-devel and alsa-lib-devel packages were installed.
Then Kindly;
pip install pyaudio

All the problem went away with my execution.

A: I have got the same error as :

error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/

As, said by @Agaline, i download the outside wheel from this Christoph Gohlke.
If your is Python 3.7 then try to PyAudio‑0.2.11‑cp37‑cp37m‑win_amd64.whl and use command as, go to the download directroy and:
pip install PyAudio‑0.2.11‑cp37‑cp37m‑win_amd64.whl and it works.

A: If you are using Python 3.7.3 and Windows 10 64-bit machine then try the following command.
Go to the download folder and Install following command:
pip install PyAudio‑0.2.11‑cp37‑cp37m‑win_amd64.whl

and it should work.

A: For PyCharm use the Terminal:
pip install pipwin
pipwin install PyAudio <-- Remember the capital letters

A: Try following command for MacOS using python 3.8.2
install Homebrew on your terminal
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Visual Studio Code terminal
1.brew install portaudio
2.pip install pyaudio

A: I assume you are building something requiring input from the user and also the keyboard. You will need various libraries, I will list all of them directly from the source...
!apt-get install -y portaudio19-dev libasound-dev libportaudio2 libportaudiocpp0
!pip install pyaudio wave keyboard pydub

It installs various dependencies for pyaudio which may hinder the installation of pyaudio.

A: I had the same issue but solved it by using Ubuntu.

*

*python -m pip install pyaudio

*Install sudo, apt-get and then install homebrew &/ linuxbrew on your linux subsystem using Ubuntu.

*The latest version supports ubuntu.

*brew install portaudio

*Make sure you have python/python3 installed on the terminal

*Make sure the current location is added as path in your virtual computer's path in environment Variable.

*brew link portaudio


text:
Q: React: how to keep sidepanel state between url changes with history.push()? I have a fixed sidepanel that contains a search bar with filter buttons similar to https://facebook.github.io/react/docs/thinking-in-react.html
The list items are clickable and trigger history.push() for nested path urls.
The nested path structure is
/category-1
/category-1/product-1
/category-1/product-2
/category-2
/category-2/product-1
/category-2/product-2
 .
 .
 .
/category-n/product-m
/category-n/product-k

User can scroll the sidepanel's list and select filters. However, a click on a list item (with onClick() followed by history.push()) causes the whole page (including the sidepanel) to render. This in turn doesn't keep the sidepanel's state so the filters and the scroll position are reset.
The parent render: function() looks like:
return(
  <div id="main-view">
    <Sidepanel history={this.props.history} properties={this.props.properties} />
    React.cloneElement(this.props.children, {this.props});
  </div>
);

The React.cloneElement() is the product info container that should render only.
I'm using react-router, react-redux and redux-simple-router.
Do I need to store the sidepanel's list scroll position and filter values outside of the sidepanel? Or is there a better way to keep the sidepanel's state between the url changes?

A: Your architecture is not aligned with what you want to do.
Simply render the navigation in your top-level, parent component and it will never lose state - for example in your Application component. Then SidePanel wouldn't be affected by route change.
Also you could pass down a callback to set / alter navigation from children, if needed (for example hide() or addMenuItems()).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use angular varible in icon chrome extansion I try use AngularJS to Change.
There is a script that is after the lapse of time, the icon replaces the chrome extension.
Source:
`chrome.alarms.onAlarm.addListener(function( alarm ) {
  //
  console.log("Got an alarm!");
   alert('great1');
   chrome.browserAction.setIcon({ path: "icons/10n.png" });
   chrome.alarms.create({'delayInMinutes': 1});
   location.reload();
});
//
chrome.alarms.create({'delayInMinutes': 1});

The name of the icons stored in the variable {{item.weather[0].icon}}.
But the expression
 chrome.browserAction.setIcon({ path:"icons/{{item.weather[0].icon}}.png" });

not work.
Angular version
    (function(angular){
  'use strict';
angular.module('backskrip',[])
.controller('BackController',['$scope',function($scope){
chrome.alarms.onAlarm.addListener(function(alarm) {
  // события по будильнику.
  console.log("Got an alarm!");
   alert('great1');
   chrome.browserAction.setIcon({ path: "icons/{{vm.data.list[0].weather[0].icon}}.png" });
   chrome.alarms.create({'delayInMinutes': 1});
   location.reload();
});

// создаем будильник
chrome.alarms.create({'delayInMinutes': 1});
}]);
})(window.angular);


text:
Q: How to resolve CLI connection problem from java client to Jenkins server? Connecting with CLI in default way towards new Jenkins instance hangs.
java -jar $JENKINS_HOME/war/WEB-INF/jenkins-cli.jar -s http://git-dapp902.XXXXXXXX:17801 -auth admin:aaaaaaa  who-am-i
(aaaaaa = initial password for admin account)
Following actions were performed
- startup new Jenkins instance
- log on as admin with initial password
- enable global security JLNP on fixed port (without this, I would get a Connection Refused)
- restart the jenkins server
- launch the above java command (on the same Linux VM)
- client does not return. No logging on Jenkins server
- When client is canceled below logging is shown
java -jar $JENKINS_HOME/war/WEB-INF/jenkins-cli.jar -s http://git-dapp902.XXXXXXXX:17801 -auth admin:aaaaaaa  who-am-i

WARNING: Connection #4 failed
java.io.EOFException
        at java.base/java.io.DataInputStream.readFully    (DataInputStream.java:202)
        at java.base/java.io.DataInputStream.readUTF(DataInputStream.java:614)
        at java.base/java.io.DataInputStream.readUTF(DataInputStream.java:569)
        at hudson.TcpSlaveAgentListener$ConnectionHandler.run(TcpSlaveAgentListener.java:254)

A: In the meantime I found the solution.
The Jenkins URL does not need to point to the port in JLNP setting, but to the "plain" port.
Luc


text:
Q: How to find maximum time range collision occurencies in Mysql I have a time range entity with start and end datetime column.
I need to find the maximum occurrencies (count) of overlapping the same time slot.

In the example above, the count is 4.
https://www.db-fiddle.com/f/pcq1MjQeqSEMDdyGxkFsR5/0
Probably I need some recurring query but I don't know how to start.

A: For MySQL 5.x:
SELECT SUM(points2.weight) max_weight
FROM (
  SELECT start dt FROM slots
  UNION DISTINCT
  SELECT `end` FROM slots
  ) points1
JOIN (
  SELECT dt, SUM(weight) weight
  FROM (
    SELECT start dt, 1 weight FROM slots
    UNION ALL
    SELECT `end`, -1 FROM slots
    ) points
  GROUP BY dt
  ) points2 ON points1.dt >= points2.dt
GROUP BY points1.dt
ORDER BY max_weight DESC LIMIT 1

https://dbfiddle.uk/f0b56Q4X (step-by-step, with comments)


text:
Q: Spring Cloud Kubernetes fails setting ConfigMap values I am trying to support K8s ConfigMap API using Spring to handle my externalized configuration. I've been using a configuration service without any issues, so I don't believe it is a cloud-config implementation problem. I am using version 1.0.2.RELEASE of spring-cloud-starter-kubernetes-config.
My ConfigMap consists of two configurations: global (application.yml) and app-specific yaml (myapp.yml). Here is what that looks like:
apiVersion: v1
kind: ConfigMap
metadata:
  name: myapp-config
data:
  application.yml: |-
    kafka:
      hosts: kafka:9092

      topics:
        events: myapp-events
        normalized: myapp-normalized
        #...

    storage:
      uri: mongodb://mongo-0.mongo:27017,mongo-1.mongo:27017,mongo-2.mongo:27017
      database: do-stuff-db
      #...

    spring:
      cloud:
        config:
          override-system-properties: false

    #...

  myapp.yml: |-
    myapp:
      broadcast-address: 0.0.0.0:666

      #...

application.yml seems to work just fine. I can see the configuration values in my application but for whatever reason, myapp.yml does not get set. I can see Spring is successfully grabbing the entire result from the ConfigMap API but it does not do anything with myapp.yml.
Turning on debug logging exposed how Spring is interpreting the ConfigMap result. It is treating the entire myapp.yml section as one property and not its own property source. This explains why the application.yml is taking and not the myapp.yml. Here is what that log looks like (I have truncated the message):
2019-09-04 14:01:37.083 [main] INFO  config.PropertySourceBootstrapConfiguration - Located property source: CompositePropertySource {name='composite-configmap', propertySources=[ConfigMapPropertySource@92864491 {name='configmap.myapp-config.default', properties={kafka.hosts=kafka:9092, kafka.topics.events=myapp-events, kafka.topics.normalized=myapp-normalized, myapp.yml=myapp:
  bind-address: 0.0.0.0:666

  #...

    storage.uri: mongodb://mongo-0.mongo:27017,mongo-1.mongo:27017,mongo-2.mongo:27017, storage.database: do-stuff-db}}]}

Do I need to separate these configurations? The examples I've seen from Spring suggest you could consolidate your configuration into a single YAML ConfigMap file. I am stumped.


text:
Q: htaccess modify headers IF url ends with "news" I have a wordress page that resolves to /mysite/news and I'm trying to load it onto another site using javascript. This is a natural cors violation so I'm setting cors to * to bypass the issue ONLY if the url is /mysite/news
However, the following isn't working. I suspect REQUEST_URI is actually resolving to something like index.php?page=xxx but I'm not sure. How can I get around this cors issue ?
<If "%{REQUEST_URI} =~ m#news\/?$#">
  Header always set Access-Control-Allow-Origin "*"
  Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
  Header always set Access-Control-Max-Age "1000"
  Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
</If>

A:
I suspect REQUEST_URI is actually resolving to something like index.php?page=xxx

Yes, it would seem that mod_rewrite is processed before the Apache Expression is evaluated. So, the URL has already been rewritten to index.php (the WordPress front-controller) before we get to evaluate the requested URL in the expression.
However, we can get around this by setting an environment variable "early" using SetEnvif based on the requested URL (which occurs before mod_rewrite) and check for this env var in the expression instead. HOWEVER, an added complication is that this env var is renamed/prefixed with REDIRECT_ after the URL has been rewritten  (the first round of processing) to index.php.
For example:
SetEnvIf Request_URI "news/?$" APPLY_CORS
<If "-n reqenv('REDIRECT_APPLY_CORS')">
  Header always set Access-Control-Allow-Origin "*"
  Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
  Header always set Access-Control-Max-Age "1000"
  Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
</If>

SetEnvIf sets the APPLY_CORS env to "1" if the regex matches the request.
The -n operator in the Apache Expression simply tests that the returned string is not empty.

UPDATE: An alternative is to check against THE_REQUEST server variable instead, which contains the first line of the HTTP request (eg. GET /mysite/news HTTP/1.1*1) and does not change as the URL is rewritten. A slight caveat with this is that the regex can be a little more complex.
(*1 - THE_REQUEST contains the raw, %-encoded URI as sent from the client, query string and all.)
For example, an equivalent to the above (which allows for any reasonable query string) would be something like:
<If "%{THE_REQUEST} =~ m#news/?(\?[\w=&-]*)?\s#">
:
</If>


text:
Q: Use Anchor using Html.MenuLink asp.net mvc4 I'm using Asp.net MVC4 and i'm trying to add an "anchor" in the Html.MenuLink without rewriting a new MenuLink
Here my the html link

    @Html.MenuLink("Join us", "Index", "JoinUs", null, new { @class = "active" })

Resulting in this html when render

    Join us

and the target anchor

Point here

and the MenuLink code
public static MvcHtmlString MenuLink( this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues = null, object htmlAttributes = null)
{
    string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
    string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");

    if (controllerName == currentController)
    {
        if (htmlAttributes == null)
            htmlAttributes = new { @class = "selected" };

        return htmlHelper.ActionLink(
            linkText,
            actionName,
            controllerName,
            routeValues,
            htmlAttributes
        );
    }

    return htmlHelper.ActionLink(linkText, actionName, controllerName);
}

The 4th parameter of the Html.MenuLink is used for adding parameters to the target link, but  that is not what I needed.
I want to have an url like localhost/JoinUs#PointHere
Thanks for help

A: You could use the following overload of the Html.ActionLink helper to generate an url with a fragment identifier:
return htmlHelper.ActionLink(
    linkText: linkText,
    actionName: actionName,
    controllerName: controllerName,
    protocol: null,
    hostName: null,
    fragment: "some_fragment",
    routeValues: routeValues,
    htmlAttributes: htmlAttributes
);

Obviously you will need to adapt your MenuLink custom helper to take as additional parameter the fragment identifier that will be appended to the url.
And then you will be able to invoke it like this:
@Html.MenuLink("Join us", "Index", "JoinUs", null, new { @class = "active" }, fragment: "PointHere")


text:
Q: How to get minimum value of an element combination of str and int in a list Creating list of name and price, this will be the given list:
alist = [["Chanel-1000, Dior-2000, Prada"],["Chloe-200,Givenchy-400,LV-600"],["Bag-1,Bagg-2,Baggg-3"]]

To get minimum value of each element
This will be the output:
chanel-1000,chloe-200,bag-1

A: Check out this code:
1 .If u want output based on integer tag of each name then use the method.
alist = [["Chanel-1000, Dior-2000, Prada-500"],
         ["Chloe-200,Givenchy-400,LV-600"], ["Bag-1,Bagg-2,Baggg-3"]]

alist_min = [
    min(map(str.strip, x[0].split(',')),
        key=lambda i: int(str.strip(i).split('-')[-1])) for x in alist
]
print(alist_min)

OUTPUT :
['Prada-500', 'Chloe-200', 'Bag-1']

2 .If u want output based on name tag of each name then use the method.
alist = [
    ["Chanel-1000, Dior-2000, Prada"],
    ["Chloe-200,Givenchy-400,LV-600"],
    ["Bag-1,Bagg-2,Baggg-3"]]

alist_min = [min(map(str.strip, x[0].split(','))) for x in alist]
print(alist_min)

Now u can use this alist_min object to get required output.

A: Use min() along with a list comprehension:
alist = [["Chanel-1000, Dior-2000, Prada"],["Chloe-200,Givenchy-400,LV-600"],["Bag-1,Bagg-2,Baggg-3"]]
alist_min = [min(re.split(r',\s*', x[0])) for x in alist]
print(alist_min)  # ['Chanel-1000', 'Chloe-200', 'Bag-1']


text:
Q: jQuery bluimp Fileupload - Keep Select Images Rows After Uploading I have been using http://blueimp.github.com/jQuery-File-Upload/ for my rails application. The current behaviour of this plugin is after image is uploaded it removes the row of selected image and show different row to download the image uploaded.
I want to keep selected images table, block the page with preloader image and redirect after all images uploaded. I manage to show preloader, block the page and redirect but don't know how to prevent plugin from removing selected images.
Would anyone please help me to override this behaviour so plugin doesn't remove the row of selected image even after image is uploaded.
Thanks, Amit Patel

A: I did a trick. I modified download file row template to match the file upload row template. After file is uploaded it now shows newly created thumnail. So looks like image is still there.


text:
Q: .htaccess rewrite to convert directories into /key/value/key/value I've seen it before where a rule was used to convert directories on a URL to key=value request queries.
I have no idea how to do this so I can have more than one of these pairs.
For example:
http://www.example.com/mykey/myvalue/mykey2/myvalue2

Would map to:
http://www.example.com?mykey=myvalue&mykey2=myvalue2

Thanks.

A: Use this .htaccess code to have recursion based translation of key/value based URI:
Options +FollowSymLinks -MultiViews
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)(/.*)?$ $3?$1=$2 [N,QSA]
RewriteRule ^(/[^/]+|[^/]+/|/?)$ /index.php [L,QSA]

Using these rules a URL of http://localhost/n1/v1/n2/v2/n3/v3/n4/v4 will be INTERNALLY redirected to http://localhost/?n4=v4&n3=v3&n2=v2&n1=v1 treating each pair of URL segments separated by / as a name-value pair for QUERY_STRING. BUT keep in mind if URI doesn't have even number of segments eg: http://localhost/n1/v1/n2/ then it will be redirected to http://localhost/?n1=v1, discarding extra n2.

A: The most common usage I've seen of this type of pattern is in the Zend Framework, but I believe this is achieved by the Front Controller, i.e. PHP code. There is, I believe, no way to match an unknown number of matches via mod_rewrite. That is to say, if you know there's going to be a maximum of say 3 pairs, you can use...
RewriteRule ^([^/]+)/([^/]+)/?$ /index.php?$1=$2 [QSA,L]
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)/$ /index.php?$1=$2&$3=$4 [QSA,L]
RewriteRule ([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/$ /index.php?$1=$2&$3=$4&$5=$6 [QSA,L]

...but if there is no known maximum it can't be done.

A: You have an excellent tutorial here
http://www.addedbytes.com/for-beginners/url-rewriting-for-beginners/


text:
Q: CSS specific alignment need I am quite new to html/css, and I spent some time writing my own website from scratch. I have understood the very basics of the thing, but many subtleties are still unclear in my mind. Currently, I am unable to achieve a specific feature on my website, and I was hoping that maybe some of you would come up with a simple solution.
Here is what my website looks like: the colors are here to make things clearer. The four blocks "converge" toward the focal point. The top left part "Research interests" is dedicated to contain short descriptions, while the top right part "PhD thesis" is dedicated to contain either large texts or pictures. From now on, I will only focus on the top right part, where my problem occurs.
Green part :
#maindisplay
{
    display: inline-block;
    position: relative;
    text-align: left;
    width: 66.6%;
    height: 80.0%;
    float: right;
    background-color: green;
}

Red part :
#maindisplay article
{
    background-color: red;
    font-family: Conv_verdana, sans-serif;
    display: inline-block;
    position: relative;
    margin-left: 1.5%;
    top: 10%;
    width: 70.0%;
    height: 75.0%;
    overflow: auto;
}

Dark gray part :
#maindisplay p
{
    background-color: gray;
    font-weight: normal;
    font-size: 90%;
    position: absolute;
    bottom: -30px;
}

I get my bottom alignment for the #maindisplay paragraphs by absolute positioning them inside the relative positioned article (and therefore, the "overflow: auto;" is here totally useless). When the text is short enough, this works like a charm and the result is exactly what I want it to be. However, when the text is longer, or when the screen is smaller (typically, my laptop), I would like things to look like this : the top of the text appears first, and a scroll bar is available. When the text is scrolled to the bottom, the bottom of the scrolled text is aligned with the bottom of the top left part, as it is in the first picture. This is achieved by setting :
#maindisplay p
{
    background-color: gray;
    font-weight: normal;
    font-size: 90%;
    position: relative;
    margin: 0;
    padding: 0;
    bottom: 0;
}

So here is my problem : I would like the first behavior when the text is short enough, and the second behavior when it is longer than the #maindisplay article div. I was hoping that this could be done in a css-only way but I have looked for quite some time and now I am unsure about this (please note that I know precisely nothing about the javascript/jquery stuff). I am not allergic to tables, but I just don't see how to use them here.
Please let me know if there is anything unclear about this, and thanks in advance for your answers !

A: here's a fiddle making what you need http://jsfiddle.net/7N6Gp/ or http://jsfiddle.net/7N6Gp/1/
you need 2 div's for this one
the holder div that has position: relative;
.holder {
    width: 500px;
    height: 500px;
    position: relative;
}

and a content div that has overflow: auto and max-height
.content {
    width: 500px;
    max-height: 500px;
    overflow: auto;
    position: absolute;
    bottom: 0;
    left: 0;
}

with your code . you need to wrap content in a div not p . p should only contain text or inline elements . and from your pictures it looks like it contains titles and other paragraphs (block elements)
#maindisplay p change into #maindisplay div.content


text:
Q: how to fix Unknown error in my emulator when running react native project How to fix Unknown error in my emulator when running react native project?
My project was good 2 minutes ago.
but I run it again, and i get this error in my emulator

A: i fix my error
and i had a mistake from in my file( just would put a "," in my file)
thanks


text:
Q: Python calculation issue for certain numbers I'm using Odoo 10 and I have met some rounding issue with calculation using Python.
For example:
My formula is:
a = 224.689511
b = 195.382186
c = 1000

return round((a - b) * c, 2)

The return value is 29307.32
But the correct value is 29307.33
Value before rounding is 29307.324999999997 but it should be 29307.325
Is there any solution for this kind of case?

A: 29307.325 rounds up to 29307.33, since you want only 2 decimal places


text:
Q: Making new list of Object Attribute then calling each attribute with a incrementing int variable This might be a stupid question but I am new to C# coding and object-oriented programming. I'm trying to assign strings to a Class attribute while using an incrementing variable called "x".
But after increment x once, C# tells me "System.ArgumentOutOfRangeException: 'Index was out of range".
I just not getting it, it should be able to create a lot of clients with this.
        int x = 0;
        private void buttonSubmit_Click(object sender, EventArgs e)
        {

            List<Client> newClient = new List<Client>();  //creates a variable called "newClient" which is a list of Client object
            newClient.Add(new Client());                  // calling a constructor to create a Client Object
            newClient[x].Name = textBoxName.Text;         //newclient[0]
            newClient[x].Address = textBoxAddress.Text;
            newClient[x].Birthday = textBoxBirthDay.Text;
            newClient[x].Gender = textBoxGender.Text;
            newClient[x].PhoneNumber = textBoxPhoneNumber.Text;
            newClient[x].Income = textBoxIncome.Text;

            string Output = newClient[x].Name + " " + newClient[x].Address + " " + newClient[x].birthday + " " + newClient[x].Gender + " " + newClient[x].PhoneNumber + " " + newClient[x].Income;
            labelOutput.Text += Output + "\n";
            x++;
        }

A: I edit your function to works as you want !!!!
    List<Client> newClient = new List<Client>();  //creates a variable called "newClient" which is a list of Client object
    private void buttonSubmit_Click(object sender, EventArgs e)
    {

        var tobeInsertedClient = new Client()
        {
            Name = textBoxName.Text,
            Address = textBoxAddress.Text,
            Birthday = textBoxBirthDay.Text,
            Gender = textBoxGender.Text,
            PhoneNumber = textBoxPhoneNumber.Text,
            Income = textBoxIncome.Text
        };
        newClient.Add(tobeInsertedClient);

        string Output = tobeInsertedClient.Name + " " + tobeInsertedClient.Address + " " + tobeInsertedClient.birthday + " " + tobeInsertedClient.Gender + " " + tobeInsertedClient.PhoneNumber + " " + tobeInsertedClient.Income;
        labelOutput.Text += Output + "\n";
    }

You can Initialize an object with brackets {} and then you can use it in the scope you want :D


text:
Q: Remote debug Azure web job with .NET 6 in Visual Studio 2022 I followed this tutorial to create a simple web job in Azure: https://learn.microsoft.com/en-us/azure/app-service/webjobs-sdk-get-started. The web job itself does its job, consumes the message in the queue and I see them appear in Application Insights.
However, I want to debug the function on my local machine by using the tools available in Visual Studio 2022.
I have published with following profile settings:

Next I've attached the debugger under het Hosting menu:

First thing I noticed is a message about no symbols being loaded when putting a breakpoint in the function:

When I add a message to my queue, it gets consumed by the web job but the breakpoint is never hit. I've been reading a lot of similar questions regarding a this issue but I'm not progressing any further.

*

*In Azure Portal, I've enabled Remote debugging under Configuration > general settings

*In Visual Studio 2022, I checked if the correct process is attached

Here I'm a bit confused thou, the connection target is connecting through port 4024, which is according to this document, the port for Visual Studio 2019. However, a connection target with port 4026 is not found.
What am I missing here? Am I forgetting another setting somewhere?
If have tried changing the stack setting .NET version from APS.NET V4.8 to NET 6 (LTS) but that didn't help.

Should the platform architecture match the architecture of my machine in order to get it to work? Or is this not linked in any way with the debugger?

Is there anything else that I should check or try? Because my hair is turning grey here :)

A: Apologies for the delay here!
It should be 4024 for both 32 and 64 bit.
See this Azure doc: Remote Debugger Ports on Microsoft Azure App Service
Typically, the error "The breakpoint will not currently be hit. No symbols have been loaded for this document." -- This error message indicates we can start debug process and attach, but cannot set a breakpoint on any or some lines of code in the project.
Most, likely cause:  Application is built without debug symbols or debug symbols are not available
Kindly try these steps:

*

*Verify Debug Symbols are being used and published and in sync

*Workaround the issue by disabling "Enable Just My Code" from the
Tools >> Options >> Debugging >> general menu in Visual Studio

Other things to narrow-down the issue:

*

*Debug symbols must be available locally or deployed to the Azure App Service, and must match the local code you are trying to debug.

*It is recommended to use Cloud Explorer over Server Explorer to
connect and debug which requires the Azure SDK.

*You could optionally Manually Attach a Debugger to Azure Web Apps to troubleshoot this further or recommend this as a workaround.
(old blog, try similar steps)

*Kindly verify the port (Visual Studio remote debugger port assignments ) required is open in the corporate firewall and on your local machine.
As a test, you may use tool like Wireshark/netmon, to see if the port successfully connects to the port (4024) needed by the process.


text:
Q: Android Compass that can Compensate for Tilt and Pitch I'm trying to make a application on my Android phone (Nexus 4), which will be used in a model boat. I've added low pass filters to filter out the gitter from the sensors.
However, the compass is only stable when the phone is flat on its back. If I tilt it up, (such as turning a page of a booK), then the compass heading goes way off - as much as 50*.
I've tried this with Sensor.TYPE_MAGNETIC_FIELD with either Sensor.TYPE_GRAVITY and Sensor.TYPE_ACCELEROMETER and the effect is the same.
I've used the solution mentioned here, and many other places. My maths is not great but this must be a common problem and I find it frustrating that there is not an API to deal with it.
I've been working on this problem for 3 days and have still not found any solution, but when I use the Compass from Catch, theirs stays stable no matter how much the phone is inclined. So I know it must be possible.
All I want to do is create a compass that if the phone is pointing say north, then the compass will read north, and not jump around when the phone is moved through any other axis (roll or pitch).
Can anyone please help before I have to abandon my project.
Thanks,
Adam

A: By co-incidence I've been thinking about this problem for several weeks, because
*
*As a mathematician, I haven't been satisfied by any of the answers that I've seen suggested elsewhere; and
*I need a good answer for an app that I'm working on.So over the last couple of days I've come up with my own way of calculating the azimuth value for use in a compass.
I've put that maths that I'm using here on math.stackexchange.com, and I've pasted the code I've used below.  The code calculates the azimuth and pitch from the raw TYPE_GRAVITY and TYPE_MAGNETIC_FIELD sensor data, without any API calls to e.g.  SensorManager.getRotationMatrix(...) or SensorManager.getOrientation(...).  The code could probably be improved e.g. by using a low pass filter if the inputs turn out to be a bit erratic.  Note that the code records the accuracy of the sensors via the method onAccuracyChanged(Sensor sensor, int accuracy), so if the azimuth seems unstable another thing to check is how accurate each sensor is.  In any case, with all the calculations explicitly visible in this code, if there are instability problems (when the sensor accuracy is reasonable) then they could be tackled by looking at the instabilities in the inputs or in the direction vectors m_NormGravityVector[], m_NormEastVector[] or m_NormNorthVector[].
I'd be very interested in any feedback that anyone has for me on this method.  I find that it works like a dream in my own app, as long as the device is flat face up, vertical, or somewhere in between.  However, as I mention in the math.stackexchange.com article, there are issues that arise as the device gets close to being turned upside down.  In that situation, one would need to define carefully what behaviour one wants.
    import android.app.Activity;
    import android.hardware.Sensor;
    import android.hardware.SensorEvent;
    import android.hardware.SensorEventListener;
    import android.hardware.SensorManager;
    import android.view.Surface;

    public static class OrientationSensor implements  SensorEventListener {

    public final static int SENSOR_UNAVAILABLE = -1;

    // references to other objects
    SensorManager m_sm;
    SensorEventListener m_parent;   // non-null if this class should call its parent after onSensorChanged(...) and onAccuracyChanged(...) notifications
    Activity m_activity;            // current activity for call to getWindowManager().getDefaultDisplay().getRotation()

    // raw inputs from Android sensors
    float m_Norm_Gravity;           // length of raw gravity vector received in onSensorChanged(...).  NB: should be about 10
    float[] m_NormGravityVector;    // Normalised gravity vector, (i.e. length of this vector is 1), which points straight up into space
    float m_Norm_MagField;          // length of raw magnetic field vector received in onSensorChanged(...).
    float[] m_NormMagFieldValues;   // Normalised magnetic field vector, (i.e. length of this vector is 1)

    // accuracy specifications. SENSOR_UNAVAILABLE if unknown, otherwise SensorManager.SENSOR_STATUS_UNRELIABLE, SENSOR_STATUS_ACCURACY_LOW, SENSOR_STATUS_ACCURACY_MEDIUM or SENSOR_STATUS_ACCURACY_HIGH
    int m_GravityAccuracy;          // accuracy of gravity sensor
    int m_MagneticFieldAccuracy;    // accuracy of magnetic field sensor

    // values calculated once gravity and magnetic field vectors are available
    float[] m_NormEastVector;       // normalised cross product of raw gravity vector with magnetic field values, points east
    float[] m_NormNorthVector;      // Normalised vector pointing to magnetic north
    boolean m_OrientationOK;        // set true if m_azimuth_radians and m_pitch_radians have successfully been calculated following a call to onSensorChanged(...)
    float m_azimuth_radians;        // angle of the device from magnetic north
    float m_pitch_radians;          // tilt angle of the device from the horizontal.  m_pitch_radians = 0 if the device if flat, m_pitch_radians = Math.PI/2 means the device is upright.
    float m_pitch_axis_radians;     // angle which defines the axis for the rotation m_pitch_radians

    public OrientationSensor(SensorManager sm, SensorEventListener parent) {
        m_sm = sm;
        m_parent = parent;
        m_activity = null;
        m_NormGravityVector = m_NormMagFieldValues = null;
        m_NormEastVector = new float[3];
        m_NormNorthVector = new float[3];
        m_OrientationOK = false;
    }

    public int Register(Activity activity, int sensorSpeed) {
        m_activity = activity;  // current activity required for call to getWindowManager().getDefaultDisplay().getRotation()
        m_NormGravityVector = new float[3];
        m_NormMagFieldValues = new float[3];
        m_OrientationOK = false;
        int count = 0;
        Sensor SensorGravity = m_sm.getDefaultSensor(Sensor.TYPE_GRAVITY);
        if (SensorGravity != null) {
            m_sm.registerListener(this, SensorGravity, sensorSpeed);
            m_GravityAccuracy = SensorManager.SENSOR_STATUS_ACCURACY_HIGH;
            count++;
        } else {
            m_GravityAccuracy = SENSOR_UNAVAILABLE;
        }
        Sensor SensorMagField = m_sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        if (SensorMagField != null) {
            m_sm.registerListener(this, SensorMagField, sensorSpeed);
            m_MagneticFieldAccuracy = SensorManager.SENSOR_STATUS_ACCURACY_HIGH;
            count++;
        } else {
            m_MagneticFieldAccuracy = SENSOR_UNAVAILABLE;
        }
        return count;
    }

    public void Unregister() {
        m_activity = null;
        m_NormGravityVector = m_NormMagFieldValues = null;
        m_OrientationOK = false;
        m_sm.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent evnt) {
        int SensorType = evnt.sensor.getType();
        switch(SensorType) {
            case Sensor.TYPE_GRAVITY:
                if (m_NormGravityVector == null) m_NormGravityVector = new float[3];
                System.arraycopy(evnt.values, 0, m_NormGravityVector, 0, m_NormGravityVector.length);
                m_Norm_Gravity = (float)Math.sqrt(m_NormGravityVector[0]*m_NormGravityVector[0] + m_NormGravityVector[1]*m_NormGravityVector[1] + m_NormGravityVector[2]*m_NormGravityVector[2]);
                for(int i=0; i < m_NormGravityVector.length; i++) m_NormGravityVector[i] /= m_Norm_Gravity;
                break;
            case Sensor.TYPE_MAGNETIC_FIELD:
                if (m_NormMagFieldValues == null) m_NormMagFieldValues = new float[3];
                System.arraycopy(evnt.values, 0, m_NormMagFieldValues, 0, m_NormMagFieldValues.length);
                m_Norm_MagField = (float)Math.sqrt(m_NormMagFieldValues[0]*m_NormMagFieldValues[0] + m_NormMagFieldValues[1]*m_NormMagFieldValues[1] + m_NormMagFieldValues[2]*m_NormMagFieldValues[2]);
                for(int i=0; i < m_NormMagFieldValues.length; i++) m_NormMagFieldValues[i] /= m_Norm_MagField;
                break;
        }
        if (m_NormGravityVector != null && m_NormMagFieldValues != null) {
            // first calculate the horizontal vector that points due east
            float East_x = m_NormMagFieldValues[1]*m_NormGravityVector[2] - m_NormMagFieldValues[2]*m_NormGravityVector[1];
            float East_y = m_NormMagFieldValues[2]*m_NormGravityVector[0] - m_NormMagFieldValues[0]*m_NormGravityVector[2];
            float East_z = m_NormMagFieldValues[0]*m_NormGravityVector[1] - m_NormMagFieldValues[1]*m_NormGravityVector[0];
            float norm_East = (float)Math.sqrt(East_x * East_x + East_y * East_y + East_z * East_z);
            if (m_Norm_Gravity * m_Norm_MagField * norm_East < 0.1f) {  // Typical values are  > 100.
                m_OrientationOK = false; // device is close to free fall (or in space?), or close to magnetic north pole.
            } else {
                m_NormEastVector[0] = East_x / norm_East; m_NormEastVector[1] = East_y / norm_East; m_NormEastVector[2] = East_z / norm_East;

                // next calculate the horizontal vector that points due north
                float M_dot_G = (m_NormGravityVector[0] *m_NormMagFieldValues[0] + m_NormGravityVector[1]*m_NormMagFieldValues[1] + m_NormGravityVector[2]*m_NormMagFieldValues[2]);
                float North_x = m_NormMagFieldValues[0] - m_NormGravityVector[0] * M_dot_G;
                float North_y = m_NormMagFieldValues[1] - m_NormGravityVector[1] * M_dot_G;
                float North_z = m_NormMagFieldValues[2] - m_NormGravityVector[2] * M_dot_G;
                float norm_North = (float)Math.sqrt(North_x * North_x + North_y * North_y + North_z * North_z);
                m_NormNorthVector[0] = North_x / norm_North; m_NormNorthVector[1] = North_y / norm_North; m_NormNorthVector[2] = North_z / norm_North;

                // take account of screen rotation away from its natural rotation
                int rotation = m_activity.getWindowManager().getDefaultDisplay().getRotation();
                float screen_adjustment = 0;
                switch(rotation) {
                    case Surface.ROTATION_0:   screen_adjustment =          0;         break;
                    case Surface.ROTATION_90:  screen_adjustment =   (float)Math.PI/2; break;
                    case Surface.ROTATION_180: screen_adjustment =   (float)Math.PI;   break;
                    case Surface.ROTATION_270: screen_adjustment = 3*(float)Math.PI/2; break;
                }
                // NB: the rotation matrix has now effectively been calculated. It consists of the three vectors m_NormEastVector[], m_NormNorthVector[] and m_NormGravityVector[]

                // calculate all the required angles from the rotation matrix
                // NB: see https://math.stackexchange.com/questions/381649/whats-the-best-3d-angular-co-ordinate-system-for-working-with-smartfone-apps
                float sin = m_NormEastVector[1] -  m_NormNorthVector[0], cos = m_NormEastVector[0] +  m_NormNorthVector[1];
                m_azimuth_radians = (float) (sin != 0 && cos != 0 ? Math.atan2(sin, cos) : 0);
                m_pitch_radians = (float) Math.acos(m_NormGravityVector[2]);
                sin = -m_NormEastVector[1] -  m_NormNorthVector[0]; cos = m_NormEastVector[0] -  m_NormNorthVector[1];
                float aximuth_plus_two_pitch_axis_radians = (float)(sin != 0 && cos != 0 ? Math.atan2(sin, cos) : 0);
                m_pitch_axis_radians = (float)(aximuth_plus_two_pitch_axis_radians - m_azimuth_radians) / 2;
                m_azimuth_radians += screen_adjustment;
                m_pitch_axis_radians += screen_adjustment;
                m_OrientationOK = true;
            }
        }
        if (m_parent != null) m_parent.onSensorChanged(evnt);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        int SensorType = sensor.getType();
        switch(SensorType) {
            case Sensor.TYPE_GRAVITY: m_GravityAccuracy = accuracy; break;
            case Sensor.TYPE_MAGNETIC_FIELD: m_MagneticFieldAccuracy = accuracy; break;
        }
        if (m_parent != null) m_parent.onAccuracyChanged(sensor, accuracy);
    }
}

A: The problem you've got is probably Gimbal lock.  If you think about it, when the phone is upright so the pitch is plus or minus 90 degrees, then azimuth and roll are the same thing.  If you look into the maths, you'll see that in that situation either azimuth+roll or azimuth-roll is well defined, but they're not defined individually.  So when the pitch gets close to plus or minus 90 degrees the readings become unstable.  Some people choose to remap the co-ordinate system tom try and get round this, see e.g. How should I calculate azimuth, pitch, orientation when my Android device isn't flat?, so perhaps that might work for you.

A: This is an other way to get the magnetic heading without being affected by pitch or roll.
private final static double PI = Math.PI;
private final static double TWO_PI = PI*2;

 case Sensor.TYPE_ROTATION_VECTOR:
                float[] orientation = new float[3];
                float[] rotationMatrix = new float[9];

                SensorManager.getRotationMatrixFromVector(rotationMatrix, rawValues);
                SensorManager.getOrientation(rotationMatrix, orientation);

                float heading = mod(orientation[0] + TWO_PI,TWO_PI);//important
                //do something with the heading
                break;

private double mod(double a, double b){
        return a % b;
    }

A: OK, think I solved it.
Rather than using Sensor.TYPE_ACCELEROMETER (or TYPE_GRAVITY) and Sensor.TYPE_MAGNETIC_FIELD, I used Sensor.TYPE_ROTATION_VECTOR with:
float[] roationV = new float[16];
SensorManager.getRotationMatrixFromVector(roationV, rotationVector);

float[] orientationValuesV = new float[3];
SensorManager.getOrientation(roationV, orientationValuesV);

This returned a stable azimuth no matter the roll or pitch of the phone.
If you look here at the Android Motion Sensors, just beneath Table 1, it says that the ROTATION sensor is ideal for compass, augmented reality etc.
So easy when you know how.... However, I've yet to test this over time to see if errors are introduced.

A: Take a look at Mixare, an open source augmented reality tool for android and iphone, it has some great stuff in there about compensating the phones orientation/position to show things correctly on the screen.
EDIT: in particular take a look at the MixView java class which handles the sensor events.

A: i found that on certain smartphone models , the activation of the camera can change COMPASS datas... 1/10 grads... (related to light of the scene)
black scene... 1/2 .... very white scene (10 or more grads)


text:
Q: Retrieve a GoogleMap from a fragment in backstack I've a class "MainActivity" which calls the different fragments in particular a fragment which display a GoogleMap called MapsFragment.
When this fragment is called for the first time, I had some markers (which are refresh every timeToRefresh. The method startDrawingBomb() is called from the MainActivity class) and everything works perfectly when the user do not change to another fragment.
When a user ask to move to an other fragment I save the the MapsFragment created before in the backStack of the MainActivity (to retrieve it later)
The problem happens when I call this MapsFragment a second time, the fragment is displaying the map but not all the markers I've added before.
I imagine it's because the MapView, and the GoogleMap created by the MapsFragment are not the same as before.
My question is : How can I retrieve the map that I draw before easily ? Or I had to stop all my threads (in onPause() for example), create a new MapsFragment, obtain a new MapView, a new GoogleMap object and apply again all the previous threads ?
This is a part of my MapsFragment :
public class MapsFragment extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, LocationListener {

private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private OnMessageListener mCallback;
private GoogleMap _googleMap;
private MapView mMapView;
private ArrayList<Marker> markerArrayListScout = new ArrayList<>();
private ArrayList<Circle> markerArrayListBomb= new ArrayList<>();
private ArrayList<String> idToCircleId = new ArrayList<>();
private ArrayList<Integer> idArray = new ArrayList<>();

private boolean isfirstLocation = true;
boolean mustBeScoutLocationEnabled;
boolean mustDrawCircle;

public MapsFragment(){
    super();
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.v("MAPS_FRAGMENT","onCreate() called");
    mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
    mGoogleApiClient.connect();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log.v("MAPS_FRAGMENT","onCreateView() called");
    View rootView = inflater.inflate(R.layout.map, container, false);
    mMapView = (MapView) rootView.findViewById(R.id.mapView);
    mMapView.onCreate(savedInstanceState);
    mMapView.onResume(); // needed to get the map to display immediately
try {
        MapsInitializer.initialize(getActivity().getApplicationContext());
    } catch (Exception e) {
        e.printStackTrace();
    }
    mMapView.getMapAsync(this);
    return rootView;
}
@Override
public void onResume() {
    super.onResume();
    mMapView.onResume();
}

@Override
public void onPause() {
    super.onPause();
    mMapView.onPause();

}

@Override
public void onDestroy() {
    super.onDestroy();
    mMapView.onDestroy();
}

@Override
public void onLowMemory() {
    super.onLowMemory();
    mMapView.onLowMemory();
}
@Override
public void onMapReady(GoogleMap googleMap) {
    Log.v("MAPS_FRAGMENT","onMapReady() called");
    _googleMap = googleMap;
    _googleMap.setMyLocationEnabled(true);
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    Log.v("Location","onConnected");
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(1000); // Update location every second

        //Execute location service call if user has explicitly granted ACCESS_FINE_LOCATION..
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
}

@Override
public void onConnectionSuspended(int i) {
    Log.v("Location","onConnectionSuspended");
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.v("Location","onConnectionFailed");

}

@Override
public void onLocationChanged(Location location) {
    Log.v("Location","location : " + location.toString());
    // Add a marker and move the camera
    if(isfirstLocation) {
        LatLng currentLat = new LatLng(location.getLatitude(), location.getLongitude());
        _googleMap.moveCamera(CameraUpdateFactory.newLatLng(currentLat));
        _googleMap.moveCamera(CameraUpdateFactory.zoomTo(19));
        isfirstLocation = false;
    }
    //if(mCallback != null)
        mCallback.onUpdateLocation(location.getLatitude(),location.getLongitude());
}

/**
 * Draw Bomb and update its view all the timeToRefresh milliseconds.
 * @param timeToRefresh the time in milliseconds which the marker needs to refresh
 * @param id the id of the current bomb we need to work with
 */
public void startDrawingBomb(final int timeToRefresh,final int id){
    mustDrawCircle = true;
    Log.v("JOSE","passe1");
    final Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                while (mustDrawCircle) {
                    Log.v("JOSE","update bomb");
                    mCallback.updateBombs();
                    //Log.v("JOSE","bomb updated ?");
                    Thread.sleep(timeToRefresh);
        // This method is called from the MainActivity
                    final CircleOptions circleOptions = mCallback.drawBombCircle(id);
                    final String idToCompare = getIdCircle(id);
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            boolean isCenterSet = false;
                            if (circleOptions != null) {
                                Log.v("JOSE","size marker : " +markerArrayListBomb.size());
                                for(int i=0;i<markerArrayListBomb.size();i++){
                                    Log.v("JOSE","Id to compare : " +idToCompare);
                                    Log.v("JOSE","Id markearray : " +markerArrayListBomb.get(i).getId());
                                    if((markerArrayListBomb.get(i).getId()).equals(idToCompare)){
                                        // si c'est la même chose, il suffit de updater
                                        markerArrayListBomb.get(i).setCenter(circleOptions.getCenter());
                                        markerArrayListBomb.get(i).setVisible(true);
                                        isCenterSet = true;
                                    }
                                }
                                // il faut creer une nouvelle bombe
                                if(!isCenterSet) {
                                    Circle newCircle = _googleMap.addCircle(circleOptions);
                                    markerArrayListBomb.add(newCircle);
                                    newIdCircle(id, newCircle.getId());
                                    //Log.v("JOSE", "New bomb drawn id : " + newCircle.getId());
                                }

                            }
                        }
                    });
                }
                String idToCompare = getIdCircle(id);
                for(int i=0;i<markerArrayListBomb.size();i++){
                    if((markerArrayListBomb.get(i).getId()).equals(idToCompare)){
                        final int index = i;
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                markerArrayListBomb.get(index).setVisible(false);
                            }
                        });
                    }
                }
            }
            catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    });
    thread.start();
}
public void cancelDrawingBomb(){mustDrawCircle = false;}

// Container Activity must implement this interface
public interface OnMessageListener {
    public void onUpdateLocation(double lat,double lon);
    public void getAllOtherScoutsLocation();
    public void updateBombs();
    public CircleOptions drawBombCircle(int id);
}

/**
 *
 * @param id de la bombe dans la classe Bomb
 * @return le cercle créé associé. Sinon, return null
 */
private String getIdCircle(int id){
    if(idArray.size() == 0)
        return null;
    for(int i=0 ; i<idArray.size();i++){
        if(idArray.get(i) == id)
            return idToCircleId.get(i);
    }
    return null;
}

/**
 * Si une bombe est supprimée, il faut appeler cette méthode
 * @param id
 */
private void removeIdCircle(int id){
    for(int i=0 ; i<idArray.size();i++){
        if(idArray.get(i) == id) {
            idToCircleId.remove(i);
            idArray.remove(i);
        }
    }
}

/**
 * A appeler à chaque fois u'une bombe est créée
 * @param id l'id de la classe BOMB
 * @param ids l'id créé grâce à la classe Circle de google
 */
private void newIdCircle(int id,String ids){
    idToCircleId.add(ids);
    idArray.add(id);
}

}
And this how I called the second time my MapsFragment :
 if (id == R.id.map) {
        if(fragmentManager.findFragmentByTag(MAPS_FRAGMENT) != null){
            MapsFragment fragment =          (MapsFragment)fragmentManager.findFragmentByTag(MAPS_FRAGMENT);
            fragmentManager.beginTransaction().replace(R.id.frame_container, fragment,MAPS_FRAGMENT).addToBackStack(MAPS_FRAGMENT).commit();
        }
    }

Thanks a lot everyone, and sorry for my bad English.
If you want more information, or a better explanation, don't hesitate to tell me !

A: Implement save to bundle functionality at Onpause() for your MapFragment. Then in onCreateView() always check your bundle.
If the bundle is empty then it's a new fragment. If the bundle is not empty this means it was previously created.
Hope this helps :
For saving and restoring to bundle : Saving Android Activity state using Save Instance State


text:
Q: Why doesn't the import in the following Jupytor Notebook work?
So I used ! sys instead of use "pip" directly. From what I searched, this should be the best practice.
But the second cell doesn't print anything.
I got the code from this web, it should work. But can anyone tell me why it didn't.
geekforgeek

A: There shouldn't be a space between - and m:
python -m pip install thing
python - m pip install thing # NOT this

Otherwise the dash - will be treated as "read input from stdin", I presume.


text:
Q: SQL Server Query won't run I am connected to a remote SQL Server instance
These queries works fine:
SELECT COUNT(*) FROM Provider
SELECT TOP 1 * FROM Provider

but these don't
SELECT * FROM Provider
SELECT TOP 2 * FROM Provider

and return this error after a long delay:

Msg 64, Level 20, State 0, Line 0
  A transport-level error has occurred when receiving results from the
  server. (provider: TCP Provider, error: 0 - The specified network name
  is no longer available.)

What configuration should I be looking at that would allow a single row result but not a multiple row result?

A: I found the following
Hey mate, another thing to try i found the following and have included the URL for you. Considering the first bit of trouble shooting didn't work for you
Symptoms
The stack trace of the error resembles the following:
A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The specified network name is no longer available.)
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
   at System.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error)
   at System.Data.SqlClient.TdsParserStateObject.ReadSni(DbAsyncResult asyncResult, TdsParserStateObject stateObj)
   at System.Data.SqlClient.TdsParserStateObject.ReadPacket(Int32 bytesExpected)
   at System.Data.SqlClient.TdsParserStateObject.ReadBuffer()
   at System.Data.SqlClient.TdsParserStateObject.ReadByte()

Cause
The error is being caused by a timeout exception for long running queries. In previous versions of Visual Studio .NET, the exception was properly represented as a exception with a timeout description.
Resolution
Set the commandtimeout property of the command object to an appropriate value. Use a value of zero to wait without an exception being thrown.
Taken from https://support.microsoft.com/en-us/kb/555938


text:
Q: jQuery create div with elements from data I have a html template and im getting data with jquery post on page load. I want to create the template div with using foreach and as basic as i can. I mean i want to do it clean as much as i can. My data is an array of objects. Im getting my data with :
const emailData = async () => {
var offset = 0;
var limit = 10;
const values = {offset : offset, limit: limit}
  const res = await PostService.getCaseDetails(URL, values);
  res.forEach((obj) => {
    $('.ListLine').append(html(obj.id, obj.date, obj.from, obj.subject))
  }
)

}
My data is :
[
{
    "id": 1,
    "projectName": "Project Name 1",
    "date": "03.15.2021",
    "from": "Name 1",
    "subject": "Example folder",
    "lastLegalSituation": "DURUM"
},
{
    "id": 2,
    "projectName": "Project Name 2",
    "date": "03.15.2021",
    "from": "Name 2",
    "subject": "Example folder1",
    "lastLegalSituation": "DURUM"
},
{
    "id": 3,
    "projectName": "Project Name 3",
    "date": "03.15.2021",
    "from": "Name 3",
    "subject": "Example folder2",
    "lastLegalSituation": "DURUM"
}

]
And my template :

                                <input type="checkbox">

                    04.02.2020

                    First Name - Last Name

                    Example Folder

                        + New Mail

            Yanıtla
            Tümünü yanıtla
            Sil

What I tried to do :
  const html = (id, date, from, subject) => {
return (
  "
\n' +
  "\n" +
  '
\n' +
  '                        \n' +
  '
\n' +
  "                                \n" +
  '                                    <input type="checkbox">\n' +
  '                                    \n' +
  "                                " +
  "
\n" +
  "                        \n" +
  '                    \n' +
  date +
  "                        \n" +
  '                    \n' +
  from +
  "                        \n" +
  '                    \n' +
  subject +
  "                        \n" +
  "\n" +
  '                    \n' +
  "                            + Yeni Mail\n" +
  "                        \n" +
  "\n" +
  "
\n" +
  "
\n" +
  '
\n' +
  "                \n" +
  "                \n" +
  "                \n" +
  "
\n" +
  '
\n' +
  '                Yanıtla\n' +
  '                Tümünü yanıtla\n' +
  '                Sil\n' +
  "
"
);
};

Any helps will be thankful.

A: You could use template literals with ease.
Template literals (Template strings)
const html = (id, date, from, subject) => {
    return `

                        <input type="checkbox">

            ${date}
            ${from}
            ${subject}
            Yeni Mail

        Yanıtla
        Tümünü yanıtla
        Sil

    `;
}


text:
Q: PHP development server on Windows fails to read environment variables I'm running PHP via command line as follows:
C:\PHP\5.6.4\php.exe -S localhost:8080 -t "C:\path\to\dir"

Having before that created an environment variable, APPLICATION_ENV. Attempting to see it in PowerShell gives me:
PS C:\Users\Eyas> $env:APPLICATION_ENV
development

Yet, when I look at $_ENV and $_SERVER via print_r, all I get is:
# $_ENV
Array
(
[ALLUSERSPROFILE] => [...]
[APPDATA] => [...]
...
[COMPUTERNAME] => [...]
[ComSpec] => C:\WINDOWS\system32\cmd.exe
...
[HOME] => [...]
[HOMEDRIVE] => [...]
[HOMEPATH] => [...]
[LOCALAPPDATA] => [...]
...
[Path] => [...]
...
[ProgramData] => C:\ProgramData
[ProgramFiles] => C:\Program Files (x86)
[ProgramFiles(x86)] => C:\Program Files (x86)
[ProgramW6432] => C:\Program Files
[PSModulePath] => C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\
[PUBLIC] => C:\Users\Public
[SESSIONNAME] => Console
[SystemDrive] => C:
[SystemRoot] => C:\WINDOWS
[TEMP] => [...]
[TMP] => [...]
[USERDOMAIN] => [...]
[USERDOMAIN_ROAMINGPROFILE] => [...]
[USERNAME] => [...]
[USERPROFILE] => [...]
[VS110COMNTOOLS] => C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools\
[VS120COMNTOOLS] => C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\
[windir] => C:\WINDOWS
[__COMPAT_LAYER] => DetectorsWin7
)

# $_SERVER
Array
(
[DOCUMENT_ROOT] => [...]
[REMOTE_ADDR] => ::1
[REMOTE_PORT] => 44786
[SERVER_SOFTWARE] => PHP 5.6.4 Development Server
[SERVER_PROTOCOL] => HTTP/1.1
[SERVER_NAME] => localhost
[SERVER_PORT] => 8080
[REQUEST_URI] => [...]
[REQUEST_METHOD] => GET
[SCRIPT_NAME] => [...]
[SCRIPT_FILENAME] => [...]
[PHP_SELF] => [...]
[HTTP_HOST] => localhost:8080
[HTTP_CONNECTION] => keep-alive
[HTTP_CACHE_CONTROL] => max-age=0
[HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
[HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36
[HTTP_ACCEPT_ENCODING] => gzip, deflate, sdch
[HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.8,ar;q=0.6,de;q=0.4
[HTTP_COOKIE] => _ga=GA1.1.750333862.1419043051
[REQUEST_TIME_FLOAT] => 1421118347.0132
[REQUEST_TIME] => 1421118347
[argv] => Array
    (
    )

[argc] => 0
)

Further, getenv("APPLICATION_ENV") returns an empty result.
What could the problem be?

A: Looks like I was restarting php.exe and re-launching it from a process that I haven't relaunched after changing my environment variable. Therefore, when launching the process, php.exe got the environment of its parent (spawning) process, and did not reload the environment variables.
In my case I was using PhpStorm, restarting that allowed me to see my new environment variable.


text:
Q: Regex to validate Uniform Type Identifier Uniform Type Identifiers (UTIs) are the modern method to identify file types on Mac OS X.  In Apple's documentation it says:

A UTI is defined as a string (CFString) that follows a reverse Domain
  Name System (DNS) convention.

However, the UTI-related functions in LaunchServices do not provide any method to validate a UTI, i.e. check whether a given string is a UTI and conforms to the UTI string format (i.e. uses only legal characters, etc.).
The Wikipedia page on UTIs says:

UTIs use a reverse-DNS naming structure. Names may include the ASCII
  characters A-Z, a-z, 0-9, hyphen ("-"), and period ("."), and all
  Unicode characters above U+007F.[1] Colons and slashes are prohibited
  for compatibility with Macintosh and POSIX file path conventions.

What would a regex to validate a UTI look like?

A: Through some further searching I found this on the Reverse domain name notation Wikipedia page:
^[A-Za-z]{2,6}((?!-)\\.[A-Za-z0-9-]{1,63}(?<!-))+$

Concocted the following function to validate an NSString containing a UTI:
BOOL UTTypeIsValid(NSString *inUTI) {
    NSString *reverseDNSRegEx = @"^[A-Za-z]{2,6}((?!-)\\.[A-Za-z0-9-]{1,63}(?<!-))+$";
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", reverseDNSRegEx];
    return [test evaluateWithObject:inUTI];
}


text:
Q: Using google map into excel This is my first question so I am re-editing to better suit the culture here in stack overflow!
I recently found the API below that helps me plan out my trips/stops for a wide range of activities. It gives me the distance, directions, and time on excel! I have a wide variety of address that I use and I need the data of each in an excel format.
Problem: I have a problem where I want to find out my time/duration to get to a certain location to the next based on the time and day. For example if i want to depart toronto at 4:00pm to get to chicago, how long will that take based on the average traffic records.
This is pretty relevant to others who are in need of geocoding information on their excel! I am not very familiar with programming,vba, and sql but i definitely want to get into it so this is a good stepping stone to learn some cool stuff!
' Usage :
' GetGoogleTravelTime (strFrom, strTo) returns a string containing journey duration : hh:mm
' GetGoogleDistance (strFrom, strTo) returns a string containing journey distance in either miles or km (as defined by strUnits)
' GetGoogleDirections (strFrom, strTo) returns a string containing the directions
'
' where strFrom/To are address search terms recognisable by Google
' i.e. Postcode, address etc.
'
'
Const strUnits = "imperial" ' imperial/metric (miles/km)

Function CleanHTML(ByVal strHTML)
'Helper function to clean HTML instructions
Dim strInstrArr1() As String
Dim strInstrArr2() As String
Dim s As Integer

strInstrArr1 = Split(strHTML, "<")
For s = LBound(strInstrArr1) To UBound(strInstrArr1)
   strInstrArr2 = Split(strInstrArr1(s), ">")
   If UBound(strInstrArr2) > 0 Then
        strInstrArr1(s) = strInstrArr2(1)
   Else
        strInstrArr1(s) = strInstrArr2(0)
   End If
Next

CleanHTML = Join(strInstrArr1)
End Function

Public Function formatGoogleTime(ByVal lngSeconds As Double)
'Helper function. Google returns the time in seconds, so this converts it into time format hh:mm

Dim lngMinutes As Long
Dim lngHours As Long

lngMinutes = Fix(lngSeconds / 60)
lngHours = Fix(lngMinutes / 60)
lngMinutes = lngMinutes - (lngHours * 60)

formatGoogleTime = Format(lngHours, "00") & ":" & Format(lngMinutes, "00")
End Function

Function gglDirectionsResponse(ByVal strStartLocation, ByVal strEndLocation, ByRef strTravelTime, ByRef strDistance, ByRef strInstructions, Optional ByRef strError = "") As Boolean
On Error GoTo errorHandler
' Helper function to request and process XML generated by Google Maps.

Dim strURL As String
Dim objXMLHttp As Object
Dim objDOMDocument As Object
Dim nodeRoute As Object
Dim lngDistance As Long

Set objXMLHttp = CreateObject("MSXML2.XMLHTTP")
Set objDOMDocument = CreateObject("MSXML2.DOMDocument.6.0")

strStartLocation = Replace(strStartLocation, " ", "+")
strEndLocation = Replace(strEndLocation, " ", "+")

strURL = "http://maps.googleapis.com/maps/api/directions/xml" & _
            "?origin=" & strStartLocation & _
            "&destination=" & strEndLocation & _
            "&sensor=false" & _
            "&units=" & strUnits   'Sensor field is required by google and indicates whether a Geo-sensor is being used by the device making the request

'Send XML request
With objXMLHttp
    .Open "GET", strURL, False
    .setRequestHeader "Content-Type", "application/x-www-form-URLEncoded"
    .Send
    objDOMDocument.LoadXML .ResponseText
End With

With objDOMDocument
    If .SelectSingleNode("//status").Text = "OK" Then
        'Get Distance
        lngDistance = .SelectSingleNode("/DirectionsResponse/route/leg/distance/value").Text ' Retrieves distance in meters
        Select Case strUnits
            Case "imperial": strDistance = Round(lngDistance * 0.00062137, 1)  'Convert meters to miles
            Case "metric": strDistance = Round(lngDistance / 1000, 1) 'Convert meters to miles
        End Select

        'Get Travel Time
        strTravelTime = .SelectSingleNode("/DirectionsResponse/route/leg/duration/value").Text  'returns in seconds from google
        strTravelTime = formatGoogleTime(strTravelTime) 'converts seconds to hh:mm

        'Get Directions
        For Each nodeRoute In .SelectSingleNode("//route/leg").ChildNodes
            If nodeRoute.BaseName = "step" Then
                strInstructions = strInstructions & nodeRoute.SelectSingleNode("html_instructions").Text & " - " & nodeRoute.SelectSingleNode("distance/text").Text & vbCrLf
            End If
        Next

        strInstructions = CleanHTML(strInstructions) 'Removes MetaTag information from HTML result to convert to plain text.

    Else
        strError = .SelectSingleNode("//status").Text
        GoTo errorHandler
    End If
End With

gglDirectionsResponse = True
GoTo CleanExit

errorHandler:
    If strError = "" Then strError = Err.Description
    strDistance = -1
    strTravelTime = "00:00"
    strInstructions = ""
    gglDirectionsResponse = False

CleanExit:
    Set objDOMDocument = Nothing
    Set objXMLHttp = Nothing

End Function

Function getGoogleTravelTime(ByVal strFrom, ByVal strTo) As String
'Returns the journey time between strFrom and strTo

Dim strTravelTime As String
Dim strDistance As String
Dim strInstructions As String
Dim strError As String

If gglDirectionsResponse(strFrom, strTo, strTravelTime, strDistance, strInstructions, strError) Then
    getGoogleTravelTime = strTravelTime
Else
    getGoogleTravelTime = strError
End If

End Function

Function getGoogleDistance(ByVal strFrom, ByVal strTo) As String
'Returns the distance between strFrom and strTo
'where strFrom/To are address search terms recognisable by Google
'i.e. Postcode, address etc.

Dim strTravelTime As String
Dim strDistance As String
Dim strError As String
Dim strInstructions As String

If gglDirectionsResponse(strFrom, strTo, strTravelTime, strDistance, strInstructions, strError) Then
    getGoogleDistance = strDistance
Else
    getGoogleDistance = strError
End If

End Function

Function getGoogleDirections(ByVal strFrom, ByVal strTo) As String
'Returns the directions between strFrom and strTo
'where strFrom/To are address search terms recognisable by Google
'i.e. Postcode, address etc.

Dim strTravelTime As String
Dim strDistance As String
Dim strError As String
Dim strInstructions As String

If gglDirectionsResponse(strFrom, strTo, strTravelTime, strDistance, strInstructions, strError) Then
    getGoogleDirections = strInstructions
Else
    getGoogleDirections = strError
End If

End Function

Anything would help.

A: I hope it helps.
This works by using an API so that you are able to get Google map's information through those functions.
' Usage :
' GetGoogleTravelTime (strFrom, strTo) returns a string containing journey duration : hh:mm
' GetGoogleDistance (strFrom, strTo) returns a string containing journey distance in either miles or km (as defined by strUnits)
' GetGoogleDirections (strFrom, strTo) returns a string containing the directions
'
' where strFrom/To are address search terms recognisable by Google
' i.e. Postcode, address etc.
'
' by Desmond Oshiwambo

Const strUnits = "imperial" ' imperial/metric (miles/km)

Function CleanHTML(ByVal strHTML)
'Helper function to clean HTML instructions
Dim strInstrArr1() As String
Dim strInstrArr2() As String
Dim s As Integer

strInstrArr1 = Split(strHTML, "<")
For s = LBound(strInstrArr1) To UBound(strInstrArr1)
 strInstrArr2 = Split(strInstrArr1(s), ">")
   If UBound(strInstrArr2) > 0 Then
        strInstrArr1(s) = strInstrArr2(1)
   Else
        strInstrArr1(s) = strInstrArr2(0)
   End If
Next

CleanHTML = Join(strInstrArr1)
End Function

Public Function formatGoogleTime(ByVal lngSeconds As Double)
'Helper function. Google returns the time in seconds, so this converts it into time format hh:mm

Dim lngMinutes As Long
Dim lngHours As Long

lngMinutes = Fix(lngSeconds / 60)
lngHours = Fix(lngMinutes / 60)
lngMinutes = lngMinutes - (lngHours * 60)

formatGoogleTime = Format(lngHours, "00") & ":" & Format(lngMinutes, "00")
End Function

Function gglDirectionsResponse(ByVal strStartLocation, ByVal strEndLocation, ByRef strTravelTime, ByRef strDistance, ByRef strInstructions, Optional ByRef strError = "") As Boolean
On Error GoTo errorHandler
' Helper function to request and process XML generated by Google Maps.

Dim strURL As String
Dim objXMLHttp As Object
Dim objDOMDocument As Object
Dim nodeRoute As Object
Dim lngDistance As Long

Set objXMLHttp = CreateObject("MSXML2.XMLHTTP")
Set objDOMDocument = CreateObject("MSXML2.DOMDocument.6.0")

strStartLocation = Replace(strStartLocation, " ", "+")
strEndLocation = Replace(strEndLocation, " ", "+")

strURL = "http://maps.googleapis.com/maps/api/directions/xml" & _
            "?origin=" & strStartLocation & _
            "&destination=" & strEndLocation & _
            "&sensor=false" & _
            "&units=" & strUnits   'Sensor field is required by google and indicates whether a Geo-sensor is being used by the device making the request

'Send XML request
With objXMLHttp
    .Open "GET", strURL, False
    .setRequestHeader "Content-Type", "application/x-www-form-URLEncoded"
    .send
    objDOMDocument.LoadXML .responseText
End With

With objDOMDocument
    If .SelectSingleNode("//status").Text = "OK" Then
        'Get Distance
        lngDistance = .SelectSingleNode("/DirectionsResponse/route/leg/distance/value").Text ' Retrieves distance in meters
        Select Case strUnits
            Case "imperial": strDistance = Round(lngDistance * 0.00062137, 1)  'Convert meters to miles
            Case "metric": strDistance = Round(lngDistance / 1000, 1) 'Convert meters to miles
        End Select

        'Get Travel Time
        strTravelTime = .SelectSingleNode("/DirectionsResponse/route/leg/duration/value").Text  'returns in seconds from google
        strTravelTime = formatGoogleTime(strTravelTime) 'converts seconds to hh:mm

        'Get Directions
        For Each nodeRoute In .SelectSingleNode("//route/leg").ChildNodes
            If nodeRoute.BaseName = "step" Then
                strInstructions = strInstructions & nodeRoute.SelectSingleNode("html_instructions").Text & " - " & nodeRoute.SelectSingleNode("distance/text").Text & vbCrLf
            End If
        Next

        strInstructions = CleanHTML(strInstructions) 'Removes MetaTag information from HTML result to convert to plain text.

    Else
        strError = .SelectSingleNode("//status").Text
        GoTo errorHandler
    End If
End With

gglDirectionsResponse = True
GoTo CleanExit

errorHandler:
    If strError = "" Then strError = Err.Description
    strDistance = -1
    strTravelTime = "00:00"
    strInstructions = ""
    gglDirectionsResponse = False

CleanExit:
    Set objDOMDocument = Nothing
    Set objXMLHttp = Nothing

End Function

Function getGoogleTravelTime(ByVal strFrom, ByVal strTo) As String
'Returns the journey time between strFrom and strTo

Dim strTravelTime As String
Dim strDistance As String
Dim strInstructions As String
Dim strError As String

If gglDirectionsResponse(strFrom, strTo, strTravelTime, strDistance, strInstructions, strError) Then
    getGoogleTravelTime = strTravelTime
Else
    getGoogleTravelTime = strError
End If

End Function

Function getGoogleDistance(ByVal strFrom, ByVal strTo) As String
'Returns the distance between strFrom and strTo
'where strFrom/To are address search terms recognisable by Google
'i.e. Postcode, address etc.

Dim strTravelTime As String
Dim strDistance As String
Dim strError As String
Dim strInstructions As String

If gglDirectionsResponse(strFrom, strTo, strTravelTime, strDistance, strInstructions, strError) Then
    getGoogleDistance = strDistance
Else
    getGoogleDistance = strError
End If

End Function

Function getGoogleDirections(ByVal strFrom, ByVal strTo) As String
'Returns the directions between strFrom and strTo
'where strFrom/To are address search terms recognisable by Google
'i.e. Postcode, address etc.

Dim strTravelTime As String
Dim strDistance As String
Dim strError As String
Dim strInstructions As String

If gglDirectionsResponse(strFrom, strTo, strTravelTime, strDistance, strInstructions, strError) Then
    getGoogleDirections = strInstructions
Else
    getGoogleDirections = strError
End If

End Function
Public Function ACOF(Rango As Range) As Variant
 Dim x(), y(), z() As Variant
 Dim i, n, mu, k, j As Double
  n = Rango.Rows.Count
  mu = Application.Average(Rango)
  k = 1
  ReDim z(n - k)
 Do Until k = n - 1
 ReDim x(n - k), y(n - k)
   For i = 1 To n - k Step 1
    x(i) = Rango(i) - mu
    y(i) = Rango(i + k) - mu
   Next i
z(k) = Application.Correl(x, y) 'Application.SumProduct(x, y) / Application.DevSq(Rango)
 k = k + 1
Loop
ACOF = Application.Transpose(z)
End Function

Public Function JBTEST(Rango As Range, p As Double) As Variant
 If IsNull(Rango) Then
  MsgBox prompt:="Introduce un rango válido"
   End If
 Dim s, k, n As Double
  s = Application.Skew(Rango)
  k = Application.Kurt(Rango)
  n = Rango.Rows.Count
   JBTEST = Application.ChiDist((n - p + 1) / 6 * (s ^ 2 + 1 / 4 * (k - 3) ^ 2), 2)

End Function

Function IFERROR(ByRef ToEvaluate As Variant, ByRef Default As Variant) As Variant
    If IsError(ToEvaluate) Then
        IFERROR = Default
    Else
        IFERROR = ToEvaluate
    End If
End Function

Sub RegisterUDF()
    Dim s As String
    s = "Provides a shortcut replacement for the common worksheet construct" & vbLf _
    & "IF(ISERROR(<expression>, <default>, <expression>)"

    Application.MacroOptions Macro:="IFERROR", Description:=s, Category:=9
End Sub

Sub UnregisterUDF()
    Application.MacroOptions Macro:="IFERROR", Description:=Empty, Category:=Empty
End Sub


text:
Q: Removing multiple elements from a bash array based on different patterns So I have this:
INTERFACES=($(ip -o link show | awk -F': ' '{print $2}'))

Giving me an array of interfaces, however I want to remove the loopback and tun adapters from the array.
INTERFACES=(${INTERFACES[@]/lo/})
INTERFACES=(${INTERFACES[@]/tun*/})

Works, but is there a way to do this in a single line?
Probably super easy and derp, but I'd like to understand how the expression actually works (google gave me 47239432 examples of the above but not one explained how it worked or gave an example of using more than one expression at a time).
I know this can be done with the awk command, so both a solution with awk and one with the array filter would be appreciated greatly :)
My apologies if this is a stupid question.

A: There are many ways to do this. One example:
# arr=(lo tun0 net1 net2)
# echo ${arr[@]}
lo tun0 net1 net2
# arr=( $( printf '%s\n' ${arr[@]} | egrep -v '^(lo|tun)' ) )
# echo ${arr[@]}
net1 net2
#

And you can also exclude these interfaces at the very beginning:
INTERFACES=( $(ip -o link show | awk -F': ' '$2 !~ /^(lo|tun)/ {print $2}') )


text:
Q: Stream iTunes TV shows to iPad? Is it possible to stream television programs from the iTunes store to an iPad, like you would do with an Apple TV, or is it only possible to watch them by downloading first?

A: You could start the download of the TV show on the iPad and then start watching it after a few minutes (depending in your connection speed) once its buffered enough.
To do this start the download in the iTunes app and the switch to the videos app and you can start watching, as it downloads it will fill in the time slider bar in white.
Then delete it after you've watched it. This is effectively streaming.
Hopefully the rumoured upcoming iTunes revamp, will include more natural streaming. It's likely though that there is no traditional streaming because of licensing issues.


text:
Q: iPhone simple commercial barcode reader via camera
Possible Duplicate:
Is there a barcode recognition framework for iOS?

I've done some iPhone programming (safely midlevel) and now a requirement has come up for us to write a barcode reader that uses the iPhone camera. This is not for shopping or the general public but will be for internal use. My first thought was to simply programatically take a picture, upload it to server, and have a web service or something similar handle the heavy lifting of extracting the numbers out of the bar code. However I recently installed some apps already available on the iPhone that read bar codes, refer you to shopping sites, etc. and they seem to use the video camera to identify barcodes and extract the numbers. Does anyone know how this is being done or could point me to some open source or sample code?

A: This looks helpful:
http://sourceforge.net/apps/mediawiki/zbar/index.php?title=HOWTO:_Add_a_barcode_reader_to_an_iPhone_app


text:
Q: Making a Synology diskstation accessible via WLAN tl;dr
What do I need to get a Synology DS214 locked in a cellar room to connect to my Wifi/ethernet/DSL router (to which the DS414 and the clients are connected via ethernet)?
The situation
I have a DS414 (connected to the client computers via a 10-port Netgear switch) which I would like to backup regularly to a DS214 that is locked in a cellar room. Pulling a cable down there would be an ordeal.
The DSL router (which is also hooked up to the switch) has support for 802.11 n/g/b enabled and working (connects a tablet, some IP cameras, and a BD-player).
The Diskstation software suggests you plug in a USB dongle and you magically have Wifi working, and the Synology site lists a hundred or so dongles that have been tested for compatibility. Most are "micro" or "ultra compact" dongles, but for example the TP-Link WN722N has a nice looking, big antenna. Since the signal has to go via 2 floors, a big antenna looks like a good idea.
The WN722N says "high gain" whereas the WN8200ND looks very similar but says "high gain, high power", which sounds like ("big antenna and big sender" as opposed to "big antenna only"). Also, it has 2 antennas which are even bigger, and 300Mbit/s instead of 150MBit/s.
Two antennas are better than one, and 300 is bigger than 150, so I bought the WN8200ND and two supplemental 8dBi antennas, because you know, bigger is aways better.
Of course that didn't work. Why did I expect it would.
The quest
How do I get this working? Plugging the WN8200ND into the disk station does exactly nothing (tried both of them, and tried the AVM DSL router, too).
My first impulse was to plug it into a Windows 8.1 tablet. Maybe you need to configure it once initially, enter the SSID password, whatever. That'll do.
After 2 seconds of automatic driver install without user intervention, Windows told me that I could press the WPS button on the router if there is one. Doing so zzzzzzzzzap... worked. Not a single thing to configure, ready to go in 2 seconds. Just what I expected, really.
Pulling the plug and putting it into the Diskstation makes the "connect to a network" button in the wireless setup screen enabled, but no matter what I try, nothing will happen.
I am fine loading a kernel module by hand or editing a config script on the disk station if that is necessary (but if "nothing happens" is the only information that you have, that's somewhat futile).
I am fine spending another 20 currency on buying a Wifi router or a Wifi access point, provided that that won't mean I have another blinking box standing around which does nothing useful.
Maybe I just bought the wrong thingie, it could be as simple as that.
My expectation is that an access point is a "black box" with an ethernet connector that (after given the SSID password) simply forwards what comes in on the ethernet cable onto the wireless network and vice versa, and doesn't need a Windows computer with a fitting driver or such.
In other words, I'd simply plug the diskstation into the access point, and have it accessible from two floors above. Though I'm not sure if that expectation will be met.
So, where do I go from here?


text:
Q: Using Redux, is it a bad practice to cancel a previous action in an action creator? I am creating a validator for a field and triggering validation on update. I only care about the validation result of the current state. So if another update is triggered before the validation completes, I don't want the validation success to occur for the old piece of data.
I have read and believe that accessing the store in an action creator is somewhat of an anti-pattern in https://stackoverflow.com/a/35674575/816584.
I currently have the following:
export const USERNAME_VALIDATION_PENDING = 'USERNAME_VALIDATION_PENDING';
export const USERNAME_VALIDATION_SUCCESS = 'USERNAME_VALIDATION_SUCCESS';
export const USERNAME_VALIDATION_FAILURE = 'USERNAME_VALIDATION_FAILURE';
export const USERNAME_VALIDATION_ABORTED = 'USERNAME_VALIDATION_PENDING';

export interface Validator {
    validate(subject: string): Promise<void, Error>;
    cancel();
}

const cache = new WeakMap();

function memoize(obj: {}, subject: string, result: Error | true) {
    const map: {[subject: string]: Error | true} = cache.has(obj) ?
        cache.get(obj) : {};

    // TODO: Do consider caching just the message so the stack can get GC
    map[subject] = result;
    cache.set(obj, map);
}

function resultCacheP(obj: {}, subject: string) {
    const map: {[subject: string]: Error | true} = cache.has(obj) ?
        cache.get(obj) : {};
    return Object.keys(map).indexOf(subject) !== -1;
}

function resultCache(obj: {}, subject: string) {
    const map: {[subject: string]: Error | true} = cache.has(obj) ?
        cache.get(obj) : {};

    return map[subject];
}

export function requestUsernameValidation(username: string, validator: Validator) {
    return {
        type: USERNAME_VALIDATION_PENDING,
        isValidating: true,
        isValid: false,
        username,
        validator,
    }
}

export function receiveUsernameValidationSuccess() {
    return {
        type: USERNAME_VALIDATION_SUCCESS,
        isValidating: false,
        isValid: true,
    }
}

export function receiveUsernameValidationFailure(error: string) {
    return {
        type: USERNAME_VALIDATION_FAILURE,
        isValidating: false,
        isValid: false,
        error,
    }
}

export function validateUsername(username: string, validator: Validator) {
    return (dispatch) => {
        dispatch(requestUsernameValidation(username, validator));

        if (resultCacheP(validator, username)) {
            const result = resultCache(validator, username);
            if (result instanceof Error) {
                dispatch(receiveUsernameValidationSuccess());
            } else {
                dispatch(receiveUsernameValidationFailure(result.message));
            }
        } else {
            validator.validate(username)
                .then(() => {
                    memoize(validator, username, true);
                    dispatch(receiveUsernameValidationSuccess());
                })
                .catch((err: Error) => {
                    memoize(validator, username, err);
                    dispatch(receiveUsernameValidationFailure(err.message));
                });
        }
    };
}

I would like for the requestUsernameValidation to call cancel on the validator from the previous action if my state is currently validating to avoid a race condition where the previous validator finishes later and incorrectly updates the state.
I think I need to change requestUsernameValidation to a thunk to get the current state.
This is my first attempt at using Redux. Most tutorials I've read have really lean action creators, but a lot of real world projects I've seen have a lot of complex logic in them. Is this approach the correct way to solve this?

A: Usually with input fields i would go with using a debounce method:
Quoting https://github.com/component/debounce

Creates and returns a new debounced version of the passed function that will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked.

for example if you do
let waitTime = 300;
const debouncedValidateUsername = debounce((username, validator) => dispatch => { ... })

The validation will happen only 300 milliseconds after the last change and you will have the latest user input
UPDATE
Inspired by this great answer you can do the following
let cancellationAmbassador = {
  cancel() {}
};

function validate(validator, username, cancellationAmbassador) {
  return new Promise((resolve, reject) => {
    validator
      .validate(username)
      .then(() => {
        resolve("valid");
      })
      .catch((err: Error) => {
        reject("invalid");
      });
    cancellationAmbassador.cancel = function() {
      reject("cancellation");
    };
  });
}

export function validateUsername(username: string, validator: Validator) {
  return dispatch => {
    cancellationAmbassador.cancel();
    dispatch(requestUsernameValidation(username, validator));
    if (resultCacheP(validator, username)) {
      const result = resultCache(validator, username);
      if (result instanceof Error) {
        dispatch(receiveUsernameValidationSuccess());
      } else {
        dispatch(receiveUsernameValidationFailure(result.message));
      }
    } else {
      validate(validator, username, cancellationAmbassador)
        .then(() => {
          memoize(validator, username, true);
          dispatch(receiveUsernameValidationSuccess());
        })
        .catch(reason => {
          if (reason !== "cancellation") {
            memoize(validator, username, err);
            dispatch(receiveUsernameValidationFailure(err.message));
          }
        });
    }
  };
}


text:
Q: Efficient and fair way to evenly distribute multiple items with various quantities I am developing small lottery games where the participant can win one of many gifts, each having various quantities. (The code is in PHP)
Simple scenario:
I have 5 types of gifts, 1000 in total, and am expecting 1000 participations.
What algorithm can I use to ensure that these 1000 gifts are distributed somewhat evenly. The time period doesn't matter.
Uneven: 2 drones given away first, then 10 tablets, etc...
| Title     | Quantity |
|-----------|----------|
| Drone     | 5        |
| Tablet    | 10       |
| Hotel     | 100      |
| Gift card | 200      |
| Coupon    | 685      |

More complex scenario:
I have the same gifts and gift quantities, but I anticipate 600 participations.
I wish for the drone, tablet, and hotel nights to be all given out by the 600th participation.
So there should be 400 (gift cards + coupons) left, and better if there's the same percentage left: 116 gift cards (200/685=29%) and 284 coupons (71%).
What I tried:
For the first scenario, I tried using these probabilities, and looping through the 5 gifts sequentially:
- Each gift has its own counter
- The gift's counter increases every time the gift is considered
- The gift is given if the gift's counter == originalQuantity
- The loop starts back from the drone when a gift is given
| Title     | Quantity | Probability                   |
|-----------|----------|-------------------------------|
| Drone     | 5        | 5/1000                        |
| Tablet    | 10       | 10/(1000-5)                   |
| Hotel     | 100      | 100/(1000-5-10)               |
| Gift card | 200      | 200/(1000-5-10-100)           |
| Coupon    | 685      | 685/(1000-5-10-100-200) = 1/1 |

This solution works, and by adding a coefficient to each gift (Drone, table and hotel must have 20% more chance to come out, and gift card and coupon 30% less chance), I could also handle the more complex scenario.
My question is: are there better, fairer, simpler ways to distribute these gifts ?
Edit 1: Even distribution would mean random, and have for example, after 20% of participation, have approximately 20% of each gifts given out (1 drone, 2 tablets, etc...)

A: You can just do it like the lottery: shuffle and pick. It is possible that the same kind of item is picked two or more times, just as it is possible that sequential rolls with dice yield the same number, that's how random works :-)
For the case where a number of prizes should be drawn until the 600th draw, put all of these prizes in a list together with enough of the other prizes to make 600, then shuffle that list. Shuffle the remaining 400 and concatenate the shuffled lists.


text:
Q: a Django URLField has fixed max_length as 200 characters link = models.URLField(max_length=500, blank=True, default='')

I have already set the max_length as 500, but every time I tried to set this field with url larger than 200 characters, it still threw an error saying that Ensure this value has at most 200 characters (it has 327). Is this a Django restriction or something I forgot to set up?

A: You forgot to actually update/migrate your database. This should happen upon initial syncdb, and ideally via a proper database migration using django-south in Django version up to 1.6, or using the new Django migrations framework to be released in Django 1.7+.
For development purposes you can reset your DB (this will delete all data!) and recreate:
$ ./manage.py reset appname
$ ./manage.py syncdb

If you're using South migrations:
$ ./manage.py schemamigration --auto appname
$ ./manage.py syncdb --migrate

A: I guess the problem is solved by now, but I ran into the same issue last week. While the answers regarding migrations are correct, it is worth noting that URLField is based on CharField. This means that the length limitations of CharField also apply to URLField, no matter what max_length you define (see also https://docs.djangoproject.com/en/3.0/ref/models/fields/#urlfield - this answer referred to Django 1.9 which was the latest release when I initially wrote it and this is still the same for Django 3.0 in 2020).
Somewhat unrelated to the original question, but a possible problem even if you use the default max_length=200 is how MySQL currently deals with UTF-8 text. You can find out more about this VARCHAR() indexing issue on https://serversforhackers.com/mysql-utf8-and-indexing or in the MySQL 5.7 manual on http://dev.mysql.com/doc/refman/5.7/en/charset-unicode-upgrading.html.
A possible solution for having a longer URLField has been posted in Advantages to using URLField over TextField? - simply define a Textfield with the relevant validator.