问:
Zend 2 module.config with constraints with model/controller not retrieveing record
I am learning Zend 2 and have an issue i cannot seem to get around. Im sure it is something simple but i cannot pinpoint it. What i am trying to do is list records by state_id and also view a record from the list. Showing only one of the views. When i bring up /Blog/view/1 I get a message that says: Could not find row 0. This shows up with the current link and if i take the /1 off. So it is not even looking at the record number. I suspect it may be in routing but not sure. thanks
This is what i have:

```<code>Module.config
'router' => array(
  'routes' => array(
      'blog' => array(
        'type'    => 'Literal',
        'options' => array(
            'route'    => '/Blog',
            'defaults' => array (
              'module'     => 'Blog',
              'controller' => 'BlogController',
              'action'     => 'index',
            ), // defaults end
        ), // options end
        'may_terminate' => true,
            'child_routes' => array(
                'list' => array(
                    'type'    => 'segment',
                    'options' => array(
                        'route'    => '/list[/:state_id]',
                        'defaults' => array (
                            'action'     => 'list',
                        ), //defaults end
                        'constraints' => array(
                            'state_id'     => '[0-9]+',
                        ) // constraints end
                    ), // options end
                ), // view end
                'view' => array(
                    'type'    => 'segment',
                    'options' => array(
                        'route'    => '/view[/:post_id]',
                        'defaults' => array(
                            'action'     => 'view',
                        ), // defaults end
                        'constraints' => array(
                        'post_id'     => '[0-9]+',
                        ) // constraints end
                    ), // options end
                ),  // post end
            ) // child route end
        ), // blog end
    ) // routes end
) // router end

); // return array end
</code>```

Model:PostTable.php

```<code> public function getPosts($post_id)
 {
   $post_id  = (int) $post_id;
   $rowset = $this->tableGateway->select(array('post_id' => $post_id));
   $row = $rowset->current();
   if (!$row) {
       throw new \Exception("Could not find row $post_id");
   }
   return $row;
 }
</code>```

View:

```<code><h1><?php echo $this->escapeHtml($title); ?></h1>
<table class="table">
<tr>
   <th>Title</th>
   <th>View</th>
   <th>Comments</th>
   <th>Post Date</th>
</tr>
<?php foreach ($list as $posts) : ?>
<tr>
  <td><?php echo $this->escapeHtml($posts->post_title);?></td>
  <td><?php echo $this->escapeHtml($posts->num_views);?></td>
  <td><?php echo $this->escapeHtml($posts->num_comments);?></td>
  <td><?php echo $this->escapeHtml($posts->post_date);?></td>
</tr>
<?php endforeach; ?>
</code>```

Edit: 06/06/2016 Added View Action.

```<code> public function viewAction()
 {
    return new ViewModel(array(
     'list' => $this->getPostsTable()->getPosts(),
    ));
 }
</code>```

Also here is the getPostTable Action:

```<code> public function getPostsTable()
 {
     if (!$this->postsTable) {
        $sm = $this->getServiceLocator();
        $this->postsTable = $sm->get('Blog\Model\PostsTable');
     }
     return $this->postsTable;
 }
</code>```

答:
You need to provide the post ID into the getPosts() method in the controller. The following is according to your PostTable's getPosts() method.

```<code>public function viewAction()
{

    // Get the post ID from the route, /Blog/view/1
    $post_id = $this->params()->fromRoute('post_id');

    $list = $this->getPostsTable()->getPosts($post_id);

    $view = new ViewModel(array(
        'list' => $list,
    ));

    return $view;
}
</code>```

Body:
I am learning Zend 2 and have an issue i cannot seem to get around. Im sure it is something simple but i cannot pinpoint it. What i am trying to do is list records by state_id and also view a record from the list. Showing only one of the views. When i bring up /Blog/view/1 I get a message that says: Could not find row 0. This shows up with the current link and if i take the /1 off. So it is not even looking at the record number. I suspect it may be in routing but not sure. thanks
This is what i have:

Module.config
'router' => array(
  'routes' => array(
      'blog' => array(
        'type'    => 'Literal',
        'options' => array(
            'route'    => '/Blog',
            'defaults' => array (
              'module'     => 'Blog',
              'controller' => 'BlogController',
              'action'     => 'index',
            ), // defaults end
        ), // options end
        'may_terminate' => true,
            'child_routes' => array(
                'list' => array(
                    'type'    => 'segment',
                    'options' => array(
                        'route'    => '/list[/:state_id]',
                        'defaults' => array (
                            'action'     => 'list',
                        ), //defaults end
                        'constraints' => array(
                            'state_id'     => '[0-9]+',
                        ) // constraints end
                    ), // options end
                ), // view end
                'view' => array(
                    'type'    => 'segment',
                    'options' => array(
                        'route'    => '/view[/:post_id]',
                        'defaults' => array(
                            'action'     => 'view',
                        ), // defaults end
                        'constraints' => array(
                        'post_id'     => '[0-9]+',
                        ) // constraints end
                    ), // options end
                ),  // post end
            ) // child route end
        ), // blog end
    ) // routes end
) // router end

); // return array end

Model:PostTable.php

 public function getPosts($post_id)
 {
   $post_id  = (int) $post_id;
   $rowset = $this->tableGateway->select(array('post_id' => $post_id));
   $row = $rowset->current();
   if (!$row) {
       throw new \Exception("Could not find row $post_id");
   }
   return $row;
 }

View:

<?php echo $this->escapeHtml($title); ?>

   Title
   View
   Comments
   Post Date

<?php foreach ($list as $posts) : ?>

  <?php echo $this->escapeHtml($posts->post_title);?>
  <?php echo $this->escapeHtml($posts->num_views);?>
  <?php echo $this->escapeHtml($posts->num_comments);?>
  <?php echo $this->escapeHtml($posts->post_date);?>

<?php endforeach; ?>

Edit: 06/06/2016 Added View Action.

 public function viewAction()
 {
    return new ViewModel(array(
     'list' => $this->getPostsTable()->getPosts(),
    ));
 }

Also here is the getPostTable Action:

 public function getPostsTable()
 {
     if (!$this->postsTable) {
        $sm = $this->getServiceLocator();
        $this->postsTable = $sm->get('Blog\Model\PostsTable');
     }
     return $this->postsTable;
 }

Body:
You need to provide the post ID into the getPosts() method in the controller. The following is according to your PostTable's getPosts() method.

public function viewAction()
{

    // Get the post ID from the route, /Blog/view/1
    $post_id = $this->params()->fromRoute('post_id');

    $list = $this->getPostsTable()->getPosts($post_id);

    $view = new ViewModel(array(
        'list' => $list,
    ));

    return $view;
}


来源: stackexchange

问:
Finding memory violations/leaks
I have an application developed in VC 2008 (C++) which uses axis dlls, which use openssl dlls. And someone in the chain corrupts heap - a situation which ends up giving me "memory access violation" in my application in places where violation shouldn't/couldn't happen. So, someone in the chain axis-ssl corrupts something, but I cannot find who or what.

I tried using DevPartner's tool for memory leaks, but it finds no leaks - no anything.

How should I approach this problem? I looked over axis and ssl documentation a number of times, and implemented and checked all possible memory management issues and fixes, but to no avail.

Thank you very much!
Marin

答:
If you get the debug versions of the libraries, MSVC offers a debug malloc and free, as well as a debug new and delete. These contain things like overwrite detection.

http://msdn.microsoft.com/en-us/library/bebs9zyz.aspx

ContentLicense: CC BY-SA 2.5

Title: Finding memory violations/leaks


问:
QListWidget shifts when user selects an item
I have a peculiar issue. I have a QListWidget of 1000 QListWidgetItem.
I have a search textbox that triggers the following code whenever someone starts typing in it.

```<code>QRegExp regExSearch(searchText, Qt::CaseInsensitive, QRegExp::RegExp);
for (QListWidgetItem * currIt : allItems)
{
    currIt->setHidden( !(currIt->text().contains(regExSearch)) );
}
</code>```

What ends up being is once my search is performed, I will have a QListWidget with 600 items hidden, and 400 shown. Whenever I click on an item, the entire list just jumps down a few rows so that my selection is not even visible on the screen.

I've confirmed that it is the setHidden that seems to be causing it. If I just highlight found rows, without hiding/showing items, the selection does not cause the list to scroll down.

As such, I am wondering what am I missing? Which function to I call, to make sure that my QListWidget does not shift whenever I select an item?

Working example below:

```<code>#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QListWidget>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QListWidget * myListWidget = new QListWidget();

    for (int i = 0; i <= 1000; ++i)
    {
        QListWidgetItem * myItem = new QListWidgetItem(myListWidget);
        QString text("");
        for (int i = 0; i <= 100; ++i)
        {
            text.append("W");
        }
        myItem->setText(text + QString::number(i));
    }

    for (int i = 0; i <= 1000; ++i)
    {
        if (i%2)
            myListWidget->item(i)->setHidden(true);
    }

    setCentralWidget(myListWidget);
}

MainWindow::~MainWindow()
{
    delete ui;

}
</code>```

I have basically replicated and isolated the issue to being horizontal scrollbars. In my original application AND in this mcve, if you select an item (for example at index 314) the list will jump down. However, if I resize the list to not have horizontal scrollbars, then it does not shift.

So now that I know the issue is with having horizontal scrollbar, I am still not sure how to go about preventing the jump from happening.

UPDATE:

I have attempted to use SIGNAL-SLOT as such:

```<code>connect(myListWidget, SIGNAL(itemClicked(QListWidgetItem*)), myListWidget,
            SLOT(scrollToItem(const QListWidgetItem*,QAbstractItemView::ScrollHint)));
</code>```

I have also attempted to create my own slot where I explicitly specify that the item should be visible:

```<code>void MainWindow::scrollToItem(QListWidgetItem * item)
{
    std::cout << "Scrolling to item." << std::endl;
    myListWidget->scrollToItem(item, QAbstractItemView::EnsureVisible);
}
</code>```

However, it still jumps down and out of view! It does work if I set the ScrollHint to PositionAtCenter! BUT, from a user experience perspective, it is not a desired behaviour to have the list shift every time they click an item (even if that item is now in the center of the screen). Do I have any other options?

答:
Using QListWidget::scrollToItem you can rescroll your list so that your selected item is visible.

scrollToItem also takes a ScrollHint which allows you to specify where the QListWidget scrolls to (the default is EnsureVisible)

