text:
Q: How can I plot a function that is the sum of another function? I plotted m[t], but actually what I want to plot is g[t], which is a summation of m[t] from 0 to 19 seconds. But when I plot g[t], I get dots. On the picture, what I want is on the right, I don't want the dots, so I guess list plot is not the way to go. How should I plot g to look like the picture I have to the right;

EDIT
My code;
period = 1;
beta = 0.05;
An = List[{-1 , 1, -1, +1, -1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, -1, 1, -1, -1}];

sinch[t_] := (Sin[(Pi*t - t*period)/period])/(Pi* t);
m[t_] :=
  An * sinch[t] * (Cos[(Pi*beta*t - t*period) / period] /
    (1 - (4*beta^2 * (t - t*period)^2 )/period^2 ));

Plot[{m[t]}, {t , 0, 19}]

g = Sum[m[t], {t, 1, 20}];
ListPlot[g]

A: *

*Your usage of Sum gives you only a single sum, not a cumulative one.  I shall assume that you want to integrate your function.

*Your function produces many identical lines; I shall keep only two unique ones.

*You have an extraneous List level in An; I shall remove it.

*You probably want the option PlotRange -> All in the Plot, so that you see everything.

*I shall add Evaluated -> True to give independently styled lines.  See: Plot draws list of curves in same color when not using Evaluate.  I use Evaluated -> True rather than Evaluate to properly localize the plot variable.(1) (2)
Code:
period = 1;
beta = 0.05;
An = {-1, 1};

sinch[t_] := (Sin[(Pi*t - t*period)/period])/(Pi*t);

m[t_] := An*sinch[t]*(Cos[(Pi*beta*t - t*period)/
       period]/(1 - (4*beta^2*(t - t*period)^2)/period^2));

Block[{t},
  g[t_] = Integrate[m[t], t] // Chop;
]

Plot[m[t], {t, 0, 19}, PlotRange -> All, Evaluated -> True]

Plot[g[t], {t, 0, 19}, PlotRange -> All, Evaluated -> True]

Result:


text:
Q: Terminal Services printing We are using a hosted terminal server to run some applications on.
We have three users who connect to the server through RDP and try to print to a networked printer called: HP Photosmart C7280.
One of the users is using Windows XP Pro 32-bit on the host and when they print through the terminal server it works fine.
Another one of the users is using Vista 32-bit on the host and when they print through the terminal server it works fine.
The third user is using Windows 7 64-bit on the host and when they print through the terminal server it only print the first line of the page (A test page print 3/4s of the test page compared to printing all of the page when using the other 2 machines).
We are only printing from Word 2007 and Excel 2007 on all machines.
The server is Windows 2003. No errors in the event log.
Any ideas?

A: Printing from a terminal server, particularly 2k3 servers, is always a hassle.
I don't have advice for this particular scenario, but I can share my experiences.
We found after having problem after problem with 150 users in different locations with different printers, and having spoolers crash etc, that we would offload our printing to one of two solutions:

*

*ThinPrint

*Screwdrivers
We went with ThinPrint, simply because it was the one we had more experience with, and since doing it we've not had any trouble with printing on any clients, at all.
(careful with older versions of thinprint though, as installing .NET 3.0 will kill the entire system - we found this out the hard way and had to rebuild 4 terminal servers)

A: You can also try TSPrint from terminalworks. Their application isn't as expensive.
http://www.terminalworks.com/tsprint.php

A: If it's not been done already, load the x32 2003 drivers directly onto the terminal server. It will then pick that driver up and use it when printing for clients.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is font not available in ASP.NET code? I have an ASP.NET site where I generate ID cards for users. I use a Bitmap object and call Graphics.DrawString to write various bits of text on the image. I have used various fonts to do this for quite a while, without any fuss.
A customer has now asked me to use the Roboto font for their card. I downloaded it from Google and installed it on my system - it appears in the control panel and is available to other apps. However, my card generator can't access it - it defaults to Microsoft Sans Serif. I used foreach (FontFamily family in FontFamily.Families) to see if it was listed, and it was not included in the list. I tried the same thing in a WinForms app, and the font was included in the list.
So, my question is, why can't I access this font from within an ASP.NET process? Is there some difference in the way fonts are supported between ASP.NET and WinForms?

A: Because the asp.net is run under specific pool, and this pool is logged in as different user - that probably have not installed that fonts.
So check under which user your pool is run, and install for that user that font.


text:
Q: A problem with transitivity of ordering of stationary sets In chapter 8 of Jech's Set Theory in the Third Millenium, he defines the following ordering on stationary sets: $S<T$ if the set $\{\alpha\in T:\alpha\cap S\text{ is stationary}\}$ is stationary. He goes on to state that

*

*$S<\text{Tr}(S)$,

*$S<T$ and $T<Q$ implies that $S<Q$, and

*that if $S\sim S',T\sim T'$ modulo $I_{NS}$ and $S<T$, then $S'<T'$.

The first seems to be obvious, but I'm having trouble seeing why (2) and (3) are true.

A: I think that you've misinterpreted Definition $\mathbf{8.18}$. I'll quote it and the sentence that precedes it.

In the context of closed unbounded and stationary sets we use the phrase for almost all $\alpha\in S$ to mean that the set of all contrary $\alpha\in S$ is nonstationary.
Definition $\mathbf{8.18.}$ Let $S$ and $T$ be stationary subsets of $\kappa$.
$$S<T\qquad\text{if and only if}\qquad S\cap\alpha\text{ is stationary for almost all }\alpha\in T\;.$$

The given set of $\alpha\in T$ is $\{\alpha\in T:S\cap\alpha\text{ is stationary}\}$. To say that almost all $\alpha\in T$ are in this set is to say that set of $\alpha\in T$ that are not in this set — i.e., the set of contrary $\alpha\in T$ — is nonstationary. In other words, $S<T$ iff $S\cap\alpha$ is stationary for almost all $\alpha\in T$ iff the set $\{\alpha\in T:S\cap\alpha\text{ is not stationary}\}$ is nonstationary.
Think of non-stationary sets as small, their complements as large, and stationary sets as not small (but not necessarily large). When we say that $\varphi(\alpha)$ holds for almost all $\alpha\in S$, we mean that the set of $\alpha\in S$ for which $\varphi(\alpha)$ fails is small (is non-stationary); this is stronger than saying that the set of $\alpha\in S$ for which $\varphi(\alpha)$ holds is not small (is stationary).


text:
Q: xslt, javascript and unescaped html entities i have a tiny little problem with xslt, js and html entities, eg. within a template:
<script type="text/javascript">
    <xsl:value-of select="/some/node"/>
    for (var i = 0; i < 5; i++) {
        //            ^^^ js error
    }
</script>

<script type="text/javascript">
    <xsl:value-of select="/some/node"/>
    for (var i = 0; i < 5; i++) {
        //            ^ xslt error
    }
</script>

<script type="text/javascript">
    <xsl:value-of select="/some/node"/>
    // <![CDATA[
    for (var i = 0; i < 5; i++) {
        //            ^ becomes <
    }
    // ]]>
</script>

<script type="text/javascript">
    <xsl:value-of select="/some/node"/>
    for (var i = 0; i <xsl:value-of disable-output-escaping="yes" select="string('<')"/> 5; i++) {
        // works of course
    }
</script>

does anyone have an idea where my problem could come from? i always thought the xslt processor would leave the content of a <script/> element unescaped when using the html output method ...
i run libxslt2 version 1.1.24 on OSX which was installed using macportsports ...

A:
i always thought the xslt processor would leave the content of a script element unescaped when using the html output method

You are correct: http://www.w3.org/TR/xslt#section-HTML-Output-Method
The html output method should not perform escaping for the content of the script and style elements.
For example, a literal result element written in the stylesheet as
    <script>if (a < b) foo()</script>
or
    <script><![CDATA[if (a < b) foo()]]></script>
should be output as
    <script>if (a < b) foo()</script>

If your XSLT processor is doing otherwise, it's a bug.
However, in any case it's a good idea to avoid '<' and '&' in embedded scripts, and an even better idea to kick all the code out into a linked .js file.

A: ok. long story, short answer:
it seems that with some libxslt versions the xslt processor leaves the content of a <script/> element unescaped when using the html output method, with others
not ... therefore the following is recommended:
<script type="text/javascript">
    <xsl:value-of select="/some/node"/>
    <xsl:text disable-output-escaping="yes">
        // ^ does the trick ...
        for (var i = 0; i < 5; i++) {
            //            ^ works
        }
    </xsl:text>
</script>

A: The CDATA blocks should have worked; they always have for me. What's your disable-output-escaping value?
UPDATE:
Using Xalan, with disable-output-escaping on its default, which I'm pretty sure is no, I have the following in my working XSL files:

*

*No CDATA block:
for (var i = 0; i `<` foo.length; i++) {
…
}

*CDATA block:
<![CDATA[

for (var i = 0; i < foo.length; i++) { … }

]]>

A: Try removing the double slash before the CDATA of your third solution

A: If the xsl:output method is html, the CDATA section would work. If the xsl:output method is xml, the < and > signs would still be converted.
To get around this problem, you may define the script element to not behave this way using the xsl:output element. you can also force the method of the output using xml or html
<xsl:output method="xml" cdata-section-elements="script" />
...
<script type="text/javascript" language="javascript">
<![CDATA[
  for (var i = 0; i < foo.length; i++) { … }
]]>
</script>


text:
Q: msdeploy restore one site from package containing multiple sites We create a msdeploy package for multiple sites as follows:
"c:\Program Files\iis\Microsoft Web Deploy V3\msdeploy.exe" -verb:sync -source:manifest=MultipleSitesMultipleProviders.xml -dest:package=Test.zip,encryptPassword="password" -disableLink:ContentExtension -enableLink:AppPoolExtension

MultipleSitesMultipleProviders.xml
<sitemanifest>

   <appHostConfig path="SITE1" />
   <appPoolNetFx path="SITE1" />
   <dirPath path="C:\SITES\SITE1" />

   <appHostConfig path="SITE2" />
   <appPoolNetFx path="SITE2" />
   <dirPath path="C:\SITES\SITE2" />

   <appHostConfig path="SITE3" />
   <appPoolNetFx path="SITE3" />
   <dirPath path="C:\SITES\SITE3" />

</sitemanifest>

And here is how that package is then restored
"c:\Program Files\iis\Microsoft Web Deploy V3\msdeploy.exe" -verb:sync -dest:auto -source:package=Test.zip,encryptPassword="password"

This restores all three sites.  The problem I'm trying to solve is how to tell msdeploy.exe to restore just one of the sites that I specify somehow.  I'm thinking this might be done using the -skip rule which would tell the deploy to skip the two sites we don't want to install.  But I could not understand what the format of that this command might look like.
Is this even possible to do?  Any help would sure be appreciated!  Thank you.
Update: I think I found a way to do this through the UI.
This installed just SITE1 and not SITE2 from a package that contained two sites.  I'd like to understand how to do this from the command line.

