Communication behind firewall

Question: I am trying to solve a problem that appear to be simple but I can't find a clean architecture.
The problem: I have a client trying to access grafana in a Local network.
   |Router|------|Client
          |         |
          |------|Grafana

When you are behind the router (and thus the firewall) then you can easily access grafana and use it. I would like the same to happen when outside of the local network.
Client|------|Router|-------|Grafana

Easy solution:
The basic solution is port forwarding and to simply open port X on the router. I don't want this solution because I can't open ports (for different reason unrelated).
Better Idea I am thinking of setting up the following architecture where a new server is introduced.
Client|------|Server|-------|Router|-------|Grafana

The idea, is that Server will maintain a connection  with Grafana. This will prevent any port forwarding as grafana server is making the first move.
Then if the client wants to access grafana, it will access server that will redirect it to grafana.
After the first call, Ideally I would like the client to establish a direct connection with grafana, without going through the server.
Also grafana is an exemple/tuto, any other solution with http communication would just be fine
Questions:

Is that possible ?
It seems that there are tools (CND, reverse proxy) but they don't exactly fit my needs, or maybe I just don't know how to use them ?
Which tools to use on server A and B (websocket, socket.io, Nginx, Apache ...). Both servers are using linux.

Thanks !
Answer: This looks a lot like a question for Super User, not Serverfault.
That said: The router in your picture is a computer that decides how traffic from the Internet can communicate with resources in your network and vice versa. Placing another computer in front of your router effectively makes that computer your router: turtles all the way down.
So yes, in an IPv4 setting with a single available publicly routable IP address, port forwarding, either directly (if presenting a single service) or via a reverse proxy (if presenting multiple ones over the same port) is the way to go.
Additionally you can harden your network by placing publicly available resources in a separate logical network (what's usually called a DMZ), with strict firewall rules for what traffic is allowed from servers in the DMZ to servers in your server networks (for example communication with the database underlying the service).

Communication behind firewall


Rails 3 :mobile MIME type throws 406 error after attempt to load content with JavaScript

Question: I'm following Railscast #199 to allow my web app to be viewed in a mobile browser. It works great, except when I try to access information in a tabbed interface using UJS in the mobile version. Clicking on the tabs works in the web app, but on the mobile side I get a 406 error. (I tried this after setting the User Agent as iPhone in Safari. I also tested on iOS Simulator and my iPhone. Neither time loaded anything.)
Below is some code for one of the tabs. Can anyone can help me target what is going on? Here is my code.
Here's the profile_about action in profiles_controller.rb:
def profile_about
  @profile = Profile.find(params[:id])
  respond_to do |format|
    format.js { render :layout => nil }
  end
end

In my profiles/show.mobile.erb (this is the exact same code as in profiles/show.html.erb):

<%= link_to "Cred", profile_cred_profile_path, :class=> 'active', :remote => true %>

<%= link_to "About", profile_about_profile_path, :class=> 'inactive', :remote => true %>

  <%= render :partial => 'profile_cred' %>

(NOTE: I have a file for profiles/_profile_about.html.erb and profiles/_profile_about.mobile.erb.)
Here is my profiles/profile_about.js.erb:
$("#tabs-1").html("<%= escape_javascript(render(:partial => 'profile_about'))%>");

My Heroku logs showing the 406:
2012-03-08T03:02:55+00:00 app[web.1]: Started GET "/profiles/1/profile_about" for 188.8.131.52 at 2012-03-08 03:02:55 +0000
2012-03-08T03:02:55+00:00 heroku[router]: GET myapp.com/profiles/1/profile_about dyno=web.1 queue=0 wait=0ms service=14ms status=406 bytes=1
2012-03-08T03:02:55+00:00 app[web.1]:   Processing by ProfilesController#profile_about as JS
2012-03-08T03:02:55+00:00 app[web.1]:   Parameters: {"id"=>"1"}
2012-03-08T03:02:55+00:00 app[web.1]: Completed 406 Not Acceptable in 3ms
2012-03-08T03:02:55+00:00 heroku[nginx]: 18.104.22.168 - - [08/Mar/2012:03:02:55 +0000] "GET /profiles/1/profile_about HTTP/1.1" 406 1 "http://myapp.com/profiles/1" "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A405 Safari/7534.48.3" myapp.com

From running tail -f logs/development.log:
Started GET "/profiles/1/profile_about" for 127.0.0.1 at Wed Mar 07 22:35:36 -0500 2012
  Processing by ProfilesController#profile_about as JS
  Parameters: {"id"=>"1"}
  PK and serial sequence (5.4ms)   SELECT attr.attname, seq.relname
 FROM pg_class seq,
 pg_attribute attr,
 pg_depend dep,
 pg_namespace name,
 pg_constraint cons
 WHERE seq.oid = dep.objid
 AND seq.relkind = 'S'
 AND attr.attrelid = dep.refobjid
 AND attr.attnum = dep.refobjsubid
 AND attr.attrelid = cons.conrelid
 AND attr.attnum = cons.conkey[1]
 AND cons.contype = 'p'
 AND dep.refobjid = '"goals_profiles"'::regclass
  PK and custom sequence (2.5ms)   SELECT attr.attname,
 CASE
 WHEN split_part(def.adsrc, '''', 2) ~ '.' THEN
 substr(split_part(def.adsrc, '''', 2),
 strpos(split_part(def.adsrc, '''', 2), '.')+1)
 ELSE split_part(def.adsrc, '''', 2)
 END
 FROM pg_class t
 JOIN pg_attribute attr ON (t.oid = attrelid)
 JOIN pg_attrdef def ON (adrelid = attrelid AND adnum = attnum)
 JOIN pg_constraint cons ON (conrelid = adrelid AND adnum = conkey[1])
 WHERE t.oid = '"goals_profiles"'::regclass
 AND cons.contype = 'p'
 AND def.adsrc ~* 'nextval'

  Profile Load (1.3ms)  SELECT "profiles".* FROM "profiles" WHERE "profiles"."id" = '1' LIMIT 1
Completed 406 Not Acceptable in 30ms

Comment: Are you in development environment right? What does the log/development.log says about the 500?
Comment: Just updated with the information in my log when I click "about" with a user agent of iPhone.
Answer: There's a few bugs in your code, maybe it's just stackoverflow formatting here but the inner quotes should be ' instead of " , like this:
$("#tabs-1").html("<%= escape_javascript(render(:partial => 'profile_about'))%>");

And this line is casuing your error:
format.mobile.js {render :layout => nil}

This is impossible because the request can only have a single mime type. "mobile" or "js", not both. If you are requesting the "profile_about" action from javascript, then you must respond back to it with js. "format.mobile" should only be used to render a "profile_about.mobile" template.
Hopefully that's at least a step in the right direction for you.
Comment: Thanks. I changed the js.erb file so that the partial is surrounded by single quote instead of double. And I removed `format.mobile.js`. However I'm still getting a `406 error`. I'll paste what's in my log above as an update.
Answer: Probably don't fully answer your question but I was having the 406 status problem, because I've been deploying my app to Phonegap!
It basically happened because the request type didn't match any of the Rails responders in the action.
it was like:
respond_to do |format|
  format.json {
    render( json: (@parishes) )
  }
end

Since I only used it to responde to JSON I changed and it now works:
    render( json:(@parishes) )

A more complete way to deal with this is to figure exactly what responder is being asked for that request, or default to something you know to work
Answer: Turns out this was due to a lacking check for an xhr request in the prepare_for_mobile method. I found the answer in another question. So the below prepare_for_mobile method allows the JS to work:
def prepare_for_mobile
  session[:mobile_param] = params[:mobile] if params[:mobile]
  request.format = :mobile if mobile_device? && !request.xhr?
end


What are good sources for free orchestra scores?

Question: Are there usable free sources for (symphonic) orchestra scores?
I'm talking about legal sources for pieces that are now in public domain.
Comment: Some of the works that you may think are in the public domain in the US have had their copyrights retroactively renewed.  http://chronicle.com/article/A-Professors-Fight-Over/127700/
Comment: @Tangurena Fortunately I don't have to care about USA copyright laws.
Answer: from my bookmarks:

http://www.sheetmusictrade.com/
http://imslp.org/wiki/
http://icking-music-archive.org/index.php
http://www1.cpdl.org/wiki/
http://www.mfiles.co.uk/sheet-music.htm
http://www.bh2000.net/score/ (link dead on 7 Sept 20)
http://www.rowy.net/sheet-music-for-piano.html
http://www.free-scores.com/index_uk.php

plus in French:

http://www.lespartitions.info/gratuites/index.php
http://partitions.metronimo.com/
Comment: IMSLP.org is huge. It has a big list of other music score websites too: http://imslp.org/wiki/IMSLP:Other_music_score_websites
Answer: Don't overlook your local library. I find that university libraries (especially when they have a music program) will have a lot more sheet music than you might think (if your library uses Library of Congress indexing, look under M). Many city public libraries carry orchestral and operatic scores as well (usually at the "main" or "downtown" branch).
Comment: Usually it's not legal to copy those.
Comment: @Let_Me_Be: you are right, they are only for private study purpose. But it can help to decide if you want to use it with your orchestra and look harder for a free source version, invest in commercial material, etc.
Comment: You don't need to copy them.  As a kid with little money, I would borrow one or two at a time, study them for a few weeks, and swap them for others.  If I wanted them for longer, I could always renew them as no one else ever requested them.
Answer: To add to @cardian's list:

http://www.classical-scores.com/free/

http://www.8notes.com/orchestra/

http://www.freesheets.org.uk/

http://www.dlib.indiana.edu/variations/scores/

http://musicaviva.com/fsmd/ (link no longer to music site on 7 Sept 20)

Also:

http://www.bandmusicpdf.org/

http://dme.mozarteum.at/DME/briefe/doclist.php
Answer: One more: http://www.mutopiaproject.org/
Answer: Along the lines of @Tangurena's mention of the local library, you can check things out (pun intended) globally through inter-library loan. Try looking at https://www.worldcat.org/.


Javascript tail recursion instead of loop

Question: In one of Douglas Crockford speeches, He favours the use of tail recursion over loops. this code was presented,
function repeat(myFunc) {
  if (myFunc !== undefined) {
    return repeat(myFunc);
  }
}

I thought to define a myFunc but don't know if a static counter can retain its state during function calls or use a global counter. but being new to javascript I wanted to ask first. How can this be used in an example, say to count down from 10 to 0? Thanks.
Comment: The role of myFunc is irrelavant in the code you have given, either it is undefined from the start, and the function doesn't get called recursively, or it is not, and it runs indefinitely. I don't think Crockford would have presented this code. Maybe you forgot brackets somewhere? I mean: myFunc has to be called at some point...
Comment: where does the countdown happen?
Comment: `function repeat(myFunc, cnt) {
  cnt = cnt || 0;
  if (myFunc !== undefined && cnt !== 10) {
    return repeat(myFunc, ++cnt);
  }
}`
Comment: i think your browser is stuck while doing this the function is never stopped
Answer: You need to call the function myFunc somewhere -- and evaluate the result for further call of repeat.

function repeat(myFunc) {
    if (myFunc()) {
        repeat(myFunc);
    }
}

var count = 10;

repeat(function () {
    document.write(count + '
');
    count--;
    return count >= 0;
});

Answer:
How can this be used in an example, say to count down from 10 to 0?

Pass a Number to repeat, call repeat with decremented number as parameter until variable parameter is equal to 0

function repeat(n) {
  console.log(n)
  if (n) {
    return repeat(--n);
  }
}

repeat(10)
Comment: The name myFunc is a bit misleading in this case :)
Comment: @trincot Yes. Tried to change original `js` at OP  at little as possible. `myFunc` could be any varible; updated variable name to `n`
Comment: @guest271314 your solution does not print zero at the end. not withstanding this, the reason for the question is to understand how to call a function and the number count down was 'just a use case. Poor one I must add.
Comment: @FredJ. _"your solution does not print zero at the end."_ ? Logs `0` at `console` here. Yes, a function could be called to decrement number passed as parameter, though not necessary to achieve expected results. `-`  operator provides same results as calling a function to do the same.
Answer: Here is a version that keeps state without global variable:

function repeat(myFunc, arg) {
    if ((arg = myFunc(arg)) !== undefined) {
        repeat(myFunc, arg);
    }
}

repeat(function (count) {
    document.write(count + ',');
    count--;
    if (count >= 0) return count;
}, 10);

Answer: Not sure if I understand what approach you want, but you can use this to count down recursively
function repeat(myFunc, times) {
  if(times > 0 && typeof myFunc == 'function') {
    myFunc(times);
    repeat(myFunc, times-1);
  }
}
repeat(alert, 10);


Why for-of-loop has not finished running, jump out to run console.log?

Question: Runtime environment

Visual Studio Code v1.15.1 own compiler
Node.js v8.2.1
OS: Windows 10

Description
I want to add "After sort:" between source arry and sort arry, look like this:

But console occasionally shows:

Why for-of-loop  has not finished running, jump out to run console.log ? Source code:
<code>// Random to generate double digits.
function getRandom() {
  return Math.round(Math.random() * 100);
}
// Writing data to the array.
var score = [
  ["a", getRandom()],
  ["b", getRandom()],
  ["c", getRandom()],
  ["d", getRandom()],
  ["e", getRandom()]
];
console.log("Before sort:");

// Print source arry
for (let m of score) {
  console.log(m);
}

// Call sort()
score.sort((a, b) => {
  return b[1] - a[1];
});
console.log("After sort:");

// Print sort arry.
for (let n of score) {
  console.log(n);
}
</code>
Comment: This sure looks like a bug in the inspector.
Comment: yes true, my bad
Comment: So this is a bug of node-inspector  rather than the js code error?
Comment: Yes. Unless you can get the code to output wrongly computed results, this seems to be a problem with the tooling around `console.log`.
Comment: Given the high reproducability and the minimal test case, you probably should report this issue to the developers of Visual Studio Code.
Answer: Seems array is not prepared when you try to print due to accessing same method from array property multiple times and the method contains some numerical calculation so surround by timeout
<code>// Random to generate double digits.
   function getRandom() {
     return Math.round(Math.random() * 100);
    }
   // Writing data to the array.
   var score = [
   ["a", getRandom()],
   ["b", getRandom()],
   ["c", getRandom()],
   ["d", getRandom()],
   ["e", getRandom()]
  ];
  console.log("Before sort:");
  setTimeout(function(){
      // Print source array
      for (let m in score) {
        console.log(m);
       }

      // Call sort()
     score.sort((a, b) => {
         return b[1] - a[1];
     });
     console.log("After sort:");
     for (let n in score) {
       console.log(n);
     }
  },300);
</code>
Comment: sort is not external link , its internal library function. its not async.
Comment: Sorry, your code produces the same error.[Screenshot](https://i.imgur.com/AYqZm8W.png)
Comment: Array should have homogenized elements only here the array having [string, number]
Comment: "*May be reference issue*" - what do you mean? What does your code do different?
Comment: @RajaMohamed Heterogenous arrays are completely fine in JS.
Comment: suspect 'Math.round(Math.random() * 100)' consuming much of time and didt behave like sync in this place
Comment: `Math` is definitely sync and takes hardly any time.
Comment: I m not blaming math alone.  you cant call and execute same method in same time (millisecond equal ) because methods are not instances, I hope time out will work
Comment: You don't understand my mean . If code like this:

```

var score = [["a", 55], ["b", 33], ["c", 44], ["d", 88], ["e", 22]];

for (let m of score) {
  console.log(m);
}
console.log("After sort:");
```

This bug will still appear: [Screenshot](https://i.imgur.com/0fUXBNo.png)
Comment: Still I hope settimeout will help you ,if you don't have best option then try with settimeout.
Comment: @Raja Mohamed Thanks, i will try it.


Como mudar a codificação de multiplos arquivos de ISO-8859-1 para UTF-8?

Question: Eu tenho um projeto (em java) com mais de 100 arquivos, alguns deles estão em ISO outros em UTF8.
Como mudar a codificação de todos os arquivos de ISO para UTF-8 sem perder os caracteres especiais ?
Answer: Se estiver usando o Eclipse:

Abra o Eclipse com seu projeto;
Na aba do "Project Explorer", clique com o botão direito e selecione "Properties";
No menu esquerdo, escolha "Resource" e a direita, em "Text File Encoding" escolha UTF-8;
De OK em tudo;

Se estiver no NetBeans:

Abra o NetBean com seu projeto;
Na aba "Projetos" clique com o botão direito e selecione "Propriedades";
No menu a esquerda, selecione "Códigos-Fonte" e a direita, bem na parte inferior, altere a "Codificação" para UTF-8;

Como você disse que seu projeto tem mais de 100 arquivos em codificação diferente de UTF-8, e você irá altera-los, é bem provável que um monte de caracteres especiais quebrem (mesmo que você não queira). Por exemplo: "á" pode virar "�". E mais, se você ao compilar seu software, você poderá ter erro de unmappable character.
Faça um teste no NetBeans, eu fiz alguns testes aqui e não quebrou os caracteres especiais, diferentemente do Eclipse.
Comment: O UTF-8 inclui todos os caracteres do ISO-8859-1, portanto qualquer conversor bem feito deve conseguir converter os ficheiros todos sem caracteres de erro.
Comment: Fiz três testes aqui convertendo "áãâéêíîóú". Notepad++, Eclipse e Netbeans. Todos os testes convertendo de ISO-8859-1 para UTF-8. Resultado: quebra no Notepad++ e no Eclipse. No Netbeans, a conversão não quebrou caracteres especiais.
Comment: Se a conversão for bem feita, não quebra. Fiz a experiência em Notepad++ e funciona. (escolha explicitamente "Converter para UTF-8", não "Codificar em UTF-8")
Comment: Correto @luiscubal. Eu apenas trocava o encoding.
Answer: É bom configurar seu editor para usar a codificação correta depois, mas inicialmente é muito melhor converter os arquivos de maneira automática.
Se estiver em algum Unix, basta usar o recode:
<code>$ recode utf8 *.java
</code>
Para processar recursivamente:
<code>$ find . -name "*.java" -exec recode utf8 {} \;
</code>
O recode é bastante flexível, dá para fazer muito mais coisas.
Créditos para esta resposta.


maven doesnt recognize execution'a tag from build-helper-maven-plugin

Question: Im trying to export resources (.java, .gwt.xml, .ui.xml) from project A to Project B with Maven. So in project A I write the following pom:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
    <groupId>com.pe.interbank</groupId>
    <artifactId>reactor</artifactId>
    <version>1.0.0</version>
    <relativePath>../reactor</relativePath>
</parent>

<properties>
    <path2>Reactor/pom.xml</path2>
    <path1>C:/Angelo/Workspace/MultipleGWTv2/Reactor/pom.xml</path1>
</properties>

<artifactId>transferencias</artifactId>
<packaging>jar</packaging>
<name>transferencias</name>

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.java</include>
                <include>**/*.gwt.xml</include>
            </includes>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>build-helper-maven-plugin</artifactId>
            <execution>
                <phase>generate-sources</phase>
                <goals>
                    <goal>add-source</goal>
                </goals>
                <configuration>
                    <sources>
                        <source>src/main/java</source>
                    </sources>
                </configuration>
            </execution>
        </plugin>
    </plugins>
</build>

<dependencies>
    <dependency>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>gwt-maven-plugin</artifactId>
        <version>2.4.0</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <version>1.7</version>
    </dependency>
</dependencies>

But when I run Install Maven I got this error:
The build could not read 1 project -> [Help 1]

The project com.pe.interbank:transferencias:1.0.0 (C:\Angelo\Workspace\MultipleGWTv2\Transferencias\pom.xml) has 1 error

 Malformed POM C:\Angelo\Workspace\MultipleGWTv2\Transferencias\pom.xml: Unrecognised tag: 'execution' (position: START_TAG seen ...</artifactId>\r\n\t\t\t\t<execution>... @36:16)  @ C:\Angelo\Workspace\MultipleGWTv2\Transferencias\pom.xml, line 36, column 16 -> [Help 2]

Any know why?
Thanks.
Answer: <execution> element must be surrounded with <executions> collection container, even when you specify a single <execution>.
<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>build-helper-maven-plugin</artifactId>
  <executions>
    <execution>
    ...


Como faço para não precisar ficar fazendo requisição toda hora a api?

Question: Sou iniciante em desenvolvimento .net core e estou desenvolvendo uma aplicação que consome dados de uma api e mostra para os usuários, porém preciso ficar atualizando o site toda hora e isso demora um pouco.
Existe alguma forma de eu armazenar o retorno da api temporariamente em algum lugar?
Classe PageModel, que faz a requisição a api:
public class IndexModel : PageModel
{
  public Global Global { get; private set; }
  public Country[] Countries { get; private set; }

  public async Task OnGetAsync()
  {
    try
    {
      var create = RestService.For<IGetRootobject>("https://api.covid19api.com/summary");
      var result = await create.GetAsync(); // ou var result = create.GetAsync().GetAwaiter().GetResult();
      Global = result.Global;
      Countries = result.Countries;
    }
    catch (Exception e)
    {
      _logger.LogInformation("Erro na requisição http: " + e.Message);
    }
  }
}

Answer: O mais simples pode ser utilizado o Cache in-memory in ASP.NET Core (tradução: Cache na memória) que pode ser configurado em segundos, minutos, dias, etc. a sua permanência na memória da informação, ou seja, conforme a sua necessidade.
Para habilitar esse código no seu projeto no startup.cs no método ConfigureServices chame o método de extensão .AddMemoryCache() com mostrado no código:
public void ConfigureServices(IServiceCollection services)
{
    services.AddMemoryCache(); // adicione essa linha para funciona cache em memoria
    services.AddRazorPages();
}

com isso agora está habilitado pra ser utilizar nas Pages Razor e como está num batalha em algumas perguntas (1 e 2) segue o mesmo exemplo a seguir:
Adicione um propriedade:
public IMemoryCache MemoryCache { get; private set; }

depois no construtor da sua PageModel passe a interface e atribua a propriedade anteriormente criada para a injeção que é passado no construtor:
public MostrarModel(IMemoryCache memoryCache)
{
    MemoryCache = memoryCache;
}

a partir disso tem a possibilidade criar cache das informações na memória de qualquer tipo e por um simples estrutura de decisão pode buscar o valor no cache ou então criar o valor e armazenar no cache por uma quantidade de tempo (no caso exemplo logo abaixo no código completo foi adicionado trinta minutos, mas, como já foi relatado por ser configurado dias e horas a sua maneira):
Código final:
public class MostrarModel : PageModel
{
    public Country[] Countries { get; private set; }
    public IMemoryCache MemoryCache { get; private set; } // cache
    public MostrarModel(IMemoryCache memoryCache) // injeção
    {
        MemoryCache = memoryCache; // atribuição
    }
    public async Task OnGetAsync()
    {
        //chave do cache (cada valor armazenado tem a sua)
        string key = "countries_cache";
        //verificando se o valor está ou não em cache e tomando as medidas
        //dependendo da decisão na estrutura
        if (!MemoryCache.TryGetValue<Country[]>(key, out Country[] values))
        {
            var create = RestService
                .For<IGetRootobject>("https://api.covid19api.com/summary");
            var result = await create.GetAsync();
            Countries = result.Countries;
            //Armazenando em cache
            MemoryCache.Set(key, Countries, System.TimeSpan.FromMinutes(30));
        }
        else
        {
            //recuperando do cache
            Countries = values;
        }
    }
}

A outra forma é com Distributed caching in ASP.NET Core que nesse caso é um informação compartilhada em vários servidores que melhora muito o desempenho e escabilidade e sua configuração é parecida com a anterior:
Adicione o método de extensão:
services.AddDistributedMemoryCache();

e no construtor e no código são bem parecidos com o anterior
private readonly IDistributedCache MemoryCache;
public MostrarModel(IDistributedCache memoryCache)
{
    MemoryCache = memoryCache;
}

e com os métodos GetAsync para recuperar e SetAsync para gravar o cache.

Vários tipos ainda existem como:

Distributed caching in ASP.NET Core
Distributed SQL Server Cache
Distributed Redis Cache
Comment: Qual seria o mais recomendado? Cache in-memory in ASP.NET Core ou Distributed caching in ASP.NET Core ?
Comment: Pode usar cachê in-memory @eduardonogueira


oracle connection open error

Question: I use QTP/UFT for my application testing.
I had to access my oracle DB (11g) to do some DB setup (to update records).
I use oracle.manageddataaccess.dll (referenced to myDBWrapper class library project).
I have below dlls
(myDBWrapper is the one I created - where the issue is present)

My connection string:
Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=<HOST>)(PORT=<PORT>>)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=<SERVICENAME>)));User Id=<USERNAME>;Password=<PASSWORD>;

Issue:
The below code during conn.open() throws error. It works sometimes & sometimes throws an error that 'Object reference not to set an instance of an object' in the same machine.
conn = New OracleConnection()
conn.ConnectionString = ConnectionString
MsgBox("isnothing? : " & (conn Is Nothing).ToString)   'it is always False. So , not null

conn.Open()  ' It throws an error that "Object reference not to set an instance of an object"

Dim cmd As OracleCommand = New OracleCommand(strQuery)
cmd.BindByName = True
cmd.Connection = conn
RowsAffected = cmd.ExecuteNonQuery()
cmd.Dispose()
conn.Dispose()

Note:
It is not a resource leak. I just make 1 connection and dispose. No one else is connecting to the DB.
Issue happens - When QTP has COM lib. When i use that to automate & make it invisible (QTP.Visible = FALSE). If I use QTP.Visible = TRUE - issue does not happen. What kind of issue is this!!!
 StackTrace :
Object reference not set to an instance of an object.
   at OracleInternal.I18N.Conv.GetMaxBytesPerChar(Int32 charsetId)
   at OracleInternal.ServiceObjects.OracleConnectionImpl.Connect(ConnectionString cs, Boolean bOpenEndUserSession)
   at OracleInternal.ConnectionPool.PoolManager`3.CreateNewPR(Int32 reqCount, Boolean bForPoolPopulation, ConnectionString csWithDiffOrNewPwd)
   at OracleInternal.ConnectionPool.PoolManager`3.Get(ConnectionString csWithDiffOrNewPwd)
   at OracleInternal.ConnectionPool.OraclePoolManager.Get(ConnectionString csWithNewPassword)
   at OracleInternal.ConnectionPool.OracleConnectionDispenser`3.Get(ConnectionString cs, PM conPM, ConnectionString pmCS, SecureString securedPassword, SecureString securedProxyPassword)
   at Oracle.ManagedDataAccess.Client.OracleConnection.Open()
   at myDBWrapper.Utility.DBUtil.OpenConnection()

Comment: Seems to me like a bug in OracleInternal.I18N... I don't know if there is anything you can do about it.
Comment: Possible workaround: start hidden, un-hide for just the connect, then re-unhide. Also, you can config qtp to be minimized, I think, and still have "visible" status.
Comment: Please show a complete stack trace.
Comment: @OldProgrammer, thanks for checking. added stacktrace.
Comment: @OldProgrammer,As an additional info, QTP is an automation tool. it can import .net dll and use its methods. In the GUI mode , it works awesome. In the non-GUI mode - it throws error. happens in both 64 and 32 bit machines. all other dlls are working in non gui mode. I would love to give any info you need to get this issue fixed.
Comment: @TheBlastOne, thanks for checking this. Yes, i also mentioned the same in my question - in the stacktrace.
Comment: @TheBlastOne, The problem is - I have a `driver.vbs` which uses QTP's AOM - it should hide QTP during the startup. Once QTP is invoked, it starts executing all the actions. There is a global object initialized using dotnetfactory with the dll by QTP once QTP is invoked. If i have to make it un-hide again, i need a separate function in QTP to do this as driver.vbs can not handle this as it is a separate process. For the time being i am not using hidden mode due to this issue. But I would like to use hidden mode to improve the overall performance. Thanks for checking.
Comment: Qtp can find its own instance of AOM (there is only one), and toggle "visible" from within the action script code, no?
Comment: @TheBlastOne, Yes, it is doable.
Comment: Sorry if I am missing something but UFT doesn't support VB.NET. It uses VBScript instead. And in my project i use Adodb object to connect to oracle DB from VBScript.
Answer: Because that looks like VB.NET Have you got that code in a form load? That event is unpredictable if you are not showing the form.
Answer: have u tried the oracle connection using the ADOB connection object ? you need to have the Oracle driver installed and it will help you to connect to the DB by creation the ADOB connection object
Comment: This should probably be a comment rather than an answer
Answer: Try this
conn = New Oracle.ManagedDataAccess.Client.OracleConnection(ConnectionString)

oracle connection open error


No Ajax response even though URL is correct?

Question: i get error in firebug when i try to get the data from the second url, but when i try the url in comments (the first one) everything is ok,
function build()
{
   $.ajax({
             type: "GET",
         contentType: "application/json",
         crossDomain: true,
         /// url: "http://localhost:9100/todo-0.1/data.json",
         url:'localhost:9000/rest/admin/component?componentUri=file:/home/workspace/app/5-Integration/',
              dataType: "json",
              success: function (data)
                {
                 var n=data.links.link[1]['@href'].indexOf("file");
                 var ContObject=new Object();
                     ContObject.data=new Object();
                     ContObject.data["title"]= decodeURI(data.links.link[1]          ['@href'].substring(n));
                     ContObject.state="open";

                     ContObject.metadata=new Object();
                     ContObject.metadata["id"]= decodeURI(data.links.link[1]['@href'].substring(n));
                 var jsonText = JSON.stringify(ContObject);
                 var output="
";
                     output+=  jsonText;
                     output+="
";
                     document.getElementById("placeholder").innerHTML=output;
                   alert("success");

                },
          error: function (data,status)
               {
                  console.log("ERROR");
                  console.log(status);
               }
         });

thanks for guidance
Comment: *i get error in firebug* - OK.  What is the error you get in firebug?
Comment: i get error in console, and Object { readyState=0, status=0, statusText="error"}
Comment: what do you get as output by `success: function (data) { console.log(data); }`
Comment: i get nothing, if i use this url, and i don't know why
Comment: i tried http:// localhost:9000/rest/admin/co... also but doesn't work
Comment: if you get nothing, then the error is inside `localhost:9000/rest/admin/component?componentUri=file:/home/workspace/app/5-Integration/`document. when you access this by browser, you get nothing too?
Does the server on port 9000 allow cross domain requests?
Comment: yes,when i access by the brower i get my data. Can you explain what do you mean by the server allows cross domain requests.thank you
Comment: i add a new parameter in error: function (data,status,errorThrown){  console.log(errorThrown);} and i get this error [Exception... "Failure" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: http://localhost:9100/todo-0.1/jquery-1.7.2.min.js ::  :: line 4" data: no] { name="NS_ERROR_FAILURE", message="Failure", result=2147500037, more...}
Comment: http://stackoverflow.com/questions/6871021/how-to-enable-cross-domain-request-on-the-server
Answer: url:'localhost:9000/rest/admin/co....
must be
url:'http://localhost:9000/rest/admin/co....
update:
enable cross domain requests: How to enable cross-domain request on the server?
debug:
success: function (data) { console.log(data); }

Comment: i have used two servers. i run my application using  port :9000 and  so i want to get data from  http://localhost:9100. so i can't .

finally, i solved the problem, by using just one server 9100.

thank you all for help


Need to extrapolate missing monthly data from annual data; the monthly/seasonal index is reasonably well-known

Question: I have a revenue dataset for various businesses. For about half of those businesses, monthly data is available. For the other half, only annual revenue data is present. I know the seasonality of the revenues fairly well from the half of the businesses who have reported their monthly revenue. In addition, the data goes back at least five years, so I know that seasonal effects are real. What is the best way to go about extrapolating monthly revenue for businesses with missing data given the information I have on hand? Even though it is not strictly true, I am assuming that the businesses with missing data and businesses with complete data are sufficiently similar that we need not worry about any underlying issues.
Comment: Whatever approaches are suggested, you should obviously hold out some of the monthly-revenue companies as test cases and see what happens when you impute monthly values from their annual totals.
Comment: This probably can be done with the proportional Denton method of interpolation of a low-frequency time series by use of an associated higher-frequency indicator series, imposing the constraints that the
interpolated series obeys the original low-frequency series totals. There's an IMF document that goes through the approach and various implementations in several languages.
Answer: One possibility is to calculate a seasonality curve from the monthly data - each month will get a seasonality index - and then use the trend in annual revenue and the seasonality curve to get monthly revenue predictions.
Rough steps:

Calculate a seasonality curve from the companies with monthly data. Each month receives a seasonality index.
For companies with annual revenue, predict the following year's revenue using whichever method you like best
Calculate the monthly revenue for those companies by multiplying the predicted annual revenue and the seasonality curve
Answer: Time series analysis incorporating Intervention Detection can estimate these missing values. Essentially the "0" value at a particular point in time is treated as an exception and the size of the exception is the estimated coefficient associated with that point in time. You can search for Intervention Detection OR AUTOMATIC Intervention Detection using a browser. If the number of missing values is "large" relative to normal data points then you might have to iteratively pursue this.


Como converter imagem de cinza para RGB?

Question: Para converter uma imagem em RGB para escala de cinza é relativamente fácil, basta fazer uma combinação linear( ou a média) dos 3 canais. Por exemplo :
Gray = 0.3*R +0.59*G +0.11*B

Pela expressão acima se obtém uma matriz em tons de cinza.
Minha dúvida é : como obter as matrizes R, G e B a partir da matriz Gray para se obter uma imagem colorida a partir de uma em tons de cinza ?
Comment: Para que fique mais facil entender o problema: 16 + 2 + 22 = 40, correto? Partindo do número 40, como é que você poderia saber quais foram os três números somados? Não tem como, pois tem infinitas combinações de três números que resultam em 40 quando somados. A conversão para cinza é quase a mesma coisa (muda um pouco a fórmula, tem um range numérico mais definido, mas que em nada ajuda sem uma análise de outros fatores)
Comment: Basicamente abrindo num programa de edição de imagens e colorindo "conforme o gosto"
Comment: Não obtém. A transformação é só de ida
Comment: Colorir de vez em quando faz bem pra mente. :)
Answer: Como dito nos comentários, não tem como recuperar os valores originais apenas a partir do valor cinza.
O que você pode fazer é armazenar tanto o valor em cinza quanto o RGB.
Por exemplo, você terá uma classe Pixel (pseudo codigo):
class Pixel {
  byte R
  byte G
  byte B
  byte Gray

  public Pixel(byte R, byte G, byte B) {
    this.R = R
    this.G = G
    this.B = B
    this.Gray = mean([R, G, B]) // Escala de cinza a partir da média dos valores RGB
  }
}

Com essa classe você tem todas as informações necessárias pra exibir a imagem colorida ou cinza. O programa vai usar mais memória, mas é o preço que se paga por manter a informação da cor original.
Answer: Se Gray = 0.3*R +0.59*G +0.11*B
é só fazer Gray=R=G=B que a imagem no ponto RGB(i,j,k) terá as 'mesmas cores' da imagem cinza.
No math/octave:
pkg load image;
imagemGray = imread('gray.png'); %ler arquivo gray

for i = 1 : 3
 imagemRGB(:,:,i) = imagemGray(:,:);
endfor


XSLT - Problems changing the node context in conjunction with the identity pattern

Question: I have a given source XML document with a structure like this:
<?xml version="1.0" encoding="UTF-8"?>
<sample>
  <definition>
    <variable>
      <name>object01_ID_138368350261919620</name>
      <value>NUL</value>
    </variable>
    <variable>
      <name>param01_ID_138368350261919621</name>
      <value>10</value>
    </variable>
    <variable>
      <name>param02_ID_138368350261919622</name>
      <value>100</value>
    </variable>
  </definition>
  <override>
    <assignment>
      <name>object01_ID_138368350261919620</name>
      <path>module01/object01</path>
    </assignment>
    <assignment>
      <name>param01_ID_138368350261919621</name>
      <path>module01/object01/param01</path>
    </assignment>
    <assignment>
      <name>param02_ID_138368350261919622</name>
      <path>module01/object01/param02</path>
    </assignment>
  </override>
</sample>

The characteristic of the source XML is:
Each <assignment> element within the <override> element corresponds to exactly one <variable> element within the <definition> element. This 1:1 relationship is established by the content of their <name> element.
The requirements of the transformation and the target XML are:
Depending on the pattern of the content of the <path> elements, within the <assignment> elements in an <override> element, I like to add a new <assignment> element. Important to note is, that an <assignment> element is the leading information. Therefore always at first, a new <assignment> element with its <path> and <name> content has to be created and in conjunction with that a corresponding new <variable> element with the same <name> content and a specific <value> content has to be created and inserted at last position in the <definition> element. For example, for adding param03, the right result should look like:
<?xml version="1.0" encoding="UTF-8"?>
<sample>
  <definition>
    <variable>
      <name>param00_ID_138368350261919620</name>
      <value>NUL</value>
    </variable>
    <variable>
      <name>param01_ID_138368350261919621</name>
      <value>10</value>
    </variable>
    <variable>
      <name>param02_ID_138368350261919622</name>
      <value>100</value>
    </variable>
    <variable>
      <name>Param03_ID_138368350261919623</name>
      <value>1000</value>
    </variable>
  </definition>
  <override>
    <assignment>
      <name>param00_ID_138368350261919620</name>
      <path>module01/object01</path>
    </assignment>
    <assignment>
      <name>param01_ID_138368350261919621</name>
      <path>module01/object01/param01</path>
    </assignment>
    <assignment>
      <name>param02_ID_138368350261919622</name>
      <path>module01/object01/param02</path>
    </assignment>
    <assignment>
      <name>Param03_ID_138368350261919623</name>
      <xpath>module01/object01/param03</xpath>
    </assignment>
  </override>
</sample>

My XSL 2.0 stylesheet for transformation:
For identity transformation, I have choosen to use the fine-grained control identity rule, recommended by [Dimitre Novatchev]. Applying the processing param03 template, I create a new <assignment> element with its specific <path> and <name> content. Within that template, I like to change the node context by using for-each, to the <definition> element and add at last position a new <variable> element with the corresponding <name> content and a specific <value> content. This stylesheet has been tested with Saxon HE 9.5.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:fo="http://www.w3.org/1999/XSL/Format"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:fn="http://www.w3.org/2005/xpath-functions"
  exclude-result-prefixes="fo xs fn">

  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:variable name="randomid" select="138368350261919623"/>

  <xsl:template match="node()|@*" name="identity">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()[1]"/>
    </xsl:copy>
    <xsl:apply-templates select="following-sibling::node()[1]"/>
  </xsl:template>

  <xsl:template name="variable_assignment">
    <xsl:param name="value_node_name"/>
    <xsl:param name="value_node_path"/>
    <xsl:message select="'processing: variable assignment'"/>
    <xsl:message select="concat('applying name: ', $value_node_name)"/>
    <xsl:message select="concat('applying path: ', $value_node_path)"/>
    <xsl:call-template name="identity"/>
    <assignment>
      <name>
        <xsl:value-of select="$value_node_name"/>
      </name>
      <xpath>
        <xsl:value-of select="$value_node_path"/>
      </xpath>
    </assignment>
  </xsl:template>

  <xsl:template match="/sample/override[not(assignment
              /path[matches(text(), '.*/object01/param03$')])]
              /assignment[path[matches(text(), '.*/object01$')]]">

    <xsl:param name="value_node_name_target">
      <xsl:value-of select="concat('Param03_ID', '_', $randomid)"/>
    </xsl:param>
    <xsl:param name="value_node_path_target">
      <xsl:value-of select="concat(./path, '/param03')"/>
    </xsl:param>
    <xsl:param name="value_node_value_target" select="'1000'"/>

    <xsl:call-template name="variable_assignment">
      <xsl:with-param name="value_node_name" select="$value_node_name_target"/>
      <xsl:with-param name="value_node_path" select="$value_node_path_target"/>
    </xsl:call-template>

    <xsl:for-each select="/sample/definition/*[position()=last()]">
        <xsl:message select="'processing: variable definition'"/>
      <xsl:message select="concat('Here we are: ', .)"/>
      <xsl:message select="concat('applying name: ', $value_node_name_target)"/>
      <xsl:message select="concat('applying value: ', $value_node_value_target)"/>
      <xsl:call-template name="identity"/>
      <variable>
        <name>
          <xsl:value-of select="$value_node_name_target"/>
        </name>
        <value>
          <xsl:value-of select="$value_node_value_target"/>
        </value>
      </variable>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

The resulting wrong XML is:
<?xml version="1.0" encoding="UTF-8"?>
<sample>
  <definition>
    <variable>
      <name>object01_ID_138368350261919620</name>
      <value>NUL</value>
    </variable>
    <variable>
      <name>param01_ID_138368350261919621</name>
      <value>10</value>
    </variable>
    <variable>
      <name>param02_ID_138368350261919622</name>
      <value>100</value>
    </variable>
  </definition>
  <override>
    <assignment>
      <name>object01_ID_138368350261919620</name>
      <path>module01/object01</path>
    </assignment>
    <assignment>
      <name>param01_ID_138368350261919621</name>
      <path>module01/object01/param01</path>
    </assignment>
    <assignment>
      <name>param02_ID_138368350261919622</name>
      <path>module01/object01/param02</path>
    </assignment>
    <assignment>
      <name>Param03_ID_138368350261919623</name>
      <xpath>module01/object01/param03</xpath>
    </assignment>
    <variable>
      <name>param02_ID_138368350261919622</name>
      <value>100</value>
    </variable>
    <variable>
      <name>Param03_ID_138368350261919623</name>
      <value>1000</value>
    </variable>
  </override>
</sample>

The problems I got are:

The node context becomes not changed. The new <variable> element becomes added at last position into the <override> element, instead into the <definition> element, as wanted.
Additionally the last <variable> element from <definition> element becomes copied into the <override> element. That is not what I want.

Help needed!
I really would appreciate if somebody could advice me, in which way I would have to adapt my XSLT in order to get rid of the problems and the right behavior as delineated above.
Many thanks.
The XSLT 2.0 proposed by you, adapted by me:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions" exclude-result-prefixes="fo xs fn">

  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:param name="baserandom" select="138368350261919623"/>

  <xsl:template match="node()|@*" name="identity">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()[1]"/>
    </xsl:copy>
    <xsl:apply-templates select="following-sibling::node()[1]"/>
  </xsl:template>

  <xsl:template match="definition/*[last()]">
    <xsl:param name="value_node_name"/>
    <xsl:param name="value_node_value"/>
    <xsl:call-template name="identity"/>
    <xsl:if test="$value_node_name">
      <xsl:message select="'processing: variable definition'"/>
      <xsl:message select="concat('Here we are: ', .)"/>
      <xsl:message select="concat('applying name: ', $value_node_name)"/>
      <xsl:message select="concat('applying value: ', $value_node_value)"/>
      <variable>
        <name>
          <xsl:value-of select="$value_node_name"/>
        </name>
        <value>
          <xsl:value-of select="$value_node_value"/>
        </value>
      </variable>
    </xsl:if>
  </xsl:template>

  <xsl:template match="/sample/override[not(assignment/path[matches(text(), '.*/object01/param03$')])]
        /assignment[path[matches(text(), '.*/object01$')]]">

    <xsl:param name="value_node_name">
      <xsl:value-of select="concat('param03_ID', '_', $baserandom)"/>
    </xsl:param>

    <xsl:param name="value_node_path">
      <xsl:value-of select="concat(./path, '/param03')"/>
    </xsl:param>

    <xsl:param name="value_node_value" select="'1000'"/>

    <xsl:apply-templates select="/sample/definition/*[last()]">
      <xsl:with-param name="value_node_name" select="$value_node_name"/>
      <xsl:with-param name="value_node_value" select="$value_node_value"/>
    </xsl:apply-templates>

    <xsl:message select="'processing: variable assignment'"/>
    <xsl:message select="concat('applying name: ', $value_node_name)"/>
    <xsl:message select="concat('applying path: ', $value_node_path)"/>
    <xsl:call-template name="identity"/>
    <assignment>
      <name>
        <xsl:value-of select="$value_node_name"/>
      </name>
      <path>
        <xsl:value-of select="$value_node_path"/>
      </path>
    </assignment>
  </xsl:template>
</xsl:stylesheet>

The resulting XML (still wrong):
<?xml version="1.0" encoding="UTF-8"?>
<sample>
  <definition>
    <variable>
      <name>object01_ID_138368350261919620</name>
      <value>NUL</value>
    </variable>
    <variable>
      <name>param01_ID_138368350261919621</name>
      <value>10</value>
    </variable>
    <variable>
      <name>param02_ID_138368350261919622</name>
      <value>100</value>
    </variable>
  </definition>
  <override>
    <variable>
      <name>param02_ID_138368350261919622</name>
      <value>100</value>
    </variable>
    <variable>
      <name>param03_ID_138368350261919623</name>
      <value>1000</value>
    </variable>
    <assignment>
      <name>object01_ID_138368350261919620</name>
      <path>module01/object01</path>
    </assignment>
    <assignment>
      <name>param01_ID_138368350261919621</name>
      <path>module01/object01/param01</path>
    </assignment>
    <assignment>
      <name>param02_ID_138368350261919622</name>
      <path>module01/object01/param02</path>
    </assignment>
    <assignment>
      <name>param03_ID_138368350261919623</name>
      <path>module01/object01/param03</path>
    </assignment>
  </override>
</sample>

Comment: When you say *"For example of adding param03..."* -- how is `param03` *added*? It's not clear to me how the source XML you mention at the very top should be translated into the result XML you post.
Comment: With the example of _param03_ I like to show that both XSLTs are working very well regarding adding the `` element within the `` element (see code after comment _"processing variable assignment"_). Just try it. The problems described by me came up within the transformation needed for adding the corresponding `` element into the `` element (see code after comment _"processing variable definition"_. For this part of the transformation I tried the two approaches (_for-each_ and _apply-templates_) and unfortunately failed.
Comment: I guess that users are reluctant to answer this question because it is overly long and verbose. Please state in very few sentences the way you want your input XML to change. (However, it _is_ clear that you made an effort to solve this yourself).
Comment: Thank you very much for your hint. Herewith I have shorten it. Now I hope it is much easier to read. I'm still looking for a solution. Any help is appreciated.
Answer: The issue you are having is that xsl:for-each isn't changing the output context. It's only changing the iteration context.
You are still outputting in the context of assignment (template match) when you're iterating over xsl:for-each select="/sample/definition/*[position()=last()].
You'll need to output the new variable from the context of definition.
I've modified your XSLT to produce what you want. It might not be the final solution, but should get you closer. I added comments (all uppercase) to try to explain what I changed. Please let me know if there are questions.
Modified XSLT 2.0
<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:fo="http://www.w3.org/1999/XSL/Format"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:fn="http://www.w3.org/2005/xpath-functions"
    exclude-result-prefixes="fo xs fn">

    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:param name="randomid" select="138368350261919623"/>

    <xsl:param name="value_node_name_target">
        <xsl:value-of select="concat('Param03_ID', '_', $randomid)"/>
    </xsl:param>
    <xsl:param name="value_node_path_target">

        <xsl:value-of select="concat(/sample/override[not(assignment/path[matches(text(), '.*/object01/param03$')])]
            /assignment[1]/path, '/param03')"/>
    </xsl:param>
    <xsl:param name="value_node_value_target" select="'1000'"/>

    <xsl:template match="node()|@*" name="identity">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()[1]"/>
        </xsl:copy>
        <xsl:apply-templates select="following-sibling::node()[1]"/>
    </xsl:template>

    <xsl:template match="definition[../override[not(assignment/path[matches(text(), '.*/object01/param03$')])]
        /assignment[path[matches(text(), '.*/object01$')]]]/*[last()]">
        <xsl:message select="'processing: variable definition'"/>
        <xsl:message select="concat('Here we are: ', .)"/>
        <xsl:message select="concat('applying name: ', $value_node_name_target)"/>
        <xsl:message select="concat('applying value: ', $value_node_value_target)"/>
        <xsl:call-template name="identity"/>
        <variable>
            <name>
                <xsl:value-of select="$value_node_name_target"/>
            </name>
            <value>
                <xsl:value-of select="$value_node_value_target"/>
            </value>
        </variable>
    </xsl:template>

    <xsl:template match="/sample/override[not(assignment/path[matches(text(), '.*/object01/param03$')])]
        /assignment[path[matches(text(), '.*/object01$')]]">

        <xsl:message select="'processing: variable assignment'"/>
        <xsl:message select="concat('applying name: ', $value_node_name_target)"/>
        <xsl:message select="concat('applying path: ', $value_node_path_target)"/>
        <xsl:call-template name="identity"/>
        <assignment>
            <name>
                <xsl:value-of select="$value_node_name_target"/>
            </name>

            <path>
                <xsl:value-of select="$value_node_path_target"/>
            </path>
        </assignment>

    </xsl:template>
</xsl:stylesheet>

Output
<sample>
   <definition>
      <variable>
         <name>object01_ID_138368350261919620</name>
         <value>NUL</value>
      </variable>
      <variable>
         <name>param01_ID_138368350261919621</name>
         <value>10</value>
      </variable>
      <variable>
         <name>param02_ID_138368350261919622</name>
         <value>100</value>
      </variable>
      <variable>
         <name>Param03_ID_138368350261919623</name>
         <value>1000</value>
      </variable>
   </definition>
   <override>
      <assignment>
         <name>object01_ID_138368350261919620</name>
         <path>module01/object01</path>
      </assignment>
      <assignment>
         <name>param01_ID_138368350261919621</name>
         <path>module01/object01/param01</path>
      </assignment>
      <assignment>
         <name>param02_ID_138368350261919622</name>
         <path>module01/object01/param02</path>
      </assignment>
      <assignment>
         <name>Param03_ID_138368350261919623</name>
         <path>module01/object01/param03</path>
      </assignment>
   </override>
</sample>

Comment: Thank you very much for your quick answer. Your solution works, but it doesn't solve my problem yet. The challenge is, that the assignment must always be the leading task. That means, if the matching rule for assignment of the sample param03 evaluates to true (could be false too), then based on an individual ID (incrementing baserandom) processing has to be done as delineated with *"The requirements of the transformation and the target XML"*. Therefore in my opinion, creating the definition has to be initiated parametrized by creating the assignment (e.g. param03). But then my problem is back.
Comment: Any testing that needs to be done for `assignment` can be done for the `definition` too. I've added a predicate to the `definition` template. I only modified your version of the XSLT, so I didn't try to add any incrementing of IDs. If that's need, I can try to take a look later when I have more time.
Comment: Thank your very much for your proposal. I mentioned the fact with the ID only to emphasize that there is a strong dependency between assignment and definition. The added predicate to the definition template, proposed by you, may be a way to go. But for me it's not clear how to provide both with the same ID at runtime. See also above (*The XSLT 2.0 proposed by you, adapted by me*) how I adapted the XSLT proposed by you. Unfortunately it produces the same wrong XML.


Why is postgresql 8.4 randomly shutting down on the weekend?

Question: I have a production 8.4 service and a dev 8.4 service.  They have been running solidly, but the past two weekends, the production service has randomly stopped running, this week on Sunday, last week on Saturday, not during any particular event or scheduled job.  The dev service, however, was fine.
This seems out of order, but according to the event logs, first pgAgent shuts down ("Failed to query jobs table!"), and then 8 seconds later postgres shuts down.  Both weekends it happened in that order.  I would expect, if anything, that postgres shutting down would cause pgAgent to then shut down.  I guess, if it got stuck on something that took >8 seconds to kill it, maybe at some point it would cause pgAgent to no longer work, before postgres fully died.
In the postgres logs themselves, there's this error:
<code>FATAL: pre-existing shared memory block is still in use
</code>
...which according to this post could be related to antivirus software.  We run Symantec, and resource hog it may be, I certainly am not going to leave the system unprotected as the post suggests.  Any other suggestions?
Answer: I'm not sure what's up with postgre itself, but you could always use something like Service Hawk to monitor the service to keep it running.


bigcommerce rest api v3 php

Question: I have to implement bigcommerce API integration with PHP
and I am trying to use the official library from https://github.com/bigcommerce/bigcommerce-api-php
and I am not even able to start step 1 here.
Issues:

Basic Auth method

Bigcommerce::configure(array(
    'store_url' => 'https://store.mybigcommerce.com',
    'username'  => 'admin',
    'api_key'   => 'd81aada4xc34xx3e18f0xxxx7f36ca'
));

So the question here is how to get a username? bigcommerece user only created using email address so how to get username here?

OAuth method

In order to obtain the auth_token you would consume Bigcommerce::getAuthToken method
$object = new \stdClass();
$object->client_id = 'xxxxxx';
$object->client_secret = 'xxxxx;
$object->redirect_uri = 'https://app.com/redirect';
$object->code = $request->get('code');
$object->context = $request->get('context');
$object->scope = $request->get('scope');

$authTokenResponse = Bigcommerce::getAuthToken($object);

Bigcommerce::configure(array(
    'client_id' => 'xxxxxxxx',
    'auth_token' => $authTokenResponse->access_token,
    'store_hash' => 'xxxxxxx'
));

here the question is what is the $request variable? also, redirect_uri is the bigcommerce store URL or my site URL?
Please can anyone help to get started with this?
Answer: It's because that library is a bit out of date with how api accounts are managed. For the basic auth you would use "legacy accounts". You can just use the OAuth method without the oAuth flow (assuming you're trying to connect to your own store, not create an app).
Just the following will work:
Bigcommerce::configure(array(
    'client_id' => 'client-id',
    'auth_token' => 'access-token',
    'store_hash' => 'store-hash'
));

You should get these after creating a user in the dashboard (you can ignore the secret for this use case)

bigcommerce rest api v3 php


Calculating number of standard deviations that contain $x$ percent of data

Question: I would like to calculate how many standard deviations contain $x\%$ of data in a normal distribution. For example, if I wanted to split my data/normal distribution into thirds, I would need to know how many standard deviations contain $33.3\%$ of my data.
Comment: It's time to do some integrals!
Comment: is [this](http://en.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7_rule) helpful?
Answer: The calculation for this is troublesome, but it is always the same, so usually people consult a table on which it has been precalculated. You should try Google search for "z-score table" or just "standard normal distribution table" and numerous examples will appear.  Or you could use this one, which is the first one I found:

The entry in the row x.y and column 0.0z tells you the probability that a sample element will be no more than x.yz standard deviations above the mean.
Looking for $\frac23$ in the table, we find that the entry at row $0.4,$ column $0.03$ is $0.6664$, which is close enough for government work.  This tells us that $\frac23$ of the sample will be less than $0.43$ standard deviations above the mean; therefore $\frac13$ of the sample will be more than $0.43$ standard deviations above the mean, and therefore by symmetry $\frac13$ of the sample will be more than $0.43$ standard deviations below the mean.
So if you want to divide the sample into thirds, the lower third is the part that is up to  $0.43$ standard deviations below the mean; the middle third is the part between $0.43$ standard deviations below and $0.43$ standard deviations above the mean, and the upper third is the part more than  $0.43$ standard deviations above the mean.
Similarly, looking for $\frac34$ in the table we find that it is at about $0.675$ standard deviations, so the quartile cuts are at $-0.675, 0, $ and $+0.675$ standard deviations, respectively.


How to set border color of input field for only numeric values?

Question: I need to set border color of input field to green but only in case when the value in this field is a number. How can I do this?  Here is my html:

            <input type="text" class="field" value="1245"/>

            <input type="text" class="field" value="efg#21"/>

            <input type="text" class="field" value="34536"/>

            <input type="text" class="field" value="abcd"/>

            <input type="text" class="field" value="12asd"/>

Could you suggest a valid js/jquery code for this?
Comment: Please show us what you have tried so far
Answer: I'd combine regex with jQuery.  This also responds to input from the user.

function validate() {
  $("input").each(function () {
    if ($(this).val().match("^[0-9]+$")) {
      $(this).css("border-color","green")
    } else {
      $(this).css("border-color","red")
    }
  });
}

$("input").on("keyup", validate);
validate()
input {
  border-width:1px;
  border-style:solid;
}

    <input type="text" class="field" value="1245"/>

    <input type="text" class="field" value="efg#21"/>

    <input type="text" class="field" value="34536"/>

    <input type="text" class="field" value="abcd"/>

    <input type="text" class="field" value="12asd"/>

Answer: You can use the callback of the .css()-function to check the value and set the border accordingly:

$("input").css("border", function() {
  return (!isNaN($(this).val())) ? '1px solid green' : '';
});

  <input type="text" class="field" value="1245" />
  <input type="text" class="field" value="efg#21" />
  <input type="text" class="field" value="34536" />
  <input type="text" class="field" value="abcd" />
  <input type="text" class="field" value="12asd" />

Reference
isNaN
ternary operator


Given a bivector, determine the decomposition of $\mathbb{R}^3$ into symplectic leaves

Question: Say I have a bivector, given by $f(z) \partial_x \wedge \partial_y$, where $f(z)$ is a smooth function of $z$. How do I determine the decomposition of $\mathbb{R}^3$ into symplectic leaves from this?
Answer: Let us denote the bivector field by $$\Pi=f(z)\partial_{x}\wedge\partial_{y}.$$
There is an associated vector bundle map $$\Pi^{\sharp}:T^{*}\mathbb{R}^{3}\rightarrow T\mathbb{R}^{3}:\alpha\mapsto\iota_{\alpha}\Pi,$$
which takes a one-form $\alpha$ and contracts $\Pi$ with it. The symplectic foliation integrates the (singular) distribution $\text{Im}(\Pi^{\sharp})$. In this case, we have
\begin{align}
\text{Im}(\Pi^{\sharp})&=\text{Span}\{\Pi^{\sharp}(dx),\Pi^{\sharp}(dy),\Pi^{\sharp}(dz)\}\\
&=\text{Span}\{f(z)\partial_{y},f(z)\partial_{x}\}.
\end{align}
Note that this gives at each point $(x,y,z)$ either a zero-dimensional or a two-dimensional subspace, depending on whether or not $z$ is a zero of $f$.
It follows that the symplectic leaves are the  following:
1) Each horizontal plane $z=c$ is a leaf whenever $f(c)\neq 0$.
2) If $f(c)=0$, then all points $(x,y,c)$ are symplectic leaves.
Comment: Thanks for the answer. What happens if instead I have a bivector field like $(x \partial_x + y\partial_y)\wedge \partial_z$? I see that this is similar to what you have above, but it is more like an addition of two bivector fields of the form above. How does this differ?
Comment: @Sorey As above, we now have \begin{align}\text{Im}(\Pi^{\sharp})&=\text{Span}\{\Pi^{\sharp}(dx),\Pi^{\sharp}(dy),\Pi^{\sharp}(dz)\}\\&=\text{Span}\{x\partial_{z},y\partial_{z},-x\partial_{x}-y\partial_{y}\}.\end{align} Every point $(0,0,z)$ is a leaf, because the distribution is zero at those points. In other points, the distribution is spanned by the vertical vector field $\partial_{z}$ and the vector field $-x\partial_{x}-y\partial_{y}$, which points to the $z$-axis in radial direction. So the other leaves are half-planes going outwards from the $z$-axis.
Comment: Ok, great. One last thing - I did one on my own, with the bi-vector field $(x\partial_y + y\partial_x)\wedge \partial_z$. We get that

$$\text{Im}(\Pi^{\#}) = \text{Span}\{y\partial_z,x\partial_z,-y\partial_x-x\partial_y\}$$

 So, again all points $(0,0,z)$ are leaves, and the distribution is spanned by $\partial_z$ and $-x\partial_y - y\partial_x$. This still points to the $z$-axis in the radial direction, correct? So would the leaves be half-planes still?
Comment: @Sorey The vector field $x\partial_{y}+y\partial_{x}$ does not always point in the radial direction. If you draw it carefully, you will see that its integral curves are branches of hyperbolas. So the leaves in this case are the points on the $z$-axis, and sheets of hyperbolic cylinders.


Connect phpmyadmin to existing db server

Question: I would like to access and modify records in an existing database server using phpmyadmin.
I am currently using the XAMPP testing server and can access the default localhost/phpmyadmin.
I tried to see if there is some config file I can point to the db server using the hostname, username, and password, i.e. C:\xampp\apache\conf\extra\httpd-xampp.conf however, I have not succeeded with that.
I was wondering if someone ever accomplished this task with phpmyadmin?
I appreciate any suggestions.
Many thanks in advance!
Comment: You want to use your existing phpMyAdmin installation to connect to a different MySQL server?
Comment: Yes, exactly. I want to use my existing phpMyAdmin on my 'testing' xampp server to connect to a 'production' db mySQL server by changing the credentials (host, username, password, etc).
Answer: In this case you can add another server to config.inc.php, as long as the other MySQL server allows remote connections. The phpMyAdmin wiki has an example. Also, the included documentation has more in-depth information.
Basically you'll edit config.inc.php and add (or edit) the host value (and, if your auth_type is config, also the user and password values).
Here's a short example of how to do the multiserver, see the links I referenced for more details.
<?php
$cfg['blowfish_secret'] = 'setthistosomethingelse';
$i = 0;

$i++; // server 1
$cfg['Servers'][$i]['verbose']   = 'Development server';
$cfg['Servers'][$i]['host']      = 'localhost';

$i++; // server 2
$cfg['Servers'][$i]['verbose']   = 'Production server';
$cfg['Servers'][$i]['host']      = 'production.example.com';

?>


How to send data by Intent from BroadcastReceiver to Fragment in Kotlin

Question: I will send step count:
Foreground Service -> Broadcast Receiver -> Fragment
Since I need to keep tracking step count on background and when app is off, I've created two Broadcast Receiver, one for notification to keep showing step count on background and one for fragment UI which will be unregistered on Destroy.
So this process is for the latter.

Foreground Service

: I send "stepCount" value to broadcast.
   Intent().also { intent ->
        intent.setAction(ACTION_STEP_COUNTER_NOTIFICATION)
        intent.putExtra("stepCount", "$todayTotalStepCount")
        sendBroadcast(intent)
    }

BroadcastReceiver
open class StepCountBroadcastReceiver : BroadcastReceiver() {
 override fun onReceive(context: Context?, intent: Intent?) {
     super.onReceive(context, intent)

     if(intent!!.action == ACTION_STEP_COUNTER_NOTIFICATION) {
         var intent = Intent()
         var stepCount = intent.getStringExtra("stepCount")

         var sendMyDiary = Intent(context!!, MyDiaryFragment::class.java)
         sendMyDiary.putExtra("stepCount", stepCount)
         context.startActivity(sendMyDiary)
     }
 }

}

when custom Action is triggered, this will get 'stepCount' from Service and here I will send it to Fragment named MyDiaryFragment.
So I send it by using Intent().putExtra.

Fragment

    private val stepCountBroadcastReceiver: BroadcastReceiver = StepCountBroadcastReceiver()

        val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION).apply {
            addAction(ACTION_STEP_COUNTER_NOTIFICATION)
        }
        LocalBroadcastManager.getInstance(requireActivity()).registerReceiver(stepCountBroadcastReceiver, filter)

Here is my question.
I register this StepCountBroadcastReceiver in onCreate.
But I don't know how to get stepCount coming from broadcast in Fragment whenever Broadcastreceiver is called.
It that same process like just adding this below line at the bottom?

var stepCount = requireActivity().intent.getStringExtra("stepCount")

    val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION).apply {
        addAction(ACTION_STEP_COUNTER_NOTIFICATION)
    }
    LocalBroadcastManager.getInstance(requireActivity()).registerReceiver(stepCountBroadcastReceiver, filter)
    var stepCount = requireActivity().intent.getStringExtra("stepCount")

Comment: You cann't startActivity with Fragment. Do you want try with RxJava?
Answer: In your broadcast receiver, add this.To Send a LocalBroadCast
override fun onReceive(context: Context?, intent: Intent?) {
     super.onReceive(context, intent)

     if(intent?.action == ACTION_STEP_COUNTER_NOTIFICATION) {
         var stepCount = intent.getStringExtra("stepCount")
         var localBroadCastIntent = Intent(LOCAL_BROADCAST_KEY)
         localBroadCastIntent.putExtra("stepCount",stepCount?:"")
         Handler(Looper.getMainLooper()).post {
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
        }
     }
 }

const val LOCAL_BROADCAST_KEY = "step_counter_local_broadcast"

In your Fragment Call this register function.And in onCreateView and make sure to call unregisterReceiver in ondestroyview of Fragment.
    private fun registerBroadCastReceiver() {
LocalBroadcastManager.getInstance(applicationContext).registerReceiver(
                receiver,
                IntentFilter(LOCAL_BROADCAST_KEY)
            )
        }
    }

Add this BroadCast Receiver,in Fragment Class globally.
 private var receiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            intent?.let {
                val stepCount = it.getStringExtra("stepCount")
            }
        }
    }

