Erro na função de forçar download por php

Question: Ola estou com o código abaixo de forçar e renomear arquivos de media em mp4 via download de URL remota com tudo o download esta vindo corrompido pois não esta efetuando o download devidamente. Como posso concertar isso pois o arquivo ao efetuar o download esta ficando com 2kbs de tamanho.
<code>$file = 'http://thumb.mais.uol.com.br/15328248.mp4';
$nome = 'novoNome.mp4';
header("Content-Description: File Transfer");
header("Content-Type: video/mp4");
header('Content-Disposition: attachment; filename="' . ($nome) . '";');
header('Content-Length: ' . strlen(file_get_contents($file)));
readfile($file);
</code>
Comment: cara, eu testei seu código e o download funcionou normalmente, não pode ser algo em sua rede que corrompeu o download? faz o teste com arquivos menores ou de outros tipos... neste [link](http://stackoverflow.com/questions/7263923/how-to-force-file-download-with-php) diz para colocar ob_clean(); flush(); antes do readfile, veja se muda algo pra vc....
Comment: Aqui só funcionou com arquivos pequenos necessito que funcione com arquivos grandes no max ate 300mbs.
Answer: Veja se os atributos:
memory_limit,
post_max_size,
upload_max_filesize,
max_execution_time
Estão com os valores que você deseja no php.ini
Comment: ai que ta coloquei tudo a 300 mb e mesmo assim ainda não pega o tamanho maximo do arquivo deixando ele corrompido com 2kbs. E no caso eu estou pegando URL remota não estou efetuando o upload deste arquivo pro meu servidor só necessito que ele pegue o tamanho certo e mude o nome do arquivo direto pela header.
Comment: Você modificou o memory_limit para quanto? Geralmente esse tipo de erro ocorre porque o servidor consome mais que 300 MB quando é solicitado um download de algo de 300 MB. Dai depende de quanto você pode aumentar no seu servidor. Mas, tinha casos que eu tinha que setar 1024 MB ou 2048 para conseguir passar grandes downloads para o usuário. (as vezes eu só setava esses valores na página PHP que utilizava o download).
Ou então modificava o PHP ini, reiniciava o APACHE e ia tranquilo.
Comment: Os arquivos não chegam nem a 200mb e memory_limit coloquei a 300mb.
Comment: Mas, como te disse, ele sempre consome mais que o tamanho do arquivo.  E, no caso, eu sempre modificava pelo menos os 3 parametros (upload max filesize, post max size e o memory limit). Tenta colocar um tamanho maior e veja se vai.


Retrieve pfSense/freeBSD logs with elk

Question: I am attempting to centralize logs from different systems.
I installed the Elastick Stack (Elasticsearch, Logstash, Kibana) and WAZUH OSSEC on one server (named elk).
I have installed the OSSEC agent on three ubuntu server and I am able to check logs and file integrity.
However, how could I also get logs from a pfSense ? I tried installing OSSEC agent by compiling it, but it is not so easy... I was thinking to do it via remote syslog, but it doesn't seem to be working...
On the pfSense Interface -> Status -> System Logs -> Settings I put the address and port of my elk in the remote log server field, and I added this in /var/ossec/etc/ossec.conf of elk :
<remote>
    <connection>syslog</connection>
    <port>514</port>
    <protocol>udp</protocol>
    <allowed-ips>192.168.2.0/24</allowed-ips>
    <local_ip>192.168.2.4</local_ip>
</remote>

But I don't get any logs of my pfSense when I visualize them with Kibana...
Do you know how to make it work?
Answer: Try running tcpdump to actually confirm you have traffic coming from your pfSense device. For example you could run something like:
tcpdump -nni eth0 port 514 -s 0 -AA

That will show you the packet header and payload.
Try also checking that ossec-remoted process is listening for incoming traffic. You can do it by running:
netstat -nap | grep 514

In addition, as another option that I personally like, you can use (on the Wazuh server) Rsyslog daemon to collect Syslog data and dump it into a file.
Then you can configure the Wazuh server logcollector component to read that log file, so it is also processed by Wazuh and the analysis engine.
A good tool to monitor if Rsyslog is writing to the file and if ossec-logcollector component is reading it is running lsof. Example:
lsof /var/log/your_syslog_file.log

To use Rsyslog you will need to configure it to listen for remote data, and a rule to write logs to the file. An example of a rule would be:
if ($fromhost == '192.168.98.1') and ($msg contains 'pfSense') then -/var/log/your_syslog_file.lgo

If you go this way, to avoid conflict, remember to disable ossec-remote sysl
Comment: Thank you for your answer. I am able to see traffic coming from pfSense via tcpdump... The format of the pfSense logs and other logs coming from ohter devices (auth.log for example) are slightly different... May it be the problem ? Does elk know how to parse it ?

Retrieve pfSense/freeBSD logs with elk


Crash STS when open with Unable to acquire application service. Ensure that the org.eclipse.core.runtime bundle is resolved and started

Question: Hi this happend with version of Spring:
Spring Tool Suite 4
Version: 4.12.0.RELEASE
Build Id: 202109130635
The error in logs is:
java.lang.IllegalStateException: Unable to acquire application service. Ensure that the org.eclipse.core.runtime bundle is resolved and started (see config.ini)
The file of log is in C:\Users\user\sts-4.12.0.RELEASE\configuration
Answer: I think this version works with JDK  of Java only. So when I tried to open with a version 8  of Java STS inform me the exception. Changing to version of Java 11 in my laptop this works ok again.


GitHub credential authentication to push files on a repo

Question: This question is some kind of follow up of this one:
Authorization when creating a file in Javascript in a GitHub repo using API
My goal is to create a static page with GitHub Pages with a simple button.
When a user presses this button, a new file is created in the same repository, with fixed content, in the same branch used for GitHub pages.
Suppose you have the address of GitHub Pages static page, for example:
https://github.com/MyGitHubAccount/MyGitHubRepo/blob/gh-pages/index.html
If this repo is public, anyone can go to this page and see the content in the browser.
Suppose a user wants to press the button to create the new file. I can see 3 scenarios:

the user is not logged in GitHub -> if the user clicks the button, the file cannot be created in the repo

the user is logged in GitHub, but MyGitHubRepo is not one of his repo ->  if the user clicks the button, the file cannot be created in the repo

the user is logged in GitHub and MyGitHubRepo is one of his repo

If the user clicks the button, is it possible to create and push the file in the repo?
What are the conditions? Is there any example I can study?
Comment: as it was mentioned in your previous post, If you don't want to use the Backend server, You have to create a Github Application that will authenticate the user and give you access to upload files to repo.
Comment: See https://docs.github.com/en/developers/apps for detail
Answer: TiddlyWiki does what you want
( host on GH/GL Pages , save via JS and https:// git push with token )
See e.g. the Settings Dialogue here: https://doc-links-manual-howto.github.io/


How to create a single page with a jump select menu?

Question: I need to create a page with a single jump select menu. Once the user makes a selection he/she will be redirected to a view page where the selection will be used as contextual filter
Can I do it with the webform module? What other option do I have?
I've found this one: http://drupal.org/project/jump but just a dev version for d7.
Answer: Views provides a "jump menu" display, you could just use that.
Answer: You can create a page with a page callback using hook_menu(). Here is a workaround.
<code><?php
/**
 * Implements hook_menu().
 */
function mymodule_menu() {
    $items = array();
    $items['mypage'] = array(
        'title' => 'Available vouchers for you',
        'page callback' => 'mymodule_country_select_page',
        'access callback' => TRUE,
    );
    return $items;
}

function mymodule_country_select_page(){
    $country = array(
        '#type' => 'select',
        '#name' => 'country',
        '#title' => t('Select country to see your available Vouchers'),
        '#options' => array(
            '' => t(' - Select - ')
        ),
        '#attributes' => array(
            'onchange' => "window.location=this.value"
        ),
    );

    $options = array(
        '1' => 'Country 1',
        '2' => 'Country 2',
        '3' => 'Country 3',
    );
    foreach($options as $arg => $name){
        $url = url('path/to/view/', array('query'=> array('arg'=>$arg), 'absolute'=>TRUE));
        $country['#options'][$url] = t($name);
    }

    return render($country);
}
</code>


Add S3 Bucket as a network drive

Question: I'm using windows and I need to add my s3 buckets as a network drive on my system. I've found 3 applications: webdrive, tntdrive and gladient. I want to know the idea behind doing this so I could do it myself. Because first, they are not free and second, I need an application with possibility of running from command line.
Answer: To mount an S3 filebucket as a network drive, you'd need a filesystem driver that supports it. I'm not aware of any such driver for Windows that's native. Unless you find some application that comes bundled with the driver (AWS forum link to this topic), you're down to writing one.
Comment: That's **way** more than a single Q&A question. Start here: https://www.google.com/search?q=writing+windows+filesystem+driver
Comment: So you are saying all those three applications have their own driver?
Comment: @AliBZ Yes, they must install their own driver software to function.
Comment: Could you give me some tips on where and how to start implementing this?

Add S3 Bucket as a network drive


How to group data into 10 second intevals?

Question: I have a table with 3 columns.
id  bigint,
rate decimal(18,2),
dateCreated datetime
I need the results to be grouped by 10 second interval.
Something like :
2019-12-15:00 13:20:10   avg(rate)
2019-12-15:00 13:20:20   avg(rate)
2019-12-15:00 13:20:30   avg(rate)
etc....
I am using SQL server 2017.
How do I accomplish that ?
Thank you in advance.
Comment: [so] is *not* a free code writing service. You are expected to try to **write the code yourself**. After [doing more research](http://meta.stackoverflow.com/questions/261592) if you have a problem you can **post what you've tried** with a **clear explanation of what isn't working** and providing a **[mcve]**. I suggest reading [*How do I ask a Good Question*](/help/how-to-ask) and [*Writing the Perfect Question*](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/). Also, be sure to take the [tour].
Comment: Are there rows within _every_ 10 second interval? Do you need output for every 10 second interval even if there are no rows? What have you tried?
Answer: Perhaps truncating the datetime
Example
Select TrimTime = convert(varchar(18),dateCreated,120)+'0'
      ,AvgRate  = avg(Rate)
 From  YourTable
 Group By convert(varchar(18),dateCreated,120)

Comment: Brilliant - so simple it hurts. I was making a big ol' answer...but I think I'll stop before embarrassing myself ;-)
Comment: @Clay Thanks for the grin.  :)   Don't be shy about posting.  Feedback is how we all learn... and that's the fun part.
Comment: Aite - will do...I spent some time...might as well. But this is *the* answer
Comment: @VadimS Always happy to help.  I'm sure my wife would dispute the "genius" thing  :)
Answer: Imagine you have a time table... let's call it TimeHacks...and it's divided into 10 second time spans. Maybe it looks something like
create table TimeHacks
(
  IntervalNumber bigint,
  DateTimeAtInterval datetime
)

Then it would be easy to join it to your table:
select
  t.IntervalNumber,
  avg( y.rate )
from
  dbo.TimeHacks i
  inner join
  dbo.YourTable y
  on
    datediff( s, y.DateCreated, i.DateTimeAtInterval ) between 0 and 9
group by
  i.IntervalNumber

...and so the question is...do you make a table that has all those time hacks in it, or is there a better way?
So...now let's say that TimeHacks table isn't a table at all, but a SQL Server table valued function that takes 3 arguments, a start datetime, an end datetime and a number of seconds between hacks.
You could say something like:
select
  i.IntervalNumber,
  avg( y.rate )
from
  dbo.TimeHacks( '2019-1-15 10:10:10', '2019-1-16 10:10:10', 10 )
  inner join
  dbo.YourTable y
  on
    datediff( s, y.DateCreated, i.DateTimeAtInterval ) between 0 and 9
group by
  i.id

Hmmm...but how to make that TimeHacks function? Let's imagine that we also have a table valued function that can generate arbitrary sequences of integers from any start to any end... like dbo.FromTo( start bigint, end bigint ). Then, our TimeHacks could be something like:
create function dbo.TimeHacks( @start datetime, @end datetime, @seconds int ) returns table as return
select
  ft.x as IntervalNumber,
  dateadd( s, ft.x * @seconds, @start ) DateTimeAtInterval
from
  dbo.FromTo( 0, datediff( s, @start, @end ) / @seconds ) ft

...and finally...how would we generate a sequence of numbers that forms the basis for our dbo.TimeHacks function? There's a number of answers to that question...some good ones here. I learned a lot from those answers. You might, too. Anyway, I've got a favorite version I've tweaked out of those answers. It makes a sequence of numbers without doing any I/O and can produce any sequence in order in the range of integers...and it's screaming fast:
create function dbo.FromTo( @start bigint, @end bigint ) returns table as return
with
x0 as (select x from (values (0),(0x00000001),(0x00000002),(0x00000003),(0x00000004),(0x00000005),(0x00000006),(0x00000007),(0x00000008),(0x00000009),(0x0000000A),(0x0000000B),(0x0000000C),(0x0000000D),(0x0000000E),(0x0000000F)) as x0(x)),
x1 as (select x from (values (0),(0x00000010),(0x00000020),(0x00000030),(0x00000040),(0x00000050),(0x00000060),(0x00000070),(0x00000080),(0x00000090),(0x000000A0),(0x000000B0),(0x000000C0),(0x000000D0),(0x000000E0),(0x000000F0)) as x1(x)),
x2 as (select x from (values (0),(0x00000100),(0x00000200),(0x00000300),(0x00000400),(0x00000500),(0x00000600),(0x00000700),(0x00000800),(0x00000900),(0x00000A00),(0x00000B00),(0x00000C00),(0x00000D00),(0x00000E00),(0x00000F00)) as x2(x)),
x3 as (select x from (values (0),(0x00001000),(0x00002000),(0x00003000),(0x00004000),(0x00005000),(0x00006000),(0x00007000),(0x00008000),(0x00009000),(0x0000A000),(0x0000B000),(0x0000C000),(0x0000D000),(0x0000E000),(0x0000F000)) as x3(x)),
x4 as (select x from (values (0),(0x00010000),(0x00020000),(0x00030000),(0x00040000),(0x00050000),(0x00060000),(0x00070000),(0x00080000),(0x00090000),(0x000A0000),(0x000B0000),(0x000C0000),(0x000D0000),(0x000E0000),(0x000F0000)) as x4(x)),
x5 as (select x from (values (0),(0x00100000),(0x00200000),(0x00300000),(0x00400000),(0x00500000),(0x00600000),(0x00700000),(0x00800000),(0x00900000),(0x00A00000),(0x00B00000),(0x00C00000),(0x00D00000),(0x00E00000),(0x00F00000)) as x5(x)),
x6 as (select x from (values (0),(0x01000000),(0x02000000),(0x03000000),(0x04000000),(0x05000000),(0x06000000),(0x07000000),(0x08000000),(0x09000000),(0x0A000000),(0x0B000000),(0x0C000000),(0x0D000000),(0x0E000000),(0x0F000000)) as x6(x)),
x7 as (select x from (values (0),(0x10000000),(0x20000000),(0x30000000),(0x40000000),(0x50000000),(0x60000000),(0x70000000)) as x7(x))

select s.x
from
    (
    select
          x7.x
        | x6.x
        | x5.x
        | x4.x
        | x3.x
        | x2.x
        | x1.x
        | x0.x
        + @start
         x
    from
        x7
        inner remote join x6 on x6.x <= @end - @start and x7.x <= @end - @start
        inner remote join x5 on x5.x <= @end - @start
        inner remote join x4 on x4.x <= @end - @start
        inner remote join x3 on x3.x <= @end - @start
        inner remote join x2 on x2.x <= @end - @start
        inner remote join x1 on x1.x <= @end - @start
        inner remote join x0 on x0.x <= @end - @start
    ) s
where @end >= s.x

The way this function works borders on magic. It's based on the question I referenced, and in particular it builds on the answers by Brian Pressler and
mechoid.
Comment: When I run my TVF https://dbfiddle.uk/?rdbms=sqlserver_2016&fiddle=e2624f62a8a7c925399c8493186a7642 vs your function... your's has a cost of 88% vs 12%
Comment: @JohnCappelletti, yer making me feel low, my friend! When I did the same locally...mine said 100% relative to batch and yours said 0% relative to batch...so I felt even lower. But I saw weirdness...I could *see* that mine appeared to run faster: looking in profiler, while mine took nearly twice the cpu, it consistently returned quicker. Parallelization? More investigating. I messed with yours to take `datetime, datetime,int` (secs)...so that it matched TimeHacks. Maybe I did bad? I don't know how to do the SO chat...but would love to continue this thread. I did 100 days in 1 sec intervals.
Comment: Let me dig into this a bit later.   Need to shovel before it turns into slush and then ice.   I'm so done with Winters.
Comment: Then I won't tell you how bad things are here in Florida ;-)
Answer: This is actually a very good and somewhat complex question.  I'm sorry you were treated so.  Take a look at this Stack Overflow post for a possible way of attacking it and good luck.
Comment: Thanks, Def a good start.  Plenty of ways to group by min... But grouping by seconds had me stumped...


Pros and cons of 5 ANOVAs for 5 DVs instead of 1 MANOVA

Question: This** study asked subjects to rate musical excerpts along 5 subjective dimensions (valence, tension, energy, consonance, preference); each excerpt had a certain chord type and a certain register.
The authors did 5 separate ANOVAs, one for each DV, to look for the effect of chord type and register on the 5 rating dimensions.
Would it not have been "more correct" to do one MANOVA, given that (as they report) there was moderate correlation between them?
Or is it the case that doing multiple ANOVAs presents its own advantages?
Screenshots below.
** Lahdelma, I., & Eerola, T. (2016). Mild Dissonance Preferred Over Consonance in Single Chord Perception. I-Perception, 7(3), 2041669516655812. http://doi.org/10.1177/2041669516655812
Comment: Separate ANOVAs are more specific than one global MANOVA. You run MANOVA to avoid false positives due to multiple testing and to increase the power. When all 5 anovas yield p<0.001 significant effects (as in the table), one does not really need to pursue either of these aims.
Answer: It depends on what the research question is. Multivariate analyses help to answer the question "Is there a main effect on any of these DVs?". So, if there's no theory-driven prediction on any particular DV, it's important to run a MANOVA before running separate ANOVAs to help us interpret our finding. But if the 5 relationships are conceptually distinct, then just running the separate ANOVAs is fine. The problem, I guess, is that it can be difficult to work out if researchers are conjuring up conceptual distinctions post hoc.
Comment: +1 But I would add that when all 5 anovas yield p<0.001 significant effects (as in the table reproduced in the question), then it does not really matter what test to run. There is little danger of false positives due to multiple testing if all 5 tests are significant with p<0.001.
Comment: The correct test to run should not be predicated on what the result ends up being. I mean, it'd be sketchy to say that we *didn't* run corrections for multiple comparisons because if we did, some of the tests were significant. So, the decision to make corrections for multiple comparisons has to begin with theory and intention.
Comment: Excellent point Jon, and thanks to both for your helpful responses


Citrix Secure Gateway not redirecting to login URL

Question: We have an older setup for XenApp - users log in through Citrix Secure Gateway running on a windows box.  (We hope to start using a NetScaler soon.)
Earlier today, connections to https://citrix.company.com/ starting throwing up a 503 error page, instead of redirecting to https://citrix.company.com/Citrix/XenApp/  If you go directly to the /Citrix/Xenapp/ URL, the user is properly directed to the login page, and can launch apps.
We've restarted the service, and rebooted the server.  We haven't yet tried uninstalling and reinstalling the software.  Before we do this, I'm looking for ideas as to how we can get the redirect working again without a fairly major outage window.
To make things more interesting, many of our users have Citrix Receiver installed, also pointed at https://citrix.company.com/.  Receiver makes itself the default launcher for ICA files, and gives a connection error when it tries to load apps - probably because of the same non-functional rediect?
Comment: Also, have you definitely narrowed this down to CSG vs Web Interface. What happens if you try it on port 80 with http. I believe the redirect is actually there rather than with CSG. You may need to reconfigure the default site.
Comment: Just need to clarify if you're using the Access Gateway or the Secure Gateway - they are two different products and will impact what you need to look at.
Comment: The MMC snap-in for it calls it "Secure Gateway 3.3"
Comment: +1 to Dan. Generlaly, with CSG, the redirects are done on the web interface side.
Comment: Connecting directly to the web interface also yields the 503, but works if the /Citrix/XenApp/ path is specifically entered.  I will investigate further.
Comment: Yep, the DefaultAppPool for the web interface wasn't running, and would not start.  Rebooting the server in question fixed the issue.  Dan, if you want to post an actual answer, I will mark it as accepted.
Answer: The redirect from the root to the Citrix site is performed on Web Interface server, rather than through the Secure Gateway. You should check the Web Interface directly, bypassing CSG.


Overpopulated apartment

Question: $119$ people live in a building with $120$ apartments. An apartment is called overpopulated if there are more than $15$ people living in it. Each day the tenants of some overpopulated apartment have a quarrel and they all move to different apartments in the same building. Is it true that eventually none of the apartments will be overpopulated?
Attempts and observations:

If we organize the building into a $15\times 8$ grid with $8$ floors, after a quarrel at least $2$ of new floors(floors other than the floor on which the quarrel happened) occupy $1$ more tenants each(floors might be same)

If an apartment is called overpopulated if there are more than $14$ people in it, then the answer is no

If we prove that this process terminate, then we are done
Comment: how are all the 119 people distributed amongst the 120 apartments to begin with? if there is a quarrel do the 15 people relocate to 15 new different apartments?
Comment: We don't know the distribution. There is a quarrel only with 16 or more people in which case they do relocated to new different appartment
Comment: All of them move out of the appartment
Comment: Not just the extra person
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/118586/discussion-between-saket-yagay-and-no-lemon-no-melon).
Comment: Maybe this example is simpler: say you have two apartments A and B. A has 16 people, quarrel breaks out, all of them move to B. Next day all of them move to A. Next day to B, next day... And so on, and so on, an infinite loop. And no overpopulation threshold changes that.
Comment: Or perhaps they move randomly and this is a question about the expected number of days until no apartment is overpopulated? But then it will work for any overpopulation threshold because there are more apartments than tenants.
Comment: It is given that they all move to distinct apartments
Comment: For eg, 2 people from overpopulated apartment X can't move to same apartment just yet
Comment: @saketyagay $7$ apartements with $15$ people plus $1$ apartement with $14$ people is a stationary situation. There are many others, until each person is in one apartment and 1 is empty. If one of these situation is reached the problem terminates. Am I right?
Comment: @raffaele yes you are
Answer: To try and prove that it is false would entail beginning from an overpopulated apartment, dispersing the inhabitants to different apartments  and getting another overpopulated apartment, and thus dispersing the inhabitants can cause the population of an apartment to increase by one for each abandoned apartment.
Say, you wanted a sequence of overpopulated apartments with $n_i$ people living in each one,
$$ n_i \geq 16 ,1 \leq i \leq m+1.$$
Beginning from $n_1$, $n_1$ people are dispersed to $n_1$ different apartments, if you want an apartment next with $n_2$ people in it, you would of needed to have an apartment with at least $n_2 -1$ people in it at first go. And then an apartment with at least $n_3 -2$ people in it at first go... and so on and so on.
Thus in general there must be $n_1 + n_2 -1 + n_3 -2 + ... =\sum\limits_{i=1}^{m+1} n_i - \sum\limits_{i=0}^{m}i \geq 16(m+1)-\frac{m(m+1)}{2}= 136> 119$ for $m=16$, since an apartment cannot have negative people in it. Thus if you wanted a sequence other than $16,16,16,...$ you would need even more people.