A: Found out how to do this.  All sites except SITE1 are excluded.  You need to work with archive.xml in the package zip file and come up with xpath expressions that will exclude the six elements that are generated by the six MultipleSitesMultipleProviders.xml entries.
The xpath that prevented the copying of the files was tricky because the element in archive.xml is '<MSDeploy.dirPath>' and you'd think the xpath expression would be //MSDeploy.dirPath[@path='C:\SITES\SITE3'] but that had didn't work but //dirPath[@path='C:\SITES\SITE3'] did work.  Don't know why that is the case.
-skip=xPath=//appHostConfig[@path='SITE2'] -skip:xPath=//appPoolNetFx[@Site='SITE2'] -skip:xPath=//dirPath[@path='C:\SITES\SITE2'] -skip=xPath=//appHostConfig[@path='SITE3'] -skip:xPath=//appPoolNetFx[@Site='SITE3'] -skip:xPath=//dirPath[@path='C:\SITES\SITE3']

I'm guessing there are other ways to do accomplish the same thing but I'm happy to just find something that worked!


text:
Q: How do I avoid redundant data fields in the result set when using JOINs? Following join is supposed to retrieve user info along with their messages for users with a certain status:
SELECT * FROM user, message WHERE message.user_id=user.id AND user.status=1

The problem is that all rows about a certain user in the result set contain redundant columns that repeat the same data about that user (those fields retrieved from user table), only fields from the message table contain non-redundant information. Something like this:
user.id  username email            message.id  subject
1        jane     jane@gmail.com   120         Notification
1        jane     jane@gmail.com   122         Re:Hello
1        jane     jane@gmail.com   125         Quotation
2        john     john@yahoo.com   127         Hi jane
2        john     john@yahoo.com   128         Fix thiss
2        john     john@yahoo.com   129         Ok
3        jim      jim@msn.com      140         Re:Re:Quotation

As you can see many data are redundant and we do not want to first find the users and then go about their messages in loop like structures or something like that. Loops that cause micro-queries should be avoided at all costs.
I am not concerned about the output of my program, that is well handled in the UI. I think perhaps the network traffic produced by returning the result of this query could be substantially reduced if somehow I can manage to eliminate the repetition of user data in all rows pertaining to that user.

A: There are several things you should know.
The first is that the default SQL JOIN construct is essentially a set cross product, restricted by the WHERE clause.  This means it's multiplicative - you get duplicate results out which you then prune down.  You also have to be careful in the presence of NULL fields.
The second is that there is a 'DISTINCT' keyword.  When you prefix a column in the selection with this, you'll get at most one instance of a certain value for that column in the results.  So, as per your query, 'SELECT DISTINCT user.id FROM' will eliminate the redundancies on the server side.
The third is that the correct way to solve this problem is likely not using the * operator.  I suggest:
SELECT user.id,username,email,subject FROM message m,user WHERE m.user_id=user.id AND user.status=1

This uses the simple, easy-to-understand implicit-join syntax and should be valid SQL on whatever server.  I can vouch for it working with MySQL, at least.  It also aliases the 'message' table to 'm' as shorthand.
As you surmise, this will reduce the traffic from the SQL server to your database.
edit: if you want to eliminate the "redundant" email information, you can't - you must make two distinct queries.  SQL results are tables and must be rectangular, with all known values filled.  There's no 'ditto' entry.
edit 2: You only have to make two queries.  For instance:
SELECT subject FROM message WHERE message.id IN (SELECT user.id FROM user WHERE status=1)

This is one query that contains a nested query, so it's really making two database hits.  But it doesn't have any programmatic loops.

A: In the straight sql query there is not if you keep them as a single query. If you are programmatically printing this out, then you would order by user id and only reprint that information if the user id changes.

A: In the SQL standard, you would use NATURAL JOIN; this joins on common column names and only preserves one copy of those common names.
In practice, you carefully list the columns you want, rather than resorting to the '*' shorthand notation.

A: Assuming you can use stored procedure, you could write one to run the above query and then use a cursor to store nulls for 'redundant information' to get something like

user.id  username email            message.id  subject
1        jane     jane@gmail.com   120         Notification
null     null     null             122         Re:Hello
null     null     null             125         Quotation
2        john     john@yahoo.com   127         Hi jane
null     null     null             128         Fix thiss
null     null     null             129         Ok
3        jim      jim@msn.com      140         Re:Re:Quotation

and then return this resultset in a temporary table. but while this may reduce network traffic, it will add a processing overhead
Another way is to run 2 queries, one to get the user information, and the other to get the message information with just the linked user id and then do the "join" using application server side code. something like
SELECT DISTINCT user.* FROM user, message WHERE message.user_id=user.id AND user.status=1

and
SELECT user.id, message.* FROM user, message WHERE message.user_id=user.id AND user.status=1

which will result in 2 trips to the database, instead of 1, which might eventually be slower, even if the network traffic is reduced.
And another way is to bunch these 2 into a single resultset with something like
SELECT user.* FROM user, message WHERE message.user_id=user.id AND user.status=1
UNION ALL
SELECT user.id, message.* FROM user, message WHERE message.user_id=user.id AND user.status=1

to get something like

   user.id  username/message.id    email/subject
    1        jane                   jane@gmail.com
    2        john                   john@yahoo.com
    3        jim                    jim@msn.com
    1        120                    Notification
    1        122                    Re:Hello
    1        125                    Quotation
    2        127                    Hi jane
    2        128                    Fix thiss
    2        129                    Ok
    3        140                    Re:Re:Quotation

and then use application server logic to separate it out. reduced network traffic but more application server load / marginally more database server load.
But the saved network traffic is rarely worth the added complexity.


text:
Q: Frontend conditionally open download dialog or display error Given the following expressjs server code which conditionally responses to the same entry point, I want to display error  message or open download dialog based on server's response. It possible and if so, what i s a recommended way to do it?
app.get('/download', (req, res) => {
  if (conditionA) {
    return res.status(403).send({err: 'Message I want to display with frontend JS'});
  } else {
    return res.sendFile('file I want to  send');
  }
});


text:
Q: Apache server sub directory pages are not showing I am using LAMP on my ubuntu 12.04 system. When I browse any sub directory or sub page which is located inside my /var/www/ folder it is showing like
Not Found
The requested URL /directory/subdirectory/filename was not found on this server.

Apache/2.2.22 (Ubuntu) Server at localhost Port 80

But the file is already present in that sub directory. So can someone kindly tell me why I am getting this error? Any help and suggestions will behighly appreciable. Thanks
My /etc/apache2/sites-available/default file is like this
<VirtualHost *:80>
    ServerAdmin webmaster@localhost

    DocumentRoot /var/www
    <Directory />
        Options FollowSymLinks
        AllowOverride All
    </Directory>
    <Directory /var/www/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
        AllowOverride All
        Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
        Order allow,deny
        Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined

    Alias /doc/ "/usr/share/doc/"
    <Directory "/usr/share/doc/">
        Options Indexes MultiViews FollowSymLinks
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.0/255.0.0.0 ::1/128
    </Directory>

</VirtualHost>

A: It might be because of access permission on the sub folder, try
chmod -R 775 /var/www/html/subfolder
Or
chmod -R 775 /var/www/subfolder

as per your folder structure


text:
Q: Sub-busca com SQL Estou tentando resolver um exercício no khanacademy no curso de SQL e estou com uma certa dificuldade.
O exercicio pede o seguinte:

Para terminar de criar a lista de reprodução "Pop", adicione outra busca que vai selecionar o título, title, de todas as músicas dos artistas do gênero "Pop". Ela deve usar IN em uma sub-busca aninhada com base em sua busca anterior.

Eu tentei de diversas maneiras e não consegui, notei que se eu usar;
SELECT title FROM songs WHERE genre...

O sistema já acusa que não existe coluna genre na tabela songs (o que está correto) então como eu poderia buscar por uma coluna em outra tabela se a tabela em que estou fazendo a pesquisa não tem o mesmo nome?
abaixo segue uma imagem do exercicio para que me entendam melhor.

A: Olá,
Para esta situação é bem simples de se fazer.
Você deve ver quais colunas entre as duas tabelas tem uma ligação (FOREIGN KEY), no seu caso, provavelmente são as colunas "name" da tabela artist e "artist" da tabela songs.
Após ter essa informação em mãos é simples, crie a query que vai retornar os titulos da tabela artists, depois crie uma clausura WHERE onde a coluna "name" da tabela artists pertence (IN) a coluna "artist" da tabela songs, para isso, crie uma query que retorne o artist da tabela de songs onde genre é igual a "Pop".
Segue exemplo:
SELECT title
  FROM artists
 WHERE name IN ( SELECT artist
                   FROM songs
                  WHERE genre = 'Pop' );

A: Na verdade você seleciona o titulo dos artista onde tem o gênero pop, name é igual a artist então só fiz repetir:
SELECT title FROM songs WHERE artist IN ( SELECT name FROM artists WHERE genre IN ("Pop"));

A: SELECT title
FROM songs
WHERE artist IN (SELECT name FROM artists WHERE genre = "Pop");

A:
explicación:
es una consulta que implica consultar datos de dos tablas por ende, es necesario hacer un join..

respuesta:
select title from songs where artist=(select  artist from songs
    inner join artists on songs.id=artists.id
        where artists.genre IN ("Pop"));

Esta consulta la puedes encontrar en khan academy:
https://es.khanacademy.org/computing/computer-programming/sql/more-advanced-sql-queries/p/challenge-playlist-maker.


text:
Q: Input a stream of characters in a character array I have got a stream of characters as input without any whitespaces, and I have to store them in a character array using scanf().
#include <stdio.h>
#include <iostream>

int main() {
    int n,q,l,r,k;
    scanf("%d",&n);
    char A[n];
    scanf("%d",&q);

    for(int i=0; i<n; i++) {
        scanf("%c",&A[i]);
    }
    for(int i=0; i<n; i++) {
        printf("%c",A[i]);
    }
    return 0;
}

The above loop does not work.

A: The loop will work only if you have declare (and possibly initialized) n, otherwise the compile will complain that n has not been declared.
Then, when the program run you are asked to insert n characters. Note that every key you press will be interpreted as a char, so that, if n=10:
1 2 3 4 5

are 10 character because you have entered 5 numbers, 4 spaces and a new line character '\n' to give the input to your program.
So, if you need to populate your array with 10 numbers, say from 0 to 9, you need to write:
0123456789

and then press enter. Note that in this way you provide 11 characters, 10 numbers and the new line but only the first 10 are read, because of the bound of your loop.
Note: this program can only accept one-digit numbers as long as you are using char
Advise:since you are using C++, do not use the C I/O-library stdio.h but the C++ one: iostream


text:
Q: Jenkins Multijob filnaly result I have Multijob structure:
Master MultiJob Project (Job)
 |----- Phase 1
            |------> JOB A
            |------> JOB D
 |----- Phase 2
            |------> JOB B
            |------> JOB D
 |----- Phase 2
            |------> JOB C

Job D is always failed, but it's Ok for this project.
How I can exclude result job D from final results? (Because all other jobs is success, but final result is FAILED)

