text:
Q: How to change estimote beacon UUID using AndroidSDK I'm trying to change the UUID of the estimote beacons and have not found a specific API for this, anyone have any example or help?

A: Here you have, It's the same for the proximityUUID but you gotta change the writeMajor by writeProximityUuid.
private void setMajorID(final int majorid,final Beacon beacon) {

        mMajorsConnection = new BeaconConnection(this, beacon, new BeaconConnection.ConnectionCallback() {
            @Override
            public void onAuthenticated(BeaconConnection.BeaconCharacteristics chars) {
                Log.d(TAG, "Authenticated to beacon: " + chars);
                mMajorsConnection.writeMajor(majorid, new BeaconConnection.WriteCallback() {
                    @Override
                    public void onSuccess() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mAdapter.update(beacon);
                            }
                        });
                        Log.d(TAG, "Successfully writted the major id!");
                        mMajorsConnection.close();
                    }

                    @Override
                    public void onError() {
                        Log.d(TAG, "Error while writting the major id!");
                    }
                });
            }

            @Override
            public void onAuthenticationError() {
                Log.d(TAG, "Authentication Error");
            }

            @Override
            public void onDisconnected() {
                Log.d(TAG, "Disconnected");
            }
        });
            mMajorsConnection.authenticate();
    }

A: You can use the writeProximityUuid method of the BeaconConnection class.


text:
Q: Touch device HTML element :hover state There is a HTML button, with 3 backgrounds - each for normal, hover and clicked states. Of course, it works fine with non touch device. If the button is clicked on touch device, the :hover state is also triggered and stays until another element is touched.
Is it possible to programmatically remove :hover state from element after it was clicked or prevent it from activating on touch devices?
Sorry, but suggestions to a detect mouseover and mouseout events and add artificial classes are not accepted.
One possible solution is to add "no-touch" class to html element in advance and remove it if only touch device is detected. In that case, CSS selector "html.no-touch button:hover" will not match for touch device.
Do you know more elegant solutions you may suggest?

A: I would try to overwrite the :hover state in an additional style-sheet for handheld devices like:
<link rel="stylesheet" type="text/css" href="handheld.css" media="handheld">

and in handheld.css put something like:
#some_selector:hover {
    background: none;    /* if you are setting a background in the main css file for example */
}

However, I´m not sure if handheld and touch screen are completely the same, there might be devices that have a touch screen and are not qualified as a handheld.
Edit: It seems you cannot detect touch screen devices 100% reliably, also see this question.

A: Seems that this issue can be resolved by overwriting the :hover state for a given element in media query - see this question:
CSS hover not being ignored on touch screen devices

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to show a specific div with its own id in jQuery when I click a link? I have a div like this:

blablabla

that I have hided with jQuery
$('article').hide();

now I'd like to have a link menu that show a specific article id when it's clicked for example.
If I click on link:
 LINK PIPPO

I'd like that the article named #pippo is shown
if I click on link that point to #pluto, an article with id #pluto have to be shown...
how can I do this in jQuery?

A: If you want this to work for every  tag on your page then you can do the following
$('a').click(function (e) {
  var id = $(this).attr('href');
  $(id).show();

  // Don't follow the link
  e.preventDefault();
});

More likely though you want this to work on a subset of  on the page.  If so you can distinguish them by putting a class in the link and changing your selector as appropriate
HTML:
 LINK PIPPO

JavaScript:
$('a.fakeLink').click(function (e) {
  var id = $(this).attr('href');
  $(id).show();

  // Don't follow the link
  e.preventDefault();
});

A: Try this
$("a").click(function(){

   $(this.href).show();

   return false;

});

A: First add a class to identify the anchor tags that need this functionality, eg. 'visibility_toggle'. Then add a handler that uses the href attribute to work out which div to show/hide.
$('a.visibility_toggle').click(function(e) {
    $(this.href).toggle();
    e.preventDefault();
});


text:
Q: Analytic function on unit disk, Schwartz lemma type inequality Let $f:\Bbb{D}\to\Bbb{C}$ be an analytic function that satisfies the inequality $|f(z)|\le\dfrac{1}{1-|z|}.$
How can I show that $|f'(0)|\le 4.$

Also, I am looking for the equality case. Is this a sharp upper bound?

A: We can show that $|f'(0)|\le 4$ using Cauchy's Integral Formula
$$f'(0)=\frac{1}{2\pi i}\oint_{|z|= r<1}\frac{f(z)}{z^2}\,dz \tag1$$
Taking the magnitude of both sides of $(1)$ reveals
$$\begin{align}
|f'(0)|&=\left|\frac{1}{2\pi i}\oint_{|z|=r<1}\frac{f(z)}{z^2}\,dz\right|\\\\
&\le \frac{1}{2\pi }\oint_{|z|= r<1}\frac{|f(z)|}{|z^2|}\,|dz|\\\\
&=\frac1{2\pi}\frac{(2\pi r )\left(\frac{1}{1-r}\right)}{r^2}\\\\
&=\frac{1}{r(1-r)}\tag 2
\end{align}$$
The minimum of $\frac{1}{r(1-r)}$ occurs when $r=1/2$ in which case we have
$$|f'(0)|\le 4$$
as was to be shown!

