text:
Q: jQuery at the highlight paragraph it is adding again and again same text I have an input with type text which then I perform a click and the matcher text will be highlighted.
The highlighted works but for every paragraph it is adding a new paragraph with the same text.
Here you can find a jsfiddle which I have created and maybe it will help in my problem

$(document).ready(function() {
  $("#searchButton").click(function() {
    searchHighlight($("#search").val());
  });
});

function searchHighlight(searchText) {
  if (searchText) {
    var searchExp = new RegExp(searchText, "ig");
    var content = $('p').text();
    var matches = content.match(searchExp);
    if (matches) {
      $('p').html(content.replace(searchExp, function(match) {
        return "" + match + "";
      }));
    } else {
      $(".highlight").removeClass(".highlight");
    }
  } else {
    $(".highlight").removeClass(".highlight");
  }
}
.highlight {
  background: yellow;
  font-weight: bold;
}

  <form class="form-inline">
    Search

      <input id="search" type="text" class="form-control" placeholder="Highlight in text">

        <button class="btn btn-secondary" id="searchButton" onclick="selectText()" type="button">Search</button>

  </form>

Perceived end knowledge certainly day sweetness why cordially

As collected deficient objection by it discovery sincerity curiosity. Quiet decay who round three world whole has mrs man. Built the china there tried jokes which gay why. Assure in adieus wicket it is. But spoke round point and one joy. Offending her moonlight men sweetness see unwilling. Often of it tears whole oh balls share an.

Unpacked reserved sir offering bed judgment may and quitting speaking. Is do be improved raptures offering required in replying raillery. Stairs ladies friend by in mutual an no. Mr hence chief he cause. Whole no doors on hoped. Mile tell if help they ye full name.

Behaviour we improving at something to. Evil true high lady roof men had open. To projection considered it precaution an melancholy or. Wound young you thing worse along being ham. Dissimilar of favourable solicitude if sympathize middletons at. Forfeited up if disposing perfectly in an eagerness perceived necessary. Belonging sir curiosity discovery extremity yet forfeited prevailed own off. Travelling by introduced of mr terminated. Knew as miss my high hope quit. In curiosity shameless dependent knowledge up.

Sudden she seeing garret far regard. By hardly it direct if pretty up regret. Ability thought enquire settled prudent you sir. Or easy knew sold on well come year. Something consulted age extremely end procuring. Collecting preference he inquietude projection me in by. So do of sufficient projecting an thoroughly uncommonly prosperous conviction. Pianoforte principles our unaffected not for astonished travelling are particular.

Situation admitting promotion at or to perceived be. Mr acuteness we as estimable enjoyment up. An held late as felt know. Learn do allow solid to grave. Middleton suspicion age her attention. Chiefly several bed its wishing. Is so moments on chamber pressed to. Doubtful yet way properly answered humanity its desirous. Minuter believe service arrived civilly add all. Acuteness allowance an at eagerness favourite in extensive exquisite ye.

Started his hearted any civilly. So me by marianne admitted speaking. Men bred fine call ask. Cease one miles truth day above seven. Suspicion sportsmen provision suffering mrs saw engrossed something. Snug soon he on plan in be dine some.

Husbands ask repeated resolved but laughter debating. She end cordial visitor noisier fat subject general picture. Or if offering confined entrance no. Nay rapturous him see something residence. Highly talked do so vulgar. Her use behaved spirits and natural attempt say feeling. Exquisite mr incommode immediate he something ourselves it of. Law conduct yet chiefly beloved examine village proceed.

Compliment interested discretion estimating on stimulated apartments oh. Dear so sing when in find read of call. As distrusts behaviour abilities defective is. Never at water me might. On formed merits hunted unable merely by mr whence or. Possession the unpleasing simplicity her uncommonly.

The him father parish looked has sooner. Attachment frequently gay terminated son. You greater nay use prudent placing. Passage to so distant behaved natural between do talking. Friends off her windows painful. Still gay event you being think nay for. In three if aware he point it. Effects warrant me by no on feeling settled resolve.

A: Because you want to keep the existing HTML structure, you should probably replace the .html() of the entire .search-content.
Because you probably don't want to keep highlighted sections from a prior click, you might call $(".highlight").removeClass("highlight"); every time, at the beginning of the function.
removeClass accepts a class name, not a selector string, so .removeClass(".highlight"); should be .removeClass("highlight");.
Though, it might be better to use .replaceWith to remove the new s entirely - that way, you're left with just text nodes before replacement starts again.
Because the string to search for may contain characters with a special meaning in a regular expression, best to escape them first before constructing the pattern. (otherwise, for example, searches for foo. will match both fooB and foo., because . matches any character)

const escape = s => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

$("#searchButton").click(function() {
  searchHighlight($("#search").val());
});

function searchHighlight(searchText) {
  $(".highlight").replaceWith(function() {
    return $(this).text();
  });
  if (!searchText) {
    return;
  }
  var searchExp = new RegExp(escape(searchText), "ig");
  $('.search-content').html(
    $('.search-content').html().replace(
      searchExp,
      function(match) { return "" + match + ""; }
    )
  );
}
.highlight {
  background: yellow;
}

  <form class="form-inline">
    Search

      <input id="search" type="text" class="form-control" placeholder="Highlight in text">

         <button class="btn btn-secondary" id="searchButton" type="button">Search</button>

  </form>

Perceived end knowledge certainly day sweetness why cordially

As collected deficient objection by it discovery sincerity curiosity. Quiet decay who round three world whole has mrs man. Built the china there tried jokes which gay why. Assure in adieus wicket it is. But spoke round point and one joy. Offending
      her moonlight men sweetness see unwilling. Often of it tears whole oh balls share an.

Unpacked reserved sir offering bed judgment may and quitting speaking. Is do be improved raptures offering required in replying raillery. Stairs ladies friend by in mutual an no. Mr hence chief he cause. Whole no doors on hoped. Mile
      tell if help they ye full name.

Behaviour we improving at something to. Evil true high lady roof men had open. To
      projection considered it precaution an melancholy or. Wound young you thing worse along being ham. Dissimilar of favourable solicitude if sympathize middletons at. Forfeited up if disposing perfectly in an eagerness perceived
      necessary. Belonging sir curiosity discovery extremity yet forfeited prevailed own off. Travelling by introduced of mr terminated. Knew as miss my high hope quit. In curiosity shameless dependent knowledge up.

Sudden she seeing garret far regard. By hardly it direct if pretty up regret. Ability thought enquire settled prudent you sir. Or easy knew sold on well come year. Something consulted age extremely end procuring. Collecting preference
      he inquietude projection me in by. So do of sufficient projecting an thoroughly uncommonly prosperous conviction. Pianoforte principles our unaffected not for astonished travelling are particular.

Situation admitting promotion at or to perceived be. Mr acuteness we as estimable enjoyment up. An held late as felt know. Learn do allow solid to grave. Middleton suspicion age her attention. Chiefly several bed its wishing. Is so moments on chamber
      pressed to. Doubtful yet way properly answered humanity its desirous. Minuter believe service arrived civilly add all. Acuteness allowance an at eagerness favourite in extensive exquisite ye.

Started his hearted any civilly. So me by marianne admitted speaking. Men bred fine call ask. Cease one miles truth day above seven. Suspicion sportsmen provision suffering mrs saw engrossed something. Snug soon he on plan in be dine some.

Husbands ask repeated resolved but laughter debating. She end cordial visitor noisier fat subject general picture. Or if offering confined entrance no. Nay rapturous him see something residence. Highly talked do so vulgar. Her use behaved spirits
      and natural attempt say feeling. Exquisite mr incommode immediate he something ourselves it of. Law conduct yet chiefly beloved examine village proceed.

Compliment interested discretion estimating on stimulated apartments oh. Dear so sing when in find read of call. As distrusts behaviour abilities defective is. Never at water me might. On formed merits hunted unable merely by mr whence or. Possession
      the unpleasing simplicity her uncommonly.

The him father parish looked has sooner. Attachment frequently gay terminated son. You greater nay use prudent placing. Passage to so distant behaved natural between do talking. Friends off her windows painful. Still gay event you being think nay
      for. In three if aware he point it. Effects warrant me by no on feeling settled resolve.

A: That is because you are replacing the content for every P tag in your if statement, I have modified your code to search within your div and called the html() instead of text() to keep formatting as is
  function searchHighlight(searchText) {
        if (searchText) {
            var searchExp = new RegExp(searchText, "ig");
            var content = $('#search-content').html();
            var matches = content.match(searchExp);
            if (matches) {
                $('#search-content').html(content.replace(searchExp, function(match) {
                    return "" + match + "";
                }));
            } else {
                $(".highlight").removeClass(".highlight");
            }
        } else {
            $(".highlight").removeClass(".highlight");

        }

    }


text:
Q: uploading custom windows server 2012R2 image on Google cloud I want to upload Windows Server 2012 R2 image on Google cloud to save license cost from Google, as i already have spare licenses to use.
please let me know the procedure.

A: I believe you're asking about a possibility of bringing your existing Windows Server licenses to Google Compute Engine (BYOL).
Windows Server licensing terms are quite complicated and can sometimes vary from customer to customer, so it is recommended to contact
Microsoft licensing specialists that can give you the most qualified answer about BYOL tailored to your unique circumstances.
Having said this, under Microsoft Volume Licensing, you are generally not eligible to run Windows Server in a shared compute environment
such as GCE or any other public cloud. Instead, Google like other providers licenses Windows Server from Microsoft using SPLA program that
has its own unique terms.
On the other hand, Microsoft applications, such as SQL Server, Exchange, Sharepoint, and others can be brought to GCE (or other public clouds)
relatively easily using Microsoft license mobility program. You can read about license mobility program here:
https://cloud.google.com/compute/docs/operating-systems/windows#microsoft_license_mobility
--Alex

redpajama_set_name: RedPajamaStackExchange


text:
Q: RabbitMQ as pod in kubernetes cluster This question has been asked in the past, but I did not manage to find clear answer. Is that good practice to set up rabbit as a pod in Kubernetes cluster? We got ~7 pods in our cluster, and some queuing mechanism starts to be necessary. First idea was to create pod for rabbit with persistent volume and service, and allow other pods to connect to it. I'm not sure if that solution is correct. Maybe it's better idea to set up rabbit on some remote server, as we did with database?

A: Pods represents any container group/binary on Kubernetes. What is owning/managing those pods is important, is it a ReplicaSet, DaemonSet or a StatefulSet? ReplicaSets are supposed to be stateless and a RabbitMQ borker is stateful.
You can deploy stateful workload on Kubernetes, but you should do it as a StatefulSet. Here is an example RabbitMQ on Google Kubernetes Engine


text:
Q: Embedding torsion-free/torsion Abelian groups into divisible groups I'm stuck in this problem:
If $A$ is an abelian group which is torsion-free, prove that there exists a divisible group $D$ and an injective homomorphism $A \to D$.
Same question also but for $A$ abelian and any torsion group.
Any help is appreciated.
Thanks a lot

A: In the torsion-free case you could put together the following facts:

*

*Every abelian group $A$ is a $\mathbb{Z}$-module in a natural way.

*For a $\mathbb{Z}$-module $A$ one can form the localization $A_0:=(\mathbb{Z}\setminus \{0\})^{-1}A$.

