What does "invalid procedure call" mean in IIS 7 with asp application and how to fix it?

Question: What does "invalid procedure call" mean in IIS 7 with asp application and how to fix it?
Comment: "Classic" asp, not asp.net, right?
Comment: Yep, that's right! ;-)
Answer: Look at this article which explains some possible reasons:
Why do I get 'Invalid procedure call or argument'?

This often happens because you used a
  VBScript "friendly name" constant in
  place of its integer equivalent.
  Visual Basic understands these
  friendly names, such as
  FileSystemObject's 'forAppending' and
  'forWriting' constants.

or

Another possible cause is trying to
  use a string operation (like Mid(),
  InStr(), Left() or Right()) on a NULL
  value.

or

Another possibility is that you are
  coming over from JavaScript, or
  otherwise think that string lengths
  are 0-based.

or

Still one more possibility is that you have unexpected characters in an FSO writeline call.

This Microsoft Support article could also be helpful:
"Invalid Procedure Call" Error Message or Access Violation When You Try to Assign User-Defined Type to Variant

When you assign a user-defined type to
  a Variant in a multithreaded
  environment (for example, in Microsoft
  COM+ or in Microsoft Internet
  Information Server [IIS]), you may
  receive an "Invalid Procedure Call"
  error message or an access violation
  (0xC0000005) in MSVBVM60.dll.


How to display JSON returned (from external REST API) in a Block? [my code attempt inside]

Question: I am trying to display the data from a REST API (URL: 'http://api.kivaws.org/v1/loans/38239/lenders.json') to display in a block. Below is my code. It is not working, any hint on why will be sincerely appreciated.
/**
 * Implements hook_block_info().
 */
function restapiexample_block_info() {
  // This example comes from node.module.
  $blocks['kiva'] = array(
  'info' => t('Kiva Test Block'),
  'cache' => DRUPAL_NO_CACHE
);

return $blocks;
}

/**
 * Implements hook_block_view().
 */
function restapiexample_block_view($delta = '') {
// This example is adapted from node.module.
$block = array();

switch ($delta) {
  case 'kiva':
    $block['subject'] = t('Kiva Example');
    $block['content'] = array(
    '#theme'  =>  'page',
    '#markup' =>  kiva_list_loans(),
  break;
}
return $block;

}
function kiva_list_loans() {
  $request = drupal_http_request('http://api.kivaws.org/v1/loans/38239/lenders.json');
  return drupal_json_decode($request->data);
}

You can try the URL, good JSON data is being returned. Error I receive is several instances of the following text in the $messages area: "Warning: Cannot use a scalar value as an array in drupal_render() (line 5859 of /home/drupalpro/websites/example7.dev/includes/common.inc)"
UPDATE 1:
With help from comments/answer below, I made some progress. from my function "kiva_list_loans()", I am able to see the response in my $page array. I changed the '#theme' in my "$block['content']" in hook_block_view to 'page' - but still I only see the word "Array". How to get this to render?
Comment: You shouldn't need to add "my code attempt inside" to title. That's what we expect to be usual behavior ;)
Comment: Please don't change the meaning of your question. Questions like that are called [chameleon questions](http://meta.stackexchange.com/q/43478/225745) and people really hate them. For example, you have just invalidated my answer. You can expect anybody who sees that to refrain from answering you in future. Consider reverting to older revision, and asking new question instead.
Comment: Sorry i dont see how i am changing the meaning. My challenge was always how to display in a block, I am still not able to do this. I made some progress (with your help, thank you), so i posted the update. I dont think your answer is invalidated, and this comment should show that. Thank you for the help so far.

I am still working on how to display the data in a block but i will mark you answer as the answer, and continue work myself or ask separate question.
Answer: $block['content'] should be an array, like in the example for hook_block_view:
$block['content'] = array(
    '#theme' => 'feed_icon',
    '#url' => 'rss.xml',
    '#title' => t('Syndicate'),
  );

For more examples, see Examples for Developers project, block_example module.
If you are putting array there, it must be a renderable array. If it's not, then either:

Implode it into string. With nested arrays, it can get a bit complicated.
Put it as an element in $block['content'] array, and set $block['content']['#theme'] element to something that can theme it. More complicated, but also more versatile and cleaner solution.
Comment: That's definitely true for best-practice - technically the content is passed through `render()`, so it _can_ be a string. I suspect OP's current problem is that they're returning an array from `kiva_list_loans()`, and not formatting it into a render array, so `render()` throws a wobbly
Comment: @Clive updated. Old problem with "but *I* know what I mean" on my part.
Comment: @Mołot What can I use for '#theme' here? I tried the #1-implode option and the output just is "ArrayArray". (The json output can be seen at this link: http://api.kivaws.org/v1/loans/38239/lenders.json)
Sorry if I am asking for a bit of hand holding here, been stuck on this for entire day.
Comment: @drupalmav well it means your array has 2 sub-arrays and implode can't work on that directly. Imploding nested arrays was discussed on Stack Overflow already. For a `'#theme'`, pretty good example is in examples project I linked. You would need to write own theming function, but that's not so scary. Try and feel free to ask about details when you will have something (probably copied from examples and only modified to your needs ;) ).


Multiple Transactions in Hyperledger Composer

Question: I need to make multiple transactions, fast
 I'm developing a  Node.JS  application on Hyperledger Composer. I'm sending an insane amount of transactions per second (11,500) but it's fairly slow. I'm using the code from the Hyperledger Composer Tutorial and some examples from the web, but it seems to be that I can't make it any faster.
My model is fairly simple, it's the following:
participant Client identified by id {
  o String id
}

asset Wallet identified by id {
  o String id
  o Double balance
  --> Client owner
}

My script.js is the following
function transferFunds(transfer){
    //Transfer the funds
    transfer.from.balance -= transfer.amount;
    transfer.to.balance += transfer.amount;

    return getAssetRegistry('org.acme.Wallet')
    .then(function(assetRegistry){
        //persist the state of the Wallet
        assetRegistry.update(transfer.from);
        assetRegistry.update(transfer.to);
    });
     }

And I'm supposed to be transferring money between them, so my Node.js code to interact has the following logic:

Connect to Hyperledger Fabric
Get the Network Definition
Load the wallet that is transferring money
Load the wallet that is receiving money
Make the transfer
Execute the transaction

I feel my code is  badly done , it's fairly slow and it will usually overwhelm my Hyperledger Fabric instance. This is the NodeJS Code:
const makeTransaction = (fromID, toID, funds) => {
    let walletRegistry;
    let from;
    let to;

    businessNetworkConnection.connect(connectionProfile, businessNetworkIdentifier, participantId, participantPwd)
        .then((result) => {
            businessNetworkDefinition = result;
            return businessNetworkConnection.getAssetRegistry('org.acme.Wallet')
                .then(function (vr) {
                    walletRegistry = vr;
                    return walletRegistry.get(fromID);
                })
                .then(function (v) {
                    from = v;
                    return walletRegistry.get(toID);
                })
                .then(function (v) {
                    to = v;
                })
                .then(function () {
                    let serializer = businessNetworkDefinition.getSerializer();
                    let resource = serializer.fromJSON({
                        "$class": "org.acme.Transfer",
                        "amount": funds,
                        "from": {
                            "$class": "org.acme.Wallet",
                            "id": from.getIdentifier(),
                            "balance": from.balance,
                            "owner": "resource:org.acme.Client#" + from.owner.getIdentifier()
                        },
                        "to": {
                            "$class": "org.acme.Wallet",
                            "id": to.getIdentifier(),
                            "balance": to.balance,
                            "owner": "resource:org.acme.Client#" + to.owner.getIdentifier()
                        }
                    });
                    return businessNetworkConnection.submitTransaction(resource);
                });
        }).then((result) => {
            console.log(chalk.blue(' ------ All done! ------'));
            console.log('\n');
            return businessNetworkConnection.disconnect();
        }).catch(function (error) {
            businessNetworkConnection.disconnect();
            throw error;
        });
}

So basically, I'd like to know:

How could I improve it to allow multiple transactions without connecting multiple times?
Could my model be optimized to reduce the transaction size or to not have to preload both wallets?

Thank you so much!
Answer: I didn't see what was modeled for your transfer transaction.
assetRegistry.update() is done twice, perhaps an updateAll API call could be used ? -> https://hyperledger.github.io/composer/jsdoc/module-composer-client.AssetRegistry.html might help.
I can understand why your Node.js app would connect to the business network and interact ; but why wouldn't you just create your JSON transactions independently and just use REST to submit your transactions ? Eg using Node-Red https://hyperledger.github.io/composer/integrating/node-red.html to integrate / load your JSON from a file of transactions (if that's what you want to do, to transfer from and to wallets).  So to install Node Red use npm install node-red -g then launch it node-red and choose (from the palette) the Node red node 'node-red-contrib-fs' under the Install tab (reads files from a directory on the file system). In the 'file pattern' use the pattern string *.json .
in answer to q2. Yes your model could be better modeled. This might be of use -> When to call getAssetRegistry to update assets (and the participants equivalent)


Reducing Number of Fields in Content Type

Question: Context:
I have a product content type on Drupal 7 with >100 fields, and there are >7000 products, all with several revisions. Our client keeps requesting that we add and remove fields, which is quite painful and takes several tries to successfully complete due to mysql having a conniption.
The go-to strategy has been to increase the RAM on the server, but we are hitting a cost wall and this bothers me as a developer since we are just deferring dealing with the problem.
Comedy Option:
The majority of these fields are specifications which are never related, filtered or displayed outside of the detail view. Could I reasonably create a JSON product_spec field that contains all of these spec fields and write custom modules to display them on the detail/spec screens, allow editing through the API, and allow editing them on the admin interface?
Is there an existing module that does something similar? Would entitycache be a much more practical option?
Comment: Possible duplicate of http://drupal.stackexchange.com/questions/121297 - or at least the answers may be relevant. Specifically Clive's answer.
Comment: That is an excellent link, and points out the Examples module which I was not aware of. I do like the idea of a custom field, which would solve many of my performance issues. It still has the problem that when the client inevitably decides to add or remove a spec I'll have to do some update schema stuff, which I'm hoping to avoid.
Comment: What do you mean MySQL having a conniption? We need a more precise error message or symptoms or something.
Comment: @chx I really wish I knew why it was having a conniption :) I enabled the slow query log and it showed a bunch of very complicated very slow queries (mostly involving the cache)
I believe mysql was having trouble with locks and updating tables, meaning fatty queries were blocking other fatty queries until it timed out. The fix was to delete old revisions (10,000 revisions, ~1.5 million rows gone)
Answer: This is really interesting and, whereas the suggestions in the other question are really good as pointed out by the comment above, I don't really think it's practical to give up on the Field UI for this (like mentioned in the other question).
Let me explain:

