问:
Docker NGINX setup to run Django project is giving invalid port specification error
I am trying to setup Docker for my django project. I believe everything is setup to run docker in my machine. Currently, the docker version gives following output:

```<code>Client version: 1.6.2
Client API version: 1.18
Go version (client): go1.2.1
Git commit (client): 7c8fca2
OS/Arch (client): linux/amd64
Server version: 17.05.0-ce
Server API version: 1.29
Go version (server): go1.7.5
Git commit (server): 89658be
OS/Arch (server): linux/amd64
</code>```

I have setup my docker-compose.yml file as follows:

```<code>version: '3'
services:
  nginx:
    restart: always
    image: nginx:latest
    container_name: NGINX
    ports:
      - "8000:8000"
    volumes:
      - ./src:/src
      - ./config/nginx:/etc/nginx/conf.d
      - /static:/static
    depends_on:
      - web
  web:
    restart: always
    build: .
    container_name: DJANGO
    command: bash -c "python manage.py makemigrations && python manage.py migrate && gunicorn loop.wsgi -b 0.0.0.0:8000 --reload"
    depends_on:
      - db
    volumes:
      - ./src:/src
      - /static:/static
    expose:
      - "8000"

  db:
    restart: always
    image: postgres:latest
    container_name: PSQL
</code>```

docker-compose build successfully builds docker images and shows following message:

```<code>Successfully built 6b13b02488dc
Successfully tagged loopserver_web:latest
nginx uses an image, skipping
</code>```

But, when I try to run docker-compose up following error occurs:

```<code>Creating NGINX ...
Creating NGINX ... error

ERROR: for NGINX  Cannot create container for service nginx: invalid port specification: "None"

ERROR: for nginx  Cannot create container for service nginx: invalid port specification: "None"
ERROR: Encountered errors while bringing up the project.
</code>```

And theserver.conf file inside config/nginx folder.

```<code>upstream web {
  ip_hash;
  server web:8000;
}

# portal
server {
  location /static/ {
        autoindex on;
        alias /static/;
    }
  location / {
        proxy_pass http://web/;
    }
  listen 8000;
  server_name localhost;
}
</code>```

I am using docker for the first time and stuck with this error. Any guidance will be very helpful.

答:
in web service, just add:

```<code>environment:
   - NGINX_HOST=foobar.com
   - NGINX_PORT=80
</code>```

for more information: docker nginx

Body:
I am trying to setup Docker for my django project. I believe everything is setup to run docker in my machine. Currently, the docker version gives following output:

Client version: 1.6.2
Client API version: 1.18
Go version (client): go1.2.1
Git commit (client): 7c8fca2
OS/Arch (client): linux/amd64
Server version: 17.05.0-ce
Server API version: 1.29
Go version (server): go1.7.5
Git commit (server): 89658be
OS/Arch (server): linux/amd64

I have setup my docker-compose.yml file as follows:

version: '3'
services:
  nginx:
    restart: always
    image: nginx:latest
    container_name: NGINX
    ports:
      - "8000:8000"
    volumes:
      - ./src:/src
      - ./config/nginx:/etc/nginx/conf.d
      - /static:/static
    depends_on:
      - web
  web:
    restart: always
    build: .
    container_name: DJANGO
    command: bash -c "python manage.py makemigrations && python manage.py migrate && gunicorn loop.wsgi -b 0.0.0.0:8000 --reload"
    depends_on:
      - db
    volumes:
      - ./src:/src
      - /static:/static
    expose:
      - "8000"

  db:
    restart: always
    image: postgres:latest
    container_name: PSQL

docker-compose build successfully builds docker images and shows following message:

Successfully built 6b13b02488dc
Successfully tagged loopserver_web:latest
nginx uses an image, skipping

But, when I try to run docker-compose up following error occurs:

Creating NGINX ...
Creating NGINX ... error

ERROR: for NGINX  Cannot create container for service nginx: invalid port specification: "None"

ERROR: for nginx  Cannot create container for service nginx: invalid port specification: "None"
ERROR: Encountered errors while bringing up the project.

And theserver.conf file inside config/nginx folder.

upstream web {
  ip_hash;
  server web:8000;
}

# portal
server {
  location /static/ {
        autoindex on;
        alias /static/;
    }
  location / {
        proxy_pass http://web/;
    }
  listen 8000;
  server_name localhost;
}

I am using docker for the first time and stuck with this error. Any guidance will be very helpful.

Body:
in web service, just add:

environment:
   - NGINX_HOST=foobar.com
   - NGINX_PORT=80

for more information: docker nginx


来源: stackexchange

问:
Remove end-ticks from D3.js axis
I'm using (the excellent) D3.js to generate some plots, and I can't find a way to remove the end ticks from the x and y axis.

Take the y-axis for example.

When the end tick value coincides with a label, I'm ok with having it.

But when the last round label is below the end of the plot, I get two ticks, one for the last rounded label and one above it at the end of the y-axis.

I don't want this end-tick visible, because I find the fact that it appears in less than the regular interval between labels distracting.

See here for an example of what I'm describing, the ticks at 0 and 15 are the end ticks:

```<code>15 ─┐
    |
10 _|
    |
5  _|
    |
0  ─┤──────
</code>```

Any tips?

P.S As a response suggested, I could set the ticks explicitly. But I like the convenience of the implicit generated ticks, just don't want unlabelled ticks to pollute the axis. So an ideal solution (if exists) would also take than into account.

答:
In d3.js v4.x use .tickSizeOuter(0), like:

```<code>self._leftAxis = d3.axisLeft(self._y)
      .tickSizeInner(3) // the inner ticks will be of size 3
      .tickSizeOuter(0); // the outer ones of 0 size
</code>```

Note that the zero tick below is considered a inner on

This d3.js v4 doc: https://github.com/d3/d3-axis

ContentLicense: CC BY-SA 4.0

Title: Remove end-ticks from D3.js axis

Body:
I'm using (the excellent) D3.js to generate some plots, and I can't find a way to remove the end ticks from the x and y axis.

Take the y-axis for example.

When the end tick value coincides with a label, I'm ok with having it.

But when the last round label is below the end of the plot, I get two ticks, one for the last rounded label and one above it at the end of the y-axis.

I don't want this end-tick visible, because I find the fact that it appears in less than the regular interval between labels distracting.

See here for an example of what I'm describing, the ticks at 0 and 15 are the end ticks:

15 ─┐
    |
10 _|
    |
5  _|
    |
0  ─┤──────

Any tips?

P.S As a response suggested, I could set the ticks explicitly. But I like the convenience of the implicit generated ticks, just don't want unlabelled ticks to pollute the axis. So an ideal solution (if exists) would also take than into account.

Body:
In d3.js v4.x use .tickSizeOuter(0), like:

self._leftAxis = d3.axisLeft(self._y)
      .tickSizeInner(3) // the inner ticks will be of size 3
      .tickSizeOuter(0); // the outer ones of 0 size

Note that the zero tick below is considered a inner on

This d3.js v4 doc: https://github.com/d3/d3-axis


问:
Delete featured image with post Wordpress
Iv'e been searching for a while now and my search so far has been very unsuccessful. I'm looking for a function that deletes the featured image and post when clicking delete post on the posts page in the dashboard.

What I would like: Clicking delete on a post deletes instantly along with it's featured image instead of being moved to the "trash".

Sorry I'm not a pro developer, I'm a noob and just starting out. Any help would be great. Thank you!

答:
In any case, wp_delete_attachment requires attachment_id and not post_id. saved you half an hour ;)</p>

```<code>add_action( 'wp_trash_post', 'delete_post_permanently' );

function delete_post_permanently( $post_id ){
    wp_delete_post($post_id, true); // deletes post
    //wp_delete_attachment ( $post_id, true ); // deletes attachment
    if( has_post_thumbnail( $post_id ) )
    {
        $attachment_id = get_post_thumbnail_id( $post_id );
        wp_delete_attachment($attachment_id, true);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In any case, wp_delete_attachment requires attachment_id and not post_id. saved you half an hour ;)

add_action( 'wp_trash_post', 'delete_post_permanently' );

function delete_post_permanently( $post_id ){
    wp_delete_post($post_id, true); // deletes post
    //wp_delete_attachment ( $post_id, true ); // deletes attachment
    if( has_post_thumbnail( $post_id ) )
    {
        $attachment_id = get_post_thumbnail_id( $post_id );
        wp_delete_attachment($attachment_id, true);
    }
}


问:
Universal meta-language for "simple" programs
I realize that it is impossible to have one language that is best for everything.

But there is a class of simple programs, whose source code looks virtually identical in any language.

I am thinking not just "hello world", but also arithmetics, maybe string manipulation, basic stuff that you would typically see in utility classes.

I would like to keep my utilities in this meta-language and have it automatically translated to a bunch of popular languages. I do this by hand right now.

Again, I do not ask for translation of every single possible program. I am thinking a very limited, simple language, but superportable.

Do you know of anything like that? Is there a reason why it should not exist?

答:
If you find that there is no universal language, you can try a pragmatic model-driven development approach, using a template-based code generator.

On the template you keep the underlying concepts of an algorithm. Then, you would add code for this algorithm in one or more specific languages (C++,Java,JS,Python) when necessary. You would have to do it anyway, whatever the language or approach you choose. A configuration switch would pick the correct language for any template you apply.

AtomWeaver is a code generator that works with templates and employs ABSE as the modeling approach.

ContentLicense: CC BY-SA 2.5


问:
Docker file to run Python with Pandas
I have created the following Dockerfile

```<code>FROM python
COPY . /home
CMD pip install pandas
CMD mkdir /home/report
CMD mkdir /home/data
CMD python /home/hello.py
</code>```

where hello.py is the simple Python script

```<code>name = input('What is your Name? ')
print('Nice to meet you', name)

from pandas import read_csv
mydf = read_csv('mycsv.csv')
print(mydf.head())
</code>```

I then build the Docker image with docker build -t myexample . and run it with docker run -it myexample bash so as to interact with it via the shell. The building goes fine and upon running it I presented with the shell prompt, but then:

No directories report or data have been created under /home.

The last command python /home/hello.py does not execute on its own. I have to type it myself to get the script to run.

Once I type python /home/hello.py, the first two lines that greet and prompt for my name are executed properly, but then an error says that pandas is unknown.

It is not until I install pandas manually that the whole script runs correctly.

So, in summary, it seems that none of the CMD statements were taken into account. What am I doing wrong?

答:
```<code>FROM python
RUN pip install --no-cache-dir pandas && \
    mkdir /home/report /home/data && \
    chmod +x /home/hello.py