A: With the Schwarz lemma I get :
If $r \in (0,1)$ then for $|z| < 1$ : $|f(rz)| \le \frac{1}{1-r}$ and $|f(0)| \le 1$ so that $$g(z)=\frac{f(rz)-f(0)}{1+\frac{1}{1-r}}$$
is analytic on $\mathbb{D} \to \mathbb{D}$ and $g(0) = 0$. Thus by Schwarz's lemma $$1 \ge  |g'(0)| = \left|\frac{r f'(0)}{1+\frac{1}{1-r}}\right|=|f'(0)|\frac{r(1-r)}{2-r}$$
whose optimum is at $r \approx 0.6$ with $\frac{r(1-r)}{2-r} \approx 0.18$
I wonder if there is a way to improve this to $|f'(0)| \le 4$ as Mark Viola did with the Cauchy's integral formula.


text:
Q: Recommended way to enable touch events in Bootstrap 3? Now that Bootstrap 3 is out, what is the recommended option for enabling touch? As before, there aren't many touch events in the bootstrap.js, though it is supposed to be a mobile first framework.
The last thing I've found on github suggests using fastclick.js, but that was before the v3.0 release.

A: My recommendation is to use Bootstrap alongside JQuery mobile, TouchSwipe, or Hammer.js . An example of a bootstrap touch carousel can be found here.

A: Start working on another fully working Touch Carousel on GitHub. This also includes drag events...

A: Despite I believe bootstrap is a joke of a css framework (especially due to no multileveled navigation), I would probably agree with others to go with some different carousel if you have a choice.
From my experience JQuery mobile will work rather smoothly but my site was not built alongside jquery mobile and the css belonging to it really messed the things up.
<script>
    $(document).ready(function() {
        $('.carouselresp').carousel({'data-interval': 6000, 'data-pause': "hover"});
        var clicking = false;
        var currentMousePos = 0;
        var newMousePos = 0;

        $('.carouselresp img').on('mousedown', function(event) {
            clicking = true;
            currentMousePos = event.pageX;
        });

        $('.carouselresp img').on('touchstart', function(event) {
            clicking = true;
            var touchstart = event.originalEvent.touches[0];
            currentMousePos = touchstart.pageX;
        });

        $(document).on('mouseup', function(event) {
            clicking = false;
        });

        $('.carouselresp img').on('touchend', function(event) {
            clicking = false;
        });

        $(document).on('mousemove', function(event) {
            if (!clicking) {
                return;
            }else {
                if (event.pageX < currentMousePos) {
                    if ((currentMousePos - event.pageX) > 50) {
                        $('.carouselresp').carousel('next');
                        clicking = false;
                    }
                } else {
                    if ((event.pageX - currentMousePos) > 50) {
                        $('.carouselresp').carousel('prev');
                        clicking = false;
                    }
                }
            }
        });

        $('.carouselresp img').on('touchmove', function(event) {
            var touch = event.originalEvent.touches[0];
            if (!clicking) {
                return;
            }else {
                if (touch.pageX < currentMousePos) {
                    if ((currentMousePos - touch.pageX) > 50) {
                        $('.carouselresp').carousel('next');
                        clicking = false;
                    }
                } else {
                    if ((touch.pageX - currentMousePos) > 50) {
                        $('.carouselresp').carousel('prev');
                        clicking = false;
                    }
                }
            }
            event.preventDefault();
        });
    });

</script>

It works fine for me on android and iphone too, plus I am allowing the move event in browsers with no touch support.
I hope it helped.
TomHre


text: Q: Problems running KOTOR I in Virtual Box My host machine is running Ubuntu 18.04.4 LTS and the virtual box is running Windows xp. I'm trying to run KOTOR 1 through shared files but I keep getting hit with error 5:0000065434. Looking it up it seems this error is caused by Steam.exe being on a different drive than the game and the bandaid solution is to just copy and paste Steam.exe into the games file folder. But since linux doesn't have .exe files (I think, I'm still a little new to this) how can I get this to work?


text:
Q: In JMockit throw exception for a method Apologies, It may sound a duplicate question.
After googling it I tried to use:
result = new Exception();
but had no luck.
MainClass
public class DemoClass
{
    public void processMessage(String message)
    {
        System.out.println("Inside process method. processing message: " + message);
        if (message.isEmpty())
        {
            new IllegalArgumentException();
        }
    }

    public void retry(String message)
    {
        try
        {
            processMessage(message);
        }
        catch (IllegalArgumentException e)
        {
            System.out.println("Reprocessing of process method failed");
            finalMessage(message);
        }
    }

    public void finalMessage(String message)
    {
        System.out.println("Inside finalMessage method. " + message);
    }
}

TestClass
import mockit.Expectations;
import mockit.integration.junit4.JMockit;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(JMockit.class)
public class DemoClassTest
{
    @Test
    public void test() {
        DemoClass demoClass = new DemoClass();
        String message = "Hello World";
        new Expectations() {{

           demoClass.processMessage(message);
           result = new IllegalArgumentException();
           times = 1;

            demoClass.finalMessage(message);
            times = 1;
        }};

        demoClass.retry(message);

    }
}

While running above test class i am getting below error
Inside process method. processing message: Hello World
java.lang.IllegalStateException: **Missing invocation to mocked type at this point; please make sure such invocations appear only after the declaration of a suitable mock field or parameter**

I want to throw error on call of processMessage() method, so that catch block gets executed.

A: You need to do Partial Mocking
@Test
public void test() {
    DemoClass demoInstance = new DemoClass();

    String message = "Hello World";

    new Expectations(demoInstance) {{
        demoInstance.processMessage(message);
        result = new IllegalArgumentException();
        times = 1;

        demoInstance.finalMessage(message);
        times = 1;
    }};

    demoInstance.retry(message);
}

Notice that we're passing the demoInstance instance to the new Expectations block.


text:
Q: Given a transformation matrix $L$, how can I find a basis $B$ for which the same transformation is the identity matrix $I$? $L: V \to W$ where $V$ is the vector space of all polynomials with degree $n \leq2$, $W = \mathbb R^3$ and $L$ is the linear transformation that maps each polynomial $p \in V$ to the vector $w \in W$ where $w_1, w_2, w_3$ correspond to $p$ evaluated at $-1, 0, 1$ respectively.
For the basis $(x^2,x,1)$  the matrix $L$ should be equal to $\begin{pmatrix}1 & -1 & 1 \\0 & 0 & 1 \\1 & 1 & 1 \\\end{pmatrix}$. Now I need to find a basis $B$ such that $L'=I$ where $I$ is the identity matrix.
My reasoning is that we could have a change of basis matrix $A$ and then $A^{-1}LA=I$, if we find $A^{-1}$ we can find $B$ since $B=A^{-1}$. If we multiply $A^{-1}LA=I$ by $A$ on both sides we get $LA=A$ and hence $L=I$ which is a contradiction. Where is my error?

A: Hint:
Think of Lagrange's interpolation polynomial:  you have to find quadratic polynomials $p_1,p_2,p_3$ such that
$$\begin{cases}p_1(-1)=1,& p_1(0)=p_1(1)=0, \\[1ex] p_2(0)=1,& p_2(-1)=p_2(1)=0, \\[1ex]
p_3(1)=1,& p_1(-1)=p_1(0)=0.
\end{cases}$$

A: You can't find such a change of basis, since then the only eigenvalue would be $1$.  In fact the characteristic polynomial is $(x-1)^2x-1-1-x=x^3-2x^2-2$, so $1$ is not an eigenvalue at all (much less the only one).
You and @uniquesolution correctly noted that if there were such a change of basis, then your original matrix would be the identity, since we would have $ALA^{-1}=I\implies L=A^{-1}IA=I$.

However, as @Bernard notes, it is possible if you allow a different basis for the domain and the range.  Change the basis for $V$ to $\{1/2x(x-1), -(x+1)(x-1),1/2x(x+1)\}$, so that the change of basis matrix is $L^{-1}$.


text:
Q: Could not start 2 embedded active-mq on different ports within different spring boot applications I have 2 spring-boot applications. Each application has embedded active mq broker.
I need to have 2 applications working on the same PC in parallel but it doesn't work now. First application always starts successfully:
2018-02-02 11:48:20.095  INFO 7660 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@53045c6c: startup date [Fri Feb 02 11:48:20 MSK 2018]; root of context hierarchy
2018-02-02 11:48:20.923  INFO 7660 --- [  JMX connector] o.a.a.broker.jmx.ManagementContext       : JMX consoles can connect to service:jmx:rmi:///jndi/rmi://localhost:7777/jmxrmi
2018-02-02 11:48:20.923  INFO 7660 --- [           main] o.apache.activemq.broker.BrokerService   : Using Persistence Adapter: KahaDBPersistenceAdapter[D:\work\arbitrage_robot\root\activemq-data\localhost\KahaDB]
2018-02-02 11:48:21.231  INFO 7660 --- [           main] o.a.a.store.kahadb.MessageDatabase       : KahaDB is version 6
2018-02-02 11:48:21.260  INFO 7660 --- [           main] o.a.a.store.kahadb.plist.PListStoreImpl  : PListStore:[D:\work\arbitrage_robot\root\activemq-data\localhost\tmp_storage] started
2018-02-02 11:48:21.395  INFO 7660 --- [           main] o.apache.activemq.broker.BrokerService   : Apache ActiveMQ 5.15.2 (localhost, ID:ntkachev-60101-1517561301266-0:1) is starting
2018-02-02 11:48:21.441  INFO 7660 --- [           main] o.a.a.t.TransportServerThreadSupport     : Listening for connections at: tcp://127.0.0.1:61617?broker.persistent=false
2018-02-02 11:48:21.442  INFO 7660 --- [           main] o.a.activemq.broker.TransportConnector   : Connector tcp://127.0.0.1:61617?broker.persistent=false started
2018-02-02 11:48:21.442  INFO 7660 --- [           main] o.apache.activemq.broker.BrokerService   : Apache ActiveMQ 5.15.2 (localhost, ID:ntkachev-60101-1517561301266-0:1) started
2018-02-02 11:48:21.442  INFO 7660 --- [           main] o.apache.activemq.broker.BrokerService   : For help or more information please see: http://activemq.apache.org
2018-02-02 11:48:23.002  INFO 7660 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-02-02 11:48:23.021  INFO 7660 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 2147483647
2018-02-02 11:48:23.024  INFO 7660 --- [           main] o.a.activemq.broker.TransportConnector   : Connector vm://localhost started
2018-02-02 11:48:23.051  INFO 7660 --- [           main] pack.Application                 : Started Application in 3.337 seconds (JVM running for 3.922)

but second freezes and print:
2018-02-02 11:48:30.450  INFO 17008 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@53045c6c: startup date [Fri Feb 02 11:48:30 MSK 2018]; root of context hierarchy
2018-02-02 11:48:31.296  INFO 17008 --- [           main] o.apache.activemq.broker.BrokerService   : Using Persistence Adapter: KahaDBPersistenceAdapter[D:\work\app\root\activemq-data\localhost\KahaDB]
2018-02-02 11:48:31.297  INFO 17008 --- [  JMX connector] o.a.a.broker.jmx.ManagementContext       : JMX consoles can connect to service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi
2018-02-02 11:48:31.300  INFO 17008 --- [           main] o.a.activemq.store.SharedFileLocker      : Database activemq-data\localhost\KahaDB\lock is locked by another server. This broker is now in slave mode waiting a lock to be acquired

Both applications have approximately the same configuration:
@SpringBootApplication
public class Application {

  @Bean
  public BrokerService broker() throws Exception {
    BrokerService broker = new BrokerService();
    broker.addConnector("tcp://localhost:61616?broker.persistent=false");
    return broker;
  }

  @JmsListener(destination = "robotCommand")
  public void listen(String in) {
      System.out.println(in);
  }

and following dependencies:
   <dependency>
        <groupId>org.apache.activemq</groupId>
        <artifactId>activemq-kahadb-store</artifactId>
        <version>5.15.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.activemq</groupId>
        <artifactId>activemq-broker</artifactId>
        <version>5.15.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-activemq</artifactId>
        <version>1.5.10.RELEASE</version>
    </dependency>

How can I fix this(application hanging on startup)?

A: your config broker.addConnector("tcp://localhost:61616?broker.persistent=false"); is wrong, this is can be done only if you create a broker using ActiveMQConnectionFactory, http://activemq.apache.org/how-do-i-embed-a-broker-inside-a-connection.html#HowdoIembedaBrokerinsideaConnection-UsingActiveMQConnectionFactory
Using ActiveMQConnectionFactory
An embedded broker can also be created using an ActiveMQConnectionFactory and using a vm connector as a uri. e.g.
ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");

try
 @Bean
  public BrokerService broker() throws Exception {
    BrokerService broker = new BrokerService();
    broker.addConnector("tcp://localhost:61616");
    broker.setPersistent(false);
    return broker;
  }


text:
Q: What are main reasons of input splitting in MapReduce? In MapReduce papers is described that input files are partitioned in M input splits. I know the HDFS in Hadoop makes partitioning automatically to blocks of 64 MB (default) and then replicate these blocks to few other nodes in cluster for providing fault tolerance. I'd like to know if this partitioning of files in HDFS means the input splitting described in mentioned MapReduce papers. Is fault tolerance single reason of this splitting or are there more important reasons?
And what if I have MapReduce over cluster of nodes without distributed file system (data only on local disks with common file sytem)? Do I need to split input files on local disk before map phase?
Thank you for your answers.

A: Would Like to Add few Missing concept (ans is confusing for me )

HDFS
A file is stored as blocks(Fault/Node Tolerance) .The block size (64MB-128MB) 64MB. So a file is divided in blocks, blocks are stored on different Nodes on cluster. A block is being replicated by a replication factor(default =3).
Map-Reduce
The file which is already stored in HDFS is logically divided into INPUT-SPLITS.
The splits size can be set by the user
Property name           Type   Default value

mapred.min.split.size   int     1
mapred.max.split.sizea  long    Long.MAX_VALUE.

And then the split size is calculated by the formula:
max(minimumSize, min(maximumSize, blockSize))
NOTE:: The Split are logical

Hope to ans your questions now
 I'd like to know if this partitioning of files in HDFS means the input splitting described in mentioned MapReduce papers.

NO, Not at all HDFS blocks and Map-Reduce splits are the same thing.
Is fault tolerance single reason of this splitting or are there more important reasons?

No , Distributed computing will be the reason.
And what if I have MapReduce over cluster of nodes without distributed file system (data only on local disks with common file sytem)? Do I need to split input files on local disk before map phase?

In your case ,I Guess ,Yes you will have to split the input-file for Map Phase , and also you will have to split the intermediate output(from Mapper) for Reduce Phase.
Other prob : consistency of Data,Fault tolerance,Data Loss(in hadoop its =1%).
Map-Reduce is made for Distributed Computing , so using Map-Reduce in Non-Distributed environment is not useful.
Thanks

A: I'd like to know if this partitioning of files in HDFS means the input splitting described in mentioned MapReduce papers.

No, the input splitting in MapReduce is to take advantage of the computing capacity of multiple processors during the reduce phase. The mapper takes in a large amount of data and splits the data into logical partitions (most of the times as specified by the custom implementation of the mapper by the programmer). This data then goes to individual nodes where  independent processes called reducers perform the data crunching and then, the result gets collated in the end.
Is fault tolerance single reason of this splitting or are there more important reasons?

No, it is not the single reason for doing so. You can compare it to the file-system level block size for ensuring transfer of data into chunks, compression of data on a per-block basis and allocation of I/O buffers.


text:
Q: Finite etale covers of pro-curves Let $X$ be an inverse limit of integral, normal affine curves $X_i = Spec(A_i)$ where all the transition maps are finite etale covering maps (so in particular $X$ exists in the category of schemes), and all the curves are over some field $k$. Let $F$ be the function field of $X$, so $F$ is the union of the function fields $F_i$ of each $X_i$, or alternatively the fraction field of $A$, the union of the $A_i$.
Now let $f \in A^* \setminus (A^*)^p$. Let $Y$ be the normalization of $X$ in $F(f^{1/p})$.
Is the morphism $Y \rightarrow X$ constructed above a finite etale cover?
I have some reasons for suspecting the answer might be no, but am very unsure. The problem seems to be that $A$ is not noetherian, I think, and so the normalization might fail to be finite.

A: If $f \in A^*$ then there exists an $i$ such that $f \in A_i^*$. Then you obtain an etale cover of $\operatorname{Spec} A_i$. It is easy to see that $Y$ is the base change of this etale cover from  $\operatorname{Spec} A_i$ to $X$, hence is etale.


text:
Q: How to read values from a view to insert in ratingValue and ratingCount in my web in order to be recognized by Google Structured data testing tool? I was using an external service to get Aggregate Rating in my recipes blog, but dis service disappeared so I decided to build one myself. First of all, this is my first experience with cloud data and JavaScript programming so please, be paciente with me :-).
I'm doing my experiments in this duplicate of my blog: https://jleavalc.blogspot.com/
by now it works as I planned, letting one to vote and storing results in a oracle table, making it possible to retrieve results from a view of this table to get ratingCount and ratingValue values, as anyone can see in that link...
But at the end, despite you can see the stars, despite you can vote and get result stored, showing voting results, Structured data testing tool don't see tag values, so all work is useless.
I think I'm getting close to the problem, but not getting close to the solution. I have the impression that the cause of my problems is the asynchrony of the execution of the script that brings the data from the table, while the function is executed, the browser continues to render the page and it doesn't arrive in time to write those values before the google tool can read them, so they appear empty to it.
I have tried everything including labels and variables in GTM with the same result. The latest version of the code, from this morning is installed right before the "/head" tag and it looks like this:
  <script style='text/javascript'>
  var myPostId = "<data:widgets.Blog.first.posts.first.id/>";

// <![CDATA[
  var micuenta = 0;
  var nota = 0;
  getText("https://ge4e65cc87f573d-XXXXXXXXXXXX.adb.eu-amsterdam-1.oraclecloudapps.com/ords/admin/notas/?q={\"receta\":{\"$eq\":\"" + myPostId + "\"}}");
  async function getText(file) {
    let x = await fetch(file);
    let y = await x.text();
    let datos = JSON.parse(y);
    nota =  datos.items[0].media;
    micuenta =  datos.items[0].votos;
  };

// This version gives the same result and is interchangeable with the previous one. I keep it commented so as not to forget it:
// var settings = {
//  "url": "https://ge4e65cc87f573d-db20220526112405.adb.eu-amsterdam-1.oraclecloudapps.com/ords/admin/notas/?q={\"receta\":{\"$eq\":\"" + myPostId + "\"}}",
//  "method": "GET",
//  "timeout": 0,
// "async": false,
// };
// $.ajax(settings).done(function (response) {
//     if (response.items.length != 0) {
//  micuenta = response.items[0].votos;
// nota = response.items[0].media;
//        }
//  });
</script>

The key is, I think, getting this call to execute before Google's tool finishes rendering the Blogger post page.
The URL that I invoke to get the data calls an oracle view that returns a single row with the corresponding data from the recipe, placing this call:
recipe
In the browser the result is the following:
{"items":[{"receta":"5086941171011962392","media":4.5,"votos":12}],"hasMore":false,"limit":25,"offset":0,"count":1,"links":[{"rel":"self","href":"https://ge4e65cc87f573d-db20220526112405.adb.eu-amsterdam-1.oraclecloudapps.com/ords/admin/notas/?q=%7B%22receta%22:%7B%22%24eq%22:%225086941171011962392%22%7D%7D"},{"rel":"edit","href":"https://ge4e65cc87f573d-db20220526112405.adb.eu-amsterdam-1.oraclecloudapps.com/ords/admin/notas/?q=%7B%22receta%22:%7B%22%24eq%22:%225086941171011962392%22%7D%7D"},{"rel":"describedby","href":"https://ge4e65cc87f573d-db20220526112405.adb.eu-amsterdam-1.oraclecloudapps.com/ords/admin/metadata-catalog/notas/"},{"rel":"first","href":"https://ge4e65cc87f573d-db20220526112405.adb.eu-amsterdam-1.oraclecloudapps.com/ords/admin/notas/?q=%7B%22receta%22:%7B%22%24eq%22:%225086941171011962392%22%7D%7D"}]}

And I just need to take the median and votes values to create the RatingCount and RatingValue labels
Can anyone offer me an idea that solves this little problem? :-)


text:
Q: Need help to understand service bus message unit? I use two Premium service bus namespaces in my subscription with capacity 1 and I am getting a monthly bill like "54 message units is charged at X amount of $". I am curious how azure calculates number of message units my services spent. If there is a calculation that given throughput of 10k requests/second, it is translated this number of message units, then it will help me predict cost. Any idea?
Thanks,

A: Since Premium Tier is a dedicated offer, you are billed per messaging unit an hourly rate and not for number of operations you process. Doesn't matter if you do 10 or 10K messages per second. Number of operations matters on a standard tier. And it's hard to say how many messages per second it translates into as there's no commitment to a specific throughput on the standard tier and performance is not guaranteed.


text:
Q: Generate random field during load file infile I am trying to generate a random alphanumeric field named Access while importing a .csv file. The .csv file has 3 fields: First_Name, Last_Name, Email. My MYSQL table has 4 fields: First_Name, Last_Name, Email, Access. I need to add a 4th field during import called Access that can just be a random Alphanumeric. This is what I have come up with so far.
//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = @fopen($file,"r");

//loop through the csv file and insert into database

if ($_FILES[csv][size] > 0) {

$access2 = random_password_length(15);

$temp = $_FILES['csv']['tmp_name'];

$sqlstatement="LOAD DATA LOCAL INFILE '$temp' INTO TABLE sendit_emails
FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n'
(@First_Name, @Last_Name, @Email, @Access)
SET First_Name=@First_Name, Last_Name=@Last_Name,
Email=@Email, '$access2'=@Access";

At the bottom of my PHP page I declare the function for random_password:
<?php
function random_password_length($length = 15) {
$chars = "ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
$password = substr(str_shuffle($chars), 0, $length);
return $password;
}
?>

I am getting a syntax error near @Access. Any help would be appreciated. I am also willing to try another technique.

A: You don't need user-variables. Just map the three columns from the CSV to the three relevant DB columns, and use a SET statement to set the fourth column.
Something like this should work for you:
$sqlstatement="LOAD DATA LOCAL INFILE '$temp' INTO TABLE sendit_emails
FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n'
(First_Name, Last_Name, Email)
SET Access='$access2'";

Use the following solution for importing a different Access code for each row: Assuming you want to use your existing approach of 15 pseudo-random alphanumeric characters, you can do that in MySQL like this: SET Access=upper(left(md5(rand()),15))
Thus the full query would be:
$sqlstatement="LOAD DATA LOCAL INFILE '$temp' INTO TABLE sendit_emails
FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n'
(First_Name, Last_Name, Email)
SET Access=upper(left(md5(rand()),15))


text:
Q: General formula for $\prod (x+a_i)$ What could be a general formula for this in terms of $x$ and $a_1,\; a_2\; \ldots\; a_{n-1}, \;a_n$?
$$\prod_{i=0}^n(x+a_i)$$
I've tried solving it, but I'm lost at the sum-of-product-of-all-possible-combinations stage.

A:
$$\prod_{i=1}^n(x+a_i)=\sum_{B\subseteq\{1,2,...,n\}}x^{n-|B|}\prod_{b\in
B}a_b$$

A: I don't know if that is, what you want, but: One can see that the coefficient of $x^k$ in the expanded form is the sum of all $k$-term sums of $a_{i_\mu}$s. As a particular $i$ can appear only once among the $i_\mu$, we can order the $i_\mu$ strictly increasing, giving
$$\prod_i (x+a_i) = \sum_{k=0}^n \left(\sum_{i_1 < \ldots < i_k} \prod_{\mu=1}^k a_{i_\mu}\right) x^k $$


text:
Q: SSIS package only executes the last part of package in SQL Agent job but executes all of the package in Visual Studio I created an SSIS package which has 3 script tasks that checks if a different file exists for each and if the any of the script tasks finds the file, then it goes to a foreach loop which imports data to a sql server staging table, then copy and renames the file.
It works successfully within Visual Studio, however when I set up a sql agent job, the package only processes the last file and ignores the first two.
Any ideas why this may be occurring?

A: Probably either permissions of the SQL Agent, or invalid file paths on the SQL Server.


text:
Q: SBS 2008 Backup Drive Full - Error Code '2147942512' We are using Windows Backup on SBS 2008 SP2 and backing up to 1TB external hard drives. Recently after switching drives our backup started failing because the backup drive is full and auto-delete isn't automatically deleting older backups/show copies. I'm trying to get more information to help me effectively prevent this problem from reoccurring in the future.
How I can tell that the drive is getting full:
In the event viewer under Windows Logs > Application, I'm seeing Event ID 517 but it fails to show an intelligible description. However, under Applications and Services Logs > Microsoft > Windows > Backup > Operational, I'm seeing an event with the ID of 5 and a description like this: Backup started at '10/4/2011 12:30:12 PM' failed with following error code '2147942512'.
One of the most informative posts I've found on this error is located on Microsoft's Technet Forums here. In that post, a Microsoft representative gives this hazy explanation:
auto-delete feature to ensure that at least some old backup copies are maintained on the disk -- does not automatically delete backups if space utilization by older copies is less than 1/8 of the disk size or in other words, 13% of the disk size. that means if the one full backup copy does not fit in the 7/8 of the disk size, backup may fail with disk full error. auto-delete will not automatically delete older versions to reclaim more older versions of backup.
In the above explanation, I do not understand what is meant by "older copies" except that it appears that anything older than the very last shadow copy would be considered "older copies". I'm going to make the assumption that this problem where auto-delete will not work will affect any hard drive that is large enough to make an effective backup drive, or in other words, any hard drive that is large enough to hold more than one backup/shadow copy at once.
The same MS representative proposes the solution of using a larger backup drive. I can't understand how this will help. It appears to me it will simply delay the problem until a later date.
In order to resolve this problem for now, I did the following:

*

*Assign the backup drive a disk letter under disk management.

*Run the command line with Administrative rights.

*diskshadow.exe [enter]

*delete shadows oldest x: [enter] (where X: is the letter you
assigned your backup drive)

*I manually ran the above command some 60 or 80 times to free up about 200 GB of space on my 1 Terrabyte External Hard drive.

However, I do not feel this is a satisfactory solution to prevent the problem from happening again in the future. Does anyone have a solution to prevent your Windows Server backup drive from getting full?

A: I found a good answer here.  You have change the "use limits" for shadow copies.


text:
Q: Geometric structure of atomic nucleus? The electrons in an atom have a certain configuration and we can predict in which space the electrons can be present of a certain energy level (s-orbitals have a sphere-shape,....).
Recently I read that there are magic numbers for nuclei: special configurations of the nuclei that makes them more stable (the magic numbers are 2, 8, 20, 28, 34, 50, 82, and 126) - so there are definitely shells in a nucleus. I was wondering : do the neutrons and protons form certain geometric structures in these sub-shells of the nucleus?
Or are they all stacked closely on each other?


text:
Q: How to load a SD Grid and scroll automatically to last record on Genexus 15? I have a SD grid to show messages received from other users (a simple chat app) and every time I open this panel, the first records appears and I have to manually scroll to reach last message.
Is there a way to automatically go to last record on this grid  ?
I know there is a Select() method on grids, but this can´t be used on Refresh Event, only on user events.
I´m using GX15 U6
Thanks,
Rogelio Arosemena

A: Yes, it is possible with Inverse Loading property

This property is available for grids in the Smart Devices generator.
By setting it to True (its default value is False), the developer will
  be able to load the grid in reverse direction (i.e. the Common Grid
  will be loaded from bottom to top, and the Horizontal Grid will be
  loaded from right to left).
Example of use The canonical use case of inverse loading on a grid is
  that of a chat messaging system. What are its characteristics? It is
  loaded from bottom to top, pagination is performed with a swipe-down
  gesture, and when the user refreshes it the first page will be
  displayed in the lower section.


text:
Q: Read out (and edit) data from a table with def, xdef, let etc. (by using a pgf-loop and pgfplotstable) If I read out from a table with \def, say
\pgfplotstablegetelem{\row}{No}\of{\mytable}
\def\No{\pgfplotsretval}

it becomes wrong. By using \xdef
\pgfplotstablegetelem{\row}{No}\of{\mytable}
\xdef\No{\pgfplotsretval}

it becomes correct.
But I had to hear in some comments \xdef is not good, better is \let etc.; so what is the correct way?

\begin{filecontents}[overwrite]{originaltable.csv}
No; Name
3;   aaa
5;   bbb
7;   ccc
\end{filecontents}

\documentclass{article}
\usepackage{pgfplotstable}
\pgfplotsset{compat=newest}
\pgfplotstableread[col sep=semicolon, header=true]{originaltable.csv} {\mytable}

\begin{document}

\section{def-variant -- wrong}
\foreach[count=\n from 0] \row in {0,1,2}{%%
% In:
\pgfplotstablegetelem{\row}{No}\of{\mytable}%
\def\No{\pgfplotsretval}%
\pgfplotstablegetelem{\row}{Name}\of{\mytable}%
\def\Name{\pgfplotsretval}%
% Out:
\noindent \No, \Name \\
}%%

\section{xdef-variant -- correct}
\foreach[count=\n from 0] \row in {0,1,2}{%%
% In:
\pgfplotstablegetelem{\row}{No}\of{\mytable}%
\xdef\No{\pgfplotsretval}%
\pgfplotstablegetelem{\row}{Name}\of{\mytable}%
\xdef\Name{\pgfplotsretval}%
% Out:
\noindent \No, \Name \\
}%%
\end{document}

A: This isn't really related to anything you want to do with pgfplotstable, it is more a general understanding issue, imho.
What does \def/\gdef do?
\def sets up a macro to expand to the definition you provided, without altering it in any way, so if you \def a macro that contains other macros, and those other macros change some time in the future, the result of your macro will change. (\gdef is just the global variant of \def)
What does \let do?
\let lets a macro to the meaning of the following token. If that following token is a macro itself, \let will set the first macro to have the same meaning as that other macro currently has.
The syntax of \let is somewhat convoluted. If you're using \let\macro<tok> and <tok> is neither a space nor an equals sign, \macro will have the meaning of <tok> (that could be any character with any category code, or a macro, or a primitive). But you can also use an optional = between \macro and <tok>, in which case TeX will only ignore one following space.
What does \edef/\xdef do?
\edef will do the same as \def, but it will fully expand the definition of the macro and assign the result of that expansion to the macro. (\xdef is just the global variant of \edef)
All in an example file
(this uses plain TeX syntax for simplicity, the same would work in LaTeX)
This example will show the different effects of \def, \let, and \edef with an easy to understand example.
% helper functions
\def\exponce#1{\unexpanded\expandafter{#1}}
\def\exptwice#1{\expandafter\exponce\expandafter{#1}}
\def\expthrice#1{\expandafter\exptwice\expandafter{#1}}
\newlinechar`\^^J
\def\showfoursteps#1%
  {%
    \message
      {%
        ^^J%
        \unexpanded{#1}-> \exponce{#1}-> \exptwice{#1}-> \expthrice{#1}
        ^^J%
      }%
  }

\def\BB{\CC}
\def\CC{CC}

\def\Adef{\BB}
\let\Alet\BB
\edef\Aedef{\BB}

\showfoursteps\Adef
\showfoursteps\Alet
\showfoursteps\Aedef

\def\BB{CC}

\showfoursteps\Adef
\showfoursteps\Alet
\showfoursteps\Aedef

\bye

This will print the following on the terminal:
\Adef -> \BB -> \CC -> CC

\Alet -> \CC -> CC-> CC

\Aedef -> CC-> CC-> CC

\Adef -> \BB -> CC-> CC

\Alet -> \CC -> CC-> CC

\Aedef -> CC-> CC-> CC

What to watch out for?
In general \def and \let are pretty safe. But \edef can go horribly wrong if used on material that can't be fully expanded safely.
What to use to store the results of something else
If the results of some other routine are stored in a macro and you want to keep those results in another macro, \let is the way to go. If you need to keep the value longer than the current group you can prefix \let with \global: \global\let\foo\bar
If the results are returned by full expansion \edef is the way to go (this is true for many of the functions in expl3 which use \unexpanded at the end to yield some results without expanding them any further, e.g., you'd use \edef\mymacro{\stripspaces{<stuff>}} with \stripspaces being an expandable macro that removes spaces from either end of <stuff>).
If you know exactly how many expansion steps something takes (e.g., \pgfplotsretval needs exactly one step) you can use the \unexpanded primitive and \expandafter to trigger exactly as many expansion steps as you need and that even inside an \edef. So you could as well use the following:
\def\BB{\CC}
\edef\AA{BB is \unexpanded\expandafter{\BB}}

Applied to your situation:
You can use \let to assign \No the current meaning of \pgfplotsretval like so:
\begin{filecontents}[overwrite]{originaltable.csv}
No; Name
3;   aaa
5;   bbb
7;   ccc
\end{filecontents}

\documentclass{article}
\usepackage{pgfplotstable}
\pgfplotsset{compat=newest}
\pgfplotstableread[col sep=semicolon, header=true]{originaltable.csv} {\mytable}

\begin{document}

\section{let-variant -- correct}
\foreach[count=\n from 0] \row in {0,1,2}{%%
% In:
\pgfplotstablegetelem{\row}{No}\of{\mytable}%
\let\No\pgfplotsretval%
\pgfplotstablegetelem{\row}{Name}\of{\mytable}%
\let\Name\pgfplotsretval%
% Out:
\noindent \No, \Name \\
}%%
\end{document}


text:
Q: How to Change Button Alignment in Bootstrap (also using Angular 8)? After changing the size of my button with btn-sm, it has got misaligned with respect to the rest of the social icon buttons on my navbar. How would I recenter it?

I'm also using Angular 8 to manage the backend of my website (maybe that changes something in this case?); and my top navbar is of class navbar navbar-expand navbar-light bg-light flex-column flex-md-row.

      {{ title }}

              {{ itemNavbar[langNavbar] }}

        <button
          class="btn btn-outline-secondary btn-sm"
          id="dropdownBasic1"
          ngbDropdownToggle>
            {{ upperCaseFirstLetter(langNavbar) }}
        </button>

                {{ upperCaseFirstLetter(language) }}

A: I couldn't really solve the problem, but one way to adjust the positioning of this button would be by adding more margin or padding to it. For example, mt will add margin to the top of the button, hopefully you will hit a big enough margin. In my case, I ended up using:

...

The number for each margin and padding is a multiplier for the $spacer variable found in node_modules/bootstrap/scss/_variables.scss. The $spacer variable has a 1rem measurement by default.


text:
Q: Unable to edit a table element after having just added column I just added a new "imgurl" column by the following migration:
rails generate migration add_imgurl_to_users imgurl:string

and when I check my rails console, this is what I see for user 1:
irb(main):002:0> a = User.find_by(id: 1)
  User Load (0.3ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 1 LIMIT 1
  => #<User id: 1, name: "iscprz", email: "fakeemail2@gmail.com", created_at: "2014-11-04 02:18:15", updated_at: "2014-11-04 02:45:33", password_digest: "$2a$10$UvHGZPAxQdCrsbOEyJeLPOuzXm7aJLYWJNKRnkJ5NkA...", imgurl: nil>

Whenever I make a new user, I get to my new.html.erb file inside the users view:

New user

Sign up

    <%= form_for(@user) do |f| %>
      <%= f.label :name %>
      <%= f.text_field :name %>

      <%= f.label :email %>
      <%= f.text_field :email %>

      <%= f.label :password %>
      <%= f.password_field :password %>

      <%= f.label :password_confirmation, "Confirmation" %>
      <%= f.password_field :password_confirmation %>

      <%= f.label :imgurl, "Background image URL" %>
      <%= f.text_field :imgurl %>

      <%= f.submit "Create my account", class: "btn btn-primary" %>
    <% end %>

<%= link_to 'Back', users_path %>

but at the screen, I enter text into the imgurl field and it doesn't save it to the database upon submitting the form...(the imgurl field is always nil after I check in rails console).
What step have I forgotten to take after having created the new imgurl column?

A: Your params.require(:user).permit(:name, :email, ...) in your controller?


text:
Q: How does the Alarm Stack in Starcraft II work? I'm trying to improve my macromanagment speed and I recognize that I never use the Alarm sound cues. There is a hotkey to jump to the last cue, but I can't quite figure out how it works. You can jump to the last alarm with Spacebar and an alarm can be if a unit was created, you were attacked somewhere, minerals or vespin gas resources are finished in one location, etc.
My first impression was that the alarm system works like a stack. The newest event will be put on top on the stack. If you press Spacebar, you will get to the top of the stack, then to the second element and so on. I thought that if I jumped to an element it would get pushed from the stack and I wouldn't be able to get to it anymore when pressing Spacebar. But it appears to loop. That means if I press Spacebar a couple of times and see the latest events and then do some other stuff, when I come back the same events are still in the stack.
Has anyone used the spacebar hotkey frequently and figured out how it works? Thanks!

A: The alarm cue hotkey will always move you to the latest alarm event, then cycle through the next recent alarm. Alerts will not be removed from the stack once you visit them, only after the alarm condition has passed.
Additionally, user Aequitas has some good advice on this question from 2016:

While this answer is correct, I'd advise against using this method generally. What if just as you push space, you get a different alert? Then you end up being in the wrong spot and wasting time. Set Camera Locations for important places, such as your main, nat and third. You can double tap control groups for most other regions of interest, otherwise just click on the map.

I would also recommend only using this hotkey to quickly move to a location with an alarm that you could not otherwise move to, such as in the event of an unexpected attack.


text:
Q: How can I get the value inside the xml tag? I am trying to get the value of xml file.
<p1>
    <cts>Pq44</cts>
    <cts>qw44</cts>
</p1>

P1.JAVA
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class P1 {
    private List<Cts> cts;

     public P1() {
         cts = new ArrayList<cts>();
     }
     public List<cts> getcts() {
        return cts;
     }
     public void setcts(List<cts> cts) {
        this.cts = cts;
     }
}

CTS.JAVA
public class CTS {

    private String ct;

    // Getter and setter for ct.

}

My Main.java
try {
    File file = new File("D:\\Bye.xml");
    JAXBContext jaxbContext = JAXBContext.newInstance(P1.class);

    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    P1 p = (P1) jaxbUnmarshaller.unmarshal(file);

    List<CTS> cts =  p.getCTS();
    // Size of list coming right `2`
    for (CTS c : cts) {
          System.out.println(CTS2.getCT());
    }
} catch (JAXBException e) {
    e.printStackTrace();
}

When I run main.java, it prints:
null
null

A: I think your loop should look like
for (CTS c : cts) {
    System.out.println(c.getCt());
}

A: You could use @XmlValue and do the following:
CTS
import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class CTS {

    @XmlValue
    private String ct;

    public String getCt() {
        return ct;
    }

    public void setCt(String ct) {
        this.ct = ct;
    }

}

P1
import java.util.*;
import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class P1 {

    private List<CTS> cts;

    public P1() {
        cts = new ArrayList<CTS>();
    }

    public List<CTS> getCts() {
        return cts;
    }

    public void setCts(List<CTS> cts) {
        this.cts = cts;
    }

}

p1.xml
<p1>
    <cts>Pq44</cts>
    <cts>qw44</cts>
</p1>

App
import java.io.File;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main( String[] args ) throws JAXBException
    {
        System.out.println( "Hello World!" );
        String filePath = ".\\p1.xml";

        File file = new File(filePath);
        JAXBContext jaxbContext = JAXBContext.newInstance(P1.class);

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        P1 p = (P1) jaxbUnmarshaller.unmarshal(file);

        List<CTS> cts =  p.getCts();
        // Size of list coming right `2`
        for (CTS c : cts) {
              System.out.println(c.getCt());
        }
    }
}

Output
Hello World!
Pq44
qw44

A: I have done some work around. I am posting my  Code which will work on based XML file.
p1.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<p1>
    <cts>Pq44</cts>
    <cts>qw44</cts>
</p1>

P1.java
import java.util.ArrayList;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "p1")
public class P1 {

    private ArrayList<String> cts;
    public ArrayList<String> getCts() {
        return cts;
    }
    public void setCts(ArrayList<String> cts) {
        this.cts = cts;
    }
}

TestApp.java
import java.io.File;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main( String[] args ) throws JAXBException
    {
        System.out.println( "Hello World!" );
        String filePath = ".\\p1.xml";

        File file = new File(filePath);
        JAXBContext jaxbContext = JAXBContext.newInstance(P1.class);

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        P1 p = (P1) jaxbUnmarshaller.unmarshal(file);

        List<String> cts =  p.getCts();
        // Size of list coming right `2`
        for (String c : cts) {
              System.out.println(c);
        }
    }
}

try this way it will work fine.
output
Hello World!
Pq44
qw44


text:
Q: Can Visual Studio connected to adb server on other computer run android devices connected to the other computer? My setup:
I have mac which has the android tools. And a windows virtual machine - which unfortunately can't run android directly. So I have connected them following this guide: https://learn.microsoft.com/en-us/xamarin/android/troubleshooting/questions/connect-android-emulator-mac-windows and they are on the same vpn.
I can see the emulators started on my mac and run my xamarin app successfully from the windows machine:

But when connecting an android device to the mac it won't show up in visual studio on the windows machine. Running adb devices on my mac it shows up:

And I can run apps on it successfully from other frameworks that I have installed on my mac.
Is there some way I can expose the android device for visual studio to find via the adb server?

A: I think you will have better luck if you are using ADB over network.
On the computer where you have connected the devices you can run:
adb tcpip 5555

Then if you know the IP of the device you can connect from any computer on the same network with:
adb connect ip:5555

Then it should appear in VS in the device list.


text:
Q: Losing selection highlight in NSOutlineView subclass To customize the default blue gradient highlight style I made a subclass of NSOutlineView and overrode the method -highlightSelectionInClipRect, like so:
- (void)highlightSelectionInClipRect:(NSRect)theClipRect
{
    NSRange aVisibleRowIndexes = [self rowsInRect:theClipRect];
    NSIndexSet *aSelectedRowIndexes = [self selectedRowIndexes];
    NSInteger aRow = aVisibleRowIndexes.location;
    NSInteger anEndRow = aRow + aVisibleRowIndexes.length;

    for (int aRow; aRow < anEndRow; aRow++) {
        if([aSelectedRowIndexes containsIndex:aRow]) {
            // draw gradient
        }
    }
}

This works fine, but sometimes the background is not drawn. On the screenshot below you can see how the selection highlight is not drawn when clicking on the first item after the last one was selected.

It seems as if this only happens if the new selected item is not directly beneath or above the old selected one. Selecting five items in the order 1-2-3-4-5-4-3-2-1 always draws the appropriate background, anything else (e.g. 1-2-5) not.
Why is this happening? If you need any more details I will be glad to add some more code, but at the meantime I have no clue where to search for this behaviour.

A: here is my (very simple) solution using blocks:
- (void)highlightSelectionInClipRect:(NSRect)clipRect
{
    [[self selectedRowIndexes] enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop)
     {
         // draw gradient
    }];
}


text:
Q: How to unmap keys in fish? I want to unmap (unbind) certain keys such as Up, Down, Left, Right, Page Up, Page Down, Home, End specifically in the fish shell.
I guess I have to use the bind command in the .config/fish/fish.config file, but I am not sure how.

A: You will need to define a custom fish_user_key_bindings function with the appropriate bind --erase statements, then save that function with funcsave or by editing ~/.config/fish/functions/fish_user_keybindings.fish directly.
For example:
function fish_user_key_bindings
    bind --erase --key up
    bind --erase --key down
    # and so on
end

funcsave fish_user_key_bindings

Note that some terminals don't send the terminal codes that their terminal description files say they do - you may need to use fish_key_reader (introduced in 2.3.1) to confirm the exact binding you need to erase.


text:
Q: Autoplay audio file on active div I'm terrible at JS and I've tried dozens of thing to make this work, but nothing seems to work for me.
I want AUDIO1 file to play and AUDIO2 file to pause automatically when certain div element has "elementor-active" class, and vice versa.
Any help appreciated.
Here's my code:

TAB 1

TAB 2

<audio id="AUDIO1" loop="loop">
<source src="http://localhost/test/wp-content/uploads/2018/06/audio1.ogg">
<source src="http://localhost/test/wp-content/uploads/2018/06/audio1.mp3" type="audio/mpeg">
</audio>

<audio id="AUDIO2" loop="loop">
<source src="http://localhost/test/wp-content/uploads/2018/06/audio2.ogg">
<source src="http://localhost/grad/wp-content/uploads/2018/06/audio2.mp3" type="audio/mpeg">
</audio>

A: For example:
var audio_one = new Audio('PATH_TO_AUDIO_1');
var audio_two = new Audio('PATH_TO_AUDIO_2');

var timerId = setInterval(function() {
  if ($('YOUR_BLOCK_SELECTOR').hasClass('active')) {
    audio_one.play();
    audio_two.pause();
  } else {
    audio_one.pause();
    audio_two.play();
  }
}, 250);


text:
Q: how to split single integer value columns into n column? I have a SQL Server table table_name like:
col1
1
2
3
4
5
6
7
8
9
.
.
.
N

i want output like below
col-1 | col-2 | col-3 | col-4 |col-5
-------------------------------
1     | 2     | 3     | 4     |5
6     | 7     | 8     | 9     |10
11    | 12    | 13    | 14    |15

how to get from this output  in sql-server query.

A: Another option is a Dynamic Pivot.
This will create N columns.
Example
Declare @nCols int  = 5

Declare @SQL varchar(max) = '
Declare @nCols int = '+str(@nCols,5)+'
Select *
 From (
        Select RowNr = ((row_number() over (order by col1)-1)/@nCols)+1
              ,ColNr = concat(''col-'',isnull(nullif((row_number() over (order by col1))%@nCols,0),@nCols))
              ,Value = col1
         From YourTable
      ) A
 Pivot (max(Value) For ColNr in (' + Stuff((Select Top (@nCols) ','+QuoteName(concat('col-',Row_Number() Over (Order By (Select NULL)))) From  YourTable For XML Path('')) ,1,1,'') + ') ) p'
Exec(@SQL);
--Print @SQL

Returns

If @nCols = 3 , the Results are:

EDIT a Fully Parameter Driven Version

This version you can supply the

*

*Number of Columns @NbrCols (same as above)

*Source @FromSrc, which is the table name or a SQL String in () i.e. (Select ...)

*The column name @ColName to Pivot @ColName

*The colum prefix @ColPrfx  i.e. 'Col-' or even ''

Declare @NbrCols int  = 5
Declare @FromSrc varchar(max) = 'YourTable'  -- Or SQL '(Select col ...)'
Declare @ColName varchar(100) = 'col1'
Declare @ColPrfx varchar(100) = 'Col-'

Declare @SQL varchar(max) = '
Declare @NbrCols int = '+str(@NbrCols,5)+'
Select *
 From (
        Select Row = ((row_number() over (order by '+quotename(@ColName)+')-1)/@NbrCols)+1
              ,Col = concat('''+@ColPrfx+''',isnull(nullif((row_number() over (order by '+quotename(@ColName)+'))%@NbrCols,0),@NbrCols))
              ,Val = '+quotename(@ColName)+'
         From '+@FromSrc+' A1
      ) A
 Pivot (max(Val) For Col in (' + Stuff((Select Top (@NbrCols) ','+QuoteName(concat(@ColPrfx,Row_Number() Over (Order By (Select NULL)))) From master..spt_values For XML Path('')) ,1,1,'') + ') ) p'
Exec(@SQL);
--Print @SQL

A: Using conditional aggregation based on dividing a row_number(), and using modulo % for column placement:
test setup:
select n into dbo.numbers from (values
  (1), (2), (3), (4), (5), (6), (7), (8), (9),(10)
,(11),(12),(13),(14),(15),(16),(17),(18),(19),(20)
) t(n)
delete from dbo.numbers where n in (12,13,17);

query:
select
    col1 = sum(case when rn%5=0 then n end)
  , col2 = sum(case when rn%5=1 then n end)
  , col3 = sum(case when rn%5=2 then n end)
  , col4 = sum(case when rn%5=3 then n end)
  , col5 = sum(case when rn%5=4 then n end)
from (
  select n, rn = row_number() over (order by n)-1
  from dbo.numbers
  ) t
group by rn/5;

rextester demo: http://rextester.com/UHKY16981
returns:
+------+------+------+------+------+
| col1 | col2 | col3 | col4 | col5 |
+------+------+------+------+------+
|    1 |    2 | 3    | 4    | 5    |
|    6 |    7 | 8    | 9    | 10   |
|   11 |   14 | 15   | 16   | 18   |
|   19 |   20 | NULL | NULL | NULL |
+------+------+------+------+------+

The same concept but using pivot() instead of conditional aggregation returns the same results.
select
    col1 = [0]
  , col2 = [1]
  , col3 = [2]
  , col4 = [3]
  , col5 = [4]
from (
  select n
    , rn  = (row_number() over (order by n)-1)%5
    , grp = (row_number() over (order by n)-1)/5
  from dbo.numbers
  ) t
pivot (sum(n) for rn in ([0],[1],[2],[3],[4])) p;

A: Assuming your table does not simply holds consecutive numbers from 1 to n (if it does, Gordon's answer is better),
here is one way to do it:
First, create and populate sample table (Please save is this step in your future questions)
SELECT TOP 100 IDENTITY(int,1,1) AS col1
    INTO table_name
    FROM sys.objects s1
    CROSS JOIN sys.objects s2

DELETE
FROM table_name
WHERE col1 IN
(
    SELECT TOP 67 col1
    FROM table_name
    ORDER BY NEWID()
)

(table_name now contains 33 random numbers between 1 and 100)
Using a couple of common table expressions to get column number and row number:
;With Cols as
(
    SELECT  col1,
            ROW_NUMBER() OVER(ORDER BY col1) % 5 ColNumber
    FROM table_name
), RowsAndCols as
(
    SELECT col1, ColNumber, ROW_NUMBER() OVER(PARTITION BY ColNumber ORDER BY col1) As RowNumber
    FROM Cols
)

And the query:
SELECT c1.col1, c2.col1 As col2, c3.col1 As col3, c4.col1 As col4, c5.col1 As col5
FROM RowsAndCols c1
LEFT JOIN RowsAndCols c2 ON c1.RowNumber = c2.RowNumber AND c2.ColNumber = 2
LEFT JOIN RowsAndCols c3 ON c1.RowNumber = c3.RowNumber AND c3.ColNumber = 3
LEFT JOIN RowsAndCols c4 ON c1.RowNumber = c4.RowNumber AND c4.ColNumber = 4
LEFT JOIN RowsAndCols c5 ON c1.RowNumber = c5.RowNumber AND c5.ColNumber = 0
WHERE c1.ColNumber = 1

Note I've used left joins, so in case the number of rows is not a multiple of five you'll get nulls in the the last columns in the last row.
See a live demo on rexteser.

A: If you want that output, you don't even need to start with a table:
with cte as (
      select 1 as col1, 2 as col2, 3 as col3, 4 as col4, 5 as col5
      union all
      select 5 + col1, 5 + col2, 5 + col3, 5 + col4, 5 + col5
      from cte
      where 5 + col1 <= 15
     )
select *
from cte;


text:
Q: Submitting hidden as well as non hidden form field angular I am trying to submit a form which is having both hidden and non hidden form field.
My component HTML look like:
<form #myForm="ngForm" (ngSubmit)="addMyForm(myForm.value);">

                    <input type="text" name="endPointType" [(ngModel)]="endPointType" [value]="WAVEFRONT" [hidden]="true" required>

                    Endpoint Name
                    <input type="text" placeholder="Endpoint Name" name="name" [(ngModel)]="name" required>

            <button type="submit" class="btn btn-primary">ADD</button>
        </form>

While submitting this form the POST body I am getting in component class as {"name":"bla bla"} but I want POST body data as {"name":"bla bla", "endPointType":"something"} What is the issue in my code?

A: You need to add the default value for endPointType in your controller in order to avoid this problem.
Reason : working example
The reason behind this if you send value as it is you get from submitting method it contained endPointType value as undefined. which logged perfactly as shown in the example.
{endPointType: undefined, name: "fsdfsd"}

But When you send data to the server you are sending data by parsing it to Stringify. which removed all the keys whose value is undefined
so the result will be -
"{name: 'fsdfsd'}"

Update
To set default value just initialize your variable like this -
export class yourClassName {
...
endPointType = 'WAVEFRONT'
...
}

and use while sending data to server-
{endPointType: this.endPointType, name: "fsdfsd"}


text:
Q: Table at bottom of two-column environment stretching two tables I have been assigned the task of producing a table as the one shown in the picture. I have problems with placement of the rules, the background color and the caption-font and caption counter(Table I) being too large. A quick response would be appreciated.

A: in lack of information and not knowing what you try so far, which document class you use, does gray table's background must be ...

instead of table environment i would rather use enumerate environment. for placing on the same page where table is inserted serve `{stfloats}˙:
\documentclass[twocolumn]{article}
\usepackage{enumitem}
\usepackage{stfloats} % for positioning of table* on the same page

\usepackage{lipsum}

\begin{document}
\lipsum[1]
\begin{table*}[b]
\caption{table caption}
\rule{\linewidth}{1pt}
\begin{enumerate}[nosep, leftmargin=*, label=(\alph*)]
\item   \lipsum[11]
\item   \lipsum[11]
\item   \lipsum[11]
\end{enumerate}
\rule{\linewidth}{1pt}
\end{table*}
\lipsum[2-5]
\end{document}


text:
Q: Указатели внутри функций в C В функцию передаётся указатель на корень B-дерева и число, которое нужно вставить в дерево:
void bt_insert(Tree** tree_ptr, const int key);

далее, ищется узел, в который можно вставить данные:
if (!(*tree_ptr)->is_leaf) node = bt_get_node(*tree_ptr, key);
else node = *tree_ptr;

после вставки данных в дерево, оно, при необходимости балансируется
if (node->count != DEGREE) return;
bt_balance(&node);

Но в случае, если нужно отбалансировать корневой элемент, tree_ptr и node имеют разные значения. То есть, если
else node = *tree_ptr;

То tree_ptr != &node
И я не могу вставить вместо *tree_ptr другой узел в функции bt_balance (согласно алгоритма).
Что тут можно сделать?

A: Если я вас правильно понял, то объявите node как
Tree **node;

и используйте
node = tree_ptr;

или еще один фрагмент
if ( ( *node )->count != DEGREE) return;
bt_balance( node );

Возможно, в некоторых местах вам надо будет объявить еще одну промежуточную переменную, как
Tree *tmp;

и использовать конструкцию
node = &tmp;

для передачи node в другие функции, которые требуют объект типа Tree **
Или
Tree *tmp;
//...
if (!(*tree_ptr)->is_leaf) tmp = bt_get_node(*tree_ptr, key);
//...
node = &tmp;

или в зависимости от условий
node = tree_ptr;


text:
Q: Two python2 in the cmd and cannot use pip2 for any of the version I am using OS X 10.12 and I have some troubles with my python installation. Currently I have two python2 installed. One is Python 2.7.10 at /Library/Python/2.7 and the other is Python 2.7.13 at /usr/local/Cellar/python/2.7.13_1. At the moment, all the pips (pip2, pip2.7, pip) direct to Python 2.7.10, and I cannot use pip for Python 2.7.13 in the cmd. Even Python 2.7.10 has pips, they do not work, for example, when I tried to upgrade numpy, I got error messages like this:
Collecting numpy
  Downloading numpy-1.13.1-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (4.6MB)
    100% |████████████████████████████████| 4.6MB 162kB/s
Installing collected packages: numpy
  Found existing installation: numpy 1.8.0rc1
    DEPRECATION: Uninstalling a distutils installed project (numpy) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
    Uninstalling numpy-1.8.0rc1:
Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 342, in run
    prefix=options.prefix_path,
  File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 778, in install
    requirement.uninstall(auto_confirm=True)
  File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 754, in uninstall
    paths_to_remove.remove(auto_confirm)
  File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py", line 115, in remove
    renames(path, new_path)
  File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 267, in renames
    shutil.move(old, new)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move
    copy2(src, real_dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2
    copystat(src, dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat
    os.chflags(dst, st.st_flags)
OSError: [Errno 1] Operation not permitted: '/tmp/pip-N61eSI-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy-1.8.0rc1-py2.7.egg-info'

What I want to do is to make pip in the cmd for Python 2.7.13 and make pip2 for Python 2.7.10. And I want them both work.

A: An easy method to do this would be to just use -m pip.
<path to python 2.7.10> -m pip
<path to python 2.7.13> -m pip

Or you could add the python 2.7.10 and 2.7.13 to environment variables and just use
<python 2.7.10> -m pip
<python 2.7.13> -m pip

While there are methods to just rename their respective pip to a different name, since I've never really used OSX, I'll leave that for more experienced people to answer.


text:
Q: Clogit wtp interpretation I have performed a clogit with the package survival in R. The aim the work was to estimate the willingness to pay from a discrete choice model. The choice set was composed of 4 attributes, 3 of them with 3 levels and the attribute price with 5 levels. In particular the price was composed by the levels 20, 40, 50, 70 and 90 euros.
My question is related to results interpetation. Why I have obtained a value of WTP much higher than the value that I have proposed? In particular if I made the ratio between the a certain level of the non-monetary term and the coefficient of the price (as follows):
$$WTP=-\frac{β_nonmonetary}{β_price}$$
I obtain a WTP of -237. What could be the problem?


text:
Q: How to pass complex data as model from view to controller in mvc 2 I have following in database (and I use them as models):
Category
{
long id;
string name;
long subcategoryId;
}

Subcategory
{
long id;
string subName;
//other data
}

I get data from db with Entity SQL like:
public static Category GetCategory(long catId)
        {
            Category cat;
            using (Entities db = new Entities())
            {
                cat = (from c in db.Categories
                       where c.id == catId
                       select c).SingleOrDefault();

                cat.SubcategoryReference.Load();
            }
            return cat;
        }

Now, I have some partial view:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Test.Database.Subcategory>>" %>
<%--Some code--%>
<%:Html.ActionLink("Move to new category", "editcategory", "category",
                                             new { model = new Category { Subcategory = item } }, null)%>

Plan is to navigate with this action link to CategoryController and action
public ActionResult EditCategory(Category model)
        {
            //some code
            return View(model);
        }

where I can edit some info about this category which would contain chosen subcategory. Problem is that I keep getting model=null as parameter in this EditCategory Action. What am I doing wrong? Any advice is welcome.

A: You cannot pass complex objects using GET as action links. If you wanted to do this you will need to send all properties, one by one and leave the default model binder cope with it but this could be very tedious:
<%: Html.ActionLink(
    "Move to new category",
    "editcategory",
    "category",
    new {
        prop1 = item.Prop1,
        prop2 = item.Prop2,
        ...
    },
    null
)%>

I would recommend you the standard way to achieve which consists in passing the category id that you are willing to edit:
<%: Html.ActionLink(
    "Move to new category",
    "editcategory",
    "category",
    new { id = item.Id },
    null
) %>

and inside the controller action fetch the corresponding model from the repository:
public ActionResult EditCategory(int id)
{
    Category model = ... fetch category from id
    //some code
    return View(model);
}

Then the corresponding view will contain a form with input fields for all the different category properties and it is the POST action which you will submit this form to that can take a Category model as action parameter:
[HttpPost]
public ActionResult EditCategory(Category category)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }
    // some code to update the category
    return RedirectToAction("Success");
}

A: You might want to reconsider how you're passing this object to your action link and load the data from within the controller
public ActionResult EditCategory(long id)
{
    Category model = id > 0
        ? GetCategory(long id)
        : new Category() { Subcategory = item };

    return View(model);
}

[HttpPost]
public ActionResult EditCategory(int id, Category category)
{
    if (ModelState.IsValid) { /* save then redirect */ }
    return View();

}

and construct your action links like this:
<%:Html.ActionLink("Move to new category",
    "editcategory", "category", new { id = 0 }, null)%>


text:
Q: How to write a loose Python interface where subclasses can add extra data? Here are two object makers I made:
def make_assassination(i):
    neighbors = []
    def test(graph):
            for n in graph.neighbors(i):
                neighbors.append(n)
                graph.remove_edge(i, n)

    def reset(graph):
            for n in neighbors:
               graph.add_edge(n, i)

    return {'test': test, 'reset': reset, 'strategy': lambda : 'assassinate(%d)' % len(neighbors)}

def make_toggle(i, j):
    return {'edge': (i, j),
            'strategy': lambda : '',
            'test': lambda graph : toggle_edge(graph, i, j),
            'reset': lambda graph : toggle_edge(graph, i, j)
            }

Both return an object (dictionary) with keys 'test', 'reset' and a lambda 'strategy'. One object also wants to add a key 'edge'.
I was thinking of ways to convert this to something more class-oriented or typed. It would go like:
class Action(self, **kwargs):
    self.test = test
    self.reset = reset
    self.strategy = strategy

Then I'm not sure how to pass the extra edge.
I think there is a strategy where the class can do something akin to extending dictionary, or the child "classes" can access action's underlying dictionary and amend it. Coming from a Java background this sounds to get into the object's internals more than I'm sure is good design.
Another option is for an 'extra_stuff' kwarg. Also a bit of an antipattern.
There is also an argument I should just leave as a raw dictionary. In fact I am not even sure if there is an advantage to using a class at all.
Which of these patterns are acceptable design?

A: Python is a very dynamic language, so you don't have to create any particular class hierarchy. Your classes for Assassination and Toggle can be entirely independent even when they declare the same methods. You can therefore decide to add a method only to one of these classes.
While Python does not generally require it, there would be two reasons to define interfaces that are then inherited by Assassination and Toggle: if you rely on isinstance() checks in your code, or if you use an external static type checker like MyPy or a Python IDE with type-aware autocomplete suggestions. Python does not have explicit interfaces like Java, but you can create abstract base classes (ABC). Inside an ABC, you can mark methods that must be implemented with the @abstractmethod decorator. But it doesn't seem like any of these cases applies in your case.
In this particular case, the edge isn't a method but more like an instance field. In Python, instance fields are created by simply assigning them in the __init__ method.
I would implement these classes like this:
class Assassination(object):
  def __init__(self, i):
    self._neighbors = []
    self._i = i

  def strategy(self):
    return 'assasinate(%d)' % len(self._neighbors)

  def test(self, graph):
    for n in graph.neighbors(self._i):
      self._neighbors.append(n)
      graph.remove_edge(self._i, n)

  def reset(self, graph):
    for n in self._neighbors:
      graph.add_edge(n, self._i)

class Toggle(object):
  def __init__(self, i, j):
    self.edge = (i, j)

  def strategy(self):
    return ''

  def test(self, graph):
    (i, j) = self.edge
    return toggle_edge(graph, i, j)

  def reset(self, graph):
    (i, j) = self.edge
    return toggle_edge(graph, i, j)

The advantage of explicitly defining classes like this is that the available methods etc. are fairly obvious, and that you can document them easily with docstrings. Fields can't have docstrings, but we can hide them behind a property. Python's properties are like Java's setters and getters.
class Toggle(object):
  def __init__(self, i, j):
    self._edge = (i, j)

  @property
  def edge(self):
    """The edge toggled by test() and reset()"""
    return self._edge

  ...

If your class has no methods but is only a dict-like collection of instance fields, you can use an empty class and directly assign fields, they spring into existence automatically. If you want a convenient kwargs interface, you can directly access the __dict__ that underlies the object. While that would be legitimate metaprogramming, it isn't exactly obvious:
class Dynamic(object):
  def __init__(self, **kwargs):
    self.__dict__.update(kwargs)

In Python 3, the built-in types.SimpleNamespace class does exactly this, and adds equality and repr() implementations.


text:
Q: ExtJS4 toolbar issue I am new to ExtJS4.I have one doubt,if we add buttons to toolbar buttons are arranged from left side.Is it possible to add buttons from right side?
Actually toolbar is using box layout so i think we need to change options in Box.js.I tried a lot to get the solution.But i am not able to find where it is specifying from left side.Can anyone please help me.
Help would be appreciated.

A: Like the man said, with a stretched layout 1,2 will be at the right side.

&nbspl;	1	2',
            { text: '1' },
            { text: '2' } ],
});

