Sanitized text input for EntityMetadataWrapper set()

Question: Through searching, I've found plenty of examples using the EntityMetadataWrapper set() function to update entity fields, and have implemented it successfully in my module. However, I haven't been able to find much in the way of documentation / best practices on the different array options you can pass to set(). I want to make sure the way I'm updating data won't cause unforeseen issues later on.
I am doing a straightforward update of text field values in a form submit callback:
function hook_FORM_ID_submit(&$form, &$form_state) {
  // Get the node.
  $node = node_load($form_state['nid']);

  // Create entity metadata wrapper to get and set values easily.
  $node_wrapper = entity_metadata_wrapper('node', $node, array('bundle', $node->type));

  // Set fields
  $node_wrapper->field_quip->set(array("value" => $form_state['values']['field_quip']['value']));
  $node_wrapper->field_short_sentence_summary->set(array("value" => $form_state['values']['field_short_sentence_summary']['value']));

  // Save node.
  $node_wrapper->save();
}

I am passing set() an array with only one key: value. This seems to be working fine. However, I notice that when I call value() on that same field before I set a new value, it returns an array with three keys:
$original_value = $node_wrapper->field_quip->value();

// Output of $original_value:
// Array (
//   'value' => '
The original value
',
//   'format' => 'general',
//   'safe_value' => '
The original safe value
',
// )

The way I am current setting fields, I lose the sanitized value. Will this come back to bite me? Should I be running check_markup() on the value and passing format and safe_value to set(), rather than an array with just value? I might be splitting hairs here, but I want to make sure I do things right.
Answer: It turns out that if you just set the value, Drupal will not display your HTML without converting your tags to entities. So the value
Foo bar
 will be displayed literally in Views (and other areas) as <p>Foo bar</p>.
Rather than attempt to create a sanitized safe_value myself before calling set(), I found that if I passed a format value, Drupal will take care of the sanitization for me with the filter settings defined for that format.
So the correct syntax is:
$quip = array(
  "value"  => $form_state['values']['field_quip']['value'],
  // Change to match the text format of your field.
  "format" => "general"
);
$node_wrapper->field_quip->set($quip);


Cauchy and convergent sequences

Question: Let $(X,d)$ be a metric space.
A sequence $\{x_n\}$ in $X$ is called Cauchy sequence if for any $\varepsilon>0$ exists $N$ such that $n,m\geqslant N$ implies that $d(x_n,x_m)<\varepsilon$.
I know that Cauchy sequence not necessarily convergent. But if we look at the definition of Cauchy sequence and take $m=N$ we got that for any $\varepsilon>0$ exists $N$ such that $n\geqslant N$ implies that $d(x_n,x_N)<\varepsilon$.
And we got the definition of convergent sequence. What's the problem?
Can anyone explain this? Sorry for stupid question.
Comment: The $N$ depends on $\delta.$
Comment: What is $\delta$?
Comment: @Pacman I'm sorry. The $N$ depends on $\varepsilon$ (I always use $\delta$ instead of $\varepsilon$).
Comment: In the semi-open interval $]o, 1]$ you have {$\frac {1}{n}; n\in\mathbb N$}   is Cauchy but it is not convergent.
Answer: A converget sequence has a limit $L$. The definition says:

$(x_n)$ converges to $L$ if for any $\epsilon>0$ there exist some $N$
  such that $d(x_n,L)<\epsilon$ for any $n\ge N$.

Note that the limit $L$ does not depend on $\epsilon$ or that $N$. But in the difinition of Cauchy sequences, the inequality $d(x_n,x_N)<\epsilon$ that you have correctly deduced depends on $N$, and $N$ depends on $\epsilon$.

Cauchy and convergent sequences


Can I put nylon strings on Martin D28 Dreadnought?

Question: I would like to play some Spanish classical music on my Martin D28. And I was wondering would it be possible to put nylon strings on it and which kind you would recommend?
Thanks
Comment: They don't make nylon strings with ball ends for that type guitar.  But you might want to try Silk and Steel Acoustic Strings which are softer to the touch and feel more like nylon strings that regular steel strings.
Answer: Probably not.  I am coming from experience with classical guitars.  Strings for steel string guitars have a large metal ball bearing of sorts on one end that goes into a hole in the tail piece (behind the bridge).  Nylon strings usually do not have this and need to be tied at both ends (not a real knot but a twist that is held in place under tension).  Also most nylon strings are quite fat compared to their steel string counterparts and will not fit into the grooves in the nut or bridge that keep the string in place.  Lastly, even if you were to find a set of strings that fit nylon string guitars usually have a soft wood top whereas steel string acoustics might have a hard wood top.  And both have different bracing inside.  This amounts to a completely different tone and I am not sure that nylon strings would sound very good on a steel string acoustic.
If you really want to start playing classical or flamenco I'd suggest investing in a low cost but decent quality beginner classical guitar.
Comment: You'd probably have to drop all the tension off the truss rod too, or the neck will pull back like crazy.
Comment: Good point, but I doubt you could get that far.


Windows server 2008 OR 2008 R2 SP1 for SharePoint 2010

Question: Could anyone suggest me on this- we have sharepoint 2007 running on win server-2008 64bit
and we are about to upgrade to 2010 sharepoint, problem is do we keep the 2008 64bit as is or
upgrade to R2 and install SP 2010 on it.
obviously R2 must be more reliable than 2008 but just asking if we can we just upgrade
2008 to R2 with out a new server?
any help is appreciated!
Answer: Consider

Have the 2008 installation been unreliable and if so is it really windows? If it has it might be time to buy some new hardware
Are you worried about the support and update cycle for windows 2008? Obviously the ones for R2 will extend further into the future

However, If it's a dedicated SharePoint server machine that has been running just fine I see little or no reason to upgrade to R2.
If you choose to keep your server upgrading to Windows 2008 R2 remember to install the sp2 for SharePoint 2007 (wss3) BEFORE you upgrade.
Windows SharePoint Services 3.0 Service Pack 2 (SP2) - English
http://www.microsoft.com/downloads/details.aspx?FamilyID=79bada82-c13f-44c1-bdc1-d0447337051b&displaylang=en
Comment: when we upgrade to R2 from server 2008 x64, will the applications and data get carried across without any issue or do we need to re-setup everything from scracth?
Comment: also my MOSS version is 184.108.40.20614, is this the latest version and includes WSS 3.0 SP2?
Comment: The version 18.104.22.16821 included the SP2 so you should be good. There are however some later builds than 6515, your build was released in august 2009.
Comment: You might want to do some more reading about upgrading. Check technet http://technet.microsoft.com/en-gb/library/cc303309(office.12).aspx
Answer: When i first started doing sp2010, i used windows2008. That was a real pain, things were just buggy. As soon as i moved to r2, no more bugs. So i would say go with r2. It also means you can install r2 sp1.
Comment: when we upgrade to R2 from server 2008 x64, will the applications and data get carried across without any issue or do we need to re-setup everything from scratch?


Upperbound for $ \sum _{i=1}^N a_i\ln a_i $

Question: It's easy to prove that following upperbound is true:
$\sum_{i=1}^N a_i\ln a_i \le A \ln A$, where $\sum_{i=1}^N a_i=A$ and $ a_i\ge 1$
I'm wondering, is there stronger upperbound?
Answer: You can also use the following estimate
$$\sum_{j=1}^{N} a_j\ln a_j \leq A\ln (A-N+1) .$$
Comment: Could you tell me more about this ? It is very interesting to me since the lhs is a part of entropy.


Multiple if else statements to classify existing values in a new column in R

Question: I have tried reproducing the method described in this post (Trying to create a new column using multiple if else statements in R)
I would like to classify the severity of a patients blood work. My intention is to give a certain score (i.e. 0, 1, 2, 3) to an already existing value for each patient's blood work value. After that, I want to save these new values into a new column.
The cut off values are:
if value is >=150000, score = 0
if value is <150000, score = 1
if value is <100000, score = 2
if value is <50000, score = 3
if value is <20000, score = 4

dput is
> dput (platelets_v1)
structure(list(ID = c(13055908, 13059026, 13154920, 13201107,
13207119, 13207948, 13234892, 13261022, 13082943, 13193903, 13259391,
13283776, 13262499, 13154288, 13207315, 13269178, 13135316, 13055690,
13207670, 13220627, 13233898, 13055009, 13044947, 13181075, 13261607,
13186960, 13240091, 13060589, 13201616, 13260671, 13302375, 13021555,
13054278, 13062360, 13035346, 13077712, 13128769, 13267480, 13160156,
13040172, 13160971, 13239318, 12977871, 13090190, 13321288, 13040530,
13100979, 13124511, 13192142, 13289317, 13315577, 13154966, 13044653,
13079694, 13128639, 13165362, 13207352, 13049409, 12999835, 13210994,
13283675, 13223721, 13064865, 13104602, 13036280, 13040507, 12964437,
13029805, 13029001, 12993036, 13072516, 13060586, 13119819, 13040632
), platelets = c("469.000", "NA", "NA", "243.000", "NA", "NA",
"NA", "334.000", "522.000", "NA", "NA", "NA", "NA", "312.000",
"421.000", "NA", "321.000", "NA", "NA", "NA", "298.000", "263.000",
"109.000", "280.000", "NA", "NA", "430.000", "288.000", "159.000",
"528.000", "NA", "163.000", "NA", "439.000", "NA", "477.000",
"NA", "473.000", "NA", "459.000", "183.000", "343.000", "285.000",
"459.000", "253.000", "NA", "227.000", "NA", "569.000", "NA",
"NA", "NA", "239.000", "382.000", "270.000", "NA", "362.000",
"NA", "146.000", "367.000", "NA", "531.000", "NA", "363000",
"NA", "257000", "158000", "56000", "417", "NA", "171000", "NA",
"NA", "NA")), row.names = c(NA, -74L), class = c("tbl_df", "tbl",
"data.frame"))

I have tried the following:
> labels <- c('0', '1', '2','3', '4')
> breaks <- c(500000, 150000, 100000, 50000, 20000)
> teste01 <- platelets_v1 %>% mutate(platelets_v1 = cut(platelets_v1, breaks = breaks, labels = labels, include.lowest = TRUE))

Desired result:
ID platelets score
13055908 469000 0
13059026 NA NA
13154920 NA NA
13201107 243000 0

and so on
Any light would be greatly appreciated.
Comment: Use `case_when` or cut()
Comment: Platelets in dataframe seems of character type
Comment: Since the output is numeric, `findInterval` is the best option.
Answer: platelets_v1 %>%
  mutate(
    platelets = suppressWarnings(as.numeric(platelets)),
    bin = 5L - cut(platelets,
                   c(0, 20000, 50000, 100000, 150000, Inf), labels = FALSE)
  ) %>%
  slice(c(1:5, n() - 0:4))