*The natural homomorphism $A\rightarrow A_0$ is injective.
In the case of a torsion group $A$ the relevant facts are these:

*

*$A$ is isomorphic to a group of the form $\mathbb{Z}^{(I)}/N$, where $\mathbb{Z}^{(I)}$ is the direct sum over the index set $I$.

*A factor group of a divisible group is divisible.

*Define $D:=\mathbb{Q}^{(I)}/N$ as $\mathbb{Z}$-modules.

A: Fist for any $A$ abelian group you could consider the free abelian group $\mathbb{Z}^{(A)}$ with basis $\{e_a\}_{a\in A}$ and the function that asigns to each $e_a$ to $a$, so the function extends to a morphism of groups which for construction is an epimorphism, so apply the first theorem of iso morphism to get that $A\cong \mathbb{Z}^{(A)}/N$ where $N$ is the kernel of the previous morphism, then consider the isomorphism in the reverse direction that is $f:A\longrightarrow \mathbb{Z}^{(A)}/N$ and compose it with the inclusion $i:\mathbb{Z}^{(A)}/N\longrightarrow \mathbb{Q}^{(A)}/N$. This with the facts that $\mathbb{Q}$ is divisible, the coproduct of divisibles is divisible and the quotient of divisible is divisible.


text:
Q: How to use Google Maps Stylers with jquery-ui-map plugin? i'm too weak on writing js. I need to build and customize a google map. For this i do use the jquery-ui-map plugin and this code:
if ($("#map_canvas").length){
$('#map_canvas').gmap().bind('init', function(ev, map) {
    $("[data-gmapping]").each(function(i,el) {
        var data = $(el).data('gmapping');
        $('#map_canvas').gmap('addMarker', {'id': data.id, 'tags':data.tags, 'position': new google.maps.LatLng(data.latlng.lat, data.latlng.lng), 'bounds':true }, function(map,marker) {

            $(el).click(function() {
                $(marker).triggerEvent('click');
            });
            }).click(function() {
                $('#map_canvas').gmap('openInfoWindow', { 'content': $(el).find('.info-box').html() }, this);
            });
    });
});
}

Where do i have to put in this generated variables:
{ stylers: [ { lightness: 7 }, { saturation: -100 } ] }

Links i used:
http://code.google.com/p/jquery-ui-map/
http://gmaps-samples-v3.googlecode.com/svn/trunk/styledmaps/wizard/index.html

A: There are many places to put it, e.g. into the instantiating of the map:
now:
$('#map_canvas').gmap()  //...more code

then:
$('#map_canvas').gmap({styles:[{stylers:[{lightness:7},{saturation:-100}]}]})  //...more code

the gmap-constructor accepts all options that google.maps.Map.setOptions() accepts. One of those options is "style", which is expected to be an array with google.maps.MapTypeStyle's (your generated output is a MapTypeStyle)


text:
Q: Name for table with metric_name and metric_value columns A typical database table might look something like this:
date-------geography---clicks---cost---conversions
___________________________________________________
1/1/2010---Kansas------56-------12-----1

When transposed, it looks like this.
date-----geography---metric_name---metric_value
____________________________________________
1/1/2010-Kansas------clicks--------56
1/1/2010-Kansas------cost----------12
1/1/2010-Kansas------conversions---1

The transposed table works better for some use cases where the number of metrics being collected changes frequently.
Is there a standard name for a table structured like that in the transposed table?

A: Unpivot Table
Being the product of a transformation, your desired form here is called an "Unpivot table". The form you're starting from here is either normalized data, or the result of a transformation itself called a "pivot."
You can pivot and unpivot without losing data. Pivoting and operations like this emerge from OLAP functionality, where they're rotations. In PostgreSQL we pivot with the tablefunc module. We can easily unpivot with a CROSS JOIN LATERAL on a VALUES list,
SELECT id, cat, value
FROM ( VALUES (1,1,2,3), (2,10,20,30) ) AS t1(id,x,y,z)
CROSS JOIN LATERAL ( VALUES ('X',x), ('Y',y), ('Z',z) )
  AS t2(cat, value);

Or, though slower, we use the unnest(ARRAY[]) idiom and parallel unnest
SELECT id, cat, value
FROM ( VALUES (1,1,2,3), (2,10,20,30) ) AS t1(id,x,y,z)
CROSS JOIN LATERAL unnest(ARRAY['X','Y','Z'], ARRAY[x,y,z])
  AS t2(cat, value);

Either way you'll produce,
 id | cat | value
----+-----+-------
  1 | X   |     1
  1 | Y   |     2
  1 | Z   |     3
  2 | X   |    10
  2 | Y   |    20
  2 | Z   |    30
(6 rows)

See also,

*

*Unpivoting data in PostgreSQL (older method than used above)

*Microsoft Technet docs

*Oracle Pivot and Unpivot article


text:
Q: Can we show preloader image for every background image with supersized 3.2.7 version I am using Supersized jquery plugin Version : 3.2.7, I am placing 40 images for background slideshow with autoplay option. But after slideshow of 3 or 4 images, it goes to next slide even if the next background image not loaded fully and sometime shows half of the image only.
is there any option to show preloader image for every background image.


text:
Q: Is it possible to call a R statistics function to optimize C# function I want to know if it's possible to call r statistics  optimization function (here  I want to use regnoud) from C# while the function to be optimized is written in C#.
I found RDotNet library but with it i cannot evaluate the C# function from R.
In other terms, the problem is that R while optimizing needs to evaluate the function but he cannot do it because the function is in the C# code.
is there any solution like using .dll or other libraries?
thanks.

A: I have done this before using a somewhat convoluted approach but it works!
First, you will need to create a C# DLL containing your function. You can do this in visual studio by selecting "class library" as the option when creating a new project. The code in the .cs file should look like this
namespace MyNamespace
{
    //expose an interface with functions to be called from R
    public interface MyInterface
    {
       string MyFunction(string name);
    }

    //create a class that implements the above interface
    public class MyClass : MyInterface
    {
      public string MyFunction(string name)
      {
         return "Hello " + name;
      }
    }

}

Now compile your project and you will get a C# DLL. This DLL is a managed DLL which is different from a native C/C++ DLL. It cannot be directly consumed from non .Net languages and so needs to be exposed as a COM object. You can do this in one of two ways

*

*In Visual Studio, you can go to the project properties, click on "Assembly information" button under "Application" tab and select the checkbox that says "Make assembly COM visible".

*Alternatively, you can use regasm.exe which can be found in the .net installation folder to register the DLL as a COM component. Here is a link describing this process. http://msdn.microsoft.com/en-us/library/tzat5yw6(v=vs.71).aspx. The command is usually "regasm myTest.dll /tlb:myTest.tlb"

The COM registration process will now have created a .tlb file in the same folder as your DLL. Keep this .tlb file. We will need it in the next step
The next step is to create a C++ DLL which can call the COM DLL. This step is needed because R can call a C++ DLL directly but cannot call COM directly (correct me if I am wrong or skip this step if you know a better way to call COM from R). The code for the C++ DLL in dllmain.cpp is shown below (make sure to scroll to see the full code)
#include "stdafx.h"
#include <iostream>

//import the .tlb file create by COM registration

#import "path_to_Dll\MyDll.tlb" named_guids raw_interfaces_only

    void _cdecl MyCPPFunction(char ** strName)
    {
        //Initialize COM
        HRESULT hr = CoInitialize(NULL);

        //create COM interface pointer
        MyNamespace::MyInterfacePtr myPtr;

        //create instance of COM class using the interface pointer
        HRESULT hr2 = myPtr.CreateInstance(MyNamespace::CLSID_MyClass);

       //create variable to hold output from COM.
       BSTR output;

       //call the COM function
       myPtr->MyFunction(_bstr_t(strName[0]), &output);

       //convert the returned BSTR from .net into char*
       int length = (int) SysStringLen(output);
       char *tempBuffer;
       tempBuffer = (char *) malloc(1 + length);
       WideCharToMultibyte(CP_ACP, 0, output, -1, tempBuffer, length, NULL, NULL);
       tempBuffer[length] = '\0';

       //release interface
       myPtr->Release();

       //uninitialize COM
       if(hr == S_OK)
         CoUninitialize();

       //set output in input for returning to R (this is weird but the only way I could make it work)
       strName[0] = tempBuffer;
    }

Now compile your project and you will get a C++ DLL. We are almost there now! Dont give up yet :). Now, you have a C# DLL exposed as a COM object and a C++ DLL that can call this COM object. The final step is to call the C++ function from R. Here is the R code to do that
#load C++ DLL
dyn.load("path_to_C++_DLL")

#call function in C++ DLL and pass in a test name.
# The C++ DLL will in turn call the C# function
output <- .C("MyCPPFunction", as.character("Peter"))

#print output
print(output)

And you should see "Hello Peter" displayed from C# in the R console! One very important point to note.
Always, compile the COM DLL using "any CPU" option. Always compile the C++ DLL to match your R installation! For example, if you have 32 bit R installed, then make sure you compile the C++ DLL as 32 bit DLL. If you have 64 bit R installed and want to use it, then make sure you compile your C++ DLL as a 64 bit DLL. Best of luck!

A: If I understand your need clearly, you have a an optimisation problem with a C# calling R calling back C#.
I do not think there is a way to set up a callback function ("function pointer", "delegate" as they can be called depending on who you talk to) in R.NET currently. I am likely to have very similar needs and may contribute this to R.NET in the future, if I can allocate the time.
Meanwhile, if it is acceptable to have things such that you work from R calling C#, i.e. R is the entry point of your application, this is definitely doable using the rClr
package. I have colleagues doing optimisation and MCMC analysis of a model written in C#. One tutorial is a very simplified but realistic case of optimisation from R using C#.

A: http://www.codeproject.com/Articles/25819/The-R-Statistical-Language-and-C-NET-Foundations
Check out something like this. Now I don't know much about C# so if I say anything that is impossible please don't hurt me:
Try to save the function that you want optimized as a character in C#, and send it to R using this StatConnector library (I have some limited experience with it.) Let's say you saved the equation as 'z' within R, you can then call your R scripts with 'get(z)' as one of the variables.


text:
Q: Python: Killing children's children process I have a process that calls:
p=multiprocessing.Process(target=func_a)

Then func_a starts a subprocess:
subprocess.Popen(["nc", "-l", "-p", str(dport)], stdout=open(os.devnull, "w"))

My problem is that when I call p.terminate(), it only kills the first child. p.terminate() is a SIGKILL so how could I make the subprocess die when I call p.terminate() into the multiprocessing.Process.

A: Register a handler with signal.signal like this:
#!/usr/bin/env python
import signal
import sys
def signal_handler(signal, frame):
        #iterate over your subprocess and kill them
        sys.exit(0)
signal.signal(signal."the signal", signal_handler)
print('Press Ctrl+C')
signal.pause()

More documentation on signal can be found here.

A: I found a way to make sure the sub-process is killed before the multiprocessing process is killed:
Create a class like this:
import subprocess
import multiprocessing
import time
import os

