text:
Q: getElementById() doesn't work when entering by react-router's  I created a simple react app with react-router(v5.) There are footers with current year in every page.
const footerYear = document.getElementById('footerThisYear');
if (footerYear) {
  footerYear.innerHTML = new Date().getFullYear();
}

The problem is the snippet above doesn't work in child pages entering through react-router's <Link>. It works when entering the complete urls.
Preview:
https://stackblitz.com/edit/react-mqjws7?file=index.js
Child page example url:
https://react-mqjws7.stackblitz.io/page/a
Question: How to get this work in every page?
Thank you!

A: If you want to get that to work on every page, you're going to have to put that if statement in the Footer.js file. The easiest way to explain this is that your routes are working like this:
URL -> index.js -> Router -> Page

When entering the page using the direct URL, this is the path it goes through since your Router component is located in index.js. When clicking on the Links on Home.js, since it originates from Home.js which is already in index.js, it's only going through
Router -> Page

As a result of this, the proper footer you want is not showing because the function to display it is located in index.js. To test this, you can place a console.log statement inside your if statement. It will not be called if you're navigating to your pages inside of Home.js.
Change Footer.js to a class and put the if statement in there and it should work correctly. Otherwise, you can also set the footer to conditionally render the year given a prop.


text:
Q: php mail multiple email with same emails It is my code
$headers    = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: no-reply@domain.com\r\n";
$subject    = SITE_TITLE ." Account Upgrade Email!";
$to_email = user@gmail.com,user@gmail.com,user@gmail.com;

mail($to_email, $subject, $message, $headers);

I sending mail to same email id three times....
three different emails will be sent or only one email will be sent....
thanks in advance

A: You can have it comma seprated, see to ref from php docs
mail('user@abc.com,user@xyz.com', $subject, $message, $headers);

A: You can concatenate the email addresses.
This will send the same email to 3 different recipients
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: no-reply@domain.com\r\n";
$subject = SITE_TITLE ." Account Upgrade Email!";
$to_email = 'user1@gmail.com' . ', ';
$to_email .='user2@gmail.com' . ', ';
$to_email .='user3@gmail.com';

mail($to_email, $subject, $message, $headers);