# # A tibble: 10 x 3
#          ID platelets   bin
#       <dbl> <chr>     <int>
#  1 13055908 469.000       4
#  2 13059026 NA           NA
#  3 13154920 NA           NA
#  4 13201107 243.000       4
#  5 13207119 NA           NA
#  6 13040632 NA           NA
#  7 13119819 NA           NA
#  8 13060586 NA           NA
#  9 13072516 171000        0
# 10 12993036 NA           NA

or
platelets_v1 %>%
  mutate(
    platelets = suppressWarnings(as.numeric(platelets)),
    bin = 5L - findInterval(platelets,
                            c(0, 20000, 50000, 100000, 150000, Inf))
  )

But if you want the generic ability to find ranges that may not be perfectly aligned (left-closed, right-open), then
platelets_v1 %>%
  mutate(
    platelets = suppressWarnings(as.numeric(platelets)),
    bin = case_when(
      platelets < 20000 ~ 4,
      platelets < 50000 ~ 3,
      platelets < 100000 ~ 2,
      platelets < 150000 ~ 1,
      platelets >= 150000 ~ 0)
    )

The order here matters, since if you reversed them, everything would be either 0 or 1 (and NA). Also, one might be tempted to use between ... realize that this is "closed" on both sides, so between(platelets, 20000, 50000) is equivalent to 20000 <= platelets & platelets <= 50000, where your logic suggests you prefer ... & platelets < 50000.
Also, one might be tempted to replace platelets >= 150000 ~ 0 with TRUE ~ 0 as an assumption that all remaining values must be in that category. Since your data includes NA, I recommend against that, preferring to keep the default value of NA for unmet conditions.
Comment: One premise with `case_when` is that the first condition that is true is retained. If you have `< 100000` and then `< 1000`, the second will never be used because every number that is under 1000 is also under 100000 (obviously).
Comment: An easy way to verify that is to reverse the order of the conditions in the `case_when` code block above and rerun ... and see that all of your data will only contain `NA`, `0`, and `1`.
Comment: I have inversed the order of the conditions and it worked just fine for a particular case where I needed to classify another blood work. Thank you so much. If possible, let me know how can I pay you a coffee as a token of appreciation.
Comment: This is absolutely on point on what I needed. Thank you so much. I am not replacing ```platelets >= 15000 ~0``` with ```TRUE ~0``` as I need ```NA``` to be disclosed.
I find the ```case_when```  solution very elegant and easy to understand.
One question though is why the order matters, showing 0 and 1? Does it mean anytime I need to classify a set of values I have to begin by the highest interval and highest score (e.g  ```platelets < 20000 ~ 4```)?


How to explain Django/Python installation to Python-newbie running a shared IIS server

Question: For reasons beyond my control, our website is hosted with a hosting provider that uses IIS for their servers. They currently offer PHP and ASP, and also Python and Perl through cgi-scripts.
I want to do a re-design, re-write of our website, and want to change from PHP to a Python/Django setup. The hosting provider is open for suggestions, but are clear that "We don't really know what Python is, or how it works, but if you can explain it to us, we'll try to set you up with whatever you need".
However, I might know how to set up Django in a shared hosting environment on apache/mod_python, but I have no clue how it would be set up on IIS, and certainly not how it would be set up for a shared hosting environment. I've googled a bit, but most of the resources I find assume that the sysadmin 1) knows Python/Django and 2) is using dedicated IIS hosting for his site.
Could someone explain how I can explain the process to my hosting provider, or give me pointers to good, detailed resources I can forward to my hosting provider? Keep in mind that the people running the hosting might know "everything" about IIS, but have no idea how to deal with Python.
Answer: If you're stuck with using IIS, use PyISAPIe instead of CGI if you can.  Instructions and links for PyISAPIe are below.  Your web host will know a lot more about ISAPI extensions if they manage IIS than about Python, and they don't need to know much about Python with PyISAPIe.
A MUCH BETTER WAY OF DOING THIS IS USING PyISAPIe, AN ISAPI EXTENSION. PyISAPIe is much, much faster than CGI on IIS7. What this does is similar to mod_python on Apache.  The PyISAPIe project homepage has instructions for setting up Django with WSGI over PyISAPIe. This will bring your performance up to reasonable speeds for a public/high traffic website.

http://apps.sourceforge.net/trac/pyisapie/
http://pypi.python.org/pypi/PyISAPIe/

Setting up Django in an IIS+Python via CGI environment is going to be horribly slow for any production use. You should never use this for a website on which you expect to service more than a handful of requests per minute. It also limits you severely in what you can cache in memory in Django's caching framework, since the Django app's process is restarted with each new request.
In a sane web server like Apache, lighttpd, etc., with mod_python, the Python interpreter running the Django process remains in memory and is initialized with each new Apache worker thread that handles many requests over the course of time. This means that Python + Django are not exited and restarted for each new request. In a FastCGI setup, the web server (Apache or lighttpd for example) creates a socket (UNIX domain or TCP) across which it communicates with a FastCGI application (your Django web application) over the FastCGI protocol. Ditto for HTTP proxy setups (they speak HTTP instead of FastCGI). In a CGI environment, the Python interpreter is called which runs the Django application, completely anew for each request, so the application can not keep state across requests in memory and can't cache properly anywhere but in a database.
Enough ranting, if you must use IIS+CGI+Django, here's how to accomplish this horrible horrible thing: Use the following code to create your own CGI script which runs your Django app (it translates between CGI and WSGI). You'll have to edit the script a little to make it point to your Django app and code. That is the CGI script you would need to pass requests to. Next, you need to forward/rewrite all requests to your CGI script...
Under IIS6, you'll need a mod_rewrite equivalent like IISRewrite, which I think is not free and is closed source. Under IIS7, Microsoft finally included a URL rewriting module. Documentation for it is located here. Instructions for creating rewrite rules in IIS7 are here. You will want to forward everything at the target base URL to be handled by your CGI script.

http://code.djangoproject.com/attachment/ticket/2407/django.cgi
http://learn.iis.net/page.aspx/460/using-url-rewrite-module/
http://learn.iis.net/page.aspx/461/creating-rewrite-rules-for-the-url-rewrite-module/
http://apps.sourceforge.net/trac/pyisapie/
http://pypi.python.org/pypi/PyISAPIe/
Comment: Since the hosting is shared, the main issue is how would the hosting provider configure PyISAPIe to fit my needs, and also the different needs of their other customers. I couldn't find the instructions for setting up Django with WSGI on the homepage...

If all else fails, I'll just use the CGI approach. With less than 400 requests per *week*, I think we can live with the CGI solution until we decide to switch hosting.
Answer: How to set up Python on FastCGI on IIS
Here's how to set up Python on FastCGI IIS 7+ with opens the way for a decent DJango setup
... and be able to hook a debugger into the process enabling you to step through your Python code
This example doesn't use the IIS management console but lists the contents of the resulting configuration files
Step 1
Install Python + a good debugger (this example uses WingIDE which I found an excellent tool)
This example assumes folder c:\python27
Step 2
Create a web folder, eg on localhost c:\inetpub\wwwroot\mypythonfolder and put the following web.config file in it:

Note the | pipe character in the scriptProcessor directive. This is used by IIS to map the script to a fastCgi application (step 3).
It should match character by character the fullpath + pipe character + arguments settings from step 3 below.
Step 3
In the applicationHost.config file in c:\windows\system32\inetsrc\config folder place the following in the
 section:
<code>    <fastCgi>
        <application fullPath="c:\python27\python.exe" arguments="c:\python27\lib\mylib\myfcgi.py" monitorChangesTo="C:\Python27\Lib\r4a\r4afcgi.py" stderrMode="ReturnStdErrIn500" maxInstances="4" idleTimeout="300" activityTimeout="300" requestTimeout="90" instanceMaxRequests="200" protocol="NamedPipe" queueLength="1000" flushNamedPipe="true" rapidFailsPerMinute="10" />
    </fastCgi>
</code>
Step 4
In c:\python27\lib\mylib\myfcgi.py put the following code:
<code>import wingdbstub
</code>
import os, io, sys
ret = "environment:\r\n"
for param in os.environ.keys():
    ret = ret + "%s=%s\r\n" % (param,os.environ[param])
ret = ret + "\r\nArgs:"
for arg in sys.argv:
    ret = ret + arg