COPY . /home
VOLUME /home/report /home/data
WORKDIR /home
ENTRYPOINT /home/hello.py
</code>```

Notes:

As a general rule, it's better to collapse 2 RUN statements into one so one layer is created.

I suggest you use a better directory than /home

Use volumes to store data and logs.

Title: Docker file to run Python with Pandas

Body:
I have created the following Dockerfile

FROM python
COPY . /home
CMD pip install pandas
CMD mkdir /home/report
CMD mkdir /home/data
CMD python /home/hello.py

where hello.py is the simple Python script

name = input('What is your Name? ')
print('Nice to meet you', name)

from pandas import read_csv
mydf = read_csv('mycsv.csv')
print(mydf.head())

I then build the Docker image with docker build -t myexample . and run it with docker run -it myexample bash so as to interact with it via the shell. The building goes fine and upon running it I presented with the shell prompt, but then:

No directories report or data have been created under /home.

The last command python /home/hello.py does not execute on its own. I have to type it myself to get the script to run.

Once I type python /home/hello.py, the first two lines that greet and prompt for my name are executed properly, but then an error says that pandas is unknown.

It is not until I install pandas manually that the whole script runs correctly.

So, in summary, it seems that none of the CMD statements were taken into account. What am I doing wrong?

Body:
FROM python
RUN pip install --no-cache-dir pandas && \
    mkdir /home/report /home/data && \
    chmod +x /home/hello.py
COPY . /home
VOLUME /home/report /home/data
WORKDIR /home
ENTRYPOINT /home/hello.py

Notes:

As a general rule, it's better to collapse 2 RUN statements into one so one layer is created.

I suggest you use a better directory than /home

Use volumes to store data and logs.


问:
how to perform query in Postresql that returns a data count created grouped by month?
In postgresql, how do I perform a query that returns the sum amounts of rows created of a particular table by month? I would like the result to be something like:

```<code>month: January
count: 67

month: February
count: 85
....
....
</code>```

Let's suppose a I have a table, users. This table has a primary key, id, and a created_at column with time stored in ISO8601 formatting. Last year n number of users were created, and now I want to know how many were created by month, and I want the data returned to me in the above format -- grouped by month and an associated count reflecting how many users were created that month.

Does anyone know how to perform the above SQL query in postgresql?

答:
The query would look something like this:

```<code>select date_trunc('month', created_at) as mm, count(*)
from users u
where subscribed = true and
      created_at >= '2016-01-01' and
      created_at < '2017-01-01'
group by date_trunc('month', created_at);
</code>```

I don't know where the constant '2017-03-20 13:38:46.688-04' is coming from.

Of course you can make the year comparison dynamic:

```<code>select date_trunc('month', created_at) as mm, count(*)
from users u
where subscribed = true and
      created_at >= date_trunc('year', now()) - interval '1 year' and
      created_at < date_trunc('year', now())
group by date_trunc('month', created_at);
</code>```

Body:
In postgresql, how do I perform a query that returns the sum amounts of rows created of a particular table by month? I would like the result to be something like:

month: January
count: 67

month: February
count: 85
....
....

Let's suppose a I have a table, users. This table has a primary key, id, and a created_at column with time stored in ISO8601 formatting. Last year n number of users were created, and now I want to know how many were created by month, and I want the data returned to me in the above format -- grouped by month and an associated count reflecting how many users were created that month.

Does anyone know how to perform the above SQL query in postgresql?

Body:
The query would look something like this:

select date_trunc('month', created_at) as mm, count(*)
from users u
where subscribed = true and
      created_at >= '2016-01-01' and
      created_at < '2017-01-01'
group by date_trunc('month', created_at);

I don't know where the constant '2017-03-20 13:38:46.688-04' is coming from.

Of course you can make the year comparison dynamic:

select date_trunc('month', created_at) as mm, count(*)
from users u
where subscribed = true and
      created_at >= date_trunc('year', now()) - interval '1 year' and
      created_at < date_trunc('year', now())
group by date_trunc('month', created_at);


问:
Is there a PHP function that will check to make sure fields are set in an array
Does php library have any function to check if all required fields are set in an array?  For example:

```<code>function required_fields($vals,$required_fields_names){
    for($i = 0; $i < count($required_fields_names); $i++){
        if(!array_key_exists($required_fields_names[$i],$vals)){
            return false
        }
    }
    return true;
}
</code>```

Is there already a native PHP function/method that does this?

答:
NO, there is no native method.

But you can improve that code.

```<code><?php

function check_keys($keys,$array) {
    foreach ($keys as $key) {
        if(!array_key_exists($key, $array)) {
            return false;
        }
    }
    return true;
}

# Test Zone

$a = array('a' => 1,
           'b' => 2,
           'c' => 3);

$b = ['a','b','c'];
$c = ['a','b'];
$d = ['a','b','d'];

echo (int) check_keys($b,$a).'</br>'; # 1
echo (int) check_keys($c,$a).'</br>'; # 1
echo (int) check_keys($d,$a).'</br>'; # 0
?>
</code>```

Body:
Does php library have any function to check if all required fields are set in an array?  For example:

function required_fields($vals,$required_fields_names){
    for($i = 0; $i < count($required_fields_names); $i++){
        if(!array_key_exists($required_fields_names[$i],$vals)){
            return false
        }
    }
    return true;
}

Is there already a native PHP function/method that does this?

Body:
NO, there is no native method.

But you can improve that code.

<?php

function check_keys($keys,$array) {
    foreach ($keys as $key) {
        if(!array_key_exists($key, $array)) {
            return false;
        }
    }
    return true;
}

# Test Zone

$a = array('a' => 1,
           'b' => 2,
           'c' => 3);

$b = ['a','b','c'];
$c = ['a','b'];
$d = ['a','b','d'];

echo (int) check_keys($b,$a).'</br>'; # 1
echo (int) check_keys($c,$a).'</br>'; # 1
echo (int) check_keys($d,$a).'</br>'; # 0
?>


问:
VB.Net Excel Addin, how to write data to specific worksheet by name?
So here's the problem I have. I am converting an old Excel macro into an excel add in so I can share it easier with my coworkers. I am new to VB.net but I'm doing what I can so please go easy on me.

I have a Windows form that allows a user to enter data and when they hit the enter data button the data is supposed to go form the form to a specific worksheet. The code is as follows:

```<code>Imports Excel = Microsoft.Office.Interop.Excel

Public Class Form_CutListEntry

    Dim xApp As New Excel.Application
    Dim wss As Microsoft.Office.Tools.Excel.Worksheet

    Private Sub Btn_InsertJobInfo_Click(sender As Object, e As EventArgs) Handles Btn_InsertJobInfo.Click
        wss = xApp.Worksheets("Job Info")

        'Check that all data is entered
        If Trim(TxtBx_CustomerName.Text) = "" Then
            TxtBx_CustomerName.Focus()
            MsgBox("Please enter a Customer Name")
            Exit Sub
        End If

        If Trim(TxtBx_OrderNum.Text) = "" Then
            TxtBx_OrderNum.Focus()
            MsgBox("Please enter an Order Number")
            Exit Sub
        End If

        If Trim(TxtBx_CutlistAuthor.Text) = "" Then
            TxtBx_CutlistAuthor.Focus()
            MsgBox("Please enter your initials")
            Exit Sub
        End If

       'Write data to excel worksheet.
        wss.Cells(3, 1) = "Customer Name: " + TxtBx_CustomerName.Text
        wss.Cells(4, 1) = "Order Number: " + TxtBx_OrderNum.Text
        wss.Cells(5, 1) = "Todays Date: " + TxtBx_TodaysDate.Text
        wss.Cells(6, 1) = "Cutting List Prepared By: " + TxtBx_CutlistAuthor.Text

        Exit Sub
    End Sub
</code>```

(Note I took out the comments and some extra parts that aren't pertinent so the detailed error message below has the wrong line numbers)

I can open the windows form just fine from excel, but when I enter some data and click enter data this happens:

```<code>An exception of type 'System.Runtime.InteropServices.COMException' occurred in Toms CutList Maker.dll but was not handled in user code
Additional information: Exception from HRESULT: 0x800A03EC
</code>```

On this line:

```<code>wss = xApp.Worksheets("Job Info")
</code>```

Any chance anyone can point me in the write direction with this?

Here is the full error details if someone is interested:

```<code> System.Runtime.InteropServices.COMException was unhandled by user code
  ErrorCode=-2146827284
  HResult=-2146827284
  Message=Exception from HRESULT: 0x800A03EC
  Source=Microsoft.Office.Interop.Excel
  StackTrace:
       at Microsoft.Office.Interop.Excel.ApplicationClass.get_Worksheets()
       at Toms_CutList_Maker.Form_CutListEntry.Btn_InsertJobInfo_Click(Object sender, EventArgs e) in d:\tom\documents\visual studio 2013\Projects\Toms CutList Maker\Toms CutList Maker\CutList Entry.vb:line 15
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
  InnerException:
</code>```

答:
You're getting an error straight from Excel.
I have done the same exact thing, and this is what I have got:

```<code>Dim xlWorkBook As Excel.Workbook = xlapp.Workbooks.Add(Application.StartupPath + "\My Workbook.xlsx")
xlWorkBook.Sheets.Add("Job Info")
Dim xlWorkSheet As Excel.Worksheet = xlWorkBook.Sheets("JobInfo")
</code>```

Make sure the workbook that you're trying to open exists.

Body:
So here's the problem I have. I am converting an old Excel macro into an excel add in so I can share it easier with my coworkers. I am new to VB.net but I'm doing what I can so please go easy on me.

I have a Windows form that allows a user to enter data and when they hit the enter data button the data is supposed to go form the form to a specific worksheet. The code is as follows:

Imports Excel = Microsoft.Office.Interop.Excel

Public Class Form_CutListEntry

    Dim xApp As New Excel.Application
    Dim wss As Microsoft.Office.Tools.Excel.Worksheet

    Private Sub Btn_InsertJobInfo_Click(sender As Object, e As EventArgs) Handles Btn_InsertJobInfo.Click
        wss = xApp.Worksheets("Job Info")

        'Check that all data is entered
        If Trim(TxtBx_CustomerName.Text) = "" Then
            TxtBx_CustomerName.Focus()
            MsgBox("Please enter a Customer Name")
            Exit Sub
        End If

        If Trim(TxtBx_OrderNum.Text) = "" Then
            TxtBx_OrderNum.Focus()
            MsgBox("Please enter an Order Number")
            Exit Sub
        End If

        If Trim(TxtBx_CutlistAuthor.Text) = "" Then
            TxtBx_CutlistAuthor.Focus()
            MsgBox("Please enter your initials")
            Exit Sub
        End If

       'Write data to excel worksheet.
        wss.Cells(3, 1) = "Customer Name: " + TxtBx_CustomerName.Text
        wss.Cells(4, 1) = "Order Number: " + TxtBx_OrderNum.Text
        wss.Cells(5, 1) = "Todays Date: " + TxtBx_TodaysDate.Text
        wss.Cells(6, 1) = "Cutting List Prepared By: " + TxtBx_CutlistAuthor.Text

        Exit Sub
    End Sub

(Note I took out the comments and some extra parts that aren't pertinent so the detailed error message below has the wrong line numbers)

I can open the windows form just fine from excel, but when I enter some data and click enter data this happens:

An exception of type 'System.Runtime.InteropServices.COMException' occurred in Toms CutList Maker.dll but was not handled in user code
Additional information: Exception from HRESULT: 0x800A03EC

On this line:

wss = xApp.Worksheets("Job Info")

Any chance anyone can point me in the write direction with this?

Here is the full error details if someone is interested:

 System.Runtime.InteropServices.COMException was unhandled by user code
  ErrorCode=-2146827284
  HResult=-2146827284
  Message=Exception from HRESULT: 0x800A03EC
  Source=Microsoft.Office.Interop.Excel
  StackTrace:
       at Microsoft.Office.Interop.Excel.ApplicationClass.get_Worksheets()
       at Toms_CutList_Maker.Form_CutListEntry.Btn_InsertJobInfo_Click(Object sender, EventArgs e) in d:\tom\documents\visual studio 2013\Projects\Toms CutList Maker\Toms CutList Maker\CutList Entry.vb:line 15
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
  InnerException:

Body:
You're getting an error straight from Excel.
I have done the same exact thing, and this is what I have got:

Dim xlWorkBook As Excel.Workbook = xlapp.Workbooks.Add(Application.StartupPath + "\My Workbook.xlsx")
xlWorkBook.Sheets.Add("Job Info")
Dim xlWorkSheet As Excel.Worksheet = xlWorkBook.Sheets("JobInfo")

Make sure the workbook that you're trying to open exists.


问:
Matlab: How to find frequency, amplitude and phase of a sinusoidal function with linerary increasing frequency and phase?
I am trying to calculate amplitude and frequency modulation, as well as phase, of a sinusoidal function.

The function is decribed as follows:

```<code>fs = 128;
x1 = 1/fs:1/fs:1;
A1 = 50*x1;
B1 = 10*x1;
C1 = 1;
D1 = 1;
y1 = D1 + A1.*sin(C1 + B1.*x1);
</code>```

As a result I have obtained a sinusoidal function. It's amplitude and frequency increase over time, and are dependant on time. I need to use only 128 samples, so sampling frequency was changed to 128Hz.

Now, assuming I do NOT know A1, B1, C1 or D1 parameters, and only know the sampling frequency and result of "y1", is it possible to calculate all of those parameters?

What I would like, is to be able to determine frequency, amplitude and shift of the function at any given point in time.

I know that it's possible to calculate all of those for a function with stable parameters in few ways, I personally have tried this:

```<code>zastep2 = 1 + 40.*sin(1 + 10.*x1);

 x = x1';
 y = zastep2';

 calc = @(d) [ones(size(x)),sin(d*x),cos(d*x)]\y;
 calc2 = @(d) sum((y-[ones(size(x)),sin(d*x),cos(d*x)]*calc(d)).^2);

 Bw = fminbnd(calc2,1,50)
 abb = calc(Bw);
 Dw = abb(1)
 Aw = norm(abb([2 3]))
 Cw = acos(abb(2)/Aw)