EnsureVisible: scroll to ensure that the item is visible.

PositionAtTop: scroll to position the item at the top of the viewport.

PositionAtBottom: scroll to position the item at the bottom of the viewport.

PositionAtCenter: scroll to position the item at the center of the viewport.

Full working example below:

```<code>#include <QApplication>
#include <QMainWindow>
#include <QVBoxLayout>
#include <QPushButton>
#include <QListWidget>
#include <QLineEdit>
#include <QRegExp>

int main(int argc, char** argv)
{
    QApplication* app = new QApplication(argc, argv);
    QMainWindow*  window = new QMainWindow();

    QWidget widget;
    QVBoxLayout layout(&widget);

    QLineEdit edit;
    layout.addWidget(&edit);

    QListWidget list;
    layout.addWidget(&list);

    for (int i = 0; i < 1000; ++i)
    {
        QListWidgetItem* item = new QListWidgetItem(QString::number(i));
        list.addItem(item);
    }

    QObject::connect(&edit, &QLineEdit::textChanged, [&](const QString& text)
        {
            QRegExp re(text, Qt::CaseInsensitive, QRegExp::RegExp);
            for(int i = 0; i < list.count(); ++i)
            {
                QListWidgetItem* item = list.item(i);
                item->setHidden(!(item->text().contains(re)));
            }

            auto selected = list.selectedItems();
            if (selected.size() == 1)
            {
                list.scrollToItem(selected.front());
            }
        });

    window->setCentralWidget(&widget);
    window->show();
    return app->exec();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a peculiar issue. I have a QListWidget of 1000 QListWidgetItem.
I have a search textbox that triggers the following code whenever someone starts typing in it.

QRegExp regExSearch(searchText, Qt::CaseInsensitive, QRegExp::RegExp);
for (QListWidgetItem * currIt : allItems)
{
    currIt->setHidden( !(currIt->text().contains(regExSearch)) );
}

What ends up being is once my search is performed, I will have a QListWidget with 600 items hidden, and 400 shown. Whenever I click on an item, the entire list just jumps down a few rows so that my selection is not even visible on the screen.

I've confirmed that it is the setHidden that seems to be causing it. If I just highlight found rows, without hiding/showing items, the selection does not cause the list to scroll down.

As such, I am wondering what am I missing? Which function to I call, to make sure that my QListWidget does not shift whenever I select an item?

Working example below:

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QListWidget>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QListWidget * myListWidget = new QListWidget();

    for (int i = 0; i <= 1000; ++i)
    {
        QListWidgetItem * myItem = new QListWidgetItem(myListWidget);
        QString text("");
        for (int i = 0; i <= 100; ++i)
        {
            text.append("W");
        }
        myItem->setText(text + QString::number(i));
    }

    for (int i = 0; i <= 1000; ++i)
    {
        if (i%2)
            myListWidget->item(i)->setHidden(true);
    }

    setCentralWidget(myListWidget);
}

MainWindow::~MainWindow()
{
    delete ui;

}

I have basically replicated and isolated the issue to being horizontal scrollbars. In my original application AND in this mcve, if you select an item (for example at index 314) the list will jump down. However, if I resize the list to not have horizontal scrollbars, then it does not shift.

So now that I know the issue is with having horizontal scrollbar, I am still not sure how to go about preventing the jump from happening.

UPDATE:

I have attempted to use SIGNAL-SLOT as such:

connect(myListWidget, SIGNAL(itemClicked(QListWidgetItem*)), myListWidget,
            SLOT(scrollToItem(const QListWidgetItem*,QAbstractItemView::ScrollHint)));

I have also attempted to create my own slot where I explicitly specify that the item should be visible:

void MainWindow::scrollToItem(QListWidgetItem * item)
{
    std::cout << "Scrolling to item." << std::endl;
    myListWidget->scrollToItem(item, QAbstractItemView::EnsureVisible);
}

However, it still jumps down and out of view! It does work if I set the ScrollHint to PositionAtCenter! BUT, from a user experience perspective, it is not a desired behaviour to have the list shift every time they click an item (even if that item is now in the center of the screen). Do I have any other options?

Body:
Using QListWidget::scrollToItem you can rescroll your list so that your selected item is visible.

scrollToItem also takes a ScrollHint which allows you to specify where the QListWidget scrolls to (the default is EnsureVisible)

EnsureVisible: scroll to ensure that the item is visible.

PositionAtTop: scroll to position the item at the top of the viewport.

PositionAtBottom: scroll to position the item at the bottom of the viewport.

PositionAtCenter: scroll to position the item at the center of the viewport.

Full working example below:

#include <QApplication>
#include <QMainWindow>
#include <QVBoxLayout>
#include <QPushButton>
#include <QListWidget>
#include <QLineEdit>
#include <QRegExp>

int main(int argc, char** argv)
{
    QApplication* app = new QApplication(argc, argv);
    QMainWindow*  window = new QMainWindow();

    QWidget widget;
    QVBoxLayout layout(&widget);

    QLineEdit edit;
    layout.addWidget(&edit);

    QListWidget list;
    layout.addWidget(&list);

    for (int i = 0; i < 1000; ++i)
    {
        QListWidgetItem* item = new QListWidgetItem(QString::number(i));
        list.addItem(item);
    }

    QObject::connect(&edit, &QLineEdit::textChanged, [&](const QString& text)
        {
            QRegExp re(text, Qt::CaseInsensitive, QRegExp::RegExp);
            for(int i = 0; i < list.count(); ++i)
            {
                QListWidgetItem* item = list.item(i);
                item->setHidden(!(item->text().contains(re)));
            }

            auto selected = list.selectedItems();
            if (selected.size() == 1)
            {
                list.scrollToItem(selected.front());
            }
        });

    window->setCentralWidget(&widget);
    window->show();
    return app->exec();
}


问:
Wordpress keeps redirecting to install-php after migration
Here's my situation.
I have followed the exact instructions on wordpress codex page about moving a site to another server.
Here are the step's i have taken.

Export a copy of my database

Make a new database in the new server

Import the database I exported earlier

Upload a copy of my Wordpress files via Ftp

Use this script to change all my local url's to new one's

Make changes to my wp-config.php file according to the new server(I did not forget table prefix. Although it has some uppercase characters in it )

And then when I try to open my site on the new location it just directs me to wp-admin/install.php
Now just to make the scenario clearer: The destination folder(on live server) is a sub directori in a public_html folder which already has another wordpress install inside it(I'm saying this just in case it should matter)

My .htaccess looks like this

```<code>    # BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /subDirectoryName/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /subDirectoryName/index.php [L]
</IfModule>

# END WordPress
</code>```

I have tried checking and repairing my tables via phpMyadmin but everything seems to be ok there and has no effect on the problem.

I also tried emptying the database on the live server and go through with the install. And it installs with no problems and everything works fine but, well I have no use for another clean install. But I think this at least rules out any trouble with wp-config file.
I'm using Wordpress Version 3.3.1

So I guess the big question I'm left with is:
Why isn't wordpress recognizing my Install after migration?

Any help much appreciated!

答:
There can be many causes to this problem.

My suggestion is to turn on WP_DEBUG in wp-config.php

```<code>define('WP_DEBUG', true);
</code>```

Body:
Here's my situation.
I have followed the exact instructions on wordpress codex page about moving a site to another server.
Here are the step's i have taken.

Export a copy of my database

Make a new database in the new server

Import the database I exported earlier

Upload a copy of my Wordpress files via Ftp

Use this script to change all my local url's to new one's

Make changes to my wp-config.php file according to the new server(I did not forget table prefix. Although it has some uppercase characters in it )

And then when I try to open my site on the new location it just directs me to wp-admin/install.php
Now just to make the scenario clearer: The destination folder(on live server) is a sub directori in a public_html folder which already has another wordpress install inside it(I'm saying this just in case it should matter)

My .htaccess looks like this

    # BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /subDirectoryName/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /subDirectoryName/index.php [L]
</IfModule>

# END WordPress

I have tried checking and repairing my tables via phpMyadmin but everything seems to be ok there and has no effect on the problem.

I also tried emptying the database on the live server and go through with the install. And it installs with no problems and everything works fine but, well I have no use for another clean install. But I think this at least rules out any trouble with wp-config file.
I'm using Wordpress Version 3.3.1

So I guess the big question I'm left with is:
Why isn't wordpress recognizing my Install after migration?

Any help much appreciated!

Body:
There can be many causes to this problem.

My suggestion is to turn on WP_DEBUG in wp-config.php

define('WP_DEBUG', true);


问:
How can I merge an existing jsonb field when upserting a record in Postgres?
Say I have a table on Postgres with a jsonb column containing {"a": 1, "b": 2}. Now I'd like to upsert a record with the same id and {"b": 10, "c": 20} as the jsonb column value.

Consequently, I'd like the jsonb field of the row to contain {"a": 1, "b": 10, "c": 20}. How can this be achieved?

答:
If concatenate 2 jsonb value, you achieve what you want, for example:

```<code>select '{"a": 1, "b": 2}'::jsonb  || '{"b": 10, "c": 20}'::jsonb
</code>```

produces: "{"a": 1, "b": 10, "c": 20}"

if both operands are objects with a common key field name, the value of the field in the result will just be the value from the right hand operand.

https://www.postgresql.org/docs/current/static/functions-json.html

Body:
If concatenate 2 jsonb value, you achieve what you want, for example:

select '{"a": 1, "b": 2}'::jsonb  || '{"b": 10, "c": 20}'::jsonb

produces: "{"a": 1, "b": 10, "c": 20}"

if both operands are objects with a common key field name, the value of the field in the result will just be the value from the right hand operand.

https://www.postgresql.org/docs/current/static/functions-json.html


问:
How to pass the query result to another method
I am querying

```<code>select empname
from employee
where empsal > 5000
</code>```

I got 3 rows (one column having 3 rows) and now I want to return this as string array.

And then I want the strings in the String array as separate string

答:
A more object oriented approach would be to loop through the resultset as proposed, but instead of assigning Strings in an array, create an object that encapsulates the data you are retrieving from the database. You are limiting yourself too much by simply storing Strings in an array.  Use an object that reflects your business needs / domain.

For example:

```<code>import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class Employee {

    private String name;
    private int salary;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

}

class DataAccessor {