handle = io.open("c:\temp\myfcgi.log", 'wb')
handle.write(ret)
handle.close()
Step 5
Make sure IUSR has rights to write into your c:\temp folder
Step 6
Put wingdbstub.py and wingdebugpw into your c:\python27\lib\mylib\ folder. This will enable debugging in wingide. These files are provided with your wing installation.
Note: if Python also needs to compile your code into wingstub.pyc, IUSR needs write rights on that folder since the python process will be launched under that account by IIS
Step 6
Open wingdb and set a breakpoint on the 'import os, io, sys' line
Step 7
Hit in your browser http://localhost/mypythonfolder
If everything works correct, wingide should now be triggered to display the running code at your breakpoint. If not:
- either there's a firewall issue. The python process communicates with the WingIDE interface through a tcp connection
- or there's an issue with security within wingide. It needs the proper version of the wingdebugpw file, which basically contains a password or token that validates access against your wingide installation. If this were not the case, anybody with tcp access to your pc could debug against your code.
Step 8
Verify that in c:\temp the logfile is created. This should also work if you can't get step 7 going
Step 9
Note that this page triggers the debugger but does not return any page to the webbrowser. Some background: the webserver communicates fastcgi through so called 'records'. This means that each single user-request comes into your application packed in multiple separate 'records'. Each record is a data structure that indicates the beginning of a request, the querystring, post variables etc.
The un-packing of these records to a single request is kind of cumbersome, it follows the fastcgi specification of
http://www.fastcgi.com/devkit/doc/fcgi-spec.html#S1
As the content of c:\python27\lib\mylib\myfcgi.py I just dropped in a copy of zoofcgi.py provided by helicontech.
This python file is able to decode these records and serve a page and is quite interesting to debug.
Also note that helicontech optionally provides a dll that sits in between IIS and and zoofcgi.py but this dll is not strictly necessary.
I believe it implements a slightly improved and generic version of the fastcgi implementation that msft provides. However when you use their dll, when you want to step through your code the process is terminated rather quicly and IIS/the DLL kills your python process when it concludes no response is coming back within a sec or 2.
That's it. In principle the communication between IIS and your python code is done with named pipes. You should be able to set it up using tcp sockets but I wasn't able to figure out which port is used (I believe the stdin should be transformed into the port which then can be select() ed but I didn't give that any attempt)
Answer: I haven't tried this with Python, but it worked great as a CGI with Perl.  ActiveState's products integrate seemlessly with IIS.  I had great success with ActivePerl.  They also have ActivePython which might (probably) would also do the trick there.  Then I think you would just download Django install it.
EDIT:
Ok, so scratch the seemless integration with IIS...  HOWEVER, here's an article on how to integrate into IIS.  You might also consider Iron Python as your distro for a Windows box.
For the provider, I would doubt they need to know more than it is a web development platform like ASP / ASP.NET and that Python is the language used to develop with it.
As far as the installation I mention above, I'm going to try that and see how it fares.  I'll post notes on it if I get it working ok!


Complexity analysis with loop unrolling

Question: I want to know if the time taken to complete a program (barring cache effects and anything else) is any different if you unroll the loop once. Essentially, is there any difference in
the 2 loops: for(i = 0; i < n; i++) and for(i = 0; i < n/2; i++) if you access double the number of elements in the second loop as compared to the first loop? Do both the loops take the same time to finish, or does one finish before another?
Answer: Complexity analysis does not take unrolling into consideration: an unrolled loop iterating N times is still O(n).
The only thing the unrolling is good for is reducing the overhead. In a typical loop you have to do three things repeatedly:

Check if you are done
Execute the "payload" body of the loop
Adjust the loop counter

If a loop repeats N times, each of these three steps is repeated N times as well. Note, however, that the first and the last steps are pure overhead: they are there to deal with loop bookkeeping.
When you unroll the loop once, you cut half of steps 1 and 3, while step 2 is repeated N times. The complexity is the same, yet the overhead is only 50% of what it used to be.
Note: One observation that follows from this is that unrolling makes most sense when the timing of your payload activity is comparable with the timing of the overhead. For example, if the payload takes 10ms and the overhead is also 10ms, eliminating 50% of the overhead speeds up the loop by 25%. If the overhead is 1ms and the payload is 10ms, however, unrolling gives you back only 0.5/11, or 4.5%.
Comment: `you cut half of steps 1 and 3` No, you cannot cut in half step 3, there is increment somewhere (though not applied to loop counter) to access second "payload" in one cycle
Comment: @SeverinPappadeux In many cases the second increment can be optimized away quite nicely. For example, when C compiler sees `a[i+1]`, it adds `1` to the address of `a` at compile time, and uses the new offset. The increment is done once, but now the step is 2.
Answer: Loop unrolling is a form of optimization, as it reduces the number of increment, compare and jump operations. (Though leave the actual unrolling and other optimizations to the compiler, it will usually find more efficient ways to do it. If you think you know better - prove it!)
Unrolling does not change the complexity class of the problem, though. The complexity of a problem is usually not determined by constant factors, like loop overhead, and really only works out at higher numbers. (For example, O(n*log(n)) Quicksort or Mergesort are often only used to break down the list to sort into short segments, while O(n²) Insertsort is then used to sort those due to the lower overhead.)
Answer: If work-per-cycle is comparable to loop overhead, then unrolling might improve performance. From the other hand, you'll have more instructions to execute in one loop cycle. If your instruction cache is small and filled, then your unrolling might make things worse.
Try and measure, that's the only way to prove or disprove guesses
For a fun reading, here is original loop unroller, Duff's device
http://www.lysator.liu.se/c/duffs-device.html#duffs-device
On one tight loop it once gave me 4% boost

Complexity analysis with loop unrolling


Services user/login and system/connect

Question: I would like to know the difference between user/login and system/connect.
Answer: system/connect

Returns the details of currently logged in user.

user/login

Login a user for a new session

To login a user you will use user/login service call... Once user is logged in if you would like to pull logged in user details you will use system/connect service.. You can see above details in services module help section

Services user/login and system/connect


How to find a value from List> in dart(flutter)?

Question: I have a list of all countries like this:
List<Map<String, Object>> allCountries = [
  {
    "name": "Afghanistan",
    "code": "AF",
    "capital": "Kabul",
    "region": "AS",
    "currency": {"code": "AFN", "name": "Afghan afghani", "symbol": "؋"},
    "language": {"code": "ps", "name": "Pashto"},
    "flag": "https://restcountries.eu/data/afg.svg",
    "dialling_code": "+93"
  },
   .................
  {
    "name": "Zimbabwe",
    "code": "ZW",
    "capital": "Harare",
    "region": "AF",
    "currency": {"code": "BWP", "name": "Botswana pula", "symbol": "P"},
    "language": {
      "code": "en",
      "iso639_2": "eng",
      "name": "English",
      "nativeName": "English"
    },
    "flag": "https://restcountries.eu/data/zwe.svg",
    "dialling_code": "+263"
  }

];

I want to create another List<Map<String, Object>> resultOfQuery from the original list but only when the query match or start with a name of country.
How can this be done ?
Comment: Hi, you mean filtering your list with elements containing country starting with a country
Comment: Yes, filtering your list with elements containing countries starting with a country name
Answer: Use this method:
List<Map<String, Object>>filterByCountry(List<Map<String, Object>> list, String value){
   return list.where((mapObject) => (mapObject["name"] as String).startsWith(value)).toList();
  }

and you can use it like this:
print(filterByCountry(allCountries, "Afghan")); // will return List containing only the Map with the Afghanistan name


Adding a delay to a hover function

Question: I have this code which triggers a mega menu.
    $('li#locations a').hover(function(){
$('#locationsSuperNav').slideDown();
});

$('#locationsSuperNav').mouseleave(function(){
$(this).slideUp();
});

Here is the html

Culture

Advantage

Testimonials

Programs

Locations

Careers

All the content goes here

What I'd like to do is add a simple timer to the original hover event. That way, if a user accidentally touches the a tag, it won't fire unless they sit there for half a second or so. Any suggestions??
Comment: go for hoverintent plugin its very nice todo these type of stuff
Answer: You should look at using jQuery's delay() function.
Update (see edits for history)
Alright. Now I much better understand your problem. Thank you for the clarification. I think this code does what you want it to do. You can play with an example here: http://jsfiddle.net/57eGD/
$('li#locations a').mouseenter(function() {
    var curElement = this;
    var timeoutId = setTimeout(function() {
       $('#locationsSuperNav').slideDown();
    }, 650);

    // Use data so trigger can be cleared.
    $(curElement).data('timeoutId', timeoutId);
}).mouseleave(function() {
    clearTimeout($(this).data('timeoutId'));
});

$('#locationsSuperNav').mouseleave(function() {
    $(this).slideUp();
});

Basically, delay() wouldn't work for you as that only delays the event, but it does not allow an event to be canceled. As a result, it won't work for you because, even if you delay the slideDown() event, it will still happen if the user mouses over. Because of this, you have to use window.setTimeout which does allow for a cancellation. However, the (sort of) tricky part is that you have to be able to tell the timeout to cancel. This is where jQuery's data function comes into play. This function allows you to attach data of any type to DOM elements. So, in your case, you should attach it to the element you care about triggering the event (in this case, $('li#locations a')) which will allow you to cancel if you leave the element before the event triggers. You can adjust the 650 for a longer or shorter delay.
The other thing to note is that hover() should work here instead of mouseenter and mouseleave. It should be something like this:
$('li#locations a').hover(function() {
    var curElement = this;
    var timeoutId = setTimeout(function() {
       $('#locationsSuperNav').slideDown();
    }, 650);

    // Use data so trigger can be cleared.
    $(curElement).data('timeoutId', timeoutId);
}, function() {
    clearTimeout($(this).data('timeoutId'));
});

I hope this helps you! Good learning experience for me as well.
Comment: For some reason the delay function is not working for the hover event and the hover intent plugin looks like it won't work either. I need to delay the initial hover, not the mouseout. The other issue I have is the hover function is showing a separate div. Hover Intent is fixed on the parent element if I read properly. I need to have the #locationsSuperNav stay open when the user leaves the li. Any other suggestions?
Comment: @mmsa - Updated the answer. Does this help at all? If not, I will try for round three. :-p
Comment: Make sure you have the latest jQuery.  .delay is 1.4+
Comment: @JasCav, thanks for the update. Sorry for the confusion. Here's what is happening. I have a standard nav ul on a site. When the user hovers over li#locations a, I need to have a div which is hidden on the page show up. Basically creating a mega-menu. The mouseleave event hides the megamenu when the user's mouse leaves that div. The div extends the full width of the screen. Hope that helps.
Comment: @mmsa - Can you add some of your HTML to your post?
Comment: @mmsa - Okay. I think the answer is what you are looking for now. If it's not, please let me know, but I think this is it. Please don't forget to accept if this answers your question. Thanks!
Answer: jquery.hoverIntent.js is exactly what you are looking for.
http://plugins.jquery.com/project/hoverIntent
Comment: yeah hover is apt for these type of things
Comment: From what I can read, the delay happens on the mouseout event. What I need to delay is the hover event. Any other suggestions?

Adding a delay to a hover function


True or False?( Calculus)

Question: If $F(x)$ is a continuous function in $[0,1]$ and $F(x) = 1$ for all rational numbers then $F(1/\sqrt2) = 1$. (True/ False)
I think the statement is true because since $F$ is continuous and $1/\sqrt2$ is in neighbourhood of some rational number so $F(1/\sqrt2)$ should be one so that limit can exist. Is this reason valid to prove the statement true.
Comment: Yes, you thinking is correct.  You can improve your wording.  "so F(1/2–√) should be one so that limit can exist" is badly worded and semantically ... weird. But I know what you are trying to express and it is absolutely correct.
Comment: Yes, yes, yes, yes. (Sorry I can't only type one 'yes')
Comment: @SeewooLee try `Yes ${}{}{}{}{}{}$`
Comment: Joel Pereira's answer is a very nice mathematical way to express your thinking.
Comment: "$1/\sqrt{2}$ is in neighborhood of some rational number" is not what you want to be saying. The idea you want to convey is "every neighborhood of $1/\sqrt{2}$ contains a rational number", which is what @Joel Pereira does more precisely in his answer.
Answer: For every $n$, there exists a rational number $q_n$ such that $\mid \frac{1}{\sqrt{2}}-q_n\mid < \frac{1}{n}$. So $\displaystyle\lim_{n\rightarrow \infty}q_n$ =  $\frac{1}{\sqrt{2}}$. Since F is continuous, 1 = $\displaystyle\lim_{n\rightarrow \infty}$F($q_n$) = F($\frac{1}{\sqrt{2}}$) .
Answer: The statement is true, although I would express it: there is a sequence $\{r_n\}_{n\in\mathbb{N}}$ of rational numbers in the interval $[0,1]$ such that $r_n \to 1/\sqrt{2}$, hence by continuity
$$
F(1/\sqrt{2}) =
F(\lim_{n\to\infty} r_n) =
\lim_{n\to\infty} F(r_n) =
\lim_{n\to\infty} 1 = 1 \,.
$$

True or False?( Calculus)


VB6: Shell invalid arguments

Question: I went through all related answers, but I still could not solve my problem.
I would like to shell the following:
C:\Program Files (x86)\my application\application\bin\app.exe background

As one can see, there are spaces in the path, and there is an argument.
I tried just anything I could image regarding quotes, but I just don't find the right escaping.
Could anybody help?
Thank you very much!
Comment: How exactly did things you tried not work? What have you observed that led you to conclude its "wrong escaping"?
Answer: Quote the path and stick the argument on the end:
ret = shell("""C:\Program Files (x86)\my application\application\bin\app.exe"" background", vbNormalFocus)

Comment: How so? `ret = Shell("""C:\Program Files (x86)\Notepad++\notepad++.exe"" c:\windows\win.ini", vbNormalFocus)` works fine for me
Comment: I don't know why, sorry.
Comment: do you use the correct double quotes? ... some systems convert the starting double quotes to inverted ones ... please post the code you are using (just copy and paste, dont change it)

VB6: Shell invalid arguments


load custom CSS/JS for each CKEditor instance on page

Question: I would like to find out  the best way to load custom CSS/JS for each textarea with CKEditor. For me, each Content Type has different CSS/JS and I would like to load them with the CKEditor on that particular page.
How do I hook into the CKEditor module to do just that?
P.S CKEditor is an independent module and not part of WYSIWYG Drupal Setup.
Answer: use hook_page_build to add or remove css or js files to the page based on the url. See the examples module for developers on how to add/remove js or css and to examples of render arrays.
your question is not so much about the CKeditor module or WYSIWYG module -- just how to customize css and js on specific criteria such as the page url.
Comment: Thank you tenken. The CSS/JS added to the Content Page do not apply to the content of textarea of CKEditor..How to apply the same CSS/JS of the page to the content of the textarea? Thanks for help
Comment: http://stackoverflow.com/questions/22934398/ckeditor-issue-how-to-apply-custom-css-to-ckeditor


How to see which docker volume is or was being used by which container

Question: I can list all containers with docker ps (-a), I can list all volumes with docker volumes ls, when I inspect a volume, I can see the name, driver and mountpoint, but not the container(s) it is being used by.
When I use docker inspect <container>, I can see the Mount data like this for example:
"Mounts": [
    {
        "Name": "centos_db_symfony",
        "Source": "/var/lib/docker/volumes/centos_db_symfony/_data",
        "Destination": "/var/lib/mysql",
        "Driver": "local",
        "Mode": "rw",
        "RW": true,
        "Propagation": "rprivate"
    },

so in theory, I could write a script that loops through all containers to match a specific volume by name. But I ran some containers through docker-compose, and didn't bind a name (like now is possible in v2) to some volumes, so they show up like a sha256 in the docker volume ls list, like this:
DRIVER              VOLUME NAME
local               34009871ded5936bae81197247746b708c3ec9e9b9832b702c09736a90...etc
local               centos_data
local               centos_db_symfony

In this case 34009871ded5 (example) was created before I named the volume in docker-compose and centos_db_symfony after.
Question
When docker-compose.yml volume information is updated like in this case making the volume named and the information in docker inspect <container> is updated, is the history forever lost or can I find out which container a volume was used by? If so, is it also possible to restore an old volume like this?
Extra info
docker-compose version 1.6.0, build d99cad6
Docker version 1.10.2, build c3959b1

Answer: As of Docker v1.11 you can filter ps by volumes! Unfortunately this is not available in previous versions.
Here's how it would be used:
docker ps -f "volume=/var/lib/mysql"

or
docker ps -f "volume=centos_db_symfony"

Comment: I believe this feature was added in Docker 1.11, so the OP will need to upgrade to get it.
Comment: This helps if you know the volume name and want to track down containers, but not so helpful if you know the container and want to track down the volumes.
Comment: if you no the container you can use  "docker inspect" command and find the volume used by the container


Authenticate User in Symfony 3 without Database

Question: I have an application where the login process runs against an external API. The API gives me a JSON back which I store in my User Enitiy.(Call it Member)
The User Class implements AdvancedUserInterface.
And my Login Prozess.
    $firewall = 'main';
    $token = new UsernamePasswordToken($member, null, $firewall, $member->getRoles());
    $this->tokenStorage->setToken($token);
    $this->session->set('_security_'.$firewall, serialize($token));

    $request = new \Symfony\Component\HttpFoundation\Request();

    $event = new InteractiveLoginEvent($request, $token);
    $this->eventDispatcher->dispatch("security.interactive_login", $event);

But that dosen't work. Now i'm read here That this Prozess need users in a Database. My application dosen't have a User DB. Is there a way to Login the User without it.
Answer: You can define a custom guard authenticator: How to Create a Custom Authentication System with Guard. I will quickly go over the main steps here, but check out the link since it explains the steps in much more depth.
First you need to create a user class and a corresponding user provider. It looks like you already have done that. You can also skip the user provider class (or create a fake one) if you don't use it in your authenticator class later.
Next create your Authenticator class (lets say AppBundle\Security\ExternalApiAuthenticator). It is just a normal symfony service, extending Symfony\Component\Security\Guard\AbstractGuardAuthenticator. The comments on that class are pretty good at explaining how to implement it so you should check them out, but one thing that could be helpful: You can already check the credentials using your API inside the getUser method and then always return true in checkCredentials.
Finally add some config to app/config/security.yml:
# app/config/security.yml
security:
    # ...

    firewalls:
        # ...

        main:
            anonymous: ~
            logout: ~

            guard:
                authenticators:
                    - AppBundle\Security\ExternalApiAuthenticator

Comment: Thanks ! Thats not that what i'm looking for but it helps me to find it:D i only need a Custom providerand Config in the security.yml


Finding immediate children of an XML node

Question: Suppose I have the following XML
<building>
    <phonenumber></phonenumber>
    <room>
        <phonenumber></phonenumber>
    </room>
</building>

Using building.getElementsByTagName('phonenumber'), I also get the <phonenumber> node under <room>.
How can I choose only the immediate <phonenumber> node under building?
Answer: Well, I cheated and used jQuery.  Then again, doesn't everyone???

Comment: Try this: alert($(this)[0].attributes.length)
Comment: Do you know a way to count the attributes of the immediate  child? Replacing the contents of the each() function with alert($(this).attributes.length) displays an error saying that .attributes is undefined.
Answer: This can't be done with getElementsByTagName alone, since it always searches the entire subtree beneath the element.
You could try using XPATH, or just loop through the immediate children of <building>:
function getPhoneNumber() {
    var building = document.getElementsByTagName("building")[0];
    for (var i = 0; i < building.childNodes.length; i++) {
        if (building.childNodes[i].tagName == "PHONENUMBER") {
            return building.childNodes[i];
        }
    }
    return undefined;
}


Confusion about geometric interpretation of proof that $\mathbb R[X,Y,Z]/ \left\langle X^2+Y^2+Z^2 -1 \right\rangle $ is a UFD

Question: I'm working through a proof that $R=\mathbb R[X,Y,Z]/ \left\langle X^2+Y^2+Z^2 -1 \right\rangle $ is a UFD. The idea is to localize at $1-x$ and show the result is a UFD. Since $R$ is atomic as a quotient of a Noetherian ring, and $1-x$ is prime, Nagata's lemma will imply the resut.
Let $x,y,z$ be the images of $X,Y,Z$ in the quotient.
By exactness of localization $R_{1-x}\cong \mathbb R[X,Y,Z]_{1-X}/ \left\langle X^2+Y^2+Z^2 -1 \right\rangle$. If I understand correctly, $\mathbb R[X,Y,Z]_{1-X}$ means we're deleting the plane $X=1$ from $\mathbb R^3$.
Take $T=(1-X)^{-1}$ and note $\mathbb R[X,Y,Z]_{1-X}\cong \mathbb R[X,Y,Z,T]$. Descending to $R_{1-x}$ as the quotient above, some manipulations enable me to show $\mathbb R[x,y,z,t]\cong \mathbb R[ty,tz,t^{-1}]$, and since the latter is the localization at $t$ of a UFD, Nagata ends the proof.
I would like to understand what exactly is going on geometrically here and I really have no clue where to start because already at the quotient $R_{1-x}\cong \mathbb R[X,Y,Z]_{1-X}/ \left\langle X^2+Y^2+Z^2 -1 \right\rangle$ I have no idea what I should be visualizing.
Comment: @GregoryGrant yes it seems very strange to me - visualizing these things is exactly my problem!
Comment: I'm not sure what exactly you want to visualize.  The ring $\Bbb R[X,Y,Z]$ is basically all (polynomial) functions on $\Bbb R^3$.  The quotient $R$ then identifies two such functions if they are the same on the unit sphere.  The localization then just extends this to functions that are ratios of polynomials, where the denominator is not allowed to vanish on the sphere when $x=1$.
Comment: @GregoryGrant I would like to understand why the ring of such rational functions (identified if they're the same on the sphere) is a UFD geometrically, if possible.
Comment: Well, $\Bbb R[X,Y]$ is a UFD and is a much simpler space.  The UFD property there is just the fact that every curve is a unique union of irreducible curves (varieties).  So for example $XY$ is a union of two lines each of which is irreducible.  The analogous property in $\Bbb R[X,Y,Z]$ is that every surface is a unique union of irreducible surfaces.  So somehow in $R$ the same property must hold, all objects are unions of irreducibles in the same way, even if you identify the unit sphere to zero.  In fact I'm having trouble visualizing when the UFD property might fail.  Do you have an example?
Comment: @GregoryGrant $\Bbb R[X,Y]/ \left\langle X^2+Y^2-1 \right\rangle $ is not a UFD.
Comment: Okay but how do you visualize the non-UFD property of that ring?  And doesn't it seem strange to be a UFD in 3 variables but not in 2?
Comment: @Gregory, Arrow: I have tried to provide some "visualization" in my answer.
Answer: Given a noetherian integrally closed domain $A$ we have the equivalence $$ A \operatorname { is a } UFD \iff Cl(A)=0$$where $Cl(A)=0$ is the class group of $A$.
If your case $\operatorname {Spec}(R)$ is smooth so that $Cl(R)=Pic(R)$, the Picard group of $R$.
So the problem boils down to proving that the algebraic Picard group $Pic(S^2)$ of a sphere is trivial.
I don't know a  way of showing that simpler than the calculation you made but intuitively this is not so surprizing since all continuous (or differentiable) line bundles on the sphere are trivial because $H^1(S^2,\mathbb Z/2\mathbb Z)=0$.
Contrastingly the ring $\mathcal O(S^1)=\mathbb R[X,Y]/\langle X^2+Y^2-1 \rangle$ is not a UFD since the circle $S^1$ possesses a non-trivial line-bundle, the notorious Möbius line bundle, which can be given an algebraic structure.


Adding a docBase for Virtual Host using the Tomcat Virtual Host Manager

Question: In the Tomcat Virtual Host Manager there is an option to add a virtual host with options for:
Name
Aliases
App base
AutoDeploy
DeployOnStartup
DeployXML
UnpackWARs
Manager App

However there doesn't appear to be an option to set the docBase for a virtual host as I have done previously when adding them manually in the XML configuration file:
<Host name="[my_domain_name]" appBase="webapps">
   <Context path="" docBase="[path_to_my_site]" />
</Host>

Is there any way to add this via the manager, or if not, what would the default docBase end up being?
Thanks.
N.B. I'm using Tomcat 7
Answer: There is no docBase attribute for an Host. There is one for the context as you can see in your snippet.
Per the documentation :

The Document Base (also known as the Context Root) directory for this web application, or the pathname to the web application archive file (if this web application is being executed directly from the WAR file). You may specify an absolute pathname for this directory or WAR file, or a pathname that is relative to the appBase directory of the owning Host.

(see Tomcat 7.0.x documentation)
To declare a personnalised docbase, you will have to set it in all context declaration for the host. (As a side note, it is strongly discouraged to declare context in web.xml, you should add an xml file in the folder conf/<engine-name>/<host> )
As an alternative, seeing as you have an appBase attribute on your host, you can just deploy your war in that path and the doc base will then be the path to your war (expended or not following the other attributes).
For exemple, let's say we have an host in server.xml like :
<Host name="exemple.org" appBase="webapps/exemple.org">
</Host>

andan application i want to deploy to exemple.org/appli. Either I add a file appli.xml in conf/Catalina/exemple.org/ which content is :
<Context docBase="<path/to/war>" ... />

Or I put the war (named appli.war) in webapps/exemple.org/
Again see Tomcat Documentation for all the details.


Can I pass a clock signal as an input argument in a Verilog task?

Question: I was writing a testbench in VCS(G-2012.09) to verify an SPI module.
Here is a task to get a byte from a SPI master:
task get_byte;
begin
    repeat(8) @(posedge spck)
    begin
        if (spss == 1'b0)
            tmp = {tmp[6:0], mosi};
    end
    $display ("[Time:%dns]---->Get a byte: 0x%h", $stime, tmp);
end
endtask

It works. Then I want to parameterize this task and replace the code with:
task get_byte;
    input clk, oen, din;
    output [7:0] byte;
begin
    byte = 8'd0;
    repeat(8) @(posedge clk)
    begin
        if (oen == 1'b0)
            byte = {byte[6:0], din};
    end
    $display ("[Time:%dns]---->Get a byte: 0x%h", $stime, byte);
end
endtask

But when I called the task with get_byte(spck, spss, mosi, tmp) and run the testbench in VCS, it stucked. It seemed that spck did not pass to work as clk inside this task.
So is there a rule that a clock signal can not be used as an input argument within a task or did I make anything wrong?
Answer: In one of the old stackoverflow questions you can find following answer:

In Verilog arguments are passed to tasks by value. This means that the value of clock will be fixed for the lifetime of the call to the task. Your task will never find a posedge of clock, and will wait forever.

So the answer is: you can use clk as an input argument to a task, but it won't work as "standard" clock.
Answer: You can do what you ask if you declare the task as automatic and pass the input by reference (using the ref keyword instead of the input keyword in the port definition of the task)
Answer: Use the clock without declaring it an input, as you did in the first task.  Passing by reference won't work either, since the task will try to set the clock signal at the end of the task, and the simulator will throw an error.
You may want to have several tasks that reference the different clk names, i.e.:
get_byte_spclk(...)
get_byte_clk(...)

Answer: As mentioned by Qiu, this will not work.
You however can do one trick.
see the code below:
task my_task;
@(posedge testbench.name_of_the_signal_you_want_to_use_as_refernce)
Do something here
endtask

So you basically have to give path to the clock signal, something like that:
testbech.instance_of_instantiated_module.clock_signal_name


Covariance matrices for jointly gaussian distributions

Question: Is the 2nd parameter of a jointly gaussian distribution, the covariance matrix $\Sigma$, always just a diagonal matrix with values of the variances as the diagonal entries?
When I google image covariance matrix most of them just appear like this, but a couple have nonzero entries in indices other than the diagonals.
Answer: $\Sigma$ is properly called variance-covariance matrix, has variances on the diagonal and covariances off diagonal. It is diagonal if the random variables involved have zero covariances. Would seeing plots help? Try here or here.


Restore default ownership in CentOS after terrible chown

Question:
Possible Duplicate:
How do I recover a RHEL 4.3 server from bad permissions set over the entire filesystem?

Is there any way to restore the default ownership of a CentOS filesystem after an accidental chown -R user:group /* ?
Before I go and reinstall, I thought I'd ask and perhaps save some time. I'm in the process of setting up a new dev machine (thankfully not prod) and typed too fast or missed the . key or something. I tried to cancel as soon as I caught it but all my /bin /boot /dev etc had already been changed.
Is there hope, or just reinstall and be happy it wasn't a production machine?
Comment: This one has been asked a bunch, kind of disconcerting actually :-)
Comment: Hopefully you have good backups of your production machines.  So if something like this does happen all you have to do is restore.
Answer: "Just reinstall and be happy it wasn't a production machine?"
Yes.
Answer: rpm -a --setugids

Comment: I used this, worked like a charm, but some specific folders didn't change, I had to take care of them manually.
Comment: Also had to use this and it works up to a point. I had to manually reset the owner of files in /var/log and also /var/lib/mysql (mysql user) and erase a lock file for postfix. Most importantly, setuid,sticky settings were removed. I had to reset the setuid bit on /usr/bin/sudo and the sticky bit on /var/spool/postfix/maildrop.
Comment: Also setuid: /usr/bin/passwd
Answer: If you happen to have an exact clone of that machine, it is possible to restore permissions  using the other machine as a model. Something like:
server1:# find / /usr /home -xdev | xargs getfacl -Pp > /tmp/permissions_from_server1

server2:# setfacl --restore=/tmp/permissions_from_server1

-xdev tells find to stay on one filesystem.
The upper-case -P
stands for Physical walk; i.e.: ignore symlinks.
The lower-case p preserves leading slash. Without this switch, getfacl's default behavior is to remove the leading slash, causing the restore fail.

YMMV, here's a starting point.
Answer: Reinstalling is ultimately easier, and is the route I would take. If this were a production server and you didn't have backups, your first task would be regaining root privileges, as /bin/su and /usr/bin/sudo may not work any longer.
Log in locally, as root, reset the ownership of those binaries, and start working on the errors you immediately see crop up, such as libraries not working, etc.
From a similar machine, you could build a list of files in various system directories with a shell/Perl/Python script, and then run the script in reverse on the affected system, to grant proper ownerships to the files.
It's not the end of the world, although pretty close, and it's a huge pain in the bum.


Allow users to manage their own mailing list?

Question: I would like to allow each user to manage its own mailing list (import a csv list, add/remove emails).
My goal is to allow users to send an email notification to this list when they create a certain content type.
Modules like simplenews, Views_Send, or mailing_list don't seem to match my needs as they only allow to create "globals" newsletters associated with a subscription  system, not real email list "crud" by user.
Maybe should I use a generic csv data importer, views/bulk and rules to achieve this?
Answer: Start with adding a multi-value field to store eMail addresses. Say with a machine name like field_email_addresses. Assume the content type you're using for this is "Article" (pick whatever fits).
With the above in place, uou could use the Rules module to achieve your goal. Similar to what is shown in my answer to "How to check with Rules if a new element has been added to a list in a node?". By using the rule included in that answer, you can discover scenarios such as these:
Value firstname.lastname@example.com was removed from the multi value field.
Value email@example.com was added to the multi value field.

Here is a simplified version of the rule that only shows the inserted values:
{ "rules_verify_updates_to_selected_email_ids" : {
    "LABEL" : "Verify updates to selected eMail IDs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "ON" : { "node_update--article" : { "bundle" : "article" } },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-email-addresses" ] },
          "ITEM" : { "current_email_id" : "Current eMail ID" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT list_contains" : {
                      "list" : [ "node-unchanged:field-email-addresses" ],
                      "item" : [ "current-email-id" ]
                    }
                  },
                  "DO" : [
                    { "drupal_message" : { "message" : "Value [current-email-id:value] was added to the multi value field." } }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

If you just add a field with machine name "field_email_addresses" to your articles content type you should be able to import this rule in your own site and experiment with this rule in your own site to see it at work (for nodes of content type "Article", adapt this type to fit your needs).
All that's left to do is to transform the message that is displayed by sending an appropriate eMail (which is like a Rules-getting-started exercise). That will allow you to eMail relevant parts of the node whenever some eMail Id is added to that field already.
Some suggestions to further improve this solution:

Send it to all (not just updated) eMail ids mentioned in the field_email_addresses field, by creating another rule that is triggered with Rules Event "After saving a new node of content type Article".
Also use the Flag module so that if the node is flagged by the node author (and only then), send it to all eMail ids mentioned in the field_email_addresses field (something that is straight forward to do with another rule).
Variation of the previous item (which does not require the Flag module): add an extra (boolean) field to Articles, to indicate something like "Send this node as an eMail now".
Replace that field_email_addresses field (related to the Article content type) by a similar profile field with similar purpose. So that by combining it with the Views Rules module, you create a Rules loop to eMail all those users when such article is created, flagged, etc.

The above are just some basic solutions to implement what you're looking for. To further improve it (eg: combine it with importing a CSV list) should really be a different question.


Python combining html and xml files into a single dictionary

Question: I'm trying to combine html files (text) and xml files (metadata) into a single flat dictionary which I'll write as a Json. The files are contained in the same folder and have following name structure:

abcde.html
abcde.html.xml

Here's my simplified code, my issue is that I had to separate the xml meta-data writing into
        ### Create a list of dict with one dict per file, first write file content then meta-data

        for path, subdirs, files in os.walk("."):
            for fname in files:

                docname, extension = os.path.splitext(fname)

                filename = os.path.join(path,fname)

                file_dict = {}

                if extension == ".html":
                    file_dict['type'] = 'circulaire'
                    file_dict['filename'] = fname

                    html_dict = parse_html_to_dict(filename)
                    file_dict.update(html_dict)
                    list_of_dict.append(file_dict)

                #elif extension == ".xml":
                #   if not any(d['filename'] == docname for d in list_of_dict):
                #       print("Well Well Well, there's no html file in the list yet !")
                #       continue
                #   else:
                #       index = next((i for i, element in enumerate(list_of_dict) if element['filename'] == docname), None)
                #       metadata_dict = extract_metadata_xml(filename)
                #       list_of_dict[index].update(metadata_dict)

                else: continue

        json.dump(list_of_dict, outfile, indent=3)

        outfile.close()

############# Extract Metadata from XML FILES #############
import xmltodict

def extract_metadata_xml(filename):
    """ Returns xml file to dict """
    with open(filename, encoding='utf-8', errors='ignore') as xml_file:
        temp_dict = xmltodict.parse(xml_file.read())
        metadata_dict = temp_dict.get('doc', {}).get('fields', {})
    xml_file.close()

    return metadata_dict

Normally, I would add an elif condition (now commented) below the if loop for html files, which checks for xml and updates the corresponding dictionary (bool condition that filenames are identical) with the metadata, thus sequentially.
But, unfortunately it seems that for most files, the list of dict isn't fully up to date, or at least I can't find a match for 40% of my filenames.
The work-around I use seems a little silly to me, I wrote a second loop with os.walk after the first one which is used exclusively for html files, my second loop then checks for xml extensions and appends the list_of_dict, which is fully up to date and I get 100% of my html filenames matched with xml metadata.
Can I introduce some forced timing to make sure my html is done writing before I start to match any xml filename, is it possible that both if/elif loops are executed in parallel for different files?
Or else what is in terms of processing the best way to have all my html files processed before my xml files (just ordering my list of files by type before proceeding with my if/elif loops?)
I'm quite new to this forum, so please let me know if I can improve my question writing style, be mindful though that I'm trying my best ;).
Thanks for your help!
Comment: If the naming convention is as you described, you should be able to get the corresponding xml file for each html file you encounter by `xml_filename = os.path.join(path, fname+'.xml')`. Open and process it after the html file and store it to the dict within the same loop, no need to loop over everything twice.
Comment: NB: `else: continue` at the end of a loop does literally nothing, so better just remove it.
Comment: Thanks, @fsimonjetz, (filename) and (fname + '.xml') are the same thing, so this is the methodology I was trying to apply, still in the same loop it works for 60% of my files but not for the rest of them. For sake of completeness I now added the code for my metadata extraction function... please lmk if you see an issue there? Thanks for your time!
Comment: unrelated question, but I'm using the get method to extract the value from my nested dict. But I'd actually prefer to raise an exception in case that key has no value attached, should I therefor use square bracket notation with try/except statements? Something more like:  `try: metadata_dict = temp_dict['doc']['fields']`followed by an except statement to catch a KeyError exception?
Comment: The most pythonic way to handle possibly missing keys is to check whether the key exists with `if key in temp_dict:` and then handle both cases accordingly. `try/except` is really only for cases where you have no control over the inputs, like catching user input. But all of that shouldn't be necessary in your case if you follow the strategy I outlined in my answer below.
Answer: The way it is now you check all files and handle them differently, depending on whether they are html or xml, hoping that the corresponding html for each xml you encounter has already been processed – but that's not guaranteed, which I suspect to be the cause of the issues.
Instead, you should only look for html files and retrieve the corresponding xml right away:
if extension == ".html":
    file_dict['type'] = 'circulaire'
    file_dict['filename'] = fname
    html_dict = parse_html_to_dict(filename)
    file_dict.update(html_dict)

    # process the corresponding xml file

    # this file should always exist, according to your description of the file structure
    xml_filename = os.path.join(path, fname+'.xml')

    # extract the meta data
    metadata_dict = extract_metadata_xml(xml_filename)

    # put it in the file dict we still have
    file_dict.update(metadata_dict)

    # and finally store it
    list_of_dict.append(file_dict)

Alternatively, though less efficiently, you could also iterate over the sorted file list - for fname in sorted(files): - and proceed as you did, as this would also result in the html files preceding the corresponding xml files.
Comment: Thanks, I'll give this a try on Monday and let you know if that worked, but I'm sure it will. As to why the processing would not happen sequentially, can you elaborate a little? Just tryin to understand the basic principle here, if the files aren't cycled through sequentially but in parallel when I separate xml & html file handling un if/else statements?
Comment: Sure. The problem ultimately is that the `os` module lists files in (more or less) arbitrary order. So you might get `abcde.html.xml` *before* `abcde.html`. But if you only look for the \*.html files and build the path to the corresponding \*.xml file manually, the html is guaranteed to be done processing when you add the content of the xml.
Comment: Thanks for explaining this! It did work as expected with your advice!


developing an algorithm visualization/simulation

Question: I would like to develop a visualization tool that able to read c programming syntax. The code will includes some functions call, timing information and some triggering mechanism. By recognizing all these syntax, I will be able to simulate and visualize those "functions calls". The program usually use to perform searching and sorting algorithm.
Some visualization tools such as python Bokeh could be use for visualization (can recommend if there are better tools). The question here is how can the c-syntax to be translated to language such as python, and each items/objects written in C code in the searching/sorting algorithm, can be represented as an visual kind of shape object.
Is anyone does anything similar? appreciate if some suggestion on the tools used and the work flow or steps to realized this task.
Thank you
Comment: *"Connect the c code"* - what's that supposed to mean?
Comment: @m02ph3u5 sorry wasnt explained well. "Connect the c code" as to able to read the c-code syntax and translate it into the visualization tool like Bokeh or D3.js or Processing.js/py. Rather than re-write the algorithm from c to python or js for the tools, is there a faster way for the translation? Thanks!
Answer: If you want to do it well, you are looking for a C abstract syntax tree (AST) parser that runs under python.
However as it seems you want to interactively run the code as well, an existing opensouce C interpreter might be a better starting point.
This is just giving you some pointers for your own research. There are many existing C AST parsers and C interpreters. Read a bit about them. The subject is not so simple that I could give one simple and clear answer however.


What Distribution Summed is Uniform?

Question: The sum of n independent uniform random variables forms a new random variable having an Irwin–Hall distribution with parameter n.  (Approximately normal when n is large)
$$X_i \sim \cal{U},\quad \sum_{i=1}^n \mathit{X}_i \sim \mathcal{IH}(n)$$
But an IRV of what distribution will produce a uniformly distributed RV, when summed?
When I have, $$Z = \sum_{i=1}^{n}{Y_i} \sim \cal{U}$$ What is the distribution of $Y?$
I am particularly interested in the discrete case, and I suspect the particular solution will look like an upside-down bell curve.
Answer: It does not exist.
If such a distribution existed, the distribution of $Y$ would have compact support, therefore its characteristic function would be entire.  Moreover the characteristic function of the uniform distribution would be the $n$'th power of the characteristic function of the distribution of the $Y_i$.  But the characteristic function of the uniform distribution on $[a,b]$ is
$$ \phi(t) = \frac{e^{ibt} - e^{iat}}{it(b-a)}$$
which has simple zeros at $2 \pi n/(b-a)$ for nonzero integers $n$, and therefore does not have an $n$'th root that is analytic at those points.
If by "discrete case" you mean a discrete uniform distribution, a similar thing happens. The discrete uniform distribution on $0, 1, \ldots, m$, say, has characteristic function $(m+1)^{-1} (1 + e^{it} + e^{2it} + \ldots + e^{mit})$, which has simple zeros at $t = 2 \pi i k/m$ where $k$ is not a multiple of $m$, and thus this can't be the sum of $n$ iid random variables.
Answer: I didn't see Robert Israel's answer when answering (or was writing when he answered), but here is a more elementary proof in the discrete case, I think.
Suppose you had such $Z$ uniform over $[0,M]$ and corresponding $Y_i$.
Then (in the discrete case):
$$Pr(Z=M) = \prod_{i=1}^nPr(Y_i=M/n) = Pr(Y_i=M/n)^n.\\
 Pr(Z=0) = \prod_{i=1}^nPr(Y_i=0) = Pr(Y_i=0)^n.$$
($M/n$ is necessarily the maximum value with non-zero probability for $Y_i$)
Thus, $$Pr(Y_i=M/n) = Pr(Y_i=0).$$
But now you have
$$Pr(Z=M/n) \geq Pr(Y_1=M/n)\prod_{i=2}^nPr(Y_i=0) +  Pr(Y_n=M/n)\prod_{i=1}^{n-1}Pr(Y_i=0)\\
= 2Pr(Y_i=0)^n = 2Pr(Z=0).$$
And $Z$ is not uniform.

What Distribution Summed is Uniform?


dynamic variable.optiones.selected

Question: I'm new here in this Forum so this is my first question.
If I do something wrong just say it.
But now my Question: I've got a multiple select in a html file which values I save in a Database. When the site is loaded again I would like to select the select options that were selected before automaticly. For this I need something like this:
<select multiple id="a">
    <option>tomato</option>
</select>
<select multiple id="b">
    <option>apple</option>
</select>
<select multiple id="c">
    <option>orange</option>
</select>
<select multiple id="d">
    <option>cake</option>
</select>

This is what I tried (on the web page the selects have more then one option). I've done also research in the internet, but I was not able to find good results.
The problem is the dynamic variable it's interpreted like it's a id of an html object by the compiler but it should be interpreted like a variable. I only need the right syntax.
But I couldn't get it to work because there is an error whit the dyanamic variable. How can I do this right, that it works?
Comment: Do learn basics of the programming before jumping into _sea_.. As you are gonna get many big fishes later on....
Comment: If this are Basics of programming why don't you answer my question then?
Comment: Well, Your question does not qualify as an valid SO question. You must share what efforts you have taken to achieve what you want. Also [_Create a Minimal, Complete, and Verifiable example_](http://stackoverflow.com/help/mcve) Kindly do not teach me what to do and what not to do.. It is totally my preference...
Comment: So I edited the post. I think now it's better.
Comment: Which option you want to be selected ?
Comment: Oh sorry I forgot that but now it's right.
Answer: So I done a lot o research again and now I done it this way:
document.getElementById(id).options[0].selected = true;

dynamic variable.optiones.selected


c++ pointer error (access violation)

Question: I am new to C++ and think I am probably doing something I shouldn't be with pointers. I've checked tons of resources, but just can't find the problem. After debugging for a while it looks like this is the problem code.
writeHeader(outFile, width, height);
for (int row=0; row < width+1; row++){ // row == 0 is the bottom row
    for (int col=0; col < height+1; col++){ // col == 0 is the leftmost column
    Color c =  getPixel(row, col);
    outFile.write((char*)c.blue, 1);
    outFile.write((char*)c.green, 1);
    outFile.write((char*)c.red, 1);
    }
}

can anyone see what is wrong?
The getPixel method looks like this.
Color BMPCanvas::getPixel(int x, int y){
if (x<=width && y<=height){
        return image[y*width + x];
    }
    return Color(0,0,0);
}

EDIT: I changed the above code to:
    for (int row=0; row < width; row++){ // row == 0 is the bottom row
        for (int col=0; col < height; col++){ // col == 0 is the leftmost column
        Color c =  getPixel(row, col);
        unsigned char green = c.green, blue = c.blue, red = c.red;
        outFile.write((char*)&blue, 1);
        outFile.write((char*)&green, 1);
        outFile.write((char*)&red, 1);
        }
    }

which I believe fixed one of the problems, but I am still getting a memory error. Green blue and red refer to numbers referring to their color value such as (255,255,255).
I truly appreciate the help.
Comment: Did you mean `(char*)&c.blue` instead of `(char*)c.blue`? As written now you're reinterpreting a value, a byte probably, as a pointer. Or simply `&c.blue`, since `c.blue` is probably a `char`.
Comment: I realized that just a moment ago. I think that was indeed the problem though. Thanks. Still seem to be getting a memory can't be accessed problem though, although I think it has to do with the getPixel method more than the top code now.
Comment: You're probably mixing `row` and `col`. `row` should go vertically (height), and `col` horizontally (width). Right now you have them mixed up.
Comment: I.e. you're passing the `row` to `x` in `getPixel` and `col` to `y` which makes zero sense. It should probably be `col` to `x` and `row` to `y`?
Answer: My best guess would be you have an "off by one" error.  C++ arrays are zero based and so when you have an array with 10 slots you iterate from 0 to 9, not 0 to 10.
Try changing getPixel to this:
Color BMPCanvas::getPixel(int x, int y){
if (x<width && y<height){
        return image[y*width + x];
    }
    return Color(0,0,0);
}

And your other loop to this:
for (int row=0; row < width; row++){ // row == 0 is the bottom row
    for (int col=0; col < height; col++){ // col == 0 is the leftmost column

c++ pointer error (access violation)


Break up locales/en.json into multiple files

Question: I want to break up my localization json files into blocks each representing an area of the page in sailsjs. So instead of loading just en.json it would load all files for locale en like en.block1.json and en.block2.json when I set locale to 'en'.
Is there any way of doing this? I have searched online and can't find an answer.
Answer: Sails uses i18n(npm) module for i18n support.
Looking into this module's code, it seems that it expects a single file (code) in JSON format for a locale.
One way to solve your use case will be to have a Grunt task which reads en.*.json files and merges them into a en.json file for i18n module. Run this grunt task while lifting your app.


the hit script run for 3d objects but not 2d

Question: this is the script for my game.but it just works for 3d object like cube and not for 2d images in the game.how to fix it?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class touchinput : MonoBehaviour {
    void Update () {
        if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began)
        {
            Ray ray = Camera.main.ScreenPointToRay( Input.GetTouch(0).position );
            RaycastHit hit;

            if ( Physics.Raycast(Ray, out hit))
            {
                Destroy(hit.collider.gameObject);
            }
        }
    }
}

i try to change to this but i get lots of errors and don't know how to fix.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class touchinput : MonoBehaviour {
    void Update () {
        if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began)
        {
            Ray2D ray = Camera.main.ScreenPointToRay( Input.GetTouch(0).position );
            RaycastHit2D hit;

            if ( Physics2D.Raycast(Ray2D, out hit))
            {
                Destroy(hit.collider.gameObject);
            }
        }
    }
}

Comment: 2d and 3d physics can not interact with each other
Answer: Raycast indeed doesn't work on 2D colliders.
I found this method the other day, you can try it:
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
    Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
    Vector2 touchPos = new Vector2(wp.x, wp.y);
    if (collider2D == Physics2D.OverlapPoint(touchPos))
    {
        //your code
    }
}


how to do mapping user to user in drupal

Question: I created 4 user in my site.
<code>1)contributor1
2)contributor2
3)validator1
4)validator2
</code>
Contributor can able to create a node  and validator can able to review the node
I am using workbench module for content moderation.
My question is?
When contributor1 create a node, then he send the node to validator1 for review
and  contributor2 create a node , then he send the node to validator2 for review
So please let me know, how can I do the user wise mapping
contributor1 create node1 through content type 1  , then only node1 access only validator1 user and he can publish the content   same as
contributor2 create node2 through content type 2 , then only node2 access only validator2 user and he can publish the content..
you have any idea please let me know
Answer: So you have 4 user roles and 2 different content types. The first 2 user roles work with content type 1 and the other 2 user roles with content type 2.
I believe you'll find the answer to your question on this page as it explains:

How to configure Workbench Moderation states
How to configure and check Workbench Moderation transitions for each role

So you can set additional States according to your needs but the three default States of "Draft", "Needs Review" & "Published" seem to do the job for your case. You can also set what transitions between which states should generally be available and then configure the transition permissions for every role according to your needs.
Applying those guidelines, a Contributor1 user would create a node of content type 1 (in "Draft" state), given that they have the proper content creation permission. After that, Contributor1 would not be able to do the transition to other states for that content type. On the other hand, Validator1 should be given permissions to do the transition from "Needs Review" to "Published" for content type 1.


Multiple circular image with green border as map pin on Xamarin forms ,Xamarin android Xamarin IOS

Question: I have an image which should have circular border around it .
Please help I am struggling from weeks now
Comment: Did you solve the issue?
Answer: Solution 1:
You can put the image in a Frame , and set the CornerRadius and BorderColor .
<Frame CornerRadius="50" Padding="0" BorderColor="Green" HeightRequest="100" WidthRequest="100">
    <Image Source="xxx.png" />
</Frame>

Solution 2:
You can use  Custom Renderer in xamarin.forms
in iOS
//...
using xxx;
using xxx.iOS;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(MyImage), typeof(MyImageRenderer))]
namespace xxx.iOS
{
  public class MyImageRenderer:ImageRenderer
  {
    protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
    {
        base.OnElementChanged(e);

        if (Control != null)
        {
            Control.Layer.MasksToBounds = true;
            Control.Layer.CornerRadius = 50;  //set the rounded corner
            Control.Layer.BorderColor = UIColor.Green.CGColor;
            Control.Layer.BorderWidth = 1;
        }
    }
 }
}

in Android
creat a xml file in the folder Resource->drawable image_view_style.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item>
   <shape
     android:shape="rectangle">
    <solid
      android:color="#00ff00" />
    <corners
      android:radius="50dp" />
    <stroke
      android:width="1dp"
      android:color="#00ff00" />
   </shape>
</item>

using Android.Support.V4.Content.Res;
using xxx;
using xxx.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(MyImage), typeof(MyImageRenderer))]
namespace xxx.Droid
{
 public class MyImageRenderer:ImageRenderer
 {
   public MyAndriodEntry(Context context):base(context)
    {

    }

    protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
    {
        base.OnElementChanged(e);

        if(Control!=null)
        {
           Control.SetBackgroundResource(Resource.Drawable.image_view_style);
        }

    }
  }
}

in Forms
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;

namespace xxx
{
 public class MyImage : Image
 {
    public MyImage()
    {

    }
 }
}


Convergence of a sequence of measures of sets implies convergence of the indicator functions.

Question: Let $\lambda$ be the lebesgue measure on the Borel sets. Suppose $\lambda(A) < \infty$
Is the following true? $\lambda(B_n) \uparrow \lambda (A), B_n \subseteq A \implies
 I_{B_n} \to I_A$ a.e.
I think it should be true. I cannot apply monotone convergence theorem because that would be the other implication.
I tried rewriting $\lambda(B_n) = \int I_{B_n}d\lambda$ and do something with that but that didn't work either.
Any hints?
Comment: Say $A=[0,1]$, $B_n=[0,1]-[a2^{-k}, (a+1)2^{-k}]$ where $k$ is the biggest integer with $2^k\leq n$ and $a=n-2^k$.
Comment: If $B_1\subset B_2\subset B_3\subset ...$ then this is true (a.e.). Otherwise you can have counterexamples.
Comment: Mind providing/referencing a counterexample? Or in the first place, why it is true when you have that chain of inclusions.
Comment: Thanks. And what about the case where $B_1 \subseteq B_2 \subseteq \dots$?
Comment: @Math_QED that is called the continuity of measure from below (and you could actually use MCT there)
Comment: The continuity of measure from below just implies that $\lambda(\bigcup_n B_n) = \lim_n \lambda(B_n) = \lambda(A)$. How does that help?
Comment: My bad, it actually may not be necessary. Suppose the conclusion weren't true in the nested case. Then $\lambda(A-B) >0$ where $B = \cup B_n$, a contradiction.
Comment: Thanks! Add this to your answer! Why exactly we have $\lambda(A - B) > 0?$ I also managed to show the result using monotone convergence theorem if they are nested.
Comment: Because the question changed (to $A$ being finite measure) @YuDing's example is more appropriate -- I can expand on that
Comment: Oh $\lambda(A-B) >0$ since if $\mathbb{1}_{B_n}$ doesn't converge almost everywhere to $\mathbb{1}_{A}$, then there is a positive-measure-set of nonconvergence.
Comment: Yes, the set $\{x \mid \neg(I_{B_n}(x) \to I_A(x))\}$ must have positive measure. Then still how $\lambda(A -B) > 0$?
Comment: This is because when $B_n$ are nested and contained in $A$, that positive measure set is exactly the same as the set $A-B$. If you integrate $1$ over that set, you get a positive number.
Answer: Take $B_n= [n,2n]$ and $A=(-\infty,\infty)$ to get a counterxample in the infinite case.
If you assume $A$ to be finite, construct a counterexample as follows. Let $A=[0,1]$
Step 1: Divide $A$ into halves. $B_1$ will be $[0,1/2]$, then $B_2$ will be $[1/2,1]$. Notice how each has measure 1/2.
Step 2: Divide $A$ into quarters. $B_3$,$B_4$,$B_5$ and $B_6$ will each have measure 3/4 by picking exactly three of these quarters.
Step 3: Divide $A$ into eighths. The next 8 $B_n$'s will be formed by choosing exactly seven of these eighths. These each have measure 7/8.
and so on... The measure of $B_n$ approaches 1. The indicators do not converge, since every point will be 0 infinitely often.


For what values of $\alpha >0$ and $\beta >0$ does the following series $\sum_{n=2}^\infty \frac{1}{n^{\alpha}(\log n)^{\beta}}$ converge?

Question: For what values of  $\alpha >0$ and $\beta >0$ does the following series $$\sum_{n=2}^\infty \frac{1}{n^{\alpha}(\log n)^{\beta}}$$ converge?
if $\alpha >1$ ,then limit comparison test  suggest that given series converge for any $\beta >0$
Also when $\alpha=1$ given series converge iff $\beta >1$ by integral test.
Is it correct ? Also what will happen when $0 <\alpha <1$
Any suggestions?Thanks
Comment: You are right. If $0<\alpha<1,$ you can still apply the limit comparison test (with $1/n$) to show that the series diverges.
Comment: Use [Cauchy Condensation test](https://en.wikipedia.org/wiki/Cauchy_condensation_test)
Answer: What you said until using integral test is correct.
If $0 \lt \alpha \lt 1$, then as
$(\log n)^\beta \lt n^{\frac{1-\alpha}{2}}$ for $n $ large enough, you get
$$\frac{1}{n^\alpha(\log n )^\beta} \ge \frac{1}{n^{\frac{1+\alpha}{2}}}.$$
Hence the series diverges as $\frac{1+\alpha}{2}\le 1$.


Including a PCL library DLL in a C++ winrt Project

Question: I created Portable Class Library that I want to use in various WinRT projects. I can use this PCL dll in C# Winrt Apps, VB WinRT Apps, silverlight and Windows Phone. But for some reason, I can't successfully add the library to my C++ project. The error that I get when I try this is:

Could not add a reference to file 'C:\Users\xyz\pqr.dll' because it is
  neither a .NET assembly nor a registered ActiveX control.

I saw the same question on SO earlier and the OP posted a solution that seems to work for him. I tried to find the following line as the original question suggested but I can't find it in the vcxproj file.
<code><TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</code>
Since I can't post a comment on the original question, I figured I should post another question here.
Any Ideas?
Edit:
My project setup looks something like this:

Lets assume that My PCL library is called A.dll.
My WinRT component is called B.winmd.
Now, B.winmd uses A.dll internally and creates a wrapper around it.

Now when I want to create a Store App C in C++, I have to add references to both A.dll and B.winmd in my project C. If I just include B.winmd, I get a runtime exception the first time something from A.dll is used. What am I doing wrong?
Answer: A C++ application does not know how to execute managed code.  If you want to create a library using C# and make it available to another runtime environment like C++ or Javascript then you have to create a Windows Runtime Component project.  Its public interface is limited to WinRT compatible types to allow the interop between runtime environments to work.  Lots of other little rules.
The MSDN starter page is here.
Comment: I wonder how many types in PCL are not compatible with WinRT. It would certainly be nice if these converged.
Comment: I agree.  But I think I am using the right subset of PCL because my winmd + dll setup works fine on C# and VB winrt apps but I can't get it to work on c++.
Comment: It doesn't matter that you use PCL.  The C++ code can only use WinRT types, it doesn't know beans about .NET types.  PCL is only interesting if you want your library to be used by managed code on other platforms (phone, xbox, etc).
Comment: Right, but WinRT projects .NET types from a .NET WinRT component to types that work in other languages. If a PCL component could be a WinRT component at the same time - you could use it in all flavors of .NET AND in WinRT.
Comment: hmm...  So is this an artificial restriction imposed by Visual Studio? When I copy the PCL library to the Debug\CppApp\AppX\ folder, the App start working as expected. I just don't know how to package my component so that the DLL reaches the appx folder.
Comment: @Filip - the language project works only one way.  The type system of WinRT is very simple, just COM with metadata annotations that allow a language projection to emulate features that COM doesn't have.  Like implementation inheritance and generics.  That cannot work the other way around, you cannot map a rich type system like .NET to  simple one like WinRT.  Which is why WRC classes must be sealed and cannot use generics and only use types that another runtime environment like C++ or Javascript has access to.  WinRT types.
Comment: OK, so these two can't easily be combined without forsaking some .NET features in a WinRT component, but they could make an even more portable PCL library that would work as a WinRT component if none of the features possible in PCL were exposed through WinRT, for example limiting generics to only be used internally in the library. I'm just a UI developer and I don't know too much about internals of the assemblies and ABIs, but it still sounds like something Microsoft could pull off.
Comment: You can already do all of those things without PCL.  Using generics is fine, as long as you don't make a generic type public and thus expose it to another runtime environment that doesn't know anything about generics.  Like C++ and Javascript.  PCL is a pure .NET platform detail.
Answer: Your message should be a good hint there - a PCL library is a .NET library. WinRT projects need WinRT components. You need to create a .NET-based WinRT component that will wrap your PCL library to make it usable in non-.NET languages.
Comment: I am not sure what you mean by "component that will wrap your PCL library to ...". I do have a Winrt component that uses the PCL library. But If I reference the winmd file without referencing the PCL dll then there are errors that show up.  Do I just need to copy the dll in the same directory as winmd file to make things work?
Comment: If you create a new Windows Store project in VS - one of the templates you will see is "Windows Runtime Component". I think you would need to reference your PCL library in that component and create a proxy type/method/member for each PCL symbol you want exposed to other WinRT languages.
Comment: I don't think I am understanding this properly. Lets assume that My PCL library is called A.dll. My WinRT component is called B.winmd. Now, B.winmd uses A.dll internally and creates a wrapper around it. Now when I want to create a Store App C, I have to add references to both A.dll and B.winmd in my project C. If I just include B.winmd, I get a runtime exception the first time something from A.dll is used. What am I doing wrong?
Comment: Sorry, I haven't done that before, so I am not sure. Personally I would simply include source projects for A and B in solution C. If you  want to use the binaries and want A to always be deployed with B - I think NuGet works only in .NET, but perhaps you could write a vsix like in [Tim Heuer's post](http://timheuer.com/blog/archive/2012/03/07/creating-custom-controls-for-metro-style-apps.aspx). Otherwise - you might just need to reference both to force them both to be deployed with your app.
Comment: Thanks again for being so patient. After my last post, I manually copied A.dll to the AppX directory of App C and once I do that the app works fine. So I don't think this is an issue about support not being present. I just need to figure out how to package it properly so that both A.dll and B.winmd are deployed together. (A.dll and B.winmd are supposed to be part of an SDK that I am working on and hence including the source in the same solution as C is not a solution for me.) Thanks again for your answers though!


Finish Setting Up For Android?

Question: So I am trying to install and setup to be an Android develop following this helpful video:
https://www.youtube.com/watch?v=VLUDui3VuGk
I got a few easily fixable errors then I got this one:
<code>arm-linux-androideabi-g++: error: C:\android-ndk-r12b-windows-x86_64\android-ndk-r12b\/toolchains/arm-linux-androideabi-4.9/prebuilt/windows-x86_64/lib/gcc/arm-linux-androideabi/4.9/libgcc.a: No such file or directory
Error: error running arm-linux-androideabi-g++ -olibApplicationMain-v7.so -frtti -nostdlib -std=c++11 -Wl,-shared,-Bsymbolic -Wl,--no-undefined -Wl,-z,noexecstack --sysroot=C:\android-ndk-r12b-windows-x86_64\android-ndk-r12b\/platforms/android-9/arch-arm -LC:\android-ndk-r12b-windows-x86_64\android-ndk-r12b\/platforms/android-9/arch-arm/usr/lib @obj/android-v7/all_objs C:\android-ndk-r12b-windows-x86_64\android-ndk-r12b\/sources/cxx-stl/gnu-libstdc++/4.9/libs/armeabi/libgnustl_static.a C:\android-ndk-r12b-windows-x86_64\android-ndk-r12b\/platforms/android-9/arch-arm/usr/lib/crtbegin_so.o C:\android-ndk-r12b-windows-x86_64\android-ndk-r12b\/toolchains/arm-linux-androideabi-4.9/prebuilt/windows-x86_64/lib/gcc/arm-linux-androideabi/4.9/libgcc.a C:\android-ndk-r12b-windows-x86_64\android-ndk-r12b\/platforms/android-9/arch-arm/usr/lib/libc.so C:\android-ndk-r12b-windows-x86_64\android-ndk-r12b\/platforms/android-9/arch-arm/usr/lib/libm.so -llog -ldl
Build halted with errors (haxelib.exe).
</code>
Okay fine. I thought. So another hour or so of downloads more. What's another? Then I got to THIS page:
https://developer.android.com/ndk/guides/standalone_toolchain.html
And I am absolutely lost and have no idea how to follow the instructions provided at all.
Can someone possibly walk me through this next step please?
Answer: Did you check if file available and search path where it placed

C:\android-ndk-r12b-windows-x86_64\android-ndk-r12b/toolchains/arm-linux-androideabi-4.9/prebuilt/windows-x86_64/lib/gcc/arm-linux-androideabi/4.9/libgcc.a
Comment: The file is there if that is what you mean.
Answer: Im install NDK and folder
/toolchains/arm-linux-androideabi-4.9/prebuilt/windows-x86_64/lib/gcc/arm-linux-androideabi/4.9.x/
has renamed to
/toolchains/arm-linux-androideabi-4.9/prebuilt/windows-x86_64/lib/gcc/arm-linux-androideabi/4.9/
and all works!!!
;-)
Answer: Copy folder 4.9.x to 4.9, solved my problem.
(Renaming was not enough for me: show me more linking errors... Other files need 4.9 and 4.9.x folder...)

Finish Setting Up For Android?


Display different shipping rate depening on taxonomy terms

Question: I would like to offer a different flat shipping to users depending on what taxonomy terms the product they have in their cart.
If a product tagged with "postage rate 1"  I would like to display shipping rate 1. If they have a product tagged with shipping rate 2 I would like to display shipping rate 2.
I would also like to if possible make it so that if the cart has items with each of the tags then one item shipping rate would win through (the most expensive one to cover costs I would think)
I have had a go with rules but I cannot figure out how to get the different shipping rates to display on taxonomy terms.  I do have the commerce rules extra module installed if that will peform part of the solution
Thank you for looking
Answer: I needed the exact thing for my webshop. Couldn't find it anywhere so a friend of mine made this module which works great!
https://drupal.org/project/commerce_taxonomy_conditions
On my site every product has either the taxonomy term 'letter' or 'package'
And then with that module you can add an extra condition to your shippingmethods to only use the products which that specific term.
If you are still in need for it then try it out :)