text:
Q: Facebook actions like spotify? I'm trying to understand actions and objects on facebook and im completely blown away by how spotify publishes actions with that format. How the heck do you customize the layout of a user's action like that?
As far as im concern, with facebook's lovely documentation, all you can do is  publish actions on a single line : (user A) -- (action) -- on -- (object) followed by a title and description.
How do you design html/css layout of a user's actions? Link? Attachment? I'm guessing you have to do some sort of "magic" on the description? Thanks!

A: Facebook's open Graph Tutorial does a decent job of explaining this but with the various options you have to scroll for a while to make it to the grouping part. In short, the individual actions you're familiar with combine together via "aggregations" which can be set to show a number of formats from lists to grids.
To set one of these up you must configure your Actions and Objects via the open graph settings first and then manually create an aggregation and a few defaults to fill in for preview purposes.
This will show up when a user authenticates your app for open graph and becomes customized to them as they start actually using said actions.
Now as for the play button option, that's something I assume is unique to their integration.
Documents at https://developers.facebook.com/docs/beta/opengraph/tutorial/


text:
Q: SimplePie RSS Not Getting pubDate I am using SimplePie RSS to aggregate 4 feeds and they are being sorted by the date (descending) and in the code it is set to echo out the pubDate but it is not showing it. It just prints a blank element.
For sanaties sake (as the code file is tens of lines long I have it in a *.txt file on my server which can be found here: http://feeds.powercastmedia.net/feeds.php.txt
I am completely lost.
Cheers!,
Phill

A: Try placing other information in the echo calls to ensure that those lines are actually being called, and that the output is being displayed in the expected manor -
<title><? echo "Title: ".$item->get_title(); ?></title>
<link><? echo "Permalink: ".$item->get_permalink(); ?></link>
<pubDate><? echo "PubDate: ".$item->get_date(); ?></pubDate>
<description><? echo "Description: ".$item->get_description(); ?></description>

This kind of "debug output" can help with debugging all sorts of things. It should help you figure out exactly where the problem is originating from.
Also, I noticed that you have numerous unnecessary PHP opening and closing tags, where multiple lines could be consolidated into a single, cleaner code block (Ex:)
<?php if ($success): ?>
<? $itemlimit=0; ?>
<?php foreach($feed->get_items() as $item): ?>
<? if ($itemlimit==10) { break; } ?>

Could be cleaned up to be:
<?php
if($success)
{
    $itemlimit = 0;
    $items = $feed->get_items(); // This might also help, as PHP sometimes has issues when iterating through arrays returned directly from functions
    foreach($items as $item)
    {
        if($itemlimit == 0) break;
...

In fact, most of the file could be within one pair of PHP tags.
Just a suggestion.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to access EF Core InMemory DB from SpecFlow test? My setup is this:

*

*I have a REST API written in .NET Core using Web API. It is fetching data from a SQL Server database using Entity Framework. It is setup so it wil use an Entity Framework In-Memory DB if the environment is "Test".

*I've created a SpecFlow test project in .NET Framework (as SpecFlow doesn't support .NET core yet).
My question is this:
How do I inject data in the API In-Memory DB from the SpecFlow Steps? Does the In-Memory DB have a Connection String that I can use to insert data, or is there some other way to do it?
I have the following Scenario (simplified):
Given the user 'JohnDoe' with rating '123' is exists
When I request the API with HTTP GET '/users/JohnDoe/rating'
Then I get the rating '123'

In the Given step I would like to put the user in the In-Memory DB so the API can find it and return it.


text:
Q: i have an unhandled exception in asp.net i am going to create a website and load a gis map to it.
i am using arcgis 10 and i created a web application in arcgis server 10
i created a new WebSit in visual studio 2010 and add a map resource manager.
add a MapResourceItem for this.
after that add a map control and set MapResourceManager property.
i config ArcGISIdentity too.
but unfortunately when i run application occurs this error

Error processing server request
[SoapException: Error processing server request]
     System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall) +4159
     System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) +328
     ESRI.ArcGIS.ADF.ArcGISServer.MapServerProxy.ComputeScale(MapDescription MapDescription, ImageDisplay MapImageDisplay) +117
     ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.MapFunctionality.GetScale(Envelope extent, Int32 mapWidth, Int32 mapHeight) +564
     ESRI.ArcGIS.ADF.Web.UI.WebControls.Map.get_Scale() +794
     ESRI.ArcGIS.ADF.Web.UI.WebControls.Map.setExtent(Envelope value, Boolean addSetExtentCallbackResult) +2556
     ESRI.ArcGIS.ADF.Web.UI.WebControls.Map.set_Extent(Envelope value) +39
     ESRI.ArcGIS.ADF.Web.UI.WebControls.Map.validatePrimaryMapResource() +2586
     ESRI.ArcGIS.ADF.Web.UI.WebControls.Map._OnLoad(EventArgs e) +115
     ESRI.ArcGIS.ADF.Web.UI.WebControls.Map.OnLoad(EventArgs e) +37
     System.Web.UI.Control.LoadRecursive() +134
     System.Web.UI.Control.LoadRecursive() +232
     System.Web.UI.Control.LoadRecursive() +232
     System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3412

A: copy your project in inetpub => wwwroot folder.wwwroot folder usually located in (C:\Inetpub\WWWRoot) .then build project


text:
Q: Creating an Array of JS objects from Firebase I am struggling with creating an array of object from firebase database.
I need to get an array like this:
see the console printscreen of an array
Instead Iam getting this: see the console printscreen of an array Iam getting when retrieving date from firebase
Here is the code Iam using to get the data:
function gotData(data) {
  //console.log(data.val());
  var mesta = data.val();
  var keys = Object.keys(mesta);
  //console.log(keys);
  for (var i = 0; i < keys.length; i++) {
    var k = keys[i];
    var nazevmesta = mesta[k].nazevmesta;
    var lat = mesta[k].lat;
    var lng = mesta[k].lng;
    var mesto = new Object();
    mesto.name = nazevmesta;
    mesto.lat = lat;
    mesto.lng = lng;

    var mestaz = new Array();
    mestaz.push(mesto);
    console.log(mestaz);

  }
}

I am trying to create the array at the very end.
Any help would be much appreciated.
Thanks

A: Create the mestaz array only once outside the loop not a new instance every iteration of the loop
var mestaz = []; /// create one array

for (var i = 0; i < keys.length; i++) {
  var k = keys[i];

  var mesto = {
    name: mesta[k].nazevmesta,
    lat: mesta[k].lat,
    lng: mesta[k].lng
  };

  // push each object to same array
  mestaz.push(mesto);

}

// log whole array after adding all of the elements in the loop
console.log(mestaz);


text:
Q: Use of the Well Ordering Principle in the proof of the Fundamental Theorem of Arithmetic Unlike a previous question that was closed on accounts of ambiguity, I perfectly understand the 'need' of the Well Ordering Principle in the proof of the Fundamental Theorem of Arithmetic. What I do not understand is which is the set on which the well ordering principle is applied? Is it the set of numbers that cannot be written as a product of primes? Is the step intuitive?
The link contains the PDF that can be referred to for details on the proof:
http://math.hawaii.edu/~lee/courses/fundamental.pdf

A: The set of natural numbers which do not have a unique prime factorisation is either empty or it isn't. If it isn't empty, the WOP applies, and there is a smallest such number, $N$.
Now, it's not a question of having or not having a prime factorisation. It's easy to prove that a number has a prime factorisation. Any simple, naive factorisation algorithm is entirely deterministic and conclusive.
The issue is whether there can be more than one factorisation. And assuming $N$ as defined above exists, with multiple distinct prime factorisations, we can use Euclid's lemma to find a strictly smaller such number, contradicting the definition of $N$.


text:
Q: xdebug_start_trace behaving strangely I'm trying to reduce my script memory usage even more. I am trying to make my script generate output with xdebug to analyse the memory usage. It's a CLI based script has shebang
#!/usr/local/bin/php -q
I pass a parameter to it and check it with
$argc > 1 && is_numeric( $argv[1] )
When I login to ssh and do ./script.php 90 and add this code,
if( $argv[1] == 90 ) {
       xdebug_start_trace('/var/www/html/logs/' . rand(1,9999999) );
}

I see the output file in the logs folder.
But when I put the xdebug_start_trace without the if statement in production script, no output file is created.
The script.php is called from another php file, placed in another folder, so I use absolute path in the filename and call it using exec and append &> /dev/null & to it, so it runs in the background.
This is driving me crazy! Help, guys!

A: Don't know why this occurred but I got an error
PHP Notice:  Function trace already started in /var/www/html/script.php on line 9 [Check "Edit" for info]
Although, there is no code that triggers this xdebug_start_trace();.
So I put xdebug_stop_trace(); before xdebug_start_trace();, everything works fine.
Strange.
Edit: I was getting the above error as I had set auto_trace to On in php.ini
Also, turns out that if you are append &> /dev/null & to the command, no xdebug log is generated. However, if I do &> /dev/null (notice the last & ), xdebug generates logs. This is probably related to custom output xdebug must be using internally. Not sure, though.

A: You mean ...
if( $argv[1] == 90 ) {
       xdebug_start_trace('/var/www/html/logs/' . rand(1,9999999) );
}

... leads to a trace-file and ...
xdebug_start_trace('/var/www/html/logs/' . rand(1,9999999) );

... just leaving out the condiional statement gives you none?
And well, I really cannot believe that the tracing starts out of no where ... so there has to be a function call somewhere. Given your description it seems like your setup is pretty messed up. So I don't think your problem is in any way related to XDebug, but this trace-phenomenon is just a random symptom you happend to notice.
Try to set up a scripting which is as simple as possible and still gives you this. Then post again what's going on, b/c your description is also pretty confusing IMHO.
Best
Raffael


text:
Q: How to export instance from Google Compute Engine to other clouds How Can I migrate instance from Google Compute Engine to other cloud like Amazon, Vsphere using java client API.

A: If you are running your stack in a Docker container, then you could move your docker image to the new provider if this provider also supports Docker.

A: You can use terraform.io to describe your infrastructure as code. It isn't possible to use the exact same syntax for different cloud providers, but it definitely is easy to migrate.
If I had to "migrate" instances, I would do that. About migrating the data (i.e. bucket), that's a different problem, and should be solved by mirroring, synchronizing, and shutting down the unused one after instance migration.


text:
Q: How to constructor-inject a string that is only known at runtime? (Windsor Castle) I have class that has dependency on string:
public class Person
{
    private readonly string _name;

    public Person(string name)
    {
        if (name == null) throw new ArgumentNullException("name");
        _name = name;
    }
}

This string 'name' is known only at runtime, eg. it is defined in configuration. So I have this interface that provides this string:
public interface IConfiguration
{
    string Name { get; }
}

Both types, Person and IConfiguration (with its implementation which is not important here) are registered with Windsor container.
Question: how can I tell WindsorCastle container that it should inject the Name property of IConfiguration to the constructor of Person class?
Caveat: I don't want to inject IConfiguration to Person class or use typed factories... the Person class must be simple and accept only string as parameter.

A: There are probably more ways to do this since Windsor is ridiculously flexible, but here are three off the top of my head:
Option 1:
If IConfiguration is a singleton or somehow can populate Name without any other assistance, you could do the following:
container.Register(Component.For<IConfiguration>().ImplementedBy<Configuration>());
container.Register(Component
    .For<Person>()
    .DynamicParameters((DynamicParametersDelegate)ResolvePersonName));