Creating a custom field is really easy, there's a good example in Panopoly Widgets for the dashboard widget, which has a custom field for the Spotlight widget.
Creating a custom entity isn't so bad either but creating every single field using Form API should be out of the question

The only plausible solution that I can think of would be to implement hook_field_storage_info() and create a new Field API storage backend that uses a better table configuration.
If you look at field_sql_storage.module in core, it's a pretty concise module that provides the one field per table storage backend, I'm sure with some hacking around you could create a new backend that uses one table per entity and stores each field in a new column there (kinda like D6 CCK with cardinality 1 fields).
You would have to be constantly altering the table schema whenever new fields are added (which should be fine). This might be the place to do it: hook_field_storage_create_field().
It's pretty theoretical but I think it'll work... the beauty of this approach is that you can still use Field UI for everything as usual.
Caveat: You're gonna have to figure out how to handle complex fields or multiple cardinality (hint: more columns?)
PS - Knowing of the frequent schema changes, you wanna make sure you have backups/concurrency for peace of mind.
Good luck and if you get this working I'd like to see it! :)
Comment: https://www.drupal.org/project/pbs is a proof of concept for one table per bundle. Noone picked it up. Perhaps it's not as easy as you think nor is it desirable, I think.
Comment: I never said it was easy! Just there looks like there's a lot of stuff to explore... nice module, wasn't aware of it.  And I definitely don't think its desirable either, that's the OPs problem :)
Answer: Why not solve it with custom fields, grouping similar fields into one compound custom field and trying to keep a sane data model (ex: not 'all the things in one field').  There are many tutorials on how to create custom fields and it's quite easy.
Comment: Yes, this is the sane and practical option. I'm just seeing what is out there.
Answer: I would give the Dynamic Properties module a try.


Faster way to generate multiple adjacency matrix

Question: Suppose I have a arbitrary probability matrix P like below,
P = matrix(c(0.3,0.2,0.2,0.2,0.3,0.2,0.2,0.2,0.3),3,3)
P
      [,1] [,2] [,3]
[1,]  0.3  0.2  0.2
[2,]  0.2  0.3  0.2
[3,]  0.2  0.2  0.3

For single adjacency matrix, it is generated like (unweighted, no self-loof)
tem = matrix(runif(3^2), nrow = 3)
tmpG = 1 * (tmpmat < P)
tmpG[lower.tri(tmpG)] <- 0
tmpG <- t(tmpG) + tmpG - diag(diag(tmpG))

However, what if I need to generate 100 adjacency matrix, so I write down the following code
G = list()
for (i in 1:rep) {
  tmpmat = matrix(runif(n^2), nrow = n)
  tmpG = 1 * (tmpmat < P)
  tmpG[lower.tri(tmpG)] <- 0
  tmpG <- t(tmpG) + tmpG - diag(diag(tmpG))
  if (noloop) {
    diag(tmpG) = 0
  }
  G[[i]] = tmpG
}

In my case, the n >10000 and T = 1000, so it is extremely slow, any better idea to improve this?
Comment: The code as written (plus lines for noloop=FALSE, rep <- 100, and n<-3) runs almost instantly on my machine. Are your matrices larger than 3x3 in real life? Using `replicate` will be your friend here to avoid the [Second Circle of the R Inferno](https://www.burns-stat.com/pages/Tutor/R_inferno.pdf)
Comment: In my case, the n > 10000, T = 1000. thanks
Comment: Little typo in your example, you have `tem` where I think you mean `tmpmat`? Also, can you please clarify, when you say `n > 10000`, is that the dimension that you are currently using `3`? And when you say `T = 1000`, is that the number of replications, where you are currently using (the undefined) `rep`?
Comment: Dubukay is right that `replicate(rep, {<<code>>})` will be faster, but by the time your matrices get big it probably won't matter. I don't think you'll get much speed without improving your algorithm. Maybe you could work on only operating the upper triangle?
Answer: I think we can do a bit better by only working with a vector of the length needed, and putting it into a matrix at the very end. I haven't checked this very carefully, and your code has no comments for me to compare intention to, so do make sure this is right before trusting it.
p_vec = P[upper.tri(P, diag = !noloop)]
nn = length(p_vec)

tmpG_vec = runif(nn) < p_vec
tmpG = matrix(0, n, n)
tmpG[upper.tri(tmpG, diag = !noloop)] = tmpG_vec
tmpG[lower.tri(tmpG, diag = !noloop)] = tmpG_vec
tmpG

We can then wrap that in replicate for the iteration.
Benchmarking on more dimensions/higher reps, we get about a 25% speedup, but it's still pretty slow (I aborted a benchmark of n = 5000 because I got tired of waiting). You can probably get quite a bit of speed by running in parallel - say an almost 8x speedup if you have 8 cores. See, e.g., this question, though there may be more modern ways to do it.
rep = 5L
n = 2000
noloop = TRUE

P = matrix(runif(n^2), n)
P = P %*% t(P)
P = P / colSums(P)

p_vec = P[upper.tri(P, diag = !noloop)]
nn = length(p_vec)

microbenchmark::microbenchmark(
  loop = {
    G = list()
    for (i in 1:rep) {
      tmpmat = matrix(runif(n^2), nrow = n)
      tmpG = 1 * (tmpmat < P)
      tmpG[lower.tri(tmpG)] <- 0
      tmpG <- t(tmpG) + tmpG - diag(diag(tmpG))
      if (noloop) {
        diag(tmpG) = 0
      }
      G[[i]] = tmpG
    }
  },
  diagonal = replicate(rep, {
    tmpG_vec = runif(nn) < p_vec
    tmpG = matrix(0, n, n)
    tmpG[upper.tri(tmpG, diag = !noloop)] = tmpG_vec
    tmpG[lower.tri(tmpG, diag = !noloop)] = tmpG_vec
    tmpG
  }),
  times = 5L
)

# Unit: seconds
#      expr      min       lq     mean   median       uq      max neval
#      loop 1.525028 1.614544 2.136637 2.148771 2.387423 3.007417     5
#  diagonal 1.312022 1.360457 1.592914 1.444902 1.602536 2.244652     5


Must have Windows Systems Client-side tools and settings

Question: What tools do you install on Windows systems on a regular basis - the 'can't live without' tools?
(Edit : I mean to focus on more client tools for usage rather than sysadmin tools - as pointed out Tools a Windows administrator cannot live without does a good job of that)
Answer: might want to check out
Tools a Windows administrator cannot live without
but to summarise; SysInternals, WinDirStat and Powershell
Answer: I really like having a copy of UnxUtils handy.
For those of us most comfortable with tools like gawk, sed, grep, tail, less, etc having native ports (read: not dependent on cygwin) of these is a life savor.
I know you can get a lot of the same functionality from PowerShell, but when you've been doing something one way for 10+ years, familiar is just easier.
You can easily copy a needed .exe to a server w/o installing anything.
Comment: UnxUtils is new to me, I usually just use Cygwin. Neat!
Answer: here a non exhaustive list of the tools i keep on my usb stick for windows work:

truecrypt
Password Generator
AccessEnum
ADexplorer
ADinsight
Autologon
blat
changepw
chwinpw
Cover your tracks
diskmon
Fpipe
LogonSessions.exe
LSASecretDump
NetSpeed
newsid
ntfsinfo
ofl
portmon
Sysinternals suite
putty
user2sid
sid2user
Wireshark
cdrtools
stunnel
killbox
tcpxd
tftpd

Some of them are probably outdated now, hope this helps anyway.
Answer: Most of this has been covered with other questions here but:
-Windows server 2003 resource kit tools and management tools
-viruscanning
-enable remote administration
Beyond that I don't put anything else on unless needed by the apps being "served".
Answer: None. Though I do have a large number of tools and utilities that I keep in a directory, mapping to it and using them when needed.
By doing this, you don't have to reinstall them on all your servers, then be sad when you have to work on some server where the tools have not yet been installed.
Answer: If I read your question correctly, I think you are asking about which tools you should include in your client image (or install on all client boxes).
I've found many tools over the years and mainly keep them all on a server for when I need them.
However, I almost always include the i386 directory off of the WinXP/Vista installation media.  I usually put it in the root of the client machine - very useful when you have to install/remove a windows component and don't have the original media.
Sure you could put it on the network - but sometimes the problem is no network!
Comment: Great idea! I've done this in the past but never on all machines.
Answer:
UNIX subsystem aka Interix (Services for UNIX 3.5 or Subsystem for Unix Application + Utilities)

pkg bootsrapper from Interopsystems SUA community
OpenSSH (includes OpenSSL)
curl (unix version)
md5
zip/unzip
whois

PowerShell
info-zip (zip.exe, unzip.exe)
curl with ssl
ncftp
7-zip
MagicISO
inSSIDer
Network Monitor
On Vista:

Windows telnet client
PuTTYtel
Answer: The "basic" pack:

List item
Firefox (web browser)
Filezilla (ftp client)
OpenOffice.org
VLC
Concept Draw Office ( visio & Project like)

On Windows computers, I add:

notepad++ (text editor)
PDF Creator
Winrar (or winace, or other)
and WinMine of course ;-)

On Mac computers:

Flip4Mac (codecs)
Microsoft Remote Desktop client
TextWrangler (text editor)
Comment: I like the "List item" tool *g*
Answer: I usually install the following on a new (Windows) workstation:

Firefox
Open Command Window Here (from MS Powertoys for Windows collection)
GnuWin32 (*ix command line tools for windows)
WinZip
Pidgin (IM Client)
Putty (ssh Client)

On a Ubuntu Linux box I install:

