Create Facebook Android Key hash from apk file

Question: First I'm not an Android developer and I know almost nothing about it .
as a vbulletin forum owner , I've got vbulletin android application .
I got it by filling a multi-step web form with data ( api key , facebook application id , secret , site name .. etc ) .. no development .. I get only a .apk file at the end .. so I have no android development environment installed .. no key store ( I don't even know what key store is ) .. the application has integrated facebook login but when I try to use it it asks for Key Hash .. is there a way to generate that .. thank you
Comment: If you install the Android SDK (https://developer.android.com/sdk/installing/index.html), you'll have the keystore at ~/.android/debug.keystore. Then you can generate the Key Hash.
Comment: thank you .. I will install it and come back
Answer: How to create a key hash from a keystore file is in Facebook Developer site.
On OS X:
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

On Windows:
keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl base64

If you want to upload your app to Google Play Store(not for debugging), you have to create another keystore file for release and use the same keystore file whenever you update the app. DO NOT LOSE YOUR KEYSTORE FILE.
See Signing Your Applications.
Create a key hash from the keystore for release again and register it to Facebook.


Java sort method in JML

Question: I need a sort method for JML I tried Insertion Sort but I don't know what requires and ensures or maintaingins I need. Please help.
I need //@requires, //@ensures and //@maintaining.
<code>public class InsertionSort

{

void sort(int arr[])
{
    int n = arr.length;
    for (int i=1; i<n; ++i)
    {
        int key = arr[i];
        int j = i-1;
        while (j>=0 && arr[j] > key)
        {
            arr[j+1] = arr[j];
            j = j-1;
        }
        arr[j+1] = key;
    }
}
}
</code>
Answer: The following ensures ascending order and preserves repetitions.
<code>//@ assignable arr[*];
//@ requires arr != null;
//@ ensures (\forall int i; 0 <= i && i <= arr.length-1; arr[i] <= arr[i+1]) &&
//@         (\forall int i; 0 <= i && i <= arr.length;
//@            (\num_of int j; 0 <= j && j <= arr.length;
//@               arr[i] == \old(arr[j])) ==
//@            (\num_of int j; 0 <= j && j <= arr.length;
//@               arr[i] == arr[j])
//@         );
//@
void sort(int arr[])
</code>

Java sort method in JML


How to determine which task is invoking an unanauthorized call in an ECS cluster running jenkins

Question: I have a situation where SOME task, under an assumed ECS role, is attempting to invoke a "CreateCluster" command and it's being (thankfully) denied!
However, there are 1000s of these invocation per hour and we are really trying to cut down on the noise.
We are running jenkins agents in ECS and SOME job (I assume) is trying to create clusters. I have checked our entire source code repo looking for a culprit and I find nothing. How do I figure out the origin of these calls when it could be any task/container on any host in this ECS cluster? Below is a snip of some athena output to help illustrate
Comment: Look at cloudtrail events with  the right eventName, they do have sourceIP Addresses, that might help.
Comment: It does. It's a public IP I don't recognize
Comment: I see that the CreateCluster call is invoked with an `assumed-role`. You can look in CloudTrail to find the AssumeRole call that gave these credentials. If Instance credentials were used to acquire these, it can point you to the instance/container.
Comment: @Niobos - thanks - let me try that
Comment: look at the cloudtrail event JSON, you should have a userIdentity element, see if the principalID, arn, sessionIssuer helps you figure out the instance id, taskid or role that was used to create the session and see if that provides a hint of where the call came from. Also see if you can paste the complete error message that might also have a hint of the task/instance-id that made the call. Also if your VPC is private the API source IP might be the one for the NAT gateway.
Comment: I know the instance id - it has an arn and the instance id is one of our cluster hosts. I have already completely inspected the userIdentity - that's the only reason I know it's the cluster. Thanks for the hint though
Answer: Ok, I figured it out:
All of my nodes are docker optimized AMIs - so, they would have the ecs agent installed even if I am not using them in an ECS cluster.
I temporarily gave it access to create a cluster (And it turns out it also wanted to RegisterContainerInstance) and it immediately created a cluster called default and registered my 2 docker build nodes and a 3 node I didn't readily recognize (which clued me in). it then registered 3 container instances.
When I look at the one instance I don't recognize I realized that isn't running a docker container on an optimized host and that's when it all came together: The ECS agents on virts, if they aren't part of a cluster, try to make themselves part of a default cluster and register themselves.
$ aws ecs describe-clusters --profile default --clusters default
{
    "clusters": [
        {
            "clusterArn": "arn:aws:ecs:us-east-1:882038671278:cluster/default",
            "clusterName": "default",
            "status": "ACTIVE",
            "registeredContainerInstancesCount": 3,
            "runningTasksCount": 0,
            "pendingTasksCount": 0,
            "activeServicesCount": 0,
            "statistics": [],
            "tags": [],
            "settings": [
                {
                    "name": "containerInsights",
                    "value": "disabled"
                }
            ]
        }
    ],
    "failures": []
}

instances
aws ecs list-container-instances --profile default --cluster default \
| jq -r '.containerInstanceArns[]' \
| xargs -L 1 aws ecs describe-container-instances --profile default --container-instances \
| jq -r .containerInstances[].ec2InstanceId
i-0f6e3c0b2e125c46c
i-07c6e10b85ac3bace
i-0619eccf3c2734b64


Migrating a Content Types and its Nodes into another site

Question: I have 2 Drupal 7 sites and I want to migrate data from one into the other. One of the D7 sites has a bunch of content types that the other doesn't have, along with a bunch of nodes associated with it (about 1000+ nodes). It's something I can't migrate manually or else it would take forever.
I know everyone points to the Migrate module to do something like this, but are there other similar methods that are just a streamlined. FYI, I never used the migrate module, as it seems like its more for migrating foreign data from other DB sources into drupal.
I remember there was another module that lets you copy data from another Drupal site, but it has to be the same version. Which one was this called?
Now the question is, what is the fastest approach in migrating data + content types between same version Drupal 7 sites? And what are some other caveats I might need to know?
Comment: There are a lot of questions here. :) "Fastest" is a matter of opinion and every situation is unique. Have you considered [Features](https://drupal.org/project/features) plus [Data Export Import](https://www.drupal.org/project/data_export_import)? This might suit your circumstances.
Answer: migrate_d2d provides a framework based on the Migrate API for migrating content from Drupal 5, Drupal 6, or Drupal 7 sites into the Drupal 7 site where it is installed
https://www.drupal.org/project/migrate_d2d
Using this module you can easly migrate your content types to other d7 instance.
Here You Just need to give database link form which you want to migrating content types.
Answer: Use features module to capture your content types and use node export module to export and import your nodes to your drupal site.


Command runs from command line, not from cron?

Question: I have the following command in my cron file:
*/15 * * * * NODE_ENV=production ~/bin/node ~/myapp/app.js > /var/log/nodelog/nodelog_`date "+%Y-%m-%d_%H-%M"`.log

The command itself runs OK when copied and pasted into the bash shell, but the cron job keeps sending the following error message:
/bin/sh: -c: line 0: unexpected EOF while looking for matching ``'
/bin/sh: -c: line 1: syntax error: unexpected end of file

Why does it run OK from the command line, but fail in the cron job? Is there a difference between the syntax expected on the command line and that expected in cron?
Answer: From crontab manpage:

Percent-signs  (%) in  the  command,  unless escaped with backslash
  (\), will be changed into newline characters, and all data after the
  first % will be sent to the command as standard input.
Answer: Crontabs are error prone for the following general reasons:

formatting requirements in crontab
permissions
environment

Hints

Use scripts, not inline commands in your crontab (!) - avoids escaping issues
Use absolute paths in your cron script.
Test using env -i ./myscript.sh
Comment: @MichaelKrelin-hacker: ninja editing - was typing response _while reading queston_ :) You're right my first hunch wasn't the main problem here
Comment: Yes, I've seen you put in the escaping after I commented and unless you're a computer, probably started doing so before you read it :)
Answer: Look at the cron file permissions. If it is owned by you, then you can use ~. Otherwise use full path..!


Trouble hitting EC2 AmazonProvidedDNS server over VPN

Question: I have a VPC using the network 10.10.0.0/16, and a VPN server in the public subnet (10.10.0.0/24). The VPN uses addresses in the 10.11.254.0/24 range. When I connect to the VPN, I can access hosts in both the public subnet and the private subnet (10.10.1.0/24), so I believe I have the routing table set up properly to send packets bound for the VPN back through the VPN server. I have disabled source/destination checks on the VPN server (which is also needed to be able to access other hosts in the network).
The AmazonProvidedDNS server seems to be working properly inside the VPC; I can run dig @10.10.0.2 ip-10-10-1-215.ec2.internal from a host in the VPC, and I get the expected response.
However, if I run that same dig command from may laptop, connected to the VPN, I get no response.
From running tcpdump on the vpn server, I see the A? packets coming from my VPN address, going to 10.10.0.2, but I don't see any response coming back. Is there something I need to do to enable the DNS server to answer requests from outside the VPC address range?
Answer: That sounds like unusual way to do it, but given the inside/outside split resolution magic they've implemented, I can see why it makes sense (now that I think about it).
It's unlikely that the EC2 DNS resolvers would answer requests from a foreign IP address, but there should be an easy workaround.
For example, if your IP address on the vpn is 192.168.2.*, then, on the vpn server in VPC...
$ sudo iptables --table nat -A POSTROUTING -s 192.168.2.0/24 -d 10.10.0.2/32 -j MASQUERADE