    public List<Employee> getEmployees() {

        List<Employee> employeeList = new ArrayList<Employee>();

        String query = "select empname, empsal from employee where empsal>5000";

        // Create the database connection & statement somehow...
        Statement stmt = createStatement();

        try {
           ResultSet results = stmt.executeQuery(query);

           while (results.next()) {
               Employee employee = new Employee();
               employee.setName(results.getString(1));
               employee.setSalary(results.getInt(2));
               employeeList.add(employee);
           }
        } finally {
           stmt.close();
        }

        return employeeList;
    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am querying

select empname
from employee
where empsal > 5000

I got 3 rows (one column having 3 rows) and now I want to return this as string array.

And then I want the strings in the String array as separate string

Body:
A more object oriented approach would be to loop through the resultset as proposed, but instead of assigning Strings in an array, create an object that encapsulates the data you are retrieving from the database. You are limiting yourself too much by simply storing Strings in an array.  Use an object that reflects your business needs / domain.

For example:

import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class Employee {

    private String name;
    private int salary;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

}

class DataAccessor {

    public List<Employee> getEmployees() {

        List<Employee> employeeList = new ArrayList<Employee>();

        String query = "select empname, empsal from employee where empsal>5000";

        // Create the database connection & statement somehow...
        Statement stmt = createStatement();

        try {
           ResultSet results = stmt.executeQuery(query);

           while (results.next()) {
               Employee employee = new Employee();
               employee.setName(results.getString(1));
               employee.setSalary(results.getInt(2));
               employeeList.add(employee);
           }
        } finally {
           stmt.close();
        }

        return employeeList;
    }

}


问:
Jenkins - Get repos and branches as choice parameter
Hi I want to be able to grab a list of repos and present them as a selectable choice parameter for my pipeline.

What would be the best way to do this?

I would like to avoid having to run some sort of build that scrapes all repos and branches and creates a list in a xml or json file.

I also then want to be able to take all the branches in that repo and display them as another selectable choice parameter.

Edit:

Is there a way to add different type of project recognizers for a github organization. I don't want to use a jenkinsfile. Would rather look for a specific filename in the repo ("JenkinsProject.xml") as I have jenkinsFiles in other repos I dont want in this list.

Edit 2:

I found this sh command in jenkins.

resolveScm source: github(checkoutCredentialsId: 'SAME', id: '_', repoOwner: 'GITOWNER', repository: 'REPONAME', scanCredentialsId: 'CREDENTIALS'), targets: ['.']

Seems to find all the branches for the given repo. But how do I access the provided info as its only output to the console.

Edit 3

Okay So I think I will be using the github api. I can call this api call

GET /orgs/:org/repos

which returns all the repos in the given organization in json format. From here I can grab all the branches in a given repo with the api call

GET /repos/:owner/:repo/branches

Then I can checkout master of each repo. If master contains the "JenkinsProject.xml" I will save the repo name and branch names to a file which will be used as choice parameters hopefully.

Sadly I cant find another way to do this other than parsing through all the repos.

I will update this question again if this works out. Otherwise Im still open to more suggestions

Edit 4

I need help figuring out how to import this json file as parameters. Or maybe not use json. I might need to parse and update my buildscript then  commit it.

答:
So how I did this was using the api. I have a JenkinsProject.xml file inside of any of the games I want built with this job.

So I have a repo called JenkisDevOps with a jenkinsfile.

This jenkinsfile calls the github api and saves this to a file.

The api call to search for a file within an organization is

https://api.github.com/search/code?q=org:{ORGANIZATION_NAME}+filename:{FILENAME}

This will return every repo with this file in it. from here I can get each branch for these repos with.

https://api.github.com/repos/{ORGANIZATION_NAME}/{REPO_NAME}/branches

Then from here I save all this to a json file with

```<code>repos{
    repo:{
        name:"repoName",
        branches:{
            name:"branchname",
            name:"branchName2"
            ...
        }
    }
}
</code>```

The full script is here. I still need to figure out how to convert the saved json file to parameter options now.

```<code>pipeline {
agent any

stages {
stage ('Create Build Parameters'){
    steps{
        sh 'echo !---SETUP---!'
        git credentialsId: '', url: 'https://github.com/GenesisGaming/DevOpsJenkins.git'
        httpRequest acceptType: 'APPLICATION_JSON', authentication: '', consoleLogResponseBody: false, contentType: 'APPLICATION_JSON', outputFile: 'Repos.json', responseHandle: 'NONE', url: 'https://api.github.com/search/code?q=org:GenesisGaming+filename:Project.xml&per_page=100'
        readFile 'Repos.json'
        stash includes: '**', name: 'build'
        script {
            node{
                unstash 'build'
                env.WORKSPACE = pwd()
                def buildConfig = load "GenerateBuildSelections.Groovy"
                def repos = buildConfig.GetListOfRepos("${env.WORKSPACE}/Repos.json")

                def dataMap = new HashMap<String,List>()
                for(i = 0; i < repos.size(); i++){
                    def repoName = repos[i]
                    httpRequest acceptType: 'APPLICATION_JSON', authentication: '', consoleLogResponseBody: false, contentType: 'APPLICATION_JSON', outputFile: "branches_${repoName}.json", responseHandle: 'NONE', url: "https://api.github.com/repos/GenesisGaming/${repoName}/branches"
                    env.WORKSPACE = pwd()
                    def branches = buildConfig.GetListOfBranches("${env.WORKSPACE}/branches_${repoName}.json")
                    dataMap.put("${repoName}", "${branches}")

                }
                def builder = new groovy.json.JsonBuilder(dataMap)
                new File("/home/service/BuildSelectionOptions/options.json").write(builder.toPrettyString())
            }
        }
    }
}
}
post {
always {
    sh 'echo !---Cleanup---!'
    cleanWs()
}
}
}
</code>```

I used the active parameter plugin to get the selectable branches and repos.

For selectedGame( the repo ) I use a groovyscript choice wit hthis script.

```<code>#!/usr/bin/env groovy
import groovy.json.JsonSlurper

def inputFile = new File("/var/BuildOptions/options.json")
def InputJSON = new JsonSlurper().parseText(inputFile.text)
def output = []
InputJSON.each{key, val ->
    output.add(key)
}
return output;
</code>```

and then for the branch parameter I use a active reactive parameter choice with this groovy script and I reference the selectedGame parameter

```<code>#!/usr/bin/env groovy
import groovy.json.JsonSlurper

def inputFile = new File("/var/BuildOptions/options.json")
def InputJSON = new JsonSlurper().parseText(inputFile.text)
def output = []
InputJSON.each{key, val ->
String strOut = ""
if(selectedGame == key){
    val.each { outChar ->
        if(outChar == "[" || outChar == " ")
        {
            strOut = ""
        }
        else if(outChar == "]" || outChar == ",") {
            output.add(strOut)
            strOut = ""
        }
        else
        {
            strOut+= outChar
        }
    }
}
}

return output;
</code>```

Body:
So how I did this was using the api. I have a JenkinsProject.xml file inside of any of the games I want built with this job.

So I have a repo called JenkisDevOps with a jenkinsfile.

This jenkinsfile calls the github api and saves this to a file.

The api call to search for a file within an organization is

https://api.github.com/search/code?q=org:{ORGANIZATION_NAME}+filename:{FILENAME}

This will return every repo with this file in it. from here I can get each branch for these repos with.

https://api.github.com/repos/{ORGANIZATION_NAME}/{REPO_NAME}/branches

Then from here I save all this to a json file with

repos{
    repo:{
        name:"repoName",
        branches:{
            name:"branchname",
            name:"branchName2"
            ...
        }
    }
}

The full script is here. I still need to figure out how to convert the saved json file to parameter options now.

pipeline {
agent any

stages {
stage ('Create Build Parameters'){
    steps{
        sh 'echo !---SETUP---!'
        git credentialsId: '', url: 'https://github.com/GenesisGaming/DevOpsJenkins.git'
        httpRequest acceptType: 'APPLICATION_JSON', authentication: '', consoleLogResponseBody: false, contentType: 'APPLICATION_JSON', outputFile: 'Repos.json', responseHandle: 'NONE', url: 'https://api.github.com/search/code?q=org:GenesisGaming+filename:Project.xml&per_page=100'
        readFile 'Repos.json'
        stash includes: '**', name: 'build'
        script {
            node{
                unstash 'build'
                env.WORKSPACE = pwd()
                def buildConfig = load "GenerateBuildSelections.Groovy"
                def repos = buildConfig.GetListOfRepos("${env.WORKSPACE}/Repos.json")

                def dataMap = new HashMap<String,List>()
                for(i = 0; i < repos.size(); i++){
                    def repoName = repos[i]
                    httpRequest acceptType: 'APPLICATION_JSON', authentication: '', consoleLogResponseBody: false, contentType: 'APPLICATION_JSON', outputFile: "branches_${repoName}.json", responseHandle: 'NONE', url: "https://api.github.com/repos/GenesisGaming/${repoName}/branches"
                    env.WORKSPACE = pwd()
                    def branches = buildConfig.GetListOfBranches("${env.WORKSPACE}/branches_${repoName}.json")
                    dataMap.put("${repoName}", "${branches}")

                }
                def builder = new groovy.json.JsonBuilder(dataMap)
                new File("/home/service/BuildSelectionOptions/options.json").write(builder.toPrettyString())
            }
        }
    }
}
}
post {
always {
    sh 'echo !---Cleanup---!'
    cleanWs()
}
}
}

I used the active parameter plugin to get the selectable branches and repos.

For selectedGame( the repo ) I use a groovyscript choice wit hthis script.

#!/usr/bin/env groovy
import groovy.json.JsonSlurper

def inputFile = new File("/var/BuildOptions/options.json")
def InputJSON = new JsonSlurper().parseText(inputFile.text)
def output = []
InputJSON.each{key, val ->
    output.add(key)
}
return output;

and then for the branch parameter I use a active reactive parameter choice with this groovy script and I reference the selectedGame parameter

#!/usr/bin/env groovy
import groovy.json.JsonSlurper

def inputFile = new File("/var/BuildOptions/options.json")
def InputJSON = new JsonSlurper().parseText(inputFile.text)
def output = []
InputJSON.each{key, val ->
String strOut = ""
if(selectedGame == key){
    val.each { outChar ->
        if(outChar == "[" || outChar == " ")
        {
            strOut = ""
        }
        else if(outChar == "]" || outChar == ",") {
            output.add(strOut)
            strOut = ""
        }
        else
        {
            strOut+= outChar
        }
    }
}
}

return output;


问:
Custom deserializer for requests with content-type application/x-www-form-urlencoded in Spring Boot
I want to write a custom deserializer for some parameters in the requests of type application/x-www-form-urlencoded like used in case of requests of type application/json, with @JsonDeserialize(using = AbcDeserializer.class) annotation. I am using spring boot and Jackson, although I figured out that Jackson is not used here.

I tried figuring out how spring deserializes object by default. But couldn't find a way.

How does spring deserialize a request of type application/x-www-form-urlencoded by default?

Can I override this deserialization, preferrably by using some annotation on parameters that need special handling?

答:
My solution is based on custom ConditionalGenericConverter. It works with @ModelAttribute. Let's see whole implementation.

Application bootstrap example.

```<code>import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootApplication
public class DemoApplication {

    @Configuration
    public class WebConfig extends WebMvcConfigurerAdapter {

        @Override
        public void addFormatters(FormatterRegistry registry) {
            registry.addConverter(new Base64JsonToObjectConverter());
        }
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
</code>```

Here is custom annotation.

```<code>import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface Base64Encoded {
}
</code>```

Next we need implementation of the converter. As you can see, converter converts only String -> Object, where Object field must be annotated with Base64Encoded annotation.

```<code>import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.convert.ConversionFailedException;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Base64;
import java.util.Collections;
import java.util.Set;

@Component
public class Base64JsonToObjectConverter implements ConditionalGenericConverter {

    private final ObjectMapper objectMapper;
    private final Base64.Decoder decoder;

    public Base64JsonToObjectConverter() {
        this.objectMapper = new ObjectMapper();
        this.decoder = Base64.getDecoder();
    }

    @Override
    public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
        return targetType.hasAnnotation(Base64Encoded.class);
    }

    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        return Collections.singleton(new ConvertiblePair(String.class, Object.class));
    }

    @Override
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        if (source == null) {
            return null;
        }
        String string = (String) source;

        try {
            byte[] decodedValue = this.decoder.decode(string);

            return this.objectMapper.readValue(decodedValue, targetType.getType());
        } catch (IllegalArgumentException | IOException e) {
            throw new ConversionFailedException(sourceType, targetType, source, e);
        }
    }
}
</code>```

Here is an example of POJO (see the annotated field) and REST controller.

```<code>import com.example.demo.Base64Encoded;

public class MyRequest {

    private String varA;

    @Base64Encoded
    private B varB;

    public String getVarA() {
        return varA;
    }

    public void setVarA(String varA) {
        this.varA = varA;
    }

    public B getVarB() {
        return varB;
    }

    public void setVarB(B varB) {
        this.varB = varB;
    }
}
</code>```

import com.example.demo.domain.MyRequest;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

    @RequestMapping(path = "/test", method = RequestMethod.POST)
    public MyRequest test(@ModelAttribute MyRequest myRequest) {
        return myRequest;
    }
}
```

Body:
My solution is based on custom ConditionalGenericConverter. It works with @ModelAttribute. Let's see whole implementation.

Application bootstrap example.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootApplication
public class DemoApplication {

    @Configuration
    public class WebConfig extends WebMvcConfigurerAdapter {

        @Override
        public void addFormatters(FormatterRegistry registry) {
            registry.addConverter(new Base64JsonToObjectConverter());
        }
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Here is custom annotation.

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface Base64Encoded {
}

Next we need implementation of the converter. As you can see, converter converts only String -> Object, where Object field must be annotated with Base64Encoded annotation.

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.convert.ConversionFailedException;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Base64;
import java.util.Collections;
import java.util.Set;

@Component
public class Base64JsonToObjectConverter implements ConditionalGenericConverter {

    private final ObjectMapper objectMapper;
    private final Base64.Decoder decoder;

    public Base64JsonToObjectConverter() {
        this.objectMapper = new ObjectMapper();
        this.decoder = Base64.getDecoder();
    }

    @Override
    public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
        return targetType.hasAnnotation(Base64Encoded.class);
    }

    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        return Collections.singleton(new ConvertiblePair(String.class, Object.class));
    }

    @Override
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        if (source == null) {
            return null;
        }
        String string = (String) source;

        try {
            byte[] decodedValue = this.decoder.decode(string);

            return this.objectMapper.readValue(decodedValue, targetType.getType());
        } catch (IllegalArgumentException | IOException e) {
            throw new ConversionFailedException(sourceType, targetType, source, e);
        }
    }
}

Here is an example of POJO (see the annotated field) and REST controller.

import com.example.demo.Base64Encoded;

public class MyRequest {

    private String varA;

    @Base64Encoded
    private B varB;

    public String getVarA() {
        return varA;
    }

    public void setVarA(String varA) {
        this.varA = varA;
    }

    public B getVarB() {
        return varB;
    }

    public void setVarB(B varB) {
        this.varB = varB;
    }
}

import com.example.demo.domain.MyRequest;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

    @RequestMapping(path = "/test", method = RequestMethod.POST)
    public MyRequest test(@ModelAttribute MyRequest myRequest) {
        return myRequest;
    }
}


问:
What type of data that stored in sensor after converting an audio signal into digital (ADC)
Please excuse my lack of knowledge but I tried to search for an answer for couple days and I wasn't able to figure this out.

I'm trying to do a simulation for acoustic sensor (mica2) that sense audio signal and do some feature extraction, etc.
In matlab, when I read an audio file (ex. using readaudio) it will give me a normalised values between -1 and 1 that represents that amplitude of the signal and then i do the feature extraction using these values.

However, now I'm trying to simulate the sensor using Avrora and using C implementation, so, I represented the sample values as float numbers but I'm not sure if that is correct.

So, basically, my questions are:

How sensors store the signal after A/D conversion? I mean the digital signal sample values (an array of float or integer numbers?) and are they represent the amplitude of the signal?

Can I do the feature extraction directly on the digital signal?

I assumed that I have an array of size 4000 (because sensors has 4kb RAM) that stored a float numbers that represent the signal samples. Is that correct?

答:
read up on PCM - pulse code modulation which is the fundamental raw audio format ... basically audio is just a curve typically varying from -1 to +1 with silence as a zero signal ... this digital signal must get stored into 8 bit bytes ... greater audio fidelity means greater number of bytes per point on this audio curve ... one byte ( 8 bits ) by definition offers only 2^8 distinct values == 256 different values to get spread from -1 to +1 ... CD quality audio uses two bytes ( 16 bit ) which gives you 2^16 different values spread from -1 to +1 ... 24 bit and 32 bit audio exist yet same benefits there ... so yes your digital audio curve is represented by integers (16 bit signed ints, or unsigned ints if you shift your data from -1 to +1 to a spread of 0 to +1)

feature extraction :  well you are dealing with a time series curve however there is an entire subfield when human perception is involved ... too much there for a short SO question

what is Avrora ?  are you spelling it correctly ?

you mention 4k of memory ... do the math :   44.1khz sample rate  this gives you just a fraction of a second of audio so that buffer is populated then immediately transferred down the wire in preparation for next set of samples ... a point on the audio curve is one sample ... quality is determined by two factors :  (1) how many samples per second ( sample rate ) typically 44.1khz and (2) resolution (number of storage bits) allocated to store the audio curve height (bit depth) typically 16 bits ...

any sensor simply generates a series of sample measurements of the audio curve ... each sample represents the height of the audio curve as it varies from say -1 to +1 ... typically a new sample is performed 44,100 times per second ... so for one second of recording you have 44,100 numbers ... each sample is a single measurement which outputs a single number typically integers the range of integers is determined by sensor bit depth ...

if the curve varies from -1 to +1 so will your sample values ... to represent this in digital format we must understand the notion of storage capacity of bits ... lets say we have a one bit sensor (not your 10 bit sensor) ... a one bit sensor by definition can only output two distinct values :  0 or 1 why only two values ? because one bit has 2^1 possible values available  ... a two bit sensor can give you 4 distinct values : 0 1 2 3 because 2^2 == 4 ... a 3 bit sensor offers 8 distinct values since 2^3 is 8 ... now you have a 10 bit sensor then it can output 2^10 distinct values ... remember what is getting measured here :  height of the audio curve ...

if we have a 10 bit sensor a given sample measurement will be one of 2^10 distinct possible values, since 2^10 == 1024 so possible sample values would range from 0, 1,2 ... up to 1023 [ from 0 to (2^n - 1)] ...

For simplicity lets stick to unsigned integers ( all positive from 0 on up) ... if your audio curve samples vary from -1 to +1 then to represent that range as unsigned integers just add 1 to the sample and divide by 2 ... (SAMPLE + 1)/2 which will output values from 0 to +1 instead of -1 to +1 ...

To quote your comment :  "if my sensor use 10 bit ADC, i will get a vector of values between -1 and 1, and i'll get different 1024 values?"

Answer : possibly but not likely ... it depends on the input audio signal ... one sample will generate one integer in a range of possible values from 0 to 1023 ... to output 1024 different values this would require 1024 samples each with a different value meaning the audio curve change in height would have to vary in lock step with each new sample and the audio curve would have to vary across its entire range of -1 to +1, or 0 to +1 (what the range actually is can be ignored since its always normalized to an easy to use range -1 to +1 or 0 to +1, or whatever you like)

Even though you have a 10 bit sensor, it is likely stored using two bytes (consuming 16 bits) which makes the code simpler yet less efficient use of storage.  It is possible to store 10 bit data into a 4,000 byte buffer giving you 400 samples however that would be computationally slower using more complex code logic.  So if it does use two bytes (16 bits) of storage for each 10 bit sample, your 4000 byte buffer would hold 2000 samples of single channel audio


问:
PHP code not inserting into MySQL database
I double checked my code compared to the book and I'm sure I typed the code in correctly. The page loads, the errors display if I leave a field blank or if the password and confirm password fields don't match. However, if I complete the form correctly and submit, the MySQL database doesn't get the information passed to it. The "Registered!" and login page doesn't show up either. I checked the MySQL database through Ubuntu directly and the users table is still empty (Empty set (0.00 sec)). phpMyAdmin also returns empty, "MySQL returned an empty result set (i.e. zero rows). (Query took 0.0011 seconds)", for the users table as well.

```<code><!DOCTYPE HTML>
<html lang="en">
    <head>
        <metacharset="UTF-8">
        <title>Register Page</title>
    </head>
    <body>
        <?php
            $page_title = 'Register';
            include('/var/www/html/learn/php/header.html');