A: Try adding '->' before the first item which should be on the right side.


text:
Q: Play wav file in callback mode [Pyaudio / Python] I wanna play wav file using PyAudio with callback mode. I could play wav file once but then stops. For example, if I want to play a wav file (trumpet sound, etc.) every five seconds, how should I implement this? Also, lemme know how to play array (wav data) in callback mode, just in case.
The code that I've implemented so far in the following...
    import pyaudio
    import numpy as np
    import wave
    import time

    FORMAT = pyaudio.paInt16
    CHANNEL = 2
    CHUNK = 1024
    RATE = 44100

    flag = True
    cur_dt = 0

    # reading wav file here
    wf = wave.open('test_3.wav', 'rb')

    # instantiate PyAudio (1)
    p = pyaudio.PyAudio()

    # define callback (2)
    def callback(in_data, frame_count, time_info, status):

        global flag, cur_dt, wf

        if flag:
            wf = wave.open('test_3.wav', 'rb')
            flag = False

        data = np.zeros((frame_count,), dtype=np.int16)
        data = wf.readframes(frame_count)

        # convert bytes to int
        data_int = np.frombuffer(data, dtype=np.int16)\

        # convert int to float
        data_float = data_int.astype(np.float32) / 32768.0

        # # convert float to int
        # data_int_again = (data_float*32768.0).astype(np.int16, order='C')

        # ur processing...
        f1 = np.fft.fft(data_float)
        f2 = np.fft.ifft(f1)
        f3 = (f2*32768.0).astype(np.int16)

        # make it sound!
        data = f3

        # cur_dt += 1
        # print(cur_dt)

        return (data.tobytes(), pyaudio.paContinue)

    # open stream using callback (3)
    stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                    channels=wf.getnchannels(),
                    rate=wf.getframerate(),
                    output=True,
                    stream_callback=callback)

    # print(p.get_format_from_width(wf.getsampwidth())) # paInt16
    # print(wf.getsampwidth()) # 3
    # print(wf.getnchannels()) # 2
    # print(wf.getframerate()) # 44100

    stream.start_stream()

    # wait for stream to finish (5)
    while stream.is_active():
        time.sleep(5)
        flag = True

    # stop stream (6)
    stream.stop_stream()
    stream.close()
    wf.close()

    # close PyAudio (7)
    p.terminate()