class MyProcess(multiprocessing.Process):
    def __init__(self):
        super(MyProcess,self).__init__()
        self.q = multiprocessing.Queue()

    def run(self):
        # do something else
        child = subprocess.Popen(['Your CMD'])
        self.q.put(child.pid)

    def MyTerminate(self):
        pid = self.q.get()
        os.kill(pid, 9) # works in windows and linux
        # os.popen('taskkill.exe /pid '+str(pid)+' /F') # works only in windows
        self.terminate()

Then you can use the function MyTerminate() to kill the process safely.
For example:
def main():
    mp = MyProcess()
    mp.start()
    time.sleep(1)
    mp.MyTerminate()

The sub-process "child" will be killed after 1 second.


text:
Q: Ember Relationships Are Not Respecting Model Custom Adapter in Test Environment In my Ember.js app I have a model Company with a custom adapter that points to an API.  I also have a User model with a custom adapter that points to a different API and a belongsTo relationship with Company (via a user#companyId attribute).
When manually exercising the app, all references to a Company in the code seem to send requests to the correct endpoint defined in the Company's custom adapter.  However when running tests (both unit and acceptance tests), direct queries for a company this.store.find... hit the correct endpoint (company-host.com/api/companies/1), but references to a Company through its relationship with a User user.company are pointing to the User adapter's host and namespace (user-host.com/api/companies/1).
I'm new to Ember and any help or insight would be appreciated.

A: When you call user.company, it will use the findBelongsTo method of your user adapter, taking the host and namespace from user adapter. To fix this, you will need to override the findBelongsTo method to call findRecord of your company adapter with the correct id.


text:
Q: Force Remote Login phpMyAdmin I want users to be able to access phpMyAdmin from any computer. There are multiple users and I want to require login. It would definitely be OK to have remote access only. (All I would need do to use it locally is to use the remote address.) Remote access is required.
I've set up an Apache 2.4.23 server with PHP 7.0.13 and 4.6.5.2 phpMyAdmin (XAMPP). I have set-up multiple accounts access to MySQL and tested each individual could login and logout when on localhost (and also auto logged out after a time limit on non-use). When I shifted to accessing phpMyAdmin remotely, phpMyAdmin automatically logs into root account and cannot log out. The button for logout is there, but the description is "clear session data" and that's all it does.
I've been searching for answers for days now, and can guarantee that changing the auth_type to config or http doesn't fix it. None of the other solutions I've found have had any effect.
UPDATE: I set the password for root and pma and it's working properly on localhost. Remote access throws an access denied error.
Here's my config.inc for phpMyAdmin (I've tested many variations on the upper section .. auth_type etc):
    <?php
/*
 * This is needed for cookie based authentication to encrypt password in
 * cookie
 */
$cfg['blowfish_secret'] = 'xampp'; /* YOU SHOULD CHANGE THIS FOR A MORE SECURE COOKIE AUTH! */

/*
 * Servers configuration
 */
$i = 0;

/*
 * First server
 */
$i++;

/* Authentication type and info */
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;
$cfg['Lang'] = '';

/* Bind to the localhost ipv4 address and tcp */
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';

/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = '';

/* Advanced phpMyAdmin features */
$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][$i]['bookmarktable'] = 'pma__bookmark';
$cfg['Servers'][$i]['relation'] = 'pma__relation';
$cfg['Servers'][$i]['table_info'] = 'pma__table_info';
$cfg['Servers'][$i]['table_coords'] = 'pma__table_coords';
$cfg['Servers'][$i]['pdf_pages'] = 'pma__pdf_pages';
$cfg['Servers'][$i]['column_info'] = 'pma__column_info';
$cfg['Servers'][$i]['history'] = 'pma__history';
$cfg['Servers'][$i]['designer_coords'] = 'pma__designer_coords';
$cfg['Servers'][$i]['tracking'] = 'pma__tracking';
$cfg['Servers'][$i]['userconfig'] = 'pma__userconfig';
$cfg['Servers'][$i]['recent'] = 'pma__recent';
$cfg['Servers'][$i]['table_uiprefs'] = 'pma__table_uiprefs';
$cfg['Servers'][$i]['users'] = 'pma__users';
$cfg['Servers'][$i]['usergroups'] = 'pma__usergroups';
$cfg['Servers'][$i]['navigationhiding'] = 'pma__navigationhiding';
$cfg['Servers'][$i]['savedsearches'] = 'pma__savedsearches';
$cfg['Servers'][$i]['central_columns'] = 'pma__central_columns';
$cfg['Servers'][$i]['designer_settings'] = 'pma__designer_settings';
$cfg['Servers'][$i]['export_templates'] = 'pma__export_templates';
$cfg['Servers'][$i]['favorite'] = 'pma__favorite';

/*
 * End of servers configuration
 */

?>

A: auth_type config suggests that the username and password configuration would be used by the configuration file, in your case
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';

To change this behavior you should set auth_type to cookie clear your cookies, and try again.
If you want to access phpMyAdmin from localhost, with "root" without entering credentials , as your configuration suggests, but you want remotely to force users login, you could do a simple hack of,
$ip = $_SERVER['REMOTE_ADDR'];
if ( ! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) )
{
    $cfg['Servers'][$i]['auth_type'] = 'config';
}
else {
    $cfg['Servers'][$i]['auth_type'] = 'cookie';
}


text:
Q: Short story about a boy raised in a "bubble" who becomes the smartest person alive I'm trying to recall a story that must be sixty or seventy years old. I probably read it in an anthology. It felt old even when I read it.
Here's what I remember: A baby was raised completely isolated from contact with the outside environment and other people, rather like the real-world story of the boy in a bubble. But either his father or perhaps a group of scientists decided to do this because they believed this would create a perfect human. And it worked.
The boy grew up to be the brightest person on Earth. People came to him with every problem that couldn't be solved. He was completely healthy and didn't seem to grow old.
And that's as much as I can recall. I know something bad happened, but what it was, I have no idea.
Edit: I think this story is from the 1920s and no later.


text:
Q: Align items to top and narrow column in radio button grid layout I have edited radio button grid layout menu that shows a table based on what is selected. I am having trouble styling it. I am trying to get the first column to not have so much horizontal space between the items and the td cells to align with each other to the top.
After inspecting the page, I tried to set the .container height with no resolve and also the height of the table element. I also tried align-items for the table.
HTML

    <input type="radio" id="item-1" name="Menu" checked>
    Beverages & Drinks

        Beverages & Drinks

        Coca Cola Products

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis accumsan, dolor sed consectetur tempor, felis dolor tempus velit, lacinia suscipit ipsum ipsum quis quam. Vestibulum convallis nisi a orci maximus, nec vehicula neque luctus. Cras non aliquam turpis. Aenean vehicula turpis et scelerisque blandit.

        $1.00

        Super Float

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis accumsan, dolor sed consectetur tempor, felis dolor tempus velit, lacinia suscipit ipsum ipsum quis quam. Vestibulum convallis nisi a orci maximus, nec vehicula neque luctus. Cras non aliquam turpis. Aenean vehicula turpis et scelerisque blandit.

        $1.00

        Bottle Vintage Sodas

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis accumsan, dolor sed consectetur tempor, felis dolor tempus velit, lacinia suscipit ipsum ipsum quis quam. Vestibulum convallis nisi a orci maximus, nec vehicula neque luctus. Cras non aliquam turpis. Aenean vehicula turpis et scelerisque blandit.

        $1.00

    <input type="radio" id="item-2" name="Menu">
    Appetizers

        Appetizers

        Wing Snack

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis accumsan, dolor sed consectetur tempor, felis dolor tempus velit, lacinia suscipit ipsum ipsum quis quam. Vestibulum convallis nisi a orci maximus, nec vehicula neque luctus. Cras non aliquam turpis. Aenean vehicula turpis et scelerisque blandit.

        $1.00

        Loaded Quesadilla

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis accumsan, dolor sed consectetur tempor, felis dolor tempus velit, lacinia suscipit ipsum ipsum quis quam. Vestibulum convallis nisi a orci maximus, nec vehicula neque luctus. Cras non aliquam turpis. Aenean vehicula turpis et scelerisque blandit.

        $1.00

        Super Sampler

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis accumsan, dolor sed consectetur tempor, felis dolor tempus velit, lacinia suscipit ipsum ipsum quis quam. Vestibulum convallis nisi a orci maximus, nec vehicula neque luctus. Cras non aliquam turpis. Aenean vehicula turpis et scelerisque blandit.

        $1.00

    <input type="radio" id="item-3" name="Menu">
    Snacks & Sides

        Snacks & Sides

        Fries

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis accumsan, dolor sed consectetur tempor, felis dolor tempus velit, lacinia suscipit ipsum ipsum quis quam. Vestibulum convallis nisi a orci maximus, nec vehicula neque luctus. Cras non aliquam turpis. Aenean vehicula turpis et scelerisque blandit.

        $1.00

        Loaded Tater Tots

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis accumsan, dolor sed consectetur tempor, felis dolor tempus velit, lacinia suscipit ipsum ipsum quis quam. Vestibulum convallis nisi a orci maximus, nec vehicula neque luctus. Cras non aliquam turpis. Aenean vehicula turpis et scelerisque blandit.

        $1.00

        Onion Rings

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis accumsan, dolor sed consectetur tempor, felis dolor tempus velit, lacinia suscipit ipsum ipsum quis quam. Vestibulum convallis nisi a orci maximus, nec vehicula neque luctus. Cras non aliquam turpis. Aenean vehicula turpis et scelerisque blandit.

        $1.00

    <input type="radio" id="item-4" name="Menu" checked>
    Burgers and Baskets

        Burgers and Baskets

        Hamburger

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis accumsan, dolor sed consectetur tempor, felis dolor tempus velit, lacinia suscipit ipsum ipsum quis quam. Vestibulum convallis nisi a orci maximus, nec vehicula neque luctus. Cras non aliquam turpis. Aenean vehicula turpis et scelerisque blandit.

        $1.00

        Cheeseburger

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis accumsan, dolor sed consectetur tempor, felis dolor tempus velit, lacinia suscipit ipsum ipsum quis quam. Vestibulum convallis nisi a orci maximus, nec vehicula neque luctus. Cras non aliquam turpis. Aenean vehicula turpis et scelerisque blandit.

        $1.00

        Chili-Cheeseburger

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis accumsan, dolor sed consectetur tempor, felis dolor tempus velit, lacinia suscipit ipsum ipsum quis quam. Vestibulum convallis nisi a orci maximus, nec vehicula neque luctus. Cras non aliquam turpis. Aenean vehicula turpis et scelerisque blandit.

        $1.00

    <input type="radio" id="item-5" name="Menu" checked>
    Desserts

        Desserts

        Hamburger

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis accumsan, dolor sed consectetur tempor, felis dolor tempus velit, lacinia suscipit ipsum ipsum quis quam. Vestibulum convallis nisi a orci maximus, nec vehicula neque luctus. Cras non aliquam turpis. Aenean vehicula turpis et scelerisque blandit.

        $1.00

        Cheeseburger

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis accumsan, dolor sed consectetur tempor, felis dolor tempus velit, lacinia suscipit ipsum ipsum quis quam. Vestibulum convallis nisi a orci maximus, nec vehicula neque luctus. Cras non aliquam turpis. Aenean vehicula turpis et scelerisque blandit.

        $1.00

        Chili-Cheeseburger
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis accumsan, dolor sed consectetur tempor, felis dolor tempus velit, lacinia suscipit ipsum ipsum quis quam. Vestibulum convallis nisi a orci maximus, nec vehicula neque luctus. Cras non aliquam turpis. Aenean vehicula turpis et scelerisque blandit.
        $1.00