Note:
Here Flow will be like this.

Service -> BroadCast Receiver -> LocalBroadCastReceiver ->
UpdateFragment UI.

You can also directly call this localbroadcast from service based on your usecase. So it will be like below.

Service->  LocalBroadCastReceiver -> UpdateFragment UI.

So only when fragment is alive, the local broadcast receiver will receive messages and update ui.


Adding HTML element in Kendo UI Grid row?

Question: I have some grid that is going from JSON here is example of my code:
JAVASCRIPT
var orders = [{
  OrderID : 10248,
  CustomerID : "",
  EmployeeID : 5,
  OrderDate : new Date(1996, 6, 4, 0, 0, 0, 0),
  RequiredDate : new Date(1996, 7, 1, 0, 0, 0, 0),
  ShippedDate : new Date(1996, 6, 16, 0, 0, 0, 0),
  ShipVia : 3,
  Freight : 32.3800,
  ShipName : "Vins et alcools Chevalier",
  ShipAddress : "59 rue de l'Abbaye",
  ShipCity : "Reims",
  ShipRegion : "",
  ShipPostalCode : "51100",
  ShipCountry : ""
}, {
  OrderID : 10249,
  CustomerID : "TOMSP",
  EmployeeID : 6,
  OrderDate : new Date(1996, 6, 5, 0, 0, 0, 0),
  RequiredDate : new Date(1996, 7, 16, 0, 0, 0, 0),
  ShippedDate : new Date(1996, 6, 10, 0, 0, 0, 0),
  ShipVia : 1,
  Freight : 11.6100,
  ShipName : "Toms Spezialitäten",
  ShipAddress : "Luisenstr. 48",
  ShipCity : "MГјnster",
  ShipRegion : "",
  ShipPostalCode : "44087",
  ShipCountry : "Germany"
},  {
  OrderID : 11077,
  CustomerID : "RATTC",
  EmployeeID : 1,
  OrderDate : new Date(1998, 4, 6, 0, 0, 0, 0),
  RequiredDate : new Date(1998, 5, 3, 0, 0, 0, 0),
  ShippedDate : null,
  ShipVia : 2,
  Freight : 8.5300,
  ShipName : "Rattlesnake Canyon Grocery",
  ShipAddress : "2817 Milton Dr.",
  ShipCity : "Albuquerque",
  ShipRegion : "NM",
  ShipPostalCode : "87110",
  ShipCountry : "USA"
}];