</code>```

"zastep2" is used to simulate a function with unchanging parameters. As a result, I get the values of Dw = 1, Cw = 1, Aw = 40 and Bw = 10, so everything is okay.

Problem is, my function's amplitude and frequency linerary increase in every step, so using this kind of solution is impossible.

Is there any way to calculate those if both frequency and amplitude increase in every step? I am of course not asking for an instant solution or complete code, but I am really stuck on this, and after searching in the Internet for quite a while, decided to ask my own question.

答:
Instead of calculating the actual parameters A1, B1, C1 or D1 you could estimate them if you have y1 and the sampling frequency.
You could use the Cramer Rao lower bound or Maximum likelihood to find a pretty good estimate for these parameters since you already know the sampling frequency and the output y1 the estimation turns out pretty close to the original values.

https://en.wikipedia.org/wiki/Estimation_theory

Body:
I am trying to calculate amplitude and frequency modulation, as well as phase, of a sinusoidal function.

The function is decribed as follows:

fs = 128;
x1 = 1/fs:1/fs:1;
A1 = 50*x1;
B1 = 10*x1;
C1 = 1;
D1 = 1;
y1 = D1 + A1.*sin(C1 + B1.*x1);

As a result I have obtained a sinusoidal function. It's amplitude and frequency increase over time, and are dependant on time. I need to use only 128 samples, so sampling frequency was changed to 128Hz.

Now, assuming I do NOT know A1, B1, C1 or D1 parameters, and only know the sampling frequency and result of "y1", is it possible to calculate all of those parameters?

What I would like, is to be able to determine frequency, amplitude and shift of the function at any given point in time.

I know that it's possible to calculate all of those for a function with stable parameters in few ways, I personally have tried this:

zastep2 = 1 + 40.*sin(1 + 10.*x1);

 x = x1';
 y = zastep2';

 calc = @(d) [ones(size(x)),sin(d*x),cos(d*x)]\y;
 calc2 = @(d) sum((y-[ones(size(x)),sin(d*x),cos(d*x)]*calc(d)).^2);

 Bw = fminbnd(calc2,1,50)
 abb = calc(Bw);
 Dw = abb(1)
 Aw = norm(abb([2 3]))
 Cw = acos(abb(2)/Aw)

"zastep2" is used to simulate a function with unchanging parameters. As a result, I get the values of Dw = 1, Cw = 1, Aw = 40 and Bw = 10, so everything is okay.

Problem is, my function's amplitude and frequency linerary increase in every step, so using this kind of solution is impossible.

Is there any way to calculate those if both frequency and amplitude increase in every step? I am of course not asking for an instant solution or complete code, but I am really stuck on this, and after searching in the Internet for quite a while, decided to ask my own question.


问:
Is ioctl()'s FIONREAD on a C socket reliable?
I'm seeing strange behavior with the following piece of code:

```<code>int len;
ioctl(conn_fd, FIONREAD, &len);
</code>```

The usual code you might imagine precedes this (it's a toy web server):

```<code>...
int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
listen(sock_fd, 5);
int conn_fd = accept(sock_fd, (struct sockaddr *) &client_addr, &client_addr_size);
</code>```

The unusual behavior is when I use curl to make a request to my toy web server, everything works perfect and len is the exact size of the request. When I use Chrome, Postman, or wget, len is 0. Because len is 0, my code treats it as an empty response and doesn't consume the request.

To verify there is actually data (besides the fact that curl works), I follow the code up with:

```<code>char full_request[16384];
int bytes_read = read(conn_fd, full_request, 16383);
</code>```

To my delight, outputting full_request gives me, well, the full request no matter if it's curl, Chrome, Postman, or wget.

What gives? Is my call to ioctl not to be trusted? Is there a better way to know the size of the data coming in so I can consume it?

EDIT for EJP:

```<code> char *full_request = malloc(1 * sizeof(char));
 *full_request = '\0';

 for (;;) {
     char buf[64];
     int bytes_read;
     int new_len;

     bytes_read = recv(conn_fd, buf, 63, 0);
     buf[bytes_read] = '\0';

     if (bytes_read <= 0) break;

     new_len = strlen(full_request) + bytes_read + 1;

     full_request = realloc(full_request, new_len * sizeof(char));
     strcat(full_request, buf);
 }
</code>```

答:
The problem with your reasoning is that read() blocks until data is available, or end of stream or an error occurs. So the fact that it did return data doesn't indicate that FIONREAD was wrong at the moment you called it. There is rarely a good reason to use FIONREAD.

You also cannot rely on a single read returning the full request. It is only obliged to transfer at least one byte. You have to loop.

Body:
I'm seeing strange behavior with the following piece of code:

int len;
ioctl(conn_fd, FIONREAD, &len);

The usual code you might imagine precedes this (it's a toy web server):

...
int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
listen(sock_fd, 5);
int conn_fd = accept(sock_fd, (struct sockaddr *) &client_addr, &client_addr_size);

The unusual behavior is when I use curl to make a request to my toy web server, everything works perfect and len is the exact size of the request. When I use Chrome, Postman, or wget, len is 0. Because len is 0, my code treats it as an empty response and doesn't consume the request.

To verify there is actually data (besides the fact that curl works), I follow the code up with:

char full_request[16384];
int bytes_read = read(conn_fd, full_request, 16383);

To my delight, outputting full_request gives me, well, the full request no matter if it's curl, Chrome, Postman, or wget.

What gives? Is my call to ioctl not to be trusted? Is there a better way to know the size of the data coming in so I can consume it?

EDIT for EJP:

 char *full_request = malloc(1 * sizeof(char));
 *full_request = '\0';

 for (;;) {
     char buf[64];
     int bytes_read;
     int new_len;

     bytes_read = recv(conn_fd, buf, 63, 0);
     buf[bytes_read] = '\0';

     if (bytes_read <= 0) break;

     new_len = strlen(full_request) + bytes_read + 1;

     full_request = realloc(full_request, new_len * sizeof(char));
     strcat(full_request, buf);
 }


问:
Center Aligning an image in a header in WordPress
I am currently experimenting in WordPress an am using the theme Encounter Lite.  I have an image within the header that was Center aligned and now for some reason it isn't.  I have tried different code in the style.css sheet like float: center; but that hasn't made any difference.

I am using the current WordPress application (4.7.5).

Does anyone have a solution or suggestion to this?

答:
center is not a valid attribute of the float property.

I'm not familiar with the Encounter Lite theme, but text-align: center applied to the header element may work.

Specifying the width of the image and setting the left- and right- margins to auto is another option. In this case, make sure the image is a block-level element: display:block


问:
echo a javascript function with parameters in php
I am trying to pass a JavaScript function with an onclick event in php. The problem I am facing is that the function that I need to pass has a parameter that needs to be in double quotes as follows:

```<code>onclick="removeElement("div8")"
</code>```

Now when I use JavaScript to generate the parameter it comes out fine, but whenever I use an echo function in php, the following happens when I look at the function in the browser

```<code>onclick="removeElement(" div8")"
</code>```

the code I am using to generate this is:

```<code>echo '<div><img src="img.png" alt="image" onclick="removeElement("div'.$x.'")" /></div>';
</code>```

where $x is the number to be added to the parameter.

Is there a way that the function is returned as a whole and not get the space in between?

答:
when you using php echo try this code

```<code><a href="javascript:add_cota(<?php echo $value->ID .','.$k.', \''.$st.'\'';?>)">
</code>```

$st
  is the string param to avoid the ReferenceError: Active is not defined error

Body:
I am trying to pass a JavaScript function with an onclick event in php. The problem I am facing is that the function that I need to pass has a parameter that needs to be in double quotes as follows:

onclick="removeElement("div8")"

Now when I use JavaScript to generate the parameter it comes out fine, but whenever I use an echo function in php, the following happens when I look at the function in the browser

onclick="removeElement(" div8")"

the code I am using to generate this is:

echo '

';

where $x is the number to be added to the parameter.

Is there a way that the function is returned as a whole and not get the space in between?

Body:
when you using php echo try this code

<a href="javascript:add_cota(<?php echo $value->ID .','.$k.', \''.$st.'\'';?>)">

$st
  is the string param to avoid the ReferenceError: Active is not defined error


问:
vector and DataFrame length
I had a dataframe which consisted of 12 columns. Then I cut one vector from it and made it separate. I then performed train_test_split from sklearn library like below:

```<code>X=pd.DataFrame()