This adds a rule to the network address translation table so that after it makes the routing decision on packets from the specified source block to the specified destination block, instead of just forwarding the packet as usual, it will strip off your IP and add its own IP as the source address, and it will memorize the request.  When the response comes back, addressed to the vpn server's IP, it will again rewrite the address (destination, this time, back to your address) and send the response back to you.
That should accomplish what you want.
Comment: "Require?" Not in the sense that you are asking, no...  You should still be able to do everything the same as you're doing now. This adds a small exception to your routed vpn, performing NAT only for traffic to the one particular IP address, while continuing to pass traffic normally, if it doesn't match both the source and destination in the new rule.
Comment: Does this require me to use NAT on the VPN?  I'm not currently doing that. I'm using a 'routed' OpenVPN configuration.
Answer: You could spin up a micro instance and you could use it as udp proxy.
sysctl -w net.ipv4.ip_forward=1
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables -t nat -A PREROUTING -i eth0 -p udp --dport 53 -j DNAT --to 10.10.0.2


Set of open intervals in R with rational endpoints is a basis for standard topology on R

Question:
Show that the set $\mathcal{B} = \{(a,b) \subset \mathbb{R}: a,b \in \mathbb{Q}\}$ is a basis for the standard topology on $\mathbb{R}$

First I'll show that $\mathcal{B}$ is a basis on $\mathbb{R}$ and then i'll do a fineness comparison via bases:

1) Since $\cup_{p,q \in \mathbb{Q}\;for \;p < q}(p,q) = \mathbb{R}$, $\mathcal{B}$ covers $\mathbb{R}$. Since the intersection of open intervals is an open interval, every point in the intersection of two open intervals is contained in an open subinterval. Thus, $\mathcal{B}$ is a basis for some toplology $\tau$ on $\mathbb{R}$.2) Let$\;\mathcal{B_{stand}}\;$be the standard basis for the standard topology $\tau_{stand}$ on $\mathbb{R}$. Let $(p, q)\in \mathcal{B}$. Since $\cup_{x \in \mathbb{R},\;x > p} (x,q) = (p,q)$, every basis element in $\mathcal{B}$ can be written as the union of basis elements in $\mathcal{B_{stand}}$. Thus, $\tau_{stand}$ is finer than $\tau$.Let $(x, y)\in \mathcal{B}$. Since $\cup_{p,q \in \mathbb{Q}, \;x< p< q < y\;} (p,q) = (x,y)$, every basis element in $\mathcal{B_{stand}}$ can be written as the union of basis elements in $\mathcal{B}$. Thus, $\tau$ is finer than $\tau_{stand}$.$\therefore\;$ $\mathcal{B} = \{(a,b) \subset \mathbb{R}: a,b \in \mathbb{Q}\}$ is a basis for the standard topology on $\mathbb{R}$

Feedback on my proof and alternative ways to solve the problem would be appreciated.
(I also found a post where someone asked the same question, but I'm looking for  proof verification/alternative proofs so I'm not sure what the protocol is.)
Collection of open intervals $(a,b) \ a,b\in \mathbb{Q}$ is a basis for euclidean topology on $\mathbb{R}$
Answer: A couple of thoughts. First of all when you say "Since the intersection of open intervals is an open interval, every point in the intersection of two open intervals is contained in an open subinterval. Thus, $\mathcal{B}$ is a basis for some topolology $\mathcal{T}$ on $\mathbb{R}$." you need to be a bit more specific. You want to show specifically that if you have 2 basis elements $B_1$ and $B_2$ that both contain a point $x$ then you can pick a third basis element that contains $x$ and is in $B_1 \cap B_2$. To translate back to this problem you want to show that your open interval you get from intersecting the other 2 (or some smaller one inside it) has rational endpoints.
Using your notation for comparing bases we can show that $\mathcal{B}_{stand}$ is finer than $\mathcal{B}$ just by showing that $\mathcal{B} \subset \mathcal{B}_{stand}$. This is true because open intervals with rational endpoints are also just open intervals.
Finally I personally think that this lemma from Munkres would make for a more elegant argument than the final part of yours.
Lemma: $\mathcal{T}'$ is finer than $\mathcal{T}$ if and only if for each $x \in X$ and every basis element $B \in \mathcal{B}$ there is a basis element $B' \in \mathcal{B}'$ such that $x \in B' \subseteq B$.
Then instead of constructing any open interval as the union of open intervals with rational endpoints you just need to find one open interval with rational endpoints in this open interval that contains this arbitrary point $x$ from the interval.


Show border of an object on mouseover(Fabricjs)

Question: I'm trying to show borders of an object on the mouseover. i tried to use 'mouse:over' event of fabric and manually selected the object.
canvas.on('mouse:over', function(opts){
    var selectedObj = opts.target;
    canvas.setActiveObject(opts.target);
});

But there is one problem with this approach. I select one object and then try to do some operation by clicking some buttons(outside canvas). On the way of clicking button, if there is some object then that objects get selected.
So any other way to show borders of an object on its mouseover?
Answer: this is the trick that i do on my project , to programmatically activate an object and of course to show the borders and controls.
            //your object here should be opts.target
            //you set active property to true
              canvas.item(canvas._objects.length-1).set('active',true);
              canvas._activeObject = null;
           //again here you put opts.target
              canvas.setActiveObject(canvas._objects[canvas._objects.length-1]);
           //this helps to refresh
              canvas.renderAll();

and on 'mouse:out' event you can as well disable the active object, for the borders to show off.
Answer: canvas.on('mouse:over', function(opts) {
  var selectedObj = opts.target;
  canvas.setActiveObject(opts.target);
canvas.renderAll();
});


How to view status of recent AppEngine mapreduce jobs?

Question: We recently upgraded our App Engine application to GAE SDK 1.9, and upgraded the older MapReduce library we'd been using to the most recent version hosted on GitHub. We now find that the old MapReduce status page (http://.appspot.com/mapreduce/status) doesn't show the various daily jobs that we run.
The current GoogleCloudPlatform MapReduce doc (https://github.com/GoogleCloudPlatform/appengine-mapreduce/wiki/2.2-Monitoring-a-Job) describes a monitoring page that should be accessible at http://.appspot.com/_ah/pipeline/list -- but this gives a 'Requested URL ... not found on this server' message.
Is the URL described in the doc incorrect, or is this monitoring page no longer supported?
Answer: If you are using python use /mapreduce/pipeline/list
Any issues about the mapreduce library should be posted on their issues page.


Como fazer um Seed.rb buscando dados aleatoriamente SQLite no Rails?

Question: Como eu já tenho um cadastro de Cidades e estados, que podem ver abaixo, minha dúvida é a seguinte, como posso colocar dentro da função 10.times nas linhas da address_city e address_state um parâmetro para buscar cidades e estados aleatórios? dentro do que foi cadastrado no SQLite pela função BRpopulate.
Ruby 2.2.1
Rails 4.2.1
Este é o meu seed.rb:
require 'faker'

#create natural_person
10.times do
  natural_person = NaturalPerson.new(
     name: Faker::Name.name,
     short_name: Faker::Name.first_name,
     treatment: Faker::Name.prefix,
     profession: Faker::Name.title,
     email: Faker::Internet.email,
     address: Faker::Address.street_name,
     address_number: Faker::Address.building_number,
     address_district: Faker::Address.state,
     address_zipcode: Faker::Address.zip_code,
     birthday: Faker::Date.between(100.years.ago, 18.years.ago),
     phone: Faker::Number.number(10),
     mobile: Faker::Number.number(10),
     commercial_phone: Faker::Number.number(10),
     #city_id: ?
     #state_id: ?
     address_coutry: 'Brasil'
  )
  natural_person.save!
end

    # Polpulation State and City for DB
require 'net/http'
require 'json'

  module BRPopulate
   def self.states
     http = Net::HTTP.new('raw.githubusercontent.com', 443); http.use_ssl = true
     JSON.parse http.get('/celsodantas/br_populate/master/states.json').body
  end

  def self.capital?(city, state)
    city["name"] == state["capital"]
  end

  def self.populate
     states.each do |state|
      state_obj = State.new(:acronym => state["acronym"], :name => state["name"])
      state_obj.save

  state["cities"].each do |city|
    c = City.new
    c.name = city
    c.state = state_obj
    c.capital = capital?(city, state)
    c.save
  end
end
end
end

BRPopulate.populate

Models:
NaturalPerson
State
City

Answer: No meu caso Resolvi aqui assim:
city_id: City.order("RANDOM()").first.id,
state_id: State.order("RANDOM()").first.id,


New question approval by other senior person

Question: In last few days I have noticed many questions which are not actually a question but they are for the promotions of their service or product.
Where to Buy Cheap Careprost Bimatoprost Ophthalmic Solution Sale?
This is one example of it. This is wrong to share or spam on the StackExchange network.
So can't we have some Question approval process for new user ? Like if they ask question then it should be approved by senior user who have reputation more than 2K(or like any other )?
so what will be benefit, We can avoid such question to be published on the  network.
I posted this just for discussion to avoid such spamming on network.
Thank you.
Answer: It's not only about new users. Their post get reviewed as Piyush already said, but you'll still find some spam from time to time.

yes so my concern or this is just suggection that we may implement but still some negitive people have down vote it :)

When I find spam posts, I

downvote it
flag it as spam (gives another downvote)
check user profile for similiar answers