$(document).ready(function () {
  $("#rowSelection").kendoGrid({
    dataSource: {
      data: orders,
      pageSize: 7,
      resizable: true,
    },
    sortable: {
      mode: "single",
      allowUnsort: false
    },
    selectable: "multiple",
    pageable: {
      buttonCount: 5
    },
    scrollable: true,
    navigatable: true,
    columns: [
      {
        field: "ShipCountry",
        title: "Ship Country" ,
        width: 200
      },
      {
        field: "Freight",
        width: 200
      },
      {
        field: "OrderDate",
        title: "Order Date",
        format: "{0:dd/MM/yyyy}"
      }
    ]
  });
});

I got something like this

That is ok, but what I need I have to add an image in the cell and change color, here is a picture of what I need?
This is just an example, I need to add some mine HTML tag in that cell?

I know I can do it just bind table, but that way I don't get pagination on table?
Here is what I have used to bind
http://demos.telerik.com/kendo-ui/web/grid/index.html
only how to add custom HTML in table, with pagination?
Answer: If you want HTML to be rendered in a column, you have to turn off encoding.

If set to true the column value will be HTML-encoded before it is displayed. If set to false the column value will be displayed as-is. By default the column value is HTML-encoded.

From the Kendo Documentation
$(document).ready(function(){
  $("#rowSelection").kendoGrid({
    //...
    columns: [
      {
        field: "ShipCountry",
        encoded: false
      }
    ]
  });
});