X['annua_inc']=annual_inc
X['delinq_2yrs']=delinq_2yrs
X['dti']=dti
X['emp_length']=emp_length
X['loan_amnt']=loan_amnt
X['installment']=installment
X['int_rate']=int_rate
X['total_acc']=total_acc
X['open_acc']=open_acc
X['pub_rec']=pub_rec
X['acc_now_delinq']=acc_now_delinq
X['loan_stat']=loan_stat

X=X.fillna(0)
y=X['loan_stat']
X=X.drop(['loan_stat'], axis=1)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=42)
</code>```

When I check the length of for example X_test and y_test (which both should be the same) it returns me the same value. But when I try to call X_test[len(X_test)] it tells me that index is out of bounds for axis 0. But for y_test[len(y_test)] it gives me a correct value. Does anyone know why? because the last row in X_test and last row in y_test were previously combined in the same row in X so why now the last row for X_test doesn't exist and for y_test it does?

答:
arrays in python, pandas, numpy, scipy, and others are zero based in their indexing.  So the length of [0, 1, 2, 3] is 4.  But [0, 1, 2, 3][4] will be out of bounds.  Refer to the last element as either [0, 1, 2, 3][4 - 1] or [0, 1, 2, 3][-1]

In your case

```<code>X_test[len(X_test) - 1]
</code>```

Or

```<code>X_test[-1]
</code>```

Title: vector and DataFrame length

Body:
I had a dataframe which consisted of 12 columns. Then I cut one vector from it and made it separate. I then performed train_test_split from sklearn library like below:

X=pd.DataFrame()

X['annua_inc']=annual_inc
X['delinq_2yrs']=delinq_2yrs
X['dti']=dti
X['emp_length']=emp_length
X['loan_amnt']=loan_amnt
X['installment']=installment
X['int_rate']=int_rate
X['total_acc']=total_acc
X['open_acc']=open_acc
X['pub_rec']=pub_rec
X['acc_now_delinq']=acc_now_delinq
X['loan_stat']=loan_stat

X=X.fillna(0)
y=X['loan_stat']
X=X.drop(['loan_stat'], axis=1)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=42)

When I check the length of for example X_test and y_test (which both should be the same) it returns me the same value. But when I try to call X_test[len(X_test)] it tells me that index is out of bounds for axis 0. But for y_test[len(y_test)] it gives me a correct value. Does anyone know why? because the last row in X_test and last row in y_test were previously combined in the same row in X so why now the last row for X_test doesn't exist and for y_test it does?

Body:
arrays in python, pandas, numpy, scipy, and others are zero based in their indexing.  So the length of [0, 1, 2, 3] is 4.  But [0, 1, 2, 3][4] will be out of bounds.  Refer to the last element as either [0, 1, 2, 3][4 - 1] or [0, 1, 2, 3][-1]

In your case

X_test[len(X_test) - 1]

Or

X_test[-1]


问:
how to remove string before second ":" in notepad++
I want to get last two strings email@email.com:namesurname from those strings. I know how to remove the last item after : with :.*  but how can i do that for first also for those below? Just give me a recommendation if anyone can.

jobapplication:::2017-05-29:email@email.com:namesurname

also like this one:

skills:email@email.com:namesurname

I dont have idea to start it and there are around 3200 job applications.

答: Have you considered recording a quick macro in which you do it once, replace or whatever, then press home home and down arrow to advance to the next line?  Then you could do Run For Rest of File and it'd be done.  (Make a backup first. ;))  I find the quick macro feature of Notepad++ comes in handy for this kind of thing, and easier (for some of us) to remember how to use than arcane regexes.</p>


问:
How do you document your development?
I am building my first complex app (in RoR) and as I think about passing it on to new programmers, I have been thinking about the best ways to document what I'm building.

How do you like to document your work?

Are there softwares or websites that allow one to easily accumulate sections of documentation, perhaps with tagging for easy reference later on?

答:
If I'm honost: I don't document my apps. When I get new programmers on my team, I give them an introduction to the domain, and that's it. They can read the specs and cucumber features themselves. If there is any special setup required, it's in the README. They can check out the CI configuration too.

That's the power of convention over configuration for ya!

Title: How do you document your development?


问:
Keep getting error from php and mysql
I'm trying to create a website that grabs stats from a database that the minecraft server creates. I'm having trouble with the uuid being inserted into mojangs API and coming out as a username. It works when you visit the site the first time but when you refresh it im getting errors:

```<code>Warning: file_get_contents(https://sessionserver.mojang.com/session/minecraft/profile/07eb744f35b74ac083e90e0377a5a967): failed to open stream: HTTP request failed! HTTP/1.1 429 429 in C:\xampp\htdocs\index.php on line 47
Notice: Trying to get property of non-object in C:\xampp\htdocs\index.php on line 49
Warning: file_get_contents(https://sessionserver.mojang.com/session/minecraft/profile/f5cf9ff1b9a74176983bb8b1d0c0ee70): failed to open stream: HTTP request failed! HTTP/1.1 429 429 in C:\xampp\htdocs\index.php on line 47
Notice: Trying to get property of non-object in C:\xampp\htdocs\index.php on line 49
</code>```

After i refreshed it the names dissapeared out of the table and it gave me those errors. I really need a fix to this and as quickly as possible!

```<code><code>
<!DOCTYPE html>
<html>
<head>
<style>
body {
    font-family: arial;
    background-color: #3be5de;
}
table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
    text-align: center;
}
</style>
<title>SuperBlaze27 Players-Server Stats</title>
<!--<link>-->
</head>
<body>
<div style="font-family: arial; color: #23a09b;">
<h1>SuperBlaze27 Minecraft Server Player Stats</h1>
<h3>Player joins</h3>
</div>
<?php
$servername = "localhost";
$username = "stats";
$password = "***";
$dbname = "stats3";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM `stats3_joins`";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
echo "<table><tr><th>Uniqe Player ID</th><th>Username</th><th>Player Head</th><th>Times Joined</th></tr>

";
    while($row = $result->fetch_assoc()) {
$uuid = $row["uuid"];
$uuid = str_replace('-', '', $uuid);
$json_response = file_get_contents("https://sessionserver.mojang.com/session/minecraft/profile/" . $uuid . "");
$data = json_decode($json_response);
        print "<tr><td>#" . $row["id"]. "</td><td> ". $data->name . "</td><td><img src='https://crafatar.com/avatars/" . $uuid . "?size=32'/img></td><td>" . $row["value"]. "</td></tr>";
    }
} else {
    echo "0 results";
}
$conn->close();
        echo "</table>";

// echo "Player name:".$data->name;

?>