text:
Q: What is $\|a\|=\max_{f \in A^\ast}|f(a)|$? I would like to ask if the norm
$$\|a\|=\max_{f \in A^\ast}|f(a)|$$
has a name (where $A$ is a Banach space and $A^\ast$ denotes the continuous dual) and how to prove this equality. This equality is given in these lecture notes in exercise 13 on page 97.
 Also is the $1$ in the expression $\max_{f \in (A^\ast)_1}|f(a)|$ in the notes a typo? If not, what does it mean?

A: First of all it is not correct. The correct version is
$$
\|a\|=\sup_{\substack{f\in A^*,\\ \|f\|_*=1}}|f(a)|
$$
I think it is call "star-norm". (In my language at least.)
The "$\ge$" is obvious. In order to prove the "$\le$" part you need Hahn-Banach, which guarantees the existence of $f\in A^*$, which $f(a)=|a|$ and $\|f\|_*=1$.


text:
Q: I have issues with terminal service, there appear logins automatically and disappear? I have issues with my terminal service manager, there appear logins automatically and and increases the number of users but actually don't enter, my counter goes till 3000 o more in the same day and I just have 15 user.

A: It's hard to tell exactly what you're saying or what you're asking but I suspeect that you're seeing activity related to attempts to log on to the server using a brute force username/password attack. You can confirm this by watching in TS/RDS manager for multiple listening ports being created and destroyed in quick succession.