How to theme multiple entities on the same page?

Question: I am trying to write a module that displays several entities in one page, but I don't see how I should theme them.
I've found (an mostly followed) this: https://drupal.org/node/1238606.
But the point where I get stuck is the return value of the page callback. The link above suggests:
function my_entity_page_view($entity, $view_mode='full') {
  $entity_type = $entity->entityType();
  $entity_id = entity_id($entity_type, $entity);

  $entity->content = array();
  $entity->title = filter_xss($entity->title);

  field_attach_prepare_view($entity_type, array($entity_id => $entity), $view_mode);
  entity_prepare_view($entity_type, array($entity_id => $entity));
  $entity->content += field_attach_view($entity_type, $entity, $view_mode);

  $entity->content += array(
    '#theme'     => $entity_type,
    '#element'   => $entity,
    '#view_mode' => $view_mode,
    '#language'  => LANGUAGE_NONE,
  );
  return $entity->content;
}

I however try to load several entities at once and have no fields, so I tried this:
$entities = // Array of entities keyed by id;

entity_prepare_view('entity_type', $entities);

$return = array(
  '#theme'     => 'entity_type',
  '#element'   => $entities,
  '#view_mode' => 'full',
  '#language'  => LANGUAGE_NONE,
);

return $return;

Since entity_prepare_view() accepts an array of entities, I'd suppose there should be a way to theme several entities at once as well. Or am I wrong?
Answer: After a bit more fiddling, this worked for me. I've tried a similar approach earlier, but I guess there was something wrong. I've commented out the field functions, but these are the places in case you need them.
$entities = // Array of entities keyed by id;