A: You want to have the Master MultiJob Project (Job) successful irrespective of JOB Dexecution result. But, JOB A, JOB B and JOB C should be successful.
You can make the Master Multijob Project (Job) successful by using Groovy Postbuild Plugin.
Once you install this plugin in Jenkins, you will get Groovy Postbuild step in the Post-build Actions section. Choose Groovy Postbuild step and it will give an option to add Groovy scripts to manipulate your job behavior.
Add the following script there:
if( manager.build.@result == hudson.model.Result.FAILURE){
errpattern = ~/[FAILURE].*/;
manager.build.logFile.eachLine{ line ->
    errmatcher=errpattern.matcher(line)
    if (errmatcher.find()) {
        manager.build.@result = hudson.model.Result.SUCCESS
    }
  }
}

What the above script will do is change the build status of your parent job to success if it fails. But, the issue here is it will change the build status to success for any child job failure in your phases.
You only want to ignore the FAILURE status of JOB D not the other jobs. So, what we can do is determine the execution results of JOB A, JOB B and JOB C. If any of them fails we can prevent the Groovy script from changing the build status of your parent job to SUCCESS.
Now, to determine the build result for JOB A,JOB B and JOB C
We can use the following:
JOBA_BUILD_STATUS=$(curl --silent "http://<jenkins_URL>/job/JOBA/$BUILD_ID/api/json" | jq -r '.result')

JOBB_BUILD_STATUS=$(curl --silent "http://<jenkins_URL>/job/JOBB/$BUILD_ID/api/json" | jq -r '.result')

JOBC_BUILD_STATUS=$(curl --silent "http://<jenkins_URL>/job/JOBC/$BUILD_ID/api/json" | jq -r '.result')

In the Build section of your multi-job configuration, after all the phases add Execute shell step and add the above scripts to it.
Now, let's tweak the groovy script to ignore JOB D's build result and consider  the build result for JOB A,JOB B and JOB C.
if((manager.build.@result == hudson.model.Result.FAILURE) && ("SUCCESS".equals(manager.build.buildVariables.get("JOBA_BUILD_STATUS"))) && ("SUCCESS".equals(manager.build.buildVariables.get("JOBB_BUILD_STATUS"))) && ("SUCCESS".equals(manager.build.buildVariables.get("JOBC_BUILD_STATUS")))){
   errpattern = ~/[FAILURE].*/;
    manager.build.logFile.eachLine{ line ->
    errmatcher=errpattern.matcher(line)
    if (errmatcher.find()) {
        manager.build.@result = hudson.model.Result.SUCCESS
    }
  }
}

Now, it will ignore the build result of JOB D and then check if the build results for JOB A, B & C are SUCCESS or not. If they are successful then it will change the build result of your Multijob to SUCCESS.

A: Another solution with groovy script. Add it as Post build action in your Multijob.
def subjobStatusMap = [:]

manager.build.getSubBuilds().each { subBuild->
      subJobName = subBuild.getJobName()
      subJobNumber = subBuild.getBuildNumber()
      job = hudson.model.Hudson.instance.getItem(subBuild.getJobName())
      results = job.getLastCompletedBuild().getResult()

      subjobStatusMap.put((subJobName), results)
}
manager.listener.logger.println(subjobStatusMap)

if(("SUCCESS".equals(subjobStatusMap.get("JOB_A").toString()))&& ("SUCCESS".equals(subjobStatusMap.get("JOB_B").toString())) && ("SUCCESS".equals(subjobStatusMap.get("JOB_C").toString()))) {
    manager.build.@result = hudson.model.Result.SUCCESS
}

A: Try this:

*

*download Jenkins Plugin Groovy Postbuild

*add post-build step:Groovy Postbuild

*type code like this:

import hudson.model.*

jobA = Hudson.instance.getJob("JobA")
jobB = Hudson.instance.getJob("JobB")
jobC = Hudson.instance.getJob("JobC")
jobD = Hudson.instance.getJob("JobD")

if("SUCCESS".equals(jobA.getLastBuild().getResult().toString())&&
"SUCCESS".equals(jobB.getLastBuild().getResult().toString())&&
"SUCCESS".equals(jobC.getLastBuild().getResult().toString())
){
        manager.build.@result = hudson.model.Result.SUCCESS

}

See the script image


text:
Q: Problems when I upload images and show them in angular and node using the GraphicsMagick I use this code to upload images in Node:
req.file('image[]')
.upload({
  maxBytes: 5000000, // Files limit(in bytes)
  dirname: path.resolve(sails.config.appPath, 'assets/images/user') // Path to copy the files
}, function whenDone(err, uploadedFiles) {
  if (err) {
    // here must delete the created user before the error
    console.log(err);
  }
  var image_real_name = '';
  var json = [];
  for(var i = 0; i < uploadedFiles.length; i++){
    image_real_name = 'images/user/'+path.basename(uploadedFiles[i].fd);
    json.push(image_real_name);
  }
  res(json);
});

but I needed to compress the images to gain space on the server so I used the gm GraphicsMagick:
`
var receiver = new Writable({objectMode: true});
  receiver._write = function(file, enc, cb) {
    // The output stream to pipe to
    var output = require('fs').createWriteStream('assets/images/user/' + file.fd);
    gm(file).resize('200', '200').stream().pipe(output);
    cb();
  };
  req.file('image[]').upload(receiver, function(err, files){
    if (err) {
      // here must delete the created user before the error
      console.log(err);
    }
    var image_real_name = '';
    var json = [];
    for(var i = 0; i < files.length; i++){
      image_real_name = 'images/user/'+path.basename(files[i].fd);
      json.push(image_real_name);
    }
    res(json);
  });

`
I am using angular and when I change the direction of the image by binding the new image should be shown but it is not loaded, with the first code all perfect but using gm does not work anymore. I have to restart the page so that the image is displayed.
track:
  apparently the image has not been fully processed, if a setTime is entered, the image is displayed correctly:
setTimeout((dataService: DataService, image: any) => {
          dataService.getUser().image = image;
        }, 1000, this.data, dataI.json().url);

any idea?

A: There is a finish event when the file is fully loaded, I solved the problem by adding the following:
output.on("finish", function() { return cb(); });


text:
Q: BASH echo write mysql input Have a bash menu where variables write to file for mysql input.
heres what I have:
    echo "CREATE DATABASE '$mysqldbn';

#GRANT ALL PRIVILEGES ON *.* TO '$mysqlu'@'$myhost' IDENTIFIED BY '$mysqlup' WITH GRANT OPTION;

GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES ON '$mysqldbn'.* TO '$mysqlu'@'$myhost' IDENTIFIED BY '$mysqlup';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES ON '$mysqldbn'.* TO '$mysqlu'@'$myip' IDENTIFIED BY '$mysqlup';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES ON '$mysqldbn'.* TO '$mysqlu'@'localhost' IDENTIFIED BY '$mysqlup';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES< LOCK TABLES on '$mysqldbn'.* TO '$mysqlu'@'$rip' IDENTIFIED BY '$mysqlup';" > nmysql.db

mysql -u root -p$mypass < nmysql.db

problem is to get variables to show I had to put them in single quotes, the single quotes show up as I want for instances like '$mysqlu'@'localhost'. But how can I remove the quotes and still get to use the variable in the instance like, CREATE DATABASE '$mysqldbn' ? Double quotes wont work either, I am at a loss.
Thanks in advance,
Joe

A: I don't really see your problem here, but you may use ${mysqldbn} to quote the variable name in bash, would that help?

A: You should be able to omit the single quotes where you don't want them.
But I would recommend using a here document. Approximately:
mysql -u root -p$mypass <<EOF

CREATE DATABASE $mysqldbn;

#GRANT ALL PRIVILEGES ON *.* TO '$mysqlu'@'$myhost' IDENTIFIED BY '$mysqlup' WITH GRANT OPTION;

GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES ON '$mysqldbn'.* TO '$mysqlu'@'$myhost' IDENTIFIED BY '$mysqlup';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES ON '$mysqldbn'.* TO '$mysqlu'@'$myip' IDENTIFIED BY '$mysqlup';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES ON '$mysqldbn'.* TO '$mysqlu'@'localhost' IDENTIFIED BY '$mysqlup';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES< LOCK TABLES on '$mysqldbn'.* TO '$mysqlu'@'$rip' IDENTIFIED BY '$mysqlup';
EOF

A: As far as I know, you have to use double quotes to display values, here's my example:
#!/bin/bash
myvar="MyValue"
echo "$myvar"
echo '$myvar'
echo '${myvar}'

Generates:
MyValue
$myvar
${myvar}

Hope this helps


text:
Q: Swing component for entering a sequence of pairs I have a Java application, and I need an user-friendly component for entering a lot of pairs easily, I think the most friendly way to do it is make a table, somewhat like a spreadsheet and let them edit that manually, but i'm not sure what listeners to use for that, and it seems rather complicated, what I want to know is if there is a nicer component for that task.

A: I would use a JTable.  You can write a class which extends AbstractTableModel to handle display, validation, etc.  It handles most of the work for you.  You just need to override the few methods you care about.  The Java tutorial on Tables has a pretty good overview, but pretty much all you need to do to make your cells editable is have isCellEditable() return true and implement an appropriate setValueAt() function.


text:
Q: Creating sequential polygon based on spatial points location using QGIS I have a challenge to create an automatic vector grid using QGIS.
The scenario is that I have a points layer which has more than 600 features. If possible I need to generate a sequential vector grid based on spatial of points or random points location for every 50 or 60 feature points. If I have 625 point features, (625/50 = 13) and the last grid will be has 25 features
I want to create grids based on another layer (point layer), input feature (point layer) then each grid should has specific number of features for example if I have 525 features in a point layer and every grid cell should include 50 features in the point layer, so the total grids will be 13, 12 will include 50 of total point number, and the last grid will include only 25 of features
Instead of creating each polygon manually which covers 50 points, I am looking for to generate sequential polygons by spatial location of points, for example polygon starts from the south of points location.


text:
Q: Changing an array in function doesn't change it's value in main I try to fullfill a vector (which i have to allocate) with random numbers between -0.8 and 0.8. My question is why in the main function when i call the function setvector() does not return the vector and i still take the initialized with zeros? Thanks a lot. here what i did
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

void allocate(double **a, int size) {
    *a = malloc(size);
}

double setvector(double *v){
    int i, seed, send_size;

    send_size = 10;

    allocate(&v, send_size * sizeof(double)); // allocate memory for the vector
    seed = time(NULL);
    srand(seed);
    for (i = 0; i < send_size; i++)
    {
        v[i] = 1.6*((double) rand() / (double) RAND_MAX) - 0.8;
    }
    printf("Inside function the vector is:\n\n");
    for (i = 0; i < 10; i++)
    {
        printf("The %d element has the random %4.2f\n", i, v[i]);
    }
    return *v;
}

int main(){
    double *v = NULL;
    setvector(v);
    printf("\nThe vector from main is:\n\n");
    printf("The 1st element of v is %4.2f\n", &v[0]);
    printf("The 1st element of v is %4.2f\n", &v[1]);

    return 0;
}

Here is my screen output:

Inside function the vector is:
The 0 element has the random -0.79
  The 1 element has the random -0.34
  The 2 element has the random 0.48
  The 3 element has the random -0.67
  The 4 element has the random -0.70
  The 5 element has the random 0.61
  The 6 element has the random -0.67
  The 7 element has the random -0.66
  The 8 element has the random -0.44
  The 9 element has the random -0.36
The vector from main is:
The 1st element of v is 0.00
  The 1st element of v is 0.00

A: In main you're passing the addresses of the array elements to printf:
printf("The 1st element of v is %4.2f\n",&v[0]);
printf("The 1st element of v is %4.2f\n",&v[1]);

That should be printf(..., v[0]);.
Further:
double setvector(double *v){

doesn't change v in main, so v remains NULL there. You should have setvector take a double**, like allocate, and pass it the address of v.


text:
Q: Konvajs: Create a draggable area with some constraints on one of the childs I'm creating a timeline with Konva and the entire timeline (stage) is draggable on all directions but I have an axis with all the years of the timeline (Konva group) that I want to restrict its movement so that it only moves horizontally.
I can't use dragBoundFunc as it will restrict the movement on all nodes of the timeline.
I tried to change the position of the element using the dragmove event:
stage.on("dragmove", function(evt) {
  xaxis.y(0);
});

But the xaxis still moves on all direction while dragging the stage.
I could also use different draggable layers for the axis and the timeline itself, but then when I drag the axis it wouldn't move the timeline and the same if I move the timeline.

A: As the simplest solution, you can just make sure that the absolute position of your timelime group is the same:
stage.on("dragmove", function(evt) {
  // read absolute position
  const oldAbs = xaxis.absolutePosition();

  // set new absolute position, but make sure x = 0
  xaxis.absolutePosition({
   x: oldAbs.x,
   y: 0
  });
});

A: Here is a slightly more capable version that allows vertical drag of the event layer whilst keeping the time line axis visible for reference. This uses two layers - one to act as the background containing the time line and grid, whilst the second shows the events.
The key technique here is using the dragMove event listener on the draggable event layer to move the background layer in sync horizontally but NOT vertically. Meanwhile the event layer is also constrained with a dragBound function to stop silly UX.
An improvement would be to add clipping to the event layer so that when dragged down it would not obscure the timeline.

var stageWidth = 800,
  stageHeight = 300,
  timeFrom = 1960,
  timeTo = 2060,
  timeRange = timeTo - timeFrom,
  timeLineWidth = 1000,
  timeSteps = 20, // over 100 yrs = 5 year intervals
  timeInt = timeRange / timeSteps,
  timeLineStep = timeLineWidth / timeSteps,
  yearWidth = timeLineWidth / timeRange,
  plotHeight = 500,
  events = [{
      date: 1964,
      desc: 'Born',
      dist: 10
    },
    {
      date: 1966,
      desc: 'England win world cup - still celebrating !',
      dist: 20
    },
    {
      date: 1968,
      desc: 'Infant school',
      dist: 30
    },
    {
      date: 1975,
      desc: 'Secondary school',
      dist: 50
    },
    {
      date: 1981,
      desc: 'Sixth form',
      dist: 7
    },
    {
      date: 1983,
      desc: 'University',
      dist: 30
    },
    {
      date: 1986,
      desc: 'Degree, entered IT career',
      dist: 50
    },
    {
      date: 1990,
      desc: 'Marriage #1',
      dist: 0
    },
    {
      date: 1996,
      desc: 'Divorce #1',
      dist: 0
    },
    {
      date: 1998,
      desc: 'Marriage #2 & Son born',
      dist: 90
    },
    {
      date: 2000,
      desc: 'World did not end',
      dist: 20
    },
    {
      date: 2025,
      desc: 'Retired ?',
      dist: 0
    },
    {
      date: 2044,
      desc: 'Enters Duncodin - retirement home for IT workers',
      dist: 0
    },
    {
      date: 2054,
      desc: 'Star dust',
      dist: 0
    }
  ]

function setup() {

  // Set up a stage and a shape
  stage = new Konva.Stage({
    container: 'konva-stage',
    width: stageWidth,
    height: stageHeight
  });

  // bgLayer is the background with the grid, timeline and date text.
  var bgLayer = new Konva.Layer({
    draggable: false
  })

  stage.add(bgLayer);

  for (var i = 0, max = timeSteps; i < max; i = i + 1) {
    bgLayer.add(new Konva.Line({
      points: [(i * timeLineStep) + 0.5, 0, (i * timeLineStep) + .5, plotHeight],
      stroke: 'cyan',
      strokeWidth: 1
    }))

    bgLayer.add(new Konva.Text({
      x: (i * timeLineStep) + 4,
      y: 260,
      text: timeFrom + (timeInt * i),
      fontSize: 12,
      fontFamily: 'Calibri',
      fill: 'magenta',
      rotation: 90,
      listening: false
    }));

  }

  for (var i = 0, max = plotHeight; i < max; i = i + timeLineStep) {
    bgLayer.add(new Konva.Line({
      points: [0, i + 0.5, timeLineWidth, i + .5],
      stroke: 'cyan',
      strokeWidth: 1
    }))
  }

  // add timeline
  var timeLine = new Konva.Rect({
    x: 0,
    y: 245,
    height: 1,
    width: timeLineWidth,
    fill: 'magenta',
    listening: false
  });
  bgLayer.add(timeLine)

  // eventLayer contains only the event link line and text.
  var eventLayer = new Konva.Layer({
    draggable: true,

    // the dragBoundFunc returns an object as {x: val, y: val} in which the x is constricted to stop
    // the user dragging out of sight, and the y is not allowed to change.
    // ! position of bgLayer is moved in x axis in sync with eventLayer via dragMove event
    dragBoundFunc: function(pos) {
      return {

        x: function() {
          var retX = pos.x;
          if (retX > 20) { // if the left exceeds 20px from left edge of stage
            retX = 20;
          } else if (retX < (stageWidth - (timeLineWidth + 50))) { // if the right exceeds 50 px from right edge of stage
            retX = stageWidth - (timeLineWidth + 50);
          }
          return retX;
        }(),

        y: function() {
          var retY = pos.y;
          if (retY < 0) {
            retY = 0;
          } else if (retY > 200) {
            retY = 200;
          }
          return retY;
        }()

      };
    }
  });
  stage.add(eventLayer);

  // ! position of bgLayer is moved in x axis in sync with eventLayer via dragMove event of eventLayer.
  eventLayer.on('dragmove', function() {
    var pos = eventLayer.position();
    var bgPos = bgLayer.position();
    bgLayer.position({
      x: pos.x,
      y: bgPos.y
    }); // <--- move the bgLayer in sync with the event eventLayer.
    stage.draw()
  });

  for (var i = 0, max = events.length; i < max; i = i + 1) {
    var event = events[i];
    var link = new Konva.Rect({
      x: yearWidth * (event.date - timeFrom),
      y: 200 - event.dist,
      width: 1,
      height: 55 + event.dist,
      fill: 'magenta',
      listening: false
    });
    eventLayer.add(link)

    var eventLabel = new Konva.Text({
      x: yearWidth * (event.date - timeFrom) - 5,
      y: 190 - event.dist,
      text: event.date + ' - ' + event.desc,
      fontSize: 16,
      fontFamily: 'Calibri',
      fill: 'magenta',
      rotation: -90,
      listening: false
    });
    eventLayer.add(eventLabel);

    var dragRect = new Konva.Rect({
      x: 0,
      y: 0,
      width: timeLineWidth,
      height: 500,
      opacity: 0,
      fill: 'cyan',
      listening: true
    });
    eventLayer.add(dragRect);

    dragRect.moveToTop()
  }

  stage.draw()

}

var stage, eventLayer;

setup()
.konva-stage {
  width: 100%;
  height: 100%;

Drag the timeline left & right AND up & down...

A: Just for fun, a stripped down version of my answers showing the ondrag() function without all the timeline frills.

var stage;

function setup() {

  // Set up a stage and a shape
  stage = new Konva.Stage({
    container: 'konva-stage',
    width: 600,
    height: 300
  });

  // layer1.
  var layer1 = new Konva.Layer({
    draggable: false
  })

  stage.add(layer1);

  var ln1 = new Konva.Line({
    points: [10, 0, 10, 20, 10, 10, 0, 10, 20, 10],
    stroke: 'cyan',
    strokeWidth: 4
  });
  layer1.add(ln1);

  var layer2 = new Konva.Layer({
    draggable: true,
  });
  stage.add(layer2);

  var ln2 = new Konva.Line({
    points: [10, 0, 10, 20, 10, 10, 0, 10, 20, 10],
    stroke: 'magenta',
    strokeWidth: 4
  });
  layer2.add(ln2);

  // position the crosses on the canvas
  ln1.position({
    x: 100,
    y: 80
  });
  ln2.position({
    x: 100,
    y: 40
  });

  // ! position of layer1 is moved in x axis in sync with layer2 via dragMove event of layer2.
  layer2.on('dragmove', function() {
    var pos = layer2.position();
    var bgPos = layer1.position();
    layer1.position({
      x: pos.x,
      y: bgPos.y
    }); // <--- move  layer1 in sync with layer2.
    stage.draw()
  });

  stage.draw()
}

setup()
  .konva-stage {
  width: 100%;
  height: 100%;

Drag the upper cross - only one moves vertically whilst the other is contrained in the y-axis. Both move in sync on the x-axis

A: It is not entirely clear what you are asking but I have assumed you want to constrain the drag of the timeline so that it gives good UX. See working snippet below. The majority of the code is setup of the timeline. The important piece is

*

*Include a rect covering the entire timeline that has zero opacity and is listening for mouse events.

*Provide the layer with a dragBoundFunc that returns an object as {x: val, y: val} in which the x is constricted to stop the user dragging out of sight horizontally, and the y is not allowed to change. If you think of the rect and the stage as rectangles then the math is not difficult to comprehend. If your timeline is vertical, swap the x & y behaviour.

var stageWidth = 800,
  timeFrom = 1960,
  timeTo = 2060,
  range = timeTo - timeFrom,
  timeLineWidth = 1000;
yearWidth = timeLineWidth / range,
  events = [{
      date: 1964,
      desc: 'Born'
    },
    {
      date: 1968,
      desc: 'Infant school'
    },
    {
      date: 1975,
      desc: 'Secondary school'
    },
    {
      date: 1981,
      desc: 'Sixth form'
    },
    {
      date: 1983,
      desc: 'University'
    },
    {
      date: 1986,
      desc: 'Degree, entered IT career'
    },
    {
      date: 1990,
      desc: 'Marriage #1'
    },
    {
      date: 1998,
      desc: 'Marriage #2'
    },
    {
      date: 1999,
      desc: 'Son born'
    },
    {
      date: 2025,
      desc: 'Retired ?'
    },
    {
      date: 2044,
      desc: 'Enters Duncodin - retirement home for IT workers'
    },
    {
      date: 2054,
      desc: 'Star dust'
    }
  ]

function setup() {

  // Set up a stage and a shape
  stage = new Konva.Stage({
    container: 'konva-stage',
    width: stageWidth,
    height: 500
  });

  layer = new Konva.Layer({
    draggable: true,

    // the dragBoundFunc returns an object as {x: val, y: val} in which the x is constricted to stop
    // the user dragging out of sight, and the y is not allowed to change.
    dragBoundFunc: function(pos) {
      return {
        x: function() {
          retX = pos.x;
          if (retX > 20) {
            retX = 20;
          } else if (retX < (stageWidth - (timeLineWidth + 50))) {
            retX = stageWidth - (timeLineWidth + 50);
          }
          return retX;
        }(),
        y: this.absolutePosition().y
      };
    }
  });
  stage.add(layer);

  // add timeline
  var timeLine = new Konva.Rect({
    x: 0,
    y: 245,
    height: 10,
    width: timeLineWidth,
    fill: 'magenta',
    listening: false
  });
  layer.add(timeLine)

  for (var i = 0, max = events.length; i < max; i = i + 1) {

    var event = events[i];
    var link = new Konva.Rect({
      x: yearWidth * (event.date - timeFrom),
      y: 200,
      width: 5,
      height: 55,
      fill: 'magenta',
      listening: false
    });
    layer.add(link)

    var timeLabel = new Konva.Text({
      x: yearWidth * (event.date - timeFrom) + 10,
      y: 265,
      text: event.date,
      fontSize: 16,
      fontFamily: 'Calibri',
      fill: 'magenta',
      rotation: 90,
      listening: false
    });
    layer.add(timeLabel);

    var eventLabel = new Konva.Text({
      x: yearWidth * (event.date - timeFrom) - 5,
      y: 190,
      text: event.desc,
      fontSize: 16,
      fontFamily: 'Calibri',
      fill: 'magenta',
      rotation: -90,
      listening: false
    });
    layer.add(eventLabel);

    var dragRect = new Konva.Rect({
      x: 0,
      y: 0,
      width: timeLineWidth,
      height: 500,
      opacity: 0,
      fill: 'cyan',
      listening: true
    });
    layer.add(dragRect);

    dragRect.moveToTop()
  }

  stage.draw()

}

var stage, layer;

setup()
.konva-stage {
  width: 100%;
  height: 100%;

Drag the timeline...


text: Q: Get screen shot on macOS from NetCore 3.1? I need to get a screenshot on macOS from netcore 3.1 app. Unfortunately current implementation of System.Drawing.Graphics.CopyFromScreen thows PlatformNotSupportedException. But what other simplest way (maybe over OpenGL or GTK) get a screenshot?


text:
Q: String to Dictionary Word Count So I'm having trouble with a homework question.

Write a function word_counter(input_str) which takes a string input_str and returns a dictionary mapping words in input_str to their occurrence counts.

So the code I have so far is:
def word_counter(input_str):

'''function that counts occurrences of words in a string'''

    sentence = input_str.lower().split()

    counts = {}

    for w in sentence:
        counts[w] = counts.get(w, 0) + 1

    items = counts.items()
    sorted_items = sorted(items)

    return sorted_items

Now when I run the code with a test case such as word_counter("This is a sentence") in the Python shell I get the result of:
[('a', 1), ('is', 1), ('sentence', 1), ('this', 2)]

Which is what is required. However, the test code that is used to check the answer is:
word_count_dict = word_counter("This is a sentence")
items = word_count_dict.items()
sorted_items = sorted(items)
print(sorted_items)

And when I run it with that code I get the error:
Traceback (most recent call last):
File "<string>", line 2, in <fragment>
builtins.AttributeError: 'list' object has no attribute 'items'

Not sure how to change my code so that it works with the test code given.

A: It looks like you found the error in the original code, so you may be all taken care of.
That said, you can tighten-up the code by using collections.Counter().  The example for it in the docs closely matches your assignment:
>>> # Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
 ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]

A: Figured out what I was doing wrong.  Just remove the last 2 lines of code and return the counts dictionary.  The test code does the rest :)


text:
Q: Calculate Running total of active users by groups I need to find the running total of active users in the system based on the groups
If a user is currently suspended he shouldn't be considered in the current count but should be considered when he was active
For Ex
A user got suspended in april 2019 so he should be considered as a active user till all the counts in march
The users table contains the status ('Active'/'Suspended') and updatedon column
I have written the code but it doesn't give me the desired result as it only considers the current active users
 SELECT DISTINCT Concat(year(b1.created_at),'-',monthname(b1.created_at)) Date,c1.name as 'GroupName',
(
    select
    count(distinct(b.user_id))      from
        users u2 join teams_users b on u2.id = b.user_id join teams c on b.team_id = c.id
    where
    year(b.created_at)*100 + month(b.created_at) <= year(b1.created_at)*100+month(b1.created_at)
     and
    u2.organization_id =1690
             and u2.status = 'Active'
    and c.organization_id = 1690
     and c.id =c1.id
    ) total_users
 from users u1 join teams_users b1 on u1.id = b1.user_id
 join teams c1 on b1.team_id = c1.id
 where
     u1.organization_id =1690  and u1.status = 'Active'

Users
 UserId|CreatedOn|Status|Updatedon

Teams
 Id|Name

Team_users
 Team_id|User_id|CreatedOn

A: Here's a sample query that will get you a total number of users in a given month, per month, per team:
with generator as
(
SELECT 0 n UNION ALL SELECT 1  UNION ALL SELECT 2  UNION ALL
   SELECT 3   UNION ALL SELECT 4  UNION ALL SELECT 5  UNION ALL
   SELECT 6   UNION ALL SELECT 7  UNION ALL SELECT 8  UNION ALL
   SELECT 9   UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL
   SELECT 12
),
user_to_team as
(
   select user_id
        , team_id
        , tu.created_at as date_joined
        , case
            when u.status = 'suspended'
            then u.updatedon
            else curdate()
          end member_until
     from team_users tu
     join users u
       on u.id = tu.user_id
), periods as
(
   select year*100 + month as period
     from (select 2018+n as year from generator where n < 2) x
    cross
     join (select 1+n as month from generator where n<12) y
)
select periods.period
     , t.id
     , count(u2t.user_id)
  from periods
  join teams t
    on year(t.created_at) * 100 + month(t.created_at) <= periods.period
  left outer
  join user_to_team u2t
    on periods.period between year(u2t.date_joined)*100 + month(u2t.date_joined) and year(u2t.member_until)*100 + month(u2t.member_until)
   and u2t.team_id = t.id
 where periods.period <= year(curdate())*100 + month(curdate())
group by periods.period, t.id
order by periods.period, t.id

generator CTE is for generating numbers, we'll need that in periods to generate a list of year-months (yyyymm). If you have a numbers table, you can use that. user_to_team CTE just lists the relations between users with when they joined (record in user_teams created) and until when they were members (either updatedon of the user if they are suspended, or current date). Then it's just a matter of joining our periods to teams and the user_to_team to that based on dates - teams are joined ever since they were created and members to period between which they existed.
Here's a working sample on dbfiddle
There are two teams:

*

*team 1 created in 2019-01

*team 2 created in 2019-02

Users:

*

*user 1, active

*user 2, suspended since 2019-03

Team to User:

*

*user 1 in team 1 since 2019-01, in team 2 since 2019-03

*user 2 in team 1 since 2019-03, in team 2 since 2019-03


text:
Q: Responsive Website Header for Wordpress I need the header on the website I'm working on the be responsive. Right now the image will be cropped when resizing. I would like it to maintain the same ratios no matter the size.
The website is: hoganfrick.com
A website that has a header similar to this is: xiiplvs.com.

A: Your style.css has media queries resizing the image. If you have a custom.css you can override this by giving your img id #logo the width and height you desire.


text:
Q: Dimensionality reduction with b-splines - does it have to have an inverse operation? Part A
From LA course, my understanding is that:

*

*basis change (i.e. when we stay in the same dimension) amounts to change of coordinates, and is accomplished by simply multiplying change-of-basis matrix by original vector;

*projection, on the other hand, by definition entails decrease in dimension and  [almost?] inevitably loss of data, and is accomplished via projection matrix that always involves inverse (or more likely pseudo-inverse).
If the above fully accurate? What have I missed?
Part B
(if this is more appropriate to CrossValidated, I'll show myself out)
in this R code:
# `data` is say 1000 x 50 data matrix
require(fda)
n = 1000  # no of observations
k = 5    # reduced dimensionality
x = seq(0, 1, length.out = n)
splinebasis_B = create.bspline.basis(c(0, 1), k)
base_B = eval.basis(x, splinebasis_B)
data_reduced = data %*% base_B

as I understand, the last operation does not project (or otherwise reducingly transform)  data just yet, but rather it gives us data_reduced on which we can run some fitting algos (regressions, trees etc.).
For this reason, we cannot claim that data_reduced is compressed version of data.
Is this correct? Am I missing anything? What's the right way to think about data_reduced? It's clearly mapped to a lower-dimensional space, and there is loss as data's variance got collapsed during the multiplication with fewer columns... but I feel like somehow data_reduced is not "optimal". It's not the best representation of data in k-dimensional space... What is it then?
Appreciate your help.


text:
Q: python zerorpc and multiprocessing issue I'm implementing a bi-directional ping-pong demo app between an electron app and a python backend.
This is the code for the python part which causes the problems:
import sys
import zerorpc
import time
from multiprocessing import Process

def ping_response():
    print("Sleeping")
    time.sleep(5)
    c = zerorpc.Client()
    c.connect("tcp://127.0.0.1:4243")
    print("sending pong")
    c.pong()

class Api(object):
    def echo(self, text):
        """echo any text"""
        return text

    def ping(self):

        p = Process(target=ping_response, args=())
        p.start()
        print("got ping")
        return

def parse_port():
    port = 4242
    try:
        port = int(sys.argv[1])
    except Exception as e:
        pass
    return '{}'.format(port)

def main():
    addr = 'tcp://127.0.0.1:' + parse_port()
    s = zerorpc.Server(Api())
    s.bind(addr)
    print('start running on {}'.format(addr))
    s.run()

if __name__ == '__main__':
    main()

Each time ping() is called from javascript side it will start a new process that simulates some work (sleeping for 5 seconds) and replies by calling pong on nodejs server to indicate work is done.
The issue is that the pong() request never gets to javascript side. If instead of spawning a new process I create a new thread using _thread and execute the same code in ping_response(), the pong request arrives in the javascript side. Also if I manually run the bash command zerorpc tcp://localhost:4243 pong I can see that the pong request is received by the nodejs script so the server on the javascript side works ok.
What happens with zerorpc client when I create a new process and it doesn't manage to send the request ?
Thank you.
EDIT
It seems it gets stuck in c.pong()

A: Try using gipc.start_process() from the gipc module (via pip) instead of multiprocessing.Process(). It creates a new gevent context which otherwise multiprocessing will accidentally inherit.


text:
Q: Is there a way to cancel a promise? This code works well.
I have a list of available campaigns and another list of active users. For each user, I need to check which campaigns have been shown before. I would like to know if it is possible to dispense with my promise to write undefined in my return matrix.
Is there a way to cancel a promise?
In this case, if there is already a record in the redis node, the answer will be equal to one and I would like to cancel the promise to avoid undefined return.
How to fixed this?
VerificarCampanhaEnvio  : async function(user,campanhas){
     const CampanhaUsers       = [];
     let   sismember           = util.promisify(cliente_redis.sismember).bind(cliente_redis);
     return Promise.all(campanhas.map(async(campanha) =>{
          return sismember("subscription:"+user.id,campanha.id_campanha).then((response)=>{
              console.log('response',user.id,response,campanha.id_campanha);
              if(response  != 1){
                  data          = {};
                  data.user     = user;
                  data.campanha = campanha;
                  return data;
               }
          });
      })).then((response) => {
          return response;
      });
},

FireMessage       : function(){
    Sucesso  = function(data,campanhas){
        if(campanhas.length > 0){
            self.GetInscritosAtivos(function(users){
                if(users     !== false){
                    var contador = 1;
                    users.map(async(user) =>{
                        var finalArray;
                        console.log('user.id',user.id);
                        finalArray   = await self.VerificarCampanhaEnvio(user,campanhas);
                        var filtered = finalArray.filter(function(el){ return el != null; });
                        if(filtered.length > 0) self.EnviarMensagem(filtered[0]);
                    });
                }else console.log('fnpush:FireMessage','Nao existe subscricoes ativas');
            });
        }else console.log('fnpush:FireMessage','Nao existem campanhas de push disponiveis no
         sistema.');
    }
    data                = {};
    data.zona           = {};
    data.zona.tipo      = 'push';
    data.sucesso        = Sucesso;
    data.falha          = fnCampanha.CampanhaInexistente;
    fnCampanha.GetCampanhas(data);
}


text:
Q: Swift a two views within a collection view controller I want to know how to be able to use multiple views inside a collection view controller besides only having a collection view. I have looked at different tutorials but they only show me how to have two different views in different view controllers. I want to be able to put labels above my collection view cells. But it won't let me drag a normal view onto the collection view controller so I cannotput any labels above my cells this it what happens when I try to do it. The labels get pushed to the top left corner. Any help is greatly appreciated.

A: You can use a UIViewController instead of a UICollectionViewController.
To do so you can follow the accepted answer here: How to make a simple collection view with Swift


text:
Q: Save image from another model/controller via url and not form post Another team member has written the feature to allow users to upload a photo using a http form and the Rails Paperclip gem.
I am currently working on a feature to import a list of photos from the users Facebook album.
I currently have a list of the Facebook image URLs that need to be saved. I am able to get rails to download them and save to a location but I can't figure out how to trigger the paperclip process.
Where is the best place to add in my code to download the image from the URL?
Any ideas appreciated, thanks.

A: I have found the following question that answers my question.
Paperclip fetch image directly via url
Here's what i'm doing to save my image:
      photo = Photo.new
      photo.picture_from_url("http://image_url_here..")
      photo.name = "photo_name"
      photo.description = "photo_description"
      photo.user_id = current_user.id
      photo.album_id = album_id
      photo.save

And I have this function in the Photo model. Note, picture is the image field that paperclip uses.
def picture_from_url(url)
    self.picture = open(url)
end


text:
Q: Spyder IDE; resetting IPython console state due to weird logging issue In one of the scripts logging is set up like so:
logging configuration - two handlers
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('logfile')
fh.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(ch)

Pretty usual logger, right? Sure, yet it causes Spyder's IPython console to behave in a weird way.
Each subsequent script launch (Spyder's 'Run' through internal IPython console) increments the number of times each one of the log messages is being logged, i.e. the second time the script is launched the message appears twice, third time three times and so on.
2018-12-06 17:03:44,888 - root - DEBUG - Start.
2018-12-06 17:03:44,891 - root - DEBUG - Exit.
2018-12-06 17:03:45,982 - root - DEBUG - Start.
2018-12-06 17:03:45,982 - root - DEBUG - Start.
2018-12-06 17:03:45,984 - root - DEBUG - Exit.
2018-12-06 17:03:45,984 - root - DEBUG - Exit.
2018-12-06 17:03:49,739 - root - DEBUG - Start.
2018-12-06 17:03:49,739 - root - DEBUG - Start.
2018-12-06 17:03:49,739 - root - DEBUG - Start.
2018-12-06 17:03:49,742 - root - DEBUG - Exit.
2018-12-06 17:03:49,742 - root - DEBUG - Exit.
2018-12-06 17:03:49,742 - root - DEBUG - Exit.

Restarting the IPython's kernel or spanning a new console instance resets this behaviour. 'Resetting variables' seems to have no effect on this, should it?
I think new instances of 'fileHandlers' are added to the 'logger' object on each subsequent launch. Note exact same timestamp on each of the duplicate log entries.
Any ideas how to avoid / fix this?

A:
I think a new instance of 'fileHandler' is added to the 'logger' object on each subsequent launch

Yes, I think that's right. To avoid this, you can detect if fh and ch are already defined, so you don't redefine them and add them to logging on each run.
For that you could add a code like this:
from IPython import get_ipython

if not 'fh' in get_ipython().user_ns:
    fh = logging.FileHandler('logfile')
    fh.setLevel(logging.DEBUG)
    ...

and the same for ch.


text:
Q: NaN в таймере в Safari

var YearS = 2020;
var MonthS = 03;
var DayS = 20;
var HourS = 12;
var MinS = 00;

function updatecountdown() {
  var now = new Date();
  timeN = (now.getMinutes()) + now.getHours() + now.getDate() + now.getMonth() + now.getFullYear();
  time = (MinS - 1) + HourS + DayS + MonthS + YearS;
  if (time == timeN) {
    window.location.reload();
  }
  setTimeout(updatecountdown, 1000);
}
updatecountdown();

function getTimeRemaining(endtime) {
  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  var days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime) {
  var clock = document.getElementById(id);
  var daysSpan = clock.querySelector('.days');
  var hoursSpan = clock.querySelector('.hours');
  var minutesSpan = clock.querySelector('.minutes');
  var secondsSpan = clock.querySelector('.seconds');

  function updateClock() {
    var t = getTimeRemaining(endtime);

    daysSpan.innerHTML = t.days;
    hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
    minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
    secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

    if (t.total <= 0) {
      clearInterval(timeinterval);
    }
  }

  updateClock();
  var timeinterval = setInterval(updateClock, 1000);
}

var deadline = "20 03 2020 12:00:00";
initializeClock('countdown', deadline);

    ДНЕЙ

    ЧАСОВ

    МИНУТ

    СЕКУНД

Возникла проблема. Создал JS таймер. Во всех браузерах корректно работает, а Safari вместо цифр пишет NaN. В консоли ошибок нет.
Прикладываю код таймера

A: Я не знаю, как в Сафари учитываются/передаются установки локализации. Сто против одного, что не парсится дата "20 03 2020 12:00:00";. Используйте
var deadline = new Date(2020, 3, 20, 12, 0, 0);

Имейте в виду, что месяц 3 - в данном случае апрель.

У меня в Chrome тоже NaN - северо-американская локализация - месяц перед числом.

A: Проблема в дате, которую вы передаете. Такой формат не удается распарсить. 100% рабочий формат, который почти всегда парсится - yyyy-mm-dd hh:mm:ss - 2020-03-20 12:00:00.
Так же, если нет надобности, можно убрать время, оставив только дату - 2020-03-20 - будет так же успешно работать.

var YearS = 2020;
var MonthS = 03;
var DayS = 20;
var HourS = 12;
var MinS = 00;

function updatecountdown() {
  var now = new Date();
  timeN = (now.getMinutes()) + now.getHours() + now.getDate() + now.getMonth() + now.getFullYear();
  time = (MinS - 1) + HourS + DayS + MonthS + YearS;
  if (time == timeN) {
    window.location.reload();
  }
  setTimeout(updatecountdown, 1000);
}
updatecountdown();

function getTimeRemaining(endtime) {
  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  var days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime) {
  var clock = document.getElementById(id);
  var daysSpan = clock.querySelector('.days');
  var hoursSpan = clock.querySelector('.hours');
  var minutesSpan = clock.querySelector('.minutes');
  var secondsSpan = clock.querySelector('.seconds');

  function updateClock() {
    var t = getTimeRemaining(endtime);

    daysSpan.innerHTML = t.days;
    hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
    minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
    secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

    if (t.total <= 0) {
      clearInterval(timeinterval);
    }
  }

  updateClock();
  var timeinterval = setInterval(updateClock, 1000);
}

var deadline = "2020-03-20 12:00:00";
initializeClock('countdown', deadline);

    ДНЕЙ

    ЧАСОВ

    МИНУТ

    СЕКУНД


text:
Q: ListView reusing old images I created a plugin using Picasso and it uses the android.widget.ImageView to load the cached image into.
The plugin works fine if using a Repeater but whenever i try using it with a ListView after scrolling past about the 7th item the ListView begins to reuse old images even if the image source is different

A: The reason why is because list views reuse the entire fragment; so what happens is that your img being reused gets the old image shown unless you clear it.
I actually use Picasso myself; and this is my current picasso library.
So if you look in my code below, when I set the new .url, I clear the existing image. (I made a comment on the specific line) -- This way the image now show blank, and then picasso loads it from either memory, disk or a remote url (in my case a remote url) and it will assign the proper image.
"use strict";

var Img = require('ui/image').Image;
var application = require("application");

var PT = com.squareup.picasso.Target.extend("Target",{
    _owner: null,
    _url: null,
    onBitmapLoaded: function(bitmap, from) {
        // Since the actual image / target is cached; it is possible that the
        // target will not match so we don't replace the image already seen
        if (this._url !== this._owner._url) {
            return;
        }
        this._owner.src = bitmap;
    },
    onBitmapFailed: function(ed) {
        console.log("Failed File", this._url);
    },
    onPrepareLoad: function(ed) {

    }
});

Object.defineProperty(Img.prototype, "url", {
    get: function () {
        return this._url;
    },
    set: function(src) {
        if (src == null || src === "") {
            this._url = "";
            this.src = null;
            return;
        }
        var dest = src;
        this._url = dest;
        this.src = null; // -- THIS IS THE LINE TO CLEAR THE IMAGE
        try {
            var target = new PT();
            target._owner = this;
            target._url = dest;
            var x = com.squareup.picasso.Picasso.with(application.android.context).load(dest).into(target);
        } catch (e) {
            console.log("Exception",e);
        }
    },
    enumerable: true,
    configurable: true
});

Please note you only need to require this class once, then it attaches itself to the <Image> component and adds the new .url property; this allows me to use this in the Declarative XML in all the rest of the screens and when I need picasso, I just use the .url property to have picasso take over the loading of that image.


text:
Q: Append on the same line bash Using bash, I need to add to the end of a file, on the same line a string followed by the date. Example "Rebooted on Mon Aug 13 10:38:56 PDT 2012"
echo -n "Reboot done on " ; date

This gives me what I want on one line, but I can't append to the text file.
echo -n "Reboot done on " ; date > test.txt

This does not seem to work for me. It only gives me the date.
Thanks in advance.

A: This is because your output Reboot done on with echo and then you execute date and put its output into the file. Try this instead:
echo "Reboot done on $(date)" > test.txt

A: Try this
echo -n "Reboot done on `date`" > test.txt

A: Here's another way:
(echo -n "Reboot done on "; date) > test.txt


text:
Q: After skiping the test, still jest takes long time, how to make it to 0 time I am doing testing with jest.js in my angular project. It seems that, my whole testing process take closly 45min, which i not requried. I decided to skip some of unwanted tests from the project. for that I am skipping it out.
But still I am getting 25.36s for the skipped file. how to make it to 0s instead? here is my test case: (xdescribe) i skipped.
import { TestBed, inject, getTestBed } from '@angular/core/testing';
import { StoreModule } from '@ngrx/store';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { IboSharedLibModule } from '@ibo/ibo-shared-lib';
import { CourseMappingAddGuard } from './course-mapping-add.guard';
import { HttpClient } from '@angular/common/http';
import { provideMockStore, MockStore } from '@ngrx/store/testing';
import { Router } from '@angular/router';
import * as subscribe from '../previous-course-linkage/state/selectors/course-mapping.selector';

xdescribe('CourseMappingAddGuard', () => {
  let injector: TestBed;
  let guard: CourseMappingAddGuard;
  function createTranslateLoader(http: HttpClient) {
    const store: MockStore<any> = null;
  }
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [],
      imports: [
        StoreModule.forRoot({}, { runtimeChecks: { strictStateImmutability: true, strictActionImmutability: true } }),
        HttpClientTestingModule,
        IboSharedLibModule,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: createTranslateLoader,
            deps: [HttpClient],
          },
          isolate: true,
        }),
      ],
      providers: [
        CourseMappingAddGuard,
        provideMockStore({
          selectors: [],
        }),
      ],
    });
    injector = getTestBed();
    guard = injector.get(CourseMappingAddGuard);
  });

  it('should redirect to parent page if no data available', () => {
    expect(guard.canActivate()).toEqual(false);
  });
});