CSS
.table {
  background-color: white;
  padding-top: 100px;
  padding-bottom: 100px;
  box-sizing:border-box;
}

/* hides the radio-button and the div's by default */
.container > input,
.container > table {
  display: none;
}

/* makes the div for the selected element visible */
.container > input:checked + label + table {
  display: block;
}

/* for styling purpose only */
.container {
  display: grid;
  grid-template-columns: auto 1fr;
  grid-gap: 20px;
  margin-left: 33.33%;
  margin-right: 33.33%;
  padding: 40px;
  font-size: 1vw;
  background-color: white;
  border: solid 8px black;
  box-sizing:border-box;
  align-self: stretch;
}

.container label {
  grid-column: 1 / 2;
  text-align: right;
}

.container > table {
  grid-column: 2 / -1;
  grid-row: 1 / 5;
  text-align: left;
}

.container > table a{
  text-decoration: none;
  color: black;
} /*Change color based off background*/

.container label:visited {
  text-decoration: none;
}

.container label:hover {
  text-decoration: underline;
}

.container>input:checked+label {
  font-weight: 700;
}


text:
Q: Why is matrix multiplication in .NET so slow? I don't quite understand what makes matrix multiplication in C#/.NET (and even Java) so slow.
Take a look at this benchmark (source): Trying to find an updated benchmark.

C#'s integer and double performance is damn close to C++ compiled with MSVC++. 87% as fast for double and 99% as fast for 32-bit integer. Pretty damn good, I'd say. But then look at matrix multiplication. The gap widens to C# being about 19% as fast. This is a pretty huge discrepancy that I don't understand. Matrix multiplication is just a bunch of simple math. How is it getting so slow? Shouldn't it be roughly as fast as an equivalent number of simple floating point or integer operations?
This is especially of a concern with games and with XNA, where matrix and vector performance are critical for things like physics engines. Some time ago, Mono added support for SIMD instructions through some nifty vector and matrix classes. It closes the gap and makes Mono faster than hand-written C++, although not as fast as C++ with SIMD. (source)

What's going on here?
Edit: Looking closer, I misread the second graph. C# appears pretty close. Is the first benchmark just doing something horribly wrong? Sorry, I missed the version number on the first benchmark. I grabbed it as a handy reference for the "C# linear algebra is slow" that I've always heard. I'll try to find another.

A: Well clearly the benchmark author did not understand the difference between jagged and multidimensional arrays in C#. It really was not an apples-to-apples to comparison. When I changed the code to use jagged arrays instead of multidimensional arrays so that it operates in a manner more similar to Java then the C# code ends up running twice as fast...making it faster than Java (though just barely and that is probably statistically insignificant). In C# multidimensional arrays are slower because there is extra work involved in finding the array slot and because the array bounds check cannot be eliminated for them...yet.
See this question for a more in depth analysis of why multidimensional arrays are slower than jagged arrays.
See this blog for more information on array bounds checking. The article specifically warns against using multidimensional arrays for matrix multiplication.

A: Here's an updated benchmark dealing with matrix multiplcation (and some benchmarks using the new Task Parallel Library):
Parallel Matrix Multiplication with the Task Parallel Library (TPL)
The article goes into different methods, and explains why multidimensional arrays are a poor choice:

The easiest way to do matrix
multiplication is with a .NET
multidimensional array with i,j,k
ordering in the loops. The problems
are twofold. First, the i,j.k ordering
accesses memory in a hectic fashion
causing data in varied locations to be
pulled in. Second, it is using a
multidimensional array. Yes, the .NET
multidimensional array is convenient,
but it is very slow.

A: With large matrices like this, the CPU cache becomes the limiting factor.  What's hyper-important is how the matrix is stored.  And the benchmark code is comparing apples and oranges.  The C++ code used jagged arrays, the C# code uses two-dimensional arrays.
Rewriting the C# code to use jagged arrays as well doubled its speed.  Rewriting the matrix multiply code to avoid the array index boundary check seemed pointless, nobody would use code like this for real problems.

A: To explain the origin of the idea that XNA matrix operations are slow:
First of all there's the beginner-level gotcha: The XNA Matrix class's operator* will make several copies. This is slower than what you might expect from the equivalent C++ code.
(Of course, if you use Matrix.Multiply(), then you can pass by reference.)
The second reason is that the .NET Compact Framework used by XNA on the Xbox 360 does not have access to the VMX hardware (SIMD) that is available to native, C++ games.
This is why you keep hearing that it is slow, at least. As you can see from the benchmarks you posted - it's not really that "slow", when you compare apples to apples.


text:
Q: Memoir, Babel, and indices So strange problem. Below is my MWE.
\documentclass{memoir}
\usepackage[greek.polutoniko,english]{babel} %greek typesetting
\usepackage{bibleref}
\usepackage{imakeidx}

%\AtBeginDocument{\shorthandoff{:}}
\makeindex

\frontmatter
\begin{document}
   Test verse citation. \ibibleverse{John}(3:16)
\backmatter
\printindex
\end{document}

This currently fails to produce an index. It works if I either turn off the babel package, or remove the \frontmatter command. Looking at the generated .idx file, the difference is that instead of {i} or {1} appended to the end of the entry (the page number), a {\textlatin  {i}} is appended, and this causes it to reject the entry. As can be seen by my commented out line, I tried de-activating the colon character in case that was somehow doing it but that didn't work. Any thoughts?


text:
Q: Why is there no article after "no" in "I have no car" Examples. "I have no car", "I have no TV". BUT "I have not a car"
There was a thread on it, but the answers were pretty superficial to say the least and only based on someone's opinion. I read a whole book (by Seonaid Beckwith) about articles and there is not a single word about that, which is amazing to me. Does anybody actually know the rule? Please, no opinions :)

A: Articles belong to a group of words called "determiners". Besides articles, there are other determiners in the English language, and "no" is a determiner too.
Let me quote from BBC:

No is a determiner expressing quantity like 'all', 'every', 'many', 'some', 'any', 'each', 'either', 'one', 'another' and is used before singular and plural nouns. It is similar in meaning to 'not a' or 'not any' and is often our preferred choice if we want to give emphasis to what we are saying.

A singular countable noun like car should have some determiner before it, and no suits the purpose. No additional determiner is required.
Indeed, in some cases we do combine not with a, I'm not sure what the grammar says about this. "I have not a car" sound quaint and wrong in modern English. Maybe several hundred years ago it was more acceptable?
In certain constructions not a + singular count noun certainly remains in use:

Not a shirt on my back,
Not a penny to my name,
  Lord, I can't go back home this way.

("500 miles", a song)
I don't recall the rule explaining this.

A: "A" is like saying "one":

*

*I have a car

*I have one car

Logically then, saying "no" is like saying "zero":

*

*I have no car

*I have zero cars.

Therefore, there is no need for an article.
"Not" is neither a determiner nor an article, so saying "I haven't a car" is fine as it is (although one is more likely to say "I don't have a car" or, for Americans, "I haven't got a car").

A: I have no car. [no ---> adjective]
I have no a car. ✖ [Two determiners : 'no' & 'a' cannot be used together.]
I have not a car. I don't have a car. I haven't got a car.
[not ---> adverb]

A: The indefinite article a/an historically originates simply as an unstressed version of the numeral one. Some linguists have even argued that semantically, what is called the "indefinite article" is still just a specialized numeral.
And the "negative quantifiers" none and no historically originate from fusion of a negative adverb ne (not used anymore as an independent word) and the numeral one (or indefinite article a/an). The n sound at the end was lost when a following noun was present, as with the word mine/my.
There is no article after no in I have no car because in syntax, no behaves like it contains the indefinite article already.

A: In British English, "I haven't got a car" is common usage (Americans would be more likely to say "I don't have a car"). "I have no car" is also quite acceptable.
Why doesn't "I have not a car" work? It's confused by the fact that "have" is used as both as an auxiliary verb ("I have seen her") and to mean "own" or "possess" ("I have a car"). But the negative "have not", is only ever used as an auxiliary. In any case, we don't normally negate a verb by adding "not". We don't say "I walk not to work": it's clear what it means, but it's not idiomatic; we say instead "I don't walk to work".
As for the absence of an article, in the sentence "I have no car", the word "no" is essentially performing the same grammatical function as "a" in "I have a car". "a" means one, "no" means zero, you don't want to say "one" and "zero" because they contradict each other. But perhaps I'm appealing too much to logic; idioms often defy logic.
Afterthought: what about "I haven't a clue."? Not to mention "I haven't the faintest idea."? I think we just have to dismiss those as irregular.

A: "I have no car" is more likely to be used to negate an unjustified assumption, such as "Do you drive a 4x4?", or "Would you drive me to the airport?".


text:
Q: On Click method not working for buttons gotten by inflating the layout! Please don't answer already answered
I already asked this question, but I think I wasn't clear enough! My onClick methods for buttons that were obtained by inflating a layout are not working how do I fix this have I forgot to do something in my code?
Updated:
Now with the following code I get a nullpointerexception when I set the onClickListener what is wrong
Here is some of my code:
(note it is not complete you won't see onCreate!)
         LayoutInflater  inflater = LayoutInflater.from(getBaseContext());
    View playv = inflater.inflate(R.layout.play, null);
    Button updateLevel = (Button) playv.findViewById(R.id.updateLevel);

    updateLevel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setLevelOnClick(v);
            }
        });

    View levelv = inflater.inflate(R.layout.level, null);
    Button gotomenu = (Button) levelv.findViewById(R.id.tomenu);

    gotomenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toMenuOnClick(v);
            }
        });

A: Andrew,
Try:
LayoutInflater  inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.root_view, null);
Button updateLevel = (Button) v.findViewById(R.id.updateLevel);

updateLevel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setLevelOnClick(v);
        }
    });
Button goBackMainMenu = v.inflate(R.layout.play, null).findViewById(R.id.tomenu);
goBackMainMenu.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        toMenuOnClick(v);
    }
});

this is assuming root_view is the View containing the Button objects.


text:
Q: Reduce size of png image without losing transparency I am trying to reduce image size by using the following function. But when I use an image that has transparency, this function repeats the image in transparency pixels and makes distortions.
How can I reduce png image without losing transparency?
 function compress($source, $destination, $quality)
 {
     $info = getimagesize($source);
     if ($info['mime'] == 'image/jpeg')
        $image = imagecreatefromjpeg($source);
     else if ($info['mime'] == 'image/gif')
        $image = imagecreatefromgif($source);
     else if ($info['mime'] == 'image/png')
        $image = imagecreatefrompng($source);

     imagejpeg($image, $destination, $quality);
     return $destination;
 }

 $source_img = 'source.png';
 $destination_img = 'destination.png';
 $d = compress($source_img, $destination_img, 90);