So it takes two just people for three downvotes to grey-out answer to make it less attractive. Finally, posts that are flagged as spam (correctly) will be deleted very fast.
Answer: There is already a review process for post from new users (First Post Review), which is reviewed by at least one reviewer (privilege awarded to users at 500 rep). While reviewing, a reviewer can improve post by editing or if reviewer found some thing wrong he/she can flag or vote it to close.
You can always flag such post if you found it spam or promotion only post.
Comment: I don't think  approval process needs to be implemented, as such post can be removed by a simple flag. Also approving every new post will increase work load on moderators.
Comment: if there is a process then why such post are still on the network ? any one approves it ?
Comment: approval is not in the process, if it is first post, it is reviewed as mentioned in my answer, while reviewing, a reviewer can improve post by editing or if reviewer found some thing wrong he/she can flag or vote it to close.
Comment: yes so my concern or this is just suggection that we may implement
but still some negitive people have down vote it :)
Comment: Okay
every one have different mindset :)
I thought this so I posted this suggection


Disk vs Shells Volume Strategy

Question: In response to the question "When do you use the shell method vs the washer method?," a former math professor gave the answer "If the region is bounded by functions of x, put the element in vertically and if by functions of y, put the element in horizontally. Once you have put in the element, look at whether it forms a washer (disk) or shell when it rotates about the axis of revolution." Let's say my task is to find the volume enclosed rotating the area enclosed by $y=\sqrt{x}$, $y=0$, and $x=4$ around the $y$-axis. The definition of a function of $x$ is that $y$ depends upon the value of $x$. $y=\sqrt{x}$ is surely a function of $x$ but as for $y=0$, I am not sure if it is a function of $x$ or $y$. The same goes with $x=4$. Thus, I am not sure whether to put in the element vertically or horizontally for this problem.
Answer: Note that $y=\sqrt{x}$ and $x=y^2$ are equivalent. Whether you view it as a function of $x$ or $y$ is relative. In many cases, you could either use the shell or the washer/disk method to integrate volumes and you would get the same result.
For your specific case, you could integrate elther way.
1) Washer/disk method:
$$V=\int_0^2 \pi (4^2 - x^2) dy= \pi\int_0^2(16-y^4)dy= \frac{128}5\pi$$
2) Shell method,
$$V=\int_0^4 2\pi x y \>dx = 2\pi \int_0^4 x\sqrt x dx = \frac{128}5\pi$$
Comment: But can't the integral be more complicated for one method? How would I know which one is more complicated without having to construct both integrals and compare them.
Comment: @user532874 - I'm not sure if there is a general prescription. It really depends on the curves for the enclosed area and the revolved axes. For your case, which is not all that complex, you could argue that the disk method is preferred since it is simpler.
Comment: @David K - you're right. just switched. thx
Answer: There is not exactly a fixed rule as when to use disks and when to use washers.
Generally, whey $y$ is expressed as a function of $x.$ (which is most common)
And you are rotating around the x axis, use disks/ washers.  And when rotating around the y axis use shells.
But often it can be done both ways just as easily.  And sometimes, it is, in fact, better to switch up from the established rule.
First step is to make a picture of the region.

At this point we pick, which seems easier?  Is there anything that might force me to break-up the region if I integrate with respect to x or with respect to y?
In this case, no.  Both methods are about equally complicated.  Shells looks a little bit easier.
Using shells, $y = 0$ forms the bottom of our verticals, $y= \sqrt x$ forms the top.
$\sqrt x - 0 = \sqrt x$ make the height of each cylinder wall.
Rotating around the y axis, $x$ is the radius of each cylinder
$V = 2\pi \int_0^4 x\sqrt x \ dx$
If you want to use washers you can.
$x = y^2$ makes the inner radius of each washer
$x = 4$ is the outer radius.
The limit of integration -- we will integrate to $y = 2$ as that marks the point where $y = \sqrt x$ intersects $x = 4$
$V = \pi \int_0^2 4^2 - y^4 \ dy$
Answer: For the purpose of applying the professor's advice,

$y = 0$ gives $y$ as a function of $x$ (which happens to be a constant function).
$x = 4$ gives $x$ as a function of $y$ (which happens to be a constant function).
$y = \sqrt x$ gives $y$ as a function of $x,$ but the same curve is described by $x = y^2$ where $y \geq 0,$ which gives $x$ as a function of $y$.