here is the test result:
$ jest course-mapping-add.guard.spec.ts
Test Suites: 1 skipped, 0 of 1 total
Tests:       1 skipped, 1 total
Snapshots:   0 total
Time:        16.232s, estimated 20s
Ran all test suites matching /course-mapping-add.guard.spec.ts/i.
Done in 25.36s.

any one please help me to understand? thanks in advance.


text:
Q: Titanium Alloy: Can't Get Row Data To Print To A New Row It Is Always Overwriting The Previously Written Data I was hoping one of you could help me figure out why my row data keeps writing to the same row and overwriting the previously written data instead of starting on a new row after every iteration. Here's what I have so far:
This alloy.js file below gets the information I need for the app from the server and passes it to the formateData() function in the index.js file.
alloy.js
GetDataRequest("http:somejsondata/data.json");

 function GetDataRequest(url)
 {
    var xhr = Ti.Network.createHTTPClient({
    onload: function(e)
    {
        Alloy.Globals.formateAnimalData(JSON.parse(xhr.responseText));
    },

    onerror: function(e) {
        Ti.API.debug("STATUS: " + this.status);
        Ti.API.debug("TEXT:   " + this.responseText);
        Ti.API.debug("ERROR:  " + e.error);
        alert('There was an error retrieving the remote data. Try again.');
    },
    timeout:5000

    });
    xhr.open("GET", url);
    xhr.send();
}