</body>
</html>
</code>```

Btw the password i replaced with *** but in the real one it works so thats not the problem. Thx so much in advance!

答:
429 HTTP error means that you're sending too many requests in second to the server (sessionserver.mojang.com in your case).

The fact that you have to deal with a limit is quite expected, since reading from MySQL is very fast and your server makes many requests every second to get data. You need to add delays before the queries to fix this (which, in turn, can slow down the page load). Therefore, I also advise you to cache the received data and not to download it again every time the page is requested.

Title: Keep getting error from php and mysql

Body:
I'm trying to create a website that grabs stats from a database that the minecraft server creates. I'm having trouble with the uuid being inserted into mojangs API and coming out as a username. It works when you visit the site the first time but when you refresh it im getting errors:

Warning: file_get_contents(https://sessionserver.mojang.com/session/minecraft/profile/07eb744f35b74ac083e90e0377a5a967): failed to open stream: HTTP request failed! HTTP/1.1 429 429 in C:\xampp\htdocs\index.php on line 47
Notice: Trying to get property of non-object in C:\xampp\htdocs\index.php on line 49
Warning: file_get_contents(https://sessionserver.mojang.com/session/minecraft/profile/f5cf9ff1b9a74176983bb8b1d0c0ee70): failed to open stream: HTTP request failed! HTTP/1.1 429 429 in C:\xampp\htdocs\index.php on line 47
Notice: Trying to get property of non-object in C:\xampp\htdocs\index.php on line 49

After i refreshed it the names dissapeared out of the table and it gave me those errors. I really need a fix to this and as quickly as possible!

<!DOCTYPE html>

<title>SuperBlaze27 Players-Server Stats</title>

SuperBlaze27 Minecraft Server Player Stats

Player joins

<?php
$servername = "localhost";
$username = "stats";
$password = "***";
$dbname = "stats3";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM `stats3_joins`";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
echo "

Uniqe Player ID	Username	Player Head	Times Joined

";
    while($row = $result->fetch_assoc()) {
$uuid = $row["uuid"];
$uuid = str_replace('-', '', $uuid);
$json_response = file_get_contents("https://sessionserver.mojang.com/session/minecraft/profile/" . $uuid . "");
$data = json_decode($json_response);
        print "
#" . $row["id"]. "	 ". $data->name . "		" . $row["value"]. "
";
    }
} else {
    echo "0 results";
}
$conn->close();
        echo "
";

// echo "Player name:".$data->name;

?>

Btw the password i replaced with *** but in the real one it works so thats not the problem. Thx so much in advance!


问:
Identation using recursion
I want to know how you would approach a problem where you need to indent properly a text(containing java code) by reading it from a file, using recursion. The original output would be without any
 tabs.

That's the goal:

This is the code but I need to adapt it to read from a textfile:

```<code>void indent( int m, int n )
{
  System.out.println( m ); // Forward Printing

  if ( m < n )
  {
    indent( m + 1, n );
    System.out.println( m ); // Backward Printing
  }
}
</code>```

答:
Okay, the algorithm can be like...

```<code>function indent(theText, indentCharCount) {
   for each character of the text...
      if it is an end-of-line character...
         concatenate spaces to return string using indentCharCount
      else if it is a '{' character...
         scan ahead through characters to find matching '}' character
         recursively call indent() function passing...
            characters between { and } for 'theText' param
            indentCharCount+2 for 'indentCharCount' param
         concatenate return value of indent() to return string
         set loop index so that the next character will be the matched '}'
      else (it's some other character)
         concatenate character to return string
   return the concatenated string
}
</code>```

I didn't want to write out all the code in Java. If you are doing a homework assignment, I'd rather you learn something! But that's a basic recursive algorithm that I believe fits your question.

Title: Identation using recursion

Body:
I want to know how you would approach a problem where you need to indent properly a text(containing java code) by reading it from a file, using recursion. The original output would be without any
 tabs.

That's the goal:

This is the code but I need to adapt it to read from a textfile:

void indent( int m, int n )
{
  System.out.println( m ); // Forward Printing

  if ( m < n )
  {
    indent( m + 1, n );
    System.out.println( m ); // Backward Printing
  }
}

Body:
Okay, the algorithm can be like...

function indent(theText, indentCharCount) {
   for each character of the text...
      if it is an end-of-line character...
         concatenate spaces to return string using indentCharCount
      else if it is a '{' character...
         scan ahead through characters to find matching '}' character
         recursively call indent() function passing...
            characters between { and } for 'theText' param
            indentCharCount+2 for 'indentCharCount' param
         concatenate return value of indent() to return string
         set loop index so that the next character will be the matched '}'
      else (it's some other character)
         concatenate character to return string
   return the concatenated string
}

I didn't want to write out all the code in Java. If you are doing a homework assignment, I'd rather you learn something! But that's a basic recursive algorithm that I believe fits your question.


问:
Is (Document) an object in javascript?
In this code :

```<code>document.getElementById()
</code>```

Is document an object that has properties and methods?

If yes, is getElementById() a method on this object?

If no, What are document and getElementById considered?

答:
Yes, document is an object.

```<code>typeof document; // "object"
</code>```

And getElementById is a property on that object.

Title: Is (Document) an object in javascript?

Body:
In this code :

document.getElementById()

Is document an object that has properties and methods?

If yes, is getElementById() a method on this object?

If no, What are document and getElementById considered?

Body:
Yes, document is an object.

typeof document; // "object"

And getElementById is a property on that object.


问:
While with multiple conditions
This is my code.The user enters a string and if the input is 1,2 or * it displays error.The problem is that the condition is satisfied for all the numbers of which the first digits are 1,2 amd 3.(11,12,22...).I used also strlen and sizeof function to count the digits and create a condition that works but when i printed strlen the output was 1 for every number.

I don't understand if the problem is my multiple conditions or the use of scanf

Here is my code

```<code>#include < stdio.h >

int main (void)
{
    char choice;
    int i=0;
    do
    {
        scanf("%s", &choice);
        while(choice !='1' &&  choice !='2' && choice !='*' )
        {
            printf("error");
            scanf("%s",&choice);
        }

    }while (choice !='0');
    return 0;
    }
</code>```

I would be very thankful for any help. I am quite new in programming, so forgive me if the question is stupid.

答:
the following proposed code:

cleanly compiles

only calls scanf() once per each outer loop

prompts the user for the desired input

and now the code:

```<code>#include <stdio.h>  // scanf(), printf(), perror()
#include <stdlib.h> // exit(), EXIT_FAILURE

int main (void)
{
    char choice;

    do
    {
        printf( "enter 0:" );
        if( 1 != scanf(" %c", &choice) )
        {
            perror( "scanf failed" );  // to stderr:
                                       // enclosed text + reason OS thinks it failed
            exit( EXIT_FAILURE );      // once failed, it will continue to fail
                                       // so exit program with error indication
        }

        // implied else, scanf successful

        // what about other user inputs?
        if(choice !='1' &&  choice !='2' && choice !='*' )
        {
            printf("error\n");         // trailing '\n'
                                       // so immediately displayed on terminal
                                       // note: should use: 'fprintf( stderr, ... )'
                                       // because error messages should
                                       // be output to 'stderr', not 'stdout'
        }
    } while (choice !='0');

    return 0;
} // end function: main
</code>```

Title: While with multiple conditions

Body:
This is my code.The user enters a string and if the input is 1,2 or * it displays error.The problem is that the condition is satisfied for all the numbers of which the first digits are 1,2 amd 3.(11,12,22...).I used also strlen and sizeof function to count the digits and create a condition that works but when i printed strlen the output was 1 for every number.

I don't understand if the problem is my multiple conditions or the use of scanf

Here is my code

#include < stdio.h >

int main (void)
{
    char choice;
    int i=0;
    do
    {
        scanf("%s", &choice);
        while(choice !='1' &&  choice !='2' && choice !='*' )
        {
            printf("error");
            scanf("%s",&choice);
        }

    }while (choice !='0');
    return 0;
    }

I would be very thankful for any help. I am quite new in programming, so forgive me if the question is stupid.

Body:
the following proposed code:

cleanly compiles

only calls scanf() once per each outer loop

prompts the user for the desired input

and now the code:

#include <stdio.h>  // scanf(), printf(), perror()
#include <stdlib.h> // exit(), EXIT_FAILURE

int main (void)
{
    char choice;

    do
    {
        printf( "enter 0:" );
        if( 1 != scanf(" %c", &choice) )
        {
            perror( "scanf failed" );  // to stderr:
                                       // enclosed text + reason OS thinks it failed
            exit( EXIT_FAILURE );      // once failed, it will continue to fail
                                       // so exit program with error indication
        }

        // implied else, scanf successful

        // what about other user inputs?
        if(choice !='1' &&  choice !='2' && choice !='*' )
        {
            printf("error\n");         // trailing '\n'
                                       // so immediately displayed on terminal
                                       // note: should use: 'fprintf( stderr, ... )'
                                       // because error messages should
                                       // be output to 'stderr', not 'stdout'
        }
    } while (choice !='0');

    return 0;
} // end function: main


问:
How to calculate maximum from pivot table in python
I have written code to calculate the count of feature3 groupby feature1 and feature2

```<code>pd.pivot_table(data=train, index=['feature1', 'feature2'], values=['feature3'], aggfunc='count')
</code>```

Who's output is:

```<code>feature1 feature2 feature3
129001  0   4
        1   10
        2   11
        3   22
        4   26
        5   38
129002  0   6
        2   45
        5   25
</code>```

Now I want to calculate max of feature3 groupby feature1

```<code>feature1 feature3
129001    38
129002    45
</code>```

答:
IIUC:

You need the following statement:

```<code>df.groupby(level=0)['feature3'].max()
</code>```

Start with the results of your pivot_table

```<code>print(df)
                   feature3
feature1 feature2
129001   0                4
         1               10
         2               11
         3               22
         4               26
         5               38
129002   0                6
         2               45
         5               25
</code>```

groupby with level 0 of your index and max:

```<code>df.groupby(level=0)['feature3'].max()
</code>```

Output:

```<code>feature1
129001    38
129002    45
Name: feature3, dtype: int64
</code>```

Body:
I have written code to calculate the count of feature3 groupby feature1 and feature2

pd.pivot_table(data=train, index=['feature1', 'feature2'], values=['feature3'], aggfunc='count')

Who's output is:

feature1 feature2 feature3
129001  0   4
        1   10
        2   11
        3   22
        4   26
        5   38
129002  0   6
        2   45
        5   25

Now I want to calculate max of feature3 groupby feature1

feature1 feature3
129001    38
129002    45

Body:
IIUC:

You need the following statement:

df.groupby(level=0)['feature3'].max()

Start with the results of your pivot_table

print(df)
                   feature3
feature1 feature2
129001   0                4
         1               10
         2               11
         3               22
         4               26
         5               38
129002   0                6
         2               45
         5               25

groupby with level 0 of your index and max:

df.groupby(level=0)['feature3'].max()

Output:

feature1
129001    38
129002    45
Name: feature3, dtype: int64


问:
Parsing large and complicated XML file to data.frame
So, I have large XML file with lots of reports. I created data example below to approximately show the size of xml and its structure:

```<code>x <- "<Report><Agreements><AgreementList /></Agreements><CIP><RecordList><Record><Date>2017-05-26T00:00:00</Date><Grade>2</Grade><ReasonsList><Reason><Code>R</Code><Description>local</Description></Reason></ReasonsList><Score>xxx</Score></Record><Record><Date>2017-04-30T00:00:00</Date><Grade>2</Grade><ReasonsList><Reason><Code>R</Code><Description/></Reason></ReasonsList><Score>xyx</Score></Record></RecordList></CIP><Individual><Contact><Email/></Contact><General><FirstName>MM</FirstName></General></Individual><Inquiries><InquiryList><Inquiry><DateOfInquiry>2017-03-19</DateOfInquiry><Reason>cc</Reason></Inquiry><Inquiry><DateOfInquiry>2016-10-14</DateOfInquiry><Reason>er</Reason></Inquiry></InquiryList><Summary><NumberOfInquiries>2</NumberOfInquiries></Summary></Inquiries></Report>"

x <- paste(rep(x, 1.5e+5), collapse = "")
x <- paste0("<R>", x, "</R>")
require(XML)
p <- xmlParse(x)
p <- xmlRoot(p)
p[[1]]
</code>```

I would like to transform this data to data.frame, but the structure of XML isn't straightforward. Previously working with XMLs I created loop that for every report transforms its sub nodes to data.frame, but here (in this data) the sub node count is greater than 30 (didn't put all of them in the example), and the structure differs (List nodes can occur even 2 levels deep in XML).

So I have few questions:

1) I am sure that looping over reports isn't the best way to handle this. How should I approach this problem?

2) Can I somehow extract all the data of one report two one line of data.frame (recursively maybe)?

3) Or can I automatically create separate data.frames for each list object of XML?

Any help would be much appreciated.

Update:

Example of results could look like this:

```<code>Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   1 obs. of  17 variables:
 $ Record.1.Date                : chr "2017-05-26T00:00:00"
 $ Record.1.Grade               : num 2
 $ Record.1.Reason.1.Code       : chr "R"
 $ Record.1.Reason.1.Description: chr "local"
 $ Record.1.Score               : chr "xxx"
 $ Record.2.Date                : chr "2017-05-26T00:00:00"
 $ Record.2.Grade               : num 2
 $ Record.2.Reason.1.Code       : chr "R"
 $ Record.2.Reason.1.Description: chr "NA"
 $ Record.2.Score               : chr "xyx"
 $ Email.1                      : chr "NA"
 $ FirstName                    : chr "MM"
 $ Inquiry.1.DateOfInquiry      : POSIXct, format: "2017-03-19"
 $ Inquiry.1.Reason             : chr "cc"
 $ Inquiry.2.DateOfInquiry      : POSIXct, format: "2016-10-14"
 $ Inquiry.2.Reason             : chr "er"
 $ NumberOfInquiries            : num 2
</code>```

, but as I mentioned previously, sub lists could also be in separate tables.

答:
Because you mention, I would like to transform this data, consider XSLT, the special-purpose transformation language designed to restructure complex XML to various end-use structures. And in your case flattening any text holding nodes in XML which then can easily be imported with xmlToDataFrame(). While below uses xsltproc and .NET Xsl class, any external processor or language module (e.g., Python, Java, C#, VB, PHP) that supports XSLT 1.0 can work:

XSLT (save as .xsl file)

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="/R">
        <xsl:copy>
            <xsl:apply-templates select="Report"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Report">
        <xsl:copy>
            <xsl:apply-templates select="descendant::*[string-length(text())>0]"/>
        </xsl:copy>
    </xsl:template>

   <xsl:template match="*">
      <xsl:element name="{concat(local-name(), position())}">
      <xsl:value-of select="." />
      </xsl:element>
   </xsl:template>

</xsl:stylesheet>
</code>```

XML Output (with numbered suffixes to avoid repeated column error)

```<code><?xml version="1.0"?>
<R>
  <Report>
    <Date1>2017-05-26T00:00:00</Date1>
    <Grade2>2</Grade2>
    <Code3>R</Code3>
    <Description4>local</Description4>
    <Score5>xxx</Score5>
    <Date6>2017-04-30T00:00:00</Date6>
    <Grade7>2</Grade7>
    <Code8>R</Code8>
    <Score9>xyx</Score9>
    <FirstName10>MM</FirstName10>
    <DateOfInquiry11>2017-03-19</DateOfInquiry11>
    <Reason12>cc</Reason12>
    <DateOfInquiry13>2016-10-14</DateOfInquiry13>
    <Reason14>er</Reason14>
    <NumberOfInquiries15>2</NumberOfInquiries15>
  </Report>
</R>
</code>```

R Mac/Linux Script (calling xsltproc, available package on unix machines)

```<code>library(XML)

setwd("/path/to/working/folder")

# COMMAND LINE CALL (INSTALL xsltproc IN TERMINAL)
system(paste("cd", getwd(), " && xsltproc -o Output.xml XSLTScript.xsl Input.xml"))

# PARSE AND LOAD TO DF
doc <- xmlParse('Output.xml')
df <- xmlToDataFrame(nodes = getNodeSet(doc, "//Report"))

str(df)
# 'data.frame': 6 obs. of  15 variables:
#  $ Date1              : chr  "2017-05-26T00:00:00" "2017-05-26T00:00:00" "2017-05-26T00:00:00" "2017-05-26T00:00:00" ...
#  $ Grade2             : chr  "2" "2" "2" "2" ...
#  $ Code3              : chr  "R" "R" "R" "R" ...
#  $ Description4       : chr  "local" "local" "local" "local" ...
#  $ Score5             : chr  "xxx" "xxx" "xxx" "xxx" ...
#  $ Date6              : chr  "2017-04-30T00:00:00" "2017-04-30T00:00:00" "2017-04-30T00:00:00" "2017-04-30T00:00:00" ...
#  $ Grade7             : chr  "2" "2" "2" "2" ...
#  $ Code8              : chr  "R" "R" "R" "R" ...
#  $ Score9             : chr  "xyx" "xyx" "xyx" "xyx" ...
#  $ FirstName10        : chr  "MM" "MM" "MM" "MM" ...
#  $ DateOfInquiry11    : chr  "2017-03-19" "2017-03-19" "2017-03-19" "2017-03-19" ...
#  $ Reason12           : chr  "cc" "cc" "cc" "cc" ...
#  $ DateOfInquiry13    : chr  "2016-10-14" "2016-10-14" "2016-10-14" "2016-10-14" ...
#  $ Reason14           : chr  "er" "er" "er" "er" ...
#  $ NumberOfInquiries15: chr  "2" "2" "2" "2" ...
</code>```

R Windows (using Powershell xsl script calling .NET Xsl class, see here)

```<code>library(XML)

# COMMAND LINE CALL (NO INSTALLS NEEDED)
system(paste0('Powershell.exe -File',
              ' "C:\\Path\\To\\PowerShell\\Script.ps1"',
              ' "C:\\Path\\To\\Input.xml"',
              ' "C:\\Path\\To\\XSLT\\Script.xsl"',
              ' "C:\\Path\\To\\Output.xml"'))

# PARSE AND LOAD TO DF
doc <- xmlParse('Output.xml')
df <- xmlToDataFrame(nodes = getNodeSet(doc, "//Report"))
</code>```

Body:
So, I have large XML file with lots of reports. I created data example below to approximately show the size of xml and its structure:

x <- "<Report><Agreements><AgreementList /></Agreements><CIP><RecordList><Record><Date>2017-05-26T00:00:00</Date><Grade>2</Grade><ReasonsList><Reason>R<Description>local</Description></Reason></ReasonsList><Score>xxx</Score></Record><Record><Date>2017-04-30T00:00:00</Date><Grade>2</Grade><ReasonsList><Reason>R<Description/></Reason></ReasonsList><Score>xyx</Score></Record></RecordList></CIP><Individual><Contact><Email/></Contact><General><FirstName>MM</FirstName></General></Individual><Inquiries><InquiryList><Inquiry><DateOfInquiry>2017-03-19</DateOfInquiry><Reason>cc</Reason></Inquiry><Inquiry><DateOfInquiry>2016-10-14</DateOfInquiry><Reason>er</Reason></Inquiry></InquiryList><NumberOfInquiries>2</NumberOfInquiries></Inquiries></Report>"

x <- paste(rep(x, 1.5e+5), collapse = "")
x <- paste0("<R>", x, "</R>")
require(XML)
p <- xmlParse(x)
p <- xmlRoot(p)
p[[1]]

I would like to transform this data to data.frame, but the structure of XML isn't straightforward. Previously working with XMLs I created loop that for every report transforms its sub nodes to data.frame, but here (in this data) the sub node count is greater than 30 (didn't put all of them in the example), and the structure differs (List nodes can occur even 2 levels deep in XML).