It turns out that either shells or washers will work for this problem, and with approximately equal complexity. (The amount of extra complexity you get by making the "wrong" choice seems not worth spending any time worrying about in this case; you'll waste more time trying to decide than you would have spent doing the more "complicated" integral.)
What I like to do is actually plot the curves and identify the region of the $x,y$ plane that they bound. Then look at whether I would like to take vertical elements or horizontal elements.
There are all kinds of situations that can come up that will make one way more complicated that the other, for example:

Horizontal elements near the top of the region are bounded by the same curve at both ends, so I would have to cut the curve into a "left" part and a "right" part with a different function for each.
Horizontal elements near the top of the region are bounded by a pair of curves, but horizontal elements near the bottom are bounded by a different pair of curves, so I'll need to write two integrals, one for the top of the region and one for the bottom.
The same situation with horizontal elements near the bottom and top, but some elements between the top and bottom are bounded by yet other pairs of curves, so I need three or more integrals to get the volume using horizontal elements.

Vertical elements can have similar complications, just consider the ones at the left or right ends of the region rather than the bottom or top.
In your example, all horizontal elements are bounded by the same pair of curves and the third curve is just the last element (so it gives you one end of one of the integrals). A similar thing is true for the vertical elements.
So both methods are straightforward to write as a single integral.
And there may be times when you look at the region and one way seems obviously best, but then when you have set up the integrals they look awful, so you try the other way instead, which might be easier (e.g. it has two integrals instead of one but the integrals are much easier to do) or it turns out even worse so you go back to the first way and slog through it.
If there were a simple, quick-to-apply rule that always gave the simplest answer, we wouldn't need to do so many exercises to get good at this!

Disk vs Shells Volume Strategy


How to prove that $(2+\sqrt{2})^{1/3}$ is irrational

Question: How does one show that $(2+\sqrt{2})^{1/3}$ is irrational?
I have got no idea how to solve that, please help!
Comment: No reason to shout
Comment: can you use $\LaTeX$ please?
Answer: Hint: If
$$
(2+\sqrt{2})^{1/3}=\frac{a}{b},
$$
then
$$
\sqrt{2}=\frac{a^3}{b^3}-2.
$$
Answer: Assume $(2+\sqrt{2})^{1/3}$ is rational. Then $\exists m,n\in\mathbb{Z}$ such that $$\sqrt[3]{2+\sqrt{2}}=\frac{m}{n}$$ where $\dfrac mn$ is a fraction in reduced form.So $$2+\sqrt{2}=\frac{m^3}{n^3}\implies \sqrt{2}=\frac{m^3}{n^3}-2$$ This contradicts the fact that $\sqrt{2}$ is irrational.
Comment: We need not write the fractional form, as we have not made explicit use of it!
Answer: $$(2+\sqrt{2})^{1/3}\in\mathbb{Q}\Longrightarrow 2+\sqrt{2}\in\mathbb{Q}\Longrightarrow \sqrt{2}\in\mathbb{Q},$$
contradiction.


Node reference to show only author of node

Question: I have create two content types as Game and Video. For the Video content type, I have created a node reference field that will be referring to the Game type.
Suppose I have 2 users (e.g. user1, and user2) on my site. User1 has created the following nodes:

Game1 (content type: Game)
Game2
Game3

User 2 has created the following nodes:

Game4
Game5

Suppose User1 is going to create one Video node. On the node reference selected list, I just want to see Game1, Game2, and Game3, but it is displaying all Games.
How can I solve it?
Answer: Use views integration option in Node Reference Field Settings... You can connect the node reference results with the view results.. When you edit node reference field settings you can see the setting to select view with which Reference Field pulls results...
You need to build a view first that will display all games created by logged in user... Then select this view in node reference field settings....


Cakephp - login failure when the database column Is set to value other than 1

Question: I am currently working with cakephp and have a login form that works perfectly , I mean , it worked perfectly ...
My table of users is something like this :
<code>id user email password plan_id active
</code>
When users have the plan_id = 1 perfeimtamente login works , but when the plan_id = 3 login is failing ...
My login settings are:
<code>$this->Auth->authenticate = array(
   'Form' => array (
      'userModel ' => 'Supplier'
      'fields' = > array (
      'username ' => 'email' ,
      'password' => 'password '
   )
   ' scope ' => array (
     ' Supplier.active ' => 1
   )
);
</code>
I can not understand what's going on ...
The User and password are correct , when I change the value of the column plan_id I can not log in
If you can help me thank you now.
Answer: http://book.cakephp.org/2.0/en/models/model-attributes.html#recursive
Solved
with 'recursive' => -1
<code>$this->Auth->authenticate = array(
   'Form' => array (
      'userModel ' => 'Supplier',
      'fields' = > array (
         'username ' => 'email' ,
         'password' => 'password ',
       ),
      'scope' => array (
         'Supplier.active ' => 1
       ),
      'recursive' => -1
);
</code>
Comment: Your description of the problem and the solution don't match/make sense. All recursive does is prevent returning joined model data - it's not going to directly make the difference between being able to login or not.
Comment: @AD7six I agree that it makes no sense , but I decided so...
I wanted to understand why not authenticated , if anyone can answer ...


How to add files using rules module?

Question: This question follows Override webform module submit
Based on this answer, I used the rules module to create a node after webform submissions.
My webform contains an <input type="file" />
for other <input type="text" /> I used this solution to How to save webform submissions data in fields using rules module
How can I add this file data in the field-image table?
Comment: About your last phrase: (1) please explain what you mean by "file data", is it only the PATH where the file is stored and (2) is "field-image" the machine name of your node in which you want to store  the path of that file?
Comment: Yes! field-image is the machine name of my node. And for the first => how can save data where
Comment: OK, you answered (2) in my prior comment, but NOT (1). Can you try again?
Comment: Thanks @Pierre.Vriens, yes it's only the PATH where the file is stored
Answer: The tricky part of what you're trying to do, seems to be related to correctly specifying the filename of the attached file (= the value to be stored in your field-image field). For this, have a look at what is suggested in Comment # 25 of the support issue (not bug ...) #1431572 and which states that the correct way to do so is something like so:
[node:field-file-attachments:file:path]

Use Rules debugging
This question is pretty tough to answer with the limited info you provided (and without access to "your" site). Therefor, if needed, you might also consider some Rules debugging, by (temporary) enabling the Devel module, so that you can (temporary) add a Rules Action like "Display a value" (in your case of the entire node/webform that's used to submit that attached file). For way more details about such debugging, refer to Rules debugging, as explained in the answer to "How can I display the value of a variable inside a condition?".
Comment: the problem is my rules does not allow the import of values of type other than **text**. I added a text field to my content type and using the **hook_node_presave** to synchronize the two fields.. @Pierre.Vriens, Thank you

How to add files using rules module?


How to create an azure event grid webhook in asp.net minimal api?

Question: I have an endpoint to initialize the database by reading and parsing the .tsv file by the provided path
    app.MapPost("/masterdata/initmediadb/{path}", async (
    string path,
    IMasterDataService masterDataService,
    IValidator<FilePath> validator,
    ILogger<Program> logger) =>
{
    var result = await validator.ValidateAsync(new FilePath { Path = path });
    if (!result.IsValid)
    {
        logger.LogError("Invalid path: {@path}, at initmediadb endpoint.", path);
        return Results.ValidationProblem(result.ToDictionary());
    }

    await masterDataService.InitMediaDatabaseAsync(path);
    return Results.Ok();
})
    .RequireAuthorization("MustBeAdmin");

I want to call it on the blob update, like I'am adding a tsv file to the blob, it calls this endpoint read, parse, and save to the database. What type of event should I use, and how to write such endpoint?
P.S: Endpoint requires authorization, authorization is handled by Okta, and returns a token when finished.
I am currently on this stage:
Comment: hope this Reference [helps](https://www.c-sharpcorner.com/article/how-register-an-http-webhook-azure-function-with-the-azure-event-grid/#:~:text=How%20To%20Register%20An%20HTTP%20Webhook%20Azure%20Function,EventGrid%20...%205%20Seeing%20it%20in%20Action%20) and [git](https://subhankarsarkar.com/custom-azure-event-grid-event-handling-with-net-core-webhook/)
Comment: for asp, net webhooks refer [this](https://www.dotnetcurry.com/aspnet/1245/aspnet-webhooks-receive-webhooks-from-github#:~:text=ASP.NET%20WebHooks%201%20The%20source%20calls%20the%20receiver%E2%80%99s,and%20then%20sends%20it%20to%20the%20WebHook%20handler)
Comment: Create web API with webhooks from the [git](https://i.imgur.com/Kwzaf78.png) attach the [link](https://i.imgur.com/2zFc2S7.png) and [create](https://i.imgur.com/r6D8nrg.png)
Comment: Hi @Sampath, thank you for your advices, I managed to create the webhook and now I am looking into a way to "read" the file I am adding. I want to check if the file is valid .tsv format and if so -> read and parse, got any insight on how to do it?
Answer:
From WebHooks  created webhook asp.net minimal api.Thank you @dotnetcurry.

public class GitHubWebHookHandler : WebHookHandler

{

public override Task ExecuteAsync(string receiver, WebHookHandlerContext context)

{

if
("GitHub".Equals(receiver,StringComparison.CurrentCultureIgnoreCase))`

{

string action = context.Actions.First();

JObject data = context.GetDataOrDefault<JObject>();

var dataAsString = Newtonsoft.Json.JsonConvert.SerializeObject(data);`

}

return Task.FromResult(``true``);
}
}

public class GitHubMessage

{

public JObject[] Commits { get ; set ; }

public JObject Issue { get; set ; }

public JObject Comment { get ; set ; }

public string Action { get ; set ; }

public GitHubActivityType ActivityType { get ; private set; }

}

For Read input of the file refer to this link.
Comment: @SPT Thank you for a very nice answer, I've managed to do what I wanted in a very similar way, and I will mark it as an answer so other users will see that it is a correct approach.


mysqld : multiple tmpdir & balancing

Question: Our 1Tb tempdir can sometimes be completely used by mysqld, resulting in disk-full and query errors. This can be due to lots of mid-size queries, or couple of very big queries.
We have a 5Tb raid drive I could use to expand this tempdir.
The manual says the /etc/my.cnf --tmpdir option can be set to a list of several paths, and that it can spread the load effectively.
If I set --tmpdir=/my1TbTemp/:/my5TbTemp/ I am wondering how mysqld will manage these two tempdirs. If the 1Tb disk is nearly full: will mysqld nicely switch to the 5Tb drive?
I've run some tests on a small virtual machine, but I'm not sure I can fully replicate the behavior of our production machine.
Answer: it is round robin so the first query will go to my1TbTemp and the next will go to my5TbTemp. If the first is full it will then move to the my1TbTemp for the query.
Comment: Thanks Mike - So I assume there's still a chance that a very big query tempfile will land on the 1Tb and crash it.
Comment: yes it is possible

mysqld : multiple tmpdir & balancing


Referring multiple names to the same entity

Question: I am working on the models of different product types and wish to generalize them to the same entity. For example, from the given list
Toshiba-A40C
Toshiba B30
Toshiba-Z40C411
Asus -X540
Asus R4
Dell XPS 15
Dell Inspiron 13

I would like to get a clean list of
Toshiba
Toshiba
Toshiba
Asus
Asus
Dell
Dell

Is there a programmatic way to get this one ? Is this called a record linkage? What are your recommendations ?
Comment: Index-Match or Vlookup in Excel could accomplish this simply.  R base code allows you to look up a value in a dataset (like the one you have above) given an input value.
Comment: Thank you @ERT  . What if the first word is misspelled such as Thoshiba- A40C. Is there a way we can generalize it to 'Toshiba' ?
Answer: I know that there are better solutions to this problem. I used a regular expression to match first space or dash and then cut the original list.
import re

example = """Toshiba-A40C
Toshiba B30
Toshiba-Z40C411
Asus -X540
Asus R4
Dell XPS 15
Dell Inspiron 13""".split('\n')

regular_exp = '(?: +)|(-)'

for i in range(len(example)):
    where = re.search(regular_exp, example[i]).span()
    example[i] = example[i][:where[0]]

print(example)


Python - consumir api com loop para paginação

Question: Atualmente eu consumo dados de uma api paginada utilizando python. Coloquei um número de paginas x, o problema é quando existem mais paginas, ou quando tem menos paginas e fica fazendo loop sem necessidade.
Sempre que a api tem uma proxima pagina, a mesma retorna a seguinte informação:
"has_next":true

e quando não tem
"has_next":false.

Seria possível eu fazer um loop olhando se existe a informação true,avanço para nova pagina, se retornar false ele encerra o loop ?
subd = 6
a=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
if subd >= 2:
    for page in a:
        request = curl.curlEc(subd, page)

segue o trecho de retorno em Json
[
   {
      "resultados":{
         "has_next":true,
         "current_page":1,
         "pedidos":[
            {
               "id":8809,
               "user":{
                  "id":2361,
                  "name":"",
                  "cpf":"",
                  "cnpj":"",
                  "sexo":"feminino",
                  "data_nascimento":" ",
                  "devices":[

                  ]
               },
               "loja":"",
               "tipo_frete":null,
               "endereco_entrega":null,
               "forma_pagamento_entrega":"Débito",
               "cupom_desconto":null,

Comment: parece um problema a ser resolvido com o try statement. Veja documentação: https://docs.python.org/3/reference/compound_stmts.html#try
Answer: Usando requests seria algo como:
import requests

page = 1

while True:
    # supondo que a chamada passe a página como parâmetro
    r = requests.get(f'https://dominio?page={page}')

    # testando resposta, se for diferente de 200 (OK), sai do loop
    if r.status_code != 200:
        break

    #assumindo que é uma lista com um único item
    results = r.json()[0]

    #
    # AQUI VC PROCESSA O RESULTADO
    #

    # apenas para ficar claro
    has_next = results["resultados"]["has_next"]

    page = page + 1

    if not has_next:
        break


How can ı do read excel with sheetjs in Clojurescript?

Question: I have a excel file. I imported sheetjs (https://sheetjs.com/). I want to read to sheet data. How can ı do read excel with sheetjs in Clojurescript?
The project written with https://github.com/day8/re-frame
Comment: This is too broad Akaza. The library seems [well documented](https://docs.sheetjs.com/docs/) and js interop for Clojurescript is also pretty well documented, what *specifically* are you having trouble with? I'm not going to say that questions with no user-written code in them are *always* off-topic, but pretty nearly (including this one).
Comment: ı am new about clojure. I ask to how can use xlsx with clojure. Thank you so much. my answer in comment
Answer: This should put you in the right direction - it opens a file called datadump.xlsx in the same folder as index.html (the root folder of your app). Easy to adapt to upload a file through a form. In the main namespace you'd just call <code>(data/read-local-file)</code>.
<code>(ns data
  (:require [reagent.core :as r]
            [reagent.dom :as rd]
            [re-frame.core :as rf]
            ["xlsx" :as XLSX]))

(defn read-sheet [wb sheet-name]
  (let [sheet (aget (. wb -Sheets) sheet-name)
        data (XLSX/utils.sheet_to_json sheet #js {:header 1})
        dataclj (js->clj data)
        kk (map keyword (first dataclj))
        outdata (into [] (for [line (rest dataclj)] (zipmap kk line)))]

    (rf/dispatch [:source-data outdata])))

(defn read-local-file []
  (let [xhr (js/XMLHttpRequest.)]
    (.open xhr "GET" "datadump.xlsx" true)
    (set! (.-responseType xhr) "blob")
    (set! (.-onload xhr)
          (fn []
            (let [reader (js/FileReader.)]
              (.readAsArrayBuffer reader (.-response xhr))
              (set! (.-onload reader)
                    (fn [evt]
                      (let [ab (-> evt .-target .-result)
                            wb (XLSX/read ab #js {:type "array" :cellDates true})
                            sn (. wb -SheetNames)]
                        (read-sheet wb (first sn))))))))
    (.send xhr)))

</code>


java- how to generate a random hexadecimal value within specified range of values

Question: I have a scenario in a java web app, where a random hexadecimal value has to be generated. This value should be within a range of values specified by me. (The range of values can be hexadecimal or integer values).
What is the most efficient way to do this> Do I have to generate a random decimal number, and then convert it to hexadecimal? Or can a value be directly generated?
Comment: `Integer.toHexString(yourRandomNumber)` doesn't suffice?
Answer: Yes, you just generate a decimal value in your range. Something such as:
Random rand = new Random();
int myRandomNumber = rand.nextInt(0x10) + 0x10; // Generates a random number between 0x10 and 0x20
System.out.printf("%x\n",myRandomNumber); // Prints it in hex, such as "0x14"
// or....
String result = Integer.toHexString(myRandomNumber); // Random hex number in result

Hex and decimal numbers are handled the same way in Java (as integers), and are just displayed or inputted differently. (More info on that.)
Comment: `rand.nextInt(0x10)` won't generate 0x10, only 0..0xF. See [JavaDoc Random](http://docs.oracle.com/javase/6/docs/api/java/util/Random.html) _Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)_
Answer: Try this,
String s = String.format("%x",(int)(Math.random()*100));
System.out.println(s);

Comment: The OP would like the hex number to be in a range. This doesn't do it, right?
Answer: Random randomService = new Random();
StringBuilder sb = new StringBuilder();
while (sb.length() < RANDOM_HEX_LENGTH) {
    sb.append(Integer.toHexString(randomService.nextInt()));
}
sb.setLength(RANDOM_HEX_LENGTH);
System.out.println(sb.toString());

Answer: You can try this. As this works for me:
Random random = new Random();
int nextInt = random.nextInt(256*256*256);
System.out.println(String.format("#%06x", nextInt));

Comment: Question was answered 5 years ago, so I think it will not help the logger anymore... And please explain your answer, copypaste is never a solution, we want to understand the problem and the solution, if not, we will need to go on Stackoverflow again to post the same question applied on a different problem.
Answer: Using Math.sin() (colors adaptable to totalItems to be colored):
double rFactor=0;
double gFactor=0.5;
double bFactor=1;
double rAdd=0.1;
double gAdd=0.2;
double bAdd=0.3;
String lettersLight[] = "6789ABCDEF".split("");
String lettersDark[] =  "0123456789".split("");
int halfLetters=lettersDark.length/2;

private void initRandomColor2(int totalItems) {
    double rFactor=0;
    double gFactor=(Math.PI/totalItems)*2;
    double bFactor=(Math.PI/totalItems)*4;
    rAdd=(Math.PI/totalItems)+(Math.PI/totalItems);
    gAdd=(Math.PI/totalItems)+(Math.PI/totalItems)*2;
    bAdd=(Math.PI/totalItems)+(Math.PI/totalItems)*4;
}
private String getRandomColor2(boolean light) {
    int r=(int)(halfLetters+(Math.sin(rFactor)*(halfLetters-1)));
    int g=(int)(halfLetters+(Math.sin(gFactor)*(halfLetters-1)));
    int b=(int)(halfLetters+(Math.sin(bFactor)*(halfLetters-1)));
    rFactor+=rAdd;
    gFactor+=gAdd;
    bFactor+=bAdd;
    return (light
            ?lettersLight[r]+lettersLight[r]+lettersLight[g]+lettersLight[g]+lettersLight[b]+lettersLight[b]
            :lettersDark[r]+lettersDark[r]+lettersDark[g]+lettersDark[g]+lettersDark[b]+lettersDark[b]
            );
}

Answer: Random progressive hex colors:
String letters[] = "0123456789ABCDEF".split("");
int min=letters.length-(letters.length/3);
int max=letters.length;
Random rnd=new Random(1000);
String colorEx[]= new String[]{"00","00","00"};
int colorChange=0;
int addColorChange=1;

private String getRandomColor() {
    StringBuilder color = new StringBuilder("#");
    int highColor=rnd.nextInt(2)+1;
    for (int i = 0; i<3; i++) {
        int addColor=0;
        if (i==highColor)
            highColor=min;

        color.append(colorEx[i]);

        if (colorChange==i) {
            if (colorEx[i].equals("00"))
                colorEx[i]="55";
            else if (colorEx[i].equals("55"))
                colorEx[i]="AA";
            else if (colorEx[i].equals("AA"))
                colorEx[i]="FF";
            else {
                if (i>0 && !"00".equals(colorEx[i-1]))
                    colorEx[i-1]="00";
                else if (i<2)
                    colorEx[i+1]="00";
                colorChange+=addColorChange;
                //colorChange++;
                if (colorChange>2 || colorChange<0) {
                    //colorChange=0;
                    addColorChange=-addColorChange;
                    colorChange+=addColorChange;
                    colorChange+=addColorChange;
                }
            }
        }
    }
    return color.toString();
}


Migrate to GNUmake

Question: I have a proprietary build utility that builds a bunch of objects and executable across different directories.  I want to migrate to GNUmake.  Are there any tools that will parse the log files from previous build and construct makefiles?
Comment: @MadScientist: Well, to be fair, if it were smart enough to deduce intended targets and infer prerequisites (in the general case!), then it would certainly be smart enough to simplify its own rules. And it could probably serve as a pretty good system administrator, too.
Comment: I was thinking more like, something that can recognize the standard compiler format (`-o` followed by target, plus standard `-c` flag and source file names like `xxx.c` or `xxx.cpp`, and could convert that into an explicit rule.  Creating a map of regexs that can match various compiler rule commands would not take very long.  I could probably write the thing in Perl in less than 20 lines plus regex's (sorry, I'm a Perl guy.  Sue me.)  Anything more complex gets exponentially more difficult the more you want to do (match common compile commands to set variables, etc. etc.)
Comment: I'm not aware of any tool like that.  Even if it were available, it would likely create the stupidest possible result: every target hard-coded as a different explicit rule, with no use of pattern rules or variables to simplify.
Comment: Thanks PS
Any other suggestions to simplify the migration is appreciated.
Comment: Are you free to try different/all targets? Do you know what all the targets are? Then I think you could actually rebuild the dependency graph. From there, just implement that graph in GNU Make.
Answer: There isn't really an easy way to do this, mainly because, I'm guessing, your build scripts are exactly that, scripts, written in an imperative fashion, whereas make is declarative (like Prolog), which is a real shift in mindset.
If you're using GCC (and I think GreenHills or Intel), you can have the compiler generate dependency information for you automatically. See the -MD and related options in the GCC manual.
These will potentially give you some hints as to what's going on, but ultimately, you just need to sit down and work out what's going on and translate that into make syntax; the make manual is actually pretty good - just make sure you start by doing a heirarchical build (i.e., do not use make -C in your Makefiles), as recursive make systems make it almost impossible to track dependencies reliably (I've yet to see one that does).

Migrate to GNUmake


Known alpha and type I error rate simulation

Question: I am not sure why running the following code in R does not result in a type I error rate of exactly 5% given alpha = 0.05 when set.seed is set to 1. Is there a reason why running the simulation below gives a type I error rate of 4% when it should be exactly 5% using set.seed(1)? Sometimes when you run the simulation, you get a p-value <0.05 in 3.2% of the simulations, is this due to rnorm drawing a random normal number each time?
set.seed(1)
n=1000 # testing 1,000 times
t1err=0
for (i in 1:n){
  x=rnorm(100, 0, 1)
  if (((t.test(x, mu=0))$p.value)<=0.05) (t1err=t1err+1)
}
cat("Type I error rate in percentage is", (t1err/n)*100,"%")

Why is it that seed = 123, p = 3.2% sometimes with n = 1000? This seems far off from the stated true value of 5%? Is this due to how R draws random normal numbers each time using rnorm regardless of set.seed? Supposedly the function of set.seed is to make the simulations more reproducible each time.
Comment: Why do you believe the type I error rate should be "exactly" 5%?
Comment: This is asked about R, but the same thing would happen with other simulators.  It's not really about  R, so I vote to leave it open.
Comment: When you are patient enough, you can create non-random sequences with any pseudorandom number generator.  The technique is explained and illustrated at https://stats.stackexchange.com/questions/38063/some-questions-about-statistical-randomness/38067#38067.
Comment: Please register &/or merge your accounts (you can find information on how to do
this in the **My Account** section of our [help]), then you will be able to
edit & comment on your own question.
Answer: If you simulate a lot more tests it gets closer to 5% - I think this is a case of a slower convergence to the "true" value than you seem to expect:
    set.seed(1)
    n=100000 # testing 100,000 times
    t1err=0
    for (i in 1:n){
      x=rnorm(100, 0, 1)
      if (((t.test(x, mu=0))$p.value)<=0.05) (t1err=t1err+1)
    }
    cat("Type I error rate in percentage is", (t1err/n)*100,"%")

gives 4.894%
Answer: It's because rnorm is random draws.  If you use a different seed, you will get different values.
seed = 12, p = 4.9%
seed = 123, p = 3.2%
seed = 1234, p = 5.4%

and, as @dlmoore pointed out, 1,000 is not very many.  If you use 100,000, then with
seed = 1, p = 4.89%
seed = 12, p = 4.89%
seed = 123, p = 5.04%
seed = 1234, p = 5.13%

but there is no reason for it to equal exactly 5.00000.
Comment: Be careful with "never," Peter: in this Binomial simulation of 1000 draws there is almost a 5.8% chance of obtaining *exactly* a 5% result. In a simulation 100 times longer (100,000) the chance drops to a tenth of that, but a value greater then a half percent is still appreciably different from "never."
Comment: OK, good point. I will amend my answer.
Answer: Remember that p-values, test decisions, test statistics etc. are (pseudo-)random variables. You have some realization off one for each (simulated) dataset, but the expected value is solely what you expect in the long-run.
In fact, here it is clear that for a single simulated dataset the estimated type 1 error rate would soothe be 0 or 1. For two datasets 0, 0.5 or 1 and so on. You first have any possibility of exactly 0.05 for 20 simulated datasets.
If you consider the new random variable that is the estimated type 1 error rate across a finite number $m$ of datasets, its expectation is 0.05 for all values of $m>0$ in your example, but it's variance decreases with $m$, but even with rounding to 4 decimals it takes a while until your are almost certain to get 0.0500.
Answer:
Basically you are flipping a coin 1000 times and it will fall on heads (error) 5% of the time. The distribution for such occurrences is a binomial distribution:

So every time you redo the 1000 experiments you might observe a different number of failures.

The expected number of failures will be 5% (or 50 occurrences in 1000), when the null hypothesis is true.
but the observed number of failures is a variable which will be distributed according to the above image and is not necessarily equal to 5% every time.

The p-value is, in this case, just a (convenient) re-parameterization of the t-value, which is a random variable

See also below an example of your simulation repeated for 10 000 different seeds. You will get a different number of errors each time. However, the distribution of these different numbers resembles the distribution in the image above.

errors <- sapply(1:10000, FUN = function(x) {
  set.seed(x)
  n=1000 # testing 1,000 times
  t1err=0
  for (i in 1:n){
    x=rnorm(100, 0, 1)
    if (((t.test(x, mu=0))$p.value)<=0.05) (t1err=t1err+1)
  }
  t1err
})

layout(matrix(c(1,2), 1, 2, byrow = TRUE),width=c(4,1))
plot(1:1000,errors[1:1000],
     xlab="used seed", ylab="number of errors",
     ylim=c(25,75),
     pch=21,cex=0.7,
     col=adjustcolor("black",alpha.f=1),bg=adjustcolor("black",alpha.f=1))
title("number of errors for different seeds  \n (1 000 shown)")

yhist <- hist(errors, plot = FALSE,breaks=seq(25,75,by=2.5))
margins <- par()$mar
par(mar = c(margins[1],0,margins[3],1))
barplot(yhist$counts, axes = 0, horiz = TRUE)
title("histogram  \n (for 10 000)")


Prove Logistic sequence is convergent when $2<k\le3$

Question: Let $0<x_1<1$, $x_{n+1}=kx_n(1-x_n)$ be Logistic sequence. If $2<k\le3$, how to prove the sequence always converges to $1-1/k$?
Edit: I need a direct proof in calculus without using any result from dynamic system.
Answer: The fixed points are solutions to $$x=kx(1-x)$$ which are $x=0$ and $x=1-1/k$
We need to show that the fixed point $1-1/k$ is an attractor for $2<k<3$
We take derivative of $f(x)=kx(1-x)$ and show that for the given value of the fixed point $|f'(x)|<1$
Note that $|f'(1-1/k)| = |k-2|$ which is less than $1$ for $2<k<3$
Comment: But the claimed range of convergence is $2|x_1-(1-1/k)|$.


WinForm automatically resize window for new controls but still allow user to adjust the size?

Question: I have a windows form that has a list of controls on one side and a graph on the other. I want a checkbox to hide and show the graph, but to also shrink or grow the form to accommodate it.
I tried using AutoSize=true for the form, but then the user can't adjust the size of the form (ie expand or shrink the graph to their screen).
Then I tried
    private void toggleCheckBox_Click(object sender, EventArgs e)
    {
        theGraph.Visible = toggleCheckBox.Checked;

        // automatically resize the form
        this.AutoSize = true;
        this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
        this.OnResize(e);

        // this will force the form back to its original size
        // but without it the user cant adjust the form size
        this.AutoSize = false;
    }

How can I display the graph and resize the form on demand, but not restrict the users from resizing the form themselves?
Answer: The solution I came up with was to save the size, disable the autosize, and then force the size:
    private void toggleCheckBox_Click(object sender, EventArgs e)
    {
        theGraph.Visible = toggleCheckBox.Checked;

        // automatically resize the form
        this.AutoSize = true;
        this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
        this.OnResize(e);

        var NewSize = new System.Drawing.Size(this.Width, this.Height);

        // this will force the form back to its original size
        // allowing the user to adjust the form
        this.AutoSize = false;

        // force the form back to its new size
        this.Size = newSize;
    }

Note: For the AutoSize to work correctly with anchored controls be sure to set a MinimumSize for the control being toggled so that a desired amount will be visible on the form.


Use L'Hopital's rule to show that u′(t) = −λ u(t) (question from a Probability course)

Question: I'm currently in a probability course and my professor suggested this question:
Consider a continuous and differentiable function u(t) such that u(t + s) = u(t)u(s), for any s ∈ R and t ∈ R. This function has the following properties: u(0) = 1; u is a non-increasing function (i.e. u′(t) ≤ 0, for all t); and lim u(t) = 0.
I'm trying to show that u′ (t) = −λ u(t), for some constant λ > 0 by using L'Hopital's rule.
We're currently discussing the Poisson process and the Exponential distribution so my professor then added that we should show that the function u mentioned above has to be in the form of u(t) = e^(−λt). I'm not exactly sure what this has to do with what we've been learning, and if someone would be able to explain the significance of these two "show this" questions, I would appreciate the clarification.
Answer: First of all, note that since $u(0)=1$ and $u$ is continuous, there is a positive real number $\delta$ such that $u(\delta)>0$. Then $u(n\delta)=u(\delta)^n>0$ for all $n$, and since $n\delta\to\infty$ and $u$ is non-increasing, this shows that $u(t)>0$ for all $t\geq0$.
Therefore we can define $v(t)=\log(u(t))$ for $t\geq 0$. The functional equation for $u$ implies that
$$ v(t+s)=v(t)+v(s) $$
for all $t,s\geq 0$, and since $v(t)$ is continuous this implies that $v(t)=\alpha t$ for some $\alpha\in\mathbb{R}$ (look up the Cauchy functional equation if you're not familiar with this).
Thus $u(t)=e^{v(t)}=e^{\alpha t}$, and since $u$ is non-increasing with $\lim_{t\to\infty}u(t)=0$, we can take $\alpha=-\lambda$ with $\lambda>0$.
Answer: $$u'(t)=lim_{\Delta x\to0}\frac{u(x+\Delta x)-u(x)}{\Delta x}$$
$$=lim_{\Delta x \to 0}u(x)\frac{u(\Delta x)-1}{\Delta x}$$
Now since both the denominator and the numerator in the fraction is in indeterminate form $\frac0 0$, we differentiate both $u(\Delta x)-1$ and $\Delta x$ with respect to $\Delta x$.
$$=u(x)lim_{\Delta x\to 0}u'(\Delta x)$$
Since $u(x)$ is differentiable, which means $u'(0)$ must exist,  so we can let $u'(0)= -\lambda$ where $\ lambda$ is a positive real number. So you have $u'(x)=-\lambda u(x)$. Since  $u'(x)$ is negative, so $u(x)$ must be positive for all $x$.
Solving the differential equation $u'=-\lambda u$ by noticing
$ln(u(x))'=\frac{u(x)}{u'(x)}$
So $$ln(u(x))=-\lambda x +C$$
$$u(x)=e^{-\lambda x}*e^C$$
Substitute $u(0)=1$ gives
$$1=e^C$$
So $$u(x)=e^{-\lambda x}$$


Morris js dynamic ykeys

Question: I am building a chart to track my product stocks on how many do I have left in a month. I'm trying to build a 12-month projected stock from the current month.
I would like to give a try Morris.js. In there demo you have a and b as your ykeys. I assume those are products. It works great if you have control of your product list. But what if the your user added new products. Say, product c, d and e. How do you intend to those product in the chart without hard-coding it?
I'm using asp.net mvc 5, EF 4 Code-first. I can't get in my head on how to achieve it. Any help would be much appreciated. Thanks!
Comment: I find a solution for mvc : http://stackoverflow.com/questions/33347282/convert-objects-to-json-in-c-sharp/33371447#33371447
Comment: I opt to use reflection to create my classes runtime and have it populated with my data. Thanks. I'll try that one out.
Answer: You can provide an array of values that is fetched dynamically for your ykeys attribute.  How this array is fetched is really up to you, but one possibility is via an Ajax request.  Consider the following:
var request = $.ajax({
   url: getGraphDataUrl,
   type: "GET",
   statusCode: {
        200: function (msg) {
            if(typeof msg != 'undefined' && msg.length > 0) {
                msg = JSON.parse(msg);
                Morris.Line({
                    element: 'line-example',
                    data: msg.data,
                    xkey: 'y',
                    ykeys: msg.ykeys,
                    labels: msg.labels
                });
            }
        }
    });

Clearly, this is a grossly simplified example.  As you can see, many attributes could be fetched as JSON via an Ajax request.  Of course, you will have to write the server-side code that will form the JSON response, but I believe that is outside of the scope of this question.

Morris js dynamic ykeys


php mongodb full-text search and sort

Question: i nead to make a search with full text index and this code work:
$cursor=$collection->find(array('$text'=>(array('$search'=>$s))),
                    array("score"=> array('$meta'=>"textScore"))
        );

i try to sort the cursor with:
$cursor =$cursor->sort(array("score"=>1));

when i try to read
var_dump($cursor->getNext());

i gave me this error
Uncaught exception 'MongoCursorException' with message 'localhost:27017: Can't canonicalize query: BadValue can't have a non-$meta sort on a $meta projection'
any idea?
Comment: Try to eliminate "score" search criteria from find(). Most probably it is not allowing to find and sort on same key value.
Comment: but how can i ask to sort over a fiel that is built on the search, if i eliminate from the second fiel of db.collection.find() how can i save the score that is built as metadata? i tryed to eleminate but the sort not work how should i write it? thx
Comment: FYI: You have extra () around your array('$search'=>$s). See my answer below for the sort() solution
Answer: You are attempting to sort on a meta field, not a normal fieldname.
The second argument to $collection->find() determines which fields of the document you (do/do not) want to be returned by the query.
This is similar to SELECT *... vs SELECT field1, field2 ... in SQL databases.
Now, in MongoDB 2.6 there is an additional keyword you can use here, $meta. This keyword allows you to "inject" fieldnames into the return document (that otherwise would not actually exist). The value of this injected fieldname would come from some sort of "meta data" of the document or query you are executing.
The $text query operator is an example of an operator that has more information available about the matched document.. Unfortunately, it has no way of telling you about this extra information since doing so would manipulate your document in unexpected way. It does however attach a metadata to the document - and it is up to you to decide if you have need for it or not.
The meta data the $text operator creates uses the keyword "textScore". If you want to include that data, you can do so by assigning it to a field name of your choice:
array("myFieldname" => array('$meta' => 'keyword'))

For example, in the case of $text search (textScore) we can inject the fieldname "score" into our document by passing this array as the 2nd argument to $collection->find():
array("score" => array('$meta' => 'textScore'))

Now we have injected a field called "score" into our return document which has the "textScore" value from the $text search.
But since this is still just meta data of the document, if you want to continue to use this value in any subsequent operations before executing the query, you still have to refer to it as $meta data.
This means, to sort on the field you have to sort on the $meta projection
array('score' => array('$meta' => 'textScore'))

Your full example then becomes:
<?php
$mc = new MongoClient();

$collection = $mc->selectCollection("myDatabase", "myCollection");

$string = "search string";
$cursor = $collection->find(
    array('$text' => array('$search' => $string)),
    array('score' => array('$meta' => 'textScore'))
);

$cursor = $cursor->sort(
    array('score' => array('$meta' => 'textScore'))
);

foreach($cursor as $document) {
    var_dump($document);
}

php mongodb full-text search and sort


How do you read two CSV files in python using pandas and append them to each other?

Question: I am working on an application that requires me to import CSV files and display each row as a banner. The current method I am using successfully displays the banners, but what it is doing each time is overwriting the array that I am using. What I would like to do is read a CSV file, append it to an array, then have the option to read another CSV file to the same array. This is so that I can then run another method that allows me to read that array and save both sets of data back to another CSV file.
Here is my method for retrieving the data
def GetData(root, self, data_dictionary, data_arr):
        temp = Tk()
        temp.wm_state('iconic')

    filetypes = (
        ('CSV', '*.csv'),
        ('All files', '*.*')
    )

    filename = fd.askopenfilename(
        title='Open a file',
        initialdir='./geodata/',
        filetypes=filetypes)

    if filename:
        with open(filename):
            data_arr = pd.read_csv(filename)
            temp.destroy()
            return data_arr
    else:
        Alert(title='Error', text='Please select a file')
        temp.destroy()
        return

I then have another method that calls the method:
def upload_file(root, self):
    global data_arr
    values = GetData(self, root,  data_arr) #Where data_arr is defined in the global scope as []
    data_arr.append(values)
    print(data_arr)

The first time I upload a file, this is what it prints:
[(  publicid   eventtype                origintime          modificationtime   longitude  latitude  magnitude  ...  usedphasecount usedstationcount  magnitudestationcount minimumdistance azimuthalgap originerror magnitudeuncertainty
0  testid1  earthquake  2021-08-24T04:49:39.852Z  2021-08-24T04:54:00.721Z  177.428024  -37.3592   2.342669  ...              16               12                      6        0.486189   258.299072    0.542223                    0
1  testid2  earthquake  2021-08-24T04:49:39.852Z  2021-08-24T04:54:00.721Z  177.428024  -37.3592   2.342669  ...              16               12                      6        0.486189   258.299072    0.542223                    0

The problem with this method is that it prints a result like this when I try and upload a second file:
[(  publicid   eventtype                origintime          modificationtime   longitude  latitude  magnitude  ...  usedphasecount usedstationcount  magnitudestationcount minimumdistance azimuthalgap originerror magnitudeuncertainty
0  testid1  earthquake  2021-08-24T04:49:39.852Z  2021-08-24T04:54:00.721Z  177.428024  -37.3592   2.342669  ...              16               12                      6        0.486189   258.299072    0.542223                    0
1  testid2  earthquake  2021-08-24T04:49:39.852Z  2021-08-24T04:54:00.721Z  177.428024  -37.3592   2.342669  ...              16               12                      6        0.486189   258.299072    0.542223                    0

[2 rows x 21 columns],), (  publicid   eventtype                origintime          modificationtime   longitude  latitude  magnitude  ...  usedphasecount usedstationcount  magnitudestationcount minimumdistance azimuthalgap originerror magnitudeuncertainty
0  testid1  earthquake  2021-08-24T04:49:39.852Z  2021-08-24T04:54:00.721Z  177.428024  -37.3592   2.342669  ...              16               12                      6        0.486189   258.299072    0.542223                    0
1  testid2  earthquake  2021-08-24T04:49:39.852Z  2021-08-24T04:54:00.721Z  177.428024  -37.3592   2.342669  ...              16               12                      6        0.486189   258.299072    0.542223                    0

[2 rows x 21 columns],)]

Is there a way I can read the second CSV file and have it store it in the original array with the other data like this:
[(  publicid   eventtype                origintime          modificationtime   longitude  latitude  magnitude  ...  usedphasecount usedstationcount  magnitudestationcount minimumdistance azimuthalgap originerror magnitudeuncertainty
0  testid1  earthquake  2021-08-24T04:49:39.852Z  2021-08-24T04:54:00.721Z  177.428024  -37.3592   2.342669  ...              16               12                      6        0.486189   258.299072    0.542223                    0
1  testid2  earthquake  2021-08-24T04:49:39.852Z  2021-08-24T04:54:00.721Z  177.428024  -37.3592   2.342669  ...              16               12                      6        0.486189   258.299072    0.542223                    0
3  testid3  earthquake  2021-08-24T04:49:39.852Z  2021-08-24T04:54:00.721Z  177.428024  -37.3592   2.342669  ...              16               12                      6        0.486189   258.299072    0.542223                    0
4  testid4  earthquake  2021-08-24T04:49:39.852Z  2021-08-24T04:54:00.721Z  177.428024  -37.3592   2.342669  ...              16               12                      6        0.486189   258.299072    0.542223                    0

[4 rows x 21 columns],)]

Comment: Use pd.concat function
Answer: The problem is that each time you call upload_file, you're actually appending an array (returned by GetData) to an array. So you end up with a new element in the original array and the type of that element is an array itself. Try using data_arr.extend(values) instead of data_arr.append(values).
Example:
foo = ["a", "b"]
bar = ["c", "d"]
print(foo.append(bar))  # ['a', 'b', ['c', 'd']]

baz = ["e", "f"]
qux = ["g", "h"]
print(baz.extend(qux))  # ['e', 'f', 'g', 'h']


The sum of a product of two random variables: how do I know if each summand is independent?

Question: So I have a question that involves using SLLN and almost sure convergence:

I'm given $Y_{1},Y_{2},Y_{3}\ldots$ as iid r.v.'s with a finite mean $k$.
I'm also given this sum
$$
\frac{1}{n}\sum_{i=1}^{n}Y_{i}Y_{i+1}\
\overset{\rm a.s.}{\rightarrow}\ k^{2}
$$
and asked if the SLLN applies here.

My question is:

Is there a  surefire way to tell if each summand $\left(~Y_{1}Y_{2},Y_{2}Y_{3}, \mbox{etc.}~\right)$ is iid with finite mean $?$.
What would be the case for a different sum, say,  $$
\frac{1}{n}\sum_{i = 1}^{n}Y_{2i - 01}\ Y_{2i}\ ?
$$
Comment: Are you happy with a proof that there are counterexamples for which they are not independent, or you want a general proof that they can never be independent (unless they are constant)? (My current answer shows the latter)
Comment: What you sent was perfect!  Intuitively, I guessed that the overlap would cause dependence but I wasn't too sure.  Thank you so much for your help!
Comment: You're welcome!
Comment: I edited my answer to add a full characterization of *when* those things would be independent, in case that's useful. It's quite limited...
Answer: In your case, the summands are not i.i.d. in general (rather, they are identically distributed, but not independent). An easy way to see it is to consider the following: letting $Z_i := Y_i Y_{i+1}$ for every $i$, you have
$$
\mathbb{E}[Z_i Z_{i+1}]
= \mathbb{E}[Y_i Y_{i+1}\cdot Y_{i+1}Y_{i+2}]
= \mathbb{E}[Y_i Y_{i+1}^2Y_{i+2}]
= \mathbb{E}[Y_i] \mathbb{E}[Y_{i+1}^2]\mathbb{E}[Y_{i+2}]
= \mathbb{E}[Y_1]^2\mathbb{E}[Y_1^2]
$$
(using independence for the second-to-last equality, and the i.d. assumption for the last).
On the other hand,
$$
\mathbb{E}[Z_i]\mathbb{E}[Z_{i+1}]
= \mathbb{E}[Y_i Y_{i+1}]\mathbb{E}[Y_{i+1}Y_{i+2}]
= \mathbb{E}[Y_1]^4
$$
so if the expectation is non-zero$^{\dagger}$ the two differ unless $\mathbb{E}[Y_1^2]=\mathbb{E}[Y_1]^2$, i.e., unless $\mathrm{Var}[Y_1]=0$ (that is, unless $Y_1$ is constant a.s.).
For the second case where the summands are $Y_{2i} Y_{2i+1}$, however, you would have independence as the indices of different summands do not overlap.

$(\dagger$) Overall, one can prove the following result (based on this, and the comment below for the case $\mathbb{E}[Y_1]=0$, in which case you apply the same argument to $\mathbb{E}[Z_i^2Z_{i+1}^2]$ and conclude that $|Y_1|$ is constant a.s.):

Theorem. Let $(Y_n)_{1\leq n\leq \infty}$ be a sequence of real-valued i.i.d. random variables, and set $Z_n := Y_{n}Y_{n+1}$ for all $n\geq 1$. Then, the $Z_n$'s are not pairwise independent unless either

$Y_1$ is constant a.s.; or
$Y_1$ is uniformly distributed on $\{-a,a\}$ for some $a>0$.

Conversely, in both cases (1) and (2) the $Z_n$'s are mutually independent.
Comment: Note that if $k=0$, then the argument doesn't allow you to conclude they are dependent. However, you can then apply the same thing to $\mathbb{E}[Z_i^2 Z_{i+1}^2]$ and end up concluding that if the summands are independent, then one must have $Y_1^2$ is constant a.s., which since we have now assumed $\mathbb{E}[Y_1]=$  means that $Y_1$ is uniform on $\{-1,1\}$ for some $a$. That shows that the only non-constant case for which those increment could be independent is when $Y_1,Y_2,\dots$ are scaled Rademacher.
Answer: As mentioned by Clement C, SLLN does not apply directly. However, you can apply it indirectly as follows: whenever $n$ is even,
$$
\frac1n\sum_{i=1}^n Y_iY_{i+1}=\frac12\left(\frac{1}{n/2}\sum_{i=1}^{n/2}Y_{2i-1}Y_{2i}+\frac1{n/2}\sum_{i=1}^{n/2}Y_{2i}Y_{2i+1}\right)
$$
Also as mentioned by Clement C, the variables $Y_{2i-1}Y_{2i}$ are iid, so you can apply SLLN two show that the first sum converges to $E[Y_1Y_2]=k^2$, and same for the second. Therefore, the whole sum converges to $\frac12\left(k^2+k^2\right)=k^2$.
(This technically only proves the limit as $n\to\infty$ through the even integers, but you can deal with odd $n$ with a little more work).


How to declare a pointer with extern in C?

Question: I am writing a C software for a microcontroller, the compiler is Microchip MCC18.
For test purposes, I have written a very simple program as follow:
.c file
#include "x.h"

char *now_clock;

.h file
extern char *now_clock;

With the above code I get a syntax error, but I don't know what is wrong. Any help?
Comment: What error ?? Be more specific please!
Comment: Please include the actual syntax error you are getting. That code appears to be valid C to me, and compiles under GCC.
Comment: Is this an ODR violation? Can you remove the 'char* now_clock' in the .c file?
Comment: The One Definition Rule applies only to C++, not C. And it would not be the problem in this case anyway, because of the "extern" in the header file.
Comment: The error is elsewhere, not with what you posted.  Post the actual error message and teh line of code it references.  You *do* need include guards in teh header file however.
Comment: @Clifford: it is a good idea to have include guards, but as written, there is no problem with including the header many times.  The problems occur when a header includes a `typedef` or `enum` (or, contrary to standard practice, if it includes actual (initialized) variable definitions).
Comment: @Jonathan: ... or a macro definition.  Agreed, if this is the complete header and not a fragment.  I was thinking that if he was getting an error message, and this was only a fragment then lack of guards and some other part of the file may be the cause.
Comment: @Clifford: a compiler doesn't complain about a 'benign' macro definition where the token sequence is the same in both cases.  Clearly, if you include the same file twice, the token sequence for any macros is the same each time - barring extraordinary contortions.  So macros are not harmful either.  But I agree that header guards are a good idea in general - I said as much in my first comment.  We just know that we don't have the complete source of the problem in the material presented in the question.
Answer: The code shown, which doesn't seem to have changed across the edit, compiles correctly for me on MacOS X 10.6.6 with GCC 4.5.2 under stringent warnings - as indeed it should do.
$ cat x.h
extern char *now_clock;
$ cat x.c
#include "x.h"

char *now_clock;
$ gcc -O -std=c99 -Wall -Wextra -pedantic -c x.c
$

The code in x.c shows correct style - it includes the header that declares the variable to cross-check the definition of the variable.  You can also add an initializer to the definition in x.c without problems.
I conclude that you have over-simplified your example and lost the problem in the process.
Comment: Agreed: When I tried it, the only error this "very simple program" yields was a linker error *"unresolved external symbol _main"*, which is hardly surprising.
Answer: You don't declare extern char* now_clock in the .c file which is what you are doing by including x.h in your .c. Remove #include "x.h" and you'll be fine.
Only include x.h in the .c files that want to access the variable.
Comment: Yes, you **do** include x.h in the file x.c so that you get a cross-check that the definition in x.c matches the declaration in x.h.
Comment: I suspect that in older C compilers what Andrew says applies. That is why there used to be a lot of [extern redefinitions](http://www.eng.cam.ac.uk/help/tpl/languages/C/teaching_C/node29.html) in header files
Comment: @renick As it has been a long time since I did standard C this was my assumption still. But as Jonahtahn Leffler has proven, this is no longer needed.
Comment: You are right but I suspect that this PIC Compiler is still lightyears away from GCC 4.5 and C99


How to add metatag module data to the Search API indexes

Question: I am in the process of building a new site that will have some content in the form of videos and PDFs. To make those more searchable I added the metatag module. We are also using the Search API to hook into Solr and do our search operations.
I have found the hooks I need to insert, update, and delete metatag info from the metatag fields. That part is fairly straight forward.
However, I am stuck on the part where I tell the Search API about the fields so that they can be indexed. I think I will be able to figure out how to push the data to the index with the hooks. I just don't know how to tell the Search API that the fields are there and that they contain strings.
I was looking, originally, at the hook_search_api_item_type_info(). However, after reading the description in the API documentation (in the code) I realize that it is only for new entity types. These metatag fields are mainly attached to nodes. And the documentation specifically says that it should not be used for existing entity types (i.e. nodes) because this hook simply tells about the data controller classes.
Should I use hook_search_api_alter_callback_info() to do this? That seems like a good candidate, but I am just not quite following how this works in the SearchAPI.
How do I tell the Search API that the metatag fields exist and I want to be able to index them?
This is in Drupal 7.
Answer: I do it like this:
First
<code>  function HOOK_search_api_alter_callback_info() {
  $callbacks['search_api_alter_add_keywords_field'] = array(
    'name' => t('Keywords field from metatag module'),
    'description' => t("Adds Keyword field from metatag module to indexed data."),
    'class' => 'SearchApiAddKeywordField',
  );
  return $callbacks;
}
</code>
Second
<code>class SearchApiAddKeywordField extends SearchApiAbstractAlterCallback {
  public function alterItems(array &$items) {
  foreach ($items as $id => &$item) {
      if (!isset($item->metatags[$item->language]['keywords']['value'])) {

        $item->search_api_keyword = NULL;
        continue;
      }
      $item->search_api_keyword = strtolower ($item->metatags[$item->language]['keywords']['value']);
    }
  }

  public function propertyInfo() {
    return array(
      'search_api_keyword' => array(
        'label' => t('Keyword field'),
        'description' => t('Add keyword field to index.'),
        'type' => 'text',
      ),
    );
  }

}
</code>

After Clear cache go to you index filters and check: Keywords field from metatag module
If Boost settings need to be changed (to give more importance to the field) do it now.
Index Again
Go to the search results view - the view you created to list indexed content.
Assuming that you have fulltext search filter in "Searched fields" select the new "field" Keyword field
Test the things out.
Answer: The "Meta tag" module has the integration with "Search API" ready to be used for indexing your metadata.
From README.txt

Search API integration
Entity meta tag values can be made searchable using the Search API
  module (https://www.drupal.org/project/search_api).

Select "Meta tags" under "Data alterations" in the filters for the
  index:
    admin/config/search/search_api/index/INDEX NAME/workflow
Meta tag fields will now appear under "Fields" and can be enabled there:
    admin/config/search/search_api/index/INDEX NAME/fields