See PHP Documentation on mail function (Example #4)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add Dynamic fields in a form with a plus symbol in Ruby on rails I would like to add fields dynamically in a form using html/css/javascript/jquery and would like it to be stored properly in Rails.

How would I go about it in?
I have tried to check these links: rails form add fields dynamically
but they only show the front-end side.


text:
Q: SQL Query Count across 2 tables Here is what I have (i am including only the relevant cells to each table)
table1:
 - user_id

table2:
 - id
 - manager_id

... and I have a PHP variable
$manager_id

So, what I am trying to do is get a COUNT(*) of how many records exist in table1, but the record should only be counted if table1.user_id (which is the table2.id) has a table2.manager_id == $manager_id
So, the only way I know how to do this would be to do something like this in PHP (which is wildly inefficient):
$query = "SELECT user_id FROM table1 WHERE {my where clause}";
// execute query and place into $item[] array (not shown for brevity)
foreach ( $item as $user_id ) {
$query = "SELECT manager_id FROM table2 WHERE id = '{$user_id}';
// execute query, place each item into $row
if ( $row['manager_id'] == $manager_id ) {
// tick up count by 1
}

I am fairly certain there is a way to do this purely in SQL, but I am at a loss.

A: You could try the below query:
select count(1) from table1 t1, table2 t2 where t1.user_id = t2.id and t2.manager_id = ?

A: You can do this with one SELECT statement:
SELECT COUNT(*)
FROM table1
WHERE user_id IN (
    SELECT id
    FROM table2
    WHERE manager_id = <your-value-of-manager-id>
)

In case you need to use the data and want to count on PHP side you can use the following SELECT statement using a LEFT JOIN:
SELECT table1.*
FROM table1 LEFT JOIN table2 ON table1.user_id = table2.id
WHERE table2.manager_id = <your-value-of-manager-id>

To execute the SELECT statements you should use prepared statements (using PDO or mysqli).
example using the first query:
$sql = 'SELECT COUNT(*) FROM table1 WHERE user_id IN (SELECT id FROM table2 WHERE manager_id = ?)';
$sth = $dbh->prepare($sql);
$sth->execute([$manager_id]);

$rows = $sth->fetchAll();

if (count($rows) === 1) {
    echo $rows[0][0];
}

example using the second query:
$sql = 'SELECT table1.* FROM table1 LEFT JOIN table2 ON table1.user_id = table2.id WHERE table2.manager_id = ?';
$sth = $dbh->prepare($sql);
$sth->execute([$manager_id]);

$rows = $sth->fetchAll();

echo count($rows);

A: you need to set your where clause to have this condition i.e.
SELECT Count(user_id) FROM table1 where
table1.user_id = table2.id
AND Convert('Varchar', table2.manager_id) = $manager_id
I assume your php variable $manager_id has a string
if it is not a number then there is no need to convert the sql column (table2.manager_id) to varchar.


text:
Q: Kusto query to get percentage value of events over time I have a Kusto / KQL query in azure log analytics that aggregates a count of events over time, e.g.:
customEvents
| where name == "EventICareAbout"
| extend channel = customDimensions["ChannelName"]
| summarize events=count() by bin(timestamp, 1m), tostring(channel)

This gives a good results set of a count of the events in each minute bucket.
But the count is fairly meaningless, what I want to know is if that count is different to the average of over the say last hour.
But I'm not even sure how to start constructing something like that.
Any pointers?

A: There are a couple of ways to achieve this, first, calculate the hourly avg as an additional column then calculate the diffs from the hourly average:
let minuteValues = customEvents
| where name == "EventICareAbout"
| extend channel = customDimensions["ChannelName"]
| summarize events=count() by bin(timestamp, 1m), tostring(channel)
| extend Day = startofday(timestamp), hour =hourofday(timestamp);
let hourlyAverage = customEvents
| where name == "EventICareAbout"
| extend channel = customDimensions["ChannelName"]
| summarize events=count() by bin(timestamp, 1m), tostring(channel)
| summarize hourlyAvgEvents = avg(events) by bin(timestamp,1h), tostring(channel)
| extend Day = startofday(timestamp),hour =hourofday(timestamp);
minuteValues
| lookup hourlyAverage on hour, Day
| extend Diff = events- hourlyAvgEvents

Another option is to use the built-in Anomaly detection


text:
Q: Регулярные выражения: только кириллица и тире Делаю валидацию формы Имя Фамилия(поле text). В поле может быть введены только русские буквы, тире и пробел. Текста может быть сколько угодно много
Подскажите, пожалуйста, как написать регулярку? Моя регулярка работает, но когда добавляю \-, чтобы можно было тире ставить - пропускает латиницу
^[a-яА-Я\-]+\s[a-яА-Я\-]+

A: Ваше регулярное выражение
^[a-яА-Я\-]+\s[a-яА-Я\-]+

Экранирование - можно не делать, если тире будет находится сразу после квадратной скобки или в конце.
В диапазоне А-Я не содержится буква Ё, ее нужно указывать отдельно.

<form>
  <input
      id="choose"
      name="i_like"
      required
      pattern="[а-яА-ЯЁё-]+\s[а-яА-ЯЁё-]+"
      title="Кириллица разделенная одиночным пробелом"
  >
  <button>Тык</button>
</form>

[а-яА-ЯЁё-]+\s[а-яА-ЯЁё-]+

^ - начало строки
[а-яА-ЯЁё-]+  - одна и более буква кириллицы в верхнем и нижнем регистре  или знака -
\s - пробельный символ
[а-яА-ЯЁё-]+ - одна и более буква кириллицы в верхнем и нижнем регистре  или знака -

Под данное регулярное выражение будет валидным ввод - -
Поэтому тире так же следует добавить в отдельную группу, что бы после него шли буквенные символы:
[а-яА-ЯЁё]+(-[а-яА-ЯЁё-]+)?\s[а-яА-ЯЁё-]+(-[а-яА-ЯЁё-]+)?

Теперь тире может быть установлено только в середину слова

<form>
  <input
      id="choose"
      name="i_like"
      required
      pattern="[а-яА-ЯЁё]+(-[а-яА-ЯЁё-]+)?\s[а-яА-ЯЁё-]+(-[а-яА-ЯЁё-]+)?"
      title="Кириллица разделенная одиночным пробелом"
  >
  <button>Тык</button>
</form>


text:
Q: Spring Bean implements interface public interface Service {

  public void doSomething();
}

@Service
public class MyService implements service{

      @Transactional
      public void doSomething(){
      }
}

@Controller
public class MyController {

  @Autowired
  private MyService service;
}

In above scenario autowiring fails with exception "illegalArgumentException : argument type mismatch". When I remove implements service from MyService everything works fine.
I have searched and found that place <aop:aspectj-autoproxy proxy-target-class="true"/> in applicationContext.xml for successful autowiring and it worked.
I have also found that spring uses JDK proxy when @Transactional is used.
I have some confusions,

*

*How @Transactional relates to Proxying

*Why spring uses JDK Proxy for the beans which implements interfaces.

*Why I need to place <aop:aspectj-autoproxy proxy-target-class="true"/> in applicationContext.xml

Can anyone please explain ? or refer me any article or blog

A: Proxying is how Spring implements declarative transaction management. Spring reference is the best place for all your questions on this.

The most important concepts to grasp with regard to the Spring Framework's declarative transaction support are that this support is enabled via AOP proxies, and that the transactional advice is driven by metadata (currently XML- or annotation-based). The combination of AOP with transactional metadata yields an AOP proxy that uses a TransactionInterceptor in conjunction with an appropriate PlatformTransactionManager implementation to drive transactions around method invocations.

and on <aop:aspectj-autoproxy proxy-target-class="true"/>

The proxy-target-class attribute on the
  element controls what type of transactional proxies are created for
  classes annotated with the @Transactional annotation. If
  proxy-target-class attribute is set to true, class-based proxies are
  created. If proxy-target-class is false or if the attribute is
  omitted, standard JDK interface-based proxies are created. (See
  Section 8.6, "Proxying mechanisms" for a discussion of the different
  proxy types.)


text:
Q: PostgreSQL: Audio stream storage: bytea vs Large Object My current application needs to store 3~10MB audio inside PostgreSQL.
Supported operations include:

*

*Upload as a whole

*Stream-style random read

It seems that I can either store it as a bytea BLOB or upload it as a large object.
bytea pros:

*

*Simpler

*ORM/dump-friendly

cons:

*

*Must access as a whole or use the tricky substring

*have to configure my ORM to exclude it from auto fetch

Large Object pros:

*

*Native random access API without substring()/thin-provision

cons:

*

*Have to manage OID manually

*Bad modularity: dumping database would output all LOs in it

Which is the best choice?


text:
Q: Javascript timer loads automatically instead of on click event I have a JS time counter on a little game app, it works fine, but instead of beeing activated on first click (I have a firsClick variable set to true that I use on click event to invoke startTimer function ) it start as page loads and I receive error when game finishes or if I reset game with its button.
Any help or suggestion is welcomed, thank you
let liveTimer = 0;
//timer function
function startTimer(val) {
   return val > 9 ? val : "0" + val; }
   setInterval( function(){
   document.getElementById("seconds").innerHTML=startTimer(++liveTimer%60);
   document.getElementById("minutes").innerHTML=startTimer(parseInt(liveTimer/60,10));
}, 1000);
// stopping timer function - clears time stored in liveTimer var
function stopTimer() {
   clearInterval(liveTimer);
}

A: Your function definition ends too early:
function startTimer(val) {
return val > 9 ? val : "0" + val; }
setInterval( function(){
document.getElementById("seconds").innerHTML=startTimer(++liveTimer%60);
document.getElementById("minutes").innerHTML=startTimer(parseInt(liveTimer/60,10));
}, 1000);

What you might have wanted to write:
function startTimer(val) {
    setInterval( function(){
       document.getElementById("seconds").innerHTML=startTimer(++liveTimer%60);
       document.getElementById("minutes").innerHTML=startTimer(parseInt(liveTimer/60,10));
    }, 1000);
    return val > 9 ? val : "0" + val;
}

Although I don't see what you want to do with that "val". It has nothing to do with the interval body or its call at all


text:
Q: How can Reactjs update only part of text in a html dom element? I am learning reactjs and stumbled upon this peculiar detail, see my image below. It is the react demo showing how reactjs only update the parts of the dom which have changed.

function tick() {
  const element = (

Hello, world!

It is {new Date().toLocaleTimeString()}.

  );
  // highlight-next-line
  ReactDOM.render(element, document.getElementById('root'));
}

setInterval(tick, 1000);

Live example: https://codepen.io/pen?&editors=0010
As you can see, when the clock ticks, only the second part of the text gets updated. In my experience, I can update the content of a single html-element, meaning my code would update the entire text of the h2-element. Here it really looks like there are three text elements inside the h2-element. I must be missing some basic knowledge here!
As it looks, it seems to be possible to address/find and update a sub-text as if it is an element of its own, in this case, the "3:05:42 PM" text piece. How do you do this in plain javascript?

A: How React does this specifically is a question for the documentation and the code itself, however we can have a look at how we might do this in plain JS with a simulation such as this one:
let t1 = document.createTextNode("The seconds are: ");
let t2 = document.createTextNode(new Date().getSeconds());
let t3 = document.createTextNode(". Isn't it cool?");

const content = document.getElementById("content");

content.appendChild(t1);
content.appendChild(t2);
content.appendChild(t3);

setInterval(() => {
  let nextT2 = document.createTextNode(new Date().getSeconds());
  content.replaceChild(nextT2, t2);
  t2 = nextT2;
}, 1000);

https://codesandbox.io/s/replace-text-node-h4ivy
The idea here is that we're able to create the text as separate text nodes which we can later replace directly. In the case of React, they could - if they so chose to - create each part of the text as a separate text node. React will already know that the content is in 3 parts (text, code-block, text), so it seems reasonable to conclude that they may choose to append it to the DOM as 3 text nodes.
Our setInterval here is representing the final stages of some process that eventually updates the DOM. If you check in the dev tools you'll probably see only the numbers updating, similar to how you see it updating in React.


text:
Q: Read complex text file using Vb.net File Structure
RECORD
1234567890,123456789,1234567,Address1,,City,State,Zip,USA,Phone,,,,,,,,,
EmpName,DBAName,ID,,Address1,,Address1,City,60603,USA,234567890,,,,
C,03/13/2017,,1,2,
RECORD
1234567890,123456789,1234567,Address1,,City,State,Zip,USA,Phone,,,,,,,,,
EmpName2,DBAName2,ID2,,Address2,,Address2,City2,60603,USA,234567890,,,,
C,03/13/2017,,1,2,

Looking at the above file structure, I want to loop through file and for each record(RECORD), I want to put next three lines in one array and then next record in separate array.
I am looking for skeleton code, I am very new in programming using stream readers.
Code so far
 Dim read As New System.IO.StreamReader("C:\New Text.txt")
       Dim a As String

       For Each a In read.ReadLine
           If read.ReadLine.Equals("RECORD") Then
               \\How do I read next 3 lines and put them in one array with comma delimiter
           End If
       Next

A: You need a data structure where you will keep the lines loaded and then start your loop
' Here you will keep the 3 lines block joined together and splitted on comma
Dim records = new List(Of String())()

Using read As New System.IO.StreamReader("C:\New Text.txt")
   Dim a As String

   ' Read each line (Assuming that we start with a RECORD line
   For Each a In read.ReadLine
       ' Do not read another line, but just test what is present in the string
       If a.Equals("RECORD") Then

          ' Now read the 3 following lines....
          Dim line1 = read.ReadLine
          Dim line2 = read.ReadLine
          Dim line3 = read.ReadLine
          'Join the lines togeter
          Dim record = string.Join("", line1, line2, line3).
          ' Split on the comma to produce an array of strings. The fields.
          Dim fields = record.Split(","c)
          records.Add(fields)
       End If
   Next
End Using

Of course this should be enhanced using a proper class that describe your inputs where each property of the class represent a field of the CSV file loaded. And then you could change the List(Of String()) to a List(Of YourClassData)
Keep in mind that this solution is extremely dependant of an exact file structure. A line with the "RECORD" content should be always followed by three lines of data. (No blank lines allowed between the three data lines)

A:      Dim read As New System.IO.StreamReader("C:\New Text.txt")
//I usually only do C#, but rough VB.NEt code: I did not rcreate your array for you, figured you got that :-)
       Dim a As String
       Dim myConcatString as String
       For Each a In read.ReadLine
          Dim myReadLine as String
            myReadLine = read.ReadLine
           If myReadLine.Equals("RECORD") Then
myConcatString = myConcatString  & myReadLine
               \\How do I read next 3 lines and put them in one array with comma delimiter
           else
           //add myConcatString to array if not null....
myConcatString =""
           End If
       Next


text:
Q: Javafx Pane vs Region? According to the documentation, both Region and Pane will resize any resizable child nodes to their preferred size, but will not reposition them.
So i can't see where the differencies between these two containers remain and when use one or another.

A: Region is a superclass for components that have child nodes.
The difference is that Region doesn't allow to manipulate its children through the public API. The Region.getChildren() method is protected:
new Region().getChildren().add(...); // doesn't compile
new Pane().getChildren().add(...); // works

Why is that?
Because Region is dedicated to component developers, and it allows them to choose if they want to allow API users to work with children directly (like Pane, HBox, etc.) or not (like charts).


text:
Q: Label on top on input that uses flex Im using flex to format input on a row format. But right now im trying to put label on top of those inputs and its not working. Im tried using display block and floating left or right but still remains on the left side. How should i style label so it floats to the top of those inputs?
This is the snippet:

.box {
        padding-top: 1rem;
    }

    .inside-box {
        max-width: 51rem;
        margin: 0 auto;
    }

    .form-group {
        display: flex;
        flex-direction: column;
    }

    .row {
        display: flex;
    }

    .razao-social-content {
        flex: 2 1 auto;
        /* grow shrink basis */
    }

    .rua-content {
        flex: 6 1 auto;
    }

    .municipio-content {
        flex: 4 1 auto;
    }

    .numero-content {
        flex: auto 1 auto;
    }

    .bairro-content {
        flex: 4 1 auto;
    }

    .telefone-content {
        flex: 1 1 auto;
    }

    .email-content {
        flex: 1 1 auto;
    }

    .categoria-content {
        flex: 2 1 auto;
    }

    .controlador-content {
        flex: 2 1 auto;
    }

    label {}

        <form action="" class="form-group">

                Razão Social
                <input class="razao-social-content" type="text" id="name" placeholder="Informe o seu nome" required>
                CNPJ
                <input class="cnpj-content" type="text" id="cnpj_distribuidor" placeholder="CNPJ" required>

                Rua
                <input class="rua-content" type="text" id="rua" placeholder="Nome da rua" required>
                Município
                <input class="municipio-content" type="text" id="municipio" placeholder="Nome do Município" required>
                Número
                <input class="numero-content" type="text" id="numero" placeholder="Número da Residência" required>

                Bairro
                <input class="bairro-content" type="text" id="bairro" placeholder="Nome do Bairro" required>
                Estado
                <input class="uf" type="text" id="uf" placeholder="Estado" required>
                CEP
                <input class="cep-content" type="text" id="cep" placeholder="CEP" required>

                Telefone
                <input class="telefone-content" type="text" id="telefone1" placeholder="Telefone" required>
                <input class="telefone-content" type="text" id="telefone2" placeholder="Telefone" required>
                <input class="telefone-content" type="text" id="telefone3" placeholder="Telefone" required>
                <input class="telefone-content" type="text" id="telefone4" placeholder="Telefone" required>

                Email
                <input class="email-content" type="text" id="email1" placeholder="Email" required>
                <input class="email-content" type="text" id="email2" placeholder="Email" required>
                <input class="email-content" type="text" id="email3" placeholder="Email" required>
                <input class="email-content" type="text" id="email4" placeholder="Email" required>

                Categorias
                <input class="categoria-content" type="text" id="categoria" placeholder="Informe as Categorias" required>
                Data Da Constituição
                <input class="data-content" type="date" id="data_constituicao" placeholder="Data da Constituição" required>
                Data da CVM
                <input class="data-content" type="date" id="data_cvm" placeholder="Data do CVM" required>

                Controlador
                <input class="controlador-content" type="text" id="controlador" placeholder="Nome do Controlador" required>
                CNPJ
                <input class="cnpj-content" type="text" id="cnpj_controlador" placeholder="CNPJ" required>

        </form>

This image link shows how I want it to be
https://www.figma.com/file/nuLJYzwr2LtoJxt4rPKDaI/Untitled?node-id=0%3A1

A: Just wrap label and input inside a div and add :
.row > div {
    display: flex;
    flex-direction: column;
}


text: Q: multiple instances of the same widget with Durandal I have a widget (some kind of profile scope with fields and other stuff). I want to use multiple instances of this widget in one viewmodel as a composition. Is it possible to do such a thing with Durandal and Knockout frameworks?


text:
Q: radGrid filtering doesn't work This is my code for telerik RadGrid
 <telerik:RadGrid ID="grdMain" runat="server" AllowPaging="True"
 AutoGenerateColumns="False" CellSpacing="0" EnableLinqExpressions="False"
 GridLines="None" PageSize="15"  AllowSorting="true"
 OnNeedDataSource="grdMain_NeedDataSource"
 >

I have a text box txtSearch and a button to search and filter grdMain Grid .
<telerik:RadButton ID="RadButton1" runat="server" Text="Search"
OnClick="search_Click" >
</telerik:RadButton>

This is my click event
  protected void search_Click(object sender, EventArgs e)
    {

  grdMain.MasterTableView.FilterExpression = "([ColumnOne] = '" + txtSearch.Text + "')";
  grdAirLine.Rebind();
    }

But filtering in my Grid doesn't work . What I am missing here ?

A: Apply filter in the code-behind.
To apply a filter in the code behind you need 3* things:
3*: Sometimes only 2.

*

*Set a filter filter expression
 grdMain.MasterTableView.FilterExpression = "([ColumnOne] = '" + txtSearch.Text + "')";

This is the Expression the grid will filter on.

*Set your column current filter
This is Only for the filter display in your column header. This is just for display and future filter. However this Must be set or the grid will just ignore any filter expression.
GridColumn column = RAD_Grid.MasterTableView.GetColumnSafe("ColumnOne");
column.CurrentFilterFunction = GridKnownFunction.EqualTo;
column.CurrentFilterValue = txtSearch.Text;

Needed only if is AllowFilteringByColumn is set on your RadGrid or MasterTableView.

*Rebind
Rebind the grid you update the filter. If you are working with a nestedGrid rebinding the parent grid or every parent is sometimes needed.

The question code should be working once you rebind the correct grid.

A: I think you should look into telerik forums.
Here is the simliar kind of problem .
http://www.telerik.com/community/forums/aspnet-ajax/grid/radgrid-with-filtering-not-working.aspx

A: You must add the ajax manager and the loading panel, this is how RadGrid filter the results.
Ex:
<telerik:RadAjaxManagerProxy ID="RadAjaxManagerProxy" runat="server">
    <AjaxSettings>
        <telerik:AjaxSetting AjaxControlID="grdMain">
            <UpdatedControls>
                <telerik:AjaxUpdatedControl ControlID="grdMain" LoadingPanelID="RadAjaxLoadingPanelGrid" />
            </UpdatedControls>
        </telerik:AjaxSetting>
    </AjaxSettings>
</telerik:RadAjaxManagerProxy>
<telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanelGrid" runat="server" Height="75px"
    Skin="Office2007" Width="75px">
</telerik:RadAjaxLoadingPanel>


text:
Q: Error: Postgres database import in docker container I'm running a ruby on rails application in docker container. I want to create and then restore the database dump in postgres container.
But I'm
Below is what I've done so far:
1) Added bash script in /docker-entrypoint-initdb.d folder. Script is just to create database:
psql -U docker -d postgres -c 'create database dbname;'
RESULT: Database created but rails server exited with code 0. Error: web_1 exited with code 0
2) Added script to be executed before docker-compose up.
# Run docker db container
echo "Running db container"
docker-compose run -d db