            if($_SERVER['REQUEST_METHOD'] == 'POST')
            {

                require('/var/www/connect_db.php');
                $errors = array();

                if(empty($_POST['first_name']))
                {
                    $errors[] = 'Enter your first name.';
                }
                else
                {
                    $fn = mysqli_real_escape_string($dbc, trim($_POST['first_name']));
                }

                if(empty($_POST['last_name']))
                {
                    $errors[] = 'Enter your last name.';
                }
                else
                {
                    $ln = mysqli_real_escape_string($dbc, trim($_POST['last_name']));
                }

                if(empty($_POST['email']))
                {
                    $errors[] = 'Enter your email address.';
                }
                else
                {
                    $e = mysqli_real_escape_string($dbc, trim($_POST['email']));
                }

                if(!empty($_POST['pass1']))
                {
                    if($_POST['pass1'] != $_POST['pass2'])
                    {
                        $errors[] = 'Passwords do not match.';
                    }
                    else
                    {
                        $p = mysqli_real_escape_string($dbc, trim($_POST['pass1']));
                    }
                }
                else
                {
                    $errors[] = 'Enter your password.';
                }

                if(empty($errors))
                {
                    $q = "SELECT user_id FROM users WHERE email='$e'";
                    $r = mysqli_query($dbc, $q);

                    if(mysqli_num_rows($r) != 0)
                    {
                        $errors[] = 'Email address already registered. <a href="login.php">Login</a>';
                    }
                }

                if(empty($errors))
                {
                    $q = "INSERT INTO users
                        (first_name, last_name, email, pass, reg_date)
                        VALUES ('$fn', '$ln', '$e', SHA1('$p'), NOW())";
                    $r = mysqli_query($dbc, $q);

                    if($r)
                    {
                        echo '<h1>Registered!</h1>
                            <p>You are now registered.</p>
                            <p><a href="login.php">Login</a></p>';
                    }

                    mysqli_close($dbc);
                    include('/var/www/html/learn/php/footer.html');
                    exit();
                }
                else
                {
                    echo '<h1>Error!</h1>
                    <p id="err_msg">The following error(s) occurred:<br>';
                    foreach($errors as $msg)
                    {
                        echo "- $msg<br>";
                    }
                    echo 'Please try again.</p>';
                    mysqli_close($dbc);
                }
            }
        ?>