OpenSSL
Samba (Windows file sharing)
NFS
Various Nautilus scripts

I also install the following if I'll be doing "work" on the machine:

VirtualBox (Virtualization Server)
Java SDK
Eclipse
Tortoise (Subversion Client)
Maven
ANT
Answer: All the PS utilities from Sysinternals...and many of the other ones as well.
http://live.sysinternals.com/Tools/
If you are using PowerShell, you can use this function to download all the Sysinternal programs from a PowerShell prompt. I did not write this. I would supply the original link, but I can't find it.
Change the path in line 3 (counting blanks) to specify the folder to copy the programs to.
<code>Function Get-SysInternals {

   param ( $sysIntDir="d:\console\" )

   if( !$sysIntDir.endsWith("\")) { $sysIntDir+="\" }
   $log = join-path $sysIntDir "changes.log"
   add-content -force $log -value "`n`n[$(get-date)]SysInternals sync has started"

      dir \\live.sysinternals.com\tools -recurse | foreach {

         $fileName = $_.name
         $localFile = join-path $sysIntDir $_.name
         $exist = test-path $localFile

         $msgNew = "new utility found: $fileName , downloading..."
         $msgUpdate = "file : $fileName  is newer, updating..."
         $msgNoChange = "nothing changed for: $fileName"

         if($exist){

            if($_.lastWriteTime -gt (get-item $localFile).lastWriteTime){
               copy-item $_.fullname $sysIntDir -force
               write-host $msgUpdate -fore yellow
               add-content -force $log -value $msgUpdate
            } else {
               add-content $log -force -value $msgNoChange
               write-host $msgNoChange
            }

          } else {

               if($_.extension -eq ".exe") {
                  write-host $msgNew -fore green
                  add-content -force $log -value $msgNew
               }

               copy-item $_.fullname $sysIntDir -force
         }
   }
}
</code>
Comment: Very cool! Love the script.
Answer: My base client install has Firefox, Adobe Acrobat Reader, 7-Zip, Java Runtime, and putty.


Show that $u^2$ satisfies $\partial_t(u^2) = 2k[\partial_x(u\partial_xu) - (\partial_x u)^2]$

Question: Suppose that $u$ satisfies the heat equation $\partial_tu = k\partial_x^2u$. Show that $u^2$ satisfies $\partial_t(u^2) = 2k[\partial_x(u\partial_xu) - (\partial_x u)^2]$.
How do I solve this exercise? I think I just need to substitute $u^2$ into the heat equation, but I don't get to the answer I want.
I get $\partial_tu^2 = k\partial_x u^2$ and I don't know how to proceed from here..
Answer: You are correct in saying you just have to substitute in.
Starting with the left hand side
$\partial_t(u^2)$ = $2u\partial_t(u)$
$2u\partial_t(u)$ = $2ku\partial_x^2u$ = LHS (using the chain rule)
Then on the right we have
$2k[\partial_x(u\partial_xu) - (\partial_x u)^2]$
=$2k[\partial_xu\partial_xu + u\partial_x^2u - (\partial_x u)^2]$ (using the product rule)
=$2k[u\partial_x^2u]$ = RHS
Therefore LHS = RHS so $u^2$ satisfies the equation


What are probabilistic approaches to finding the right number of clusters?

Question: As per answers to this question, there are shortcomings in the heuristics of deciding on the number of clusters.
A more robust approach could be probability based clustering: from a probabilistic perspective, the goal of clustering is to find the most likely set of clusters given the data. Thus, we can never be "100% sure" that training instances should be placed into some cluster: they just have a certain probability of belonging to it.
I wonder how if this reasoning is correct and how it would work in practice.
Comment: @andreister wasn't my answer to that question also the answer to this question?
Answer: There are methods to do that. A good starting point is
Rasmussen, C. E. (2000). The Infinite Gaussian Mixture Model. In S. A. Solla, T. K. Leen, & K.-R. Müller (Eds.), Advances in Neural Information Processing Systems 12 (Vol. 12, pp. 554-560). MIT Press.
The idea is to put a Dirichlet prior on the mixture weights of a mixture of Gaussians and take the limit of infinitely many components. Since you always have have finitely many data points, it doesn't matter that you potentially have infinitely many mixtures but it allows the model to choose new clusters if it needs to.
There is a lot more work on that. A good starting point would be the publications of  Yee Whye Teh.
Answer: The first question you should then answer is:
What is a cluster?
Most of the time, a cluster is whatever the clustering algorithm finds. Which by definition then is correct.
If you run e.g. k-means, it does a good job in finding the optimal $k$ cell voronoi partitioning of the dataset. So if you are referring to k-means, the question is: what are the chances that the data set is based on $k$ Voronoi cells?


Alterar Ip ao fazer um solicitação Curl em php

Question: Olá, tudo certo?
Tenho uma função que ela recebe um termo de busca, vai google e retorna um ponto específico da página nesse termo de busca.
Tudo funcionando bonitinho, exceto pelo fato que em um determinado momento o google reconhece com atividade anormal e não permite mais o acesso.
Fazendo um pesquisa vi que é possível utilizar o curlopt_proxy para alterar o ip de consulta, forjando um tcp. Porém ao incluir o curlopt_proxy em meu código o retorno é totalmente em branco. Não sei o que houve.
    $Ch = curl_init();
    $timeout = 0;
    curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/search?client=safari&rls=x64&q='.$Busca.'&Num=1');
    curl_setopt($ch, CURLOPT_PROXYTYPE, 7);
    curl_setopt($ch, CURLOPT_PROXY, '22.214.171.124:80');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $conteudo = curl_exec ($ch);
    curl_close($ch);

Answer: O CURLOPT_PROXY define o IP do proxy que quer utilizar. O proxy pode ser http (padrão), socks4 ou socks5.
Isto é indicado na documentação: https://curl.se/libcurl/c/CURLOPT_PROXY.html.

Você não pode definir qualquer IP arbitrariamente, afinal, você quer também obter a resposta. Tecnicamente, é possível forjar IPs no TCP, mas você não conseguirá obter qualquer resultado. Seja como for, o  CURLOPT_PROXY não tem esse intuito, o CURLOPT_PROXY não forja/altera os pacotes TCP para outro IP arbitrário.
O CURLOPT_PROXY estabelece uma conexão com um servidor proxy, ele irá reencaminhar sua requisição. No final, o servidor final (o Google) verá o IP do proxy (e não verá o seu IP real).

Você deve adquirir proxies (pesquise no Google por "buy proxies"). Existem diversos tipos de proxies diferentes, deverá achar um que melhor sirva para o seu caso de uso. Alternativamente, você pode criar o seu próprio proxy, desde que possua diversos IPs... Basta configurar um servidor de proxy (como Squid Proxy Server) e então ele alternará entre os IPs que você possui. Mas, novamente, você precisa adquirir os IPs, e esses IPs serão os que o Google verá. A diferença é que, você pode ter um único servidor, e vários IPs de saida.
Você também pode tentar utilizar proxies gratuitos (pesquise por "free proxies") e terá algo como o http://www.freeproxylists.net. Ou, também pode optar por utilizar o Tor ou I2P.
Para testar, pode fazer uma requisição para o https://api.myip.com (ao invés do google) para ver o seu IP. Se a requisição via curl tiver um IP diferente do seu dispositivo, então é porque o proxy está configurado corretamente.
Obviamente, proxies públicos (e gratuitos) são utilizados por qualquer pessoa e pode não resolver o seu problema. Afinal, outras pessoas estão utilizando eles para fazer requisições ao Google.

Uma vez que tiver o IP do proxy que deseja utilizar especifique-o no CURLOPT_PROXY. Além disso, remova o CURLOPT_PROXYTYPE, ou defina ele adequadamente.
Para ver qual o erro está ocorrendo com sua requisição, adicione um echo curl_error($ch).


Drawbacks of extending Magento guest session maxlifetime?

Question: We are interested in extending the session duration for guests that visit our Magento website. By default if a guest adds an item to the cart and leaves the page afer 24 minutes the session is destroyed and when they return the cart is zeroed. I extended the maxlifetime via htaccess to 6 hours to test it out and it works correctly. I know my manager is interested in keeping sessions alive for 1 week or even longer. My question is: what are the potential drawbacks of keeping sessions alive this long? Server performance, server space for session files, security concerns, etc?
Answer: Unless you have explicit PCI compliance directives to only retain session data for a specific window - there isn't any real security concerns. The session data doesn't hold any sensitive information.
By extending the window, the only concerns I can think about would be.

You are giving a longer/greater chance for the session/customer to be vulnerable to an XSS attack on the existing session (not that this wouldn't perhaps otherwise be the case anyway).
You run the risk of the session directory becoming excessively large - causing any session clean-up cron's to have to iterate through an increased number of files.
If you are storing anything else in the session that you shouldn't be doing (ie. that makes it larger than the default 4kb); then you'll be rapidly consuming disk space.
If you are using memory storage for sessions (Memcache/Redis) - then you'll eventually run out of available space and auto-truncate older sessions. So you'll have to commit a fairly large amount of RAM purely for legacy/archived session storage.
If you are using DB storage for the sessions - then you'll end up in a bad way. Magento's DB based session storage is horrendous and falls over at the slightest hint of use - avoid
A potential security concern could perhaps be if the customer's machine is a shared computer. At least with a 24 minute (or otherwise) session volatility, chances are the session would have expired before another user can take advantage of it.

But there is a better solution
Rather than just extend session time on site, have you perhaps thought of investigating a more sophisticated solution, whereby if the cart has been abandoned, you can alert the customer of such via email and give them a link to re-instate the cart contents/wishlist/session etc.
This would obviously give you the underlying solution and the advantage that you could pro-actively convert the customer - and all it would require is capture of an email address.
Comment: Ah understood. An interesting challenge if you don't want to interrupt the users on-site experience; and the older market is unlikely going to benefit from 1-Click auth via Twitter/FB/Google. Out of interest, does this site cater to the EU - as you might fall victim to the infamous cookie law; and they'll almost definitely be some particulars in there about session expiry (jeopardising your project even further).
Comment: Thank you for the detailed write up. We are working on our abandoned cart re-marketing but it doesnt address people who dont have an account with us. We get a lot of people that come first time from a PPC ad or something, add a few items into their cart, and leave the website. Sometimes they call back later in the day saying they went to complete their order and the cart was empty. We cater to an older demographic so we are trying to keep it as painless as possible.
Comment: US based with no international dealings so will be ok for now.


Sorting of pfquery with multiple conditions for iOS7

Question: i am trying to sort a pfquery with multiple conditions, the code below sorts only one column. please help.
<code>- (PFQuery *)queryForTable
{
    PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
    [query whereKey:@"mStatus" equalTo:@"running"];
    [query orderByAscending:@"mName"];
    [query orderByAscending:@"mOrder"];
    return query;
}
</code>
Answer: <code>- (PFQuery *)queryForTable {
    PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
    [query whereKey:@"mStatus" equalTo:@"running"];
    [query orderByAscending:@"mName"];
    [query addAscendingOrder:@"mOrder"];
    return query;
}
</code>
Comment: will the above code have order of sorting ? like mName will be on first priority and order will be on second priority?
Comment: yes i already found that. thanks a lot. your answer saved me :)


Distinguishing between the square roots of a quadratic residue

Question: For a prime $p$, given $g$, $x = g^{2r}\pmod p$, and $y$ such that $y^2 \equiv x \pmod p$, is it possible to determine if $y \equiv g^r \pmod p$ without calculating the discrete logarithm? Comparing numbers by size doesn't seem to help.
For example, with $p = 107$, $g = 2$, and $x = 2^{92} \equiv 33 \pmod {107}$, the square roots are $56$ and $51 \mod p$. Is there a way to determine that $56 \equiv 2^{46}$ just from the values of $p,g,x$ without computing/knowing r?
EDIT: Could this be possible if r is restricted to some range? like $0\leq r < \frac p2$ or $\frac p2 \leq r < p$? Thanks!
Answer: (I'm assuming $p$ is odd)
No; the answer to your question depends crucially on what you have chosen for $r$.
In your example you took $r = 46$ so that $y=56$ was the right answer, but you could just as easily have taken $r = 99$ instead, which would make $y=51$ the right answer. You could also have chosen $r=152$, but that gives the same result as $r=46$.
If you want to do something like restrict $r$ to the range $0 < r < \frac{p}{2}$, I strongly disbelieve there is a general way to distinguish which of the two square you're asking for without basically computing $r$.
Comment: Just confirming, if I restrict $r$, you _disbelieve_ there is a general way?
Answer: If $y^2 \equiv (g^r)^2 \pmod p$ then $y \equiv \pm g^r \pmod p$, because $\Bbb Z/p\Bbb Z$ is a field.
Comment: (-1) although this is true, it doesn't really answer the question and should be a comment. There isn't even a clear evidence that the OP wasn't aware of that.
Answer: No. Suppose that you can find "true" (with respect to $g$) square root in $T(p)$ time (denote "true" square root of $x$ as $f_g (x)$). Then you can find discrete logarithm (for simplicity, let it take values $1, 2, \ldots, p - 1$ instead of usual choice $0, 1, \ldots, p - 2$) of any non-zero remainder modulo $p$ in $O(T(p) \mathrm{poly}(\log p))$ time:
$\log_g x = \begin{cases} 1 &\mbox{ if $x = g$ } \\ 2 \log_g f_g(x) &\mbox{ if $x$ is a quadratic residue}  \\
2 \log_g f_g(gx) - 1 &\mbox{ if $x$ is a quadratic non-residue and is not equal to $g$} \end{cases}$.
Notice that $\log_g f_g (x) = \dfrac{\log_g x}{2}$ and $\log_g f_g(gx) = \dfrac{\log_g x + 1}{2}$, so computation of $\log_g x$ using this recursive formula halts in $O(\log p)$ iterations. Also, making each recursive call takes
$O(\mathrm{poly}(\log p))$ time.
(Checking whether number is quadratic residue or not can be easily done in $O(\mathrm{poly}(\log p))$ time, for example one may calculate $x^{(p-1)/2} \!\!\! \mod \! p$ and check whether it is $1$ or $-1$).


Normal Distribution - Implications of negative values

Question: Consider a task, whereby we need to generate a normally distributed data set of 100 numbers. "tableFreq" is being used to hold the "frequency" data. The sum of the frequencies needs to be approx 10000.
Refer to the first image which shows a preview of "tableFreq" (14 out of 100 rows):

"fkey" column represents the foreign keys that should eventually be inserted in another table, call it "tableX". There are 100 rows, and the range of "fkey" is 1-100.
The frequency represents the number of times these keys should appear in the said table: "tableX". This is what should be normally distributed.

Example (refer to image): if for fkey 1, we got 90 in "tableFreq", "tableX" should have foreign key 1 in it's first 90 rows, if for fkey 2, we got 59 in "tableFreq", "tableX" should have foreign key 2 in the next 59 rows, and so on.

As already mentioned, the sum of the frequencies of the foreign keys, needs to be approx 10000, as in "tableX" we eventually need to have approx 10000 rows. PostgreSQL is being used to generate the data (if it makes any difference).
To generate "tableFreq" we are using something along these lines:
select row_number() OVER () as fkey, (floor((normal_rand)*1.9)) as frq from normal_rand(100, 50, 28.6)

normal_rand (an internal PostgreSQL function) creates 100 (supposedly) normally distributed values, with 50 as mean, and 28.6 standard deviation. We are multiplying the value retrieved from normal_rand by 1.9 to approximate towards 10000 (i.e. if SUM(floor((normal_rand)*1.9)) is replaced into the query, its value would be ≈ 10000). The mean and standard deviation are calculated from the fact that we are generating 100 numbers (mean/std of range 1-100). The problem is that "frq" is sometimes negative (this is rare, < 10%, but still > 0% every time).
We would not be able to insert, say -18 rows (refer to image above) in "tableX". So we modified the query to make sure it always returns positive values
select row_number() OVER () as fkey, (floor((normal_rand)*1.9)) as frq from normal_rand(110, 50, 28.6) where (floor(normal_rand)) > 0 LIMIT 100

In essence, generating 10 more values by the normal_rand function, restricting to > 0 values, and limiting to 100 so we stick to the range(1,100) restriction.
The final query creates approx 10k rows in "tableX" with the frequencies in "tableTemp" and as described in the Example above.
At the end we are trying to use Python/Matplotlib "hist" to prove that the foreign keys in "tableX" follow a normal distribution. The x-axis represents the foreign keys and the y-axis represents the frequencies. This does not look like a normal distribution.

Is it because of the restriction of the negative numbers (> 0)? Could generating 10 more values and then restricting to 100 be affecting in such a way? How would the negatives be handled in such a case? Or is the approach inherently wrong?
Update -
If we plot the frequencies generated by the normal_rand function as a histogram, the distribution looks "normal". However, the assignment question requires Step 2 i.e. inserting the "foreign keys" into "tableX" according to the frequencies generated in step 1. This is the misleading part.

Update with original question -
Create another two tables (e.g. tableA and tableX in the same schema). Note that table tableA is related to table tableX with a 1(p) - N(t) relationship. tableX is to have about 10k tuples. Whilst tableA has at first 1k, then 100k, and then 10m (if it does not take too much on your install). As for the foreign key distinct values, please set at 100, 2k and 7k respectively. Generate tableA and tableX for the various sizes mentioned. As for distribution, make use of the uniform, normal (average being the mid tuple by sort order of PK) and a distribution of your invention
Comment: "whereby we need to generate a normally distributed data set for a range of numbers, e.g. 1-100" - this is impossible. The normal distribution generates data over the whole real range by definition. If you don't allow that, for example because you have a constrained value range, the data cannot be normally distributed. If you want approximate normality, you need to choose a small variance so that the probability that data leave the value range is very small.
Comment: Other than that, your description is very hard to follow. You talk about "the frequency data" as if it were clear what that is, but it isn't. How can this be negative? This is not what you mean when you say you want to generate normally distributed data, or is it? I also don't get the "multiply by 1.9" bit. If you want to be between 1 and 100, why multiply by 1.9?
Comment: but then in that way, you cannot expect to see a bell curve..
Comment: Hi @ChristianHennig, thank you for your replying. Apologies, it is a bit complicated to explain and the sentence you quoted is indeed misleading. I will fix it. The range 1-100 is a range of FKs; refer to the first column of the first image. The frequency of FKs should be normally distributed and not the FK range; refer to the second column of the first image.  You can see the frequencies are not bound within the 1-100 range but there are indeed negative values: the negative values are mainly what I am asking about.
Comment: Case in point, the first step is to generate 100 numbers that are normally distributed. The sum of which needs to be approx 10,000 (hence the multiplication by 1.9, based on the chosen mean & standard deviation). The second step is to create rows within "tableX" with the frequencies obtained in step 1, i.e. foreign key 1 with the frequency obtained for 1 in step 1, foreign key 2 with the frequency obtained for 2 in step 2, etc. I hope this is clearer. Thanks again!
Comment: Hi @JurgenCuschieri, what are you even plotting in your histogram? I find the x-axis weird... Shouldn't it be the values (i.e. number of rows) and y-axis their frequencies?
Comment: In addition, what you are doing is essentially sampling 100 RVs from a N(95, 54^2), which means the std is pretty high and you only have 100 samples, so the sampled values are likely to appear more "flat" when you plot it as opposed to a normal distribution with a high peak (low variance).
Comment: @JurgenCuschieri If you choose the standard deviation of your normal small enough, chances are you won't see negative numbers.
Comment: @Tom the x-axis represents foreign keys 1-100. The y-axis represents the frequency of each foreign key.
Comment: Hi @Tom, kindly see an edit with an update. You are right in that when we try to plot the end-result, i.e. the foreign keys on the x-axis and frequencies of the foreign keys on the y-axis, the distribution does not look normal, whereas, when we plot the frequencies as generated by the normal_rand function on the x-axis and their counts on the y-axis, the distribution does look normal. The assignment asks of us to insert the rows into "tableX" based on the frequency generated in the first step and indicates that a normal distribution can be proved from the end result. Is this possible at all?
Comment: Yes: forget about the Normal distribution, because it's irrelevant.  Use the *actual frequencies* you have observed.  That's what the question seems to ask for, anyway.  It would help for you to quote the question exactly, because it sounds like your problem might arise from misinterpreting it.
Comment: Create another two tables (e.g. tableA and tableX in the same schema). Note that table tableA is related to table tableX with a 1(p) - N(t) relationship. tableX is to have about 10k tuples. Whilst tableA has at first 1k, then 100k, and then 10m (if it does not take too much on your install). As for the foreign key distinct values, please set at 100, 2k and 7k respectively.
Generate tableA and tableX for the various sizes mentioned. As for distribution, make use of the uniform, normal (average
being the mid tuple by sort order of PK) and a distribution of your invention
Comment: @whuber I hadn't added the question because I believed it would mislead further - in my opinion, it is very unclear, to say the least. We setup a session with the lecturer to try to make sense of it further; and in my initial question I tried to explain what was said in that session.
Answer: You are using invalid distribution to model this data. Normal distribution is continuous and ranges over the whole real line. Your data is discrete and bounded. So this is "by design".
To simulate from a discrete, bounded distribution you should use instead Poisson, binomial, negative binomial, or one of the many other distributions.
As an additional note, you are assuming here that all the rows in your table act independently of each other, this assumption may or may not be correct. With this assumption you have no way of ensuring the constraint that the numbers would sum to some constant. If you need the constraint, you might want to use a multivariate distribution that ensures it, like multinomial, or more complicated probabilistic model for simulation.
If for technical reasons you are limited to using normal distribution, than it's a "take it or leave it" scenario. You would see negative numbers in the results. You could be hacking the results by doing things like replacing the "invalid" values with something else (e.g. negative values with zeros), but then the samples would not be resembling the normal distribution anymore and your results become arbitrary.
Comment: Hi @Tim, thank you for your answer. Regarding using an invalid distribution model; this was not a choice but a requirement based on the assignment question. Regarding negative numbers, playing around with the mean and standard deviation we could get "frequency" values which are > 0 in almost all cases (e.g. mean 60, std 15). Also, the 10,000 sum is an approximation, as also mentioned in the question. I had not included the question as I had thought it would be misleading rather than helpful. I have edited the post and included it now though, if you kindly wish to refer to it. Thanks again!


Exemplo de Picker View em Swift

Question: Caros amigos, como faria pra popular um objeto UIPickerView com o array simples?
exemplo:
var titulos = ["texto1", "texto2", "texto3", "texto4"]

como setar esse array em uma UIPickerView?
Comment: O procedimento é o mesmo pra uma tableView. O que você tentou?
Answer: Você só precisar settar o delegate e o datasource do UIPickerView no seu viewcontroller (isso pode ser feito pelo storyboard)
Declarar os protocolos:
`class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate`

Ter uma variável global que contenha os títulos que serão utilizados no picker:
var titulosArray:NSArray = []

override func viewDidLoad()
{
    super.viewDidLoad()

    self.titulosArray = ["texto1", "texto2", "texto3", "texto4"]
}

E ai sim implementar os protocolos para preencher o picker:
// MARK: - UIPickerViewDelegate

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int
{
    // Número total de componetes na picker view
    return 1
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
    // Número total de itens na picker view
    return self.titulosArray.count
}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!
{
    // Título com a posição do array correspondente com a linha do picker
    return self.titulosArray[row] as NSString
}

E é isso. Se quiser dar uma olhada nesse exemplo funcionando é só pegar aqui:
http://github.com/xdoug/SwiftPickerView
Answer: Será necessário implementar UIPickerViewDelegate e UIPickerViewDataSource.
Com Swift eu tento usar extension porque torna o código mais explícito de forma a conhecer os métodos herdados de cada classe. Também gosto de criar um protocol para agrupar as duas classes.
Vou exemplificar.
Protocolo das duas classes necessárias
protocol PickerProtocol: UIPickerViewDelegate, UIPickerViewDataSource
{
    // Retorna o número de colunas
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int

    // Retorna os # elementos em cada componente
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int

    // Retorna o texto a mostrar em cada componente
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!
}

View Controller
class ExemploViewController: UIViewController
{
    var elementos: Array<String> = [] //Array nativo de Swift

    override func viewDidLoad()
    {
        super.viewDidLoad()

        elementos.extend(["Texto1", "Texto2", "Texto3"])

        // Criar picker view
        let pickerView = UIPickerView()
        self.view.addSubview(pickerView)

        pickerView.delegate = self
        pickerView.dataSource = self
    }
}

Implementação do Protocol
// MARK: - PickerProtocol

extension ExemploViewController: PickerProtocol
{
    // Retorna o número de colunas
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int
    {
        return 1;
    }

    // Retorna os # elementos em cada componente
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
    {
        return elementos.count;
    }

    // Retorna o texto a mostrar em cada componente
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!
    {
        return elementos[row]
    }

    // Ao seleccionar um elemento
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    {
        NSLog("%@", elementos[row])
    }
}

Exemplo de Picker View em Swift


How to set project license header in a NetBeans Module?

Question: Using NetBeans 8.1, how can I set a project license header for a NetBeans module? Specifically, I would like every new Java file I create to be populated with my license header.
I know how to achieve this for a regular NetBeans Java project. I specify the text I would like under the License Headers section of the project properties.

However, when I try to set the license header of a NetBeans Module project, there is no License Headers section in the module's project properties.

I would like to set this license at a project level as opposed to at a NetBeans level, because I would like my whole team to get the new template for any files they create. (I know I can change this for the NetBeans overall by going to Tools -> Template Manager and customizing it there. However, then my other team members won't get the header.)
I saw a similar question, but this was for a Maven project instead of a NetBeans module project.
Answer: Solution for NetBeans 8.2. (Likely works in 8.1, as 8.2 produces the error message described by OP.)

Create a text file with your license template text:

<#if licenseFirst??>
${licenseFirst}

${licensePrefix}Copyright 2017 Whoever you are
<#if licenseLast??>
${licenseLast}

2. Add the template to NetBeans
In the IDE, do Tools->Templates and open the Licenses node. Here you see the list of global license header templates. Press Add... then browse to and select your template file from step 1.
A new entry will appear under Licenses named 'license-XXX.txt' where XXX is your license file name -- all of it, so if you named your file 'license.txt' the new entry will be named 'license-license.txt.txt'.  (Don't panic, you can rename it.)

I called mine FooLicense.

Set the license in your project.
Add the line
project.license=FooLicense
to nbproject/project.properties
Now when you create a new source, if will include the the specified license header.
Bonus! The setting is inherited from the suite project.
Setting the license in the suite project properties will apply the setting to all modules in the suite.
Setting the license in module projects overrides the suite license setting.
Answer: In theory, you can manually set a custom license file for your module project by adding this property to nbproject/project.properties.
project.licensePath=./nbproject/licenseheader.txt

Then create the new license template and save it to nbproject/licenseheader.txt.
Unfortunately, this seems to be broken in NetBeans 8.1. When I create new files, I get this error message instead of the custom license text: "Error reading included file Templates/Classes/C:\some\path\module1\Templates\Classes\licenseheader.txt"
Using one of the built-in license templates does work. To use the MIT license for example, add this property instead to nbproject/project.properties.
project.license=mit

Comment: I submitted a bug: https://netbeans.org/bugzilla/show_bug.cgi?id=267228
Comment: I have tested this and this is the correct answer. Unfortunately, the bug prevents the feature from being used currently. Thank you for logging that bug report - I will have to keep an eye on it.


How to get delta of a file from within hook_tokens

Question: I am trying to create a delta token in my module.
In  hook_tokens, I manage to get the file object, but I have no clue on how to get the delta of my file...
Here is my implementation of hook_token_info
function artprod_token_info() {
  $types = array();
  $tokens = array();

  $types['delta'] = array(
    'name' => t('Delta'),
    'description' => t('Provide the delta of the field.')
  );
  $tokens['delta']['delta'] = array(
    'name' => t('Delta'),
    'description' => t('Provide the delta of the field.')
  );

  return array(
    'types' => $types,
    'tokens' => $tokens
  );
}

Here is the beginning of my implementation of hook_tokens
function artprod_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = array();
  if ($type == 'delta') {
    $file=$data['file'];
    foreach ($tokens as $name => $original) {
      // Find the desired token by name
      switch ($name) {
        case 'delta':
          $replacements[$original] = $file->delta();// NOT WORKING
          break;
      }
    }
  }
  return $replacements;
}

Answer: It's the relationship between a file entity and another entity via a reference field that has a delta, not the file entity itself. A single file could, theoretically, be referenced by many entities, via multiple separate fields, or even twice in the same entity - meaning it doesn't conceptually have a single delta related to it.
What you'll need is to run an EntityQuery with sufficient contextual conditions to narrow down to one result, load up that parent entity, and loop through the field values until you find your file, giving you the delta.
If your use case enforces that a file can only be referenced by a single entity, it'll be a lot easier to implement. But it would probably be safer to include at least some kind of limiting.
Comment: I completely agree with you; but in my use case, my file is used only once. I will vote for your clever comment and I will also update this post with a solution that I found meantime
Answer: Here is the solution I found:
Firstly, I have slightly rewrite the hook_token_info to "store" the field name of my file field in the token name:
function mymodule_token_info() {
  $types = array();
  $tokens = array();

  $types['delta'] = array(
    'name' => t('Delta'),
    'description' => t('Provide the delta of the field.')
  );
  //I name the token like my file field name for a futur use
  $tokens['delta']['field_my_file_field'] = array(
    'name' => t('Delta'),
    'description' => t('Provide the delta of field_my_file_field.')
  );

  return array(
    'types' => $types,
    'tokens' => $tokens
  );
}

Then in hook_tokens: I get the fid of my file and I compare it with all the fid's values of $mynode->field_my_file_field. When both fid matches, I use the delta for my replacement:
function mymodule_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = array();
  if ($type == 'delta') {
    // Get the fid to compare with the field attached to my node
    $file_fid = $data['file']->id();
    // loop throught all the tokens
    foreach ($tokens as $name => $original) {
      // As the token name is also the name of the field,
      // I can loop the field values. This allow me to create
      // other tokens for other fields
      foreach ($data['node']->{$name} as $delta => $file_item) {
        // compare the value with the fid
        if ($file_item->getValue()['target_id'] == $file_fid) {
          //if it matchs, I can use this delta as a replacement
          //for my token (I add 1 as a personal choice)
          $replacements[$original] = $delta + 1;
        }
      }
    }
  }
  return $replacements;
}


How can I remove values from my Parent Grouping?

Question: I would like to categorize questions as yes/no, but i dont want the values to show up on the parent row. Only the users row.
Is it best to setup a hierarchy on one table? Im still new to PowerBI. I want it structured liked the 1st screenshot.
[EXCEL]
[1]: https://i.stack.imgur.com/MztVg.png
[POWERBI]
[2]: https://i.stack.imgur.com/ugAI2.png
Answer: You can try with measure. DAX has function HASONEVALUE.
<code>MeasureToTry =
 if (hasonevalue(Table[Column]), 1, BLANK() )
</code>
Replace 1 depending on your logic.
Comment: Thank you, can I enter this formula on a current column or do I need to create a calculated column/measure?
Comment: try as new measure


jquery ui draggable + sortable helper style

Question: I am using jquery ui plugin to realize a drag and drop linked to a sortable list element. When I move the draggable element, a helper is created with a custom width and height. When my element is above the sortable area, an inline style is created and affects my custom width and height. The helper no longer has the right dimensions and takes 100% of the width of the sortable zone.
You can see an example on the jquery ui example here http://jqueryui.com/draggable/ # sortable
My goal is to prevent the insertion of inline style for the height and width of the helper.
Is that possible?
I have try the sortable forcehelpersize parameter but with no success.
edit :
I noticed that when I'm over the sortable area, the helper takes the dimensions of the initial element draggable.
Comment: can we some of your code that you are trying ?
Comment: No doubt many will disagree, but depending on how you structure your CSS (especially whether it will cause confusion for future development work) you could ensure the application of width and height using the !important property.
Answer: Unfortunately, the ui.sortable code that sets the width of your helper does not consider a width on the class as specified. I'm using jQuery 1.8.x and stumbled into this same behaviour. Looking at the source code, I saw that ui.sortable is checking if the width style is specified on the element and if not, will set it to the width of the first element in the sortable.
My solution was to explicitly set the width and height on the helper using the function form of the draggable helper option.
$('#draggable').draggable({
    helper: function() {
        var helper = $(this).clone(); // Untested - I create my helper using other means...
        // jquery.ui.sortable will override width of class unless we set the style explicitly.
        helper.css({'width': '462px', 'height': '300px'});
        return helper;
    }
});

Those values don't have to be hard coded. You could copy them from another element, for example. But they do need to be set on the helper element itself (not inherited).
Answer: Old question, google doesn't mind. Therefore this may still be usefull to some people.
I use the event on the sortable object as follows:
$('#element').sortable({
    receive: function(event, ui) {
        ui.helper.first().removeAttr('style'); // undo styling set by jqueryUI
    }

Answer: At the top of the .ready function initialize the width to the actual width.
If there is just one element use:
$('#myDraggable').css({
    'width' : $('#myDraggable').width()
});

If there are multiple elements you can loop through using:
$( "#myDraggable > div" ).each(function( index ) {
    $(this).css({
        'width':$(this).width()
    });
});

Answer: You could also grab the width and height of the cloned element, and use those to set the width and height of the clone itself.
helper: function() {
  var helper = $(this).clone(); // Untested - I create my helper using other means...
  // jquery.ui.sortable will override width of class unless we set the style explicitly.
  helper.css({'width': $(this).width(), 'height': $(this).height()});
  return helper;
}

Answer: Please, try this:
$('#draggable-id').draggable({
    stop: function ( event, ui ) {
         $(ui.helper[0]).attr('style', '');
         //your css
         //$(ui.helper[0]).css({});
    },
});

Answer: Why not use event and ui vars that the function of helper offers
instead of searching for helper with jQuery ?
For example I added a table around my element with prepend/append to keep style of my tr when moving it.
helper: function(event, ui) {
    ui.prepend('

')
      .append('

');
    ui.addClass('my-helper');
    return ui;
},

You can also use the existing .ui-sortable-helper class :
.ui-sortable-helper {
    background-color: #ccc !important;
}
.ui-sortable-helper td {
    padding: 0px 5px;
}

And on stop function you can easily remove the elements you don't need anymore like this :
stop: function(e, ui) {
    $('.sorting').replaceWith(function() {
        return $('tr', this);
    });
},


Get VSCode to use JSCS formatting rules

Question: Is there a way to integrate VSCode with JSCS? By that I mean: change the default indentation amount of spaces, make the format option (Alt+Shift+F) format the JavaScript code using <code>.jscsrc</code> rules and presets?
Answer: This is currently not supported, but we are working on a plugin story that would make this possible.

Get VSCode to use JSCS formatting rules


Set object permissions so that only the user specified in `owner` field can modify the object?

Question: I have a model, Package:
class Package(models.Model):
    VIP = models.BooleanField()
    name = models.CharField(max_length=200)
    contents = models.CharField(max_length=200)
    owner = # a string, user name goes here

For any particular instance of Package (that is, each row of the database), I want that only the user whose username matches owner can modify this instance, via the admin interface. How can I do this?
Comment: https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#django.contrib.auth.models.PermissionsMixin
Comment: @Gocht not sure how that solves my problem?
Comment: Can modify the object _how_? In the admin? via the ORM? using web forms? You need to be specific.
Comment: @Two-BitAlchemist via admin
Comment: That just sounds like normal view logic. When you're processing the form data, at some point you say `if package.owner != request.user` or whatever condition works with how you've set this up, then deny access by returning a templated message politely stating they can't do that. Is there something more complicated going on that I'm missing?
Comment: @Two-BitAlchemist Sorry, I edited my comment. It's not through forms, but through admin interface.
Comment: Try with the view's [dispatch](https://docs.djangoproject.com/en/1.8/ref/class-based-views/base/#django.views.generic.base.View.dispatch) method.
Answer: Override the has_change_permission for your model admin.
class PackageAdmin(admin.ModelAdmin):
    def has_change_permission(self, request, obj):
        if request.user.is_super_user():
            # allow superusers to edit all packages
            return True
        if obj is None:
            # The docs say that the method should handle obj=None
            # Don't allow user to edit packages in general
            return False
        # Let the user edit the package if they are the owner.
        return obj.owner == request.user

The code above assumes that owner is a foreign key, which I recommend. If you really want to store the username as a string, then you would change the last line to:
return obj.owner == request.user.username

You could add an extra check to make sure that the user has the 'change' permission for the Package model as well (see the docs for more info).
Note there is a has_delete_permission model admin method, which you might want to override as well.
Comment: Yes, I meant `obj.owner`. Usually, making owner a foreign key to the user model would be better than storing the username as a string.
Comment: you mean `return obj.owner == request.user.username`, right?
Comment: Shouldn't `has_change_permission` include a `self` argument?
Comment: Yes, it should. I have added it now.


Alter user_pass_reset for one time login D7

Question: I don't like the one time login process; sending the users directly to their user edit page is not what I want. I want to force the users to insert a new password.
I have created a module that doesn't work; obviously I'm not affecting the submit action and is not taking the newly inserted username to the user object.
// Let's try to add a form in the user pass reset form for password requests.
function xxx_login_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_pass_reset') {
    $form['#account'] = $GLOBALS['user'];
    $form['loginsetup'] = array(
      '#title' => t('Login setup'),
      '#type' => 'fieldset',
      '#collapsible' => FALSE,
      '#collapsed' => FALSE
    );
    $form['loginsetup']['account']['name'] = array(
      '#type' => 'textfield',
      '#size' => 25,
      '#title' => t('Username'),
      '#required' => TRUE
    );

    $form['loginsetup']['account']['pass'] = array(
      '#type' => 'password_confirm',
      '#size' => 25,
      '#title' => 'Please enter your new password',
      '#required' => TRUE,
    );

    $form['message']['#markup'] = FALSE;
    $form['help']['#markup'] = FALSE;
    $form['actions']['submit']['#value'] = 'Enter';
    //  $form['#validate'][] = 'xxx_login_user_pass_validate';
    $form['#submit'][] = 'xxx_login_user_pass_submit';
  }

  return $form;
}

// We'll check if the user did not leave a username.

// function xxx_login_user_pass_validate($form, &$form_state) {
//   if (empty($form_state['values']['name'])) {
//     form_set_error('name', t('You must select a username.'));
//   }
// }

// We should send the new values to the user object.

 function xxx_login_user_pass_submit($form, &$form_state) {
   // Set up the edit array to pass to user_save().
   $edit = array(
     'pass' => $form_state['values']['pass'],
     'name' => $form_state['values']['name']
   );

   // Save the account with the new password and name
   user_save($form['#account'], $edit);

   // Inform the user.
   drupal_set_message(t('Your login details have been stored. Welcome to example.com!'));
}

The validate function is now commented, but it does not affect the module; with or without it, it still does not work.
Answer: This is a bit of a SNAFU as user_password_reset doesn't have a hook associated with it. Why that is, I fail to see.
However, you can always use this little trick in hook_user_login to determine when users log in with a reset link by checking the emptiness of the $edit parameter as the only time it will be empty will be when the user didn't submit a form to log in = when they were automatically logged in.
function mymodule_user_login(&$edit, $account){
  if(!$edit){ // only for automatic pwd resets
    // do your thing, redirect to a password change form with drupal_goto or whatever you need.
  }
}

The implementation of forcing the user set a new password is another question altogether. We do it with a modal window that shows a simple custom form, but there are plenty of ways to do it. Unfortunately the easiest one is sending the user to their user edit form like the password reset functionality automatically does, but there's absolutely no reason why you couldn't just do whatever at that point as the user is logged in and good to go.
Answer: You can intercept the password reset with a hook_form_user_pass_reset_alter function.
When the user clicks the button to login, they can be taken to your alternative page.
Something like this works:
e.g:
/**
 * Implementation of hook_form_FORM_ID_alter()
 */
function MY_MODULE_form_user_pass_reset_alter(&$form, &$form_state, $form_id) {

  $uid = $form_state['build_info']['args'][0];
  $timestamp = $form_state['build_info']['args'][1];
  $hashed_pass = $form_state['build_info']['args'][2];

  // Go to our user/[uid]/edit/password page for resetting password
  $url = url("user/reset/$uid/$timestamp/$hashed_pass/login", array(
    'query' => array(
      'destination' => "user/$uid/edit/password"
    )
  ));

  $form['#action'] = $url;

}


Why is it unnecessary to escape "/" in Nginx regular expressions?

Question: So I've made it a thing to finally learn about regular expressions. Normally when working with regular expressions it is necessary to escape delimiters (like "/") with a "\". But when I'm using regular expressions in Nginx it would seem that "/" is treated literally and not as delimiter.
Nginx uses the PCRE engine for evaluating regular expressions, so it makes no sense to me that you can you just throw in an unescaped delimiter without any consequences.
As an example, the below regular expression allows a single IP address and denies all others:
location ~ /\.serverfault {
    allow 126.96.36.199;
    deny all;
}

But I would think it would need to be like this to work correctly:
location ~ \/\.serverfault {
    allow 22.214.171.124;
    deny all;
}

What am I missing here?
Answer: The reason you don't have to escape / is that / is not a delimiter.
It sounds like you are accustomed to writing regular expressions in other applications, where a delimiter is required. For instance, in Perl you might write something like:
m/\/.serverfault/

The key here is that you chose the delimiter. There is nothing special about /. In fact, you could use just about any character. # is fairly common as well.
m#/.serverfault#

If you choose a specific delimiter, and that character appears in the regular expression, you must escape it, or choose a different delimiter.
Because nginx does not need the ability to perform replace operations on regular expression matches, (e.g. s/old/new/) it also does not need to use a delimiter, thus when you specify regular expressions in nginx, no delimiter is used, and (almost) nothing needs to be escaped.
Comment: I got confused because https://regex101.com/ says "/ An unescaped delimiter must be escaped with a backslash (\)" when not escaping slashes in the search term. Any ideads why?
Comment: @JRA_TLL As noted above, nginx does not use a delimiter, so there is nothing to escape.


Como concatenar uma variável mais uma mensagem no "insert"?

Question: Tem como concatenar uma variável e uma mensagem no insert? Exemplo:
declare a int;
set a = 2;
insert into tb_usuario values ('a' + 'fez tal coisa');

Comment: Neste caso você está concatenado o caractere 'a' e não a variável a. Tente CONCAT(a, ' fez tal coisa').
Comment: deu certo. obrigada
Answer: Sim, tem, você precisa usar uma função para isto, no caso é a CONCAT(). Então ficaria algo assim:
insert into tb_usuario values (concat('a', 'fez tal coisa'));

Embora esse caso não faz muito sentido fazer assim, espero que esteja usando um campo ou variável aí. Quem sabe queira fazer isto:
insert into tb_usuario values (concat(a, 'fez tal coisa'));

Coloquei no GitHub para referência futura.
Isto inserirá 2fez alguma coisa.


Nome do atributo dinâmico em Post Jquery

Question: De que forma posso usar o dado da variável type como titulo/name do atributo que será passado no POST?
O type é dinâmico pois é de fato o nome da coluna no banco de dados.
$('body').on('click', '.setCompany', function(e){
        var type = $('.modal.in').attr('data-type')
        var id = $(this).attr('id')

        $.post("/admin/purchase_orders_groups/8",
            { ${type}: id, _method: 'PUT' }
        )
})

Comment: isso soa meio estranho.. no lado server você recebe um objeto sem saber o nome da propriedade? não seria mais fácil receber um par "nome/valor"? assim `var postData = { nome: type, valor: id }`
Comment: Posso fazer assim também, só implica em mais código no backend. Estou realmente tentando simplificar.
Do lado do servidor sim, há um validator barrando o que não for viável e aceitando o que for ideal.
Comment: entendo e realmente tem que mudar o backend, mas nem sempre o simplificar fica mais simples e claro pra entender. Neste exemplo que dei, qualquer um que ler o código vai saber o que está sendo enviado e recebido
Comment: Concordo plenamente, inclusive, se houver alguma forma de tornar o nome do elemento dinâmico, ficaria ainda mais simples de entender. Considere que poderia ser  `{ $type = id }`
Seria fácil também
Answer: Assim acho que resolve seu problema:

var type = 'AlgumaCoisa';
var id   = 'AlgumValor';

var x = { [`${type }`]: id, _method: 'PUT' };
console.log(x);

Isso funciona no Ecmascript 6
Comment: Sensacional, é exatamente isso que pensei. Mas não soube exatamente como procurar isso. Muito obrigado!
Comment: Eu tinha visto algo parecido aqui nos código q alguém fez, tb não sabia como procurar rs


jQuery ajax in each loop

Question: I have a problem with getting values in success function (ajax) inside the $.each loop.
I've got something like this:
var test = [];
$.each(images, function(index){
    var formData = new FormData();
    formData.append('image', images[index]);

    $.ajax({
        url: 'http://localhost/admin/api/offers/upload_photo',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        beforeSend: function(){
            console.log(test.length);
            test.push(images[index]);
        },
        success: function(){
            console.log(test.length);
        }
    });
});

And the output of beforeSend works fine (console log: 0, 1, 2), but another one returns three times 3 (console log: 3, 3, 3). The rest works with no problems, I only struggle with it. Is there anyone who is able to help me? Thanks!
Comment: seems like it's doing exactly what it should be.
Comment: It seems that your `each` loop finishes before any of the `success` functions fire. So, by the time `success` fires for one of the iterations, the loop has completed and the length of `test` is three. This might be informative: [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call)
Comment: That's why ajax is async :) as its name says :)
Comment: This behaviour seems logical and as expected. What did you want the code to do?
Answer: AJAX requests are asynchronous by default. This means that it sends the request to the server, but doesn't wait for the response to return before continuing with the code. So the $.each() loop sends all three AJAX requests, and executes all their beforeSend: functions, immediately. The success: functions aren't executed until the responses are processed, which won't be until your code returns to the main browser event loop.
Since all the beforeSend: functions are executed before any of the responses are processed, the test array will be filled with all the images when the success functions are executed. So they'll all see test.length == 3.
Comment: Thanks, I understood how AJAX requests exactly work and reached my aim.

jQuery ajax in each loop


Object.values seems not to work in enum type

Question: I have this enum defined in my app:
export enum Status {
    BOOKED = 'B',
    FREE = 'F',
}

and I add this message on the console
console.log ('<------------------------------------>');
        console.log (code.value);
        console.log (Object.values(Status));
        console.log (code.value in Object.values(Status));
        console.log ('<------------------------------------>');

 <------------------------------------>

and I see this on the console, code.value is not included in the enum; I should see true
    B
    [ 'B', 'F' ]
   false

Comment: See what `in` is for: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
Answer: You should use array.include() to check if an array contain a value https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
const values = Object.values(Status);
console.log(values.includes(code.value));

Comment: You may have to cast the enum to a plain array first: `Object.values(Status as {}).includes(code.value)`
Comment: I have tried this solution but I have the error: S2345: Argument of type 'string' is not assignable to parameter of type 'Status'.
Comment: @SandroRey `code.value` is supposed to be of type string. If this is not the case, it may be better to do `values.includes(code.value as Status)`.
Answer: You have this object
export enum Status {
    BOOKED = 'B',
    FREE = 'F',
}

Object.values(Status) will give you [ 'B', 'F' ] which is expected
Read this for more info -

The Object.values() method returns an array of a given object's own
  enumerable property values, in the same order as that provided by a
  for...in loop. (The only difference is that a for...in loop enumerates
  properties in the prototype chain as well.)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values


Looking for an example of a Markov Chain

Question: I am looking for an example of a Markov Chain characterized by, say, 3 by 3 matrix that has more than one eigenvector (say a population distribution of birds, or something). I remember solving a problem where instead of applying a matrix to a given vector $n$ times in a direct way, I would instead break that vector down into a linear combination of the eigenvectors and have the matrix act on them, and just raise the respective eigenvalues to the nth power. This of course requires that the matrix is diagonalizable. Is this compatible with markov chains, or am I mixing the things I did in linear algebra up? I would be glad if you can show me an example of what I am describing.
Comment: The formulation of your question is dangerously ambiguous: are you interested in stationary distributions or in eigenvectors? If the latter, with the eigenvalue 1 or for any eigenvalue? To the right or to the left? If you are interested in transition matrices with several stationary distributions (aka eigenvectors to the left with nonnegative coordinates and for the eigenvalue 1), any reducible Markov chain will do, for example [[-,-,-]|[0,1,0]|[0,0,1]] where the - are any positive parameters summing to 1.
Answer: Here is a simple example - consider a square with vertices (0,0),(0,1),(1,0) and (1,1). A fly starts at the origin and hops to one of the two adjacent vertices with probability 1/2. It stays at (1,1) when it reaches that vertex. Lets say we want to find the probability that we are at (1,1) after n hops.
The transition matrix for this Markov chain is
$M = \left[ \begin{array}{ccc} 0 & 1 & 0 \\ 0.5 & 0 & 0.5 \\ 0 & 0 & 1 \end{array} \right]$
where the vertices (0,1) and (1,0) are collapsed into one state by symmetry. The transition matrix after $n$ hops is $M^n$ and our desired probability is the (1,3)rd element of $M^n$. We can decompose $M$ as $M = Q \Lambda Q^{-1}$ where
$Q = \left[ \begin{array}{ccc} \sqrt{\frac{2}{3}} & -\sqrt{\frac{2}{3}} & \sqrt{\frac{1}{3}} \\ \sqrt{\frac{1}{3}} & \sqrt{\frac{1}{3}} & \sqrt{\frac{1}{3}} \\ 0 & 0 & \sqrt{\frac{1}{3}} \end{array} \right]$
and
$\Lambda = \left[ \begin{array}{ccc} \sqrt{\frac{1}{2}} & 0 & 0 \\ 0 & -\sqrt{\frac{1}{2}} & 0 \\ 0 & 0 & 1 \end{array} \right]$
As you describe, $M^n$ can now be computed as $M^n = Q \Lambda^n Q^{-1}$ and the (1,3)rd element of this matrix will give us the answer we want.
Comment: This Markov chain has a unique stationary distribution.
Answer: If $A$ is a $3\times3$ matrix with eigenvectors $x,y,z$ belonging to distinct
eigenvalues $a,b,c$, respectively, and $v$ is any 3-vector, then
$$A^nv=ra^nx+sb^ny+tc^nz$$
where $r,s,t$ are the coordinates of $v$ with respect to the basis $x,y,z$, that is, where
$$v=rx+sy+tz$$
This is fully compatible with Markov chains, that is, it is quite possible for a stochastic $3\times3$ matrix to have distinct eigenvalues, etc., etc.
Indeed, even if the eigenvectors are not distinct, it may still work; the important condition is that there be a basis consisting of eigenvectors (which is the same thing as the matrix being diagonalizable).
So, is that OK? Do you want an example of a diagonalizable stochastic matrix?


Do you know a good cache technology which can be used in .net to share data between a server and many client?

Question: I'm trying to adress the following issue:

I have a server side .net application holding a Dictionary of PONO: the cache.
I have many client side .net User interfaces which can query some of these PONO, either by using the key or by asking the server to filter only PONO with a specific attribute value: the clients

Edit: Clients are C# thick client, not web app. So it's ok to use any channel type between the client and the server.

And of course, some of the client can update a PONO and send it back to the server. Then I'd like the server to be smart enough to notify all the client already holding this PONO with the new value, and even send the PONO to all the client which have a filter matching the new PONO value.
I don't really care about transactional aspect. In my case, the last one to speak is always right.

I think such a functionality looks quite generic so it must already exist somewhere. Any advice ?
Thanks
Answer: Have you checked out "Project Code Name Velocity" by Microsoft? Really scalable and easy to work with.

http://msdn.microsoft.com/en-us/data/cc655792.aspx
http://blogs.msdn.com/velocity/
http://www.microsoft.com/downloads/details.aspx?FamilyId=B24C3708-EEFF-4055-A867-19B5851E7CD2&displaylang=en
Answer: Have you looked at Microsoft's WCF Technology?  We are building a system that performs similar function to your project and it is working well.
Here are 2 examples of WCF I used as roadmaps and might be helpful to you:

http://www.codeproject.com/KB/WCF/WCFWPFChat.aspx
http://www.codeproject.com/KB/WCF/WCF_Duplex_UI_Threads.aspx
Answer: You are looking for push technology. I would look into the use of Comet. Try for example, the Dojo implementation of Comet.
Answer: You are definately looking for a push model.  Unfortunately ASP.net is a request/response mechanism.  The client must make a request for the server to respond.  It is quite difficult to handle this sort of transaction from a web-based tier.  OrbMan is correct that what you are looking for is a Comet style implementation.
I'm just saying that this is not as simple as it sounds without an active client such as silverlight.


tangent on parabola bisects angle

Question: I'd like to show that the tangent on a parabola bisects the angle $\alpha$ of the triangle $QPF$:
Now I have the following:

PQ || FT   and   PF || QT (do I need to show this?
Now I wanted to show that $|PQ|=|PF|$ and $|FT|=|PQ|$. With this I have $QTFP$ as a rhombus!

Would this be a good way to show the "tangent bisect"-property as written above or is there a better/easier way?
How should I proceed?
Comment: A slightly different way to prove it is to consider the perpendicular bisector of $FQ$. Because it is a parabola, $P$ must lie on this perpendicular bisector, and for the same reason (this needs a small effort) no other point of the parabola lies on this perpendicular bisector. Then prove that it is a tangent.
Comment: @shardulc Thank you! That makes sense. I'm stuck at the "prove that it is a tangent"..
Answer: You probably should be specific about what your elements are, i.e. what you assume as their definition and what you deduce as additional properties. The way I read your figure, $P$ is an arbitrary point on the parabola, $Q$ is its orthogonal projection to the directrix, $F$ is the focus of the parabola and $T$ is the point where the tangent intersects the axis of symmetry. Right?
If this assumption is correct, then $PQ\parallel FT$ is a direct consequence of the definition. $PF\parallel QT$, on the other hand, is far from clear and would require a proof.
$\lvert PQ\rvert=\lvert PF\rvert$ is a direct consequence of the definition of a parabola via focus and directrix: the parabola is the set of all points for which the distance from the focus equals the (perpendicular) distance from the directrix. If you have a different definition of what a parabola is, then you may want to establish this property as a theorem first.
On the whole, it's a bit tricky now to bring the tangent into this. So perhaps it's better to turn things around: define $T$ as the point which completes $FPQ$ to a rhombus, and then show that the resulting line $PT$ is in fact the tangent. To that effect, show that $P$ is the only point on that line which also lies on the conic. I don't have a good argument for this just now, either, but perhaps someone else will edit that in or write a complimentary answer. Your comment suggests you might have solved this part of the problem yourself already.
Once you have established that there is no other point of intersection along the line, you can show that it is a tangent by an algebraic argument. From the family of lines parallel to this, there are some which intersect the conic twice, and others which don't intersect it at all (or only at complex points). In between these two there is the limit case where the two intersections coincide. And via a limit process, that corresponds to the situation where a secant (defined by two distinct points) turns into a tangent (defined by a single point of multiplicity two). Note that this argument only holds for points which actually have multiplicity two: it will fail e.g. for vertical lines and a hyperbola which has a vertical asymptote. There you don't get points of intersection of multiplicity two, but instead one of the points of intersection would be at infinity, which can be captured nicely using projective geometry. So perhaps the argument should include the observation that only lines parallel to the axis of symmetry do intersect the parabola at infinity. How much of this needs to be shown depends on how rigorous you aim to be and what background you have.

tangent on parabola bisects angle


electron forge make failing with errors (both squirrel and nuspec)

Question: I'm trying to package an electron app into an exe to test if everythings working in a binary and then package it into an installer.
I made the app using create-electron-app and I'm using electron-forge.
The app seems to be running fine when I use npm start but whenever I run npm run make, both Squirrel builds and nuspec builds fail with errors
PS C:\Users\aryan\OneDrive\Documents\GitHub\yt-music-desk> npm run make

> email@example.com make
> electron-forge make

✔ Checking your system
✔ Loading configuration
✔ Loading configuration
✔ Resolving make targets
  › Making for the following targets:
❯ Running package command
✔ Loading configuration
✔ Resolving make targets
  › Making for the following targets:
❯ Running package command
  ✔ Preparing to package application
  ❯ Running packaging hooks
    ✔ Running generateAssets hook
    ❯ Running prePackage hook
      ⠴ [plugin-vite] Building vite bundles
  ◼ Packaging application
g make targets
  › Making for the following targets:
❯ Running package command
g make targets
  › Making for the following targets:
❯ Running package command
  ✔ Preparing to package application
g make targets
  › Making for the following targets:
❯ Running package command
  ✔ Preparing to package application
  ✔ Running packaging hooks
    ✔ Running generateAssets hook
g make targets
  › Making for the following targets:
❯ Running package command
  ✔ Preparing to package application
g make targets
  › Making for the following targets:
g make targets
  › Making for the following targets:
❯ Running package command
  ✔ Preparing to package application
✔ Loading configuration
✔ Resolving make targets
  › Making for the following targets:
✔ Running package command
✔ Loading configuration
✔ Resolving make targets
  › Making for the following targets:
✔ Running package command
  ✔ Preparing to package application
  ✔ Running packaging hooks
    ✔ Running generateAssets hook
    ✔ Running prePackage hook
      ✔ [plugin-vite] Building vite bundles
  ✔ Packaging application
    ✔ Packaging for x64 on win32 [16s]
  ✔ Running postPackage hook
✔ Running preMake hook
❯ Making distributables
  ✖ Making a squirrel distributable for win32/x64
    › Failed with exit code: 1
    Output:
    Attempting to build package from 'youtube_music_desktop.nuspec'.
      The specified path, file name, or both are too long. The fully qualified file name must be less …
◼ Running postMake hook

An unhandled rejection has occurred inside Forge:
Error: Failed with exit code: 1
Output:
Attempting to build package from 'youtube_music_desktop.nuspec'.
The specified path, file name, or both are too long. The fully qualified file name must be less than 260
characters, and the directory name must be less than 248 characters.
at ChildProcess.<anonymous> (C:\Users\aryan\OneDrive\Documents\GitHub\yt-music-desk\node_modules\electron-winstaller\src\spawn-promise.ts:52:16)
    at ChildProcess.emit (node:events:515:28)
    at ChildProcess.emit (node:domain:488:12)
    at maybeClose (node:internal/child_process:1105:16)
    at Process.ChildProcess._handle.onexit (node:internal/child_process:305:5)

Fixes that I've tried:

Running npm run package first and then run npm run make.
Increasing max path length in registry using Powershell.

None of the fixes seem to be working.
The squirrel build of the app got created(nuspec failed) when I first built it but after making some changes to the code, both of them seem to fail.
Answer: Unfortunately, I couldn't find a fix for this issue but I had to use electron-packager instead of electron-forge and it worked fine.


How do I pass JavaScript variables back to PHP?

Question: I'm trying to build a Drupal 8 module with a jQuery plugin. I wanted to pass some of the JavaScript variables to PHP so that I can save the variables into database.
This question asked about the way to do it in Drupal 7. Since hook_menu() is gone in Drupal 8, how can I accomplish this task?
Answer: Where you implemented hook_menu(), in Drupal 8 you need:

A .routing.yml file containing the routing definition
example.name:
  path: '/example/{variable}'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::content'
  requirements:
    _permission: 'access content'

A controller class for the page callback
class ExampleController {
  // ...
  public function content($variable) {
    // Do something with $variable.
  }
}

What is important is the file structure, which should be as follows, assuming that example is the machine name of the module.

example
The directory containing the module

example.routing.yml
src
The directory containing all the classes

Controller (directory)

ExampleController.php
The file containing the controller

Keep in mind that you can change the machine name of the module, the route name (example.name), and the name of the class implementing the controller (ExampleController); the ones I used are only examples.