Overpopulated apartment


Maven assembly plugin zips the jar.original content and not the executable jar

Question: How to pack the executable jar in zip using maven-assembly-plugin and not the Original file i.e. .jar.original
Currently, on providing maven-assembly-plugin as dependency, it packs the jar.original in the zip.
maven-assembly-plugin definition
    <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.3.0</version>
                <configuration>
                    <descriptors>
                        <descriptor>assembly.xml</descriptor>
                    </descriptors>

                    <finalName>${project.artifactId}-${project.version}</finalName>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>

            </plugin>

assembly.xml
<assembly
    xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">

    <id>assembly-id</id>

    <formats>
        <format>zip</format>
    </formats>

    <includeBaseDirectory>false</includeBaseDirectory>

    <fileSets>
        <fileSet>
            <directory>./</directory>
            <outputDirectory></outputDirectory>
            <includes>
                <include>**/*.yml</include>
                <include>**/RestCoordinator-1.0-SNAPSHOT.jar</include>
            </includes>

        </fileSet>
    </fileSets>

</assembly>

Here, RestCoordinator-1.0-SNAPSHOT.jar, is the jar I want in the zip. However, it takes content of RestCoordinator-1.0-SNAPSHOT.jar.original as RestCoordinator-1.0-SNAPSHOT.jar and zips that.
pom.xml* file
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.RELEASE</version>
        <relativePath />
    </parent>
    <groupId>com.hsbc.gmmo.frtb</groupId>
    <artifactId>RestCoordinator</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>RestCoordinator</name>
    <description>Rest API to talk to FDS/Vault system</description>

    <properties>
        <java.version>1.8</java.version>
        <aws.version>1.11.818</aws.version>
        <org.json.version>20200518</org.json.version>
        <swagger.version>3.0.0</swagger.version>
        <lz4.version>1.7.0</lz4.version>
        <opencsv.version>5.0</opencsv.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.tomcat.embed</groupId>
                    <artifactId>tomcat-embed-websocket</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.glassfish</groupId>
                    <artifactId>jakarta.el</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.yaml</groupId>
                    <artifactId>snakeyaml</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-s3</artifactId>
            <version>${aws.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>com.fasterxml.jackson.dataformat</groupId>
                    <artifactId>jackson-dataformat-cbor</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>${org.json.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.vaadin.external.google</groupId>
                    <artifactId>android-json</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.lz4</groupId>
            <artifactId>lz4-java</artifactId>
            <version>${lz4.version}</version>
        </dependency>
        <dependency>
            <groupId>com.opencsv</groupId>
            <artifactId>opencsv</artifactId>
            <version>${opencsv.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.retry</groupId>
            <artifactId>spring-retry</artifactId>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc7</artifactId>
            <version>126.96.36.199</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.5</version>
        </dependency>

    </dependencies>

    <build>

        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <excludes>

                </excludes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.sonatype.plugins</groupId>
                <artifactId>nexus-staging-maven-plugin</artifactId>
                <version>1.6.3</version>
                <extensions>true</extensions>
                <configuration>
                    <serverId>dsnexus</serverId>
                    <nexusUrl>https://dsnexus.uk.hibm.hsbc:8081/nexus</nexusUrl>

                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.3.0</version>
                <configuration>
                    <descriptors>
                        <descriptor>assembly.xml</descriptor>
                    </descriptors>

                    <finalName>${project.artifactId}-${project.version}</finalName>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>

            </plugin>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>sonar-maven-plugin</artifactId>
                <version>188.8.131.526</version>
            </plugin>
            <plugin>
                <groupId>org.sonarsource.scanner.maven</groupId>
                <artifactId>sonar-maven-plugin</artifactId>
                <version>22.214.171.1245</version>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludeDevtools>true</excludeDevtools>

                </configuration>
            </plugin>
        </plugins>
    </build>

    <distributionManagement>
        <repository>
            <uniqueVersion>false</uniqueVersion>
            <id>dsnexus</id>
            <url>https://dsnexus.uk.hibm.hsbc:8081/nexus/content/repositories/releases
            </url>
        </repository>
        <snapshotRepository>
            <id>dsnexus-snapshots</id>
            <url>https://dsnexus.uk.hibm.hsbc:8081/nexus/content/repositories/snapshots
            </url>
        </snapshotRepository>

    </distributionManagement>

</project>

Comment: What kind of application are you trying to package? Where is the `RestCoordinator` coming from?
Comment: SpringBoot application , it is the name of my project.

Also in POM,
Comment: Also in POM,com.hsbc.gmmo.frtb
RestCoordinator
1.0-SNAPSHOT
RestCoordinator
Comment: I'd guess that the assembly plugin simply runs *before* the `spring-boot-maven-plugin`. From what you provided it's not possible to tell certainly however.
Comment: Please show the full pom where the maven-assembly-plugin is defined ...
Comment: @slauth From the console log, it shows that order as -> maven-compiler-plugin --> maven-assembly-plugin --> maven-spring-boot-plugin

In the target folder, two artefacts are created :
1. RestCoordinator-1.0-SNAPSHOT.jar.original (1.5mb)
2. RestCoordinator-1.0-SNAPSHOT.jar (42mb executable jar file)

Maven assembly zips taking contents of the jar.original file and not the executable jar file.
Comment: @khmarbaise added pom code above
Comment: So based on that I simply don't understand why you need maven-assembly-plugin. A spring boot needs to be packed by spring-boot-maven-plugin (boot etc.) Apart from that move the maven-assembly-plugin after the spring boot maven plugin in the pom file... because while two plugins are bound to the same life cycle phase there order of execution is given by the order in the pom file...
Comment: Got it, this scenario worked. Thanks!
Answer: The spring-boot-maven-plugin is running after the maven-assembly-plugin. So at the time the assembly is created, there simply is no executable JAR file available yet. To fix the execution order just move the definition of the maven-assembly-plugin below the spring-boot-maven-plugin in your POM.


Question on computing direct limits

Question: Lately, I've been working on direct limits. In particular, given
$$\mathbb{Z}^n \xrightarrow{M} \mathbb{Z}^n \xrightarrow{M} \mathbb{Z}^n \xrightarrow{M} \cdots$$
where $M$ is an $n \times n$ matrix over $\mathbb{Z}$, then
(1) if the eigenvalues of $M$ are integers, the direct limit is isomorphic to the sum of $\mathbb{Z}[\frac{1}{e_i}]$'s, where $e_i$ is the $i$th eigenvalue. If $0$ is an eigenvalue, then just reduce the degree $n$ by the number of $0$ eigenvalues.
Is there a good reference to draw this conclusion from? Any book or online articles would be of great help!
(2) on the event that the eigenvalues are irrational, then the determinant is considered. For instance, the direct limit becomes $\mathbb{Z}[\frac{1}{d}]^n$, where $d$ is the determinant.
I am struggling a bit on this, and any help would be appreciated. Thanks!
Answer: Let $M$ be an $R$-module and $A\in R$ not a zero divisor. Suppose we wish to compute the direct limit of the system $M\to M\to M\to\cdots$ given by repeated application of $A$. There is a nice trick that can be used to reinterpret this system as taking place entirely within the "localization" $(A)^{-1}M$:
$$\large\begin{array}{cccccccc} M & \xrightarrow{~A~} & M & \xrightarrow{~A~} & M &  \xrightarrow{~A~} & M & \xrightarrow{~A~} & \cdots \\[4pt] \uparrow & & \uparrow & & \uparrow & & \uparrow \\[4pt] M & \hookrightarrow & A^{-1}M & \hookrightarrow & A^{-2}M & \hookrightarrow & A^{-3}M & \hookrightarrow & \cdots  \end{array} $$
The up arrows represent multiplication by $A$. Check that all squares in the diagram commute. Thus the upper and lower direct systems are equivalent and their direct limits are equal.
By $(A)$ here I mean the set of all powers of $A$. Another way to think about it as the "extension of scalars" given by the tensor product $(A)^{-1}M\cong (A)^{-1}R\otimes_RM$. Note $(A)^{-1}R$ (as a ring) is the same as $R[A^{-1}]$. The direct limit, then, is $\bigcup A^{-n}M=R[A^{-1}]M=(A)^{-1}M$. An easier example (than integer matrices) is the integers by itself, two examples are covered in this question.
The rest of the exercise I assume wants Smith normal form to be used. Not sure about the ${\Bbb Z}[d^{-1}]$.
Comment: @Eric: The tensor product is only a way to formalize the intuition going on (behind extension of scalars). For your purposes, you can view ${\bf Z}^n$ as sitting inside ${\bf Q}^n$, and $E={\rm End}({\bf Z}^n)$ as sitting inside ${\rm End}({\bf Q}^n)$. Then the direct limit of ${\bf Z}^n\to{\bf Z}^n\to\cdots$ under multiplication by a matrix $A\in E$ (which is invertible in ${\rm End}({\bf Q}^n)$ but not necessarily in $E$) is isomorphic to $E[A^{-1}]{\bf Z}^n\subseteq{\bf Q}^n$; to explicitly characterize this submodule it may help to recoordinatize ${\bf Z}^n$ so that eigenvalues kick in.
Comment: @Eric One can of course consider a more general matrix $A$. The only reason I do not in this answer is because this trick only works directly if the element $A\in R$ has an inverse in some bigger ring (which requires it to not be a zero divisor in $R$). Some kind of coordinate change could probably handle when the more general situation, but I haven't thought about it deeply enough.
Comment: Thank you for this. To be honest, I am not so comfortable with tensor products, and so I will need time to understand every detail of your response. I appreciate it. Thanks!
Comment: Thanks pal! Just a clarification. If $A$ is not a zero divisor, does it imply that $A$ doesn't have any zero eigenvalues? I am just thinking on the premise that $R = \mathbb{Z}$ and $M$ is an $n\times n$ matrix over $\mathbb{Z}$.
Comment: @Eric A nonzero matrix $A$ is a zero divisor iff it has a zero eigenvalue, so yes. (You are actually thinking about $M=\Bbb Z^n$ as a module over $R=M_n(\Bbb Z)$ with the element $A\in R$ an integer matrix.)
Comment: Alright, last clarification. I already understand your explanation above. However, what's a possible explanation to simply consider a non-zero divisor $A$ rather than a more general matrix, say $A'$, where $A$ and $A'$ have the same set of non-zero eigenvalues?

I mean, computationally, the direct limit of the system $(\mathbb{Z}^n, A)$ is isomorphic to $(\mathbb{Z}^n, A')$, but is there a general way to reduce $A'$ to $A$?

Again, I cannot express how grateful I am for your help!
Answer: Let more generally $F$ be a finitely generated free module over a PID $A$ and $M : F \to F$ be an endomorphism. Then the smith normal form tells us that there is a basis of $F$ such that $M$ becomes diagonal, say $M = \mathrm{diag}(d_1,\dotsc,d_n)$ with $d_1 | \dotsc | d_n$ in $A \setminus \{0\}$. In other words, $M$ is isomorphic to the direct sum of the the endomorphisms $d_i : A \to A$. The colimit of $A \xrightarrow{d_i} A \xrightarrow{d_i} \dotsc$ is isomorphic to the localization $A_{d_i}$. Hence, the colimit of $F \xrightarrow{M} F \xrightarrow{M} $ is isomorphic to $\oplus_i A_{d_i}$.
Edit. This is not correct, since the smith normal form uses row and column operations, which means that we have to choose two bases which are different a priori. The isomorphisms above only hold when these bases are equal.

Question on computing direct limits


The barcode scanner goes stuck at the first time usage in ios,and while in the second click it works fine

Question: hi I am using phonegap barcodeplugin wildabeast/BarcodeScanner for scanning the barcodes.
Here is my code
$('#scanbtn').on( "tap", function(evt){

                    scanner = null;

                    if(ival == 0){
                        ival = 1;
                        scanaction();

                    }

            });

            function scanaction(){
                cordova.plugins.barcodeScanner.scan( function (result) {

                        scanText = result.text;
                        scanFormat = result.format;
                        scanCancelled = result.cancelled;

                    /* alert("We got a barcode\n" +
                                "Result: " + scanText + "\n" +
                                "Format: " + scanFormat + "\n" +
                                "Cancelled: " + scanCancelled); */

                                $.mobile.changePage('#pageTwo',{transition: "slide"});

                    }, function (error) {
                        ival = 0;
                        console.log("Scanning failed: ", error);

                    });
            }

And the log I'm getting on this occasion is
    2014-05-23 10:41:26.629 ShareQ[283:60b] WARNING: -[<AVCaptureVideoPreviewLayer: 0x155ba090> isOrientationSupported] is deprecated.  Please use AVCaptureConnection's -isVideoOrientationSupported
    2014-05-23 10:41:26.735 ShareQ[283:60b] WARNING: -[<AVCaptureVideoPreviewLayer: 0x155ba090> setOrientation:] is deprecated.  Please use AVCaptureConnection's -setVideoOrientation:
    2014-05-23 10:41:27.300 ShareQ[283:60b] WARNING: -[<AVCaptureVideoPreviewLayer: 0x155ba090> setOrientation:] is deprecated.  Please use AVCaptureConnection's -setVideoOrientation:
    2014-05-23 10:41:27.310 ShareQ[283:60b] Warning: Attempt to present <CDVbcsViewController: 0x155392f0> on <MainViewController: 0x1559e3c0> while a presentation is in progress!
    2014-05-23 10:41:27.321 ShareQ[283:60b] Warning: Attempt to present <CDVbcsViewController: 0x1553bb20> on <MainViewController: 0x1559e3c0> while a presentation is in progress!
    2014-05-23 10:41:27.324 ShareQ[283:60b] Warning: Attempt to present <CDVbcsViewController: 0x1553d2b0> on <MainViewController: 0x1559e3c0> while a presentation is in progress!
    2014-05-23 10:41:27.326 ShareQ[283:60b] Warning: Attempt to present <CDVbcsViewController: 0x155418b0> on <MainViewController: 0x1559e3c0> while a presentation is in progress!
    2014-05-23 10:41:27.328 ShareQ[283:60b] Warning: Attempt to present <CDVbcsViewController: 0x155456f0> on <MainViewController: 0x1559e3c0> while a presentation is in progress!
    2014-05-23 10:41:27.331 ShareQ[283:60b] Warning: Attempt to present <CDVbcsViewController: 0x155fa710> on <MainViewController: 0x1559e3c0> while a presentation is in progress!

Comment: please use this plugin on device ready
Comment: @Amit Prajapati  thanks for your edit. Do you know how to solve my issue?
Comment: which phonegap version you are working ? and which ios device you have tested this.
Comment: I have used phonegap 3.4.0 and tested on ios4(iphone) and ios7(ipad)
Comment: Plugin is used in deviceready but the issue persists
Comment: Issue solved by changing the "tap" method
Comment: issue is not tap, its is off event, your click event
Comment: Yes,The event fires multiple times, I've changed the method as follows, Now it works fine
Answer: The problem is due to the jquerymobile framework.
The "tap" function in the jquerymobile fires multiple times on a single click was the reason for the issue I've mensioned. It is rectified by changing the jquerymobile's "tap" method as follows
    $(document).off('tap', '#scanbtn')
                          .on('tap', '#scanbtn',function(e) {
                                   if(ival == 0){
                                          ival = 1;
                                          scanaction();

                                    }

                             });

Now my issue is solved. The scanner works fine.
Comment: yes, magically, I found that rebuilding the Cordova app using Cordova 3.5.0 did the trick and the barcode scanner now works. Since Cordova changed and the scanner code did not I would have to believe I have been Wrestling the problem at the wrong end. Sure makes me wary of updating Cordova again on the next small rev.
Comment: Anand, may I ask you to post the link to the specific wildabeast/BarcodeScanner plugin you are using. The one I was using fails in Phonegap 3.4.0.
Comment: @Ric sorry for the delay the url is [https://github.com/wildabeast/BarcodeScanner]
Comment: @Ric Ohh, it sounds great,glad to hear that your issue is solved.


After declaring an array of translations including Hebrew characters, str_replace() does not replace substrings as expected

Question: I have an array with Hebrew words that I need to find in a string and replace. The translation array is defined as key-value pairs.
In English, this works.
   function replace_twophrase_words($string) {

    $string = strtolower($string);

    $replacements = array (
        'movers'                =>  'Moving Services',
        'home-moving'           =>  'Home Moving',
        'commercial-moving'     =>  'office-moving',
    );

    $string = str_replace($replacements, array_keys($replacements), $string);
}

Hebrew array (asked in comments):
$replacements = array (
    'עיצוב-פנים'            =>  'עיצוב פנים',
    'עיצוב-פנים'            =>  'מעצבת פנים',
    'עיצוב-פנים'            =>  'עיצוב משרדים',
);

But... it seems that this doesn't work in Hebrew at all.
Can anyone explain what's gone wrong?
Comment: This is PHP code? (you should tag the language)
Comment: You should post a separate code block showing the code with the Hebrew words. Might help people help you.
Comment: done & done.. thanks for the comments. tagged the lang & added Heb Array for example.
Comment: It seemed to work for me. Of course all the `$replacement` values are the same so I changed them to be unique, but when I used Hebrew keys it pulled correct value.
Comment: no way ;) to my regret, currently this doesnt work. did you try to echo the result? here is some text you can test on "אני מעצב פנים מנוסה אשר מספק שירותי עיצוב פנים מקצועיים במחירים נדירים" ... this verb "עיצוב פנים" should turn to this "עיצוב-פנים" in the output.
Comment: i would ofcourse love to be wrong - but can you share an example of your code? i tested and tested many times.
Answer: You need to use mb_ereg_replace:
setlocale( LC_CTYPE, 'en_US.UTF-8' );
header( 'Content-Type: text/plain; charset=utf-8' );
echo mb_ereg_replace( 'עיצוב-פנים', 'עיצוב פנים', 'Hebrew string is here: עיצוב-פנים ; and back to Latin.' );

This is because Hebrew letters are composed of multiple bytes and str_reaplce and preg_replace (by default) do not understand these.
Comment: The function only takes strings, so you will need to loop your list of replacements through with: foreach.
Comment: going to give it a try... brb
Comment: having internet issuses here (anwering fron phone ;) ) as soon as i can check it.
Comment: This answer's snippet makes no replacements because the `find` value is never found in the haystack string.
Answer: The thing that has tripped you up is not the behavior of native PHP functions, but in the way that you've defined your lookup array containing Right-To-Left characters.
Your array is declared as:
$replacements = array (
    'עיצוב-פנים'  =>  'עיצוב פנים',
    'עיצוב-פנים'  =>  'מעצבת פנים',
    'עיצוב-פנים'  =>  'עיצוב משרדים',
);

Notice that with the RTL strings, the direction of the => is also affected. If you print it out with var_export(), you get:
array (
  'עיצוב-פנים' => 'עיצוב משרדים',
)

You see the three identical values on the right side of each line are actually the keys and PHP does not let you have duplicate keys on a single level of an array.  So your data not only collapses, it doesn't work as intended for the replacement task.

To correct your data, reverse the position of your intended keys and values. [value <= key, ...]
$replacements = array(
    'עיצוב פנים' => 'עיצוב-פנים',
    'מעצבת פנים' => 'עיצוב-פנים',
    'עיצוב משרדים' => 'עיצוב-פנים',
);

Then echo strtr($input, $replacements); will work exactly as desired.
str_replace() will also work but you'll need to isolate the keys as an array of values and pass the find and replacement parameters separately.  Because all of your replacements are the same, if you are going to use str_replace(), you could just write the single string value as the 2nd parameter.
Here is a demo of everything discussed above. https://3v4l.org/pms5Z


Como ler adequadamente essa entrada para criação de um grafo em C?

Question: Preciso fazer um trabalho na linguagem C onde a entrada é a quantidade de vértices de um grafo na primeira linha e para cada vértice é listado os nós adjacentes de cada vértice em cada linha, separando cada vértice Adjacente por ";". E a última linha especifica o tipo de representação dos grafos desejado pelo usuário, que pode ser:
1: coleção de listas de adjacências ou
2: matriz de adjacências.
Exemplos:
8
a: b;
b: c; e; f;
c: d; g;
d: c; h;
e: a; f;
f: g;
g: f; h;
h: h;
2
ou
9
undershorts: pants; shoes;
pants: belt; shoes;
belt: jacket;
shirt: belt; tie;
tie: jacket;
jacket:
socks: shoes;
shoes:
watch:
1
Eu já tenho funções para adicionar vértices e arestas ao meu grafo, mas estou com dificuldade para ler essa entrada e armazenar o conteúdo dela em variáveis que eu possa usar nas funções, minhas principais dificuldades são:
1-Como separar o que é um novo vértice do que é uma nova aresta. Imagino que eu precise comparar o último caractere da string com ':' ou ';', mas como eu identifico esse último caractere se as entradas possuem tamanhos diferentes?
2-Como fazer um laço que leia todos esses vértices e arestas, mas pare antes da última linha que indica o tipo de representação do grafo ou então sirva também para tratar essa linha?
Comment: 1 - Leia de byte em byte. cria um buffer, e vai escrevendo nele até achar um `:` ou `;` e então ja tem a resposta pra tudo aquilo que está no buffer. 2 - A primeira vez que ler é o quantidade de linhas seguintes que irá ler, dpoeis de ler toda as linhas (Que você ja sabe a quantidade, foi informado antes), só voltar a ler o numero (e que ao ler, volta a ler as linhas, como no mencionei antes).
Answer:
Como separar o que é um novo vértice do que é uma nova aresta. Imagino que eu precise comparar o último caractere da string com ':' ou ';', mas como eu identifico esse último caractere se as entradas possuem tamanhos diferentes?

A julgar pelos arquivos que mostrou o vértice é o primeiro campo de cada linha e as arestas vem a seguir. Sabe que terminou a lista de arestas quando a linha acaba

Como fazer um laço que leia todos esses vértices e arestas, mas pare antes da última linha que indica o tipo de representação do grafo ou então sirva também para tratar essa linha?

A primeira linha do arquivo não diz exatamente isso? São 2+n linhas onde a primeira linha diz o valor de n. Seu primeiro exemplo tem 10 linhas para 8 vértices. O segundo tem 11 linhas...
Exemplos em C
Duas maneiras comuns de fazer isso em C:

usar scanf() que foi escrita para consumir esse tipo de dado
usar uma maquina de estados e ler letra a letra.

[1] usando scanf()
As arestas vem linha a linha, e os delimitadores podem ser : ou ; ou um '\n' então para scanf() se pode usar
    char mascara[] = "%[^\n;:]%c";

como especificadores para consumir os dados: o primeiro especificador %[^\n;:] consome o campo e o segundo consome o caracter que encerrou o campo. Nada mais. Lembrando que o ^ na primeira posição inverte a condição, de modo a aceitar tudo exceto os 3 símbolos que vem a seguir.
2 problemas:

seria mais simples garantir que as linhas não terminem por ; e apenas com '\n' para não ter que tratar os dois casos
espaços em branco no arquivo são um inferno e vão parar dentro das strings

Deixei as duas opções nos arquivos para testar, como pode ver acima.
[1] o exemplo usando scanf()
main.c
#include <stdio.h>
#include <string.h>

void trim(char*);

int  main(int argc, char** argv)
{
    const char* tipo[] = {
        "matriz de adjacencia", "listas de adjacencia"};
    char mascara[] = "%[^\n;:]%c";
    char campo[4096], delim[4];
    int  n = 0;
    int campos = 0;
    delim[0]           = 'x';
    const char* padrao = "f2.txt";
    char arquivo[132];
    strcpy(arquivo, padrao);
    if (argc > 1) strcpy(arquivo, argv[1]);
    FILE* ent = fopen(padrao, "r");
    char* p = fgets(campo, sizeof(campo), ent);
    if (p == NULL)
    {
        fclose(ent);
        return - 1;
    }
    int n_vert = atoi(campo);
    if (n_vert <= 0)
    {
        fclose(ent);
        return -2;
    }
    printf("%d Vertices\n\nArestas:\n", n_vert);
    while (n_vert>0)
    {
        n = fscanf(ent,mascara,campo,delim);
        if (n < 1)
        {
            fgetc(ent);
            --n_vert;
            continue;
        }
        trim(campo);
        switch (delim[0])
        {
            case '\n':
                // terminou uma linha
                printf("  [%s]", campo);
                --n_vert;
                break;
            case ':':
                // novo label
                printf("\n\t[%s]:  ", campo);
                break;
            case ';':
                // nova aresta
                printf("\t[%s]", campo);
                break;
            default:
                // algo errado
                printf(
                    "\nErro! Delimitador = %d\n", delim[0]);
                break;
        };  // switch()
        campos += 1;
    };
    p = fgets(campo, sizeof(campo), ent);
    if (p == NULL)
    {
        fclose(ent);
        return -3;
    }
    n_vert = atoi(campo);
    if (n_vert <= 0)
    {
        fclose(ent);
        return -4;
    }
    printf("\n\nRepresentacao: %s\n", tipo[n_vert!=2]);
    fclose(ent);
    return 0;
};

void trim(char* str)
{   // elimina os espacos de str
    size_t n = strlen(str);
    size_t br = 0;
    char*  pin = str;
    char*  pout = str;
    while (*pin != 0)
    {   if (*pin == ' ') br++;
        else
        {   if (pin != pout) *pout = *pin;
            ++pout;
        }
        ++pin;
    };
    *(str + n - br) = 0;
    return;
};

[2] exemplo usando uma máquina de estados
Aqui não precisa de trim() porque a própria máquina pode eliminar os espaços. A lógica é a mesma e os estados são auto-explicativos: procura os vértices, depois as arestas até terminar
o código do segundo exemplo
// os estados da maquina
#define ARE_ 3
#define ERR_ 2
#define PRE_ 1
// o fim de linha
#define EOL '\n'

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv)
{
    char        st_    = PRE_; // o esado
    const char* tipo[] = {
        "matriz de adjacencia", "listas de adjacencia"};
    char        campo[512];
    const char* padrao = "f2.txt";
    char        arquivo[132];
    // trata o parametro nome do arquivo
    strcpy(arquivo, padrao);
    if (argc > 1) strcpy(arquivo, argv[1]);
    FILE* ent = fopen(arquivo, "r");
    char* p   = fgets(campo, sizeof(campo), ent);
    if (p == NULL)
    {
        fclose(ent);
        return -1;
    }
    // identifica o n. de vertices
    int n_vert = atoi(campo);
    if (n_vert <= 0)
    {
        fclose(ent);
        return -2;
    }
    printf("%d Vertices\n\nArestas:\n", n_vert);
    // tenta ler os vertices e arestas
    int c = fgetc(ent);
    if (feof(ent))
    {
        fclose(ent);
        return -3;  // arquivo vazio
    }
    while (n_vert > 0)
    {
        switch (st_)
        {
            case ARE_: // lendo arestas
                switch (c)
                {
                    case ':':
                        st_ = ERR_;
                        break;
                    case ' ':
                    case '\t':
                        break;
                    case ';':
                        *p = 0;  // termina string
                        // nova aresta
                        printf("\t[%s]", campo);
                        p = campo;  // reinicia
                        break;
                    case EOL:    // fim da linha
                        *p = 0;  // termina string
                        if (p[0] != 0)
                            printf("\t[%s]\n", campo);
                        p   = campo;  // reinicia
                        st_ = PRE_;
                        n_vert -= 1; // achou mais um
                        break;

                    default:
                        *p++ = (char)c;
                        break;
                }
                break;

            case PRE_:
                switch (c)
                {
                    case ':':
                        *p = 0;  // termina string
                        // novo label
                        printf("\n\t[%s]:  ", campo);
                        st_ = ARE_;   // busca arestas
                        p   = campo;  // reset
                        break;
                    case ' ':
                    case '\t':
                        break;
                    case ';':
                        st_ = ERR_;
                        break;
                    default:
                        *p++ = (char)c;
                        break;
                }
                break;
            case ERR_:
                fprintf(
                    stderr, "\n\tErro no arquivo %s\n",
                    arquivo);
                fclose(ent);
                return -4;
                break;
            default:
                break;
        };  // switch()
        c = fgetc(ent);
        if ((feof(ent)) && (n_vert != 0))
        {
            fprintf(
                stderr, "\n\tErro no arquivo %s\n",
                arquivo);
            fclose(ent);
            return -4;
        }
    };  // while()
    // sai do loop com o criterio lido
    // 1 = listas de adjacencia
    printf("\n\nRepresentacao: %s\n", tipo[(c=='1')]);
    fclose(ent);
    return 0;
};

A saída dos dois programas é, claro, a mesma
Os programas esperam o nome do arquivo como parâmetro. Na falta deles um valor padrão é assumido.
Considere os arquivos
f1.txt
8
a:b;
b:  c ;e ;f
c:d;g;
d:c;h
e:a;f;
f:g
g:f;h;
h:h
2

f2.txt
9
undershorts: pants; shoes;
pants: belt; shoes;
belt: jacket;
shirt: belt; tie;
tie: jacket;
jacket:
socks: shoes;
shoes:
watch:
1

saída dos 2 programas

PS C:\so> .\teste f1.txt
8 Vertices

Arestas:

        [a]:    [b]
        [b]:    [c]     [e]  [f]
        [c]:    [d]     [g]
        [d]:    [c]  [h]
        [e]:    [a]     [f]
        [f]:    [g]
        [g]:    [f]     [h]
        [h]:    [h]

Representacao: matriz de adjacencia

PS C:\so> .\teste f2.txt
9 Vertices

Arestas:

        [undershorts]:          [pants] [shoes]
        [pants]:        [belt]  [shoes]
        [belt]:         [jacket]
        [shirt]:        [belt]  [tie]
        [tie]:          [jacket]
        [jacket]:
        [socks]:        [shoes]
        [shoes]:
        [watch]:

Representacao: listas de adjacencia

e deve servir como exemplo para casos como esse. A função trim() existe para remover eventuais espaços DENTRO dos campos no arquivo, como é o caso do exemplo que o autor postou. Sem isso as arestas poderiam ter nomes diferentes a cada vez, em existindo espaços no arquivo de entrada. Um inferno. O exemplo aceita campos terminados por ; ou por '\n'.
usando isso em um programa
Ao invés de mostrar os vértices e arestas como o exemplo apenas insira os valores na lista de vértices e as arestas na matriz ou nas listas conforme o caso. É claro que seria mais esperto se a opção que define como vai armazenar as arestas viesse antes da leitura... Do modo como está vai precisar de algo intermediário.
Comment: Ah o SO pt... Então uma resposta que discute o problema, mostra como tratar os dados e tem  exemplos em C com a saída anexada é então inútil... E aquela recomendação do próprio SO para que se comente **como uma resposta inútil como a que escrevi se torne razoável ao menos**, no nível que o site merece?
Comment: Obrigada pela resposta, não foi inútil e me ajudou a resolver meu problema, infelizmente entrei aqui recentemente e não tenho reputação o suficiente para dar upvote
Comment: :) bom que ajudou em algo. Comentei apenas porque em geral assim que eu escrevo algo vem 1 ou 2 desses votos e comecei a comentar ao final. É algo pessoal, não deve ter a ver com as respostas em si. E agora eu copio esse comentário de uma questão para outra
Comment: Então 2 usuários acharam inútil o que eu escrevi, apesar do autor da pergunta  dizer que tal resposta foi útil e de ter 2 exemplos completos e uma discussão do problema. Preciso melhorar ;) as respostas