index.js
var appData = [];

Alloy.Globals.formateAnimalData = function(data)
{
    console.log("I was also called");
    for (var i = 1; i <=8; i++)
    {
        var row = {
            name: data.animals[i].name,
            animal: data.animals[i].animal,
            food: data.animals[i].food
        };
        appData.push(Alloy.createController('index', row).getView());
        //console.log(appData);
    }
};

var args = arguments[0] || {};

$.name.text = args.name || '';
$.animal.text = args.animal || '';
$.food.text = args.food || '';

$.table.setData(appData);
$.index.open();

index.xml
<Alloy>
    <TabGroup id='index'>
        <Tab title="Tab 1" icon="KS_nav_ui.png">
            <Window id='main' class='' title="Zoo">
                <TableView>
                    <TableViewRow id='table'>

                    </TableViewRow>
                </TableView>
            </Window>
        </Tab>
    </TabGroup>
</Alloy>

I should note that the:
$.table.setData(appData);

line in the index.js file doesn't work. The data still prints to the screen even if this line is not in there. The reason for this I think is because the following line:
appData.push(Alloy.createController('index', row).getView());

is not pushing a row of objects into the appData array and infact when I log the contents of the appData array to the screen I get:
           (
[INFO] :       "[object index]",
[INFO] :       "[object index]",
[INFO] :       "[object index]",
[INFO] :       "[object index]",
[INFO] :       "[object index]",
[INFO] :       "[object index]",
[INFO] :       "[object index]",
[INFO] :       "[object index]"
[INFO] :
           )