        <h1>Register</h1>
        <form action="register.php" method="POST">
            <p>
                First Name: <input type="text" name="first_name" value="<?php if(isset($_POST['first_name'])) echo $_POST['first_name'];?>">
                Last Name: <input type="text" name="last_name" value="<?php if(isset($_POST['last_name'])) echo $_POST['last_name'];?>">
            </p>
            <p>
                Email Address: <input type="text" name="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>">
            </p>
            <p>
                Password: <input type="password" name="pass1" value="<?php if(isset($_POST['pass1'])) echo $_POST['pass1'];?>">
                Confirm Password: <input type="password" name="pass2" value="<?php if(isset($_POST['pass2'])) echo $_POST['pass2'];?>">
            </p>
            <p>
                <input type="submit" value="Register">
            </p>
        </form>

        <?php include('/var/www/html/learn/php/footer.html');?>
    </body>
</html>
</code>```

This is where I believe my problem is, but I've tried various alternatives and still cannot get the data to insert users into the MySQL database:

```<code>if(empty($errors))
{
    $q = "INSERT INTO users
        (first_name, last_name, email, pass, reg_date)
        VALUES ('$fn', '$ln', '$e', SHA1('$p'), NOW())";
    $r = mysqli_query($dbc, $q);

    if($r)
    {
        echo '<h1>Registered!</h1>
            <p>You are now registered.</p>
            <p><a href="login.php">Login</a></p>';
    }

    mysqli_close($dbc);
    include('/var/www/html/learn/php/footer.html');
    exit();
}
else
{
    echo '<h1>Error!</h1>
    <p id="err_msg">The following error(s) occurred:<br>';
    foreach($errors as $msg)
    {
        echo "- $msg<br>";
    }
    echo 'Please try again.</p>';
    mysqli_close($dbc);
}
</code>```

I'm not sure why the book is making me type "if($r)", but please tell me what it means and show where I messed up.

答:
Your problem:

You are duplicating variable $q & $r. Change here

```<code>     if(empty($errors))
        {
       // changing the variable name here to $s and $m

            $s = "SELECT user_id FROM users WHERE  email='$e'";
            $m = mysqli_query($dbc, $s);

            if(mysqli_num_rows($m) != 0)
            {
                $errors[] = 'Email address already registered. <a href="login.php">Login</a>';
            }
        }