# Sleep for 10 sec so that container have time to run
echo "Sleep for 10 sec"
sleep 10

echo 'Copying db_dump.gz to db container'
docker cp db_dump/db_dump.gz $(docker-compose ps -q db):/

# Create database `dbname`
echo 'Creating database `dbname`'
docker exec -i $(docker-compose ps -q db) psql -U docker -d postgres -c 'create database dbname;'

echo 'importing database `dbname`'
docker exec -i $(docker-compose ps -q db) bash -c "gunzip -c /db_dump.gz | psql -U postgres dbname"

RESULT: Database created and restored data. But another container runs while running web application server using docker-compose up.
docker--compose.yml:
version: '2'

services:

  db:
    image: postgres

    environment:
      - POSTGRES_PASSWORD=docker
      - POSTGRES_USER=docker

  web:
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0' -d
    image: uname/application
    links:
      - db
    ports:
      - "3000:3000"
    depends_on:
      - db
    tty: true

Can some one please help to create and import database?
EDIT:
I've tried one more approach by adding POSTGRES_DB=db_name environment variable in docker-compose.yml file so that database will be created and after running the application (docker-compose up), I'll import the database. But getting an error: web_1 exited with code 0.
I'm confused why I'm getting this error (in first and third approach), seems to be something is messed up in docker-compose file.

A: Set up a database dump mount
You'll need to mount the dump into the container so you can access it. Something like this in docker-compose.yml:
db:
  volumes:
    - './db_dump:/db_dump'

Make a local directory named db_dump and place your db_dump.gz file there.
Start the database container
Use POSTGRES_DB in the environment (as you mentioned in your question) to automatically create the database. Start db by itself, without the rails server.
docker-compose up -d db

Import data
Wait a few seconds for the database to be available. Then, import your data.
docker-compose exec db gunzip /db_dump/db_dump.gz
docker-compose exec db psql -U postgres -d dbname -f /db_dump/db_dump.gz
docker-compose exec db rm -f /db_dump/db_dump.gz

You can also just make a script to do this import, stick that in your image, and then use a single docker-compose command to call that. Or you can have your entrypoint script check whether a dump file is present, and if so, unzip it and import it... whatever you need to do.
Start the rails server
docker-compose up -d web

Automating this
If you are doing this by hand for prep of a new setup, then you're done. If you need to automate this into a toolchain, you can do some of this stuff in a script. Just start the containers separately, doing the db import in between, and use sleep to cover any startup delays.

A: web_1 exited with code 0

Did you tried check the log of web_1 container? docker-compose logs web
I strongly recommend you don't initialize your db container manually, make it automatically within the process of start container.
Look into the entrypoint of postgres, we could just put the db_dump.gz into /docker-entrypoint-initdb.d/ directory of the container, and it will be automatic execute, so docker-compose.yml could be:
db:
  volumes:
    - './initdb.d:/docker-entrypoint-initdb.d'

And put your db_dump.gz into ./initdb.d on your local machine.

A: When you use command

docker-compose run -d db
you run a separate container it means you are running 3 containers where 1 is application 2 are dbs. The container you run using above command will not be a part of service. compose is using separate db.
So instead of running docker-compose up -d db run docker-compose up -d and continue with your script

A: I got it working by adding a container_name for db container. My db container have different name (app_name_db_1) and I was connecting to a container named db.
After giving the hard-coded container_name (db), it gets working.


text:
Q: Tangential harmonic 1-forms are of the form $u^\ast d\theta$ for special $u$ Let $(M^3,g)$ be a compact connected oriented Riemannian $3$-manifold with nonempty boundary. The Hodge-de Rham Theorem says that there is an isomorphism between $H^1_{dR}(M)$, the first de Rham cohomology group of $M$, and the space $\mathcal{H}_N^1(M)$ of tangential harmonic $1$-forms on $M$, given by
$$\mathcal{H}_N^1(M) = \{ \omega \in \Omega^1(M) : d \omega = 0,\, d^\ast \omega=0 \text{ and } i_\nu \omega = 0 \text{ on }\partial M\},$$
where $\nu$ is a unit normal for $\partial M$.
Suppose that $H^1(M; \mathbb{Z}) \neq 0$. Then, since $\mathbb{S}^1$ is a $K(\mathbb{Z},1)$, there is a bijection
$$\Phi : [M, \mathbb{S}^1] \to H^1(M; \mathbb{Z})$$
given by $\Phi([u]) = [u^\ast(d\theta)]$, where $d\theta \in \Omega^1(\mathbb{S}^1)$ is the volume element of $\mathbb{S}^1$. Now, de Rham Theorem and the Universal Coefficient Theorem give isomorphisms
$$H_{dR}^1(M) \cong H^1(M; \mathbb{R}) \cong H^1(M;\mathbb{Z}) \otimes_{\mathbb{Z}} \mathbb{R}$$
How do I conclude from this information that there exists a smooth map $u : M \to \mathbb{S}^1$ such that $u$ is harmonic with Neumann condition and $u^\ast(d\theta)\in H_{dR}^1(M)$ is tangential and harmonic?


text:
Q: How does expansion matter? \newcount\@repeat%
\def\repeat#1#2{%
\@repeat#1\relax%
\ifnum#1>\z@\relax%
  \advance\@repeat by -1\relax%
  \repeat{\@repeat}{#2}#2%
\fi}%
\repeat{2}{1}\\%
\repeat{11}{f}\\%
\repeat{\repeat{2}{1}}{f}% this does not work

The macro \repeat#1#2 repeats the argument #2 a total of #1 times.
I expect the last two lines produce the same thing, but the last line is wrong.
Why can't the last line produces the letter f 11 times? Does expandability matter? I don't quite understand it.
How I should edit the code so that they produce the same thing?

A: You get
! Missing = inserted for \ifnum.

because \repeat has
 \ifnum#1>\z@

so #1 has to expand to a number, but it is \repeat{2}{1} which includes many non expandable constructs such as   \@repeat, \relax and \advance.
Also although unrelated to the error in this fragment, it is a very bad idea to redefine \repeat as it is part of the basic \loop construct used throughout LaTeX and plain TeX.
This version just uses expansion:
\documentclass{article}

\begin{document}

\makeatletter

\def\xrepeat#1#2{%
\ifnum#1>\z@
  \xrepeat{\numexpr#1-1\relax}{#2}#2%
\fi}%
\xrepeat{2}{1}\\%
\xrepeat{11}{f}\\%
\xrepeat{\xrepeat{2}{1}}{f}% this does not work

\end{document}

A: David has already explained why the nested \repeat command can't work and also why it's a bad idea to use the name \repeat.
Here's a different definition, based on expl3: I'd say it's way easier, judge for yourself.
\documentclass{article}
\usepackage{expl3}

\ExplSyntaxOn
\cs_set_eq:NN \xrepeat \prg_replicate:nn
\ExplSyntaxOff

\begin{document}

\xrepeat{2}{1}\\
\xrepeat{11}{f}\\
\xrepeat{\xrepeat{2}{1}}{f}

\end{document}

Explanation
The expl3 package suite already provides the function you want to define and it's called \prg_replicate:nn. So we just make an alias for it. C'est tout.


text:
Q: Get all pattern Word fom a Text If I have a text, how can I get all the strings with a certain pattern from the text? For example I want all the strings with this patters:

The word CER followed by any number followed by one of
  this characters ;, ,, . or space .

For exemple from the text bellow I wold like to have in an array the following results : CER123 , CER23 , CER01 , CER24

Lorem CER123 ipsum dolor sit amet, quod copiosae CER23,CER01;CER24 insolens et usu, vis CER34ERD ut saperet civibus accommodare.

I've tried this:

preg_match_all("/CER[0-9*]?/",$content,$m);

but it returns : CER1 , CER2 , CER0 , CER2 and CER3

A: Use +, add a capturing group and create a character class for the characters you require after the value you need to get:
preg_match_all('/(CER[0-9]+)[;,.\s]/',$content,$m);
                 ^        ^^^^^^^^^

See the regex demo
Pattern explanation:

*

*(CER[0-9]+) - Group 1 capturing the parts of text you need:

*

*CER - a sequence of literal  characters CER (NOTE: If you need whole word CER only, after a non-word char or at the start of the string, add word boundaries: \bCER\b)

*[0-9]+ (=\d+) - 1 or more digits

*[;,.\s] - any char inside the character class: ;, ,, . or \s (whitespace - replace with a space if you only mean a regular space).

PHP demo:
$re= '/(CER[0-9]+)[;,.\s]/';
$content = "Lorem CER123 ipsum dolor sit amet, quod copiosae CER23,CER01;CER24 insolens et usu, vis CER34ERD ut saperet civibus accommodare.";
preg_match_all($re, $content, $m);
print_r($m[1]);