// This should be a private method in your bootstrapper
void ResolvePersonName(IKernel kernel, IDictionary parameters)
{
    parameters["name"] = kernel.Resolve<IConfiguration>().Name;
}

This method is invoked before resolving the Person, and is setting the name key/value pair to be the desired value.  Windsor then uses this dictionary to override any dependencies in the constructor.  I'd probably just make it a lambda to be terser:
    .DynamicParameters((k,p) => p["name"] = k.Resolve<IConfiguration>().Name));

Option 2:
If the Name value is actually defined in the applications settings file, Windsor has a built-in option for that:
container.Register(
    Component.For<Person>()
    .DependsOn(Dependency.OnAppSettingsValue("name", "configSettingKeyName")));

Option 3:
You say you don't want to use Typed Factories, but I think this is a reasonable siutation for using one.  It wouldn't complicate the Person class at all, but it would add a bit to the code creating the Person objects (people?).  Here's an example:
Define the factory interface:
public interface IPersonFactory
{
    Person Create(string name);
}

Then where you are creating your Person, inject the factory and use that instead:
public class PersonUser
{
    public Personuser(IConfiguration configuration, IPersonFactory personFactory)
    {
        Person person = personFactory.Create(configuration.Name);
    }
}

You'll have to add the facility and register the interface, but it's easy:
container.AddFacility<TypedFactoryFacility>();
container.Register(Component.For<IPersonFactory>().AsFactory());


text:
Q: Calculating force delivered by an EM wave on a cone
Question:
A parallel light beam of radiation intensity $I$ is incident on a solid right circular cone of height $H$ and radius $R$ as shown in figure. Calculate the net force experienced by the cone if, surface of cone is perfectly

*

*absorbing

*reflecting

As for an absorbing surface,
$$p = \frac Uc \Rightarrow F = \frac{dp}{dt} = \frac{IA_{||}}{c}$$
So, for the first case, $A_{||} = \pi R^2$, then
$$F=\frac{I\pi R^2}{c}$$
which was correct answer. The second part seems to be obvious as for a reflecting surface,
$$F=\frac{2I\pi R^2}{c}$$
However, this wasn't the given answer. Where am I wrong?

The correct answer to second part was,
$$F=\frac{2I\pi R^4}{c(R^2+H^2)}$$

A: The force from reflection is only exactly twice the force from absorption if the light rays retrace their original paths after reflection. In this situation, this isn't true - the direction of outgoing rays is different from the direction of incoming rays, and the force on any given point is going to be perpendicular to the surface at that point and related to the momentum change of the ray before and after reflection. Since the normal vectors to the surface don't all align, there's going to be some cancellation.


text:
Q: Пропадает соединение после подключения USB-модема Девайс: Мегафон модем  Huawei E1550.Соединение часто пропадает (случается как полное отключение модема, так и просто отсутствие пинга) примерно через 10-30 минут после подключения. Чтобы соединение восстановить, требуется вытащить модем и снова подключить.Под виндой всё работает отлично.Подключаюсь через изкоробочную тулзу (nm, кажется).Нашел команды для переключения режимов: AT^U2DIAG=0Но куда их вставлять, не имею понятия.
A: *
*Установка usb_modeswitch. Настройка 3G модема
*Настройка usb_modeswitch для подключения 3g модема


text:
Q: Converge in distribution to $\exp(-\frac{x^2}{2})$ I have been hard-pressed on how to show this discrete distribution converge in distribution $e^{-x^2/2}$.
"Let $X_m$ has the discrete distribution $P(X_m \ge n) = \prod_{i=2}^n\left(1 -\cfrac{i-1}{m}\right)$. Show that $\cfrac{X_m}{\sqrt{m}}$ converges in distribution to $X \sim P(X \ge x) = 1 - \exp(-x^2/2)$."
I can see the intuition that when m is large,  $$P(X_m \ge \sqrt{m}x) = \prod_{i=1}^{x\sqrt{m}}\left(1 -\cfrac{i-1}{m}\right) \approx \exp\left(-\sum_{i=2}^{x\sqrt{m}} \frac{i-1}{m}\right) \\=\exp\left( -\frac{(x\sqrt{m} -1)(x\sqrt{m})}{2m}\right) \to \exp\left(-\frac{x^2}{2}\right)$$ as $m \to \infty$. But how to to prove properly ?

A: Using the following estimate
$$|\log(1+x)-x|=\Bigl|\int_0^x\frac{dt}{1+t}-x\Bigr|
=\Bigl|\int_0^x\frac{t}{1+t}dt\Bigr|\le\frac{x^2}4,\quad \text{as} \quad |x|\le \frac12, $$
it is easy to get
$$\biggl|\sum_{i=1}^{x\sqrt{m}}\log\Bigl(1-\frac{i-1}m\Bigr)-\sum_{i=1}^{x\sqrt{m}}\Bigl(-\frac{i-1}{m}\Bigr)\biggr|\le \frac14\sum_{i=1}^{x\sqrt{m}}\frac{(i-1)^2}{m^2}\le \frac{x^3}{12\sqrt{m}},\quad
\text{as} \quad m>2x^2.
$$
Therefor, we have
$$ \lim_{m\to\infty}\sum_{i=1}^{x\sqrt{m}}\log\Bigl(1-\frac{i-1}m\Bigr)
=\lim_{m\to\infty}\sum_{i=1}^{x\sqrt{m}}\Bigl(-\frac{i-1}{m}\Bigr)=-\frac{x^2}{2}.
$$


text:
Q: LinQ group and sum two different type of lists and create Dictionary )
i have a question about grouping and sum two list of different types.
The situation:
i have a stock (we call it stockA) with a bucket, reference nr, pieces and more fields...
In stockB, we got just the reference nr and pieces
stockA
------
BucketNo [varchar(7)]
ReferenceNo [varchar(13)]
Productionpieces [int]

stockB
------
ReferenceNo [varchar(13)]
pieces [decimal(18,2)]

The data are coming with EF (that works fine !)
In my programm, i want to group and combine the reference nr, just into a dictionary (?).
At the runtime, i have to access a key very often. Get the pieces and subtract a value.
In my mind got a dictionary and at the runtime i want to access the key
dict[x].pieces -= 50;
The correct data coming with SQL with this statement:
SELECT REPLACE(ReferenceNo,' ','') as ReferenceNo,
    CONVERT(bigint,ISNULL(SUM(Pieces),0) + SNULL(SUM(Productionpieces ),0)) as Productionpieces
from stockA
    LEFT JOIN stockB on stockA.ReferenceNo = stockB.ReferenceNo
where ReferenceNo <> NULL
GROUP BY ReferenceNo

I have tried a couple of ways to get a KeyValuePair Object but at the runtime i got a same key exception, i guess i haven't joined the other tuple of data.
At the end of the story, i just want to combine two lists, sum and get keyvaluepairs!
Maybe you got a good example for me?

A: Best way is to put in datatable and then use linq on table.  See code below :
            SqlConnection conn = new SqlConnection();
            SqlDataAdapter adapter = new SqlDataAdapter("Your SQL Query", conn);

            DataTable dt = new DataTable();
            adapter.Fill(dt);

            Dictionary<string, long> dict = dt.AsEnumerable()
                .GroupBy(x => x.Field<string>("ReferenceNo"), y => y.Field<long>("Productionpieces"))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());