            $q = "INSERT INTO users
                (first_name, last_name, email, pass, reg_date)
                VALUES ('$fn', '$ln', '$e', SHA1('$p'), NOW())";
            $r = mysqli_query($dbc, $q);
</code>```

Also remove the additional if statement as it is not doing any purpose. Additionaly please use parametrized query to prevent sql injections. Hope you understand.

Body:
I double checked my code compared to the book and I'm sure I typed the code in correctly. The page loads, the errors display if I leave a field blank or if the password and confirm password fields don't match. However, if I complete the form correctly and submit, the MySQL database doesn't get the information passed to it. The "Registered!" and login page doesn't show up either. I checked the MySQL database through Ubuntu directly and the users table is still empty (Empty set (0.00 sec)). phpMyAdmin also returns empty, "MySQL returned an empty result set (i.e. zero rows). (Query took 0.0011 seconds)", for the users table as well.

<!DOCTYPE HTML>

        <metacharset="UTF-8">
        <title>Register Page</title>

        <?php
            $page_title = 'Register';
            include('/var/www/html/learn/php/header.html');

            if($_SERVER['REQUEST_METHOD'] == 'POST')
            {

                require('/var/www/connect_db.php');
                $errors = array();

                if(empty($_POST['first_name']))
                {
                    $errors[] = 'Enter your first name.';
                }
                else
                {
                    $fn = mysqli_real_escape_string($dbc, trim($_POST['first_name']));
                }

                if(empty($_POST['last_name']))
                {
                    $errors[] = 'Enter your last name.';
                }
                else
                {
                    $ln = mysqli_real_escape_string($dbc, trim($_POST['last_name']));
                }

                if(empty($_POST['email']))
                {
                    $errors[] = 'Enter your email address.';
                }
                else
                {
                    $e = mysqli_real_escape_string($dbc, trim($_POST['email']));
                }

                if(!empty($_POST['pass1']))
                {
                    if($_POST['pass1'] != $_POST['pass2'])
                    {
                        $errors[] = 'Passwords do not match.';
                    }
                    else
                    {
                        $p = mysqli_real_escape_string($dbc, trim($_POST['pass1']));
                    }
                }
                else
                {
                    $errors[] = 'Enter your password.';
                }

                if(empty($errors))
                {
                    $q = "SELECT user_id FROM users WHERE email='$e'";
                    $r = mysqli_query($dbc, $q);

                    if(mysqli_num_rows($r) != 0)
                    {
                        $errors[] = 'Email address already registered. Login';
                    }
                }

                if(empty($errors))
                {
                    $q = "INSERT INTO users
                        (first_name, last_name, email, pass, reg_date)
                        VALUES ('$fn', '$ln', '$e', SHA1('$p'), NOW())";
                    $r = mysqli_query($dbc, $q);

                    if($r)
                    {
                        echo '
Registered!

You are now registered.

Login
';
                    }

                    mysqli_close($dbc);
                    include('/var/www/html/learn/php/footer.html');
                    exit();
                }
                else
                {
                    echo '
Error!

The following error(s) occurred:
';
                    foreach($errors as $msg)
                    {
                        echo "- $msg
";
                    }
                    echo 'Please try again.
';
                    mysqli_close($dbc);
                }
            }
        ?>

Register

        <form action="register.php" method="POST">

                First Name: <input type="text" name="first_name" value="<?php if(isset($_POST['first_name'])) echo $_POST['first_name'];?>">
                Last Name: <input type="text" name="last_name" value="<?php if(isset($_POST['last_name'])) echo $_POST['last_name'];?>">

                Email Address: <input type="text" name="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>">

                Password: <input type="password" name="pass1" value="<?php if(isset($_POST['pass1'])) echo $_POST['pass1'];?>">
                Confirm Password: <input type="password" name="pass2" value="<?php if(isset($_POST['pass2'])) echo $_POST['pass2'];?>">

                <input type="submit" value="Register">

        </form>

        <?php include('/var/www/html/learn/php/footer.html');?>

This is where I believe my problem is, but I've tried various alternatives and still cannot get the data to insert users into the MySQL database:

if(empty($errors))
{
    $q = "INSERT INTO users
        (first_name, last_name, email, pass, reg_date)
        VALUES ('$fn', '$ln', '$e', SHA1('$p'), NOW())";
    $r = mysqli_query($dbc, $q);

    if($r)
    {
        echo '
Registered!

You are now registered.

Login
';
    }

    mysqli_close($dbc);
    include('/var/www/html/learn/php/footer.html');
    exit();
}
else
{
    echo '
Error!

The following error(s) occurred:
';
    foreach($errors as $msg)
    {
        echo "- $msg
";
    }
    echo 'Please try again.
';
    mysqli_close($dbc);
}

I'm not sure why the book is making me type "if($r)", but please tell me what it means and show where I messed up.

Body:
Your problem:

You are duplicating variable $q & $r. Change here

     if(empty($errors))
        {
       // changing the variable name here to $s and $m

            $s = "SELECT user_id FROM users WHERE  email='$e'";
            $m = mysqli_query($dbc, $s);

            if(mysqli_num_rows($m) != 0)
            {
                $errors[] = 'Email address already registered. <a href="login.php">Login</a>';
            }
        }

            $q = "INSERT INTO users
                (first_name, last_name, email, pass, reg_date)
                VALUES ('$fn', '$ln', '$e', SHA1('$p'), NOW())";
            $r = mysqli_query($dbc, $q);

Also remove the additional if statement as it is not doing any purpose. Additionaly please use parametrized query to prevent sql injections. Hope you understand.


问:
Android - Best way to hide API clientId & clientSecret
I would like to have your opinion on the best way to hide an API key and secret key.

I found 2 ways :

Use NDK like that : https://medium.com/@abhi007tyagi/storing-api-keys-using-android-ndk-6abb0adcadad

Use Gradle like that : http://www.techjini.com/blog/securing-api-key-and-secret-key-in-android

I know that risk 0 does not exist but what is the most secure solution ?

Thank in advance

答:
The NDK seems like your best bet, although not being 100% secure, but it sure is hard to reverse engineer. The gradle way doesn't seem secure at all.

For obfuscation and encryption purposes, you could also take advantage of DexGuard.


问:
Limitations of the Levenberg-Marquardt algorithm
I am using Levenberg-Marquardt algorithm to minimize a non-linear function of 6 parameters. I have got about 50 data points for each minimization, but I do not get sufficiently accurate results. Does the fact, that my parameters differ from each other by a few orders of magnitudes can be so much significant? If yes, where should I look for the solution? If no, what kind of limitations of LMA you met in your work (it may help to find other problems with my applictaion)?
Many Thanks for your help.

Edit: The problem I am trying to solve is to determine the best transformation T:

```<code>typedef struct
{
    double x_translation, y_translation, z_translation;
    double x_rotation, y_rotation, z_rotation;
} transform_3D;
</code>```

to fit the set of 3D points to the bunch of 3D lines. In detail I have got a set of coordinates of 3D points and equations of corresponding 3D lines, which should go through those points (in ideal situation). The LMA is minimizing the summ of distances of the transfomed 3D points to corresponding 3D lines.
The transform function is as follows:

```<code>cv::Point3d Geometry::transformation_3D(cv::Point3d point, transform_3D transformation)
{
    cv::Point3d p_odd,p_even;

    //rotation x
    p_odd.x=point.x;
    p_odd.y=point.y*cos(transformation.x_rotation)-point.z*sin(transformation.x_rotation);
    p_odd.z=point.y*sin(transformation.x_rotation)+point.z*cos(transformation.x_rotation);

    //rotation y
    p_even.x=p_odd.z*sin(transformation.y_rotation)+p_odd.x*cos(transformation.y_rotation);
    p_even.y=p_odd.y;
    p_even.z=p_odd.z*cos(transformation.y_rotation)-p_odd.x*sin(transformation.y_rotation);

    //rotation z
    p_odd.x=p_even.x*cos(transformation.z_rotation)-p_even.y*sin(transformation.z_rotation);
    p_odd.y=p_even.x*sin(transformation.z_rotation)+p_even.y*cos(transformation.z_rotation);
    p_odd.z=p_even.z;

    //translation
    p_even.x=p_odd.x+transformation.x_translation;
    p_even.y=p_odd.y+transformation.y_translation;
    p_even.z=p_odd.z+transformation.z_translation;

    return p_even;
}
</code>```

Hope this explanation will help a bit...

Edit2:

Some exemplary data is pasted below. 3D lines are described by the center point and the directional vector. Center point for all lines are (0,0,0) and 'uz' coordinate for each vector is equal to 1.
Set of 'ux' coordinates of directional vectors:

```<code>-1.0986, -1.0986, -1.0986,
-1.0986, -1.0990, -1.0986,
-1.0986, -1.0986, -0.9995,
-0.9996, -0.9996, -0.9995,
-0.9995, -0.9995, -0.9996,
-0.9003, -0.9003, -0.9004,
-0.9003, -0.9003, -0.9003,
-0.9003, -0.9003, -0.8011,
-0.7020, -0.7019, -0.6028,
-0.5035, -0.5037, -0.4045,
-0.3052, -0.3053, -0.2062,
-0.1069, -0.1069, -0.1075,
-0.1070, -0.1070, -0.1069,
-0.1069, -0.1070, -0.0079,
-0.0079, -0.0079, -0.0078,
-0.0078, -0.0079, -0.0079,
 0.0914,  0.0914,  0.0913,
 0.0913,  0.0914,  0.0915,
 0.0914,  0.0914
</code>```

Set of 'uy' coordinates of directional vectors:

```<code>-0.2032,  -0.0047,    0.1936,
0.3919,    0.5901,    0.7885,
0.9869,    1.1852,    -0.1040,
0.0944,    0.2927,    0.4911,
0.6894,    0.8877,    1.0860,
-0.2032,  -0.0047,    0.1936,
0.3919,    0.5902,    0.7885,
0.9869,    1.1852,    1.0860,
0.9869,    1.1852,    1.0861,
0.9865,    1.1853,    1.0860,
0.9870,    1.1852,    1.0861,
-0.2032,  -0.0047,    0.1937,
0.3919,    0.5902,    0.7885,
0.9869,    1.1852,    -0.1039,
0.0944,    0.2927,    0.4911,
0.6894,    0.8877,    1.0860,
-0.2032,  -0.0047,    0.1935,
0.3919,    0.5902,    0.7885,
0.9869,    1.1852
</code>```

and set of 3D points in (x. y. z. x. y. z. x. y. z. ...) form:

```<code> {{0, 0, 0}, {0, 16, 0},   {0, 32, 0},
 {0, 48, 0}, {0, 64, 0},   {0, 80, 0},
 {0, 96, 0}, {0, 112,0},   {8, 8, 0},
 {8, 24, 0}, {8, 40, 0},   {8, 56, 0},
 {8, 72, 0}, {8, 88, 0},   {8, 104, 0},
 {16, 0, 0}, {16, 16,0},   {16, 32, 0},
{16, 48, 0}, {16, 64, 0},  {16, 80, 0},
{16, 96, 0}, {16, 112, 0}, {24, 104, 0},
{32, 96, 0}, {32, 112, 0}, {40, 104, 0},
{48, 96, 0}, {48, 112, 0}, {56, 104, 0},
{64, 96, 0}, {64, 112, 0}, {72, 104, 0},
{80, 0, 0},  {80, 16, 0},  {80, 32, 0},
{80,48, 0},  {80, 64, 0},  {80, 80, 0},
{80, 96, 0}, {80, 112, 0}, {88,  8, 0},
{88, 24, 0}, {88, 40, 0},  {88, 56, 0},
{88, 72, 0}, {88, 88, 0},  {88, 104, 0},
{96, 0, 0},  {96, 16, 0},  {96, 32, 0},
{96, 48,0},  {96, 64, 0},  {96, 80, 0},
{96, 96, 0}, {96, 112, 0}}
</code>```

This is kind of an "easy" modelled data with very small rotations.

答:
I would suggest you try using a different approach to indirectly find your rotation parameters, namely to use a 4x4 affine transformation matrix to incorporate the translation and rotation parameters.

This gets rid of the nonlinearity of the sine and cosine functions (which you can figure out after the fact).

The tough part would be to constrain the transformation matrix from shearing or scaling, which you don't want.

Body:
I am using Levenberg-Marquardt algorithm to minimize a non-linear function of 6 parameters. I have got about 50 data points for each minimization, but I do not get sufficiently accurate results. Does the fact, that my parameters differ from each other by a few orders of magnitudes can be so much significant? If yes, where should I look for the solution? If no, what kind of limitations of LMA you met in your work (it may help to find other problems with my applictaion)?
Many Thanks for your help.

Edit: The problem I am trying to solve is to determine the best transformation T:

typedef struct
{
    double x_translation, y_translation, z_translation;
    double x_rotation, y_rotation, z_rotation;
} transform_3D;

to fit the set of 3D points to the bunch of 3D lines. In detail I have got a set of coordinates of 3D points and equations of corresponding 3D lines, which should go through those points (in ideal situation). The LMA is minimizing the summ of distances of the transfomed 3D points to corresponding 3D lines.
The transform function is as follows:

cv::Point3d Geometry::transformation_3D(cv::Point3d point, transform_3D transformation)
{
    cv::Point3d p_odd,p_even;

    //rotation x
    p_odd.x=point.x;
    p_odd.y=point.y*cos(transformation.x_rotation)-point.z*sin(transformation.x_rotation);
    p_odd.z=point.y*sin(transformation.x_rotation)+point.z*cos(transformation.x_rotation);

    //rotation y
    p_even.x=p_odd.z*sin(transformation.y_rotation)+p_odd.x*cos(transformation.y_rotation);
    p_even.y=p_odd.y;
    p_even.z=p_odd.z*cos(transformation.y_rotation)-p_odd.x*sin(transformation.y_rotation);

    //rotation z
    p_odd.x=p_even.x*cos(transformation.z_rotation)-p_even.y*sin(transformation.z_rotation);
    p_odd.y=p_even.x*sin(transformation.z_rotation)+p_even.y*cos(transformation.z_rotation);
    p_odd.z=p_even.z;

    //translation
    p_even.x=p_odd.x+transformation.x_translation;
    p_even.y=p_odd.y+transformation.y_translation;
    p_even.z=p_odd.z+transformation.z_translation;

    return p_even;
}

Hope this explanation will help a bit...

Edit2:

Some exemplary data is pasted below. 3D lines are described by the center point and the directional vector. Center point for all lines are (0,0,0) and 'uz' coordinate for each vector is equal to 1.
Set of 'ux' coordinates of directional vectors:

-1.0986, -1.0986, -1.0986,
-1.0986, -1.0990, -1.0986,
-1.0986, -1.0986, -0.9995,
-0.9996, -0.9996, -0.9995,
-0.9995, -0.9995, -0.9996,
-0.9003, -0.9003, -0.9004,
-0.9003, -0.9003, -0.9003,
-0.9003, -0.9003, -0.8011,
-0.7020, -0.7019, -0.6028,
-0.5035, -0.5037, -0.4045,
-0.3052, -0.3053, -0.2062,
-0.1069, -0.1069, -0.1075,
-0.1070, -0.1070, -0.1069,
-0.1069, -0.1070, -0.0079,
-0.0079, -0.0079, -0.0078,
-0.0078, -0.0079, -0.0079,
 0.0914,  0.0914,  0.0913,
 0.0913,  0.0914,  0.0915,
 0.0914,  0.0914

Set of 'uy' coordinates of directional vectors:

-0.2032,  -0.0047,    0.1936,
0.3919,    0.5901,    0.7885,
0.9869,    1.1852,    -0.1040,
0.0944,    0.2927,    0.4911,
0.6894,    0.8877,    1.0860,
-0.2032,  -0.0047,    0.1936,
0.3919,    0.5902,    0.7885,
0.9869,    1.1852,    1.0860,
0.9869,    1.1852,    1.0861,
0.9865,    1.1853,    1.0860,
0.9870,    1.1852,    1.0861,
-0.2032,  -0.0047,    0.1937,
0.3919,    0.5902,    0.7885,
0.9869,    1.1852,    -0.1039,
0.0944,    0.2927,    0.4911,
0.6894,    0.8877,    1.0860,
-0.2032,  -0.0047,    0.1935,
0.3919,    0.5902,    0.7885,
0.9869,    1.1852

and set of 3D points in (x. y. z. x. y. z. x. y. z. ...) form:

 {{0, 0, 0}, {0, 16, 0},   {0, 32, 0},
 {0, 48, 0}, {0, 64, 0},   {0, 80, 0},
 {0, 96, 0}, {0, 112,0},   {8, 8, 0},
 {8, 24, 0}, {8, 40, 0},   {8, 56, 0},
 {8, 72, 0}, {8, 88, 0},   {8, 104, 0},
 {16, 0, 0}, {16, 16,0},   {16, 32, 0},
{16, 48, 0}, {16, 64, 0},  {16, 80, 0},
{16, 96, 0}, {16, 112, 0}, {24, 104, 0},
{32, 96, 0}, {32, 112, 0}, {40, 104, 0},
{48, 96, 0}, {48, 112, 0}, {56, 104, 0},
{64, 96, 0}, {64, 112, 0}, {72, 104, 0},
{80, 0, 0},  {80, 16, 0},  {80, 32, 0},
{80,48, 0},  {80, 64, 0},  {80, 80, 0},
{80, 96, 0}, {80, 112, 0}, {88,  8, 0},
{88, 24, 0}, {88, 40, 0},  {88, 56, 0},
{88, 72, 0}, {88, 88, 0},  {88, 104, 0},
{96, 0, 0},  {96, 16, 0},  {96, 32, 0},
{96, 48,0},  {96, 64, 0},  {96, 80, 0},
{96, 96, 0}, {96, 112, 0}}

This is kind of an "easy" modelled data with very small rotations.


问:
cut a field from its position & place it in different position
I have 2 files - file1 & file2 with contents as shown.

```<code>cat file1.txt

1,2,3

cat file2.txt

a,b,c
</code>```

& the desired output is as below,

```<code>a,1,b,2,c,3
</code>```

Can anyone please help to achieve this?

Till now i have tried this,

```<code>paste -d "," file1.txt file2.txt|cut -d , -f4,1,5,2,6,3
</code>```

& the output came as 1,2,3,a,b,c

But using 'cut' is not the good approach i think.
Becuase here i know there are 3 values in both files, but if the values are more, above command will not be helpful.

答:
paste -d "," file*|awk -F, '{print $4","$1","$5","$2","$6","$3}'

a,1,b,2,c,3

This is simple printing operation. Other answers are most welcome.
But if the file contains 1000's of values, then this printing approach will not help.

Body:
I have 2 files - file1 & file2 with contents as shown.

cat file1.txt

1,2,3

cat file2.txt

a,b,c

& the desired output is as below,

a,1,b,2,c,3

Can anyone please help to achieve this?

Till now i have tried this,

paste -d "," file1.txt file2.txt|cut -d , -f4,1,5,2,6,3

& the output came as 1,2,3,a,b,c

But using 'cut' is not the good approach i think.
Becuase here i know there are 3 values in both files, but if the values are more, above command will not be helpful.


问:
Rewrite url query string to look like directory
Well, I am not good in English actually so I couldn't explain my problem shortly in the title...

Shortly, I need to make

```<code>http://<SITE>/user/?id=<x>
</code>```

to

```<code>http://<SITE>/id<x>
</code>```

Is it possible in Microsoft Azure using web.config?

答:
Inside your web.config you should insert inside <system.webServer> section this rules:

```<code><rewrite>
      <rules>
        <rule name="Redirect for user" stopProcessing="true">
          <match url="^user" />
          <conditions>
             <add input="{QUERY_STRING}" pattern="id=(\d+)" />
          </conditions>
          <action type="Redirect" url="/id/{C:1}" appendQueryString="false" />
        </rule>
      </rules>
</rewrite>
</code>```

It will redirect urls like that http://<SITE>/user/?id=<x> into http://<SITE>/id<x> where <x> is digits

Body:
Well, I am not good in English actually so I couldn't explain my problem shortly in the title...

Shortly, I need to make

http://<SITE>/user/?id=<x>

to

http://<SITE>/id<x>

Is it possible in Microsoft Azure using web.config?

Body:
Inside your web.config you should insert inside <system.webServer> section this rules:

<rewrite>
      <rules>
        <rule name="Redirect for user" stopProcessing="true">
          <match url="^user" />
          <conditions>
             <add input="{QUERY_STRING}" pattern="id=(\d+)" />
          </conditions>
          <action type="Redirect" url="/id/{C:1}" appendQueryString="false" />
        </rule>
      </rules>
</rewrite>

It will redirect urls like that http://<SITE>/user/?id=<x> into http://<SITE>/id<x> where <x> is digits


问:
How to Make Player Walk Up Hills in Unity
Hey guys so im making a 2D Platformer and ran into a difficult situation. Up until now I have had rectangular landscapes for the player to jump and walk on. Now I want to start adding some hills. Picture a triangle, the left side is representing a hill at which the player can walk up. Ive made the landscape as well as copied over the Box Collider 2D from my other paths. I figured out a way to rotate the collider so that it goes up at a 45 degree angle just like the slope of the triangle. For some reason though when I walk into the triangle the player doesnt start walking up it. I have to jump onto the hill and he lands on what looks like an invisible rectangle! I make the collider .25 in thickness so I know that I have the whole collider where I want it. Any idea why? I dont really have any code for this as everything Im doing has pretty much been in scene view. Thanks everyone!

Here is the Player in Play Mode, stands on top of hill by some force:

Here is what the collider looks like in scene view. Ive moved the collider all over and it still does the same thing:

Here is my movement code:

```<code>public class Player : MonoBehaviour {

    public float maxSpeed = 3;
    public float speed = 50f;
    public float jumpPower = 150f;

    public bool grounded;

    private Rigidbody2D rb2d;
    private Animator anim;

    void Start () {

        rb2d = gameObject.GetComponent<Rigidbody2D>();
        anim = gameObject.GetComponent<Animator>();
    }

    void Update () {

        anim.SetBool("Grounded",grounded);
        anim.SetFloat("Speed", Mathf.Abs(rb2d.velocity.x));

        if (Input.GetAxis("Horizontal") < -0.1)
        {
            transform.localScale = new Vector3(-1, 1, 1);

        }
        if (Input.GetAxis("Horizontal") > 0.1)
        {
            transform.localScale = new Vector3(1, 1, 1);

        }

        if (Input.GetButtonDown("Jump") && grounded)
        {
            rb2d.AddForce(Vector2.up * jumpPower);

        }

    }

    void FixedUpdate() {

        Vector3 easeVelocity = rb2d.velocity;
        easeVelocity.y = rb2d.velocity.y;
        easeVelocity.z = 0.0f;
        easeVelocity.x *= 0.75f;

        float h = Input.GetAxis("Horizontal");

        //Fake friction / Easing the x speed of our player
        if (grounded)
        {

            rb2d.velocity = easeVelocity;

        }

        //Moving the Player
        rb2d.AddForce((Vector2.right * speed) * h);

        //Limiting the Speed of the Player
        if (rb2d.velocity.x > maxSpeed)
        {
            rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);

        }

        if (rb2d.velocity.x < -maxSpeed)
        {
            rb2d.velocity = new Vector2(-maxSpeed, rb2d.velocity.y);

        }
    }
}
</code>```

The Ground Material is applied to this landscape just like the other rectangular landscape. Sorry Im new but again, thanks everyone!

答:
I believe you should take a look at the 2D Plaftormer Controller tutorial series by Sebastian Lague. The series is focused on creating a robust 2D platformer controller, and it is very well made. I have watched the videos and built a working solution based on them.

The fourth episode of the series is focused on climbing slopes, and the next episode is focused on descending them. But I still suggest that you should start from the beginning and follow the series patiently. Lague always offers very detailed explanations to why he implements thing a certain way.

Body:
Hey guys so im making a 2D Platformer and ran into a difficult situation. Up until now I have had rectangular landscapes for the player to jump and walk on. Now I want to start adding some hills. Picture a triangle, the left side is representing a hill at which the player can walk up. Ive made the landscape as well as copied over the Box Collider 2D from my other paths. I figured out a way to rotate the collider so that it goes up at a 45 degree angle just like the slope of the triangle. For some reason though when I walk into the triangle the player doesnt start walking up it. I have to jump onto the hill and he lands on what looks like an invisible rectangle! I make the collider .25 in thickness so I know that I have the whole collider where I want it. Any idea why? I dont really have any code for this as everything Im doing has pretty much been in scene view. Thanks everyone!

Here is the Player in Play Mode, stands on top of hill by some force:

Here is what the collider looks like in scene view. Ive moved the collider all over and it still does the same thing:

Here is my movement code:

public class Player : MonoBehaviour {

    public float maxSpeed = 3;
    public float speed = 50f;
    public float jumpPower = 150f;

    public bool grounded;

    private Rigidbody2D rb2d;
    private Animator anim;

    void Start () {

        rb2d = gameObject.GetComponent<Rigidbody2D>();
        anim = gameObject.GetComponent<Animator>();
    }

    void Update () {

        anim.SetBool("Grounded",grounded);
        anim.SetFloat("Speed", Mathf.Abs(rb2d.velocity.x));

        if (Input.GetAxis("Horizontal") < -0.1)
        {
            transform.localScale = new Vector3(-1, 1, 1);

        }
        if (Input.GetAxis("Horizontal") > 0.1)
        {
            transform.localScale = new Vector3(1, 1, 1);

        }

        if (Input.GetButtonDown("Jump") && grounded)
        {
            rb2d.AddForce(Vector2.up * jumpPower);

        }

    }

    void FixedUpdate() {

        Vector3 easeVelocity = rb2d.velocity;
        easeVelocity.y = rb2d.velocity.y;
        easeVelocity.z = 0.0f;
        easeVelocity.x *= 0.75f;

        float h = Input.GetAxis("Horizontal");

        //Fake friction / Easing the x speed of our player
        if (grounded)
        {

            rb2d.velocity = easeVelocity;

        }

        //Moving the Player
        rb2d.AddForce((Vector2.right * speed) * h);

        //Limiting the Speed of the Player
        if (rb2d.velocity.x > maxSpeed)
        {
            rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);

        }

        if (rb2d.velocity.x < -maxSpeed)
        {
            rb2d.velocity = new Vector2(-maxSpeed, rb2d.velocity.y);

        }
    }
}

The Ground Material is applied to this landscape just like the other rectangular landscape. Sorry Im new but again, thanks everyone!


问:
c free() function question

Possible Duplicate:

  C programming : How does free know how much to free?

Hi,

when i have following code:

```<code>void *ptr = malloc(100); // alloc 100 bytes
// do sth
free(ptr);
</code>```

how does the free() function know how much space has to be freed?

thank you!

--

ok i have found other questions asking the same, please close - sorry

答: This information is usually contained in some memory area managed by the malloc implementation. The information often preceeds the actual memory handed out to you by malloc, but that's an implementation detail, and you cannot rely on anything here.

Title: c free() function question

Body:
Possible Duplicate:

  C programming : How does free know how much to free?

Hi,

when i have following code:

void *ptr = malloc(100); // alloc 100 bytes
// do sth
free(ptr);

how does the free() function know how much space has to be freed?

thank you!

--

ok i have found other questions asking the same, please close - sorry


问:
Clustering different class
I would like to cluster my dataset which has multiple classes (up to 10). But this clustering problem is different than usual clustering. I need to cluster different classes (as shown in the image;  https://ibb.co/iiNbqv) instead same/similar classes. Which method should I use? what would you recommend?

The problem as follow;
I have several frames/images (up to 10), and each frame has hundred of thousand detections. So, as the data I am processing is the location (x and y coordinates) of the detection. What I am going to do that how much detections are overlapped within these frames with a certain distance threshold. The constraint is that each detection of a frame shouldn't be in the same overlapped cluster more than once as seen in the picture. So basically, I should find the nearest detection of a point from other frames, and put them in same cluster. But once I do that every point in the cluster shouldn't be far each other more than distant threshold

Cheers

答:
Clustering won't help you much here, because it is too exploratory.

You should instead look into optimization in general. In particular, your problem has similarities to the set cover problem. For all I can tell, you want to cover all instances with sets of three, such that the three elements are in different "classes" and most similar?

Based on the optimization theory results, you will likely be able to prove that this problem is NP hard, and therefore a greedy approximation algorithm is the preferable way of handling this.

Title: Clustering different class


问:
Why is the button border not disappearing when using a border radius of 0 in xamarin forms (Xaml)?
I am looking to make the button border to disappear when using xaml. I have tried to make the border radius = 0 and tried to make the background colour transparent. If you know the solution with XAML code that would be useful. Thank you.

Xamarin.Forms Version:2.3.4.247.

Visual result

Expected Result

XAML:

```<code><Button Image="nav_menu.png"
        VerticalOptions="Center"
        HorizontalOptions="End"
        BackgroundColor="Transparent"
        BorderColor="Transparent"
        BorderRadius="0"/>