I am just trying to get it so that it prints the animals: Name, Type and Food Preference to row 1 and the next animals Name, Type and Food Preference to row 2 and so on.

A: It's an ugly way to do. In this case, your main problem is this line :
appData.push(Alloy.createController('index', row).getView());

using getView() on your index controller will give you the top-level view, in this case the TabGroup of id index.
If you really want to keep it that way, you have to supply 'table' as arguments to ask for the TableViewRow
appData.push(Alloy.createController('index', row).getView('table'));

However, you are assigning to the newly created index controller and not to the original one instantiated by Alloy at starting....
You can try to create another controller named for instance row, and create an associated xml view this way :
row.xml
<Alloy>
    <TableViewRow id="row">

    </TableViewRow>
</Alloy>

row.js
var args = arguments[0] || {};

$.row.text = args.name || '';
$.row.text = args.animal || '';
$.row.text = args.food || '';

And, refactor the rest the following way. I'm using events to communicate easily with the original instantiated index controller.
index.xml
<Alloy>
    <TabGroup id='index'>
        <Tab title="Tab 1" icon="KS_nav_ui.png">
            <Window id='main' class='' title="Zoo">
                <TableView id="table"/>
            </Window>
        </Tab>
    </TabGroup>
</Alloy>

index.js
/* Store rows somewhere */
$._rows = [];

/* Append row each time it's needed */
$.addEventListener('newrow', function (newrowEvent) {
    $._rows.push(newrowEvent.row);
});

/* Refresh only on demand */
$.addEventListener('refreshrows', function () {
    $.table.setData($._rows);
});

$.index.open();

alloy.js
/* ...
   Your previous function with the call to formateAnimal updated
*/

function formateAnimalData(data) {
    for (var i = 1; i <=8; i++) {
        var rowContent = {
            name: data.animals[i].name,
            animal: data.animals[i].animal,
            food: data.animals[i].food
        };
        Ti.app.fireEvent('newrow', {
            row: Alloy.createController('row', rowContent).getView()
        });
    }
    Ti.app.fireEvent('refreshrows');
};

This should be a workaround a bit nicer. Keep in mind that, when you create a controller, the code that you put in the file's scope is executed only once; Also, each time you're calling createController, you'll get a new instance of that kind of controller; Do not try to modify other instances from the new instance.. This is weird and inefficient.
Finally, avoid putting bloc scopes above functions or control structures.
for ( ...; ...; ...)
{

}

or
function ()
{

}

are bad ideas. You're in JavaScript and semicolons aren't necessary for each statement or at least, the compiler will not complain and you're likely to obtain strange silent errors ...


text:
Q: message queue thinking We have implemented a message queue by using C# Queue. We know we only have ONE consumer to take available message out from the queue for processing with a while loop. We also know there is only ONE producer to put message onto the queue.
We have a lock on above message queue to make sure the consumer and producer cannot access the queue simultaneously.
My question is is that lock necessary? If the Queue increase its Count property AFTER an item is actually added and if the consumer check the Count before retrieve, the consumer should get a complete message item even we don't have that lock. Right? So we will not face a partial message item issue. Then we can get rid of that lock?
That lock will slow down the system and occasionally we can see the retrieve thread is blocked for a while because we have a very heavy producer.
EDIT:
Unfortunately we are using .Net 3.5.

A: The lock is necessary, if you're using Queue<T>.  You could easily remove this by replacing that with ConcurrentQueue<T>, however, you may want to consider simplifying this code by replacing it with a BlockingCollection<T>.
This would allow your consumer to eliminate the lock and while checking, and just do a single foreach on collection.GetConsumingEnumerable().  The producer can eliminate the lock and add items as needed.  It also would easily allow you to scale up to using multiple producers, since you mentioned you have a "very heavy producer" at the moment.

A: See ConcurrentQueue.

A: The real problem is that internal data structures of the queue may be being mutated whilst an enqueue or dequeue is happening, and during this period the data structure is in an indeterminate state from the point-of-view of another thread.
For example, an enqueue may require internal data structures to be expanded, where a new structure is created, and old items are copied form an old structure to a new structure. There will be many steps involved in this process where at any time it would be dangerous for another thread to access the queue as the operations are not complete.
Therefore, during enqueue\dequeue you have to lock to make these operation appear to be logically atomic.
You may try the new ConcurrentQueue class in .Net 4.0 as this possibly has better performance characteristics as it uses a non-locking algorithm.

A: No, this won't work consistently... why?
Let's disassemble the two methods we are going to be calling concurrently from two threads (one read & one writer):
public T Dequeue()
{
    if (this._size == 0)
    {
        ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EmptyQueue);
    }
    T local = this._array[this._head];
    this._array[this._head] = default(T);
    this._head = (this._head + 1) % this._array.Length;
    this._size--;
    this._version++;
    return local;
}

public void Enqueue(T item)
{
    if (this._size == this._array.Length)
    {
        int capacity = (int) ((this._array.Length * 200L) / 100L);
        if (capacity < (this._array.Length + 4))
        {
            capacity = this._array.Length + 4;
        }
        this.SetCapacity(capacity);
    }
    this._array[this._tail] = item;
    this._tail = (this._tail + 1) % this._array.Length;
    this._size++;
    this._version++;
}

Given the above code three of the variables are safe if (and only if) there is adequate capacity in the queue.  the fields for _array, _head, and _tail are either unmodified or modified in only one of the two methods above.
The reason you cannot remove the lock() is that both methods modify _size and _version.  Though arguably the collision on _version could be ignored, the collision on _size would cause some undesired and unpredictable behavior.

A: BTW, Lockless queues for a single reader and a single writer are fairly easy to write.  This is a very primitive example of the concept, but it does the job:
class LocklessQueue<T>
{
    class Item
    {
        public Item Next;
        bool _valid;
        T _value;
        public Item(bool valid, T value)
        {
            _valid = valid;
            _value = value;
            Next = null;
        }
        public bool IsValid { get { return _valid; } }
        public T TakeValue()
        {
            T value = _value;
            _valid = false;
            _value = default(T);
            return value;
        }
    }

    Item _first;
    Item _last;

    public LocklessQueue()
    {
        _first = _last = new Item(false, default(T));
    }