// Prepare all entities at once. Attach fields if desired.
//field_attach_prepare_view('entity_type', $entities, 'full');
entity_prepare_view('entity_type', $entities);

// Expose all entities individual to hook_theme.
foreach($entities as $key => $entity) {
  $entity->content = array();
  //$entity->content += field_attach_view('entity_type', $entity, 'full');
  $entity->content += array(
    '#theme'     => 'entity_type',
    '#element'   => $entity,
    '#view_mode' => 'full',
    '#language'  => LANGUAGE_NONE,
  );
  $entities[$key] = $entity->content;
}

return $entities;


Code::Blocks output "error: ld returned 1 exit status" without else

Question: My Code::Blocks IDE is calling just "error: ld returned 1 exit status" when I build my code. I frequently saw this error with "collect2:" as "collect2: ld returned 1 exit status". I just know this is linker error. So I need to include another linraries.
But I'm  inexperienced to use this IDE even if C++.
So I don't get it how I get rid of this error.
I would like to ask below things.
1)How to get rid of this error. What issues are considered.
2)How to set up Build options to suit my code in below.
Note(Build opetions):
Link libraries in Linker setting is added
<code>../../opencv-2.4.13/build/lib/libopencv_highgui.so

../../opencv-2.4.13/build/lib/libopencv_core.so