</code>```

答:
Oops! Just saw the image you had in your OP.

Ah, so what you're experiencing is not actually a border but a shadow. This is easily fixed by setting the style. Directions taken from this forum post.

In your Droid project, go to Resources/values/style.xml, set your state list animator to null. It should look something like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<resources>
    <style name="AppTheme" parent="AppTheme.Base">
    </style>
    <style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:buttonStyle">@style/NoShadowButton</item>
    </style>
    <style name="NoShadowButton" parent="android:style/Widget.Button">
        <item name="android:stateListAnimator">@null</item>
    </style>
</resources>
</code>```

Let me know if this doesn't work for you.

Body:
I am looking to make the button border to disappear when using xaml. I have tried to make the border radius = 0 and tried to make the background colour transparent. If you know the solution with XAML code that would be useful. Thank you.

Xamarin.Forms Version:2.3.4.247.

Visual result

Expected Result

XAML:

<Button Image="nav_menu.png"
        VerticalOptions="Center"
        HorizontalOptions="End"
        BackgroundColor="Transparent"
        BorderColor="Transparent"
        BorderRadius="0"/>

Body:
Oops! Just saw the image you had in your OP.

Ah, so what you're experiencing is not actually a border but a shadow. This is easily fixed by setting the style. Directions taken from this forum post.