text:
Q: Odoo - two servers (and two databases) working as one Is it possible to have two separate servers that would have their own database. But those databases would share same data (synchronize with each other).
For example there is one Odoo server in one end of the world and another in another end of the world (I mean real world :)). Any change that happens in one server database would automatically be reflected in another server database and vise versa.
I read that there is possibility to use postgresql database replication. And there is this cascading replication (http://www.postgresql.org/docs/9.2/static/warm-standby.html#CASCADING-REPLICATION) feature, which in theory should work similarly.
Does anyone have done something similar and could share their knowledge how to successfully implement such thing. Or it's not really possible or not worth it?
P.S. our client wants such thing, so users (in one end of the world) could have better connection because server would be closer to them. But I wonder about lag between these database replications, because of the distance and would it really increase performance this way.


text:
Q: Password visivel Estou a construir um login em asp.net e quero que ao clicar na checkbox para mostrar a password ela seja mostrada.
Design página asp
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

<asp:Label ID="lbl_administracao" runat="server" Text="Login Administração"></asp:Label>

<asp:Label ID="lbl_utilizador" runat="server" Text="Nome Utilizador:"></asp:Label>

<asp:TextBox ID="txt_utilizador" runat="server" Width="230px"></asp:TextBox>

<asp:Label ID="lbl_password" runat="server" Text="Palavra-Passe:"></asp:Label>

<asp:TextBox ID="txt_password" TextMode="Password" runat="server" Width="230px"></asp:TextBox>

<asp:CheckBox ID="chbox_mostrarpassword" runat="server" Text="Mostrar Palavra-Passe" />

<asp:Button ID="bt_login" runat="server" Text="Iniciar Sessão" />

A: Tente colocar no  evento onchange do checkbox
<asp:CheckBox ID="chbox_mostrarpassword" runat="server"
 Text="Mostrar Palavra-Passe"
 onchange="document.getElementById('lbl_password').type = this.checked ? 'text' : 'password'" />

Referencias

Add Option to Show password


text:
Q: Weird results when splitting strings in VB.NET I was getting weird results when doing multiple splits on a string, so I decided to make a simple test to figure out what was going on
testString "1234567891011121314151617181920"
If I wanted to get whats between 10 to 20 in Javascript I would do this:
var results = testString.split("10")[1].split("20")[0]

Which would return 111213141516171819
However when I do this in VB I get 111
Split(testString,"10")(1).Split("20")(0)

It seems the 2nd split is only recognizing the first character no matter what I put.
So it's stopping when it finds the next "2" in the string, even "2abc" would have the same outcome even though that string doesn't even exist.

A: String.Split does not have an overload that takes only a String. The argument is a Char array or String array. Your string is probably being converted to a char array. Explicitly pass a string array like so:
testString.Split(New String() { "10" }, StringSplitOptions.None)

A: Vb treats the delimiter argument only as a single character.

A: Try wrapping the second split so it's fashioned like the first one, i.e.:
Split( Split(testString,"10")(1), "20" )(0)"

A: This is a tricky scenario that I have seen trip people up before, so I think it is worth a little more explanation than the other answers give. In your original format Split(testString,"10")(1).Split("20")(0), you are unknowingly using two DIFFERENT Split functions.
The first Split(testString,"10") is using the Microsoft.VisualBasic.Strings.Split function, which takes String type parameters.  http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.strings.split(v=vs.110).aspx
The second .Split("20")(0) is using System.String.Split method, which does not have an overload that takes a String parameter. http://msdn.microsoft.com/en-us/library/System.String.Split(v=vs.110).aspx
So what was happening is:

*

*Split(testString,"10") uses Microsoft.VisualBasic.Strings.Split, which
returns new String() {"123456789", "11121314151617181920"}

*(1) means get 1st position of the returned array, which is "11121314151617181920"

*"11121314151617181920".Split("20")(0) uses System.String.Split, and attempts to split on string separator "20"

*NOTE: The string "20" param gets implicitly converted to a char "2" because the only single parameter overload of String.Split has a signature of Public Function Split (ParamArray separator As Char()) As String().  The ParamArray parameter option allows you to pass a comma delimited list of values into the function, similar to how String.Format works with a dynamic # of replacement values.  http://msdn.microsoft.com/en-us/library/538f81ec.aspx

*Step 3 code becomes "11121314151617181920".Split(new Char() {CChar("20")})(0), which using literal values is "11121314151617181920".Split(new Char() {"2"c})(0).  The result is {"111", "13141516171819", "0"}.  Get the 0th position, returns "111".

So to avoid confusion, you should convert your code to use the same version of Split on both sides.
Either of the 2 examples below should work:
Example 1: Using Microsoft.VisualBasic.Strings.Split:
Split( Split(testString,"10")(1), "20" )(0)

Example 2: Using System.String.Split:
testString _
    .Split(New String() {"10"}, StringSplitOptions.None)(1) _
    .Split(New String() {"20"}, StringSplitOptions.None)(0)


text:
Q: Check if there are only specified Django template variables in a string I'm working on configurable email template and need to validate if only available_variables are used in the content. So if user put {{ apple }}, the form should return ValidationError('This variable is unavailable').
models.py:
email_content = models.TextField()

forms.py:
def clean_email_content(self):
     email_content = self.cleaned_data['email_content']
     available_variables = ['{{ company_name }}', '{{ user_name }}']
     required_variables = ['{{ company_name }}']
     for required_variable in required_variables:
        if not required_variable in email_content:
                raise forms.ValidationError("{} is required".format(required_variable))
     # how to check if there are only `available_variables` in the content?

TL;DR
email_content cannot contain other variables (strings that starts with {{ and ends with }}) than specified in available_variables
Should I use regex or can I validate this using some method from Django Template Engine?

A: You may want to use the template engine's lexer instead (nb: django 1.11 code, might need to be adapted if you use django 2.x):
from django.template import base
lexer = base.Lexer("{{ var_one }} is one {% if var_two %}{{ var_two|upper }} is two {% endif %}")
tokens = lexer.tokenize()
for t in tokens:
    if t.token_type == base.TOKEN_VAR:
        print("{}: {}".format(t, t.contents)

I leave it up to you to read the template.base code to find out other useful features...
Also in your validation method you definitly want to catch ALL errors at once (instead of raising as soon as you found an error) so the user can fix all errors at once (unless you really want to drive your users mad, that is).
And finally, as Gasanov suggests in his answer, you also want to use sets to find both missing required vars and illegal ones - this is much more efficient than doing sequential lookups.

A: We can use regex to find all tags from email_content. After that we convert them to set and substract all available_variables from it to find all incorrect ones. If any exists - we throw ValidationError.
Note that available_variables is set itself and contains just tags, without curly brackets.
Our regex checks for any numbers of spaces between brackets and tag, so your users shouldn't be able to cheat.
import re

def clean_email_content(self):
        email_content = self.cleaned_data['email_content']
        available_variables = {'company_name', 'user_name'}
        finds = re.findall(r"{{[ ]*(.*?)[ ]*}}", email_content)
        invalid_tags = set(finds) - available_variables
        if invalid_tags:
            raise forms.ValidationError(
                "Should not contain invalid tags: " + str(invalid_tags)
            )
        return email_content


text:
Q: Querying huge table in MySQL I have a table which has around 1 million rows (size on physical disk is nearly 8 GB since it has a text column) which takes a lot of time for any transaction. In particular for "select" it takes enormous time for e.g. it takes around 20 minutes for count query without any condition i.e., select count(*) from TestPerformance.
Table schema is:
Name : TestPerformance
Field       Type    Null    Key     Default     Extra

ID      int(11)     NO  PRI     null
TEXT        text        YES         null
CATEGORY    varchar(100)    YES     MUL     null
DDOMAIN     varchar(100)    YES         null
NETWORK     varchar(100)    YES         null
NODE        varchar(100)    YES         null
ENTITY      varchar(100)    YES     MUL     null
SEVERITY    int(11)     YES         null
TTIME       bigint(20)  YES         null
SOURCE      varchar(255)    NO  MUL     null
HELPURL     varchar(100)    YES         null
WEBNMS      varchar(100)    YES         null
GROUPNAME   varchar(100)    YES         null
OWNERNAME   varchar(25)     NO  PRI     null

and indexes are
Table           Non_unique  Key_name        Seq_in_index    Column_name
TestPerformance     0       PRIMARY         1       ID
TestPerformance     0       PRIMARY         2       OWNERNAME
TestPerformance     1       TestPerformance0_ndx    1       ID
TestPerformance     1       TestPerformance1_ndx    1       OWNERNAME
TestPerformance     1       TestPerformance_ndx     1       CATEGORY
TestPerformance     1       TestPerformance_ndx     2       SOURCE
TestPerformance     1       TestPerformance_ndx1    1       ENTITY
TestPerformance     1       TestPerformance_ndx2    1       SOURCE

I have tuned key_buffer size to 1 GB but nothing changed in performance.
How can I speed up transaction of this table without deleting any data?
I am not a DB expert. Kindly provide your suggestions to improve the performance of the table.

A:
How can I speed up transaction of this table without deleting any data?

1 million rows is not a lot of data. 8Gb is a sizable amount of data.
Move the text type column into a sperate table (with a 1:1 relationship). Reduce the size of those varchar tables to the minimum size needed to hold the data (or consider moving any you don't need for filtering to the other table).
Do you really need id and ownername for the primary key? I suspect id may unique. If so, lose TestPerformance0_ndx - it's redundant. Indeed, you should tart analysing your logs and seeing what indexes the DBMS actually needs to service the queries and amend the schema accordingly

A: Run EXPLAIN on your query (which you should post for us to see). This will help identify what indices your query is attempting to use and what columns are using a full table scan.
Also, don't do select count *, instead count your primary recid so it can just count using your index.


text:
Q: What is the origin of the factor of $-1/4$ in the Maxwell Lagrangian? I have seen numerous 'derivations' of the Maxwell Lagrangian,
$$\mathcal{L} ~=~ -\frac{1}{4}F_{\mu \nu}F^{\mu \nu},$$
but every one has sneakily inserted a factor of $-1/4$ without explaining why. The Euler-Lagrange equations are the same no matter what constant we put in front of the contraction of the field strength tensors, so why the factor of $-1/4$?

A: The interesting point is that with factor -1/4 $$ \mathcal L =-\frac 1 4 F_{\mu\nu}F^{\mu\nu}= \frac 1 2 (\mathbf E^2- \mathbf B^2)\;,  $$
From this we roughly have
$$\mathcal H =\frac 1 2 (\mathbf E^2+ \mathbf B^2)\;, $$
which consistence with the energy of the EM field$^{[1]}$
$$U=\frac 1 2 \int \big(  \epsilon_0 \mathbf E^2 + \frac 1 {\mu_0}\mathbf B^2 \big) d\tau \;.$$
References
[1] D.J. Griffiths, Introduction to electrodynamics Fourth Edition (See back materials)

A: Comments to the question:

*

*First it should be stressed, as OP does, that the Euler-Lagrange equations (= classical equations of motion = Maxwell's equations) are unaffected by scaling the action $S[A]$ with an overall (non-zero) constant. So classically, one may choose any overall normalization that one would like.

*As Frederic Brünner mentions a normalization of the $J^{\mu}A_{\mu}$ source term with a normalization constant $\pm N$ goes hand in hand with a $-\frac{N}{4}$ normalization of the $F_{\mu\nu}F^{\mu\nu}$ term. Here the signature of the Minkowski metric is $(\mp,\pm,\pm,\pm)$.

*Recall that the fundamental variables of the Lagrangian formulation are the $4$-gauge potential $A_{\mu}$. Here $A_{0}$ is a non-dynamical Lagrange multiplier. The dynamical variables of the theory are $A_1$, $A_2$, and $A_3$. The $$-\frac{1}{4}F_{\mu\nu}F^{\mu\nu}~=~\underbrace{\frac{1}{2} \sum_{i=1}^3\dot{A}_i\dot{A}_i}_{\text{kinetic term}}+\ldots$$ is just the standard $+\frac{1}{2}$ normalization of a kinetic term in field theory. In particular note that the kinetic term is positive definite in order not to break unitarity.

A: The factor is there so that once you add a source term, i.e. $J^\mu A_\mu, $ you get the correct equations of motion, namely Maxwell's equations:
$\partial_\nu F^{\mu\nu}=J^\mu.$
Furthermore, this convention produces the usual $1/2$ in front of the kinetic term of the gauge fields.


text:
Q: Run an action by name in Eclipse As much as I like to remember as many keyboard shortcuts as possible, there's always something I don't know how to do via a keyboard shortcut. Is there an Eclipse equivalent to M-x from Emacs or Find action by name from Intellij IDEA?

A: How about Ctrl+Shift+L which is the shortcut for Show Key Assist.
I use Ctrl+3 a lot, which is the shortcut for quick access popup, where you can type the name of any view, perspective or open editor to open/switch to that, or the name of an action to run it. By the way, you can see if your choose have a shortcut assigned when selecting.
Note: this is on Ubuntu, may be slightly different on a Mac.

A: Also you can try Quick Assist by pressing Ctrl+3


text:
Q: Parse Push: Subscribe Android app to more than one Parse app Is it possible to subscribe an Android app to more than one Parse app?
In Parse.com, I have 2 apps (with its own keys). I'm developing an Android app that needs "to be initialized" to these 2 Parse apps, to receive pushes from them. Something like:
Parse.initialize(context, PARSE_APP1_ID, PARSE_APP1_KEY);
Parse.initialize(context, PARSE_APP2_ID, PARSE_APP2_KEY);

Is this possible?
I want this beacuse one of these Parse app is a "general notifier" for all my apps, and the other one is the app concrete backend/notifier.
Thanks.

A: No, it's not possible.  The methods to interact with parse.com do not provide any way to specify which app to use, which means they can't target different apps.


text:
Q: Script wont launch on reboot or shutdown on Red Hat I have a script called "storelogs" located in /etc/init.d and I have link to this in /etc/rc0.d and /etc/rc6.d called "K01storelogs".
The script runs absolutely fine when I call it directly from /etc/init.d but when I try and reboot the machine, the script doesn't ever seem to get called.
The script actually calls a php script which does a few bits and peices - and like I said, the script runs fine when I call it directly.
The script is incredibly simple:
#!/bin/sh
/usr/bin/php /var/www/html/storeLogs.php

Have I missed a step? Whats an easy way to debug this?
Cheers in advance!
Andy

A: Are you sure the script is actually runing at startup ?
You can try to add something like logger "my script is ruuning" in the script in order to be sure.
Please check also with chkconfig tool if the startup links are ok for your runlevel

*

*runlevel

*"chkconfig --list"

A: Is your link called K01storelogs or S01storelogs?


text:
Q: Create an object by receiving a 2d coordinates array Hi my issue is the following, im receiving a 2d matrix and I already create a class named City, which will holds the position coordinate for x and y the values will come separated by commas like this
0,0
0,20
4,3
6,2
7,21

for (int k = 0; k < size; k++){
String valuesStrArr2[] = s.nextLine().split(",");
for (int l = 0; l < 2; l++){
    int coord = Integer.parseInt(valuesStrArr2[l]);
    System.out.println("cordinatesss:" + coord);
    City city = new City(coord,coord);
    TourManager.addCity(city);
    }
}

so "coord" is the value of the array, and when i print it, has the right values but when i create the the city it duplicates the values, how can i solve this? i know is a dumb question but im stucked here.
My constructor
// Constructs a city at chosen x, y location
public City(int x, int y){
    this.x = x;
    this.y = y;
}

A: You seem to be under the impression that coord will have two distinct values at the same point in time when you call new City(coord,coord). The variable will only have one value at that point which will be Integer.parseInt(valuesStrArr2[l]) This is causing you to have duplicate cities, one with the correct x coordinate and one with the correct y coordinate.
To fix this, try something like this:
NOTE: This code will not work for you because I have not accounted for coordinate values above 9 (this code only works if all values are 1 digit values) Showing you this is intended to help you find the answer yourself
String coordinates = "0, 0, 0, 20, 4, 3, 6, 2, 7, 21";

for (int k = 0; k < size; k += 2){ //This is to get every other value from the coordinates
        int x = Integer.parseInt(coordinates.charAt(k));
        int y = Integer.parseInt(coordinates.charAt(k+1));
        System.out.println("cordinatesss:" + x + ", " + y);
        City city = new City(x, y);
        TourManager.addCity(city);
}

A: @Glen hit it on the nail. Within your second for loop you fill the coord integer variable on the first (of 2) iteration and then supply that value to both x and y of City in the very same iteration. You do the same thing within the second iteration. You're actually supplying twice as many Cities than you should by doing this.
Since your 2D Array has so few columns, you really don't need the inner for loop. You can do the whole thing with one loop and it will most likely be more readable:
for (int k = 0; k < size; k++) {
    String valuesStrArr2[] = s.nextLine().split(",");
    int coord1 = Integer.parseInt(valuesStrArr2[0]);
    int coord2 = Integer.parseInt(valuesStrArr2[1]);
    City city = new City(coord1, coord2);
    TourManager.addCity(city);
}


text:
Q: is there a method on how to count the longest substring or sublist that are the same when mirrored so i need to find whats the longest sublist that can be mirrored, knowing the number of element
ex:
n = 5
my_list = [1,2,3,2,1]

heres my code:
n = int(input())
my_list = list(map(int, input().split()))
c = 0
s1 = my_list
x = 0
i = 0
while i < n:
    s2 = s1[i:]
    if s2 == s2[::-1]:
        if c <= len(s2):
            c = len(s2)
    if i >= n-1:
        i = 0
        n = n - 1
        s1 = s1[:-1]
    i += 1
print(c)

as we see the list is the same when mirrored, but when n = 10 and my_list = [1,2,3,2,1,332,6597,6416,614,31] the result is 3 instead of the expected 5.

A: My solution would be splitting the array in each iteration into a left and a right array, and then reversing the left array.
Next, compare each element from each array and increment the length variable by one while the elements are the same.
def longest_subarr(a):
    longest_exclude = 0
    for i in range(1, len(a) - 1):
        # this excludes a[i] as the root
        left = a[:i][::-1]
        # this also excludes a[i], needs to consider this in calculation later
        right = a[i + 1:]

        max_length = min(len(left), len(right))
        length = 0

        while(length < max_length and left[length] == right[length]):
            length += 1
        longest_exclude = max(longest_exclude, length)
    # times 2 because the current longest is for the half of the array
    # plus 1 to include to root
    longest_exclude = longest_exclude * 2 + 1

    longest_include = 0
    for i in range(1, len(a)):
        # this excludes a[i] as the root
        left = a[:i][::-1]
        # this includes a[i]
        right = a[i:]

        max_length = min(len(left), len(right))
        length = 0

        while(length < max_length and left[length] == right[length]):
            length += 1
        longest_include = max(longest_include, length)
    # times 2 because the current longest is for the half of the array
    longest_include *= 2

    return max(longest_exclude, longest_include)

print(longest_subarr([1, 4, 3, 5, 3, 4, 1]))
print(longest_subarr([1, 4, 3, 5, 5, 3, 4, 1]))
print(longest_subarr([1, 3, 2, 2, 1]))

This covers test case for odd-length sub-array like [a, b, a] and even-length sub-array [a, b, b, a].

A: Since you need the longest sequence that can be mirrored, here is a simple O(n^2) approach for this.
Go to each index, consider it as the center, and expand towards both left and right, one step at a time, if the numbers are equal. Or else break, and move onto the next index.
def longest_mirror(my_array):
    maxLength = 1

    start = 0
    length = len(my_array)

    low = 0
    high = 0

    # One by one consider every character as center point of mirrored subarray
    for i in range(1, length):
    # checking for even length subarrays
        low = i - 1
        high = i
        while low >= 0 and high < length and my_array[low] == my_array[high]:
            if high - low + 1 > maxLength:
                start = low
                maxLength = high - low + 1
            low -= 1
            high += 1

        # checking for even length subarrays
        low = i - 1
        high = i + 1
        while low >= 0 and high < length and my_array[low] == my_array[high]:
            if high - low + 1 > maxLength:
                start = low
                maxLength = high - low + 1
            low -= 1
            high += 1

    return maxLength


text:
Q: Use JSON file as value when inserting to MongoDB I have a bunch of JSON files (say a.json, b.json, c.json). I know I can import each of them into a MongoDB collection using
mongoimport -d db -c collection --file x.json --jsonArray

And my collection will contain the three jsons. But I'd like to have the jsons be the values to keys which identify them. That is, instead of having my collection contain the following:
a.json, b.json, c.json

I'd like:
{ "a" : a.json }, { "b" : b.json }, { "c" : c.json }

Is there some functionality in Mongo's insert() method like:
    db.collection.insert( { "a" : a.json } ) ?

A: You can use jq JSON parser to merge your 3 files with the required format and then import it with mongoimport :
jq -s '{"a":.[0],"b":.[1],"c":.[2] }' a.json b.json c.json

Btw, it will work even if your json files have different root element (json object or array). The result will be like :
{
  "a": [
    {
      "field": "2"
    },
    {
      "field": "5"
    }
  ],
  "b": [
    {
      "field": "2"
    },
    {
      "field": "1"
    }
  ],
  "c": [
    {
      "field": "3"
    },
    {
      "field": "2"
    }
  ]
}

You can store this into a new json file and then import it into mongoDB :
jq -s '{"a":.[0],"b":.[1],"c":.[2] }' a.json b.json c.json > input.json

mongoimport -d db -c testDB --file input.json

The result would be :
{ "_id" : ObjectId("58b2fa56fa97671e9876afa8"), "a" : [ { "field" : "2" }, { "field" : "5" } ], "b" : [ { "field" : "2" }, { "field" : "1" } ], "c" : [ { "field" : "3" }, { "field" : "2" } ] }


text:
Q: Measuring Apache request processing times I want to measure performance of my server. The architecture is Apache2 talking to Tomcat over mod_jk. Requests are over HTTPS with mutual authentication. The client does not reuse connections, therefore I believe a new SSL session is established for each transaction.
If I configure Apache to log %D in mod_log_config, does that duration include the time spent doing SSL, including the TLS handshake? If not, how do I measure that part of the transaction?

A: You can try doing some stress test with JMeter for an end to end test. Also enable some monitoring options in Tomcat like jmxremote.

A: Clearly no,
Apache Httpd (tested on 2.2) does not include the time of the TLS handshake, which means he also doesn't include the TCP handshake either.
The Tomcat %D (tested on version 8) behaves the same as Apache Httpd, which is unfortunate for us as well.
This means the only simple way of monitoring in production the impact of TLS, is from the client side.
If you just need to check session reuse once, you can also use Wireshark on the client or server side.


text:
Q: Where is my Algolia Account Secret and its key? I am using template (Full-text search via Algolia) in Firebase Function.
See here
At the end of this link you will see > setting up the sample
Here it asks for algolia secret account and key. I have created account at Algolia when I go to my dashboard and select API KEYS then there are many keys.
Unable to know which one is account secret and which one is used as a key?
Please Indicate me secret account and key

A: The key is the id of your Algolia application.
The secret needs to be an API key that has read and write access (since the functions are doing both indexing and search). That can be your Admin API key or a specific API key you create with these permissions.

A: I believe the "secret" is what we call the "Admin API key" in the dashboard and the key must be the "search only api key".


text:
Q: UIView center X UIImageView In one UIVIew i have 5 icon (UIImageView). I show/hide icons. Its ok. But i want if i hide 2 icon the rest what not hidden (or not removed) show center of the View.
if show all:
http://sherad.info/elotte.jpg
I remove from view 2 icon (i try the set hiden but the effect same)
[share removeFromSuperview];
[sms removeFromSuperview];
After this:
http://sherad.info/utana.jpg
I want the 3 icon show in center of view. So somehow re arrange the icons inside the UIView.  How i can solved this?
thx.

A: I'll assume the black area behind the icons is a UIView and the icons have been added to it in a static position? What if, instead, you created a second UIView that was transparent. Determine what icons you want to display and add them into the second view. It would start off with the second view being the exact same size as the first view, but once you want to display less, remove all the icons from the second view
for (yourIcon *icon in [secondView subviews]) {
    [icon removeFromSuperview];
}

reset the frame of the second view to be the length you want and re-add the icons, then place it in the center of the first view
secondView.center = firstView.center;

and either do
[secondView setNeedsDisplay]

or re-add it as a subview of firstView if you previously removed it (which I don't believe is necessary).

A: The subviews should position themselves relative to each other based on how many other icons there are. Every time there is an event that add or removes an icon you should call some layout code that will make the icons postion themselves.
Removing a view should have the superview count the added subviews, create new x coordinates based on the screen width divided by the count and then set the frames of all of the subviews.
There is probably a way to do this with autolayout but I'm not familiar with those methods.


text:
Q: select only some of the rows of a dataframe I have a pandas dataframe with some info. I know how to select a certain row of the dataframe.
However, I would like to select several of the rows of the dataframe into another dataframe under the following conditions:

*

*I don't know how many rows there are

*I have to select the first and then in an interval.

For example if I have
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
                   'B': 'one one two three two two one three'.split(),
                   'C': np.arange(8), 'D': np.arange(8) * 2})

print(df)

I have
     A      B  C   D
0  foo    one  0   0
1  bar    one  1   2
2  foo    two  2   4
3  bar  three  3   6
4  foo    two  4   8
5  bar    two  5  10
6  foo    one  6  12
7  foo  three  7  14

I would like to obtain with an interval of 4
     A      B  C   D
0  foo    one  0   0
4  foo    two  4   8

or if the interval is 3
     A      B  C   D
0  foo    one  0   0
3  bar  three  3   6
6  foo    one  6  12

A: Use loc with a slice as you would do for an iterable:
df.loc[::4]

     A    B  C  D
0  foo  one  0  0
4  foo  two  4  8

df.loc[::3]

     A      B  C   D
0  foo    one  0   0
3  bar  three  3   6
6  foo    one  6  12

NB. You can also use df[::4]/df[::3], but loc is more versatile (for example for columns: df.loc[:,::3]).


text:
Q: CoreData autosaving and not loading all data after autosave I have an NSPersistentDocument subclass using NSManagedObject subclasses for my data.
When a new document is opened, I do some initializing of data structures (trivial amount of populating fields). What I've noticed is that the Untitled document gets autosaved, and when the application re-opens, that document gets loaded. If the application quits, the user doesn't (by default) get prompted with the save dialog. If the window closes, the user does.
First question:
I want to call up the save dialog when the user quits the application. I don't want this Untitled document hanging around (under normal circumstances). I either want it saved or trashed.
I attempted to fill out:
- (void)applicationWillTerminate:(NSNotification *)aNotification

In order to trigger the document to be saved. Calling save: on the context at this point gives an error. From what I can tell, this is because the user hasn't yet saved the file on their own.  In addition, calling [self close]; or [[self windowForSheet] close]; close the window without saving.
How can I force the save dialog to come up? How can I trash the untitled document?
Second question (no, I can't count):
Since when the application starts, there may or may not be an Untitled document to deal with, I'm trying to keep track of the state in another model. I've already found that the initial data (to which I referred earlier) is present when the Untitled document came up. My other model has some metadata, including a success flag/state for the populated data. Once the populated data is all in place and correct, the state indicates as such. Unfortunately, while my populated data is being loaded when the app starts with a pre-existing Untitled document, the metadata class is not.
Please excuse the roughness of the code, at this point, I'm mucking it up until I can see that it's working how I want before I polish it back off:
- (bool) createGameState {
  NSEntityDescription* description = [NSEntityDescription entityForName:[GameState name] inManagedObjectContext:[self managedObjectContext]];
  NSFetchRequest* req = [[NSFetchRequest alloc] init];
  [req setEntity:description];

  NSError *error = nil;
  NSArray *array = [[self managedObjectContext] executeFetchRequest:req error:&error];
  [req release];
  req = nil;

  GameState* result = nil;
  if (array) {
    NSUInteger count = [array count];
    if (!count) {
      // Create the new GameState.
      DebugLog(@"Creating GameState");
      result = [NSEntityDescription insertNewObjectForEntityForName:[GameState name] inManagedObjectContext:[self managedObjectContext]];
      [result setIsLoaded:[NSNumber numberWithBool:NO]];
    } else {
      if (count > 1) {
        NSLog(@"WARNING: Potentially Corrupt Game State. found: %lu", count);
      }
      result = [array objectAtIndex:0];
      if ([result isLoaded]) {
        [self variantLoaded];
      } else {
        // In this case, we have an aborted set-up. Since the game isn't
        // playable, just refuse to create the GameState. This will
        // force the user to create a new game.
        return NO;
      }
    }
  } else {
    DebugLog(@"error: %@", error);
  }

  [game setState:result];
  return result;
}

Note that array is always present, and count is always zero. No, I'm not explicitly calling save: anywhere. I'm relying on the standard auto-save, or the user performing a save.
EDIT:
I installed the Core Data Editor app. It turns out the issue isn't on saving the data, but on loading it. (Note: Due to another issue, the app saves as binary when instructed to save as XML, which causes much head banging.)
I've broken it down to the simplest code, which should pick up all objects of type GameState in an array. It retrieves none, despite there clearly being objects of the appropriate type in the saved file:
  NSManagedObjectContext* moc = [self managedObjectContext];
  NSEntityDescription* entity = [NSEntityDescription entityForName:@"GameState" inManagedObjectContext:moc];

  NSFetchRequest* req = [[NSFetchRequest alloc] init];
  [req setEntity:entity];

  NSError *error = nil;
  NSArray *array = [moc executeFetchRequest:req error:&error];

Array is not null, but [array count] is 0.
At this point, I'm guessing it's something simple that I'm overlooking.
Second EDIT:
I added -com.apple.CoreData.SQLDebug 5 and saved as SQLite. The call to executeFetchRequest does not generate any debug logs. I do see the INSERT INTO ZGAMESTATE entry show up in the logs. It seems that executeFetchRequest is not getting passed to the backend.
Third EDIT (this one burns):
I created a new xcode project, using core data (as I had with the other). I copied just this one function (stubbing where necessary) and plopped a call to it in windowControllerDidLoadNib. In this new project, the code above works.

A: Found the problem.
I errantly was loading objects in Document's - (id) init call. Moved to windowControllerDidLoadNib (which is what I did in the test version) and it worked fine.


text:
Q: Get a specific node by its ID? This sound too dumb to ask but I'm not able to figure out how to get a specific node whose ID is, say, 15
these are what I've tried
match (n) where n.id=15 return n

MATCH (n { id:15 }) return n

A: You should use the ID function, that is to say:
WHERE ID(n) = 15

A: use the node function also:
START n=node(12)
RETURN n.name
Lot's of good examples here: http://docs.neo4j.org/refcard/2.0/


text:
Q: Spring Data Neo4j SDN 4 Auditing Support I'm trying to setup simple entity audit fields using Spring Data with the annotations from spring-data-commons (e.g. @CreatedDate with type Long as mentioned here http://docs.spring.io/spring-data/commons/docs/current/reference/html/#auditing.annotations)
A solution for Neo4j 2.0 was discussed here: Audits with Spring Data Neo4j. But for version 4, the class seem to have disappeared in the distribution.
I'm assuming an event listener must be added to Neo4j in order for these fields to populate. However I can't find the neo4j counterpart of @EnableMongoAuditing (MongoDB) and @EnableJpaAuditing (JPA) anywhere in the spring-data-neo4j distro.
Does this mean that I have to ignore this particular Spring Data feature on Neo4j? Are there other alternatives?

A: @Polyakoff SDN 4 currently does not support annotations from the commons library. To solve this, I had to create a Spring bean listening to the before save event as follows:
@Bean
ApplicationListener<BeforeSaveEvent> beforeSaveEventApplicationListener() {
    return new ApplicationListener<BeforeSaveEvent>() {
        @Override
        public void onApplicationEvent(BeforeSaveEvent event) {
               event.getEntity().setCreatedDate(System.currentTimeMillis());
        }
    };
}


text:
Q: Irreducible components: associativity for intersections? Let $A$, $B$, $C$ be closed irreducible subvarieties of $\mathbb{A}^n$. Let $V_1$ be an irreducible component of $B\cap C$, and $V$ an irreducible component of $A\cap V_1$. Must there
necessarily be an irreducible component $W_1$ of $A\cap B$ such that $V$ equals some irreducible component of $W_1\cap C$?

A: No.
This is an example with irreducible (and nonsingular) $A,B,C$: Consider $\mathbb{A}^4$ with coordinates $(w,x, y, z)$. Let $B$ be the $(x,y)$-plane (i.e. the set $w = z = 0$), $C$ be the hypersurface $z = xy$, and $A$ be the $(y,z)$-plane. Then $B \cap C$ is the union of the "$x$-axis" and "$y$-axis". Let $V_1$ be "$x$-axis" and $V$ be the origin, which is the only irreducible component of $A \cap V_1$. Since $A \cap B$ is the "$y$-axis", which is irreducible, the only possibility for $W_1$ is $y$-axis. But $W_1 \cap C = W_1 \neq V$.
Note that each of $A, B, C$ is isomorphic to $\mathbb{A}^k$ (for an appropriate $k$).
 Original Example: Consider $\mathbb{A}^4$ with coordinates $(w,x, y, z)$. Let $B$ be the $(x,y)$-plane (i.e. the set $w = z = 0$), $C$ be the union of the $(w,x)$-plane and the $(w,y)$-plane and $A$ be the $(y,z)$-plane. Then $B \cap C$ is the union of the "$x$-axis" and "$y$-axis", whereas $A \cap B = A \cap C = A \cap B \cap C$ is the "$y$-axis", so that the property fails with $V_1$ equal to the "$x$-axis".

A: To give more context for possible answers: at the very least, a counterexample exists if we drop the assumption that $A,B,C$ be all irreducible (arisen in conversations with Harald). In $\mathbb{A}^{5}$, take
\begin{align*}
A & =\{x_{4}=0,x_{3}^{2}-x_{5}-1=0\}, \\
B & =\{x_{5}=0\}, \\
C & =\{x_{1}^{2}-x_{2}^{2}x_{3}^{2}=0,x_{1}-x_{2}x_{3}+x_{4}=0\}, \\
V_{1} & =\{x_{1}+x_{2}x_{3}=0,-2x_{2}x_{3}+x_{4}=0,x_{5}=0\}, \\
V & =\{x_{1}=x_{2}=x_{4}=x_{5}=0,x_{3}=1\}.
\end{align*}
Then the two candidates for $W_{1}$ are $W_{1}=\{x_{4}=x_{5}=0,x_{3}=1\}$ and $W_{1}=\{x_{4}=x_{5}=0,x_{3}=-1\}$: the second one does not contain $V$, while the first one gives
\begin{equation*}
W_{1}\cap C=\{x_{1}-x_{2}=0,x_{3}=1,x_{4}=x_{5}=0\},
\end{equation*}
which is irreducible already. In this example, $A,B$ are irreducible but $C$ is not.

A: Let $A \cap B = \cup W_i$, where $W_i$ are the irreducible components.
Then
$$
A \cap B \cap C = (\cup W_i) \cap C = \cup (W_i \cap C).
$$
Assume that $W_i \cap C = \cup Z_{i,j}$, where $Z_{i,j}$ are the irreducible components. Then
$$
A \cap B \cap C  = \cup Z_{i,j}.
$$
In particular, the irreducible component $V$ is the union of some $Z_{i,j}$.
But every $Z_{i,j}$ is closed in $A \cap B \cap C$, hence, irreducibility of $V$
imples that $V = Z_{i,j}$ for some $i$ and $j$. Then the component $W_i$ is the one you need.


text:
Q: Error al insertar datos en tabla, registro duplicado saludos. Soy nueva por aquí, mi problema es el siguiente. Mi script esta realizando una inserción duplicada a la bd después de ejecutarse por primera vez.
Ejemplo: Primera inserción: bien, inserta 1 sola vez el registro.
Segunda inserción (esta se realiza luego de hacer un .load() de ajax a la sección en la que muestro los datos): inserta dos veces el mismo registro.
Tercera inserción: inserta 3 veces el mismo registro, y así sucesivamente.
La funcionalidad es que luego de insertar el comentario, hacer un .load() a la sección de los comentarios para ver el nuevo comentario, y si se quiere volver a insertar otro pues me permita hacerlo, y aquí esta el problema, después del primer insert, realiza los demás insert duplicados.
Estas son mis funciones:
AJAX:
jQuery(document).on('submit','#comment_form',function(event){
    event.preventDefault();
    if($("#comment").val()=="" || $("#n").val()==""){
        $("#alert").html('Fill the fields');
    }else if($("#comment").val().length > 300){
        $("#alert").html('We allow 300 characters maximum for a comment');
    }else if(!expr.test($("#n").val())){
        $("#alert").html('Write a correct name');
    } else {
        jQuery.ajax({
            data: $(this).serialize(),
            type: 'POST',
            dataType:'json',
            url:'core/bin/goComent.php',
            beforeSend: function(){
                $("#submit").attr("disabled","disabled");
                $("#submit").val("Sending");
            }
        })

        .done(function(json){
            console.log(json);
            if(json.success == true){
                setTimeout(function(){
                    $("#commentss").load("core/viewsComments.php").fadeIn('slow');
                },1000);
                $("#submit").removeAttr("disabled");
                $("#submit").val("Post Comment");
                $("#n").val("");
                $("#comment").val("");
                return false;
            } else {
                $("#alert").html(json);
            }
        })
    }
});

PHP:
<?php
  if($_POST){
  $jsondata = array();
  $comment = strip_tags($_POST['comment']);
  $name = strip_tags($_POST['n']);
  $url = $_POST['url'];
   if(empty($url)){
     $url = $_SERVER["HTTP_HOST"];
   }
   if(!empty($name) or !empty($comment)){
     require('../clases/classConexion.php');
     include '../libs/geoIP/geoiploc.php';
     $db = new Conexion();
     $ip = $_SERVER["REMOTE_ADDR"];
     //$pais = getCountryFromIP($ip,'name');
     $sql = $db->prepare("INSERT INTO comentarios(nombre,comentario,ip,url,date_)VALUES(?,?,?,?,NOW())");
    if($sql->execute(array($name,$comment,$ip,$url))){
        $jsondata['success'] = true;
    } else {
        $jsondata['success'] = false;
        $jsondata['msj'] = $sql->errorInfo()[2];
    }
   } else {
    echo '<script>alert("Empty Data, NO");</script>';
   }
   } else {
     echo '<script>alert("You can not enter here");</script>';
   }
   header('Content-type: application/json; charset=utf-8');
   echo json_encode($jsondata);
   exit();
?>

No he conseguido el porque de este problema! Reviso y reviso y no doy con el error.


text:
Q: Show all months in date range even when no results are present in select I have the below query with a date range between '09/01/16' and '12/30/16'. In the attached picture results are only for September and October, I would like to still show November and December (or to the given date2 range) with a count of 0
How can I accomplish this?

declare @date1 date = '09/01/16'
declare @date2 date = '12/30/16'

select
    count(distinct w.wkid) as WksCount
    ,DATENAME(MONTH, r.date) as [month]
    ,year(r.date) as [year]
from
    Workshop w
    left join Reservation r on r.wkid=w.wkid
    left join Registration reg on reg.wkid=w.wkid
where
    r.date between @date1 and @date2
group by
    DatePart(Month, r.date)
    ,DateName(Month, r.date)
    ,year(r.date)
order by
    year(r.date)
    ,DatePart(Month, r.date)

I

A: In a slightly different - and I think easier to read and understand - approach, you can build your Dates table with a CTE and join from that to get your full list of months.
I have specified the Month Start and the Month End in my cte so that you can join from it without having to resort to functions in your on criteria which can be a performance hit if your Workshop table is large as the functions will prohibit index utilisation.
If your r.date field is a datetime, you will need to adjust the below to handle values up to the last millisecond of the last day of the month:
declare @date1 date = '20160801';
declare @date2 date = '20161231';

with Dates
as
(
    select dateadd(m,datediff(m,0,@date1),0) as MonthStart
            ,dateadd(d,-1,dateadd(m,datediff(m,0,@date1)+1,0)) as MonthEnd

    union all

    select dateadd(m,1,MonthStart)
            ,dateadd(d,-1,dateadd(m,2,MonthStart))
    from Dates
    where MonthStart < dateadd(m,datediff(m,0,@date2),0)
)
select
    count(distinct w.wkid) as WksCount
    ,DATENAME(MONTH, d.MonthStart) as [month]
    ,year(d.MonthStart) as [year]
from Dates d
    left join Reservation r on r.date between d.MonthStart and d.MonthEnd
        and r.date between @date1 and @date2
    left join Workshop w on r.wkid=w.wkid
    left join Registration reg on reg.wkid=w.wkid
group by
    DatePart(Month, r.date)
    ,DateName(Month, r.date)
    ,year(r.date)
order by
    year(r.date)
    ,DatePart(Month, r.date);

A: Here is the jist of what Sean Lange suggested.
1: A tally table is first built.
2: Then, the tally table is used with left join to fetch all month between dates and you data linked to proper month. (Min and max are included in my code sample)
So month without data will only have one record with null in every column  except the month number.
Now to have the month name instead of the month number, see this question to know how.
P.S : The month number is Tally.N
declare @date1 date = '09/01/16'
declare @date2 date = '12/30/16'

--1: Build a tally table with CTE
;WITH
N0(_)            AS (SELECT NULL UNION ALL SELECT NULL),
N1(_)            AS (SELECT NULL FROM N0 AS L CROSS JOIN N0 AS R),
Tally            AS (SELECT N = ROW_NUMBER() OVER (ORDER BY (SELECT NULL))  FROM N1 AS L CROSS JOIN N1 AS R)

--2: Select data using the tally
select
    count(distinct w.wkid) as WksCount
    ,Tally.N as [monthNo]
from Tally,
LEFT JOIN Reservation   AS r    ON Tally.N = DATEPART(MONTH, r.date)
                                AND r.date >= @date1
                                AND r.daye <= @date2
LEFT JOIN Workshop      AS w    ON r.wkid = w.wkid
left join Registration  AS reg  ON w.wkid = reg.wkid
WHERE Tally.N >= DATEPART(MONTH, @date1)
AND  Tally.N <= DATEPART(MONTH, @date2)
GROUP BY
    Tally.N --N is the month number
ORDER BY
    Tally.N

A: For not very big result tables using a table variable as a "base table" much easier:
--add these lines before your select
declare @d datetime set @d=@date1
declare @t table(count int, month varchar(12), year int)
--fill the table with 0-month-year values
while @d < @date2
begin
    insert into @t values(0, datename(mm, @d), datepart(yy, @d))
    set @d = dateadd(mm, 1, @d)
end

then add your results to the table variable:
insert into @t
select count(distinct w.wkid)
    ,DATENAME(MONTH, r.date)
    ,year(r.date)
from Workshop w
    left join Reservation r on r.wkid=w.wkid
    left join Registration reg on reg.wkid=w.wkid
where r.date between @date1 and @date2
group by DatePart(Month, r.date) ,DateName(Month, r.date), year(r.date)

and finally get required result:
select sum(count) as count, month, year from @t
    group by year, month
    order by year desc, month desc

Aggregate query from relatively little table variable is much more cheap then one more LEFT JOIN. If you have a lot of periods, consider using of #temporary table.
Sorry, I haven't MSSqlServer installed right now to check my code, but the idea is quite simple.


text:
Q: Pearson's correlation for time series requires normally distributed data? In order to use Pearson's correlation to measure the similarity  of two time series, is  normal distribution of both time series a necessary condition?

A: Several questions are bundled together here:

*

*Pearson correlation measures linearity of relationship, not similarity of values. $y$ and $a + by$ have correlation $+1$ for $b > 0$: make $a$ as different from zero or $b$ as large as you like, and the similarity is at best one of shape, not size. (Concordance correlation does measure agreement in the sense that $y = x$ is required for perfect positive correlation.)

*Normality of distribution is not a requirement to measure correlation; correlation is perfectly well defined as a descriptive statistic (or even as a non-statistical property; it's just a cosine from one point of view) so long as both variables are genuinely variable. Marginal distribution is of concern if you wish to test for significance, e.g. produce a P-value.

*But you have time series and can expect dependence in time and (quite likely) other kinds of structure. The standard machinery for Pearson correlation is for independent data, and no inference for Pearson correlation for time series can be taken seriously without adjustment for dependence structure.
What is the real problem? For assessing similarity of two time series, I would always start with plotting the series and examining (as appropriate) the difference or ratio between them. The next step is harder and entails modelling the series to see if they have the same structure; others will predictably make positive suggestions here. Also, here as elsewhere, a single summary measure will rarely do justice to the fine structure of interesting data.


text:
Q: eliminación al final de una pila en C tengo este código de pila en lenguaje c, lo que quiero hacer con este código es poder modificarlo y ponerle la opción de que elimine el numero que se encuentre al final de la lista, que vendría siendo el primer numero introducido, sin embargo no lo he conseguido y solo logro que se elimine desde el inicio osea los números que han sido introducidos recientemente.
¿Cómo podría lograr en el código que se elimine el numero localizado al final?
básicamente lo que quiero que suceda al escoger la opción de eliminar al final si tengo en la lista por ejemplo
4->3->2->1
que se elimine el 1
y quede
4->3->2
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

struct lista {
    int clave;
    struct lista * sig;
};

struct lista * inicio = NULL;
struct lista * nuevo;
struct lista * aux;
struct lista * anterior;
struct lista * ultimo;
int contador;
int n;

void insertar();
void desapilar();

int main() {
    int opcionMenu = 0;
    do {

        printf("\n\n|           pila        ");

        printf("\n| 1. Apilar");
        printf("\n| 2. Desapilar");
        printf("\n| 3. Salir");
        printf("\n\n Escoja una Opcion: ");
        scanf("%d", & opcionMenu);
        switch (opcionMenu) {
        case 1:
            printf("\n\n INSERTAR  \n\n");
            insertar();
            break;
        case 2:
            desapilar();
            break;
        case 3:
            printf("\n\n Programa finalizado...");
            break;
        default:
            printf("\n\n Opcion No Valida \n\n");
        }
    } while (opcionMenu != 3);
    return 0;
}

void insertar()
{

    while(contador<4)
    {

        nuevo = (struct lista * ) malloc(sizeof(struct lista));
        nuevo->clave=(n+1);
        n++;

        if (inicio == NULL) {

            nuevo-> sig = inicio;
            inicio = nuevo;
            ultimo=nuevo;
            contador++;
        } else

        {
            ultimo->sig=nuevo->sig;
            nuevo-> sig = inicio;
            inicio = nuevo;
            contador++;
        }
    }

    {
        aux = (struct lista * ) malloc(sizeof(struct lista));
        aux = inicio;
        if (inicio != NULL) {
            while (aux != NULL) {
                printf("%d->", aux -> clave);
                aux = aux -> sig;
            }
        } else {
            printf("\n La pila se encuentra Vacia\n\n");
        }
    }
}

void desapilar() {
    nuevo = (struct lista * ) malloc(sizeof(struct lista));
    printf(" Dato Desapilado: ");

    if (inicio != NULL) {
        aux = inicio;
        inicio = inicio -> sig;

        free(aux);
        contador--;
    }

    {

        aux = (struct lista * ) malloc(sizeof(struct lista));
        aux = inicio;
        if (inicio != NULL) {
            while (aux != NULL) {
                printf("%d->", aux -> clave);
                aux = aux -> sig;
            }
        } else {
            printf("\n La pila se encuentra Vacia\n\n");
        }
    }
}

A: Tienes que librerar ultimo y poner el antepenúltimo bloque apuntando a NULL como siguiente bloque. Es decir
 ---------     ---------
|clave: 1| -> |clave: 2| -> NULL
 ---------     ---------

Debe pasar a
 ---------
|clave: 1|  -> NULL
 ---------

El problema de esto es que no sabes cuál es el penúltimo para eso debes iterar
void desapilar() {
    nuevo = (struct lista * ) malloc(sizeof(struct lista));
    printf(" Dato Desapilado: ");

    if (inicio != NULL) {
        if (inicio == ultimo) {
            free(inicio);
            inicio = NULL;
            ultimo = NULL;
        } else {
            aux = inicio;
            while (aux -> sig != ultimo) {
                aux = aux -> sig;
            }
            aux -> sig = NULL;
            free(ultimo);
            ultimo = aux;
        }
        contador--;
    }

    {

        aux = (struct lista * ) malloc(sizeof(struct lista));
        aux = inicio;
        if (inicio != NULL) {
            while (aux != NULL) {
                printf("%d->", aux -> clave);
                aux = aux -> sig;
            }
        } else {
            printf("\n La pila se encuentra Vacia\n\n");
        }
    }
}

Lo que se hace en esta función es básicamente
if (inicio == ultimo) {
     free(inicio);
     inicio = NULL;
     ultimo = NULL;
}

Si incio y ultimo son los mismos, entonces quiere decir que solo hay un bloque, por lo que liberamos el espacio de inicio (o ultimo en este caso daría lo mismo dado que apuntan a la misma memoria) u a los dos los igualamos a NULL
else {
    aux = inicio;
    while (aux -> sig != ultimo) {
        aux = aux -> sig;
    }
    aux -> sig = NULL;
    free(ultimo);
    ultimo = aux;
}

En esta parte del else igualamos aux a inicio e iteramos hasta el siguiente, cuando veamos que aun -> sig es igual al ultimo quiere decir que estamos en el penúltimo, que es el bloque que nos interesa, por lo que dejamos de iterar. Después igualamos aux -> sig a NULL, dado que ahora este bloque será nuestro último bloque. Por lo tanto liberamos la memoria de ultimo y luego igualamos ultimo al penúltimo bloque


text:
Q: Azure - Scheduled Long Running Task - Scale Down Worker Role To Zero Ok Azure Experts,

*

*I have a task that only needs to run once every week - this is a long
running task that can take 2-3 days to run.

*I have set up a worker role to scale based on a queue. On the day
that we want the task to start - we populate the queue (using a Web
Job).

*During the rest of the time, when the queue is empty, I want the
worker roles to shut down - but I cannot scale down to 0 instances.

*Originally, we wanted to do this with a Web Job, but the website shuts down from time to time - abruptly turning off my webjob - is this supposed to happen? Even with Keep-Alive turned on? Also, you cannot stop a triggered Web Job from running - so if we want the process to stop - we need to turn off the Web site - not ideal.
How do I scale my instances down to zero?
* Alternatives solutions are also welcome.
Trying to minimize cost here - why pay for a worker role that isn't doing anything?

A: It is not possible to scale-down a Worker Role to 0 instances at this time.  Even if you STOP the worker role, you're still incurring charges for STOPPED instances.
However, behavior that you're looking for, is possible with Virtual Machines.  If you shutdown (STOP & DEALLOCATE) a virtual machine, you're not paying fees for that machine.
Now, the only challenge is to stop/start the VM based on a queue count.  I don't recall if Azure portal's native scaling supports scaling down to 0 instances for VMs.  However, if you use AzureWatch, you should be able to get this done without any issues.  Disclaimer: I am affiliated with AzureWatch.
HTH


text:
Q: Bash script to execute multiple programs with arguments usins xterm i have a server wich and i want to execute multiples programs. I think the best was use xterm in order to monitor every program output, if there are something better i would like to know it. The proble is the line 10, i need to pass a cero as an argument and i do not know how. I think there is very easy way but search without succeded.
  2 DIR=$HOME"/IRMA-III"
  3 sudo chown irma /dev/ttyACM0
  4 sudo chown irma /dev/ttyUSB0
  5 xterm $DIR"/src/init/init-cda" &
  6 xterm $DIR"/src/processors/monitor/monitor" &
  7 xterm $DIR"/src/processors/closeRangeNavigator/closeRangeNavigator" &
  8 xterm $DIR"/src/processors/laser/laser"  &
  9 xterm $DIR"/src/processors/longRangeNavigator/longRangeNavigator" &
 10 xterm $DIR"/src/processors/executive/executive" 0 &

A: The right syntax for xterm is
xterm -e programname argument1 argument2 argument3 ...

no problem to pass "0" to the "programname"
your line 10 should look like:
xterm -e "$DIR/src/processors/executive/executive" "0" &

Try to find a way to run your "server" tasks independent from a terminalsession. Monitoring via logfiles is easy ( like less +F logfilename ) and it makes everything rock solid.

A: In order not to need to layout the xterms manually, you may want to add -geometry X options. For a description see http://www2.its.strath.ac.uk/courses/x/subsection3_7_3.html.
xterm -geometry 80x25+10+10 -e /bin/bash -c "echo hello; sleep 2" &

If your programs are not interactive but only output logs then have a look at multitail.


text:
Q: give 30s delay when password not match In my application I want to give 30 sec delay  when user give multiple wrong password but the problem is how can I count the number of failure attempt and after that how can I create 30 sec delay on my app please help.

A: Create a private variable called passwordfailedcount in your private variables.
int passwordfailedcount = 0;

Also create one for your password failed limit...
int passwordfailedlimit = 5;

We should also declare a handler to (this will hadle the 30 second delay) this should be a private variable too...
Handler mHandler = new Handler();

Every time the user enters the wrong password exectute have code like this:
passwordfailedcount++;
        if (passwordfailedcount >= passwordfailedlimit)
        {
            //disable all your text boxes, display a toast or alert, whatever you fancy...
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                public void run() {
                    // re enable all your buttons and set failed count back to 0
                    passwordfailedcount = 0;
                }
            }, 30000);
        }


text:
Q: cancel intent service from broadcast broadcastreceiver I'm sending a local notification with a cancel button and when I click it, I want to cancel my intent service but the event is not getting called.
I can cancel the intent service using an activity, but when is from a notification, it is not working.
My BroadcastReceiver (the Log is showing).
class EventsReceiver: BroadcastReceiver(){
    var onEvent = {}
    override fun onReceive(context: Context?, intent: Intent?) {
        Log.i("EventsReceiver", "onReceive")
        when(intent?.action){
            Constants.ACTION_EVENT_CANCEL -> {
                Log.i("EventsReceiver", "cancel")
                onEvent()
            }
        }
    }
}

The onReceive is getting called when I click the notification button but when I call the onEvent(), the cancelTrip() function is not getting called.
My Intent Service:
override fun onCreate() {
        super.onCreate()
        notificationHelper = NotificationHelper(this)
        receiver = EventsReceiver ()
        receiver.onEvent = {
            cancelTrip()
        }
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, IntentFilter(Constants.ACTION_EVENT_CANCEL))
    }

The activity function that cancels the intent service:
private fun cancel(){
        val intent = Intent()
        intent.setAction(Constants.ACTION_EVENT_CANCEL)
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
    }

How I create my local notification:
val notif = NotificationCompat.Builder(ctx,NOTIFICATION_CHANNEL_ID)
        notif.setContentTitle("My App")
        notif.setContentText("Canceled trip")
        notif.setSmallIcon(R.drawable.ic_launcher_foreground)
        val notifIntent = Intent(ctx, MenuActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(ctx,0,notifIntent,0)
        notif.setContentIntent(pendingIntent)
        val cancelIntent = Intent(ctx, EventsReceiver::class.java)
        val cancelPendingIntent = PendingIntent.getBroadcast(ctx,0,cancelIntent,PendingIntent.FLAG_CANCEL_CURRENT)
        notif.addAction(R.mipmap.ic_launcher, ctx.getString(R.string.cancel_trip), cancelPendingIntent)
        service.notify(NOTIFICATION_CANCEL_ID, notif.build())

A: val cancelIntent = Intent(ctx, EventsReceiver::class.java)

It's because you didn't specify the action (while creating the notification) so in here when(intent?.action)
you have different action then Constants.ACTION_EVENT_CANCEL.
try using this:
val cancelIntent = Intent(Constants.ACTION_EVENT_CANCEL)

or
val cancelIntent = Intent(ctx, EventsReceiver::class.java)
cancelIntent.action = Constants.ACTION_EVENT_CANCEL


text:
Q: Reading out raster data from multiple regions into xyz format in ArcGIS Desktop? I'm trying to export maize yield data from a raster to some sort of text file in order to analyze the data statistically. So far I've managed to do so for an entire country (France), so that I ended up with a table containing the coordinates of about 8000 10x10km squares with the corresponding yield data (see pictures)

Now, data on country level is not precise enough for my purpose, I need to know for each square at least the region (department) it is located in. Extracting each department individually is way too tedious, especially considering that I will have to do the same for multiple other European countries.
Is there a way to easily extract the yield data from the raster so that I know in which department each square is located?

A: Use Make XY Event layer to add your excel table to arcgis as Points (you might also need to make a copy of the Points to make them permanent), then Intersect with counties. You will then get your table in the screenshot including a county column.
With 8000 pixels, it should also be possible to use Raster To Point, then Intersect with counties


text:
Q: Couldn't find Product with 'id'=test Basically working on setting up a favorite product situation but I'm stuck on actually setting it up
This is what I got so far
I think it's because I'm using Friendly URL - I've added friendly.find.. but I still get another error there as well (see second image)
Controller

  def update
    khollection = Khollection.where(cproduct: Cproduct.find(params[:cproduct]), user: current_user)
    if khollection == []
        # Create the khollection
        Khollection.create(cproduct: Cproduct.find(params[:cproduct]), user: current_user)
        @khollection_exists = true
    else
        # Delete the khollection
        khollection.destory_all
        @khollection_exists = false
    end
    respond_to do |format|
        format.html {}
        format.js {}
    end
  end

View
<%= link_to 'Favorite', khollections_update_path(cproduct: @cproduct.title) %>

Below With Friendly .friendly.find(params...
  def update
    khollection = Khollection.where(cproduct: Cproduct.friendly.find(params[:cproduct]), user: current_user)
    if khollection == []
        # Create the khollection
        Khollection.create(cproduct: Cproduct.friendly.find(params[:cproduct]), user: current_user)

MODEL
class Khollection < ApplicationRecord
  belongs_to :cproduct
  belongs_to :user
end

Schema.rb
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema.define(version: 2019_05_28_112623) do

  create_table "active_storage_attachments", force: :cascade do |t|
    t.string "name", null: false
    t.string "record_type", null: false
    t.integer "record_id", null: false
    t.integer "blob_id", null: false
    t.datetime "created_at", null: false
    t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id"
    t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true
  end

  create_table "active_storage_blobs", force: :cascade do |t|
    t.string "key", null: false
    t.string "filename", null: false
    t.string "content_type"
    t.text "metadata"
    t.bigint "byte_size", null: false
    t.string "checksum", null: false
    t.datetime "created_at", null: false
    t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true
  end

  create_table "cproducts", force: :cascade do |t|
    t.string "title"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "user_id"
    t.string "slug"
    t.index ["slug"], name: "index_cproducts_on_slug", unique: true
  end

  create_table "friendly_id_slugs", force: :cascade do |t|
    t.string "slug", null: false
    t.integer "sluggable_id", null: false
    t.string "sluggable_type", limit: 50
    t.string "scope"
    t.datetime "created_at"
    t.index ["slug", "sluggable_type", "scope"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type_and_scope", unique: true
    t.index ["slug", "sluggable_type"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type"
    t.index ["sluggable_type", "sluggable_id"], name: "index_friendly_id_slugs_on_sluggable_type_and_sluggable_id"
  end

  create_table "khollections", force: :cascade do |t|
    t.integer "Cproduct_id"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["Cproduct_id"], name: "index_khollections_on_Cproduct_id"
    t.index ["user_id"], name: "index_khollections_on_user_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "email"
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.text "full_company_logo"
    t.text "domain"
    t.string "business_name"
    t.string "tags"
    t.text "social_media"
    t.text "our_story"
    t.text "location_address"
    t.string "location_city"
    t.string "location_state"
    t.integer "phone"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.boolean "admin"
    t.boolean "company"
    t.boolean "judge"
    t.boolean "blogger"
    t.string "username"
    t.string "slug"
    t.string "avatar"
    t.string "company_logo"
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
    t.index ["slug"], name: "index_users_on_slug", unique: true
  end

end

CURRENT ERROR

A: this is where error is
create_table "khollections", force: :cascade do |t|
    t.integer "Cproduct_id"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["Cproduct_id"], name: "index_khollections_on_Cproduct_id"
    t.index ["user_id"], name: "index_khollections_on_user_id"
  end

replace with
create_table "khollections", force: :cascade do |t|
    t.integer "cproduct_id"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["cproduct_id"], name: "index_khollections_on_cproduct_id"
    t.index ["user_id"], name: "index_khollections_on_user_id"
  end

and
khollection = Khollection.where(cproduct: Cproduct.find_by(title: params[:cproduct]), user: current_user)

Khollection.create(cproduct: Cproduct.find_by(title: params[:cproduct]), user: current_user)

<%= link_to 'Favorite', khollections_update_path(cproduct: @cproduct.title) %>

A: Not sure what's going on behind the scenes with the friendly id, but you should be able to query by the product name:
  product = Cproduct.find_by(title: params[:cproduct]).take
  if product
    khollection = Khollection.where(cproduct_id: product.id), user: current_user).take
    if khollection.blank?
      # Create the khollection
      Khollection.create(cproduct: product, user: current_user)
      @khollection_exists = true
    else
      # Delete the khollection
      khollection.destory_all
      @khollection_exists = false
    end
  else
    # maybe return an error status "Product not found"
  end

  respond_to do |format|
    format.html {}
    format.js {}
  end

The point is that you can always fall back on the column names instead of relying on a gem.


text:
Q: Unable to run gulp task I'm trying to run a simple gulp-sass task, but I'm getting this error:
[22:42:14] Starting 'sass'...
[22:42:14] Finished 'sass' after 10 ms

 events.js:72
    throw er; // Unhandled 'error' event
          ^
   Error: File not found with singular glob
at Glob.<anonymous> (D:\Development\WebStorm\calliope\node_modules\gulp\node_modules\vinyl-fs\node_modules\glob-stream\index.js:34:30)
at Glob.EventEmitter.emit (events.js:95:17)
at Glob._finish (D:\Development\WebStorm\calliope\node_modules\gulp\node_modules\vinyl-fs\node_modules\glob-stream\node_modules\glob\glob.js:171:8)
at done (D:\Development\WebStorm\calliope\node_modules\gulp\node_modules\vinyl-fs\node_modules\glob-stream\node_modules\glob\glob.js:158:12)
at Glob._processSimple2 (D:\Development\WebStorm\calliope\node_modules\gulp\node_modules\vinyl-fs\node_modules\glob-stream\node_modules\glob\glob.js:640:12)
at D:\Development\WebStorm\calliope\node_modules\gulp\node_modules\vinyl-fs\node_modules\glob-stream\node_modules\glob\glob.js:628:10
at Glob._stat2 (D:\Development\WebStorm\calliope\node_modules\gulp\node_modules\vinyl-fs\node_modules\glob-stream\node_modules\glob\glob.js:724:12)
at lstatcb_ (D:\Development\WebStorm\calliope\node_modules\gulp\node_modules\vinyl-fs\node_modules\glob-stream\node_modules\glob\glob.js:716:12)
at RES (D:\Development\WebStorm\calliope\node_modules\gulp\node_modules\vinyl-fs\node_modules\glob-stream\node_modules\glob\node_modules\inflight\inflight.js:23:14)
at f (D:\Development\WebStorm\calliope\node_modules\gulp\node_modules\vinyl-fs\node_modules\glob-stream\node_modules\glob\node_modules\once\once.js:17:25)

I Installed gulp both globally and locally as dev depency.
Here's my task:
var gulp = require("gulp"),
sass = require("gulp-sass");

gulp.task("sass", function(){
    gulp.src('assets/sass/*.scss')
        .pipe(sass())
        .pipe(gulp.dest('assets/css'))
});

A: The error is not so clear, by the way the Exception is throwed by a wrong link ( resource not found )

A: Yes, that is correct. The error is thrown whenever the resource is not found. I wrote a function to prevent such an occurrence in my files.
run "npm install fs --save".
then add this to your gulpfile
var fs = require('fs');
var validateResources = function (resources) {
  resources.forEach(function (resource) {
    if (!fs.existsSync(resource)) {
      throw resource + " not found!";
    }
  });
};

With this, you will be safe to some extent.


text:
Q: Infinite loop when setting and using state in a `useCallback` that is being called from a `useEffect` I would like to fetch data when the user changes.
To do this I have a useEffect that triggers when the user changes, which calls a function to get the data.
The problem is that the useEffect is called too often because it has a dependency on getData and getData changes because it both uses and sets loading.
Are there ways around this, while still retaining getData as a function, as I call it elsewhere.
const getData = useCallback(async () => {
    if (!loading) {
      try {
        setLoading(true);

        const { error, data } = await getDataHook();
        if (error) {
         throw new Error("blah!");
        }

      } catch (error) {
        const message = getErrorMessage(error);
        setErrorMessage(message);
        setLoading(false);
      }
    }
  }, [loading]);

...

  useEffect(() => {
    const callGetData = async () => {
      await getData();
    };
    callGetData();
  }, [user, getData]);

A: Try moving loading from useCallback to useEffect. Something like this:
const getData = useCallback(async () => {
        try {
            const { error, data } = await getDataHook();
            if (error) {
             throw new Error("blah!");
            }

        } catch (error) {
            const message = getErrorMessage(error);
            setErrorMessage(message);
        }
  }, []);

...

  useEffect(() => {
    const callGetData = async () => {
      await getData();
    };
    if (!loading) {
      setLoading(true);
      callGetData();
      setLoading(false);
    }
  }, [user, getData, loading]);

A: The loading flag is something that the call sets, and shouldn't be effected by it, so remove it from the useEffect(), and getData() functions.
const getData = useCallback(async () => {
  try {
    setLoading(true);

    const { error, data } = await getDataHook();
    if (error) {
     throw new Error("blah!");
    }

  } catch (error) {
    const message = getErrorMessage(error);
    setErrorMessage(message);
  } finally {
    setLoading(false); // not related, but this would remove loading after an error as well
  }
}, []);

useEffect(() => {
  const callGetData = async () => {
    await getData(user);
  };
  callGetData();
}, [user, getData]);


text:
Q: op amp DC gain drop I got a really simple circuit, it is a voltage follower in cascade with an inverting amplifier. The input of the voltage follower is a current to voltage converter, measuring nanoamperes with a 1 M restore resistor. The voltage swing of the follower is 0 - 1 V, while the amplifier has a gain of 5.1 using 1k and 5.1 k resistors. Both circuits are coupled via a direct link, no resistors to ground or caps are used. I'm feeding the circuit with +/- 15 V. Signals from the current to voltage converter is really stable.
The problem is that the inverting amplifier has a gain of 3.3 only. I checked the amplifier using a power source and works fine with a 5.1 gain. Why the gain is being reduced so much using the follower? I checked the circuit using a voltage source as input for the follower and the circuit works fine.

A: Some problems:
*

*R2 makes no sense.  A TL081 isn't going to do much of anything with a 100 Ω load on its output.  Just get rid of R2.

*OA2 doesn't do much useful.  As you say, it's a voltage follower.  Ideally, its output voltage is therefore the same as its input voltage.  Such constructs are used to lower the impedance of a signal and to provide increased current drive.  Neither makes sense here.  You already have a opamp driving the signal.  There is no point buffering it to have a different opamp drive the same signal

*You apparently want a gain of -2 from the OA3 stage.  The gain is -R4/R3.  That nails down one degree of freedom.  You can't just ignore the other or pick arbitrary values.  100 Ω is again way too low.  10 kΩ for each R3 and R4 would give the same gain while not being such a excessive load on the opamps.

A: Looking at your circuit, the last 2 amplifiers may not be necessary and your problems may be caused by component selection.  In general the feedback resistor should be in the K range not M.
OA2 has a gain of +1
OA3 has a gain of -1
By feeding the signal into the positive terminal you will have a non inverting amplifier with the benefit of a high impedance input. The leakage current is much lower than your current source.  Convert your current source to a voltage by placing a resistor from the + terminal to ground.
The output of the op amp is low impedance so driving a 100 ohm resistor is not a problem but you are wasting a lot of power. Is R2 really necessary?
To adjust the non inverting amplifier (OA1) gain, just make it look like OA3 and ground R3.
Not sure where your 5.1 K resistor is on the diagram. Gain calculation for DC is straight forward but if the input is AC, you need to check the open loop gain which is frequency and temperature dependent. Error is introduced when the loop gain (open loop - close loop) is small and approach R1/R2 when it is large.


text:
Q: jQuery easyui edatagrid onLoadSuccess fires twice I use jQuery easyui, and the extension Editable DataGrid named edatagrid, which extendes from jQuery easyui datagrid.
you can download the edatagrid file this page:
http://www.jeasyui.com/extension/edatagrid.php
Then I modified the editable-datagrid.html, add handler for onBeforeLoad and onLoadSuccess event, and a button to reload json data. my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>jQuery EasyUI</title>
    <link rel="stylesheet" type="text/css" href="../../themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="../../themes/icon.css">

Editable DataGrid

        AddRow
        SaveRow
        CancelRow
        destroyRow
        reload

                Item ID
                Product ID
                List Price
                Unit Cost
                Attribute

Open editable-datagrid.html in chrome or firefox, check console log:
before load
load success
Object {total: 0, rows: Array[0]}
load success
Object {total: 10, rows: Array[10]}
click reload button to reload edatagrid, get the same result.
before load
load success
Object {total: 10, rows: Array[10]}
load success
Object {total: 10, rows: Array[10]}
Why onBeforeLoad event fired once, but onLoadSuccess event fired twice, it also should be once. How can I make the onBeforeLoad event fires just one time?
if I use datagrid, both of onBeforeLoad and onLoadSuccess fire once.
before load
load success
Object {total: 10, rows: Array[10]}

A: I found the reason
there is a onBeforeLoad handler in jquery.edatagrid.js
onBeforeLoad: function(param){
                if (opts.onBeforeLoad.call(target, param) == false){return false}
                $(this).datagrid('rejectChanges');
                if (opts.tree){
                    var node = $(opts.tree).tree('getSelected');
                    param[opts.treeParentField] = node ? node.id : undefined;
                }
            }

rejectChanges will reload the datagrid, so onLoadSuccess fired twice.

A: you typed:
$('#tt').edatagrid({

and it is:
$('#tt').datagrid({


text:
Q: WPF, No-touch deployment and error " [Application] encountered a problem and needs to close. We are sorry for the inconvenience" I have a problem and don't know what should I do.
We are deploying our application written in .NET 3.5 WPF using No-touch deployment. Our server is also written in .net 3.5 using WCF. Lots of users use this application by installing the shortcuts on their desktop. However there is a problem in our of our client. Application is installed correct but however when she tries to open the application it does not load but instead the client sees the following error occurs:

[Application] encountered a problem
  and needs to close. We are sorry for
  the inconvenience We don't know what
  is the problem.

The client has WinXP OS, .NET 3.5 SP1 and administrative privileges.
Do you have any suggestions?