How to embed my webiste Header(logo, menu) for each of my panel variant

Question: I'am using Panel and I created several variant for many content type.
Is there a way to add my Top WebSite Header composed with (Logo, Main Menu, Second Menu, Search textbox, Language switcher and social network Icon) for each of my variant in a desired region.
Here is what I would like to do.
Create a kind of template called MyHeader where I would put any html element that I need for my Website Header(Logo, menu etc...).
If it's possible to create a template for MyHeader, how to do that ?
Use MyHeader into each variant panel, I would like to drag it into a specific Region , like dragging a simple widget.
Is it possible to do this.?
Note: I'm using Omega 4 as base theme for my subtheme
Sory for my english.
Thanks a lot.
Answer: Create a block with the required Header and then assign that to your content regions in panels. I think that should be it.
And yes, you can theme your block as required using block--block--[block-id].tpl.php templates.


can i use chi square for two ordinal variables

Question: I have two variables in my research survey, Variable 1(less than 6 hours,6-8 hours, more than 8 hours) and variable 2(not at all, several days, more than half the days, nearly everyday). I want to know if there's an association between them or not. Can I use chi square for these variables or should I use some other statistical test?
Comment: Why are these data categorized ? That's usually a very bad idea.
Comment: Consider variable 1. You will treat a subject completely differently when they record 5:59:59, to another subject that recorded 6:00:00 even though they are essentially the same. Moreover, these 2 subjects will be treated the same as two that had 0:00:00, and the other 7:59:59, which are obviously very very different. This is one of the problems of categorizing a numeric variable. It's very bad.
Comment: Yes, you should record the actual number of hours slept, not a category
Comment: I am actually new to research and while designing the questionnaire I thought it was a good idea to have categorical variables rather than continuous variables but I am having a lot of problems during analysis.
Comment: Thank you so much for clarifying this sir. I just have one confusion and I would be really grateful if you could answer that too. Variable 1 was about sleeping hours and the reason I used categories was because I wanted to know how many hours they slept on average daily. Should I still have made it a continuous variable?
Comment: See also: [stats.stackexchange.com/questions/606118/can-i-use-kruskal-wallis-test-for-dependent-and-fixed-ordinal-variables/606147](https://stats.stackexchange.com/questions/606118/can-i-use-kruskal-wallis-test-for-dependent-and-fixed-ordinal-variables/606147)
Answer: First make sure that the crudely categorized versions of those two measurements are all that were collected.   Then don't use a method such as Pearson's $\chi^2$ that ignores the ordinal nature of the variables.  Consider a rank correlation method such as Goodman-Kruskal $\gamma$ or one of the Kendall $\tau$s.  Be sure to quantify the degree of association and to downplay statistical "significance" which actually means quite little.  Also consider computing a confidence interval for the rank correlation measure to show sample size limitations.
Comment: Thank you sir. Since I am treating my variables asymmetrically should I use a somer's D instead of goodman kruskal or kendall tests?
Comment: It all depends which ties you want to ignore


Handle traffic over network bridge

Question: I have 2 network, LAN1 connected with some hosts and the second LAN2 with proprietary Hardware, similar to PLCs. This kind of PLC is connected via Ethernet and is used for home automation (ie Light control, Shades positioning etc..) and all works fine.
<code>                __________               __________
[HOST1] -------|          |             |          |---[PLC1]
               |  SWITCH  |             |  SWITCH  |
[HOST2] -------|   LAN1   |             |   LAN2   |---[PLC2]
               |__________|             |__________|
</code>
Some hosts of LAN1 need to communicate with PLC to be able to send commands and to administer their web interface.
So I have connected the two LAN, connecting SWITCH1 with SWITCH2:
<code>                __________               __________
[HOST1] -------|          |             |          |---[PLC1]
               |  SWITCH  |             |  SWITCH  |
[HOST2] -------|   LAN1   |-------------|   LAN2   |---[PLC2]
               |__________|             |__________|
</code>
But when i connect LAN1 to LAN2, PLCs automation actions no longer work correctly. I think is a traffic issue: The PLCs are disturbed by the heavy communication of the LAN1.
I have to connect LAN1 with LAN2 because PLC uses a proprietary protocol that work over broadcast UDP commands on a specific port (ie port 37001). This commands must be also received and sent by some Hosts in LAN1.
Is there a way to filter packets passing through LAN1 and LAN2? For example opening only the specific UDP port and HTTP port (UDP 37001 and TCP 80). Which kind of hardware/software i need to do that?
Thank you
Comment: Are there different address spaces in LAN1 / LAN2?
Comment: currently LAN1 and LAN2 have the same address spaces: 192.168.1.1/24 but there is no problem to change it...
Answer: You should assign two different subnets for the LANs, and then add a router between them that filters traffic according to your requirements.
Filtering cannot be (at least easily) done using only Ethernet level mechanisms.
Comment: @AndreaBoc Routers do not forward broadcasts.  If you need broadcasts, then you must connect the LANs together -- which makes then essentially one LAN.  Switches will only forward traffic to PLC1 (for example) if the traffic is destined for that device, or it is a broadcast. PLC1 will never see traffic between Host 1 and 2, for example.  That may affect your conclusion about too much traffic.
Comment: Thank you. Is required a special router to preserve broadcast on port 37001 between LAN1 and LAN2?

Handle traffic over network bridge


Limits and colimits preservation under adjoint equivalence of categories

Question: If $F\colon\mathcal{A}\to\mathcal{B}$ is left adjoint to $U\colon\mathcal{B}\to\mathcal{A}$, then $U$ preserves limits and $F$ preserves colimits.
Can we say something more if $F$ is left adjoint to $U$ and they form an adjoint equivalence between $\mathcal{A}$ and $\mathcal{B}$?
My question arises from the following statement on Wikipedia:

The functor $H\colon\mathcal{I}\to\mathcal{C}$ has limit (or colimit)
  $\mathcal{I}$ if and only if the functor
  $FH\colon\mathcal{I}\to\mathcal{D}$ has limit (or colimit)
  $F\mathcal{I}$.

where $F\colon\mathcal{C}\to\mathcal{D}$ is an equivalence. Is $F$ preserving both limits and colimits? (in the Wikipedia case, $F$ is not part of an adjoint equivalence, but, according to this question, every equivalence can be upgraded to an adjoint equivalence).
Answer: An adjoint equivalence between categories $\mathcal{A}$ and $\mathcal{B}$ is not a pair $(F,U)$ of functors between them, but a quadruplet $(F,U,\eta,\varepsilon)$, where $\eta$ and $\varepsilon$ are corresponding natural transformations, such that $(F,U,\eta,\varepsilon)$ is an adjunction. Note, that every pair $(F,U)$, where $F$ and $U$ are mutually inverse equivalences of categories, may be completed to such a quadruplet. Therefore, every equivalence of categories is both a left-adjoint and a right-adjoint functor.
Of course, equivalences of categories preserve much more constructions than left-adjoints or right-adjoints. Actually, they preserve "all" categorical information (the things not preserved by equivalences are half-jokingly called "evil"). In particular, equivalences preserve and reflect all limits and colimits (they preserve limits because they are right-adjoints, preserve colimits because they are left-adjoints, reflect limits and colimits because they are fully faithful).
Answer: When $F$ and $U$ form an adjoint equivalence, the unit $\eta:I_{\mathcal{A}}\to UF$ and counit $\epsilon : FU\to I_{\mathcal{B}}$ are isomorphisms; then their inverses $\epsilon^{-1}:I_{\mathcal{B}}\to FU$ and $\eta^{-1}:UF\to I_{\mathcal{A}}$ are natural transformation, and they satisfy the identities
$$F(\eta^{-1})\circ\epsilon^{-1}_F=(\epsilon_F\circ F(\eta))^{-1}=1_F$$
and
$$\eta^{-1}_U\circ U(\epsilon^{-1})=(U(\epsilon)\circ \eta_U)^{-1}=1_U.$$
Thus $U$ is also left adjoint to $F$, so that $U$ preserve colimits and $F$ preserve limits.


Lost modified /etc/hosts file on Amazon EC2 every reboot instance?

Question: I have setup an Ubuntu 8.10 server instance on Amazon EC2. I install ejabberd on server, but I face some problems on ejabberd node can't start because hostname on cloud changes each time we relaunch the instance. After I follow this link http://blog.kenweiner.com/2008/05/ejabberd-on-amazon-ec2-ubuntu-ami.html to edit and add hostname in /etc/hosts file, it works. Unfortunately, every time I reboot the server, the /etc/hosts file get reset to default.
How could I solve this problem?
Comment: I'm running Ubuntu (desktop) 10.10 on my laptop and the problem with the /etc/hosts files persists. It's reseted any time I reboot. Googling for a solution I just found this thread. No luck at this moment. :(
Answer: This is a known problem with the current Ubuntu images for EC2 built by Canonical:
https:// bugs.launchpad.net/ubuntu-on-ec2/+bug/371936
You can wait for the next release from Canonical or run the Ubuntu images for EC2 which I publish on http:// alestic.com (and which do not have the same problem).
I have successfully run ejabberd on the Alestic.com images.
Answer: I know this a super old thread but one the pops up on ggl,
yes it is cloud-init, on my debian ami I added my custom entries in:
/etc/cloud/templates/hosts.debian.tmpl

lets see if that works on next auto-reboot by
aws ec2 create-ami ...

Answer: You could try CloudInit to perform your hosts file cleanup during instance boot. It is included in all the current official Ubuntu EC2 images and allows you to run initialization scripts passed by the --user-data switch of ec2-run-instances (or the respective input field(s) in the AWS Console wizard) which will be run at boot. Kind of like rc.local.
Edit: I did not realize it was Eric himself who wrote the other comment, at first. He's got lots of useful entries in his blog at Alestic, including one regarding the mentioned UserData.


Problema ao tentar pegar valor de um array

Question: Estou tentando trabalhar com um array que recebo por POST, mas não estou conseguindo pegar os valores contido dentro do array.
Quando dou print_r($_POST) obtenho:

Array ( [acesso] => Array ( ['KMEntrada'] => 1000 ['HorarioSaida'] =>
  2017-06-16 14:20:58 ['Status'] => 0 ) )

Já tentei acessar usando $_POST["acesso"]["KMEntrada"] mas obtenho a seguinte mensagem de erro:

Undefined index: KMEntrada
Comment: `echo $var['acesso']['KMEntrada']` isso?
Comment: Agora deu certo... o código de tem ficar assim `echo($_POST['acesso']["'KMEntrada'"]);`
Comment: Eu já tinha tentado assim, mas não funciona.
Comment: Aparece algum erro?
Comment: Undefined index: KMEntrada
Comment: Isso dentro de um for? pelo jeito o array do seu código está diferente do array da pergunta.
Comment: Eu pego esse array do código ` print_r($_POST);`
Comment: Usando o código que tu passou ficou assim `echo($_POST['acesso']['KMEntrada']);`
Answer: Para retornar qualquer valor faça assim
$meuArray = array('acesso' => array('KMEntrada' => 1000, 'HorarioSaida' => '2017-06-16 14:20:58', 'Status' => 0));

echo $meuArray['acesso']['KMEntrada'] ."\n";

echo $meuArray['acesso']['HorarioSaida'] ."\n";

echo $meuArray['acesso']['Status'] ."\n";

exemplo - ideone
Answer: Para recuperar o valor, tive que inserir o seguinte código:
$_POST['acesso']["'FrotaID'"]
Comment: Isso não faz o menor sentido!!!
Comment: Tem como editar a pergunta e adicionar mais detalhes do seu problema? Assim como o Marcelo disse, a sua solução não faz sentido. O rray já havia te indicado a solução correta nos comentários e deu erro. Não ignore o erro. Se com a forma certa deu erro, tem coisa errada no seu código.
Answer: Tenho quase certeza que o seu maior problema esta na querystring, você esta passando ela, muito provavelmente desse modo:

request = function() {
  $.ajax({
    url: "https://requestb.in/1fzmwxx1",
    type: "POST",
    data: {
      "acesso['KMEntrada']": 1000,
      "acesso['HorarioSaida']": '2017-06-16 14:20:58',
      "acesso['Status']": 0
    },
    success: function(returnjson) {},
    error: function(returnjson) {}
  });
}();

Veja no requestb.in como a informação chega:

RAW BODY
acesso%5B'KMEntrada'%5D=1000&acesso%5B'HorarioSaida'%5D=2017-06-16+14%3A20%3A58&acesso%5B'Status'%5D=0

Para enxergar melhor:

RAW BODY URL ENCODED
acesso['KMEntrada']=1000&acesso['HorarioSaida']=2017-06-16 14:20:58&acesso['Status']=0

Quando na verdade bastava passar assim:

RAW BODY
acesso%5BKMEntrada%5D=1000&acesso%5BHorarioSaida%5D=2017-06-16+14%3A20%3A58&acesso%5BStatus%5D=0
RAW BODY URL ENCODED
acesso[KMEntrada]=1000&acesso[HorarioSaida]=2017-06-16 14:20:58&acesso[Status]=0

O que você fez para acessar as variáveis dentro do array $_POST['acesso']["'FrotaID'"] funciona como um remendo, uma gambiarra, e não como uma solução definitiva, não é o recomendável...
Porque não seria recomendável?
Se no backend você, ou algum outro desenvolvedor por acaso tentar converter o $_POST para um objeto, você não conseguira acessar as variáveis dentro da variável acesso, veja um exemplo do que quero dizer:
$_POST["acesso"] = (object) Array( "'KMEntrada'" => 1000, "'HorarioSaida'" => '2017-06-16 14:20:58', "'Status'" => 0, "teste" => 540 );
$teste = (object) $_POST; // casting da variável
echo $teste ->acesso->teste // Imprime 540
echo $teste ->acesso->'KMEntrada' // invalido

Se por acaso você tentar acessar o json usando javascript, também terá um erro de sintaxe:
$arr = array(
    "acesso" => array(
        "'KMEntrada'" => 1000,
        "'HorarioSaida'" => "2017-06-16 14:20:58",
        "'Status'" => 0
    )
);
$v = json_encode($arr);
echo "";

Alem do que, não vejo algum motivo cabível para se passar uma variável com caracteres especiais, caso essa afirmação esteja incorreta, inclusive peço que me retifiquem:

Não existe algum contexto onde é valido definir uma variável em uma
  queryString com caracteres especiais tipo aspas, arroba, cifrão e etc, isso inclusive poderia trazer problemas na hora de recuperar as variáveis passadas no backend.

Basta saber como você esta enviando esse array pro seu backend e fazer a correção la, se for por ajax por exemplo:

request = function() {
  $.ajax({
    url: "https://requestb.in/1fzmwxx1",
    type: "POST",
    data: {
      "acesso[KMEntrada]": 1000,
      "acesso[HorarioSaida]": '2017-06-16 14:20:58',
      "acesso[Status]": 0
    },
    success: function(returnjson) {},
    error: function(returnjson) {}
  });
}();

Veja no requestb.in a informação que chega:

FORM/POST PARAMETERS
acesso[HorarioSaida]: 2017-06-16 14:20:58
acesso[Status]: 0
acesso[KMEntrada]: 1000
RAW BODY
acesso%5BKMEntrada%5D=1000&acesso%5BHorarioSaida%5D=2017-06-16+14%3A20%3A58&acesso%5BStatus%5D=0

Deste modo, ai sim você pode facilmente acessar as variáveis do modo correto, que seria $_POST['acesso']['KMEntrada']


Prove that $b_n={2n-3 \choose n-3}$ for all positive integers n greater or equal to 3

Question:
Let $b_n$ be the number of n-permutations containing exactly one copy of the pattern $132.$
  $$ \;b_n={2n-3 \choose n-3}\quad\forall n \geq 3$$

How do I prove this? Can someone give me a headstart, I have no idea how to start proving this.  Thanks!
Comment: I would think that $b_n = (n-2)!$. You can treat $132$ as a single block, and then permute the remaining $n-2$ blocks in any order.
Comment: @CalvinLin, wish I could read that, deleting the earlier comments
Comment: @TripleMajor I made some latex edits to your question. Can you see if this is what you want?
Comment: Yes, that's correct, thanks!
Comment: Are you referring to patterns in permutations, as described here:http://en.wikipedia.org/wiki/Permutation_pattern
Answer: This is not true.  For $n=4$ there are two, $1324, 4132$.  But $b_4={5 \choose 1}=5$
Comment: What about the permutations $\bf{143}$2, $\bf{243}$1, and 1$\bf{243}$?
Comment: @user84413:  I thought OP wanted to have $132$ in a block.  None of those do.  My solution agrees with Calvin Lin's
Comment: You and Calvin may be right about what the OP wanted, but I believe there are 5 permutations for n=4 with one copy of the pattern 132:  1324, 4132, 2413, 2431, 3142. (If the OP had said sequence instead of pattern, then there would only be 2, as you say.)


Likelihood Ratio and Expected Value Relationship

Question: I am to prove that:
1) The expected value of $(Λ^n|H_1) = E(Λ^{(n+1)}|H_0)$
2) The expected value of $(Λ|H_0) = 1 $
where $Λ$ is the likelihood ratio.  I know that the likelihood ratio is equal to $f(x|H_1)/f(x|H_0)$ but my textbook does not mention any relationships between the likelihood ratio to expected values. I am still fairly new to these statistics topics so any help/hints is appreciated. Thanks in advance!
Comment: Hint for #2: the likelihood ratio $\displaystyle \Lambda(X) = \frac{f_1(X)}{f_0(X)}$ is a _function_ of the random variable $X$. _Conditioned_ on $H_0$ being the true hypothesis, $X$ has density $f_0(X)$. Do you know how to find the _expected value_ of a _function_ $\Lambda(X)$ of $X$ directly _without first determining the density of_ $\Lambda(X)$, that is, just from knowledge of the density function $f_0(x)$?
Comment: $\displaystyle \int_{-\infty}^{\infty} xf(x)\,\mathrm dx$ will give you the expected value of $X$, not of $\Lambda(X)$. What you need to know about finding $E[\Lambda(X)]$ is perhaps the very next equation in your book.
Comment: Yes, you are on the right track. Just remember that when you find $E[\Lambda(X)\mid H_0]$ you need to use $f_0(x)$ as the density for $X$.
Comment: @DilipSarwate Would you use the intergral of x*f(x) dx?
Comment: @DilipSarwate Ok, I think I might be on the right track. Would I use E[Λ(X)] = intergral of Λ(x)f(x) dx? The inner product of Λ and f. Thanks for your time by the way
Comment: So this is easy when H0 is the true hypothesis, but what about when H1 is? Given how the H0 case works out so nicely I thought the answer for H1 should also be easy, but I'm not seeing it.
Answer: Now that any homework deadlines are long past, assuming a continuous random variable $X$ whose densities $f_0(x)$ and $f_1(x)$ enjoy the property that $f_1(x) > 0 \implies f_0(x) > 0$, (that is, the likelihood ratio does not "blow up" at any $x$), we have that
$$E[\Lambda(X)\mid H_0] = \int_{\mathbb R}\frac{f_1(x)}{f_0(x)}\cdot
f_0(x)\, \mathrm dx = \int_{\mathbb R}f_1(x)\, \mathrm dx = 1.$$
$$E[\Lambda^n(X)\mid H_1] = \int_{\mathbb R}\left[\frac{f_1(x)}{f_0(x)}\right]^n\cdot f_1(x)\, \mathrm dx
=  \int_{\mathbb R}\left[\frac{f_1(x)}{f_0(x)}\right]^{n+1}\cdot f_0(x)\, \mathrm dx  = E[\Lambda^{n+1}(X)\mid H_0].$$