../../opencv-2.4.13/build/lib/libopencv_imgproc.so

pthread

boost_system
</code>
and, Compiler in Search directories is
<code>../../opencv-2.4.13/include/opencv

../../../../usr/include/boost
</code>

<code>#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/managed_mapped_file.hpp>
#include <boost/interprocess/containers/vector.hpp>   // boost/containers/vector.hpp
#include <boost/interprocess/containers/string.hpp>   // boost/containers/string.hpp
#include <iostream>
#include <sys/time.h>
#include <stdio.h>

 //                                                                    void_allocator;
namespace bip = boost::interprocess;

typedef unsigned char uchar;
//Typedefs of allocators and containers
typedef bip::managed_shared_memory::segment_manager                       segment_manager_t;
typedef bip::allocator<void, segment_manager_t>  void_allocator;

typedef void_allocator::rebind<uchar>::other                           uchar_allocator;
typedef bip::vector<uchar, uchar_allocator>                                   uchar_vector;

template <typename Alloc = std::allocator<uchar> >
struct BasicInData {

    public:
        BasicInData(Alloc alloc = {}) : image(alloc)
        { }

        template <typename T>
        BasicInData(double x, int sizeImg, uchar_vector& image, Alloc alloc = {}) :
            x(x), sizeImg(sizeImg), image(alloc)
        { }