text:
Q: Connect to MongoDB server with Driver 2.0 best practice I have VB.net code that connects to a MongoDB. When the database is up and running my code works fine, but when the database is not running I don't get any errors back.
How do I check that the Server is up and running so I can connect to it and do my work? Basically IF the Server is up do work ELSE return a message to user that server is not available.
I look at the documentation about the MongoClient Class but I can't seem to find anything I can use.
MongoClient Class (http://api.mongodb.org/csharp/2.0/html/T_MongoDB_Driver_MongoClient.htm)
Below is my code that works to connect to the MongoDB:
Public Function DbConnection(ByRef ConnString As String, vDbName As String, vColName As String) As MongoClient

    'default port
    'ConnString = "mongodb://localhost:27017"

    'example DB and Collection
    'vDbName = "blog"
    'vColName = "users"

    'Root Object
    Dim vClient As MongoClient
    vClient = New MongoClient(ConnString)

    Dim vDb As MongoDatabaseBase
    vDb = vClient.GetDatabase(vDbName)

    Dim vCol As IMongoCollection(Of BsonDocument)
    vCol = vDb.GetCollection(Of BsonDocument)(vColName)

    Return vClient

End Function

Below is additional code where I use InsertOneAsync without creating an error:
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If txtName.Text = "" Then
        MsgBox("Enter a Name for the Database.")
    Else

        Dim ConnString As String
        ConnString = txtConnStr.Text

        Dim vDbName As String
        vDbName = txtDb.Text

        Dim vColName As String
        vColName = txtColl.Text

        'Root Object
        Dim vClient As MongoClient

        vClient = DbConnection(ConnString, vDbName, vColName)

        Dim vDb As MongoDatabaseBase
        vDb = vClient.GetDatabase(vDbName)

        Dim vCol As IMongoCollection(Of BsonDocument)
        vCol = vDb.GetCollection(Of BsonDocument)(vColName)

        Dim vAddUser As BsonDocument
        vAddUser = New BsonDocument

        vAddUser.Add("_Id", txtID.Text)
        vAddUser.Add("Name ", txtName.Text)
        vAddUser.Add("Email", txtEmail.Text)
        vAddUser.Add("City", txtCity.Text)

        rtfDataDisplay.Text = "BsonDocument = " & vAddUser.ToString & ", #" & vAddUser.Count

        Await vCol.InsertOneAsync(vAddUser)

    End If
End Sub

Below is the solution I came up with. I am only posting the Try...Catch since I have already posted entire procedures above.
        Try

            Dim watch As Stopwatch = New Stopwatch

            watch.Start()

            Dim insertResult As Task = vCol.InsertOneAsync(vAddUser)
            Await insertResult

            watch.Stop()

            MsgBox("Faulted =" & insertResult.IsFaulted.ToString & ", Status = " & insertResult.Status.ToString & ", Watch = " & watch.Elapsed.ToString)

        Catch ex As Exception
            If ex.HResult.ToString = "-2146233083" Then

                MsgBox("unable to insert data due to a timeout exception")
            Else
                MsgBox("Unable to insert data = " & ", HResult = " & ex.HResult.ToString & "!" & ex.ToString)
            End If

        End Try

A: Since the asynch only returns Task, it doesn't wait until the operation is complete. If you wait after the task and then you will capture the exception and process it accordingly, Here is the sample
Change this
Await vCol.InsertOneAsync(vAddUser)
Var insertTask = vCol.InsertOneAsync(vAddUser); insertTask.Wait();

and then remove the async keyword from the button_click method signature.


text:
Q: jquery open page in a tab and pass some POST values how can I open in a new window a php page and pass in some POST variable?
I am using jquery.
Thank you.

A: I would suggest creating an invisible form in your HTML like this:
<form id="invisible_form" action="new_window.php" method="post" target="_blank">
  <input id="new_window_parameter_1" name="parameter" type="hidden" value="default">
</form>

..and then submitting it via jQuery:
$('#new_window_parameter_1').val('value');
$('#invisible_form').submit();

A: Here is a sample how to submit a hidden form via POST:
function submit_post_via_hidden_form(url, params) {
    var f = $("<form target='_blank' method='POST' style='display:none;'></form>").attr({
        action: url
    }).appendTo(document.body);

    for (var i in params) {
        if (params.hasOwnProperty(i)) {
            $('<input type="hidden" />').attr({
                name: i,
                value: params[i]
            }).appendTo(f);
        }
    }

    f.submit();

    f.remove();
}

And to use it:
submit_post_via_hidden_form(
    'some link',
    {
        val1: val1,
        val2: val2
    }
);

A: Lite version with simple array compatibility:
    var url = 'myurl.html';
    var params = {
        inputId: 'somevalue',
        itemArray: ['as','a','example']
    };

    var f = $("<form target='_blank' method='POST' style='display:none;'></form>").attr({
        action: url
    }).appendTo(document.body);

    for (var i in params) {
        if (params.hasOwnProperty(i)) {
            if($.isArray(params[i])) {
                for (var j in params[i]) {
                    $('<input type="hidden" />').attr({
                        name: i + '[]',
                        value: params[i][j]
                    }).appendTo(f);
                }
            } else {
                $('<input type="hidden" />').attr({
                    name: i,
                    value: params[i]
                }).appendTo(f);
            }
        }
    }

    f.submit();
    f.remove();


text:
Q: Polyfill or workarounds for ECMAScript5 new features? I want to write my JS code with the new ECMAScript5 features that working today and in the future.
As not all browsers support all the features (especially IE) such as Object.create, Array.isArray or JSON.
I knew a few workarounds such as use json2.js to archieve JSON support. I want to know more polyfills or workarounds for the other feature.

A: Take a look at these :
https://github.com/kriskowal/es5-shim
https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills ( es5 shims listed in the middle)


text:
Q: Vue: Showing that the function does not exist when I have defined it the relevant store I am currently working on a simple app to store workout routines in Nuxt 3 and Appwrite. The link to the source code is here.
After logging in and adding in some workouts in the app's UI, whenever I try to call the deleteWorkout function, I get an error in the console saying that the function is not defined, whereas I have clearly defined in the workoutStore. I can't seem to figure out the reason for the same.
The same can be seen in the given screenshot.
Console on clicking the delete button
PS:

*

*Most probably the error should be originating from either /pages/workouts.vue, /components/WorkoutDetails.vue or /stores/workout.js.

*I am using Appwrite to manage the back-end of the web app, and the instructions to setup the same can be found in the README.md. (Though I don't think the error I am facing is related to the same.)

A: In your code the problem is, you declear your deleteWorkout() function outside of the actions block in workout.js file.
Make sure all your functions in the workout store are inside the actions block. Then it will be accessable from the vue component


text:
Q: Configuring Apache on top of GF3 - Not working I'm trying to configure Apache on top of Glassfish v3 using apj13.
But when I'm trying to access http://<server_name>/myApp but this is not working. It is keep on loading the page.
From Glassfish side I've not made any changes.
From Apache side I've edited the httpd.conf file to include virtual server using
JkMount /myApp/* worker1
There was no helpful logs in either from Glassfish or Apache.
Update:
Worker.properties file
worker.worker1.port=28081
worker.worker1.host=myservername
worker.worker1.type=ajp13
The application is using Primefaces if that helps.
Any help is much appreciated.!
Thanks.

A: I found the solution for this.
I was having wrong configuration (incorrect port) in my worker.properties file. Below is the correct one (for me)
worker.worker1.port=8009 //the port was wrong. Instead of having APJ port I had HTTP port
worker.worker1.host=myservername
worker.worker1.type=ajp13

Also I had included socket_connect_timeout to the properties file to check for any errors while communicating with JK and remote host.
Please note that I also had cluster enabled in my GF and I had to manually configured different APJ_LISTENER_PORT value in custer configuration page in Admin Console of GF.
Hope this might help someone.!


text:
Q: It is possible to reuse TikZ code? Let say one create the following figure and save it in a file figure.tex:
\documentclass{scrartcl}
\usepackage{tikz}
\usetikzlibrary{
                arrows.meta,
                bending,
                positioning
               }
\tikzset{
         > = Latex,
         arrows = {[bend]},
         signal/.style = coordinate,
         sum/.style = {
                       draw,
                       circle,
                       minimum size = 2mm
                      },
         block/.style = {
                         draw,
                         rectangle,
                         minimum height = 2em,
                         minimum width = 4em
                        },
         branch/.style = {
                          sum,
                          minimum size = 1mm,
                          fill = black
                         }
        }

\begin{document}

  \begin{tikzpicture}[auto]

    %placing the nodes
    \node[signal] (input) {};
    \node[sum, right = of input] (left sum) {};
    \node[block, right = of left sum] (controller) {$G_R$};
    \node[block, right = of controller] (system) {$G_S$};
    %connecting the controller and system to get the coordinates of u, its needed for the placement of the measurement block
    \draw
      [->] (controller) -- node[name = u] {$U$} (system);
    \node[block, above = of system] (dynamic of disturbances) {$G_D$};
    \node[signal, left = of dynamic of disturbances] (disturbances) {};
    \node[sum, right = of system] (right sum) {};
    \node[branch, right = of right sum] (branch) {};
    \node[signal, right = of branch] (output) {};
    \node[sum, below = of branch] (lower sum) {};
    \node[signal, right = of lower sum] (measurement noise) {};
    \node[block] (measurement) at (u |- lower sum) {$G_M$};
    %connecting the nodes
    \draw
      [->] (input) -- node {$W$} (left sum);
    \draw
      [->] (left sum) -- node {$E$} (controller);
    \draw
      [->] (system) -- (right sum);
    \draw
      [->] (disturbances) -- node {$Z$} (dynamic of disturbances);
    \draw
      [->] (dynamic of disturbances) -| (right sum);
    \draw
      (right sum) -- (branch);
    \draw
      [->] (branch) -- node {$Y$} (output);
    \draw
      [->] (branch) -- (lower sum);
    \draw
      [->] (measurement noise) -- node[above] {$M$} (lower sum);
    \draw
      [->] (lower sum) -- (measurement);
    \draw
      [->] (measurement) -| node[pos = .95] {$-$} (left sum);

  \end{tikzpicture}

\end{document}

Result:

Than one wish to load the file with \input{figure} and adding some code to it (without changing the file figure.tex), for example arrows, see my releated question. Is it possible?

A: Why don't you put everything in a macro? In that example I am using a scope to be able to use auto in your graph and not outside, but this is not needed if you use auto everywhere...
In iii.tex:
%%% probably is better left in your main file, but nothing happens if you have this
%%% multiple times
%%%
\usepackage{tikz}
%%%
%%% ditto
%%%
\usetikzlibrary{
                arrows.meta,
                bending,
                positioning
               }
\tikzset{
         > = Latex,
         arrows = {[bend]},
         signal/.style = coordinate,
         sum/.style = {
                       draw,
                       circle,
                       minimum size = 2mm
                      },
         block/.style = {
                         draw,
                         rectangle,
                         minimum height = 2em,
                         minimum width = 4em
                        },
         branch/.style = {
                          sum,
                          minimum size = 1mm,
                          fill = black
                         }
        }

\newcommand{\mygraph}{%
    \begin{scope}[auto]
    %placing the nodes
    \node[signal] (input) {};
    \node[sum, right = of input] (left sum) {};
    \node[block, right = of left sum] (controller) {$G_R$};
    \node[block, right = of controller] (system) {$G_S$};
    %connecting the controller and system to get the coordinates of u, its needed for the placement of the measurement block
    \draw
      [->] (controller) -- node[name = u] {$U$} (system);
    \node[block, above = of system] (dynamic of disturbances) {$G_D$};
    \node[signal, left = of dynamic of disturbances] (disturbances) {};
    \node[sum, right = of system] (right sum) {};
    \node[branch, right = of right sum] (branch) {};
    \node[signal, right = of branch] (output) {};
    \node[sum, below = of branch] (lower sum) {};
    \node[signal, right = of lower sum] (measurement noise) {};
    \node[block] (measurement) at (u |- lower sum) {$G_M$};
    %connecting the nodes
    \draw
      [->] (input) -- node {$W$} (left sum);
    \draw
      [->] (left sum) -- node {$E$} (controller);
    \draw
      [->] (system) -- (right sum);
    \draw
      [->] (disturbances) -- node {$Z$} (dynamic of disturbances);
    \draw
      [->] (dynamic of disturbances) -| (right sum);
    \draw
      (right sum) -- (branch);
    \draw
      [->] (branch) -- node {$Y$} (output);
    \draw
      [->] (branch) -- (lower sum);
    \draw
      [->] (measurement noise) -- node[above] {$M$} (lower sum);
    \draw
      [->] (lower sum) -- (measurement);
    \draw
      [->] (measurement) -| node[pos = .95] {$-$} (left sum);
\end{scope}}

and in your main file:
\documentclass{scrartcl}
\input{iii}

\begin{document}

\begin{tikzpicture}[auto]
    \mygraph
    %% add things
    \draw[red] (measurement) circle[radius=2cm];
\end{tikzpicture}

\end{document}

which gives the expected:


text:
Q: How to change Custom Listview row color change alternatively? I have created custom LISTVIEW for showing searched result list want to show each row with background color I tried out with some code but not working as per my requirement please help me out
here is my code
public class ListCustomBaseAdapter extends BaseAdapter {
private static ArrayList<SearchResult> searchArrayList;

private LayoutInflater mInflater;

public ListCustomBaseAdapter(Context context,
        ArrayList<SearchResult> results) {
    searchArrayList = results;
    mInflater = LayoutInflater.from(context);
}

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;

    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.custom_row_view, null);
        holder = new ViewHolder();
        holder.txtName = (TextView) convertView.findViewById(R.id.custNm);
        holder.txtProsNm = (TextView) convertView.findViewById(R.id.prosNm);
        holder.txtFrmPort = (TextView) convertView
                .findViewById(R.id.frmPort);
        holder.txtToPort = (TextView) convertView.findViewById(R.id.ToPort);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    if (position % 2 == 0) {
        holder.txtName.setBackgroundColor(Color.WHITE);
        holder.txtProsNm.setBackgroundColor(Color.WHITE);<----- change bgcolor of textview not whole row of View
        holder.txtFrmPort.setBackgroundColor(Color.WHITE);
        holder.txtToPort.setBackgroundColor(Color.WHITE);
    } else {
        holder.txtName.setBackgroundColor(Color.DKGRAY);
        holder.txtProsNm.setBackgroundColor(Color.DKGRAY);
        holder.txtFrmPort.setBackgroundColor(Color.DKGRAY);
        holder.txtToPort.setBackgroundColor(Color.DKGRAY);
    }
    holder.txtName.setText(searchArrayList.get(position).getCustNm());
    holder.txtProsNm.setText(searchArrayList.get(position).getProsNm());
    holder.txtFrmPort.setText(searchArrayList.get(position).getFrmPort());
    holder.txtToPort.setText(searchArrayList.get(position).getToPort());

    return convertView;
}

static class ViewHolder {
    TextView txtName;
    TextView txtFrmPort;
    TextView txtToPort;
    TextView txtProsNm;
}

}
calling adapter
 public void onCreate(Bundle savedInstanceState) throws SQLException {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Connection object for Spinner
    con = new DatabaseConnection(this);

    try {
        // Get Filtermap from Parent Activity
        // this Bundle contains HashMap
        Bundle wrapper = getIntent().getBundleExtra("salesActList");
        salesLstObj = (Map<String, Object>) wrapper.getSerializable("salesActCriteriaList");
        salesLst = con.searchSalesActivity(salesLstObj);

        ArrayList<SearchResult> searchResults = getSearchResults();

        lv = (ListView) findViewById(R.id.srListView);
        lv.setAdapter(new ListCustomBaseAdapter(this, searchResults));

        });
    } catch (SQLException se) {
        se.getStackTrace();
        String flag = "fail";
        dialogBox(flag);

}

here is output img

want to show Blue color area to be in gray alternately how to make it?
Custome row view code
  <TableLayout
    style="@style/TableLayoutStyle"
    android:orientation="vertical"
    android:paddingBottom="5dp"
    android:paddingLeft="5dp"
    android:paddingRight="5dp" >

    <TableRow
        android:id="@+id/tblRwCust"
        style="@style/TableRowStyle" >

        <TextView
            android:id="@+id/custNm"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#FF7F24"
            android:textSize="18sp"
            android:textStyle="bold" />
    </TableRow>

    <TableRow
        android:id="@+id/tblRwPros"
        style="@style/TableRowStyle" >

        <TextView
            android:id="@+id/prosNm"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000000" />
    </TableRow>

    <TableRow
        android:id="@+id/tblRwPort"
        style="@style/TableRowStyle" >

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/frmPort"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="5dp"
                android:textColor="#808080" />

            <TextView
                android:id="@+id/ToPort"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#808080" />
        </LinearLayout>
    </TableRow>
</TableLayout>

A: Here is my solution with Table layout instead Relative layout
<TableLayout
    style="@style/TableLayoutStyle"
    android:orientation="vertical"
    android:paddingBottom="5dp"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:id="@+id/myTable"
    android:background="#FFFFFF">

in adapter
holder.myTable = (TableLayout) convertView.findViewById(R.id.myTable);

if (position % 2 == 0) {
        holder.myTable.setBackgroundColor(Color.WHITE);
    } else {
        holder.myTable.setBackgroundColor(Color.GRAY);
    }

A: if(position%2 == 0 ){
            holder.convertView.setBackgroundColor(Color.CYAN);
        }else{
            holder.convertView.setBackgroundColor(Color.YELLOW);
        }


text:
Q: GetItem xml request using makeEwsRequestAsync() in Outlook for Mac has stopped returning a response Outlook for Mac: 16.24 (19041401)
I'm making a getItem request using makeEwsRequestAsync in Outlook for Mac and the callback does not contain a response, (status == succeeded, value is null). The same request from OWA/Outlook 2016 contains a valid xml response. I'm using the GetItem request to retrieve a changekey.
Why is there a difference in behavior here?
XML GetItem request
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soap:Header>
        <t:RequestServerVersion Version="Exchange2013"/>
    </soap:Header>
    <soap:Body>
        <m:GetItem>
            <m:ItemShape>
                <t:BaseShape>IdOnly</t:BaseShape>
                <t:BodyType>Text</t:BodyType>
            </m:ItemShape>
            <m:ItemIds>
                <t:ItemId Id="AAMkAGNlYjE1NWU4LTU1NmItNDdhYy04OTZiLWZmM2UwNjFkZjA1YwBGAAAAAACQR9mC/O1ETaOK/jgMPXmgBwCLsR3BxFcKQIBIOhhvOBA4AAAAAAEJAACLsR3BxFcKQIBIOhhvOBA4AAPI6G5DAAA="/>
            </m:ItemIds>
        </m:GetItem>
    </soap:Body>
</soap:Envelope>

A: This was a known issue acknowledged by Outlook for mac team and it is fixed in newer version of Outlook.(16.26+)


text:
Q: Button Background image won't shrink in VB.Net I used the following code in a VB.Net forms application:
    Dim btnShowHideSize As New Size(30, 30)
    btnShowHide.Size = btnShowHideSize
    Dim img As New Bitmap(Resources.change2)
    Dim img2 As New Bitmap(img, btnShowHideSize)
    btnShowHide.BackgroundImage = img2
    btnShowHide.BackgroundImageLayout = ImageLayout.Stretch

The image will expand, but not shrink. When I step through, I see that img size is 80,80 and img2 size is 30,30.  Howewver, the image is not shrinking - it is getting cut off.  If I go above 80,80 e.g. 200,200, the image does expand.
Is shrinking an image not possible?


text:
Q: Can't open multiple programs at once I'm working on a piece of code in Python 3 that acts as an interface for various dead by daylight cheats. I'm using a very basic setup, just input() and os.system() to find and open specific files. It works fine, but there's one small issue.
The interface uses cmd prompt, and I have it set up so that entering numbers 1-4 will open programs and executables used to modify the game. However, some of the programs are required to stay open while others run. For example, the BVHR Session Grabber must be running along with the SaveInjector Interface, because the SaveInjector needs to receive a certain code from the Grabber.
There's a problem here, the code is set up in such a way that you can only run one file at a time. I'm not sure what exactly causes this, but I'll try to explain what happens. When entering the number 1, for example, into the cmd prompt window, it opens the BHVR Session Grabber (as intended). After that, the interface becomes unusable until I close the BHVR Session Grabber. I can't type anything into it while it's active, so I can't open multiple programs at once.
Not entirely sure if this is intended or not, but I'm hoping it's avoidable. If anyone has any knowledge on the issue let me know how to find a way around this in the comments please.
import os.path
def interface():
    os.system('cls' if os.name == 'nt' else 'clear')
    print("""
    \n\nSelect a cheat below:
    \n
    \n1: BHVR Session Grabber
    \n2: SaveInjector Interface
    \n3: Rank / Shards Editor
    \n4: Exit\n
    """)

def checker():
    interface()
    lst = ['1','2','3','4']
    good_input = input(">")

    global user_input
    user_input = None
    while not user_input:
        if good_input in lst:
            user_input = good_input
        else:
            print("Enter a valid integer.")
            good_input = input(">")

checker()
cwd = os.getcwd()

def selection():
    if user_input == '1':
        f = (os.path.join(cwd, 'Programs', 'BHVRSession', 'CookieFinder.exe'));
        os.system(f)
        checker()
        selection()

    elif user_input == '2':
        os.system('cmd /k "cd Programs & cd Injector & SI.exe & cd.. & cd.. & Ultimate.py"')

    elif user_input == '3':
        f = (os.path.join(cwd, 'Programs', 'RankShards', 'Sender.exe'));
        os.system(f)
        checker()
        selection()

    elif user_input == '4':
        os.system('cmd /k "taskkill/im py.exe"')

selection()

A: The problem here is that os.system() is blocking. This means that it will only return and continue executing your Python code after the program it runs finishes. Instead, you should look at the subprocess package to learn how to fork a new process that can run in parallel with your Python program.


text:
Q: Diagonal shortcuts to minimize all-pairs shortest-paths in grid graph Augment the grid graph $G$ on lattice points $[1,n]^2$, which
connects each point to its four distance-$1$ vertical and horizontal neighbors.
Augment $G$ to $G'$ by adding in one of the two $\sqrt{2}$ diagonals
to each $1 \times 1$ lattice square.
I am seeking to understand which selection of diagonal shortcuts will minimize the total length
of all shortest paths:
all shortest paths between the $\binom{n}{2}$ pairs of lattice points
in the augmented graph $G'$.
An example $G'$ is shown below.

$n=7$.

Above the shortest path from $(1,1)$ to $(7,7)$ is $4+4\sqrt{2} \approx 9.7$,
while the shortest path from $(7,1)$ to $(1,7)$ is $6\sqrt{2} \approx 8.5$.

Q. What is the optimal choice of diagonals to minimize the sum of the lengths
  of the shortest paths in $G'$  between all pairs of lattice points, for
  arbitrary $n$?

Perhaps this has been studied before?
It seems related to shortest-path trees,
but I am not seeing how that concept yields the optimal network in the described situation.

Related: Shortest grid-graph paths with random diagonal shortcuts.

A: Checkerboard pattern is optimal, as long as the top left corner (or, indeed, at least one corner) has an adjacent diagonal.

Observe that the smallest possible distance between opposite corners of an $h \times w$ rectangle in any diagonal orientation is $h + w - (\sqrt{2} - 1)\cdot \min(h, w)$. One can see further that the checkerboard pattern achieves this bound for all rectangles with $h \neq w$, and is short $\sqrt{2} - 1$ to achieve it for about half of square corner pairs. Let us show that no orientation can do better than that.
A corner pair of a square is at optimum distance iff it is connected by an unbroken chain of diagonals. Consider any square with odd side length $k$; clearly, at most one of its diagonals can be unbroken. Hence, there can be at most $(n - k)^2$ optimum corner pairs, a bound that checkerboard readily achieves.
Squares with even side length $k$ require a bit more thought. Let's choose one of two diagonals in each $k \times k$ so that adjacent (= different by a shift of distance 1) squares have different orientations. There are two ways to do that, take any one of them.

Observe that in any pair of adjacent squares, at most one can have an unbroken diagonal of the chosen type. It follows that among the chosen diagonals at most $\lceil (n - k)^2 / 2 \rceil$ can be unbroken (since this is the maximum size of an independent set in an $(n - k) \times (n - k)$ grid). Accounting for two ways to choose orientation, there can be at most $2 \lceil (n - k)^2 / 2 \rceil$ optimal corner pairs in $k \times k$ squares. With a little case work, one can see that this is exactly how many optimal pairs of this kind a checkerboard pattern has.
The same argument seems to apply for $n \times m$ rectangular grids as well as square ones.


text:
Q: Adjective position in a string resource In French the position of the adjective can be before or after the noun. Depending of the length of the adjective, changing the position of the adjective can be mandatory to make a correct sentence. For example :

Bonne qualité nutritionnelle pour ce repas
Qualité nutritionnelle médiocre pour ce repas

I know plurals are implemented in Android, and also gender agreement with the SelectFormat class, but nothing on changing word order, e.g. adjective position, in a string resource.

A: You can use MessageFormat with a custom pattern. For that example:
String pattern = "{1, select, before {{0} qualité nutritionnelle} other {Qualité nutritionnelle {0}}} pour ce repas";
MessageFormat msgFmt = new MessageFormat(pattern, new ULocale("fr"));

Object args[] = {"Bonne", "before"};
Log.d("MessageFormatTAG",msgFmt.format(args));

Object args2[] = {"médiocre", "after"};
Log.d("MessageFormatTAG",msgFmt.format(args2))


text:
Q: Monotouch: How to capture the "cancel" button when sending email? I am trying to capture the "cancel" event when sending mail, so I can return to the previous view.  This is my code (http://monobin.com/__db8fa53f).  Tapping on the Cancel button, rather than the Send button, does nothing.  What do I need to add to my code?

A: I do not know what "AppDelegate.SetView(3);" does but if the result is "MFMailComposeResult.Cancelled", you are not dismissing the mail controller. It is only being dismissed if the result is "MFMailComposeResult.Sent".


text:
Q: I don't understand Dyson's argument for divergence of perturbative QED Dyson's argument that the perturbative expansion for QED must diverge:

[...] let
$$F(e^2)=a_0+a_1e^2+a_2e^4+\ldots$$
be a physical quantity which is calculated as a formal power series in $e^2$ by integrating the equations of motion of the theory over a finite or infinite time. Suppose, if possible, that the series...  converges for some positive value of $e^2$; this implies that $F(e^2)$ is an analytic function of $e$ at $e=0$. Then for sufficiently small value of $e$, $F(−e^2)$ will also be a well-behaved analytic function with a convergent power series expansion[...]

He then argues that for negative coupling $-e^2$ (like-charges attract) the vacuum of positive-coupling QED will be unstable and will continuously generate positron-electron pairs of a lower energy state (that subsequently repel). That part of the argument is fine.
The issue I have is with the argument that $F(e^2)$ must be analytic at $e^2=0$. What's to prevent $F(e^2)$ being well-behaved on $e^2\gt 0$ and poorly-behaved on $e^2\lt 0$. E.g:
$$
F(e^2) = \exp(e^2), e^2\gt 0\\
F(e^2) = \frac{1}{e^2}, e^2\lt 0
$$
and we make no claim for $F(0)$?
The Taylor series for the exponential converges everywhere, so the perturbative expansion of $F(e^2)$ is convergent for $e^2\gt 0$, as we would like to be true of QED. But this function does not have a convergent perturbative expansion in an open set around zero.
But nothing about the lack of a convergent perturbative expansion of $F(e^2)$ around $e^2=0$ implies that there is not a convergent perturbative expansion of $F(e^2)$ for $e^2\gt 0$. What am I missing?
(It seems to me that Dyson's argument is simply an argument that $F(e^2)$ must have such behavior around $e^2=0$. Switching from opposite-charges attract to opposite-charges repel while keeping matter/anti-matter pair creation the same (i.e. anti-matter has the opposite charge to matter) is not remotely a "continuous" change, no matter how small the coupling constant).

A: $F(z) = a_0 + a_1 z + \ldots$ is a power series in $z$ centered at $z=0$.  If this series converges for some $z_0>0$, then its radius of convergence is at least $z_0$ and so it is guaranteed to converge on the open ball $|z|<z_0$.
If I understand your objection, you're saying that it's possible to have a function which is non-analytic at $0$ but which is equal to $F(z)=a_0 + a_1 z + \ldots\ $ for some (or possibly all) $z>0$.  That is of course true, as your example demonstrates, but you're getting the argument twisted.  The function which Dyson is referring to is the power series in question, defined on the domain on which it converges.  In other words, letting $F$ be a formal power series, we are interested in the function $f:U\rightarrow \mathbb R$ where
$$U:= \{z\in \mathbb R \ | \ F(z) \text{ converges}\}$$
$$f :U\ni z\mapsto F(z)$$
It is this $f$ which Dyson is referring to as being analytic at $0$ if it converges for some $z_0>0$.  In your objection, you are saying that one could construct some $\hat f$ which coincides with $f$ for $z>0$ but is non-analytic at $0$, which is beside the point.

A: By being analytic at $e=0$ means that it has a perturbation expansion with a non-zero radius of convergence when expanded about $e=0$. As the radius of convergence is determined by the distance to the nearest singularity, means that there can be no nearby singularity for either positive or negative $e$. But there is is such a singularity (a branch point exactly at $e=0$) so the radius of convergence is zero, and by definition the function is not analytic at $e=0$.


text:
Q: Retrieving Fault types deep inside xml I am connecting to a web-service and getting errors in form of SoapException. This can contain different types of faults but are send down within the Detail property of SoapException. It can contain more than one faults. Here is one example of what is contained in the SoapException instance Detail.FirstChild.OuterXml.
<SomeErrorFault xmlns=\"urn:somenamespace\" xsi:type=\"SomeError\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"></SomeErrorFault>

The InnerExcpetion property is null. I would like to inspect all type of faults and take action on those. I of-course can do Detail.FirstChild.OuterXml.Contains("TypeOfFaultIAmLookingFor") but wondering if there is any better of retrieving this information?

A: You basically have to understand the data structure of SOAP fault. See this link might help.
http://msdn.microsoft.com/en-us/library/ms189538(v=sql.105).aspx


text:
Q: How to debug obtaining the web lock from a thread other than the main thread? void _WebThreadLockFromAnyThread(bool), 0x205acdf0: Obtaining the web lock from a thread other than the main thread or the web thread. UIKit should not be called from a secondary thread.

This look serious. I want the program to break at that point. I do not feel I access UIKit anywhere from outside the main thread.
However, the warning is just there and I don't know where in my code that happens

A: This means your code is called from non-main thread at some point. The problem is you don't remember or don't know where. You just feel you didn't but actually your code does.
My recommendation is heavy dynamic assertion. Install thread-check assertion on every suspicious  methods and functions. For example,
- (void)test
{
   NSAssert([[NSThread currentThread] isMainThread], @"This code is expected to be called from main thread!");
}

And then the assertion will eventually make your app to crash on invalid thread context. If you're not that lucky, you may install the assertion on every method literally.
Anyway once you got the assertion failure, you can start at there. And if you found the bad point, following steps are just trivial.


text:
Q: If $G$ acts on $X$ then $\psi: X\to X$ is a bijection I would appreciate if you could please express your opinion on this proof. I don't know how else this proof can be done.
Theorem: If $G$ acts on $X$ then $\psi: X\to X$ defined by $\psi_g(x)=g\cdot x$ is a bijection for all $g\in G$.
Proof: If $x=y$ then $\psi_g(x)=g\cdot x = g\cdot y=\psi_g(y)$, thus $\psi_g$ is injective. Since $|im(\psi_g)|=|X|$, $\psi_g$ is bijective.

A: Of course if $x=y$, then $\psi_g(x)=\psi_g(y)$! This is true for any function. What you need to show for injectivity is the converse of this, that is, if $\psi_g(x)=\psi_g(y)$, then $x=y$.
The second part about comparing cardinalities is correct (for finite sets $X$), but needs to be justified.

A: If $\psi_g(x)=\psi_g(y)$ then $gx=gy$. Then, applying $\psi _{g^{-1}}$ and using the associativity of the action, we have
$$\psi _{g^{-1}}(gx)=\psi _{g^{-1}}(gy)\Rightarrow g^{-1}(gx)=g^{-1}(gy)\Rightarrow (g^{-1}g)x=(g^{-1}g)y\Rightarrow x=y$$
so $\psi_g$ is injective.
If $x\in X$, then, again, using associativity, we have $\psi _g(g^{-1}x)=x$ which shows that $\psi _g$ is surjective.


text:
Q: Directly accessing element in result matrix http://www.mathworks.com/matlabcentral/answers/1325-what-is-missing-from-matlab#answer_1931
The basic jist is you can't create a matrix and directly index it.
My question is is there a known work-around for doing something like this?
I have a bunch of functions which operate on 2x1 vectors and I'm using an anonymous function that extracts the second element and does some operation with them.
Something like this:
f = @(theta)(rot_vec(V1,theta)(2) + rot_vec(V2,theta)(2) - rot_vec(V3,theta)(2));

How would I accomplish this same operation in matlab?

A: First of all, nothing stops you from defining an anonymous function as a pointer to regular function, with temporary variables.
 V1 = 1;
 V2 = 2;
 V3 = 3;
 f = @(theta)(GetRot(theta,V1,V2,V3);

Note that V1, V2 and V3 are frozen.
 function x = GetRot(theta,V1,V2,V3)
     r1 = rot_vec(V1,theta);
     r2 = rot_vec(V2,theta);
     r3 = rot_vec(V3,theta);
     x = r1(2) + r2(2) + r3(2);
 end

Secondly, as an ugly solution, you might as well use subsref, as it is the official name of () operator.
  m = magic(5);

  m(1:5)(1)  %THIS CAUSES AN ERROR!

  %But how about this one?
  subsref(m(1:5),struct('type','()','subs',{{1,2}}))

A: A good work around is to make your own function to do that:
function y=ind(A,i)
  y=A(i)
end

Then you can call it like that:
f = @(theta)(ind(rot_vec(V1,theta),2) + ind(rot_vec(V2,theta),2) - ind(rot_vec(V3,theta),2));

For more complicated cases, I made my own function:
function B = ind( A , varargin )
ii=varargin;
idx=find(cellfun(@isempty,ii));
for id=idx
  ii{id}=1:size(A,id);
end
if iscell(A)
  B=A{ii{:}};
else
  B=A(ii{:});
end
end

You can call it when you have several indices:
ind(foo(b),1:3,1:51:
You can also use it with cells, and you replace 1:end by []:
ind(foo(b),1:3,[])


text:
Q: rsync only sync destination folder existing files Src folder: A.txt B.txt C.txt
Dst folder: B.txt
Is there any way to let rsync only sync files in destination folder? So if A and B in source folder updated, rsync only copy B to destination folder?

A: rsync --existing will do the trick.

A: You can also try --files-from option which gives you more flexibility in controling what files would be transfered.
In your example, you can run find >/path/to/files_to_be_synced in your Dst folder, and then run rsync --files-from=:/path/to/files_to_be_synced, then only the files in files_to_be_synced will be transfered.
Note the colon ( : ) in command rsync --files-from=:/path/to/files_to_be_synced. It means read the files_to_be_synced file from remote server. You can alsa read the file from local server by omit the colon.


text:
Q: Query firestore on the server with auth info in a nuxt app I plan to query some data from Firestore within the fetch() method that Nuxt provides and then send it to the store. The problem is that the query requires the Firebase Auth info (the Firestore rules more precise), and afaik will the Firebase Auth not yet be connected or have loaded the active user since that happens client side. So that would mean that the query wouldn't have the auth info? How would I go about solving this? I have looked around and found that you could use cookies to store the Firebase Auth id and then within nuxtServerInit() in the store, load the user and get the correct uid and so forth, but Firebase will still not know about the user and I haven't found a way to load the user into Firebase Auth on the server side using the id from the cookie.
Any help would be really appreciated! (I released this got quite messy but hopefully you guys get the main point)
Worth nothing that I'm using Google as the sign in provider.
UPDATE:
I've done some digging and found that you can get the idToken and accessToken from the AuthCredential you get back after successful sign in. I think you could store those instead in a cookie and then sign in the user on the server using signInWithCredential() and pass a new GoogleAuthProvider that you could create with GoogleAuthProvider.credential(idToken, accessToken) using the tokens from the cookie.
Again, I'm not sure if this is safe to do or the correct way but I think it should work at least because now Firebase would now about the user already on the server side and therefore should the call to Firestore be no problem regarding the auth info.
I'm not able to test this right now but some thoughts on this would be great, thanks!
Still not able to test it but would like someone thoughts on this.


text:
Q: How to use in jQuery data from window.open How to use in jQuery data from window.open
  w = window.open("http://google.com",
            'test_window',
            'left=20,top=20,width=500,height=500,toolbar=1,resizable=1');
  browser = w.document;
  // execute commands in browser
  $(browser).ready(function(){
    alert($('input', browser).attr('name'));
  });
  // close browser
  w.close();

In this example I want to open new pop-up window, load Google page and get information about loaded page element (name of input filed).
I try to do this, but not found solution. Please, help me.

A: I believe you would need to open it in an iFrame.
or create a new window (http://your-domain.com/google.html) with an iframe embeded, then you can use jQuery to query the dom of the external content.

A: This is called cross site scripting (XSS). Your page (i.e. somedomain.com) is executing a script which is trying to read data off another window which has loaded a different domain (google.com). Modern browsers will prevent this since it is a security concern.
Imagine if you had a compromised site open in one window, and your bank site open in another. With XSS an attacker could sniff your bank info from the compromised site.
The only way to do such a thing is to disable XSS filters on the client (not a good idea), or install an application which does the job you are attempting to do with javascript. However, depending on what you are trying to accomplish, Google API's may offer the access you need without all that work.

A: Please tell us what are you trying to do. maybe there is a better solution. If you want to use google search stuff in your site there is a apis for that. Google search API


text:
Q: CS50 caesar doesn't exit after non-numeric input I'm getting an error that the program times out while waiting for program to exit after it handles a non-numeric key.  I can't see where the problem is.
This is the part of the code where I think the problem is:
int main(int argc, string argv[])
{
    if (argc != 2)
    {
        printf("Usage: %s\n", argv[0]);
        return 1;
    }
        for (int i = 0, n = strlen(argv[1]); i < n; i++)
        if(isalpha(argv[1][i]))
        {
            printf("Usage: %s\n", argv[0]);
            return 1;
        }

It works correctly if more than one argument is entered in the command line, but it doesn't exit if an alpha key is entered.


text:
Q: If statements in javascript, which is better? When writing javascript or PHP for that matter I use two ways to write if statements.
Return as soon as possible
Below I try to end the function as soon as possible. If the value is not what I expect, return it. The benefit I see here is that I don't need {} and I don't need to nest anything.
function hello(value = null) {
  if(!value) return;

  console.log("I'm still here!");
  console.log("End of function");
}

Do something on match
In this case I don't return at all. Instead I do something if I get a "match". The upside here is that I don't need to return anything.
function hello(value = null) {
  if(value) {
    console.log("I'm still here!");
    console.log("End of function");
  }
}

So which is better? One of them or equally good?


text:
Q: MySQL and PHP problems I'm new in server-side programming. I need lampp and mysql running on my computer. I have installed mysql using tasksel lamp-server, and then install php with apt-get install libapache2-mod-php5 phpmyadmin. And now I have now ideas how to use them. In xampp on Windows I needed only to copy my php files in htdocs directory. How to run php files in Linux and connect them to my MySQL?

A: Maybe you should install the following software first.
sudo apt-get install apache2
sudo apt-get install mysql-server
sudo apt-get install mysql-client
sudo apt-get install php5
sudo apt-get install php5-gd
sudo apt-get install php5-mysql
sudo apt-get install phpmyadmin

and then, you should configure you server.
1, Test apache, open you browser, and enter 127.0.0.1, if "It Works!" appears, okay.
2, Test php, create a file under /var/www, and name is "index.php", the content is:
<!--?php phpinfo(); ?-->

save and open the url "127.0.0.1/index.php", the php info should appear, if not, make sure you have proper permission.
3, Configure and test you phpmyadmin.
first, run as root,
sudo -i               #run as root
cd /etc/apache2/conf.d

and then create a file named "phpmyadmin-web.conf" or other you like, and the content of the file is:
Alias /phpmyadmin /usr/share/phpmyadmin
<directory usr="" share="" phpmyadmin="">
   AllowOverride All
</directory>

finally, you also should make a symbol link:
sudo ln -s /var/www/phpmyadmin /usr/share/phpmyadmin

then restart you apache server
sudo /etc/init.d/apache2 restart

Now, you can use your ubuntu as a lamp server.

A: I'm not sure if I understood your question, but if you just installed the lamp-server, you should have implicit installed apache web server.
AFAK the default directory where you have to put your files into is /var/www/. Just go to http://localhost (or which host you're running on) and check if you see something.
Per default the apache server, and the mysql database should be started automatically after boot. So you don't have to start them as with xampp.
If you're seeing any output on http://localhost it should contain a description, how to change the content. But it should be placed under /var/www/.
The mysql connection is the same as on windows, as you write it in PHP. The mysql database should run on the port 3306.
Also you can check this site where getting PHP running with tasksel is described.

A: What I have understand is, you want to install xampp server just like you did using Windows.
If this is what you want, download and install xampp from here
This xampp suite contain apache server, mysql server, php, perl, and phpmyadmin.
Installation and configuration instructions of xampp can be found here
This way, you don't need to install mysql or php separately.

If you follow instructions correctly, you will find your htdocs directory at /opt/lampp/htdocs


text:
Q: How to reset a input tag field after taking one input to take another one I wanted to create a calculator using HTML and JavaScript. I have already written the code and it works. But the main problem is that I cannot reset the input tag after I have already taken one input(like a calculator). I have an input tag like this:
 Enter First Number:
            <input  id = "num1" placeholder = "First Number"/>

In my JavaScript there are functions like sum() which requires two numbers and functions like sine() which requires one number. So I want the input tag to be reset for taking another input after the first one for the sum() function. How do I do that?

A: Do you use jQuery? Can you give us a little overview of your code?
Its hard to give you an advice when we dont know the code.
In case of jQuery you can empty the inputs value by
$("input").val("") //Replace input with the fitting selector

A: If you are not using jQuery you can use:
    document.getElementById('num1').value="";
This will clear the current value of the element. You should make sure that you have saved off the current value before you do this though.


text:
Q: Decoding a device payload sent to the Helium Console So I have defined an integration in the Helium Console (i.e. - an IoT LoRaWAN networking service). When I test out sending data from my IoT device to my Helium Console integration endpoint, I can see the payload. And I can manually decode it back to the JSON request body that's correct. But am having trouble defining a custom function in the Helium Console that will automate this for the integration. My IoT device is serializing a MsgPack payload of environmental data that's then sent to the Helium Console integration endpoint. And the Helium Console custom function allows Javascript, although just bare-bones without any requires, imports, etc.
Below is the Python script that can manually decode the payload. If anyone is familiar with this area I'd be interested as to suggestions. There are pre-defined decoders available for Helium, although none that match exactly my hardware.
If anyone has created custom decoding functions for Helium Console integrations I'd be curious as to how I could knock this out. Here is some info about this --> https://docs.helium.com/use-the-network/console/functions/.
import ssl, sys, json, base64
import msgpack

payload = "haJiVspAozMzo3RfQxilZWNfbVMWonBoB6NvcnAC"

# decode the payload from base64 and unpack
b64 = base64.b64decode(payload)
mp_dict = msgpack.unpackb(b64)

print(mp_dict) # output is {'bV': 5.099999904632568, 't_C': 24, 'orp': 2, 'ph': 7, 'ec_mS': 22}

A: Rather than reinvent the wheel, I modified the Arduino code running on my device. Pulling in the CayenneLPP library I manually encode what I need, so that the Helium Console's canned CayenneLPP decoding function can correctly parse the data.
Arduino code snippet below.
#include <CayenneLPP.h>
...

/*CayenneLPP variable*/
CayenneLPP lpp(51);

...

static void prepareTxFrame( uint8_t port )
{
    appDataSize = lpp.getSize();
    uint8_t lppBuffer[128];
    memcpy(lppBuffer, lpp.getBuffer(), 128);
    memcpy(appData, lppBuffer, lpp.getSize());
}

...

// The loop function is called in an endless loop
void loop()
{
    lpp.reset();
    lpp.addTemperature(1, 22.5);
    lpp.addBarometricPressure(2, 1073.21);
    lpp.addGPS(3, 52.37365, 4.88650, 2);

    ...

    LoRaWAN.displaySending();
    prepareTxFrame( appPort );
    LoRaWAN.send(loraWanClass);

    ...

 }

A: https://github.com/helium/console-decoders/blob/master/debugDecodeBase64.js
// LoRaWan devices automatically base64 encode data sent
// Sometimes nice just to view what original payload was sent
//
// This can help when writing your own decoder
//
//

 function Decoder(bytes, port, uplink_info) {
  var decoded={};
  try{
  var result = String.fromCharCode.apply(null, bytes);
  decoded.value = result;
  return decoded;
  } catch (err) {
  return 'Decoder: ' + err.name + " : " + err.message;;
  }
 }

// And in the integration section of the Helium console use this JSON
// For an Adafruit.io integration which is expecting JSON like { "value" : "56" }
//
// { "value": {{decoded.payload.value}} }

*

*Create account on https://app.datacake.de/

*Create integration to Datacake in here: https://console.helium.com/integrations
integrations

*Link the flow in here:
https://console.helium.com/flows
flows

*Create project and add device to DataCake, as decoder function use modified above (as is - it will receive a string)


text:
Q: CSS Make scrollbar take its own space without overlaying the content of the page I have a fixed toolbar having the buttons btn1, btn2, btn3 (the toolbar is set to display: flex, justify-content: space-between and position: fixed), but unfortunately when the content of the page is too long that makes the scrollbar to appear, the scrollbar overrides a part of btn3. What should I do to make the scrollbar take its own space when it appears? Or make the toolbar automatically stretch a bit to leave some space for the scrollbar?
 Without scrollbar
With scrollbar (the three dots are behind the scrollbar)

.Toolbar {
  height: 65px;
  background-color: rgb(48, 48, 48);
  color: white;
  width: 100vw;
  position: fixed;
  box-shadow: 0px 2px 6px -2px rgb(138, 138, 138);
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.WholePage {
   height: 1000px;
}

btn1

btn2

    btn3

A: Forcing the width to 100vw pushes it behind the scrollbar. Use 100% instead.

.Toolbar {
  height: 65px;
  background-color: rgb(48, 48, 48);
  color: white;
  width: 100%;
  position: fixed;
  box-shadow: 0px 2px 6px -2px rgb(138, 138, 138);
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.WholePage {
  height: 1000px;
}

header>* {
  border: 2px solid pink;
  padding: 3px;
}

btn1

btn2

    btn3

A: I think your issue could come from the the box-sizing.
Try box sizing: box-sizing: border-box; for those buttons. I add .btn as my example for those three buttons.
.btn {
 box-sizing: border-box;
}

For the detail of the box-sizing, please check it as https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing#box_sizes_with_content-box_and_border-box.

html {
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

.toolbar {
  background-color: rgb(48, 48, 48);
  color: white;
  box-shadow: 0px 2px 6px -2px rgb(138, 138, 138);
  height: 100px;
  width: 100vw;
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.toolbar div {
  display: flex;
  border: 1px solid red;
}

.whole-page {
  height: 2000px;
}

btn1

btn2

btn3


text:
Q: Pyomo: TypeError: argument of type 'NoneType' is not iterable I tried to maximize a non-linear function with pyomo in Python over positive integers y. When it comes to the optimization. The objective function was approximized, because it contained the pdf and cdf of a normal distribution. I don't think the problem is in the objective function or the constraints but in the package, note that I did not install the newest version of the NLP solver ipopt. Here is the code and the Error message:
conda install -c conda-forge pyomo
conda install -c conda-forge ipopt=3.11.1
conda install -c conda-forge glpk

import math
from pyomo.environ import *
import numpy as np
import pandas as pd

#average
mu={'A':30,'B':23,'C':9}

#variances
sigma={'A':10,'B':4,'C':5}

#selling price
e={'A':10,'B':12,'C':30}

#capital
K=300

#storage size per item of product
w={'A':3,'B':2,'C':5}

#Fixed costs

F=50

#rent for storage
M=40

#size of storage
G=30

#Products
products=['A','B','C']

max_production={'A':400,
               'B':300,
               'C':200}

production_costs={'A':5,
                 'B':4,
                 'C':20}

model= ConcreteModel()

#y ist variable die zu optimieren ist
model.y=Var(products,domain=PositiveIntegers  )

#constraints
model.constraints=ConstraintList()
for p in products:
    model.constraints.add(model.y[p]<=max_production[p]) #upper bound of production capacity for each product

#capital restriction
model.constraints.add(model.y['A']*production_costs['A']+model.y['B']*production_costs['B']+model.y['C']*production_costs['C']<=K)

#normal pdf
#1/(sigma[p]*np.sqrt(2*math.pi))*exp(-1/2*((model.y[p]-mu[p])/sigma[p])**2)

#approximate normal cdf see: https://mathoverflow.net/questions/19404/approximation-of-a-normal-distribution-function
#1/((model.y[p]-mu[p])/sigma[p]*np.sqrt(2*math.pi))*(1-1/(((model.y[p]-mu[p])/sigma[p])**2)+3/(((model.y[p]-mu[p])/sigma[p])**4)-15/(((model.y[p]-mu[p])/sigma[p])**6)+105/(((model.y[p]-mu[p])/sigma[p])**8))

#objective
profit=sum(-2*sigma[p]*1/(sigma[p]*np.sqrt(2*math.pi))*exp(-1/2*((model.y[p]-mu[p])/sigma[p])**2)*e[p]
+mu[p]*e[p]-sigma[p]*1/(sigma[p]*np.sqrt(2*math.pi))*exp(-1/2*((model.y[p]-mu[p])/sigma[p])**2)*w[p]*M/G
+mu[p]*1/((model.y[p]-mu[p])/sigma[p]*np.sqrt(2*math.pi))*(1-1/(((model.y[p]-mu[p])/sigma[p])**2)+3/(((model.y[p]-mu[p])/sigma[p])**4)-15/(((model.y[p]-mu[p])/sigma[p])**6)+105/(((model.y[p]-mu[p])/sigma[p])**8))*w[p]*M/G
+sigma[p]*1/(sigma[p]*np.sqrt(2*math.pi))*exp(-1/2*((model.y[p]-mu[p])/sigma[p])**2)*production_costs[p]
+(model.y[p]-mu[p])/sigma[p]*production_costs[p]-mu[p]*production_costs[p]-(model.y[p]-mu[p])/sigma[p]*1/((model.y[p]-mu[p])/sigma[p]*np.sqrt(2*math.pi))*(1-1/(((model.y[p]-mu[p])/sigma[p])**2)+3/(((model.y[p]-mu[p])/sigma[p])**4)-15/(((model.y[p]-mu[p])/sigma[p])**6)+105/(((model.y[p]-mu[p])/sigma[p])**8))*production_costs[p]
+mu[p]*1/((model.y[p]-mu[p])/sigma[p]*np.sqrt(2*math.pi))*(1-1/(((model.y[p]-mu[p])/sigma[p])**2)+3/(((model.y[p]-mu[p])/sigma[p])**4)-15/(((model.y[p]-mu[p])/sigma[p])**6)+105/(((model.y[p]-mu[p])/sigma[p])**8))*production_costs[p]-production_costs[p]*(model.y[p]-mu[p])/sigma[p]  for p in products
    )

model.objective = Objective(expr = profit, sense=maximize)

SolverFactory('mindtpy').solve(model,
                                   strategy='GOA',
                                   mip_solver='glpk',
                                   nlp_solver='ipopt')

and I get the error message:
----> 1 SolverFactory('mindtpy').solve(model,
      2                                    strategy='GOA',
      3                                    mip_solver='glpk',
      4                                    nlp_solver='ipopt')

~\anaconda3\lib\site-packages\pyomo\contrib\mindtpy\MindtPy.py in solve(self, model, **kwds)
    229             # Initialize the main problem
    230             with time_code(solve_data.timing, 'initialization'):
--> 231                 MindtPy_initialize_main(solve_data, config)
    232
    233             # Algorithm main loop

~\anaconda3\lib\site-packages\pyomo\contrib\mindtpy\initialization.py in MindtPy_initialize_main(solve_data, config)
     90     # Do the initialization
     91     if config.init_strategy == 'rNLP':
---> 92         init_rNLP(solve_data, config)
     93     elif config.init_strategy == 'max_binary':
     94         init_max_binaries(solve_data, config)

~\anaconda3\lib\site-packages\pyomo\contrib\mindtpy\initialization.py in init_rNLP(solve_data, config)
    158                 add_oa_cuts(solve_data.mip, dual_values, solve_data, config)
    159             elif config.strategy == 'GOA':
--> 160                 add_affine_cuts(solve_data, config)
    161             for var in solve_data.mip.MindtPy_utils.discrete_variable_list:
    162                 # We don't want to trigger the reset of the global stale

~\anaconda3\lib\site-packages\pyomo\contrib\mindtpy\cut_generation.py in add_affine_cuts(solve_data, config)
    264             # mcpp stuff
    265             try:
--> 266                 mc_eqn = mc(constr.body)
    267             except MCPP_Error as e:
    268                 config.logger.debug(

~\anaconda3\lib\site-packages\pyomo\contrib\mcpp\pyomo_mcpp.py in __init__(self, expression, improved_var_bounds)
    406         self.mc_expr = None
    407
--> 408         self.mcpp = _MCPP_lib()
    409         self.pyomo_expr = expression
    410         self.visitor = MCPP_visitor(expression, improved_var_bounds)

~\anaconda3\lib\site-packages\pyomo\contrib\mcpp\pyomo_mcpp.py in _MCPP_lib()
     60         return _MCPP_lib._mcpp
     61
---> 62     _MCPP_lib._mcpp = mcpp = ctypes.CDLL(Library('mcppInterface').path())
     63
     64     # Version number

~\anaconda3\lib\ctypes\__init__.py in __init__(self, name, mode, handle, use_errno, use_last_error, winmode)
    362                 import nt
    363                 mode = nt._LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
--> 364                 if '/' in name or '\\' in name:
    365                     self._name = nt._getfullpathname(self._name)
    366                     mode |= nt._LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR

TypeError: argument of type 'NoneType' is not iterable

Does anyone has an idea, which object is not iterable or why it does not work?

A: It looks like you haven't built the MC++ interface.
The Mindtpy GOA strategy relies on an interface to MC++ to build valid cuts.  Due to potentially incompatible licensing (MC++ is EPL, FADBAD++ is a custom dual-license, Pyomo is BSD), the compiled MC++ interface is not bundled as part of the Pyomo distribution.  Users need to download and build the MC++ library after installing Pyomo.  The easiest way to do it is to use the pyomo script:
pyomo download-extensions
pyomo build-extensions

One (big) catch is that you appear to be running Windows, and I have never had luck getting MC++ to build under Windows.


text:
Q: C# Get text which replaces text from span tags of an HTML code I have to do a console application in C# which reads some text from specific webpages. Now I have some problems because I dont know how to read text between  tags.
To begin with, I am downloading the html code from the webpage using WebClient object.
WebClient client = new WebClient();
String htmlCode = client.DownloadString(link);

In htmlCode string, between  tags I have an image which is a gif of an loading bar.

If I go to that website from a browser and check that part or if I use Inspect Element feature (which shows me html code) on that part of the webpage, I have a long text (which I need to get).
In addition, in the browser, if I choose to View source, there still are those  tags.
I need to get the text which replaces the gif image. How can I do that?
Thank you.

A: Just so you'll have it handy:

*

*Agility Pack - codeplex site

*Html Agility Pack Test Bed - great tool if you're going to work with agility pack.

*XPath tutorial on w3schools. You want to read this before you play with Agility.

Having said the above, if you put in the time to go through the above material, you shouldn't have a problem of finding the span and playing around with it.
Good luck :)


text:
Q: Add *.googleusercontent.com to Authorized JavaScript origins We have an add-on for Google Sheets and would like to switch other Google accounts for some functions.
Half a year ago, I successfully added a URL (https://***.googleusercontent.com) to Authorized JavaScript origins and a URL (https://oauth-redirect.googleusercontent.com/r/\*\*\*) to Authorized redirect URIs.
But now we can't and, therefore, it keeps showing

Authorization Error (Error:400: redirect_uri_mismatch).

When I try to add this URL(https://***.googleusercontent.com), it shows

"Save failed! The request failed because one of the field of the resource is invalid."

I don't know whether the rules changed and what should I do. See the screenshot for details. Thanks!

Error Message: The JavaScript origin in the request, https://***.googleusercontent.com, does not match the ones authorized for the OAuth client.

A: This appears to be a bug.
The issue you reported on Issue Tracker has been forwarded internally:

*

*Fail to Add *.googleusercontent.com into Authorized JavaScript origins

Thank you for bringing this to our attention. It has been forwarded internally.

Posting this here to give it more visibility. Please click the top-left star if you're affected by this.

A: I have the same problem, since October I am not allowed to use *.googleusercontent.com as Authorized origin.
I reported it on Issue Tracker, but their answer simply was "Thank you for your report, unfortunately Issuetracker is not the proper forum to address your report".
I solved this problem (At least temporarily) by inserting the Google sign-in button on an external site (Github pages) and once logged, redirect the user to my *.googleusercontent.com page with the sign-in token inserted in the URL as a parameter.