Como fazer um um editor de texto em uma textarea no estilo TinyMCE?

Question: Gostaria de saber o que devo estudar exatamente para conseguir transformar uma textarea em um editor de texto WYSIWYG.Logicamente sei que devo usar Javascript,mas não consigo imaginar como os estilos são aplicados em tempo real no conteúdo dentro da textarea. Já pesquisei na internet e as pessoas só davam link de editores prontos. Não quero o link de um pronto. Eu gostaria de saber o caminho mais ou menos para conseguir aplicar o estilo na parte escolhida do conteúdo dentro da textarea. Cheguei a ver pessoas falando para usar iframe, mas não explicaram o que exatamente eu faria com o iframe pra conseguir isso.
Answer: O segredo dos editores WYSIWYG é o atributo contenteditable. Com este atributo é possível que um elemento HTML como
 ou
 se torne um "input", porém mantendo a capacidade de interpretação de HTML.
Para pegar o texto atualmente selecionado e aplicar estilos no mesmo usa-se JavaScript, como você sugeriu. Porém, as APIs suportadas pelos navegadores são bastante variadas, então é necessário fazer vários tratamentos no código para oferecer suporte à vários navegadores. Por exemplo as APIs Window.getSelection() e Selection.
Se você deseja estudar como os editores WYSIWYG funcionam, sugiro analisar o código-fonte dos mesmos, há muito o que ser aprendido ali. Por exemplo, aqui você pode encontrar o código completo do editor jQuery-TE.
Comment: Perfeito!! Exatamente o tipo de resposta que eu precisava. Muito Obrigado!!
Comment: +1 pelo atributo `contenteditable`. Aprendi uma hoje - o que mais me impressionou é que ele aparentemente é suportado há um bom tempo...