        double x = 0;
        int sizeImg = 0;
        uchar_vector image;
};

using InData = BasicInData<>; // just heap allocated

namespace Shared {
    using segment                      = bip::managed_shared_memory;
    using segment_manager              = segment::segment_manager;

    template <typename T> using alloc  = bip::allocator<T, segment_manager>;
    template <typename T> using vector = bip::vector<T, alloc<T> >;

    using InData = BasicInData<alloc<uchar> >; // shared memory version

    vector<InData>& locate(segment& smt) {
        auto* v = smt.find_or_construct<vector<InData> >("InDataVector")(smt.get_segment_manager());
        assert(v);
        return *v;
    }
}

int main(int argc, char* argv[]) {
    if(argc == 1){ //Parent process
        // Remove shared memory on construction and destruction

        // Create a new segment with given name and size
        struct timeval tv;
        gettimeofday(&tv, NULL);
        struct shm_remove
        {
            shm_remove(){bip::shared_memory_object::remove("MySharedMemory");}
            ~shm_remove(){bip::shared_memory_object::remove("MySharedMemory");}
        }remover;
        Shared::segment smt(bip::create_only,"MySharedMemory", 65536); // 10 Kb for coliru
        auto &data = Shared::locate(smt);
        //Shared::alloc bip::alloc_inst (data);

        cv::Mat_<cv::Vec3b> mat;
        cv::VideoCapture vcap(0);

        Shared::InData id(smt.get_segment_manager());

        if (!vcap.isOpened())
            return -1;

        while (1) {
            vcap >> mat;
            int image_size = mat.total() * mat.elemSize();
            id.sizeImg = image_size;
            id.image.resize(image_size * sizeof(uchar));
            memcpy(&id.image[0], mat.data, image_size * sizeof(uchar));
            //Launch child process
            gettimeofday(&tv, NULL);
            double time = ((double)tv.tv_usec/1000000);
            id.x = time;
            data.push_back(id);
            if(cv::waitKey(30) >= 0) break;
        }

        std::string s(argv[0]); s += " child";
        if(0 != std::system(s.c_str()))
            return 1;

        // check child has destroyed the vector
        if(smt.find<Shared::vector<InData>>("InDataVector").first)
            return 1;

    } else{
        // Open the managed segment
        bip::managed_shared_memory segment(bip::open_only, "MySharedMemory");

        // Find the vector using c-string name
        bip::vector<InData> *myvector = segment.find<bip::vector<InData>>("InDataVector").first;
        // Use vector in reverse order

        bip::vector<InData>::iterator it;

        cv::Mat_<cv::Vec3b> im;
        for(it = myvector->begin(); it !=myvector->end(); ++it){
            im.resize(it->sizeImg);
            memcpy(im.data, &it->image[0], it->sizeImg);
            cv::imshow("window1", im);
        }

        segment.destroy<bip::vector<InData>>("InDataVector");

        return 0;
    }
}
</code>
Comment: What does the "Build Log" tab show?
Comment: You can add it under project->build options->linker settings tab.
Comment: I would try `rt` first, codeblocks should know how to pass the flag correctly
Comment: @greatwolf , I totally forgot it. I'm going to check up.
Comment: `undefined reference to symbol 'shm_unlink@@GLIBC_2.2.5'` in Build Log, and I need '-lrt', but still I don't get it. Could you teach me where to type in 'rt'?
Comment: @greatewolf  Thanks. Then, I should type in 'rt' ?, not 'lrt'?
Comment: Oh, It's 'rt'. Thanks
Answer: Thanks, @greatwolf.
Finally, I could get rid of that error.
Now,I show the "Linker setting" in below.
<code>../../opencv-2.4.13/build/lib/libopencv_highgui.so

../../opencv-2.4.13/build/lib/libopencv_core.so

../../opencv-2.4.13/build/lib/libopencv_imgproc.so

pthread

boost_system

rt
</code>


Model Theory: the Hodges book

Question: In the large Wilfrid Hodges book: Model Theory I have 2 easy questions,first on the page 164, example 2, $V$ is exactly $A$:
they begin with
Let $V$ be an infinite vector space (in my opinion this should read "Let $A$ be an infinite vector space") but then they say something about $A$:
Thus again $A$ is minimal.
Next, what should I take for $D$ in 6.4.1. in the proof of the fact 4.5.1 ?
What corresponds to $A,B$ and $C$ from the proof of 4.5.1.(the first snippet) to in 6.4.1. (the second snippet) ?
Please see 2 snippets below.

*** $\mathbf{second\  snippet}$ ***
Comment: Have you tried to prove 4.5.1 directly (using compactness) without going through 6.4.1?
Comment: @PrimoPetri No, I haven't. Besides I think that I would not be able to prove this way, I would like to understand the suggested solution through 6.4.1.
Comment: In example 2 there is a typo. Read A=V.
Answer: Suppose $C$ is a counterexample (not $B$!).
Say, $c$ is a tuple of parameters in $C$ and $\delta(x,c)$ is a formula such that for every $n$
$$C\models\exists^{\ge n} x \ \ \psi(x)\wedge\delta(x,c)$$
$$C\models\exists^{\ge n} x \ \ \psi(x)\wedge\neg\delta(x,c)$$
Let $B=A$, $D\succeq B$, and $g:C\to D$ be as in Theorem 6.4.1. Then
$$D\models\exists^{\ge n} x \ \ \psi(x)\wedge\delta(x,gc)$$
$$D\models\exists^{\ge n} x \ \ \psi(x)\wedge\neg\delta(x,gc)$$
This proves (a)$\rightarrow$(b) of Fact 4.5.1.
(I insist that proving Fact 4.5.1 by elementary amalgamation is insane.)
Comment: They are not contradictory since given that $C$ is a counter example to the claim, then $\phi(x)$ defines an infinite-coinfinite set inside of $C$. If such a $\delta$ did not exist then in fact $\psi(x)$ would be minimal in $C$.
Comment: Your snippets do not contain Hodges' definition of minimal set. So I have used the standard one: there is a definable subset $\delta(C,b)$ of $\psi(C)$ that is infinite and coinfinite.
Comment: Thank you for your answer. I do not follow what have you accomplished by these two rows; they seem to me that they are **contradictory** anyway: $$C\models\exists^{\ge n} x \ \ \psi(x)\wedge\delta(x,c)$$

$$C\models\exists^{\ge n} x \ \ \psi(x)\wedge\neg\delta(x,c).$$ What says $\delta(x,c)$ there ?
Comment: @PrimoPetri Right. Luckily I've given a link to the entire book in the first row of my OQ.

Model Theory: the Hodges book


In classical singing the speaking range is not a specific register. Why is this?

Question: I disslike singing in my speaking range. I feel like it is much easier to sing above the speaking range.
In classical singing the speaking range is not a specific register. Why is this?
Answer: You can describe 'Speaking range' as a register if you want to.
You find it easier to sing above it.  Personally, I'd define it as the singing range which is easy, minimal effort required! But we're all different.


For $\triangle ABC$, prove $\sum_{cyc}\frac{1}{4+\cos A\cos(B-C)}\geq\frac23$

Question:
For the triangle $\triangle ABC$, prove the inquality,
  $$\frac1{4+\cos A\cos(B-C)}+\frac1{4+\cos B\cos(C-A)}+\frac1{4+\cos C\cos(A-B)}\ge \frac23$$
  where $A$, $B$ and $C$ are the vertex angles.