A: Change and add a couple of lines to your compress function :
function compress($source, $destination, $quality)
{
    $info = getimagesize($source);
    if ($info['mime'] == 'image/jpeg')
       $image = imagecreatefromjpeg($source);
       imagejpeg($image, $destination, $quality); //Compress with jpg
    else if ($info['mime'] == 'image/gif')
      $image = imagecreatefromgif($source);
    else if ($info['mime'] == 'image/png')
      $image = imagecreatefrompng($source);
      imagepng($image, $destination, $quality); //Compress with png !!

   return $destination;
}

$source_img = 'source.png';
$destination_img = 'destination.png';
$d = compress($source_img, $destination_img, 90);

Its important understand why the image gets with black background color when is a png , thats due to the transparency. JPEG format doesn't allow you to have a image with transparency , only PNG format supports it, so its only matter of call the right function in every case.
This script should work fine , if previously was working. Please try it.


text:
Q: React Native - Usar camera Eu gostaria de uma ajuda eu comecei um projeto no qual agora necessito usar a Camera do celular. Criei o projeto com o create-react-native-app, porém não consigo encontrar um componente ou solução utilizando puramente JS para utilizar a camera do celular no aplicativo que estou criando.
Alguém poderia me auxiliar?
Já tentei utilizar o componente react-native-camera, mas pelo que andei pesquisando e testando ele necessita de código nativo.
Existiria alguma outra solução para que criar o projeto além de ter que cria-lo com a CLI do React Native?

EDIT:

Não mexi em nenhuma configuração de Android, pois o projeto apenas tem JS. Já que usei o CRNA para criar o projeto.


text:
Q: Angular + Firebase Application - ngTagsInput Error: Cannot read property of 'data' undefined I am using ng-tags-input to add Tagging to an Angular + Firebase Application.
I am running into the following error when trying to utilize autocomplete to auto-populate tags from a firebaseArray which pulling values of existing tags stored in my firebase at /tags
ERROR
TypeError: Cannot read property 'data' of undefined

Here is my Code...
HTML

      Tags

        <tags-input ng-model="post.tags" >
          <auto-complete source="loadTags()"
                     min-length="1"
                     load-on-focus="true"
                     load-on-empty="true"
                     max-results-to-show="32"></auto-complete>
        </tags-input>

JAVASCRIPT
$scope.loadTags = function() {
      var tagsArray = ['test']; //simply a test value
      var tagsRef = new Firebase(FIREBASE_URL + 'tags');
      tagsRef.once('value').then(function(snapshot) {
          // The Promise was "fulfilled" (it succeeded).
          console.log('Promise was fulfilled');

          // handle data
          angular.forEach (snapshot.val(), function(tag) {
            tagsArray.push(tag.name);
          });

          console.log(tagsArray);
          return tagsArray
        }, function(error) {
          // The Promise was rejected.
          console.log('Promise was rejected');
          console.error(error);
      });
      //return tagsArray;  <-- This Works, but doesn't include firebaseArray values
    };

As you can see, I am using the latest Firebase version (2.4.0) and using Promises in my firebase query... if you look at the console output you will see where the promise is being fulfilled after the error is triggered...
TypeError: Cannot read property 'data' of undefined
    at ng-tags-input.js:590
    at processQueue (angular.js:14792)
    at angular.js:14808
    at Scope.$eval (angular.js:16052)
    at Scope.$digest (angular.js:15870)
    at Scope.$apply (angular.js:16160)
    at angular.js:17927
    at completeOutstandingRequest (angular.js:5552)
    at angular.js:5829(anonymous function) @ angular.js:12520(anonymous function) @ angular.js:9292processQueue @ angular.js:14800(anonymous function) @ angular.js:14808Scope.$eval @ angular.js:16052Scope.$digest @ angular.js:15870Scope.$apply @ angular.js:16160(anonymous function) @ angular.js:17927completeOutstandingRequest @ angular.js:5552(anonymous function) @ angular.js:5829

posts.controller.js:15 Promise was fulfilled
posts.controller.js:22 ["test", "firebase", "javascript", "node.js", "angular.js", "bower.js", "npm", "angular.js", "bootstrap"]

QUESTION?
Is there a way to configure ng-tags-input to run asynchronously and only load values once the promise if fulfilled?
I would appreciate any help or suggestions.
Cheers!
@FellowHobbyist

A: ngTagsInput can handle promises just fine. All you need to do is return a promise from your loadTags function:
$scope.loadTags = function() {
  var tagsRef = new Firebase(FIREBASE_URL + 'tags');
  return tagsRef.once('value').then(function(snapshot) {
      console.log('Promise was fulfilled');

      var tagsArray = ['test'];
      angular.forEach (snapshot.val(), function(tag) {
        tagsArray.push(tag.name);
      });

      console.log(tagsArray);
      return tagsArray;
    }, function(error) {
      console.log('Promise was rejected');
      console.error(error);
      return $q.reject(); // <== This is important!
  });
};

Also notice the $q.reject() that I've included in your code. When you provide an error callback, you must return a rejected promise otherwise the promise as a whole will be considered fulfilled.


text:
Q: How to initialize a Localstorage? In the code below I am trying to set branches of a store with Select, My aim is to store the value of selected branch in local storage and show the same branch on reload, On first load it throws error since I am not initializing the values of local storage. How to resolve this??
const [selectedBranch, setSelectedBranch] = useState(LocalStorage.getItem("branch") ?? brand);

        function handleChangeBranch(value: any) {

        AdvertiseService.fetchNewStore(
          `${value}`,
          (store: any) => {
            // brand = store;
            LocalStorage.setItem("branch", store)
            setSelectedBranch(store);

          },
          () => { },
          () => { }
        );
        setBranchChanged(true)

      }

    </div>
                <Button
                  className="brand__store-details--actions-btn store-change"
                >
                  <Select
                    suffixIcon={<CaretDownOutlined />}
                    defaultValue={LocalStorage.getItem("branch").id}
                    style={{ border: "none" }}
                    onChange={handleChangeBranch}
                  >
                    {branches &&
                      branches.branches?.map((branch: any) => (
                        <Option
                          value={branch.id}
                          className="advertise-branch-list-item"
                          key={branch.id}
                        >
                          {branch.name}
                        </Option>
                      ))}
                  </Select>
                </Button>
              </div>