Fazer intervalo de datas datepicker ser usada no mysql

Question: No meu código, tenho um calendário onde o usuário seleciona o período que ele deseja analisar. O código é este:
<input type="text" name="daterange" value="01/01/2012 - 20/04/2018" />

Preciso usar esse intervalo para filtrar uma tabela de dados mysql. Já usei a função betweencom duas datas distintas, dessa forma:
SELECT * FROM `producao_hora` where data between '19/04/2018' and '20/04/2018'

Mas não sei como transformar o intervalo de datas do datepicker numa variável que eu pudesse jogar nesse select. Como poderia ser feito?
OBS: Códigos em PHP também são bem-vindos!
Answer: Boa noite Renata,
Como você esta trabalhando com PHP. Você pode simplesmente realizar o submit do formulário. E no script que receber a requisição dividir a string para obter as duas datas. E posteriormente montar sua query.
formulario.html:
<form action="pesquisar.php" method="POST">

            <input type="text" name="daterange" value="01/01/2012 - 20/04/2018" />
            <button type="submit">Filtrar</button>

</form>

pesquisar.php:
<?php
    $datas = explode(' - ', $_POST['daterange']);
    echo $datas[0];
    echo "
";
    echo $datas[1];

Veja que utilizei a função explode para separar as datas do intervalo. Portanto a nova variável terá na primeira posição a data inicial do intervalo e na segunda posição o fim do intervalo.