I had trouble tackling it. Have treated it as a minimization problem, subject to the constraint $A+B+C=\pi$. In principle, it could be solved with the Lagrange multiplier. However, the required algebraic work seems to be prohibitive. Wonder whether there is a more elegant path to show it.
Answer: First, we use the trig identity $ \cos A \cos B = \frac{1}{2} (\cos(A+B) + \cos(A-B)) $:
$$\frac1{4 + \cos A \cos(B-C)}+\frac1{4  +\cos B \cos(C-A)} + \frac1{4 + \cos C \cos(A-B)} \ge \frac23$$
$$ \Leftrightarrow \frac1{4 + \frac{1}{2} (\cos(A+B-C) + \cos(A-B+C))} + \frac1{4 + \frac{1}{2} (\cos(B+C-A) + \cos(B-C+A))} + \frac1{4 + \frac{1}{2} (\cos(C+A-B) + \cos(C-A+B))} \ge \frac23 $$
Since $A + B + C = \pi$, we get:
$$ \frac1{4 + \frac{1}{2} (\cos(\pi-2C) + \cos(\pi-2B))} + \frac1{4 + \frac{1}{2} (\cos(\pi-2A) + \cos(\pi-2C))} + \frac1{4 + \frac{1}{2} (\cos(\pi-2B) + \cos(\pi-2A))} \ge \frac23 $$
Using the trig identity $ \cos(\pi-x) = - \cos x$:
$$ \frac1{4 - \frac{1}{2} (\cos(2C) + \cos(2B))} + \frac1{4 - \frac{1}{2} (\cos(2A) + \cos(2C))} + \frac1{4 - \frac{1}{2} (\cos(2B) + \cos(2A))} \ge \frac23 $$
Applying the inequality $ \frac1a + \frac1b + \frac1c \ge \frac9{a+b+c}$:
$$ \frac1{4 - \frac{1}{2} (\cos(2C) + \cos(2B))} + \frac1{4 - \frac{1}{2} (\cos(2A) + \cos(2C))} + \frac1{4 - \frac{1}{2} (\cos(2B) + \cos(2A))} $$
$$ \ge \frac9{12 - (\cos(2A) + \cos(2B) + \cos(2C))} $$
Finally, use the inequality $ \cos(2A) + \cos(2B) + \cos(2C) \ge - \frac{3}{2}$ (which you can find the proof in here: Prove that $\cos(2a) + \cos(2b) + \cos(2c) \geq -\frac{3}{2}$ for angles of a triangle):
$$ \frac{9}{12 - (\cos(2A) + \cos(2B) + \cos(2C))} \geq \frac{9}{12 - (- \frac{3}{2})}  = \frac23 $$
The inequality holds when
$$A = B = C = \frac{\pi}{3} $$
or ABC is an equilateral triangle
Answer: Using $\cos(B+C)=\cos(\pi-A)=?$
and Prove that $\cos (A + B)\cos (A - B) = {\cos ^2}A - {\sin ^2}B$
$$2(4+\cos A\cos(B-C))$$
$$=8-\cos(B+C)\cos(B-C)$$
$$=8-(\cos^2B-\sin^2C)$$
$$=9-(\cos^2B+\cos^2C)$$
Now using AM -HM inequity,
$$\dfrac{\sum_{\text{cyc}}\dfrac2{9-(\cos^2 B+\cos^2C)}}3$$
$$\ge\dfrac3{\dfrac{27-2(\cos^2A+\cos^2B+\cos^2C)}2}$$
The equality will occur if $9-(\cos^2 B+\cos^2C)=9-(\cos^2C+\cos^2A)=9-(\cos^2A+\cos^2B)$
$\iff\cos^2A=\cos^2B=\cos^2C$
$\iff\sin^2A=\sin^2B=\sin^2C$
which will occur if $A=B=C$
using Prove $ \sin(A+B)\sin(A-B)=\sin^2A-\sin^2B $


Showing that the noncentered model can be written in centered form

Question: The model for each $y_i$ can be written in terms of centered $x$ variables as
$$\begin{align}y_i &= \beta_0+\beta_1x_{i1}+ \cdots+\beta_kx_{ik}+\epsilon_i \\&=\alpha +\beta_1(x_{i1}-\bar{x}_1)+\beta_2(x_{i2}-\bar{x}_2+\cdots+\beta_k(x_{ik}-\bar{x})+\epsilon_i \end{align}$$
$i = 1, 2, ..., n$ where
$$\alpha = \beta_0+\beta_1\bar{x}_1+ \cdots + \beta_k\bar{x}_k$$
I have to write this but in noncentered form, here is what I have tried:
$$\begin{align}\mathbf{x\hat{\beta}}&=\mathbf{x(x^Tx)^{-1}x^Ty} \\&\implies \mathbf{\hat{\beta}(x-\bar{x})=y[x(x^Tx)^{-1}x^T-\bar{x}(\bar{x}^T\bar{x})^{-1}\bar{x}^T]}  \end{align}$$
Then to find $\alpha$ we have something like
$$\alpha = \mathbf{\bar{x}\beta}=\mathbf{\bar{x}(\bar{x}^T\bar{x})^{-1}\bar{x}y} \\ \implies \mathbf{\alpha-\beta(x-\bar{x})}=\mathbf{\bar{x}(\bar{x}^T\bar{x})^{-1}\bar{x}y+y[x(x^Tx)^{-1}x^T-\bar{x}(\bar{x}^T\bar{x})^{-1}\bar{x}^T]}$$
Answer: We can show the noncentered model by the following:
$$y_i=\begin{pmatrix}j & X_C \end{pmatrix}\pmatrix{\alpha_0 \\ \beta_1} = \alpha_0j+\beta_1X_C+\epsilon$$
We have that
$$X_C = (I - \frac{J}{n})X_1 = \pmatrix{x_{11}-\bar{x}_1 & \cdots & x_{1k}-\bar{x}_k \\ \vdots & \cdots & \vdots \\ x_{n1}-\bar{x}_1 & \cdots & x_{nk}-\bar{x}_k }$$


Que tipo de dados (double, float) eu devo usar ao representar uma temperatura?

Question: Minha dúvida é em relação ao uso do Double e do Float em exercícios de Java ao ter que declarar uma temperatura (escala Celsius). Qual deles devo usar nesse caso?
Eu declarei como Double, porém a professora ao corrigir o exercício em classe acabou usando o Float.
Sei que entre esses dois dados a diferença é a precisão que eles apresentam, mas o que ainda não consegui entender é quando cada um deles, e para quais fins o Double e o Float são usados.
Comment: Eu acho que vale a pena perguntar para a professora porque float está "errado" nesse caso. A princípio, temperaturas não exigem uma precisão tão grande que um float não possa suportar. A menos que haja algum outro detalhe no exercício que "obrigue" a usar double (ou que faça ele ser a melhor escolha). Mas parece que vc está usando os wrappers (**D**ouble e **F**loat, com letra maiúscula), pode ser que isso tenha a ver com a resposta. Se quiser **[edit]** a pergunta colocando mais detalhes, como o trecho de código por exemplo, quem sabe podemos dar mais detalhes sobre este caso específico
Comment: @ramaral É mesmo, que distração a minha. Mesmo assim, qualquer um dos tipos serviria e continua sendo estranho que um deles esteja "errado" e precise ser "corrigido". A menos que haja algum detalhe no exercício que "obrigue" a usar float.
Comment: você pode encontrar uma ótima explicação [aqui](https://pt.stackoverflow.com/questions/219211/qual-a-forma-correta-de-usar-os-tipos-float-double-e-decimal/219465).
Comment: E depois de perguntar pra professora, comente aqui o que ela disse, que é pra gente ver se tem fundamento mesmo. Não duvidando dela, lógico, mas só pra ficar do lado "seguro". Já vi muito professor (de faculdade renomada, inclusive) que claramente só leu teoria, mas nunca teve que fazer nada "real", pelo tipo de aula dada.
Comment: @hkotsubo Nada obriga, no entanto há justificação para escolher `float` conforme explicado na resposta do Manieiro e do Victor.
Comment: obrigada gabriel!
Comment: @hkotsubo Julgo que entendeu mal pois *"a professora ao corrigir o exercicio em classe acabou usando o `Float`! "*
Answer: Não existe um tipo específico adequado, para este caso alguns podem ser usados.
Na verdade, se for criar tipos para lidar com essas temperaturas e for usar uma infraestrutura sofisticada para representá-los, o tipo interno que guardará os números importa pouco. Poderia usar algumas estratégias e depende do que espera realizar. Pode até que ser que um simples float resolva fácil.
Se for usar um tipo genérico para representar pode até usar um int, mas provavelmente o mais fácil seja usar um float que já tem a parte decimal. Com um int teria que fazer sempre uma divisão para pegar a parte decimal, fazer contas para adequar a escala que estiver usando, tem que ter vários cuidados e não deve valer a pena pra uso básico, e para uso mais sofisticado acho que a solução anterior é melhor.
Nada impede usar um double, mas acho exagero para este tipo de coisa. O float economiza memória e tem precisão mais que suficiente pra algo simples assim. Não dá para dizer que está errado, mas não seria a primeira escolha.
A diferença entre eles é só a precisão mesmo, o que obviamente faz o mais preciso ser maior (8 bytes contra 4). Não confundir com exatidão.
Se tivesse no enunciado para usar algo que ocupa menos espaço, poderia até pensarem outras coisas, ainda mais se tiver exigência de exatidão. Me parece que nada disso é exigido, aí float é melhor em uso real, mas dá para argumentar que o double não faz mal a não ser ocupar memória a toa, que muda pouco na maioria dos casos.
Neste caso duvido que o BigDecimal seja necessário, mas só você pode responder se deve ter exatidão além da precisão que o float já dá. Veja mais em Qual a forma correta de usar os tipos float, double e decimal?.
Coloquei no GitHub para referência futura.
Answer: Deixa eu copiar algumas coisas que postei nesta resposta:

O float e o double são implementados de acordo com o padrão IEEE 754, usado por praticamente todas as linguagens de programação modernas que trabalham com números de ponto flutuante de 32 ou 64 bits.
O float é representado com 32 bits dessa forma (imagem da wikipedia):

Observe o primeiro bit, ele é o bit de sinal. Se for 0 é um número positivo, se for 1 é negativo. De forma que o valor do float é o seguinte:

(a) , se o expoent for diferente de 0 e de 255.
(b) , se o expoent for igual a 0.
(c) , se o expoent for igual a 255 e o fraction for igual a 0.
(d) NaN, se o expoent for igual a 255 e o fraction diferente de 0.

Os valores da equação (a) são aqueles que são denominados de números de ponto flutuante normais, enquanto que os da equação (b) são denominados de números de ponto flutuante subnormais ou denormais. Já os valores do (c) são os de infinidade e (d) é NaN (not-a-number).

Ainda temos o double que usa um conceito semelhante, mas com mais bits e valores diferentes:

As equações do double são essas:

(a) , se o expoent for diferente de 0 e de 2047.
(b) , se o expoent for igual a 0.
(c) , se o expoent for igual a 2047 e o fraction for igual a 0.
(d) NaN, se o expoent for igual a 2047 e o fraction diferente de 0.

Pois bem, o double tem uma capacidade de armazenagem maior do que o float tanto no expoente quanto na mantissa (fraction). Assim sendo, todo valor float pode ser representado por um double, mas o contrário não é verdadeiro. Logo, a pergunta a ser feita é se o float oferece precisão suficiente.
O float tem 23 bits para representar o fraction. Isso é suficiente para armazenar números inteiros mantendo o expoent em 0 nos valores entre 0 até 224 - 1 = 16777215. Para representar o 16777217, ele perde o bit 1 menos significativo arredondando para 16777216.
Isso significa que números com precisão de 0.5 pode ser armazenados até 8388607.5. Com precisão de 0.25, é até 4194303.75. Mantendo-se uma precisão suficiente para representar 3 casas após o ponto decimal (com precisão 1/1024), dá para representar números até 16383.999.
Representar números que representam temperaturas com precisão de milésimos de graus até uma temperatura de mais de 16000 graus, mostra que o float tem precisão suficiente para isso. Assim sendo, tanto o float quanto o double podem ser utilizados.