So I have few questions:

1) I am sure that looping over reports isn't the best way to handle this. How should I approach this problem?

2) Can I somehow extract all the data of one report two one line of data.frame (recursively maybe)?

3) Or can I automatically create separate data.frames for each list object of XML?

Any help would be much appreciated.

Update:

Example of results could look like this:

Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   1 obs. of  17 variables:
 $ Record.1.Date                : chr "2017-05-26T00:00:00"
 $ Record.1.Grade               : num 2
 $ Record.1.Reason.1.Code       : chr "R"
 $ Record.1.Reason.1.Description: chr "local"
 $ Record.1.Score               : chr "xxx"
 $ Record.2.Date                : chr "2017-05-26T00:00:00"
 $ Record.2.Grade               : num 2
 $ Record.2.Reason.1.Code       : chr "R"
 $ Record.2.Reason.1.Description: chr "NA"
 $ Record.2.Score               : chr "xyx"
 $ Email.1                      : chr "NA"
 $ FirstName                    : chr "MM"
 $ Inquiry.1.DateOfInquiry      : POSIXct, format: "2017-03-19"
 $ Inquiry.1.Reason             : chr "cc"
 $ Inquiry.2.DateOfInquiry      : POSIXct, format: "2016-10-14"
 $ Inquiry.2.Reason             : chr "er"
 $ NumberOfInquiries            : num 2

, but as I mentioned previously, sub lists could also be in separate tables.