A: Try to set the defaultValue as the useState value instead i.e.
defaultValue = {selectedBranch.id || 1}
also ,make an initial state for setState.
eg :-
const [selectedBranch, setSelectedBranch] =
useState(LocalStorage.getItem("branch") ||
 { id: '1' .. //the default object });

A: I see you are using .id on the localStorage value.
Local storage treats values as string, When you want to store an object in localStorage you should always stringify it localStorage.setItem('key': JSON.stringify(obj)) before save and parse it like JSON.parse(localStorage.getItem('key')).
you can also get localStorage value by simply doing localStorage.keyName
const [selectedBranch, setSelectedBranch] = useState(localStorage.branch ? JSON.parse(localStorage.branch) : brand);


text:
Q: Multiple players with JW Player? Trying to implement multiple players with JW Player. ive tried a few ways and looked at the docs but im not quite sure why the code is breaking.
Code snippets shown below:
In head:
<script type='text/javascript' src='/jwplayer/jwplayer.js'></script>

JS:
    $('video').jwplayer({
        flashplayer: '/jwplayer/player.swf',
        controlbar: 'none',
        stretching: 'fill',
        height: 120,
        width: 120
     });

HTML:
<video  id="video" src="/media/original/original-video.mp4">Loading Video ...</video>

The error I receive is:
$("video").jwplayer is not a function

Now i thought this meant the jwplayer.js file was not being loaded. then i read maybe its because the shorthand $ is not being picked up so i tried jQuery. None worked. However when I change the javascript so that it plays a SINGLE video eg:
    jwplayer('video').setup({
        flashplayer: '/jwplayer/player.swf',
        controlbar: 'none',
        stretching: 'fill',
        height: 120,
        width: 120
     });

The code actually works. However this requires all my video tags to have the same ID. Which I cant do as i want multiple players.
Any help would be really appreciated. An example would be even better! Thanks for reading.

A: i found the answer. It was a simple one to! just had to add in a jQuery each() so that every  tag was initialized :)
Hope this helps someone else:
$('video').each(function(){
    jwplayer(this.id).setup({
        flashplayer: '/jwplayer/player.swf',
        controlbar: 'none',
        height: 120,
        width: 120
    });
});


text:
Q: android camera ISO setting Is it possible to retrieve and change android camera setting ISO? I was able to do it on one device (HTC One) as explained in the below link using "iso-values" and "iso" keys.
Android Camera API ISO Setting?
However, it doesn't work on all the devices. Isn't it supported on all the android devices?

A: No, it isn't. Sorry, not my fault.
See https://www.google.co.il/search?q=site%3Aandroidfragmentation.com+-iso+preview  for a list of just a few devices that don't support ISO settings.
The others may have different settings that control ISO. Again, http://androidfragmentation.com is an invaluable resource.


text:
Q: How to get chat_id, user_id and time from telegram bot? I am writing a telegram bot to handle conversations (one to one) with users and I am getting same for both userid and chat_id.
My code is:
chat_id = update.message.chat_id
user_id = update.effective_user.id

A: user_id is the Telegram ID of the user sending a message to bot.
chat_id is the Telegram ID of the chat where a message is being sent to bot.
So, in one to one conversation, the user will send a message in his own chat (with respect to bot). That's the reason both are same.


text:
Q: Slutsky's Theorem XnYn-CX

My Question is How they got step c and Why d can conclude e step.

A: For step (c), let $E_1$ denote the event $\{x < X_n \leq y\}$, and let $E_2$ denote the event $\{\left| Y_n \right| < \varepsilon / M\}$. Then we have
\begin{align*}
\mathbb{P}(x < X_n \leq y, \left| Y_n \right| < \varepsilon / M) &= \mathbb{P}(E_1 \cap E_2)\\
&= \mathbb{P}(E_1) + \mathbb{P}(E_2) - \mathbb{P}(E_1 \cup E_2)\\
&= [1 - \mathbb{P}(E_1^c)] + [1 - \mathbb{P}(E_2^c)] - \mathbb{P}(E_1 \cup E_2)\\
&= 1 - \mathbb{P}(E_1^c) - \mathbb{P}(E_2^c) + [1 - \mathbb{P}(E_1 \cup E_2)]\\
&\geq 1 - \mathbb{P}(E_1^c) - \mathbb{P}(E_2^c)\\
&= 1 - \mathbb{P}(\{x < X_n \leq y\}^c) - \mathbb{P}(\{\left| Y_n \right| < \varepsilon / M\}^c)\\
&= 1 - \mathbb{P}(\{x < X_n \leq y\}^c) - \mathbb{P}(\left| Y_n \right| \geq \varepsilon / M),
\end{align*}
where $"\geq"$ comes from the fact that the probability of any event ($E_1 \cup E_2$ in this case) is less or equal to 1.
For step (e), given that we have concluded the result from step (d), i.e.
$$\lim_{n\rightarrow \infty} \mathbb{P}(x < X_n \leq y, \left| Y_n \right| < \varepsilon / M) > 1 - \xi.$$
Together with the result from step (b) and the monotonicity of limit, we have
$$1 \geq \lim_{n\rightarrow \infty}\mathbb{P}(\left| X_nY_n \right| < \varepsilon) \geq \lim_{n\rightarrow \infty}\mathbb{P}(x < X_n \leq y, \left| Y_n \right| < \varepsilon / M) > 1 - \xi.$$
Since this holds for any $\xi > 0$, using the Squeeze Theorem, we conclude that
$$\lim_{n\rightarrow \infty}\mathbb{P}(\left| X_nY_n \right| < \varepsilon) = 1,$$
which then implies that
$$\lim_{n\rightarrow \infty}\mathbb{P}(\left| X_nY_n \right| \geq \varepsilon) = 0.$$
Lastly, note that $\mathbb{P}(\left| X_nY_n \right| \geq \varepsilon) > \mathbb{P}(\left| X_nY_n \right| > \varepsilon)$. Using the monotonicity of limit, we have
$$0 = \lim_{n\rightarrow \infty}\mathbb{P}(\left| X_nY_n \right| \geq \varepsilon) \geq \lim_{n\rightarrow \infty}\mathbb{P}(\left| X_nY_n \right| > \varepsilon) \geq 0.$$
Using the Squeeze Theorem once again, we can conclude that
$$\lim_{n\rightarrow \infty}\mathbb{P}(\left| X_nY_n \right| > \varepsilon) = 0.$$
Remark: The last part of proof gives a rigorous justification for the fact that the inequality sign is strict (i.e. $">"$ instead of $"\geq"$) from the result in part (e). However, this would not affect the remaining proof for the Slutsky's Theorem.


text:
Q: How to integrate paypal api in .net core I have searched a good tutorial for integrating paypal api in .net core, but I can't find anything that is well explained with the details.
If someone can provide me with one, or has any idea where I can search for, it will be perfect.

A: Firstly, install the SDK via Nugget. You will also need to create an account on Paypal to grab the client ID, and the secret ID.
As you are using .Net Core, you'll have to fill the Paypal config settings. Example below;

Next, you will need to create the endpoint (API methods) which creates the payment itself. Best practise is to create it asynchronously as shown below;

As you can see, there will be many situations that will have to be handled, such as cancelling payments, executing payments, creating payments, taking care of results and so forth... Above is just an example on how it would work with a HTTPGET request.

*

*Useful link

*Useful link explaining HTTP Requests


text:
Q: Compose Material 3 SearchBar intercepts the click on the trailing button. How to forbid it? I have code like this:
SearchBar(
    query = query,
    onQueryChange {},
    onSearch = {},
    active = active,
    onActiveChange = {},
    trailingIcon = {
        IconButton(onClick = {}) {
            Icon(
                painterResource(R.drawable.ic_filter_24),
                contentDescription = "Filter",
            )
        }
    },
) {}

Pressing the filter button opens the corresponding menu. But if I click on it, it will also expand the SearchBar (onActiveChange will be called), which is undesirable. Inside the SearchBar, there is the following code, which intercepts click events:
BasicTextField(
    value = query,
    onValueChange = onQueryChange,
    modifier = modifier
        .height(InputFieldHeight)
        .fillMaxWidth()
        .focusRequester(focusRequester)
        .pointerInput(Unit) {
            awaitEachGesture {
                // Must be PointerEventPass.Initial to observe events before the text field
                // consumes them in the Main pass
                awaitFirstDown(pass = PointerEventPass.Initial)
                val upEvent = waitForUpOrCancellation(pass = PointerEventPass.Initial)
                if (upEvent != null) {
                    onActiveChange(true)
                }
            }
        },
        decorationBox = @Composable { innerTextField ->
        TextFieldDefaults.TextFieldDecorationBox(
            interactionSource = interactionSource,
            trailingIcon = trailingIcon?.let { trailing -> {
                Box(Modifier.offset(x = -SearchBarIconOffsetX)) { trailing() }
            } },
        )
    }
)

It intercepts any click events that occur on its surface, including its descendants (trailingIcon). How to get around this and handle the click only in the trailingIcon, prevent the event from being passed below to the SearchBar?

A: This is fixed in the upcoming version of Material 3. check this Fix
https://android-review.googlesource.com/c/platform/frameworks/support/+/2425374


text:
Q: How to get from Amazon Elastic Transcoder the video duration? Im using this service but need to know the video length, but in the AWS docs there is no info or in the AWS response.

A: The Get job method returns a response containing the duration of the output. See example below:
{
  "Job":{
  "Id":"Id that Elastic Transcoder assigned to the job",
  "Input":{
     "AspectRatio":"auto|1:1|4:3|3:2|16:9",
     "Container":"auto|3gp|asf|avi|divx|flv|mkv|mov|mp4|
        mpeg|mpeg-ps|mpeg-ts|mxf|ogg|vob|wav|webm",
     "FrameRate":"auto|10|15|23.97|24|25|29.97|30|60",
     "Interlaced":"auto|true|false",
     "Key":"name of the file to transcode",
     "Resolution":"auto"
  },
  "Output":{
     "Duration":"duration in seconds",
     "Height":"height in pixels",
     "Id":"sequential counter",
     "Key":"name of the transcoded file",
     "PresetId":"PresetId for the job",
     "Rotate":"auto|0|90|180|270",
     "SegmentDuration":"[1,60]",
     "Status":"Submitted|In Progress|Complete|Canceled|Error",
     "StatusDetail":"additional information about job status",
     "ThumbnailPattern":""|"pattern",
     "Width":"width in pixels"
  },
  "Outputs":[
     {
        "Duration":"duration in seconds",
        "Height":"height in pixels",
        "Id":"sequential counter",
        "Key":"name of the transcoded file",
        "PresetId":"PresetId for the job",
        "Rotate":"auto|0|90|180|270",
        "SegmentDuration":"[1,60]",
        "Status":"Submitted|In Progress|Complete|Canceled|Error",
        "StatusDetail":"additional information about job status",
        "ThumbnailPattern":""|"pattern",
        "Width":"width in pixels"
     },
     {...}
  ],
  "PipelineId":"Id of the pipeline that transcoded the job",
  "Playlists":[
     {
        "Format":"HLSv3",
        "Name":"name, no / character allowed",
        "OutputKeys":[
           "Outputs:Key to include in this playlist",
           ...
        ]
     },
     {...}
  ],
  "Status":"Submitted|Progressing|Complete|Canceled|Error"
}
}

For more information see: http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/get-job.html


text:
Q: Permission denied creating folder after setting parent folder as www-data user in my phpinfo configuration, i see the following:
User/Group  www-data(33)/33

In my directory /var/www/html/pluto-php/public/ I see the following for the data directory inside this path:
4 drwxrwxrwx 2 www-data www-data 4096 Sep 19 23:25 data

I also see the following for the pluto-php directory
4 drwxr-xr-x  8 root root  4096 Sep 16 21:49 pluto-php

I set the owner and group for the data dir to www-data. Somehow, after all of this, I still get this error in my php code when running a php script which creates a directory inside the data directory:
Warning: mkdir(): Permission denied in /var/www/html/pluto-php/vendor/pluto/src/Pluto/Stdlib/FilesystemUtils.php on line 32

I tried doing apache2ctl restart and that did nothing.
I've followed along every tutorial on google search and im stuck here.
UPDATE:
Here is my process list
    root@yonaton-Lenovo-V570:/var/www/html# ps aux | grep apache
    root      3234  0.0  0.6 409908 37092 ?        Ss   Sep28   0:09 /usr/sbin/apache2 -k start
    www-data  8516  0.3  0.2 410888 16988 ?        S    10:41   0:00 /usr/sbin/apache2 -k start
    www-data  8517  0.0  0.1 409940 10632 ?        S    10:41   0:00 /usr/sbin/apache2 -k start
    www-data  8518  0.0  0.1 409940 10632 ?        S    10:41   0:00 /usr/sbin/apache2 -k start
    www-data  8519  0.0  0.1 409940 10632 ?        S    10:41   0:00 /usr/sbin/apache2 -k start
    www-data  8520  0.0  0.1 409940 10632 ?        S    10:41   0:00 /usr/sbin/apache2 -k start
    www-data  8521  0.0  0.1 409940 10632 ?        S    10:41   0:00 /usr/sbin/apache2 -k start
    root      8523  0.0  0.0  21292  1088 pts/1    S+   10:41   0:00 grep --color=auto apache

A: Permission denied is invariably an OS level issue. First make sure the user you think the process is running as really is the relevant user. You seem to have done that, but also verify you are not running something like suexec, mpm_itk or mod_ruid which can change the UID indvidual requests run as.
Next, check the path you are trying to write to is traversable by the user (in this case www-data). The namei command can help here:
namei -mo /var/www/html/pluto-php/public/
Next verify if some OS level security software such as SELinux or Apparmor is running and if it is, determine if it is interfering with your process writing to that directory.
Finally a directory permission of 0777 is never needed. 1777 possibly, but if you need  the permissions set to 0777 in order to get it to work, something else is wrong.

A: www-data must have write access to the entire tree.
You can execute chown -R www-data:yourgroup /var/www/html/pluto-php, where yourgroup is the group name of your user (avoid root for security reasons). If you don't specify your groupname, you won't be able to write and read in the data directory.
Next add the right permissions by executing chmod -R 775 /var/www/html/pluto-php.


text:
Q: Django and Bootstrap: offline reload page issue (netdna.bootstrapcdn.com) I have a Django Project that works. I have "bootstrapped" it a bit using in my base_html:
{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
{# Display django.contrib.messages as Bootstrap alerts #}
{% bootstrap_messages %}

in settings.py:
INSTALLED_APPS = (
    'bootstrap_toolkit',
    'bootstrap3',
    'django_admin_bootstrapped.bootstrap3',
    'django_admin_bootstrapped',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'jquery',
    'jquery_ui',
    'homepage',
    'simpleapp',
)

Perfect, if I surf between pages using my buttons&co. it appears bootstrapped and all is ok!
BUT...
I noticed that if my pc is offline, (only) when I reload the page (or I use in some js parent.window.location.reload(true);), it appears not bootstrapped! Moreover I noticed that when I'm online and I reload the page, the browser searches for netdna.bootstrapcdn.com... but this is not my goal: I have to create a project that works offline.
How can I resolve the reload problem?

A: The default settings of django-bootstrap3 point to CDNs as documented:
# Default settings
BOOTSTRAP3 = {

    # The URL to the jQuery JavaScript file
    'jquery_url': '//code.jquery.com/jquery.min.js',

    # The Bootstrap base URL
    'base_url': '//netdna.bootstrapcdn.com/bootstrap/3.3.1/',
    ...

You should store the related files in your static directory and set the jquery_url and base_url settings of bootstrap3. For example:
BOOTSTRAP3 = {

    # The URL to the jQuery JavaScript file
    'jquery_url': '/static/js/jquery.min.js',

    # The Bootstrap base URL
    'base_url': '/static/css/',

    # The complete URL to the Bootstrap CSS file (None means derive it from base_url)
    'css_url': '/static/css/bootstrap.min.css',

    # The complete URL to the Bootstrap CSS file (None means no theme)
    'theme_url': '/static/css/bootstrap.theme.min.css',

    # The complete URL to the Bootstrap JavaScript file (None means derive it from base_url)
    'javascript_url': '/static/js/bootstrap.min.js',

An alternative way would be to hard-code the css and js locations into your templates, like:
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet" type="text/css"/>
<link href="{% static 'css/bootstrap.theme.min.css' %}" rel="stylesheet" type="text/css"/>
<script src="{% static 'js/bootstrap.min.js' %}"></script>

A: If you don't have cache enabled on your browser, it will not store the CSS and JS downloaded from the CDN. To avoid this, either

*

*Enable caching in your browser

*Download the minified bootstrap css and js and place them in your project's static directory. Then link to them like <script src="{% static "bootstrap.min.js" %}"></script>. If you go this route, don't forget to publish your static files.


text:
Q: Cycle through labels in enumeration I'm trying to make a template for science exercises, the way our students have to solve them in secondary school, using the keywords "Given", "Asked" and "Solution" in the margin. I used Latex quite a lot some years ago, but forgot a lot since.
First of all, I'd like to find a way to automatically cycle through these three labels (every question needs to use each label only once). Is it possible to choose a string from a list or an array based on a counter, or something like that?
Second, I don't really dig the workflow I constructed below, needing to make environments in environments and so on. I would like to construct something like
\begin{question}{3}
    Question Three in words
    \given Something automatically in math mode
    \asked Something automatically in math mode
    \sol (No bullet when only a single step)
        \step First step, math mode
        \step First step, math mode
\end{question}

This is my code. As you can see, I only get the keyword "given:" so far
\documentclass[a4paper,12pt]{article}
\usepackage{enumitem}
\usepackage[marginparwidth=1in, reversemp]{geometry}

\newlist{exercise}{enumerate}{3}
\setlist[exercise]{wide = 0pt, listparindent=\parindent,labelsep = 0pt,leftmargin =\labelwidth}
\setlist[exercise, 1]{label =\llap{\textbf{Ex~\arabic*.}\hskip\marginparsep}}
\setlist[exercise, 2]{label = \itshape Given:, labelwidth = 3.5em, leftmargin =\labelwidth}
\setlist[exercise, 3]{label=$\bullet$,labelwidth = 1.333em, leftmargin =\labelwidth}
\let\cat\item
\let\step\item

\begin{document}
\begin{exercise}
\item Calculate the volume of a cylinder with a radius of 2m and a height of 3m.
    \begin{exercise}
        \cat $r = 2 \qquad h = 3$
        \cat $V$
        \cat
        \begin{exercise}
            \step $A = 2 \pi r = 2 \cdot \pi \cdot 2 \Rightarrow A = 12.57 m^2$
            \step $V = A h = 12.57 \cdot 3 \Rightarrow V = 37.70 m^3$
        \end{exercise}
    \end{exercise}
\end{exercise}
\end{document}

A: This solution is based on a few assumptions:

*

*There is only one \asked item

*There is no text after \sol

*If there is only one step, no \step command is used

Here's the code, with comments.
\errorcontextlines=100
\documentclass{article}
\usepackage{siunitx,enumitem,environ,expl3}

\newcounter{exercise}

\ExplSyntaxOn
\NewEnviron{exercise}
 {
  \refstepcounter{exercise}
  \begin{itemize}[label=\textbf{Ex.\@~\theexercise},leftmargin=*]
  \exercise_process:V \BODY
  \end{itemize}
 }
\cs_new_protected:Nn \exercise_process:n
 {
  % split the input at \sol
  \seq_set_split:Nnn \l_exercise_body_seq { \sol } { #1 }
  % get the part before \sol
  \seq_pop_left:NN \l_exercise_body_seq \l_exercise_body_tl
  % get the part after \sol
  \seq_pop_left:NN \l_exercise_body_seq \l_exercise_sol_tl
  % split the input at \asked
  \seq_set_split:NnV \l_exercise_body_seq { \asked } \l_exercise_body_tl
  % get the part before \asked
  \seq_pop_left:NN \l_exercise_body_seq \l_exercise_body_tl
  % get the asked part
  \seq_pop_left:NN \l_exercise_body_seq \l_exercise_asked_tl
  % split the input at \given
  \seq_set_split:NnV \l_exercise_body_seq { \given } \l_exercise_body_tl
  % get the part before \given
  \seq_pop_left:NN \l_exercise_body_seq \l_exercise_text_tl
  % save the \given part
  \seq_set_eq:NN \l_exercise_given_seq \l_exercise_body_seq

  %%% Now put the pieces together
  % issue the text
  \item \tl_use:N \l_exercise_text_tl
  \begin{itemize}[leftmargin=*]
  % process the \given part
  \seq_map_inline:Nn \l_exercise_given_seq { \item[given:] $##1$ }
  % process the \asked part
  \item[asked:] $\tl_use:N \l_exercise_asked_tl$
  % process the \sol part
  \item[solution:]
  \seq_set_split:NnV \l_exercise_body_seq { \step } \l_exercise_sol_tl
  \int_compare:nTF { \seq_count:N \l_exercise_body_seq = 1 }
   { % only one step
     $\tl_use:N \l_exercise_sol_tl$
   }
   { % more steps
    % throw away the first (empty) item
    \seq_pop_left:NN \l_exercise_body_seq \l_tmpa_tl
    \begin{itemize}[label=\textbullet]
    \seq_map_inline:Nn \l_exercise_body_seq { \item $##1$ }
    \end{itemize}
   }
  \end{itemize}
 }
\tl_new:N \l_exercise_text_tl
\tl_new:N \l_exercise_asked_tl
\tl_new:N \l_exercise_sol_tl
\seq_new:N \l_exercise_body_seq
\seq_new:N \l_exercise_given_seq
\cs_generate_variant:Nn \exercise_process:n { V }
\ExplSyntaxOff

\begin{document}

\begin{exercise}
Calculate the length of a circle of radius \SI{1}{m}
  \given r=1
  \asked L
  \sol L = 2 \pi r = 2\cdot\pi\cdot 1\Rightarrow L = \SI{6.28}{m}
\end{exercise}

\begin{exercise}
Calculate the volume of a cylinder with a
radius of \SI{2}{m} and a height of \SI{3}{m}.
  \given r = 2
  \given h = 3
  \asked V
  \sol
    \step A = 2 \pi r = 2 \cdot \pi \cdot 2 \Rightarrow A = \SI{12.57}{m^2}
    \step V = A h = 12.57 \cdot 3 \Rightarrow V = \SI{37.70}{m^3}
\end{exercise}

\end{document}

A: A little different than how you asked it to be, but this is how I'd do it.
\documentclass[a4paper,12pt]{article}
\usepackage{enumitem}
\usepackage[marginparwidth=1in, reversemp]{geometry}

\newcommand{\given}[1]{\item[Given:] $#1$}
\newcommand{\asked}[1]{\item[Asked:] $#1$}
\let\step\item
\newcounter{exercise}
\newenvironment{exercise}[1]{\stepcounter{exercise}
                                \begin{itemize}
                                \item[\bfseries Ex \theexercise.] #1
                                \begin{itemize}
                        }{
                        \end{itemize}
                        \end{itemize}
                        }
\newenvironment{sol}{\begin{itemize}[label={}]}{\end{itemize}}

\begin{document}
\begin{exercise}{Calculate the volume of a cylinder with a radius of 2m and a height of 3m.}
        \given{r = 2 \qquad h = 3}
        \asked{V}
        \begin{sol}
            \step $A = 2 \pi r = 2 \cdot \pi \cdot 2 \Rightarrow A = 12.57 m^2$
            \step $V = A h = 12.57 \cdot 3 \Rightarrow V = 37.70 m^3$
        \end{sol}
\end{exercise}
\end{document}

The exercise environment has an argument which is the Question's text, the exercise number is automatic. Instead of making a sol command it was made an environment so there can be many steps.


text:
Q: Convert given "from date" and "to date" to timestamp in seconds.(android application) I am developing an android application to get a reports from server in json format. So that I need to give a request as "from" date and "to" date in timestamp.
for ex: user will select from date and to date from the dropdown list so that I need to convert that and pass the "from date" to "00:00:00" timestamp and "to date" to 23:59:59 timestamp ..
How to do this in android . Please give advice and suggestions.
Regards
Anand


text: Q: How to setup UPnP Remote Acess service? I am setting up an app in which I have to remotely operate the device (switch) from the other network.From my studies I came to know that it can be done using UPnP.I have implemented the code for local network which is able to operate the device on the same network.But when I change the network I am unable to do so.I went through the UPnP forum pdf and got the theoretical idea of Remote Access implementation.But I didn't get any sample code for the same in any programming language.Is there any sample code for this or at least can somebody suggest me how can I achieve this?


text:
Q: poisson process 2 Suppose that the number of vehicles passing by the stadium entrance A can be
modelled by a homogeneous Poisson process with the rate of 10 vehicles per minute, 15% thereof
being lorries and 85% being cars. Suppose that the types of particular vehicles are independent.
(a)  Find the probability that in 3 mins, at least one lorry passes the stadium entrance A.
(b)  Suppose that during the first minute of observation, exactly 12 lorries have passed by.
Find the expected number of the cars passing the entrance during the same period.
(c)  Suppose that during the first minute of observation, exactly 15 vehicles have passed
by. Find the probability that among these vehicles, there were exactly 3 lorries and 12 cars.
(d)  What is the probability that the first four arriving vehicles are all cars?


text:
Q: Evaluating Racket expression Given these definitions:
(define s 8)
(define p (/ s 2))
(define (f s p)
        (cond [(or (> s 0) p) 'yes] [(< s 0) 'no]))

I want to evaluate this expression:
(f 0 (and (< s p) (> s 2)))

So far I have:
       ⇒    (f 0 (and (< 8 p) (> s 2)))
       ⇒    (f 0 (and (< 8 4) (> s 2)))
       ⇒    (f 0 (and false (> s 2)))
       ⇒    (f 0 false)

How do I finish this?

A: You need to replace this with the body of f (the cond expression) with the parameters replaced by their matching arguments.

A: Racket sees that f is a procedure and evaluates it's arguments:
(f 0 (and (< s p) (> s 2))) ; ==>
(f 0 (and (< 8 4) (> 8 2))) ; ==>
(f 0 (and #f #t))           ; ==>
(f 0 #f)                    ; s=0, p=#f

Then the arguments is substituted for the variables in the body of f:
; ==>
(cond [(or (> 0 0) #f) 'yes]
      [(< 0 0) 'no])

since both (or (> 0 0) #f) and (< 0 0) are #f the result is the undefined value chosen by the implementation. In racket it's #<void>
; ==>
#<void>

This could have been avoided by always have a else term:
(define (f s p)
  (cond [(or (> s 0) p) 'yes]
        [(< s 0) 'no]
        [else 'banana]))

(f 0 (and (< s p) (> s 2))) ; ==> banana


text:
Q: Ember Way to Add Rss Feed without third party widget, Front-end only I am using Ember 3.0 at the moment. Wrote my first lines of code in ANY language about 1 year ago (I switched careers from something totally unrelated to development), but I quickly took to ember. So, not a ton of experience, but not none. I am writing a multi-tenant site which will include about 20 different sites, all with one Ember frontend and a RubyOnRails backend. I am about 75% done with the front end, now just loading content into it. I haven't started on the backend yet, one, because I don't have MUCH experience with backend stuff, and two, because I haven't needed it yet. My sites will be informational to begin with and I'll build it up from there.
So. I am trying to implement a news feed on my site. I need it to pull in multiple rss feeds, perhaps dozens, filtered by keyword, and display them on my site. I've been scouring the web for days just trying to figure out where to get started. I was thinking of writing a service that parses the incoming xml, I tried using a third party widget (which I DON'T really want to do. Everything on my site so far has been built from scratch and I'd like to keep it that way), but in using these third party systems I get some random cross domain errors and node-child errors which only SOMETIMES pop up. Anyway, I'd like to write this myself, if possible, since I'm trying to learn (and my brain is wired to do the code myself - the only way it sticks with me).
Ultimately, every google result I read says RSS feeds are easy to implement. I don't know where I'm going wrong, but I'm simply looking for:
1: An "Ember-way" starting point. 2: Is this possible without a backend? 3: Do I have to use a third party widget/aggregator? 4: Whatever else you think might help on the subject.
Any help would be appreciated. Here in New Hampshire, there are basically no resources, no meetings, nothing. Thanks for any help.

A: Based on the results I get back when searching on this topic, it looks like you'll get a few snags if you try to do this in the browser:

*

*CORS header issues (sounds like you've already hit this)

*The joy of working with XML in JavaScript (that just might be sarcasm , it's actually unlikely to be fun)

If your goal is to do this as a learning exercise, then doing it Javascript/Ember will definitely help you learn lots of new things. You might start with this article as a jumping off point: https://www.raymondcamden.com/2015/12/08/parsing-rss-feeds-in-javascript-options/
However, if you want to have this be maintainable for the long run and want things to go quickly and smoothly, I would highly recommend moving the RSS parsing system into your backend and feeding simple data out to Ember. There are enough gotchas and complexities to RSS feeds over time that using a battle-tested library is going to be your best way to stay sane. And loading that type of library up in Ember (while quite doable) will end up increasing your application size. You will avoid all those snags (and more I'm probably not thinking of) if you move your parsing back to the server ...


text:
Q: DegradedArray event Since yesterday, my server is sending mails like this :
A DegradedArray event had been detected on md device /dev/md2
P.S. The /proc/mdstat file currently contains the following:

Personalities : [linear] [raid0] [raid1] [raid10] [raid6] [raid5] [raid4] [multipath] [faulty]
md1 : active raid1 sdb1[1] sda1[2](F)
      20478912 blocks [2/1] [_U]

md2 : active raid1 sdb2[1] sda2[2](F)
      96211904 blocks [2/1] [_U]

My hoster told me that one disk has failed and needs to be replaced but before that I need to resync disks. The hoster wants me to pay 250$ for that and I don't have that money.
How can I do resync disks myself please ?
Edit : result of fdisk -l /dev/sda
Disk /dev/sda: 120.0 GB, 120034123776 bytes
255 heads, 63 sectors/track, 14593 cylinders, total 234441648 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000e429d

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        4096    40962048    20478976+  fd  Linux raid autodetect
/dev/sda2        40962049   233385984    96211968   fd  Linux raid autodetect
/dev/sda3       233385985   234432512      523264   82  Linux swap / Solaris

Edit 2 : new results
sudo mdadm --re-add /dev/md1 /dev/sda1
mdadm: Cannot open /dev/sda1: Device or resource busy
root@ns3279053:~# sudo mdadm --remove /dev/md1 /dev/sda1
mdadm: hot removed /dev/sda1 from /dev/md1
root@ns3279053:~# sudo mdadm --add /dev/md1 /dev/sda1
mdadm: failed to write superblock to /dev/sda1

A: You can try to resync your disks only if the other disk shown with F namely sda can be accessed. You can try to enumerate the partitions and see if the disk is accessible using fdisk -l /dev/sda.
If not accessible, you need to replace the HD drive and install a new one, partition it, and then resync the raid array.
You can try to re-add the failed member to the mdadm array using the following commands:
sudo mdadm --re-add /dev/md1 /dev/sda1

If you got resource or device busy error, you can try the following:
sudo mdadm --remove /dev/md1 /dev/sda1
sudo mdadm --add /dev/md1 /dev/sda1

You can do it similarly for the other device /dev/md2 by adding /dev/sda2


text:
Q: Add list as row in pandas dataframe I have a multiple lists as:-
A = [1,2,3,4,5]
B = [3,4,5,5,7]
C = [6,54,3,2,8,9,9]
D = [3,2,54,33,45,55,5]
.........so on

All I want to append this list as row into pandas dataframe df as column digits-
Something as,
print (df)

digits
[1,2,3,4,5]
[3,4,5,5,7]
[6,54,3,2,8,9,9]
[3,2,54,33,45,55,5]
.............
............


text:
Q: is there a way to add a bookmark that is different than the text in the pdf document using migradoc, i see how you can add a bookmark automatically by doing this:
Paragraph p1 = document.LastSection.AddParagraph("Project Updates", "Heading2");

but what if i want to add a bookmark that says "Updates" but the text in the paragraph header says "My Project Updates"
is that possible?

A: When I needed bookmarks without visible text, I used a hack: white text with a very small font size (0.01).
I also created a style "Heading1WithoutBookmark" that is a clone of Heading1 but with
style.ParagraphFormat.OutlineLevel = OutlineLevel.BodyText;

This allows me to have the bookmark point to a page that only contains an image while the text is showing on the following page.
It also allows to have different text on the page and in the bookmark.


text:
Q: How can STM32 HID send a packet less than 64 Byte? I am using STM32F103 with "STM32_USB-FS-Device_Lib_V4.0.0" to send data to PC. The send function in STM32 is:
void USB_Send(unsigned char *p,u8 len)
{
    UserToPMABufferCopy(p, GetEPTxAddr(ENDP1), len);
    SetEPTxCount(ENDP1, len);
    SetEPTxValid(ENDP1);
    while(GetEPTxStatus(ENDP1)!=EP_TX_NAK);
}

But what's strange is when len=64, data received properly by a C# program that I write and a debug tool that I download. But when len<64 nothing can be received. I tried "Bus Hound" a USB packet sniffer, and the packet that less than 64 can be logged by the sniffer, but the readdata function in my program was never entered.
I also tried to change the value of MaxPacketSize in ConfigDescriptor and REPORT_COUNT in ReportDescriptor in STM32 program, but they doesn't work.
Does HID limit that the length of one packet must be a certain value, if length is less than the value, extra data must be filled at the end of packet until the length equals certain value?
Can someone give me some help or hint, thank you!

Complement:
I have tried to send two 32Bytes packets without delay, and it didn't work.
Here is my C# receive code:
//Init code:
HIDP_CAPS capabilities = new HIDP_CAPS();
int hidCapsSucsess = HidP_GetCaps(ptrToPreParsedData, ref capabilities);  //HidP_GetCaps is a win API
SafeFileHandle handle_read = CreateFile(devicePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);  //CreateFile is a win API
FileStream FS_read = new FileStream(handle_read, FileAccess.ReadWrite, capabilities.OutputReportByteLength, false);
//...
//Receive code:
public byte[] read()
{
    byte[] readBuf = new byte[capabilities.OutputReportByteLength];
    FS_read.Read(readBuf, 0, capabilities.OutputReportByteLength);
    return readBuf;
}

I tried to change the value of REPORT_COUNT of output in ReportDescriptor in STM32. Breakpoint debugging shows "capabilities.OutputReportByteLength" was changed but what's strange is it equals REPORT_COUNT+1. Furthermore, when the "capabilities.OutputReportByteLength" is less than 65, an error occurred:"The supplied user buffer is not valid for the requested operation" in "FS_read.Read".


text:
Q: Change TextView from AsyncTask The code below is going to act as a Timer. I was testing out the AsynchTask, when my app simply doesn't load the XML view. My code should work, but the view is not opening up. I later did some testing and moves the TextView variable "display" around a little and eventually got the view to show up, but the start button press didn't work... Can anyone tell me how I could get the TextView to update and run properly? Thanks!
THE ENTIRE LAYOUT IS NOT DISPLAYING....
 public class MainActivity extends Activity {
timer tim = new timer();
boolean running = true;
int milli = 0;
int secs = 0;
int mins = 0;
int hours = 0;
ArrayList<Lap> laps = new ArrayList<Lap>();
TextView display = (TextView) findViewById(R.id.textView1); //whats going on?
LinearLayout lapsView = (LinearLayout) findViewById(R.id.lapsView);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    try{
    Button b1 = (Button) findViewById(R.id.start);
    b1.setOnClickListener(startTimer);

    Button b2 = (Button) findViewById(R.id.stop);
    b2.setOnClickListener(stopTimer);
    }
    catch(Exception e1){

    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

private OnClickListener startTimer = new OnClickListener() {
    public void onClick(View v) {
        if(!running){
        startWatch();
        }
        else if(running){
            try{
            tim.execute(""); //start the task
            }
            catch(Exception e1){
                Toast.makeText(MainActivity.this, "Error starting: "+e1, Toast.LENGTH_LONG).show();
            }
        }
    }
};

private OnClickListener stopTimer = new OnClickListener() {
    public void onClick(View v) {
        if(running){
        stopWatch();
        }
    }
};

public void startWatch(){
    running = true;
}
public void stopWatch(){
    running= false;
}

 public class timer extends AsyncTask<String, Void, String> {
    ////NOT WORKING!!!!
    @Override
protected String doInBackground(String... params) {
    while(true){
        while(!running){
            ///Do Nothing...
        }
            while(milli < 1000 && running){
            running = true;
            milli++;
            try{
                Thread.sleep(1);
            }
            catch(Exception e1){
                System.out.println(e1);
            }
            if(milli == 1000){
                milli = 0;
                secs++;
            }
            if(secs == 60){
                secs = 0;
                mins++;
            }
            if(mins == 60){
                hours++;
                mins = 0;
            }

            display.setText(milli+":"+secs+":"+mins+":"+hours);
        }
        }
    }
    }

 }

Debug Errors....
  Thread [<1> main] (Suspended (exception RuntimeException))
<VM does not provide monitor information>
ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2053
ActivityThread.handleLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2154
ActivityThread.access$700(ActivityThread, ActivityThread$ActivityClientRecord, Intent) line: 146
ActivityThread$H.handleMessage(Message) line: 1260
ActivityThread$H(Handler).dispatchMessage(Message) line: 99
Looper.loop() line: 137
ActivityThread.main(String[]) line: 4949
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 511
ZygoteInit$MethodAndArgsCaller.run() line: 1043
ZygoteInit.main(String[]) line: 810
NativeStart.main(String[]) line: not available [native method]

A: You asyncTask can't update the UI on the doInBackground method. To do this, you'll call publishProgress from doInBackground and update the TextView there.
    public class timer extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        while(true){
            while(milli < 1000 && running){
                running = true;
                milli++;
                try{
                    Thread.sleep(1);
                }
                catch(Exception e1){
                    System.out.println(e1);
                }
                if(milli == 1000){
                    milli = 0;
                    secs++;
                }
                if(secs == 60){
                    secs = 0;
                    mins++;
                }
                if(mins == 60){
                    hours++;
                    mins = 0;
                }

                this.publishProgress(milli+":"+secs+":"+mins+":"+hours);
            }
        }
    }
    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        TextView display = (TextView) findViewById(R.id.textView1);
                 display.setText(values[0]);
    }

}