    public bool IsEmpty
    {
        get
        {
            while (!_first.IsValid && _first.Next != null)
                _first = _first.Next;
            return false == _first.IsValid;
        }
    }

    public void Enqueue(T value)
    {
        Item i = new Item(true, value);
        _last.Next = i;
        _last = i;
    }

    public T Dequeue()
    {
        while (!_first.IsValid && _first.Next != null)
            _first = _first.Next;

        if (IsEmpty)
            throw new InvalidOperationException();//queue is empty

        return _first.TakeValue();
    }
}

A: You should be Locking; the class isn't threadsafe.  If you're using the Queue in System.Collections, there is a thread-safe Queue handy (System.Collections.Queue.Synchronized() returns such a Queue).  Otherwise, be sure to use the object provided Queue<T>.SyncRoot to synchronize:
using System.Collections.Generic;
public static class Q_Example
{
    private readonly Queue<int> q = new Queue<int>();
    public void Method1(int val)
    {
        lock(q.SyncRoot)
        {
            q.EnQueue(val);
        }
    }

    public int Method2()
    {
        lock(q.SyncRoot)
        {
            return q.Dequeue();
        }
    }
}

A: ConcurrentQueue is available even if you're using .NET 3.5.  The Reactive Extensions includes what used to be the Parallel Extensions to .NET 3.5--the precursor to the Task Parallel Library that is included in .NET 4.0.


text:
Q: Google Calendar: Sync recently created calendar within my Google account I just played around with the Google Calendar Java API within my Scala Webframework and managed to create a new calendar programatically. After that, I create a new event within that calendar.
My problem is, that the event in the new calendar does not seem to be synced with my client devices (my tablet). However, if I create an event in my "primary" calendar, I immediately see the event on all of my devices.
If I go to https://www.google.com/calendar/syncselect, the recently created calendar is checked. So actually I would expect all events to be synced on my devices.
I'm using the JAVA API within a Scala context:
def addCalendar(serviceCalendar: com.google.api.services.calendar.Calendar): com.google.api.services.calendar.model.Calendar = {

    val calendar = new Calendar()
    calendar.setSummary("test calendar")
    serviceCalendar.calendars().insert(calendar).execute()
  }
 //...

 //code fragment where a new event is inserted into an existing calendar
 val credential = new GoogleCredential().setAccessToken(token.get.value)
 val calendar = Auth.getCalendarService(credential)
 //create a new test calendar
 val testCalendar = addCalendar(calendar)
 val event = createEvent

 //insert new event into "primary" calendar.
 calendar.events().insert("primary", event).execute()
 //insert event into the new calendar
 calendar.events().insert(testCalendar.getId(), event).execute()

Both events appear in the Google Calendar web interface. However only the event in the "primary" calendar is synced.
If I look into the "calendar list" of my Android (Samsung S Planner, Android 4.3.) application, I don't see the recently created calendar as "in sync". (The primary calendar is marked as in sync!).
So I guess this is the reason why I see the "primary event" but not the other one. But actually I would expect Google to send some kind of push notification that a new calendar has been added to the account.
Can I enforce that programatically? Or is it simply a matter of time?

A: Syncselect only influences iCalendar, iOS and other CalDAV clients. It's not used for Android. In there the toggle for calendar syncing is on the device and AFAIK needs to be done manually.


text:
Q: Globalizing runtime generated assemblies Background
A project installs some files that contain all the elements to define a UserControl - some user source, a CodeCompileUnit for designer code, and a resx file. At runtime, these files are compiled into an assembly and the classes are consumed by our main application (the assembly is only updated when necessary).
Question
The project has to be globalized and as part of that process, there is a need to provide localizations of these files. Two options are either to allow the inclusion of additional resx files for different locales (either within the same files or as additional side-by-side files) that can be compiled into a satellite assembly for the main assembly, or to provide a copy of each full file for each supported language, compiling the appropriate set for the language being supported.

*

*Does anyone have any other options that might be worth considering?

*What problems might be inherent in either of the solutions I've proposed?

Constraints/Disclaimer
I am aware that the scenario is less than ideal and that better choices could've been made in some areas (like globalizing from the start), but they cannot be changed at this point in the project. I appreciate any advice, solutions, or leads you can provide. Thanks.

A: Create a separate satellite assembly for each culture. This has two benefits:

*

*You can build all of the assemblies in one go, and have a definitive file for each version number and filename combination, rather than it also depending on the culture.

*You can have multiple assemblies in the same installation, and base the language to use on the system language, or a user preference etc. This will make development and testing significantly easier, as you won't need to keep rebuilding and copying files around just for the sake of changing languages.

*It's how .NET i18n is designed to work. While I'm not an expert on .NET i18n ("read Guy Smith-Ferrier's book" is my best advice!) I generally find that frameworks work best when you follow their expected model.

Even if the final part of "building the satellite assembly" is done at runtime (can you do it at install time instead?) you still get the second and third bullet advantages at least. It also means that if you ever do go the more normal route of supplying the satellite assemblies to start with (instead of building them on the user's box) you'll have less to change.
Apologies if I've misunderstood the question though...

A: If you're not planning on adding additional languages after deployment (at least not without a software update), then I'd favor compiling all the additional RESX files into a satellite assembly that you include. That way, they're not user editable once they're deployed.


text:
Q: Java generics - incompatible types Just need some help with this error in code:
interface ParticleId{
    int getX();
}

class ParticleId1 implements ParticleId{
    int a;
    @Override
    public int getX() {
        return a;
    }
}

class ParticleId2 implements ParticleId{
    int a,b;
    @Override
    public int getX() {
        return a+b;
    }
}

interface ParticleInt<K extends ParticleId, O extends ParticleInt<K, O>>{
    O withSmt();
}

class Particle<K extends ParticleId> implements ParticleInt<K, Particle<K>>{
    @Override
    public Particle<K> withSmt() {
        return new Particle<>();
    }
}

class Particle2<K extends ParticleId> extends Particle<K>{
    @Override
    public Particle2<K> withSmt() {
        return new Particle2<>();
    }
}

interface Executable<P extends Particle<? extends ParticleId>>{
    void setExecutableStrategy(ExecutableStrategy<P> s);
}

interface ExecutableStrategy<P extends Particle<? extends ParticleId>>{
    Stream<P> exec(List<P> l);
}

class Particle2Strat implements ExecutableStrategy<Particle2<? extends ParticleId>>{
    @Override
    public Stream<Particle2<? extends ParticleId>> exec(List<Particle2<? extends ParticleId>> l) {
        return l.stream().map(x -> x.withSmt());
    }
}

class ParticleStrat<P extends Particle<? extends ParticleId>> implements ExecutableStrategy<P>{
    @Override
    public Stream<P> exec(List<P> l) {
        return l.stream().map(x -> x.withSmt());
        // [44,38] incompatible types: inference variable R has incompatible bounds
        // equality constraints: P
        // [ERROR] lower bounds: Particle<capture#1 of ? extends ParticleId>
    }
}

The error is shown on the end of the code, and exact description is [44,38] incompatible types: inference variable R has incompatible bounds. equality constraints: P. [ERROR] lower bounds: Particle<capture#1 of ? extends ParticleId>.
Quick fix that I found working is just manually casting lambda to (P) like (P)x.withSmt(). Anybody knows more proper way to fix this if possible at all?
I just updated the code so it is not using anymore Integer but ParticleId interface.
UPDATE
After update I now have this problem:
class ParticleStrat<P extends ParticleId> implements ExecutableStrategy<Particle<P>>{
    @Override
    public Stream<Particle<P>> exec(List<Particle<P>> l) {
        return l.stream().map(x -> x.withSmt());  //OK NOW
    }
}

class MainExecutable<P extends Particle<? extends ParticleId>> implements Executable<P>{

    private ExecutableStrategy<P> s;

    public MainExecutable() {
        this.s = new ParticleStrat<>();
        //incompatible types: cannot infer type arguments for ParticleStrat<>
        //no instance(s) of type variable(s) P exist so that ParticleStrat<P> conforms to ExecutableStrategy<P>
    }

    @Override
    public void setExecutableStrategy(ExecutableStrategy<P> s) {
        this.s = s;
    }
}

A: Changing the declaration of ParticleStrat class to the following solves the compilation error:
class ParticleStrat<P extends ParticleInt<P>> implements ExecutableStrategy<P>{
    @Override
    public Stream<P> exec(List<P> l) {
        return l.stream().map(x -> x.withSmt());
    }
}

This way x.withSmt() is guaranteed to return P.
EDIT following the change in your question:
This passes compilation:
class ParticleStrat<K extends Integer> implements ExecutableStrategy<Particle<K>>{
    @Override
    public Stream<Particle<K>> exec(List<Particle<K>> l) {
        return l.stream().map(x -> x.withSmt());
    }
}

And after your latest update:
class ParticleStrat<K extends ParticleId> implements ExecutableStrategy<Particle<K>>{
    @Override
    public Stream<Particle<K>> exec(List<Particle<K>> l) {
        return l.stream().map(x -> x.withSmt());
    }
}

As for your latest problem, the same approach can work:
class MainExecutable<K extends ParticleId> implements Executable<Particle<K>>{

    private ExecutableStrategy<Particle<K>> s;

    public MainExecutable() {
        this.s = new ParticleStrat<>();
    }

    @Override
    public void setExecutableStrategy(ExecutableStrategy<Particle<K>> s) {
        this.s = s;
    }
}


text:
Q: Function in button So I'm working on a wordpress theme and it's really twisted. The problem is I'm comfortable just with html and css, as I'm a code noob, so I would really appreciate your help here.
The problem here is that I want to put a tracking script and a redirect on a specific button. I'd now how to do this if I'd find the button's html form.
But when I go to the code in the page where the button is, this is the only thing showing regarding the button
    <?php BookYourTravel_Theme_Utils::render_submit_button("primary-btn",
    "submit-accommodation-booking", esc_html__('TRIMITE REZERVAREA',
    'bookyourtravel')); ?>

*

*BookYourTravel is the theme

I know you should maybe see all the files to know what to do, as this doesn't seem as enough info.
But I also have a functions.php file. Should I look there? Do you have any idea where should I go?
Thank you a lot. Really stuck here.

A: Are you writing the theme yourself or are you working with someone else's theme? If you're working on someone else's theme, I would reccommend looking into building a child theme so if you change some code, the OG theme is still there in it's entirety and if they update the theme, your code wont get destroyed in the update. There are tons of tutorials on how to set up a child theme and theres a plugin that will make it for you called Child Theme Configurator if you're not too keen on doing it yourself.
You should be super careful when you're editing functions in your theme(especially if you're new to PHP), but that's where this html is being generated. One of those functions is the thing that's generating your html. If you find where the function is held, you could probably change it so it echos the extra code you're looking to implement but it would be on every button that this function generates throughout your site.

A: You didn't really give enough information for us to do anything. So if you are really pulling your hair on this one just replace the old button with a new button that you wrote. I can help you out on that end if you don't know javascript.


text:
Q: Is there something like a function pattern test? Is there something like a function pattern test?
function[x_?FunctionQ]:=Module[{},]

In order that Mathematica can tell if the argument is a function or a parameter?