Body:
Because you mention, I would like to transform this data, consider XSLT, the special-purpose transformation language designed to restructure complex XML to various end-use structures. And in your case flattening any text holding nodes in XML which then can easily be imported with xmlToDataFrame(). While below uses xsltproc and .NET Xsl class, any external processor or language module (e.g., Python, Java, C#, VB, PHP) that supports XSLT 1.0 can work:

XSLT (save as .xsl file)

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="/R">
        <xsl:copy>
            <xsl:apply-templates select="Report"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Report">
        <xsl:copy>
            <xsl:apply-templates select="descendant::*[string-length(text())>0]"/>
        </xsl:copy>
    </xsl:template>

   <xsl:template match="*">
      <xsl:element name="{concat(local-name(), position())}">
      <xsl:value-of select="." />
      </xsl:element>
   </xsl:template>

</xsl:stylesheet>

XML Output (with numbered suffixes to avoid repeated column error)

<?xml version="1.0"?>
<R>
  <Report>
    <Date1>2017-05-26T00:00:00</Date1>
    <Grade2>2</Grade2>
    <Code3>R</Code3>
    <Description4>local</Description4>
    <Score5>xxx</Score5>
    <Date6>2017-04-30T00:00:00</Date6>
    <Grade7>2</Grade7>
    <Code8>R</Code8>
    <Score9>xyx</Score9>
    <FirstName10>MM</FirstName10>
    <DateOfInquiry11>2017-03-19</DateOfInquiry11>
    <Reason12>cc</Reason12>
    <DateOfInquiry13>2016-10-14</DateOfInquiry13>
    <Reason14>er</Reason14>
    <NumberOfInquiries15>2</NumberOfInquiries15>
  </Report>
</R>

R Mac/Linux Script (calling xsltproc, available package on unix machines)

library(XML)

setwd("/path/to/working/folder")

# COMMAND LINE CALL (INSTALL xsltproc IN TERMINAL)
system(paste("cd", getwd(), " && xsltproc -o Output.xml XSLTScript.xsl Input.xml"))

# PARSE AND LOAD TO DF
doc <- xmlParse('Output.xml')
df <- xmlToDataFrame(nodes = getNodeSet(doc, "//Report"))

str(df)
# 'data.frame': 6 obs. of  15 variables:
#  $ Date1              : chr  "2017-05-26T00:00:00" "2017-05-26T00:00:00" "2017-05-26T00:00:00" "2017-05-26T00:00:00" ...
#  $ Grade2             : chr  "2" "2" "2" "2" ...
#  $ Code3              : chr  "R" "R" "R" "R" ...
#  $ Description4       : chr  "local" "local" "local" "local" ...
#  $ Score5             : chr  "xxx" "xxx" "xxx" "xxx" ...
#  $ Date6              : chr  "2017-04-30T00:00:00" "2017-04-30T00:00:00" "2017-04-30T00:00:00" "2017-04-30T00:00:00" ...
#  $ Grade7             : chr  "2" "2" "2" "2" ...
#  $ Code8              : chr  "R" "R" "R" "R" ...
#  $ Score9             : chr  "xyx" "xyx" "xyx" "xyx" ...
#  $ FirstName10        : chr  "MM" "MM" "MM" "MM" ...
#  $ DateOfInquiry11    : chr  "2017-03-19" "2017-03-19" "2017-03-19" "2017-03-19" ...
#  $ Reason12           : chr  "cc" "cc" "cc" "cc" ...
#  $ DateOfInquiry13    : chr  "2016-10-14" "2016-10-14" "2016-10-14" "2016-10-14" ...
#  $ Reason14           : chr  "er" "er" "er" "er" ...
#  $ NumberOfInquiries15: chr  "2" "2" "2" "2" ...

R Windows (using Powershell xsl script calling .NET Xsl class, see here)

library(XML)

# COMMAND LINE CALL (NO INSTALLS NEEDED)
system(paste0('Powershell.exe -File',
              ' "C:\\Path\\To\\PowerShell\\Script.ps1"',
              ' "C:\\Path\\To\\Input.xml"',
              ' "C:\\Path\\To\\XSLT\\Script.xsl"',
              ' "C:\\Path\\To\\Output.xml"'))

# PARSE AND LOAD TO DF
doc <- xmlParse('Output.xml')
df <- xmlToDataFrame(nodes = getNodeSet(doc, "//Report"))


问:
Unable to upload file from servlet
I have written a jsp with bootstrap. In the <form> tag I am calling a servlet to upload a file, but the Part part = request.getPart("NewCandCV") doesn't seem to be fetching the file, since it keeps on throwing the NullPointerException when I try to call and method on part object like part.getName().

Any help would be highly appreciated.
Below is the whole code.

I cant understand what am I missing:

web.xml:

```<code>  <servlet>
        <servlet-name>Add New Candidate</servlet-name>
        <servlet-class>AddCandidate</servlet-class>

        <init-param>
            <param-name>file-upload-internal</param-name>
            <param-value>Resume/internal</param-value>
        </init-param>

        <init-param>
            <param-name>file-upload-external</param-name>
            <param-value>Resume/external</param-value>
        </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>Add New Candidate</servlet-name>
    <url-pattern>/Add_Candidate</url-pattern>
  </servlet-mapping>
</code>```

JSP:

```<code><div id="newProfileModal" class="modal fade" role="dialog">
          <div class="modal-dialog">

            <!-- Modal content-->
            <form method="post" action="Add_Candidate" enctype="multipart/form-data">
                <div class="form-group">
                    <div class="modal-content">
                      <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">×</button>
                        <div class="medium">
                            <h4 class="modal-title">Name Candidate</h4>
                        </div>
                      </div>
                      <div class="modal-body">
                          <label for="usr">Name:</label>
                          <input type="text" id="usr" class="form-control" name="NewCandName"></input>
                          <br/>
                          <label for="attachment">Attach CV</label>
                          <input id="attachment" name="NewCandCV" type="file" class="file-loading" />
                      </div>
                      <div class="modal-footer">
                        <button type="submit" class="btn btn-default">Add</button>
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                      </div>
                    </div>
                </div>
            </form>
          </div>
        </div>
</code>```

Servlet:

```<code>public class AddCandidate extends HttpServlet{

    private String intFilePath;
    private String extFilePath;

    public void init( ){
        intFilePath = getServletContext().getInitParameter("file-upload-internal");
        extFilePath = getServletContext().getInitParameter("file-upload-external");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();

        String name = request.getParameter("NewCandName");
        Part part = request.getPart("NewCandCV");
        String CV = part.getName();
        try
        {
            String path="";

            if(profile.equals("TCS Internal"))
                path = intFilePath;
            else if(profile.equals("External"))
                path = extFilePath;

            // gets absolute path of the web application
            String appPath = request.getServletContext().getRealPath("");
            // constructs path of the directory to save uploaded file
            String savePath = appPath + "/" + path;

            // creates the save directory if it does not exists
            File fileSaveDir = new File(savePath);
            if (!fileSaveDir.exists()) {
                fileSaveDir.mkdir();
            }

            String fileName = "CV_"+name+"_"+contact;
            part.write(savePath + File.separator + fileName);
       /*     for (Part part : request.getParts()) {
                tmp=part;
                String fileName = "CV_"+name+"_"+contact;
                part.write(savePath + File.separator + fileName);
            } */

        }
        catch(Exception e){
            writer.println("<html><head></head>"
                    +"<body>Exception!!"
                    +e+"</body></html>");
        }

        writer.println("<html><head></head>"
                +"<body>Upload completed</body></html>");
    }
}
</code>```

答: You need to annotate your servlet to indicate support for multipart formdata with MultipartConfig</p>

Title: Unable to upload file from servlet

Body:
I have written a jsp with bootstrap. In the <form> tag I am calling a servlet to upload a file, but the Part part = request.getPart("NewCandCV") doesn't seem to be fetching the file, since it keeps on throwing the NullPointerException when I try to call and method on part object like part.getName().

Any help would be highly appreciated.
Below is the whole code.

I cant understand what am I missing:

web.xml:

  <servlet>
        <servlet-name>Add New Candidate</servlet-name>
        <servlet-class>AddCandidate</servlet-class>

        <init-param>
            <param-name>file-upload-internal</param-name>
            <param-value>Resume/internal</param-value>
        </init-param>

        <init-param>
            <param-name>file-upload-external</param-name>
            <param-value>Resume/external</param-value>
        </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>Add New Candidate</servlet-name>
    <url-pattern>/Add_Candidate</url-pattern>
  </servlet-mapping>

JSP:

            <form method="post" action="Add_Candidate" enctype="multipart/form-data">

                        <button type="button" class="close" data-dismiss="modal">×</button>

Name Candidate

                          Name:
                          <input type="text" id="usr" class="form-control" name="NewCandName"></input>

                          Attach CV
                          <input id="attachment" name="NewCandCV" type="file" class="file-loading" />

                        <button type="submit" class="btn btn-default">Add</button>
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            </form>

Servlet:

public class AddCandidate extends HttpServlet{

    private String intFilePath;
    private String extFilePath;

    public void init( ){
        intFilePath = getServletContext().getInitParameter("file-upload-internal");
        extFilePath = getServletContext().getInitParameter("file-upload-external");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();

        String name = request.getParameter("NewCandName");
        Part part = request.getPart("NewCandCV");
        String CV = part.getName();
        try
        {
            String path="";

            if(profile.equals("TCS Internal"))
                path = intFilePath;
            else if(profile.equals("External"))
                path = extFilePath;

            // gets absolute path of the web application
            String appPath = request.getServletContext().getRealPath("");
            // constructs path of the directory to save uploaded file
            String savePath = appPath + "/" + path;

            // creates the save directory if it does not exists
            File fileSaveDir = new File(savePath);
            if (!fileSaveDir.exists()) {
                fileSaveDir.mkdir();
            }

            String fileName = "CV_"+name+"_"+contact;
            part.write(savePath + File.separator + fileName);
       /*     for (Part part : request.getParts()) {
                tmp=part;
                String fileName = "CV_"+name+"_"+contact;
                part.write(savePath + File.separator + fileName);
            } */

        }
        catch(Exception e){
            writer.println(""
                    +"Exception!!"
                    +e+"");
        }

        writer.println(""
                +"Upload completed");
    }
}


问:
AWS volumes and AMI without a specific tag
To find list of instances without tag "Environment", I used the following command.

```<code>aws ec2 describe-instances --query 'Reservations[?Instances[?length(Tags[?Key=='Environment']) == `0`]].Instances[].InstanceId' --output text
</code>```

Now, how to find the list of volume-Id doesn't have a specific tag? Suppose some of my volumes have tag "Environment". When executing a command the result should contain volume-Ids without the tag Environment.

Similarly, I need to list the AMI and snapshot also.

答:
It would be rather challenging to fit this into an AWS Command-Line Interface (CLI) command.

Instead, use this Python script:

```<code>import boto3
client = boto3.client('ec2', region_name='ap-southeast-2')

response = client.describe_volumes()

# Find volumes that do not have an 'Environment' Tag
for volume in response['Volumes']:
  if 'Environment' not in [tag['Key'] for tag in volume['Tags']]:
    print volume['VolumeId']
</code>```

Body:
To find list of instances without tag "Environment", I used the following command.

aws ec2 describe-instances --query 'Reservations[?Instances[?length(Tags[?Key=='Environment']) == `0`]].Instances[].InstanceId' --output text

Now, how to find the list of volume-Id doesn't have a specific tag? Suppose some of my volumes have tag "Environment". When executing a command the result should contain volume-Ids without the tag Environment.

Similarly, I need to list the AMI and snapshot also.

Body:
It would be rather challenging to fit this into an AWS Command-Line Interface (CLI) command.

Instead, use this Python script:

import boto3
client = boto3.client('ec2', region_name='ap-southeast-2')

response = client.describe_volumes()

# Find volumes that do not have an 'Environment' Tag
for volume in response['Volumes']:
  if 'Environment' not in [tag['Key'] for tag in volume['Tags']]:
    print volume['VolumeId']


问:
How to apply CSS changes in every posts (every posts ID)
I want to hide the side bar and stretch the content box to full width to all posts from my WP blog. To individual posts that's what I'm doing, and it's working fine:

```<code>.postid-72 #main-sidebar {
display: none;
}
.postid-72 #main-content {
width: 100%;
}
</code>```

But I'm looking for some way to apply this changes to all my blog posts, something hypothetical like this:

```<code>.postid-**every id posts** #main-sidebar {
display: none;
}
.postid-**every id posts** #main-content {
width: 100%;
}
</code>```

I know that is possible to do something like this, which isn't usefull for me:

```<code>.postid-72, .postid-53, .postid-115 #main-sidebar {
display: none;
}
</code>```

答:
add a common class to all post like stretch-contentand use css like

```<code>.stretch-content #main-sidebar {
display: none;
}
.stretch-content #main-content {
width: 100%;
}
</code>```

Body:
I want to hide the side bar and stretch the content box to full width to all posts from my WP blog. To individual posts that's what I'm doing, and it's working fine:

.postid-72 #main-sidebar {
display: none;
}
.postid-72 #main-content {
width: 100%;
}

But I'm looking for some way to apply this changes to all my blog posts, something hypothetical like this:

.postid-**every id posts** #main-sidebar {
display: none;
}
.postid-**every id posts** #main-content {
width: 100%;
}

I know that is possible to do something like this, which isn't usefull for me:

.postid-72, .postid-53, .postid-115 #main-sidebar {
display: none;
}

Body:
add a common class to all post like stretch-contentand use css like

.stretch-content #main-sidebar {
display: none;
}
.stretch-content #main-content {
width: 100%;
}


问:
Having a issue out putting a string from a array index for a random output
Having a issue outputting a string from a array index for a random sentence  output. The hashmap is fine grabs how many of each string in the array however once it has all the info give a int display of the items. Objective is to have user select form items after that select options for Subject - Verb - Adjective - Object - Adverb then do a random output.
also for some reason when it hit the adverb it is having the user input info before stated.</p>

```<code>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package shoutbox;
import java.util.HashMap;
import java.util.Random;
import java.util.Scanner;
/**
 *
 * @author alden
 */
public class Shoutbox {

    /**
     *
     */
    public int t;
    public int o;
    public int r;
    public int q;
    public int p;
public String subjectArray[]=new String[t]; // Intilized array by the size of int y
public String verbArray[]=new String[o];
public String adjectiveArray[]=new String[r];
public String objectArray[]=new String[q];
public String adverbArray[]=new String[p];

public Shoutbox(){

}

    public static void main(String[] args) {
        // TODO code application logic here
        Boolean repeat = true;
        System.out.println(" Please select a option");

        HashMap <Integer, String> map = new HashMap<>(); // starts the hashmap

        map.put(0,"Are you new to programming");
        map.put(1, "I think java is a good start");
        map.put(2, "It is easy to learn");
        map.put(3, "You tube is a great resource");
        map.put(4,"Most people start with hello world");
        map.put(5,"After this you learn Scanners and getter and setters");
        map.put(6,"Next is encapsulation");
        map.put(7,"After this is loops");
        map.put(8,"Once you get loops work on arrays");
        map.put(9,"Next you should look at objects");

        map.entrySet().forEach((entry) -> {
            // for loop for the display of has map
            int key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key + " : " + value);
        });
char y;
while (repeat = true){  // gives options for y or n
System.out.println("Please enter a value");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String s = map.get(n);
System.out.println(s);

System.out.println("Would you like to enter another value. y/n");
y = in.next().charAt(0);

            switch (y) {
                case 'y':
                    repeat = true;
                    break;
                case 'Y':
                    repeat = true;
                    break;
                default:
                    repeat = false;
                    break;
            }
break;

}
String input1;

boolean loop = false;
Scanner in = new Scanner(System.in);

System.out.printf("How many subjects are there?");
int t = in.nextInt();
String subjectArray[]=new String[t];

System.out.printf("How many verbs are there?");
int o = in.nextInt();
String verbArray[]=new String[o];

System.out.printf("How many adjective are there?");
int q = in.nextInt();
String adjectiveArray[]=new String[q];

System.out.printf("How many adjective are there?");
int r = in.nextInt();
String objectArray[]=new String[r];

System.out.printf("How many adverbs are there?");
int p = in.nextInt();
String adverbArray[]=new String[p];

     Scanner input = new Scanner(System.in);  // aanother scanner for more input

for(int subjectCount=0;subjectCount<t;subjectCount++){
subjectArray[subjectCount]= input.next();
    int tempSub= subjectCount+1;
System.out.printf("Subject "+tempSub);
 // Assigned users value to array
}
int subjectIndex;
Random randt = new Random();
subjectIndex = randt.nextInt(+1);//for loop
// random word
//Stores and finds random subject
//System.out.println(subjectArray[subjectIndex]);

for(int verbCount=0;verbCount<o;verbCount++){
verbArray[verbCount]= input.next(); // Assigned users value to array
    int tempVerb= verbCount+1;
    System.out.printf("verb "+tempVerb);
    }
int verbIndex;
Random rando = new Random();
verbIndex = rando.nextInt(o); // random word
//

for(int adjectiveCount=0;adjectiveCount<r;adjectiveCount++){
adjectiveArray[adjectiveCount]= input.next(); // Assigned users value to array
    int tempAdj= adjectiveCount+1;
    System.out.printf("Adjective " + tempAdj);
}
int adjectiveIndex;
Random randq = new Random();
adjectiveIndex = randq.nextInt(r); // random word
//

for(int objectCount=0;objectCount<q;objectCount++){
objectArray[objectCount]= input.next(); // Assigned users value to array
    int tempObj= objectCount+1;
    System.out.printf("Object "+ tempObj);
}
int objectIndex;
Random randr = new Random();
objectIndex = randr.nextInt(q); // random word
//

for(int adverbCount=0;adverbCount<p;adverbCount++){
adverbArray[adverbCount]= input.next(); // Assigned users value to array
    int tempAd= adverbCount+1;
    System.out.printf("Adverb "+tempAd);
}
int adverbIndex;
Random randp = new Random();
adverbIndex = randp.nextInt(p);

input1 = (subjectIndex + " " + verbIndex +" "+ adjectiveIndex +" "+ objectIndex +" "+ adverbIndex); // adds all items togather for loop
while(loop = true){
System.out.println(input1);
break;
}

}}
</code>```