text:
Q: Detect click on the Collapsebutton in a TreeView I have a Treeview with nodes. If the user doubleclicks a node, an editdialog for the node opens where he can modify the data etc.
There is a problem, if the user clicks fastly twice onto the collapsebutton of a node - this also counts a double click. Is there a way to avoid this? I searched the Web but i found nothing really helpfull. Detecting if the click is within a specific area is useless, cause the Treeview is dynamic and scrollable.
Many thanks in advance.

A: You can just call HitTest and find out where the user clicked.
private void treeView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
    var hitTest = treeView1.HitTest(e.Location);
    if (hitTest.Location == TreeViewHitTestLocations.PlusMinus)
    {
        //expand collapse clicked
    }
}


text:
Q: Edit each line of text I have a text file with 60k+ of directory lines. How can I edit each line to go from this:
C:\AJ\RPG Maker\Whisper of a Rose\OST\39 The Jewel (extended mix).mp3

To this:
ROBOCOPY "C:\AJ\RPG Maker\Whisper of a Rose\OST" "E:\AJ\RPG Maker\Whisper of a Rose\OST" "39 The Jewel (extended mix).mp3"

I was thinking about a VBScript, but I can't get any further than this because I have no knowledge of it:
Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "c:\file.txt"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
    strLine = objFile.ReadLine
    If
    End If
    WScript.Echo strLine