How to read testbot feedback / get more info

Question: I have created a patch for migrate_spreadsheet, unfortunately it will not pass the testbot. Instead that gives me this (to me cryptic / uninformative) message:

fail: [run-tests.sh check] Line 0 of : FATAL
  Drupal\Tests\migrate_spreadsheet\Unit\SpreadsheetIteratorTest: test
  runner returned a non-zero error code (255).

Where/what is line 0? My first change compared to the original file was on line 7, where I corrected a class name. The only other two changes in that file where in the docs.
So what does this fail mean?
How can I get more info from the testbot?
Answer:
If you click the colored patch result (above), you will get to a detailed page. On the top of that page there is a link 'View results on dispatcher'. That will get you to the test. Then go to the 'Console output' (on the left) (direct link).
The actual error appears to be:

13:56:12 PHP Fatal error:  Class
  'PhpOffice\PhpSpreadsheet\Worksheet\Worksheet' not found in
  /var/www/html/modules/contrib/migrate_spreadsheet/tests/src/Unit/SpreadsheetIteratorTest.php
  on line 187
Comment: Not sure what you mean with *the colored patch result*, I think you mean the 'View results' link? The rest of your answer is very helpful though. Thanks, silly I missed that link :-) So it's view results -> view results on displatcher -> console log and then look for the colored text.
Comment: I was referring to the background of the test. A screenshot is now included :-) Good luck fixing the patch!
Comment: Proper feedback really helps, thanks again for pointing it out to me. The patch is ok now and already committed even. Partly thanks to you! :-)