答:
Problem:

In a couple of places you're writing while (something = true) {... break; }.  Obviously, you meant for the loop to run until something became equal to true, but instead you discovered that the loop was running forever and so added the quick fix of break; at the end.

The problem is that = is an assignment; the equality test is ==.  You would have been OK if you had written:

```<code> while (something == true)  { ... }
</code>```

You could also write the shorter version

```<code>while (something) { ... }
</code>```

Because something is a boolean, and thus already has its own value of true or false value, you don't need to test it against true (or false) to obtain the boolean condition your loop needs.  It's not actually wrong to write something == true or something == false, just more verbose than necessary.

Suggestions:

Your basic logic for picking words at random to form a sentence is basically good, but it needs to be untangled from the process of obtaining the word lists from the user, especially if you want to use that last loop to generate multiple random sentences.

Having obtained the random indices for the different word classes, you'll want to extract the corresponding words from the word lists to actually build the sentence; right now you're just printing out a "sentence" consisting of the indices themselves.

You don't need multiple Random objects; it's not particularly harmful, just extra unnecessary lines of code and a few wasted CPU cycles.

Body:
Having a issue outputting a string from a array index for a random sentence  output. The hashmap is fine grabs how many of each string in the array however once it has all the info give a int display of the items. Objective is to have user select form items after that select options for Subject - Verb - Adjective - Object - Adverb then do a random output.
also for some reason when it hit the adverb it is having the user input info before stated.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package shoutbox;
import java.util.HashMap;
import java.util.Random;
import java.util.Scanner;
/**
 *
 * @author alden
 */
public class Shoutbox {

    /**
     *
     */
    public int t;
    public int o;
    public int r;
    public int q;
    public int p;
public String subjectArray[]=new String[t]; // Intilized array by the size of int y
public String verbArray[]=new String[o];
public String adjectiveArray[]=new String[r];
public String objectArray[]=new String[q];
public String adverbArray[]=new String[p];

public Shoutbox(){

}

    public static void main(String[] args) {
        // TODO code application logic here
        Boolean repeat = true;
        System.out.println(" Please select a option");

        HashMap <Integer, String> map = new HashMap<>(); // starts the hashmap

        map.put(0,"Are you new to programming");
        map.put(1, "I think java is a good start");
        map.put(2, "It is easy to learn");
        map.put(3, "You tube is a great resource");
        map.put(4,"Most people start with hello world");
        map.put(5,"After this you learn Scanners and getter and setters");
        map.put(6,"Next is encapsulation");
        map.put(7,"After this is loops");
        map.put(8,"Once you get loops work on arrays");
        map.put(9,"Next you should look at objects");

        map.entrySet().forEach((entry) -> {
            // for loop for the display of has map
            int key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key + " : " + value);
        });
char y;
while (repeat = true){  // gives options for y or n
System.out.println("Please enter a value");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String s = map.get(n);
System.out.println(s);

System.out.println("Would you like to enter another value. y/n");
y = in.next().charAt(0);

            switch (y) {
                case 'y':
                    repeat = true;
                    break;
                case 'Y':
                    repeat = true;
                    break;
                default:
                    repeat = false;
                    break;
            }
break;

}
String input1;

boolean loop = false;
Scanner in = new Scanner(System.in);

System.out.printf("How many subjects are there?");
int t = in.nextInt();
String subjectArray[]=new String[t];

System.out.printf("How many verbs are there?");
int o = in.nextInt();
String verbArray[]=new String[o];

System.out.printf("How many adjective are there?");
int q = in.nextInt();
String adjectiveArray[]=new String[q];

System.out.printf("How many adjective are there?");
int r = in.nextInt();
String objectArray[]=new String[r];

System.out.printf("How many adverbs are there?");
int p = in.nextInt();
String adverbArray[]=new String[p];

     Scanner input = new Scanner(System.in);  // aanother scanner for more input

for(int subjectCount=0;subjectCount<t;subjectCount++){
subjectArray[subjectCount]= input.next();
    int tempSub= subjectCount+1;
System.out.printf("Subject "+tempSub);
 // Assigned users value to array
}
int subjectIndex;
Random randt = new Random();
subjectIndex = randt.nextInt(+1);//for loop
// random word
//Stores and finds random subject
//System.out.println(subjectArray[subjectIndex]);

for(int verbCount=0;verbCount<o;verbCount++){
verbArray[verbCount]= input.next(); // Assigned users value to array
    int tempVerb= verbCount+1;
    System.out.printf("verb "+tempVerb);
    }
int verbIndex;
Random rando = new Random();
verbIndex = rando.nextInt(o); // random word
//

for(int adjectiveCount=0;adjectiveCount<r;adjectiveCount++){
adjectiveArray[adjectiveCount]= input.next(); // Assigned users value to array
    int tempAdj= adjectiveCount+1;
    System.out.printf("Adjective " + tempAdj);
}
int adjectiveIndex;
Random randq = new Random();
adjectiveIndex = randq.nextInt(r); // random word
//

for(int objectCount=0;objectCount<q;objectCount++){
objectArray[objectCount]= input.next(); // Assigned users value to array
    int tempObj= objectCount+1;
    System.out.printf("Object "+ tempObj);
}
int objectIndex;
Random randr = new Random();
objectIndex = randr.nextInt(q); // random word
//

for(int adverbCount=0;adverbCount<p;adverbCount++){
adverbArray[adverbCount]= input.next(); // Assigned users value to array
    int tempAd= adverbCount+1;
    System.out.printf("Adverb "+tempAd);
}
int adverbIndex;
Random randp = new Random();
adverbIndex = randp.nextInt(p);

input1 = (subjectIndex + " " + verbIndex +" "+ adjectiveIndex +" "+ objectIndex +" "+ adverbIndex); // adds all items togather for loop
while(loop = true){
System.out.println(input1);
break;
}

}}

Body:
Problem:

In a couple of places you're writing while (something = true) {... break; }.  Obviously, you meant for the loop to run until something became equal to true, but instead you discovered that the loop was running forever and so added the quick fix of break; at the end.

The problem is that = is an assignment; the equality test is ==.  You would have been OK if you had written:

 while (something == true)  { ... }

You could also write the shorter version

while (something) { ... }

Because something is a boolean, and thus already has its own value of true or false value, you don't need to test it against true (or false) to obtain the boolean condition your loop needs.  It's not actually wrong to write something == true or something == false, just more verbose than necessary.

Suggestions:

Your basic logic for picking words at random to form a sentence is basically good, but it needs to be untangled from the process of obtaining the word lists from the user, especially if you want to use that last loop to generate multiple random sentences.

Having obtained the random indices for the different word classes, you'll want to extract the corresponding words from the word lists to actually build the sentence; right now you're just printing out a "sentence" consisting of the indices themselves.

You don't need multiple Random objects; it's not particularly harmful, just extra unnecessary lines of code and a few wasted CPU cycles.


问:
Disable Page Scroll for "href"
I'm showing 4 different tables in a "div" that has a linked list, ie the table shown changes depending on which link in the list is clicked.

When the user clicks on a link though, the page automatically scrolls down to the top of the "div". I want to disable this page movement, is there a way to do this?

Basically, I want the user to be able to choose the table they want to view but don't want the page to automatically scroll to the top of the "div".

```<code><ul style="list-style-type: none; margin: 0; padding: 0; overflow: hidden;">
<li style="list-style-type: none; float: left;"><a style="color: white; font-size: 100%;" href="#MB"><strong>ONE</strong></a></li>
<li style="list-style-type: none; float: left;"><a style="color: white; font-size: 100%;" href="#DS"><strong>TWO</strong></a></li>
<li style="list-style-type: none; float: left;"><a style="color: white; font-size: 100%;" href="#AF"><strong>THREE</strong></a></li>
<li style="list-style-type: none; float: left;"><a style="color: white; font-size: 100%;" href="#DT" ><strong>FOUR</strong></a></li>
</code>```

```<code><div style="width: 100%; float: right; overflow: hidden;">
<div style="white-space: nowrap;  width: 400%;">
<div id="MB" style="vertical-align:top;display: inline-block; width: 25%;">[table id=28/]</div>
<div id="DS" style="vertical-align:top;display: inline-block; width: 25%;">[table id=29/]</div>
<div id="AF" style="vertical-align:top;display: inline-block; width: 25%;">[table id=35/]</div>
<div id="DT" style="vertical-align:top;display: inline-block; width: 25%;">[table id=36/]</div>
</div>
</div>
</code>```

答:
The easiest option here may be just to use different div IDs.

You can use Javascript to disable or override the browser's default scroll behavior.

Title: Disable Page Scroll for "href"

Body:
I'm showing 4 different tables in a "div" that has a linked list, ie the table shown changes depending on which link in the list is clicked.

When the user clicks on a link though, the page automatically scrolls down to the top of the "div". I want to disable this page movement, is there a way to do this?

Basically, I want the user to be able to choose the table they want to view but don't want the page to automatically scroll to the top of the "div".

ONE

TWO

THREE

FOUR

[table id=28/]

[table id=29/]

[table id=35/]

[table id=36/]