Loop

A: Since the FileSystemObject doesn't allow for editing a file, create a separate file to contain your output:
Set objFile2 = objFS.CreateTextFile("c:\out.txt", True)

Then, using the loop you've already created:
Do Until objFile.AtEndOfStream

    strLine = objFile.ReadLine

    ' Get the parent folder and the file name...
    strFolder = objFS.GetParentFolderName(strLine)
    strFile   = objFS.GetFileName(strLine)

    ' Write the command to the new output file...
    objFile2.Write "ROBOCOPY "
    objFile2.Write Chr(34) & strFolder & Chr(34) & " "
    objFile2.Write Chr(34) & "E" & Mid(strFolder, 2) & Chr(34) & " "
    objFile2.Write Chr(34) & strFile & Chr(34) & vbCrLf

Loop

Nothing too tricky here. Just extracting parts of the file name using methods provided by the FileSystemObject and then concatenating strings to create our output. Chr(34) is used to represent a quote character in your output file.


text:
Q: jQuery full screen confirm with timeout I have a web based production tracking system. My users are not reading the screen so I am build a full screen alert and confirm function to make them. Alert are to stay on the screen for 15 seconds to slow the user down and make learn from their mistakes. Confirm is to show the question for 15 seconds before then can give an answer, if no option is selected I want the confirm to fade out after 30 second. Below is what I have so far.
What I can't get to work is when one of the options is selected to return true or false. Also this works if I just call the function,but when I assign it to a variable just get skip over and the rest of the code is executed. I want it to act like a confirm. Thanks for your help.
function fullScreenAlertConfirm(msg,confirmOpt){

    var returnVar;

    $('body').append("

");

    if(confirmOpt != null || confirmOpt != false){

        $('div.alert').html(msg+"
 This Message will disappear after 30 seconds
 Selection options will appear in 15 sec");

        $('div.alert').append("

");
        $("div.confirmBox").hide();
        $('div.confirmBox').append("
NO

YES
 ")
        $("div.confirmBox").delay(15000).fadeIn(400);

        $("div.no").click(function(){

            $('div.alert').fadeOut(400);

            return false;

        });

        $("div.yes").click(function(){

            $('div.alert').fadeOut(400);

            return true;

        });

        $('div.alert').delay(30000).fadeOut(400);

    }else{

        $('div.alert').text(msg+"
 This Message will disappear after 15 seconds");
        $('div.alert').delay(15000).fadeOut(400);
         return true;
    }
}

fullScreenAlertConfirm("Are you sure you want to change to the next shift?",true);

http://jsfiddle.net/tQkKh/1/
One of the ways I need this function to work.
//Change Shift
$("#change-shift").click(function () {

    var confirmShift = fullScreenAlertConfirm("Are you sure you want to change to the next shift?",true);
// var confirmShift  = confirm("Are you sure you want to change to the next shift?");

    if(confirmShift == false){
        window.location = 'orderControl.php';
        return;
    }

    $("#loading").fadeIn("fast");

    var request = $.ajax({
        url:'process.php',
        type:'POST',
        async:false,
        data:{mode:'change_shift'}
    });

    request.done(function (data) {

        var objData = jQuery.parseJSON(data);

        if(objData.results == false){
            $("#loading").fadeOut("fast");
            $('body').append("
" +objData.errorMsg+"
 This Message will disappear after 15 seconds
");
            $('div.error').delay(15000).fadeOut(400);

        } else if(objData.results == true){
            window.location = 'orderControl.php';
        }
    });

    request.fail(function (xhr) {
        alert('AJAX Error: ' + xhr.statusText);
    });

});

A jsFiddle example: for how I would like to use it.
http://jsfiddle.net/tQkKh/3/

A: The problem is happening because jquery queues the "fadeout after 30s" event, and then when you click yes/no, this new event to fade out is then queued to happen afterwards.
To clear out this queue, append .stop(true, true) before your fadeOuts like:
$('div.alert').stop(true, true).fadeOut(400);


text:
Q: Is the inequality $(\sqrt{x} - \sqrt{y})^2 \geqslant 0$ always true for $x,y \in \mathbb{R}^+$? Suppose $x,y \in \mathbb{R}^+$
Then is the following inequality true?
$(\sqrt{x} - \sqrt{y})^2 \geqslant 0$
If it is not true then please provide an example of why it fails.

A: Since $x,y \in \mathbb{R}^+$
$\sqrt{x}$ and $\sqrt{y}$ are $\in \mathbb{R}^+$
So
$\sqrt{x}-\sqrt{y}\in \mathbb{R}$
Thus $(\sqrt{x}-\sqrt{y})^2\geq0$


text:
Q: How do I show an error page when users visit my site using Microsoft Edge? When a user loads my website in Microsoft Edge, I need to show a page like in the below image:

I can see like this page when I'm trying to access sites like www.naver.com or www.daum.net on Edge.
That page looks like a Provided from Microsoft , and I guess there are
Any Javascript function to call this pages
I need to know how ..

A: If possible you should avoid browser detection and move to modern web technologies that work across browsers. A great tool you can use is the sitescan on http://dev.modern.ie/tools/staticscan/ that helps to identify common issues, like outdated js libraries or css prefixes.
If your app requires legacy technology like activeX or other IE specifics you can:

*

*have your site added to to compatiblity list managed by Microsoft
(for public sites)

*or create an enterprise site list for your company / intranet
pages which determines which pages to open in IE instead of Edge.
Charles provided some details here: https://stackoverflow.com/a/31283160/5138360

A: In my opinion you're going about this the wrong way, I know supporting new browsers may be frustrating, but you're only delaying work that needs to be done (in this case, supporting Edge when Internet Explorer's usage will be at a decline in the next few years).
However, what you're asking can be done with PHP's get_browser() function; you should check if the user-agent string has 537.36 Edge present, and if so show the error message; if not show the normal content:
<?php
    if (strpos(get_browser(),'537.36 Edge') !== false) {
        echo "Edge Browser Detected";
    }
    else
    {
       echo "You are not running Edge.";
    }

?>

Where echo "Edge Browser Detected";, replace with your error page, where echo "You are not running Edge.";, replace with your normal page content.
If you receive this error, refer to this question on how to fix:

WARNING get_browser() [function.get-browser]: browscap ini directive not set on line number 2

A: As mentioned in this thread: http://answers.microsoft.com/en-us/insider/forum/insider_internet-insider_spartan/ms-edge-show-alert-titled-this-website-needs/7771eb86-7b4d-440c-bc4d-43a88d1e489d
You may run a scan of your site here: http://dev.modern.ie/tools/staticscan/?url=http%3A%2F%2Fnaver.com
When you do so, there's an information message regarding the "Rendering Mode":

There is an issue with this website that could force an old rendering
  mode.
We've found that this webpage was added to a Compatibility View list
  when a user reported a compatibility issue while browsing in Microsoft
  Edge. For this reason, your site will render in Internet Explorer 11
  on Windows 10 as a fallback. We recommend that you use modern markup
  for all modern browsers and include Microsoft Edge in your test
  matrix.

So there you go, it seems that the website needs to be reported as incompatible for Edge to display this message. However, i'd be surprised if Microsoft added all reported sites to their compatibility list (I bet the site has to be of some significance and several users need to report the site).
Please see https://stackoverflow.com/a/31283160/1010492 on how to have your site added to the compatibility list.


text:
Q: How to fix table going outside of div tag in IE6 & 7? If a table is too big and the window is too small than the table goes outside the div.
I solved this with display:table !important; on the surrounding div but it doesn't work in IE 6&7 because they don't know it. How can I solve this in IE6 & 7?
See JSFiddle example:
http://jsfiddle.net/Kevin1990/LNS26/10/

A: Instead of using display: table, use float: left.
See: http://jsfiddle.net/thirtydot/LNS26/16/
This makes use of the "shrink wrap"/"shrink to fit" effect you get on a floated element if you don't specify an explicit width.


text:
Q: kprobe, function scheduling - processor lockup - Linux kernel I've a function I wrote in order to run a given function on all processors. It works perfectly well in all cases except the following case:
When I try to use it within a kprobe that I registered.
Here's some code:
static DEFINE_MUTEX(entryMutex);
static struct kretprobe my_kprobe = {
.entry_handler = (kprobe_opcode_t *) NULL,
.handler = (kprobe_opcode_t *) process_entry_callback,
.maxactive = 1000,
.data_size = 0
};

static int driver_init(void)
{

    my_kprobe.kp.addr =      (kprobe_opcode_t*)kallsyms_lookup_name("sys_execve");
    if ((ret = register_kretprobe(&my_kprobe)) < 0)
    return -1;
    return 0;
}

void foo(void* nothing)
{
     printk("In foo\n");
}

static int process_entry_callback(struct kretprobe_instance* instance, struct pt_regs* regs)

{
     mutex_lock(&entryMutex);

     for(int i = 0; i < 4; ++i) // assumes there are 4 processors
            run_func(foo, NULL, i);

     mutex_unlock(&entryMutex);
     return 0;
}

void run_func_wrap(struct function_data* data)
{
    data->func(data->context);
    wake_up_process(data->waiting_task);
    *(data->condition) = TRUE;
}

void run_func(SCHEDULED_FUNC func, void *context, int processor)
{
    struct function_data data;
    struct task_struct* th;
    BOOLEAN condition = FALSE;

    wait_queue_head_t queue;
init_waitqueue_head(&queue);

     data.func = func;
     data.waiting_task = current;
     data.context = context;
     data.condition = &condition;
     th = kthread_create(sched_func_wrap, &data, "th");
     kthread_bind(th, processor);
     wake_up_process(th);
     wait_event(queue, condition);
}

F
After the call to 'run_func' in process_entry_callback I can no longer run any programs. Every time I start a new program it just stuck. After a while I get 'processor lockup' warning in the system log.
I suspect that it has something to do with the IRQ levels.
Any suggestions ?
EDIT:
It also happens when using the following function:
smp_call_function_single

which can be found in smp.c @ the Linux kernel source code.
instead of my function:
run_func


text:
Q: payoff of a coin flip is $2^N$ We have a fair coin. The game ends when we get a head. the payoff is $2^N$ where N is the number of flips until we get the head. What is the expected value of the game? or, how much would you pay to play?

The series goes to infinity. We can get the head at the 1st,2nd,...,Nth flip.
The exp. payoff would thus be:
$E(x) = \frac{1}{2}2 + \frac{1}{4}4+...+\frac{1}{2^N}2^N$
$E(x) = \sum_{k=1}^n 1 $
How much would I pay? I don't know honestly

A: This question as said in the comments is a famous paradox, I would recommend reading some of the tagged literature to get a quantitative understanding, but I will provide a few qualitative things to point about.
Yes the expected value is infinite, does this mean you should mortgage your house, sell your TV and flog all your possessions to play it once? Surely the sum of all that isn't infinite? No you shouldn't, obviously not.
The notion of expected value works great when used as an indication for purchasing with "relatively small" values, lowish variance and a few other factors.
The truth is we shouldn't think of money as linear or symmetric. That is loosing $\$10,000$ and winning $\$10,000$ shouldn't be equally bad / good. Likewise winning ten billion dollars isn't a thousand times better than winning ten million dollars. In fact for a lot of normal people they would be sort of the same?
In a nutshell this question deals with an infinite amount extremely unlikely but extremely large values and as such expectation is somewhat misleading. Account for any finiteness to the game, for example consider the all the capital in circulation and the game becomes worth about $50$ bucks. Definitely not worth selling your house for!
You should look until utility functions, specifically logarithmic for easy calculations in this question to better understand it!

A: The expected value is infinite, as you've found. The variance is also infinite (this is always the case when the expected value is infinite).
Anything beyond that is not math but more of a modeling, economics or decision theory problem. For instance, the game described here can't be implemented by a real casino, as it only has a finite amount of money.
"The fair value for the game" depends on the decision model you have. A simple one might be that you bet all your money in any game with positive expectation. In this case, you should bet everything you have on this game. A more sophisticated model will likely give a different answer. Without a clear model here, you can't define the fair price for this game.


text:
Q: Passing keys to Full Screen game c++ So I'm trying to create an autowalk/run program for dayz. The current script I have seems to work for sending the 'w' key to anything except dayz. How would I go about making a run script or modifying my current code?
#include <iostream>
#define _WIN32_WINNT 0x0500
#include "windows.h"

using namespace std;

void pressW(bool x){
   INPUT ip;

   ip.type = INPUT_KEYBOARD;
   ip.ki.wScan = 0x57;
   ip.ki.time = 0;
   ip.ki.dwExtraInfo = 0;

   ip.ki.wVk = 0; //Hex code for 'W'
   ip.ki.dwFlags = KEYEVENTF_UNICODE; //Press the key down ?
   SendInput(1, &ip, sizeof(ip)); //Use function

   Sleep(10); //Sleep so it doesn't spam the key press

   //ip.ki.dwFlags = KEYEVENTF_KEYUP; //Release the key
   //SendInput(1, &ip, sizeof(ip)); //Use function
}
void releaseW(){

}

int main()
{
    bool run = false;
    while(true){
            if(GetAsyncKeyState(VK_INSERT)){run = !run;}

            while(run){
                pressW(run);
                if(GetAsyncKeyState(VK_HOME)){run = !run;}
            }
    }
    return 0;
}


text:
Q: Setting URL base to be able to use absolute links I am constantly finding myself a situation where I work on my clients' projects locally and put projects in appropriately-named folders. However, on production the files are put into root. I use absolute paths starting with a forward-slash to access all assets as such:

This works fine in production environment, but in development this translates to the root folder where all my projects are, so I would naturally have to include the folder name in the source above, which really breaks the flow of work:

I have read up about RewriteBase, but that seems to address htaccess rewrite rules only. There is also a  tag that could go into the HEAD section of the doc, but that does not seem to work too well with the front-coming forward slash. I would prefer to keep that forward-slash. Also, might be important to note, that my CSS files follow the same path logic.
Does anyone have a solution to my issue? Thanks.

A: As I've understood your question you are accessing your projects like http://localhost/project1/, http://localhost/project2/, ...
Create a virtual host for every project.
If your project is www.example.com you would create a virtual host (on your development machine) local.example.com which resolves to 127.0.0.1.

A: I use to run into the same issue, but what I did was just start placing the files I am working on in the root and when I'm done on that project move it into its proper folder. Then do the same for the next project. That way I am always coding for root to match my PROD environments.
The .htaccess you spoke of you would a pain because for each new folder you would have to go in and save it again.
Even jQuery wont be able to assist because your pathing your CSS sheets in the same manor.
It might be a few additional steps to always work in root, but at least your able to deploy the code without any find/replace.


text:
Q: How solve problem with install vue native? When I install vue native. I get this Err.
enter image description here
 I cant understand what I need to do.
I find some link about babel Requires Babel "7.0.0-0" but was loaded with "6.26.3"
install and it doesnt work.

A: I solve it, when I move in my created project, and make command npx babel-upgrade.
It's strange, because I was upgraded babel globaly erly


text:
Q: Mechanical Turk 'rollback' on HIT Creation Here is the code I currently have:
with transaction.commit_manually():
    try:
        m.update_accepted_url(episode_id)
        m.create_hit()
        m.do_insert()
        transaction.commit()
    except:
        transaction.rollback()

Now, what happens if the database operations fail -- and that rollback, but the create_hit goes through successfully? Is there a way to wrap the create_hit operation in something like a transaction, so if the db operations fail, that fails too?

A: You can add a unique token for your request, to avoid duplicates:
http://docs.aws.amazon.com/AWSMechTurk/latest/AWSMturkAPI/ApiReference_CreateHITOperation.html