In your Droid project, go to Resources/values/style.xml, set your state list animator to null. It should look something like this:

<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <style name="AppTheme" parent="AppTheme.Base">
    </style>
    <style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:buttonStyle">@style/NoShadowButton</item>
    </style>
    <style name="NoShadowButton" parent="android:style/Widget.Button">
        <item name="android:stateListAnimator">@null</item>
    </style>
</resources>

Let me know if this doesn't work for you.


问:
How to branch the whole repository including ignore files
I have a project, which is in the Mercurial repository. In the root folder there is a .hgignore file, which states, that the "Bin" folder should be ignored (and also some other files and folders).

Now I want to clone this repository but in a way, that ALL folders and files should be cloned, also the original ignored ones. If I just clone the repository, than I get only the files, which are included in the repository thus my bin folder is missing.

How can I get cloned repository with all files in it? I want to merge these two repositories together in a while...

PS - I am working on a legacy application which has a lot of external dll-s in the bin folder of the application. I know I should put them to a seperate folder, but that's another story.

答:
Just copy it.

Copy the whole tree from point a to point b, and the new copy will function perfectly as a repository. The only thing that would be different from a clone is the lack of hardlinks and that the default pull/push path will be set-up to be the same as the original, rather than pointing to the original. That's easy to change by editing .hg/hgrc if you want to.


问:
SpringBoot dependency jars not found on Tomcat 8
Using springboot 1.5.3 and tomcat 8 and 8.5.  I have a custom spring boot project im using as a dependency.  it's just repo classes.  From my main class, I've add

```<code>    <dependency>
        <groupId>com.swisher</groupId>
        <artifactId>product-common</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
</code>```

to my pom.xml file.   It works just fine, but when I package the project as a deployable war file and push to Tomcat 8 or 8.5, my dependency project model classes are not visible to my controller.

2017-06-05 14:21:57.157 ERROR 5184 --- [nio-8080-exec-6] o.s.boot.web.support.ErrorPageFilter     : Forwarding to error page from request [/] due to exception [com/swisher/pc/model/Person]

java.lang.NoClassDefFoundError: com/swisher/pc/model/Person
    at com.swisher.pc.controllers.CatalogController.index(CatalogController.java:75) ~[classes/:0.0.1-SNAPSHOT]

I've tried using

@SpringBootApplication(scanBasePackages={ "com.swisher", "com.swisher.pc"})
@ComponentScan(basePackages={"com.swisher", "com.swisher.pc"})

but still not working.

any help would be greatly appreciated.

Kevin

答:
This article further explains [link]github.com/spring-projects/spring-boot/issues/… This is due to the change in layout of executable jars in Spring Boot 1.4. Application classes are now packaging in BOOT-INF/classes So this entry in the pom does the trick`

```<code><plugin>
         <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-maven-plugin</artifactId>
                 <executions>
                     <execution>
                         <goals>
                             <goal>repackage</goal>
                         </goals>
                         <configuration>
                             <classifier>exec</classifier>
                         </configuration>
                     </execution>
                </executions>
     </plugin>
</code>```

`

Then use: mvn package spring-boot:repackage.  Followed by mvn install.

Body:
Using springboot 1.5.3 and tomcat 8 and 8.5.  I have a custom spring boot project im using as a dependency.  it's just repo classes.  From my main class, I've add

    <dependency>
        <groupId>com.swisher</groupId>
        <artifactId>product-common</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>

to my pom.xml file.   It works just fine, but when I package the project as a deployable war file and push to Tomcat 8 or 8.5, my dependency project model classes are not visible to my controller.

2017-06-05 14:21:57.157 ERROR 5184 --- [nio-8080-exec-6] o.s.boot.web.support.ErrorPageFilter     : Forwarding to error page from request [/] due to exception [com/swisher/pc/model/Person]

java.lang.NoClassDefFoundError: com/swisher/pc/model/Person
    at com.swisher.pc.controllers.CatalogController.index(CatalogController.java:75) ~[classes/:0.0.1-SNAPSHOT]

I've tried using

@SpringBootApplication(scanBasePackages={ "com.swisher", "com.swisher.pc"})
@ComponentScan(basePackages={"com.swisher", "com.swisher.pc"})

but still not working.

any help would be greatly appreciated.

Kevin

Body:
This article further explains [link]github.com/spring-projects/spring-boot/issues/… This is due to the change in layout of executable jars in Spring Boot 1.4. Application classes are now packaging in BOOT-INF/classes So this entry in the pom does the trick`

<plugin>
         <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-maven-plugin</artifactId>
                 <executions>
                     <execution>
                         <goals>
                             <goal>repackage</goal>
                         </goals>
                         <configuration>
                             <classifier>exec</classifier>
                         </configuration>
                     </execution>
                </executions>
     </plugin>

`

Then use: mvn package spring-boot:repackage.  Followed by mvn install.


问:
How can I update/refresh my iTerm2 profiles being cached in my Default Window Arrangement?
Wasn't sure if I should post this on the Apple SE boards, but since it's not first-party software, I'll keep it here.

Can't find out where I got my original piece of advice, but it told me that old profiles are cached in the window arrangement.  So I should have it open, open each window's/tab's/pane's/session's info panel (Cmd+i), and either select the same profile in the list and hit "Use Selected Profile', or change between another and back to the original on hitting that same button each time.  Then save over the window arrangement and reload to test.

I have all of my profiles updated.  I can see the new badge text reflected when I open iTerm2 again now after using the above inconvenient workaround.

Problem is I still have the wrong working directory.  I thought updating the profiles wasn't working at all, even with that technique, but I think it's just the working directory path now.

Found a possibly related link here: StackOverflow - iTerm 2 Doesn't Start Up With Proper Default Profile

答:
The technique above may still be needed, but I did not test without it carefully enough again this time.

The change needed was actually changed the current working directory in each session.  Even though I was trying to only operate on it through the Profiles section's field, that didn't seem to actually update the path upon loading the window arrangement.

If these circumstances are all accurate, then I think the iTerm2 handling of profiles in other objects needs some updating, maybe more references and less duplicate data that could become stale or different because of its separation, at least adding for the option of working this way based on user preference..


问:
LoadingCache for a list of keys
I have a downstream service which takes the list of ids and return the data for the ids. I am exploring Guava LoadingCache to cache these values. But the loader in the LoadingCache accepts only one key. Are there any ways to use the list of keys.</p>

答:
I did a small experimentation, it looks like this can be done by using getAll and loadAll APIs. https://github.com/google/guava/wiki/CachesExplained#from-a-cacheloader

Sample code available in https://github.com/gvnavin/CachingExperimentations

Title: LoadingCache for a list of keys