问:
Acceleo: The generation failed to generate any file
First of all , I am new to Acceleo and the modeling features of eclipse. What I am trying to do is just to create a simple test file. So for starters, I created  a main module:

```<code>comment encoding = UTF-8 /]
[module generate('file:/C:/Users/maria/Documents/workspace/org.eclipse.acceleo.module.m2tTransformation/model/PSMMetamodel.ecore')]

[template public generateElement( aServicePSM : ServicePSM)]
[comment @main/]
[file ('test.java', false, 'UTF-8')]
Test
[/file]
[/template]
</code>```

When i run this I get:

```<code>The generation failed to generate any file because there are no model elements that matches at least the type of the first parameter of one of your main templates.
The problem may be caused by a problem with the registration of your metamodel, please see the method named "registerPackages" in the Java launcher of your generator. It could also come from a missing [comment @main/] in the template used as the entry point of the generation.
</code>```

Also the URI I use is the nsURI attribute value I set to the root of metamodel. I am sure that my input model does contain ServicePSM elements.
What am i doing wrong?

Thanks in advance.

答:
This issue will arise in two cases

You do not have an element of the proper type in your model

The metamodel cannot be resolved

From your message I think we can safely ignore 1. since it seems you have at least one ServicePSM in your model, so we need to address 2.

If you look at your module, you've declared it to generate on metamodel file:/C:/Users/maria/Documents/workspace/org.eclipse.acceleo.module.m2tTransformation/model/PSMMetamodel.ecore. However, EMF rarely, if ever, uses this kind of URIs to refer to its metamodels. If you open your actual model with the text editor (right click > Open With > Text Editor), you can look at the URI that's actually been used to reference the metamodel with the "xmlns" tags at the start.

For example, if I open a model that references OCL elements, I can see xmlns:ocl.ecore="http://www.eclipse.org/ocl/1.1.0/Ecore". You have to make sure you use the same URI in your module file as what you see EMF using in the model file, in this case, it would be http://www.eclipse.org/ocl/1.1.0/Ecore.

Body:
First of all , I am new to Acceleo and the modeling features of eclipse. What I am trying to do is just to create a simple test file. So for starters, I created  a main module:

comment encoding = UTF-8 /]
[module generate('file:/C:/Users/maria/Documents/workspace/org.eclipse.acceleo.module.m2tTransformation/model/PSMMetamodel.ecore')]

[template public generateElement( aServicePSM : ServicePSM)]
[comment @main/]
[file ('test.java', false, 'UTF-8')]
Test
[/file]
[/template]

When i run this I get:

The generation failed to generate any file because there are no model elements that matches at least the type of the first parameter of one of your main templates.
The problem may be caused by a problem with the registration of your metamodel, please see the method named "registerPackages" in the Java launcher of your generator. It could also come from a missing [comment @main/] in the template used as the entry point of the generation.

Also the URI I use is the nsURI attribute value I set to the root of metamodel. I am sure that my input model does contain ServicePSM elements.
What am i doing wrong?

Thanks in advance.


来源: stackexchange

问:
Array inside an Object with specific key to access
So I have here an object of an photo inside that object there's a bunch of arrays with key's & values :

```<code>{
     "photos": [
                {
                  "logo": false,
                  "type": "MAIN",
                  "url": "/uploads/userpics/503892/FiyxpMqMQj.png",
                  "publicUrl": "https:test.com/medium_FiyxpMqMQj.png"
                },
                {
                  "logo": true,
                  "type": "LOGO",
                  "url": "/uploads/userpics/503892/kLwxKH6rIx.png",
                  "publicUrl": "https://test.com/medium_kLwxKH6rIx.png"
                },
                 {
                  "logo": false,
                  "type": "MAIN",
                  "url": "/uploads/userpics/543292/FiyxpMqMQj.png",
                  "publicUrl": "https:test.com/medium_asd432MQj.png"
                }
              ]
}
</code>```

what I want is after i ran this object into foreach it will display or get the "publicUrl" of the key value "logo"=true or "type"="LOGO" is that possible ?

答:
assuming $photos is the original data and that you have shown the data at the beginning level then you could do something like:</p>

```<code>$json=json_decode( $photos );
foreach( $json as $obj ){
    if( $obj->logo==true or $obj->type=='LOGO' ){
        echo $obj->publicUrl;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I have here an object of an photo inside that object there's a bunch of arrays with key's & values :

{
     "photos": [
                {
                  "logo": false,
                  "type": "MAIN",
                  "url": "/uploads/userpics/503892/FiyxpMqMQj.png",
                  "publicUrl": "https:test.com/medium_FiyxpMqMQj.png"
                },
                {
                  "logo": true,
                  "type": "LOGO",
                  "url": "/uploads/userpics/503892/kLwxKH6rIx.png",
                  "publicUrl": "https://test.com/medium_kLwxKH6rIx.png"
                },
                 {
                  "logo": false,
                  "type": "MAIN",
                  "url": "/uploads/userpics/543292/FiyxpMqMQj.png",
                  "publicUrl": "https:test.com/medium_asd432MQj.png"
                }
              ]
}

what I want is after i ran this object into foreach it will display or get the "publicUrl" of the key value "logo"=true or "type"="LOGO" is that possible ?

Body:
assuming $photos is the original data and that you have shown the data at the beginning level then you could do something like:

$json=json_decode( $photos );
foreach( $json as $obj ){
    if( $obj->logo==true or $obj->type=='LOGO' ){
        echo $obj->publicUrl;
    }
}


答: First, this is not a valid JSON. But once you fix it, json_decode($array, true) will convert your JSON to regular array (2nd parameter is important for that) and then you can use normal foreach($array as $key=>$val) { echo "{$k} = {$v}" } to iterate over it.  JSON arrays got no custom keys, so expect 0, 1 .... sequence.

Title: Array inside an Object with specific key to access


问:
Set AUTO_INCREMENT in all tables within a MySQL DB to the largest inserted increment value
Is it possible to set AUTO_INCREMENT value for all tables within a database to the latest insert value?

UPDATE
For example if my table had 1000 records with increment values from 1..1000 and I have deleted last 900 records the last increment value in the field would be 100. I would like to set the AUTO_INCREMENT to the 101. And this for all tables within DB.

答:
AUTO_INCREMENT actually remember the last number it insert even if the data has been deleted. So if your AUTO_INCREMENT number is less than 100, you can just temporary insert a blank data with AUTO_INCREMENT number = 100 and then delete it. The next time you insert a data, it will go to 101.

You can use this query to reset the AUTO_INCREMENT number to the current highest one in the table.

ALTER TABLE table_name AUTO_INCREMENT = 1;


问:
PHP equivalent passwords hashing of the following .NET code
I don't really want to dump some code and expect answers but this is a pretty lengthy function that hashes a password in order to later compare it to the database-stored value.

I have seen posts where people wasted time trying to recreate what they could achieve with the md5() function in PHP.

For that reason, I'm wondering if someone with any encryption knowledge knows of a PHP equivalent to achieve the following effect in PHP:

```<code>    internal static string GenerateEncryptedPassword(string password, string salt, int iterationCount)
    {
        byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
        byte[] saltBytes = Encoding.UTF8.GetBytes(salt);
        byte[] iterationCountBytes = BitConverter.GetBytes(iterationCount);
        int derivedLength = passwordBytes.Length + saltBytes.Length;
        byte[] passwordSaltBytes = new byte[derivedLength];
        byte[] pbkdf2Bytes;
        string encryptedString;

        for (int i = 0; i < passwordBytes.Length; i++)
        {
            passwordSaltBytes[i] = passwordBytes[i];
        }

        for (int i = 0; i < saltBytes.Length; i++)
        {
            passwordSaltBytes[passwordBytes.Length + i] = saltBytes[i];
        }

        using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, passwordSaltBytes, iterationCount))
        {
            pbkdf2Bytes = pbkdf2.GetBytes(derivedLength + iterationCountBytes.Length);
        }

        using (SHA512 sha512 = new SHA512Managed())
        {
            byte[] hashBytes = sha512.ComputeHash(pbkdf2Bytes);
            byte[] hashSaltBytes = new byte[hashBytes.Length + saltBytes.Length];

            for (int i = 0; i < hashBytes.Length; i++)
            {
                hashSaltBytes[i] = hashBytes[i];
            }

            for (int i = 0; i < saltBytes.Length; i++)
            {
                hashSaltBytes[hashBytes.Length + i] = saltBytes[i];
            }

            encryptedString = Convert.ToBase64String(hashSaltBytes);
        }

        return encryptedString;
    }
</code>```

If it changes anything, I'm using Laravel...

Thank you for any guidance

I hate encryption :D

```<code>$user = \App\User::all();
$salt = strtolower($user[2]->Salt);
$password = 'P@$$W0rd';
$dbPassword = $user[2]->Password;
$iterations = 10000;

echo openssl_pbkdf2($password, $salt, 44, $iterations, 'sha512');
</code>```

答:
I haven't used PHP for years so not sure if there are new ways to do things, but you can produce SHA-512 hashes with OpenSSL: http://php.net/manual/en/function.openssl-digest.php

```<code>openssl_digest(pbkdf2Bytes, 'sha512');
</code>```

To generate salt, it is highly recommended to use secure (unpredictable) randoms. For PHP, see this: PHP random string generator

EDIT:
You can also produce pbkfd2 directly with OpenSSL:
http://php.net/manual/en/function.openssl-pbkdf2.php

Just note the optional parameter in the end of the function signature where you define the digest algorithm.

```<code>openssl_pbkdf2(password, saltBytes, keyLength, iterationCount, 'sha512')
</code>```

Body:
I don't really want to dump some code and expect answers but this is a pretty lengthy function that hashes a password in order to later compare it to the database-stored value.

I have seen posts where people wasted time trying to recreate what they could achieve with the md5() function in PHP.

For that reason, I'm wondering if someone with any encryption knowledge knows of a PHP equivalent to achieve the following effect in PHP:

    internal static string GenerateEncryptedPassword(string password, string salt, int iterationCount)
    {
        byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
        byte[] saltBytes = Encoding.UTF8.GetBytes(salt);
        byte[] iterationCountBytes = BitConverter.GetBytes(iterationCount);
        int derivedLength = passwordBytes.Length + saltBytes.Length;
        byte[] passwordSaltBytes = new byte[derivedLength];
        byte[] pbkdf2Bytes;
        string encryptedString;

        for (int i = 0; i < passwordBytes.Length; i++)
        {
            passwordSaltBytes[i] = passwordBytes[i];
        }

        for (int i = 0; i < saltBytes.Length; i++)
        {
            passwordSaltBytes[passwordBytes.Length + i] = saltBytes[i];
        }

        using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, passwordSaltBytes, iterationCount))
        {
            pbkdf2Bytes = pbkdf2.GetBytes(derivedLength + iterationCountBytes.Length);
        }

        using (SHA512 sha512 = new SHA512Managed())
        {
            byte[] hashBytes = sha512.ComputeHash(pbkdf2Bytes);
            byte[] hashSaltBytes = new byte[hashBytes.Length + saltBytes.Length];

            for (int i = 0; i < hashBytes.Length; i++)
            {
                hashSaltBytes[i] = hashBytes[i];
            }

            for (int i = 0; i < saltBytes.Length; i++)
            {
                hashSaltBytes[hashBytes.Length + i] = saltBytes[i];
            }

            encryptedString = Convert.ToBase64String(hashSaltBytes);
        }

        return encryptedString;
    }

If it changes anything, I'm using Laravel...

Thank you for any guidance

I hate encryption :D

$user = \App\User::all();
$salt = strtolower($user[2]->Salt);
$password = 'P@$$W0rd';
$dbPassword = $user[2]->Password;
$iterations = 10000;

echo openssl_pbkdf2($password, $salt, 44, $iterations, 'sha512');

Body:
I haven't used PHP for years so not sure if there are new ways to do things, but you can produce SHA-512 hashes with OpenSSL: http://php.net/manual/en/function.openssl-digest.php

openssl_digest(pbkdf2Bytes, 'sha512');

To generate salt, it is highly recommended to use secure (unpredictable) randoms. For PHP, see this: PHP random string generator

EDIT:
You can also produce pbkfd2 directly with OpenSSL:
http://php.net/manual/en/function.openssl-pbkdf2.php

Just note the optional parameter in the end of the function signature where you define the digest algorithm.

openssl_pbkdf2(password, saltBytes, keyLength, iterationCount, 'sha512')


问:
Did the author make a mistake in explaining stack and heap in C++ or am I misreading something?
Here is the code:

```<code>int main()
{
    using namespace std;
    int nights = 1001;
    int * pt = new int; // allocate space for an int
    *pt = 1001;         // store a value there

    cout << "nights value = ";
    cout << nights << ": location " << &nights << endl;
    cout << "int ";
    cout << "value = " << *pt << ": location = " << pt << endl;

    double * pd = new double; // allocate space for a double
    *pd = 10000001.0; // store a double there

    cout << "double ";
    cout << "value = " << *pd << ": location = " << pd << endl;
    cout << "location of pointer pd: " << &pd << endl;
    cout << "size of pt = " << sizeof(pt);
    cout << ": size of *pt = " << sizeof(*pt) << endl;
    cout << "size of pd = " << sizeof pd;
    cout << ": size of *pd = " << sizeof(*pd) << endl;

    return 0;
}
</code>```

Now here is the author's note about the code:

Another point to note is that typically new uses a different block of memory than do the ordinary variable definitions that we have been using. Both the variable nights and pd have their values stored in a memory region called the stack, whereas the memory allocated by the new is in a region called the heap or free store.

Initial Question:

Now my concern is this: the variable pd was create by the keyword new, so it should be stored in the region called heap just like the variable pt, since they were both created by the keyword new.

Am I missing something here? Thank you very much in advance for your inputs.

Revised Question/Follow-up based on the hold:

This question was put on hold by 5 people because they couldn't understand what I was asking. I believe that my question has already been answered but for those who are still not sure about what I was initially asking please read along:

I was unclear about the author's explanation about where the variables and their values were stored in memory. Up to the author explanation, I had a belief that any memory created dynamically (or should I say during runtime after compiling) by using the keyword new gets stored in the heap not the stack.

So, it confused me when he wrote that the variable pd has is value
  stored in the stack, but again how is that possible if the variable
  was create during "runtime" with the keyword new, so it should be
  in the heap, not the stack.

Please try to use the code above as the reference and in particular the **variables (nights, pd, and pt) in your answer so that I can understand it from that code's perspective.

答: The pd variable is stored in stack memory, however the memory location where pd points to is allocated in heap memory. I think author wanted to emphasize exactly this difference between these concepts.

ContentLicense: CC BY-SA 4.0

Body:
Here is the code:

int main()
{
    using namespace std;
    int nights = 1001;
    int * pt = new int; // allocate space for an int
    *pt = 1001;         // store a value there

    cout << "nights value = ";
    cout << nights << ": location " << &nights << endl;
    cout << "int ";
    cout << "value = " << *pt << ": location = " << pt << endl;

    double * pd = new double; // allocate space for a double
    *pd = 10000001.0; // store a double there

    cout << "double ";
    cout << "value = " << *pd << ": location = " << pd << endl;
    cout << "location of pointer pd: " << &pd << endl;
    cout << "size of pt = " << sizeof(pt);
    cout << ": size of *pt = " << sizeof(*pt) << endl;
    cout << "size of pd = " << sizeof pd;
    cout << ": size of *pd = " << sizeof(*pd) << endl;

    return 0;
}

Now here is the author's note about the code:

Another point to note is that typically new uses a different block of memory than do the ordinary variable definitions that we have been using. Both the variable nights and pd have their values stored in a memory region called the stack, whereas the memory allocated by the new is in a region called the heap or free store.

Initial Question:

Now my concern is this: the variable pd was create by the keyword new, so it should be stored in the region called heap just like the variable pt, since they were both created by the keyword new.

Am I missing something here? Thank you very much in advance for your inputs.

Revised Question/Follow-up based on the hold:

This question was put on hold by 5 people because they couldn't understand what I was asking. I believe that my question has already been answered but for those who are still not sure about what I was initially asking please read along:

I was unclear about the author's explanation about where the variables and their values were stored in memory. Up to the author explanation, I had a belief that any memory created dynamically (or should I say during runtime after compiling) by using the keyword new gets stored in the heap not the stack.

So, it confused me when he wrote that the variable pd has is value
  stored in the stack, but again how is that possible if the variable
  was create during "runtime" with the keyword new, so it should be
  in the heap, not the stack.

Please try to use the code above as the reference and in particular the **variables (nights, pd, and pt) in your answer so that I can understand it from that code's perspective.


问:
Laravel - Redirect with variable to twig page
I've made a mail function with an try/catch situation. It checks if the mail template exists, if not it needs to return redirect / back to the page with a message(return redirect('dashboard')->with('status', "Mail doesn't exists");)

Is it possible to redirect with a variable using a twig page? Or is there just something that I am doing wrong?

This is my mail function(DashboardController.php)

```<code> public function MailContact($date_id, $contact_id)
{
    try
    {
        $contact = Contact::find($contact_id);
        $date = Date::find($date_id);
        $mail = Mails::where('datetype_id', $date->datetype_id)->first();
        $html = $mail->html;

        Mail::to($contact->email)->send(new Anniversary($html));

        return redirect('dashboard');
        }
    catch(\Exception $ex )
    {
        return redirect('dashboard')->with("Mail doesn't exists");
    }
}
</code>```

This is the twig page('dashboard.twig')

```<code> <div class="box-body no-padding" style="width: 100%; padding-top:20px;">
  <ul class="telephoneKingList" style=" display: inline-block;
    width: 100%;">
        {% for dates in datestodayUser %}
           {% if dates is not empty %}
              <li data-id="{{ dates.id }}">
                 {{ dates.contact.fullname }}, {{ dates.contact.relation.company }} <br>
                 {{ dates.description }}<br>
                 {# Place where Error needs to be #}
                 <a role="button" id="edit-button" href="/dashboard/mail/{{ dates.id }}/{{ dates.contact.id }}" class="btn btn-primary btn-sm"><i class="fa fa-envelope"></i></a>
              </li>
              <hr>
           {% endif %}
           {% else %}
              <li>
                 Geen data beschikbaar.
              </li>
           {% endfor %}
  </ul>
</code>```

答:
Use

```<code>redirect('dashboard')->withErrors(["Mail doesn't exists"])
</code>```

and in your twig you need to access the errors using

```<code>{{ errors.first() }}
</code>```

Laravel has a middleware included out of the box called ShareErrorsFromSession which shares the session errors with all views.

Body:
I've made a mail function with an try/catch situation. It checks if the mail template exists, if not it needs to return redirect / back to the page with a message(return redirect('dashboard')->with('status', "Mail doesn't exists");)

Is it possible to redirect with a variable using a twig page? Or is there just something that I am doing wrong?

This is my mail function(DashboardController.php)

 public function MailContact($date_id, $contact_id)
{
    try
    {
        $contact = Contact::find($contact_id);
        $date = Date::find($date_id);
        $mail = Mails::where('datetype_id', $date->datetype_id)->first();
        $html = $mail->html;

        Mail::to($contact->email)->send(new Anniversary($html));

        return redirect('dashboard');
        }
    catch(\Exception $ex )
    {
        return redirect('dashboard')->with("Mail doesn't exists");
    }
}

This is the twig page('dashboard.twig')

        {% for dates in datestodayUser %}
           {% if dates is not empty %}

                 {{ dates.contact.fullname }}, {{ dates.contact.relation.company }}

                 {{ dates.description }}

                 {# Place where Error needs to be #}

           {% endif %}
           {% else %}

                 Geen data beschikbaar.

           {% endfor %}

Body:
Use

redirect('dashboard')->withErrors(["Mail doesn't exists"])

and in your twig you need to access the errors using

{{ errors.first() }}

Laravel has a middleware included out of the box called ShareErrorsFromSession which shares the session errors with all views.


问:
Construct an escaped string
I am looking for an alternative api in javascript for the StringEscapeUtils in java.

Basically it should be able to convert

input string:

He didn't say, "Stop!"

output string:

He didn't say, \"Stop!\"

Can we do the same using any underscore or any other util functions?

In underscore`s escape api,

var a = '"test"';
  _.escape(a)

returns

```<code>""test""
</code>```

But I wanted in the format \"test\"'

答:
Use JSON.stringify?

console.log(JSON.stringify('Hello "world"').slice(1, -1));```

Title: Construct an escaped string

Body:
I am looking for an alternative api in javascript for the StringEscapeUtils in java.

Basically it should be able to convert

input string:

He didn't say, "Stop!"

output string:

He didn't say, \"Stop!\"

Can we do the same using any underscore or any other util functions?

In underscore`s escape api,

var a = '"test"';
  _.escape(a)

returns

""test""

But I wanted in the format \"test\"'


问:
Can't Load URL: The domain of this URL isn't included in the app's domains - Facebook Login
I'm trying to get access token from user

```<code>string response_script = "<script>top.location.href='https://www.facebook.com/v2.4/dialog/oauth?response_type=token&client_id=[APPLICATION ID]&redirect_uri=https://www.facebook.com/[APPLICATION URL]/?sk=app_[PAGE ID]&scope='; </script>";
</code>```

But I'm getting an error:

Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.

That code works well. So I think that needs to add my url to

Valid OAuth redirect URIs

But It doesn't exists in advanced section anymore. facebook changed it's design and now it looks like this. It's too big image and because I have it in out of stackoverflow

What can I do?

答:
I  had the same problem, and it came from a wrong client_id / Facebook App ID.

Did you switch your Facebook app to "public" or "online ? When you do so, Facebook creates a new app with a new App ID.

You can compare the "client_id" parameter value in the url with the one in your Facebook dashboard.

Also Make sure your app is public. Click on + Add product Now go to products => Facebook Login Now do the following:

Valid OAuth redirect URIs : example.com/

Body:
I'm trying to get access token from user

string response_script = "";

But I'm getting an error:

Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.

That code works well. So I think that needs to add my url to

Valid OAuth redirect URIs

But It doesn't exists in advanced section anymore. facebook changed it's design and now it looks like this. It's too big image and because I have it in out of stackoverflow

What can I do?


问:
"message": "Sandbox subdomains are for test purposes only. Please add your own domain or add the address to authoriz LARAVEL
i got this error when i try to test method in my controller </p>

```<code> GuzzleHttp\Exception\ClientException: Client error: `POST https://api.mailgun.net/v3/sandbox22f99fb37d4a4953a7b8d84cf89d1147.mailgun.org/messages.mime` resulted in a `400 BAD REQUEST` response:
{
  "message": "Sandbox subdomains are for test purposes only. Please add your own domain or add the address to authoriz (truncated...)
</code>```

答:
This is the sandbox domain. You need to verify your own domain or verify the recipient in order to send an email to others.They are for test, not for API implementation

Read more : https://documentation.mailgun.com/faqs.html#how-do-i-pick-a-domain-name-for-my-mailgun-account

Follow the link to add recipients: https://mailgun.com/app/testing/recipients

Body:
i got this error when i try to test method in my controller

 GuzzleHttp\Exception\ClientException: Client error: `POST https://api.mailgun.net/v3/sandbox22f99fb37d4a4953a7b8d84cf89d1147.mailgun.org/messages.mime` resulted in a `400 BAD REQUEST` response:
{
  "message": "Sandbox subdomains are for test purposes only. Please add your own domain or add the address to authoriz (truncated...)


问:
Android - SQlite check if value in row exists
This question is similar to this and this.

I have 4 columns in my database (id, name, surname, image). I only want to check if the name that is being entered already exists in "name" column.

here is my SQLiteOpenHelper:

```<code>public class SQLiteHelper extends SQLiteOpenHelper {

public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, name, factory, version);
}

public void queryData(String sql){
    SQLiteDatabase database = getWritableDatabase();
    database.execSQL(sql);
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {

}

public void insertData(String name, String surname, byte[] image){
    SQLiteDatabase database = getWritableDatabase();
    String sql = "INSERT INTO STUDENTS VALUES (NULL, ?, ?, ?)";

    SQLiteStatement statement = database.compileStatement(sql);
    statement.clearBindings();

    statement.bindString(1, name);
    statement.bindString(2, surname);
    statement.bindBlob(3, image);

    statement.executeInsert();

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

}

/*public void removeSingleContact(String name, String price, byte[] image) {

    SQLiteDatabase dbb = getWritableDatabase();
    dbb.delete(name, surname, image);

}*/

public Cursor getData(String sql){
    SQLiteDatabase database = getReadableDatabase();
    return database.rawQuery(sql, null);
}

}
</code>```

and this is how I add to SQlite;

```<code>public class AddEditStudent extends AppCompatActivity {

    public static SQLiteHelper sqLiteHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addedit_student);

        sqLiteHelper = new SQLiteHelper(this, "StudentsDB.sqlite", null, 1);

        sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS STUDENTS(Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, surname VARCHAR, image BLOB)");

            btnAdd.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {

                        if (edtName.getText().toString().trim().length() == 0) {
                            Toast.makeText(getApplicationContext(), "Please provide your students name", Toast.LENGTH_SHORT).show();

                        } else
                            try {

                                    //THIS IS WHERE I WANT TO CHECK---------

                                    sqLiteHelper.insertData(
                                            edtName.getText().toString().trim(),
                                            edtPrice.getText().toString().trim(),
                                            imageViewToByte(imageView)

                                    );

                                        Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();

                                        finish();
                                    }

                                }
                            } catch (Exception e) {
                            e.printStackTrace();
                            }

                    }
                });
</code>```

EDIT----
Thank you for the help so far. I have 2 buttons, one for update and one for insert, the problem I am facing is how will I know what row to update without using an ID. I have a gridview that is being populated by cardviews, in the cardview there is a button to edit info, please see image.

https://i.stack.imgur.com/aFJTl.png

If I click on the exit sign I do;

```<code>holder.dit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // Do something
                Intent editintent = new Intent(context, AddEditStudent.class);
                editintent.putExtra("studentname", finalHolder.txtName.getText().toString());
                editintent.putExtra("studentsurname", finalHolder.txtPrice.getText().toString());

                context.startActivity(editintent);
            }
        });
</code>```

then in AddEditStudent Class is where the insert and update is.

答:
One approach would be to let a unique constraint on the name column handle the possibility of duplicate names.  Then, attemtps to insert a duplicate name would fail at the database level.

```<code>CREATE TABLE IF NOT EXISTS STUDENTS (
    Id INTEGER PRIMARY KEY AUTOINCREMENT,
    name VARCHAR,
    surname VARCHAR,
    image BLOB,
    CONSTRAINT constraint_name UNIQUE (name)
)
</code>```

Note that it is not possible to add a unique constraint to an already existing table.  Instead, you will have to create a new one.

From the documentation for SQLiteStatement#executeInsert(), this method returns:

the row ID of the last row inserted, if this insert is successful. -1 otherwise.

In other words, with a unique constraint on the name column, this call to insert data should return -1.  You can update your code to check this return value and act accordingly (you are not currently checking the return value at all).

Body:
This question is similar to this and this.

I have 4 columns in my database (id, name, surname, image). I only want to check if the name that is being entered already exists in "name" column.

here is my SQLiteOpenHelper:

public class SQLiteHelper extends SQLiteOpenHelper {

public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, name, factory, version);
}

public void queryData(String sql){
    SQLiteDatabase database = getWritableDatabase();
    database.execSQL(sql);
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {

}

public void insertData(String name, String surname, byte[] image){
    SQLiteDatabase database = getWritableDatabase();
    String sql = "INSERT INTO STUDENTS VALUES (NULL, ?, ?, ?)";

    SQLiteStatement statement = database.compileStatement(sql);
    statement.clearBindings();

    statement.bindString(1, name);
    statement.bindString(2, surname);
    statement.bindBlob(3, image);

    statement.executeInsert();

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

}

/*public void removeSingleContact(String name, String price, byte[] image) {

    SQLiteDatabase dbb = getWritableDatabase();
    dbb.delete(name, surname, image);

}*/

public Cursor getData(String sql){
    SQLiteDatabase database = getReadableDatabase();
    return database.rawQuery(sql, null);
}

}

and this is how I add to SQlite;

public class AddEditStudent extends AppCompatActivity {

    public static SQLiteHelper sqLiteHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addedit_student);

        sqLiteHelper = new SQLiteHelper(this, "StudentsDB.sqlite", null, 1);

        sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS STUDENTS(Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, surname VARCHAR, image BLOB)");

            btnAdd.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {

                        if (edtName.getText().toString().trim().length() == 0) {
                            Toast.makeText(getApplicationContext(), "Please provide your students name", Toast.LENGTH_SHORT).show();

                        } else
                            try {

                                    //THIS IS WHERE I WANT TO CHECK---------

                                    sqLiteHelper.insertData(
                                            edtName.getText().toString().trim(),
                                            edtPrice.getText().toString().trim(),
                                            imageViewToByte(imageView)

                                    );

                                        Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();

                                        finish();
                                    }

                                }
                            } catch (Exception e) {
                            e.printStackTrace();
                            }

                    }
                });

EDIT----
Thank you for the help so far. I have 2 buttons, one for update and one for insert, the problem I am facing is how will I know what row to update without using an ID. I have a gridview that is being populated by cardviews, in the cardview there is a button to edit info, please see image.

https://i.stack.imgur.com/aFJTl.png

If I click on the exit sign I do;

holder.dit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // Do something
                Intent editintent = new Intent(context, AddEditStudent.class);
                editintent.putExtra("studentname", finalHolder.txtName.getText().toString());
                editintent.putExtra("studentsurname", finalHolder.txtPrice.getText().toString());

                context.startActivity(editintent);
            }
        });

then in AddEditStudent Class is where the insert and update is.

Body:
One approach would be to let a unique constraint on the name column handle the possibility of duplicate names.  Then, attemtps to insert a duplicate name would fail at the database level.

CREATE TABLE IF NOT EXISTS STUDENTS (
    Id INTEGER PRIMARY KEY AUTOINCREMENT,
    name VARCHAR,
    surname VARCHAR,
    image BLOB,
    CONSTRAINT constraint_name UNIQUE (name)
)

Note that it is not possible to add a unique constraint to an already existing table.  Instead, you will have to create a new one.

From the documentation for SQLiteStatement#executeInsert(), this method returns:

the row ID of the last row inserted, if this insert is successful. -1 otherwise.

In other words, with a unique constraint on the name column, this call to insert data should return -1.  You can update your code to check this return value and act accordingly (you are not currently checking the return value at all).


问:
How to continue in a loop when the file does not exist?
This script download many files. However, I want the loop to continue when it doesn't find any file: File mot found. </p>

```<code>for ii=1:length(t2)
   d=t2(ii);
   if year(d)>=2011
       download(d)

 end
end
</code>```

<p>Any ideas? Thanks </p>

答:
I'm guessing download is a function that downloads something from a server, so I don't see how exist will work. Either way, you can simply use a try catch block:

```<code>for ii=1:length(t2)
    d=t2(ii);
    if year(d)>=2011
        try
            download(d)
        catch
        end
    end
end
</code>```

Body:
This script download many files. However, I want the loop to continue when it doesn't find any file: File mot found.

for ii=1:length(t2)
   d=t2(ii);
   if year(d)>=2011
       download(d)

 end
end

Any ideas? Thanks

Body:
I'm guessing download is a function that downloads something from a server, so I don't see how exist will work. Either way, you can simply use a try catch block:

for ii=1:length(t2)
    d=t2(ii);
    if year(d)>=2011
        try
            download(d)
        catch
        end
    end
end


问:
Space Complexity of an array?
I have an array of size N, and N is <=200.

What would be the space complexity here.

O(1) or (N) - considering the constraint N.

答:
I think it will be O(1).space complexity is O(n) if the space size increase linearly with increase of n.But in your case the function is not dependent on n after 200;
f(n)=a*n+b.. </p>

Title: Space Complexity of an array?


问:
How to draw a chart in Google App Engine?
I wonder Google App Engine can return a chart ?

What I want is a statistical chart, is there a way for my app in Google App Engine to create a .png chart then return it to the browser ?

For instance when I click a url such as :

http://My_App.appspot.com/Show_App_Stats

It will show me a graphic chart.

答: Your best bet is to use the Google Visualization API.  </p>

ContentLicense: CC BY-SA 2.5


问:
SQL SERVER: SELECT TOP 1 entire row into "ROW" variable
I am trying to store the entire row as a result of the SELECT TOP * into a kind of "datarow" variable because later, depending on some condition, I need to insert this entire row to a temporary table.

For example, I have done below. The problem is that first I have to assign the values resulting from select top 1 * to variables and then using all these variables to insert into the temporary table, so I want to avoid this, I would like to insert the entire row of select top 1 * into the temporary table at once, see below.

Current scenario:

```<code>DECLARE @Field1 varchar(50)
DECLARE @Field2 int
DECLARE @Field3 DateTime

CREATE TABLE #tmpTbl(Field1 varchar(50),  Field2 int, Field3 DateTime)

SELECT TOP 1 @Field1 = field1, @Field2 = field2, @Field3 = field3 from OneTable

// EXECUTE STORE PROCEDURE
DECLARE @ReturnValue int
EXEC @ReturnValue=MySp @Field1

IF @ReturnValue > 0
   INSERT INTO #tmpTbl (Field1, Field2, Field3)
          VALUES (@Field1, @Field2, @Field3)
</code>```

And I would like to do something like this, if possible:

Desired scenario:

```<code>DECLARE @Row SOME_KIND_OF_DATA_ROW_VARIABLE

SET @Row = SELECT TOP 1 field1, field2, field3 from OneTable

// EXECUTE STORE PROCEDURE
DECLARE @ReturnValue int
EXEC @ReturnValue=MySp @Field1

IF @ReturnValue > 0
   INSERT INTO #tmpTbl (Field1, Field2, Field3)
          VALUES @Row <-- Obviously, this is incorrect, but I would like to insert the entire row at once
</code>```

答:
If the time that the row is extracted isn't important (i.e. you can SELECT it out within the IF block happily), you can use an INSERT INTO ... SELECT FROM combination to achieve the desired effect with something like this:

```<code>CREATE TABLE #tmpTbl(Field1 varchar(50),  Field2 int, Field3 DateTime)

--EXECUTE STORE PROCEDURE
DECLARE @ReturnValue int
EXEC @ReturnValue=MySp @Field1

IF @ReturnValue > 0
BEGIN
    INSERT INTO #tmpTbl (Field1, Field2, Field3)
    SELECT TOP 1 field1, field2, field3 from OneTable
END
</code>```

Body:
I am trying to store the entire row as a result of the SELECT TOP * into a kind of "datarow" variable because later, depending on some condition, I need to insert this entire row to a temporary table.

For example, I have done below. The problem is that first I have to assign the values resulting from select top 1 * to variables and then using all these variables to insert into the temporary table, so I want to avoid this, I would like to insert the entire row of select top 1 * into the temporary table at once, see below.

Current scenario:

DECLARE @Field1 varchar(50)
DECLARE @Field2 int
DECLARE @Field3 DateTime

CREATE TABLE #tmpTbl(Field1 varchar(50),  Field2 int, Field3 DateTime)

SELECT TOP 1 @Field1 = field1, @Field2 = field2, @Field3 = field3 from OneTable

// EXECUTE STORE PROCEDURE
DECLARE @ReturnValue int
EXEC @ReturnValue=MySp @Field1

IF @ReturnValue > 0
   INSERT INTO #tmpTbl (Field1, Field2, Field3)
          VALUES (@Field1, @Field2, @Field3)

And I would like to do something like this, if possible:

Desired scenario:

DECLARE @Row SOME_KIND_OF_DATA_ROW_VARIABLE

SET @Row = SELECT TOP 1 field1, field2, field3 from OneTable

// EXECUTE STORE PROCEDURE
DECLARE @ReturnValue int
EXEC @ReturnValue=MySp @Field1

IF @ReturnValue > 0
   INSERT INTO #tmpTbl (Field1, Field2, Field3)
          VALUES @Row <-- Obviously, this is incorrect, but I would like to insert the entire row at once

Body:
If the time that the row is extracted isn't important (i.e. you can SELECT it out within the IF block happily), you can use an INSERT INTO ... SELECT FROM combination to achieve the desired effect with something like this:

CREATE TABLE #tmpTbl(Field1 varchar(50),  Field2 int, Field3 DateTime)

--EXECUTE STORE PROCEDURE
DECLARE @ReturnValue int
EXEC @ReturnValue=MySp @Field1

IF @ReturnValue > 0
BEGIN
    INSERT INTO #tmpTbl (Field1, Field2, Field3)
    SELECT TOP 1 field1, field2, field3 from OneTable
END


问:
Apple says you cannot mix page-based and hierarchal navigation in a Watch app. But the Activity app does. How?
Apple's developer guide says that you cannot mix page-based and hierarchical navigation in a Watch App:

Although you cannot mix page-based and hierarchical navigation styles in your app, you can supplement these base navigation styles with modal presentations.

This appears to be true, as calling pushControllerWithName:context: from a view with page segues does nothing.

However, in Apple's Activity App, you can swipe between the Activity and Sharing pages, but when you click on a person's name in the Sharing page, it uses a hierarchal-style (not modal) transition to that person's activity.

How is this being done? Is there a custom view type being used?

答:
You can mix hierarchical and page-based Interface Controllers easily in WatchKit. The only restriction is that you can't mix different navigation types in your root controller. But as soon as you are navigating to a different Interface Controller, you can do it modally or in a hierarchical way.

You can present page based InterfaceControllers modally using self.presentController(withNames:,contexts:). You can also present a single view controller using hierarchical navigation with self.pushController(withName:, context:)


问:
Star before and after variables in c# documentation
The following code, what are the '*' doing?</p>

```<code>for (Char* ptr1 = (Char*)bstr1.ToPointer(), ptr2 = (Char*)bstr2.ToPointer();
                    *ptr1 != 0 && *ptr2 != 0;
</code>```

答: These are pointers. Normally, basic variables (like char, int, float, ...) are passed as values. Which means that if you pass that variable into a method and change the value inside that method, tha variable in the callers context won't be changed at all. Complex tapes (classes) are passed as reference. You change them in the called method and they also change in the caller. With pointers you can pass basic variables references and hence change them in the called method and they also change in the caller. You can also do a bunch of other stuff with pointer. They are a complex construct. I wouldn't recommend to work with them in C#.</p>

Body:
The following code, what are the '*' doing?

for (Char* ptr1 = (Char*)bstr1.ToPointer(), ptr2 = (Char*)bstr2.ToPointer();
                    *ptr1 != 0 && *ptr2 != 0;


问:
Object Oriented questions in Javascript
I've been using javascript for a while, but have never learned the language past the basics.  I am reading John Resig's "Pro Javascript Techniques" - I'm coming up with some questions, but I'm not finding the answers to them in the book or on google, etc.

John gives this example in his book:

Function #1

```<code>function User( name, age ){
  this.name = name;
  this.age = age;
}
// Add a new function to the object prototype
User.prototype.getName = function(){
  return this.name;
};
User.prototype.getAge = function(){
  return this.age;
};
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());
</code>```

I'm still learning about the prototype property, so I tried writing something similar:

Function #2

```<code>function User (name, age ) {
  this.name = name;
  this.age = age;
  this.getName = function() {
    return this.name;
  };
  this.getAge = function() {
    return this.age;
  };
}
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());
</code>```

It doesn't use the prototype property to create the getName and getAge functions, but the output is the same as John's example.

I took it one step further, and created this:

Function #3

```<code>var User = {
  name: "",
  age: 0,
  setName: function(name) {
    this.name = name;
  },
  setAge: function(age) {
    this.age = age;
  },
  getName: function() {
    return this.name;
  },
  getAge: function() {
    return this.age;
  }
};
User.setName("Bob");
User.setAge(44);
console.log("User: " + User.getName() + ", Age: " + User.getAge());
</code>```

Again - it looks different than John's example (and I had to add setter methods), but the output is the same.

Question #1 - what is the difference between the 3 functions?  What is the advantage of the prototype property, and is Function #2 doing anything incorrectly, because it seems more straight forward to code #2 instead of #1 (although I'm sure #1 is doing it better seeing as John created it).

Question #2 - How could I modify function #3 to not use the setName and setAge methods, but still keep the {...} shorthand?  Can the {...} shorthand have constructors?

Thanks in advance for helping me learn!

EDIT
I think my 2nd question was a little confusing. I meant how could I use the {...} shorthand to create a User object, but then after I create the object, say something like:

```<code>var user = new User("Bob", 44);
</code>```

Just like in Function #1 - or is that not possible?

EDIT #2
Wow!  Thanks everyone for the awesome answers.  That really makes it a lot more clear to me.  So if I understand correctly, the difference between #1 and #2 aren't too much.  If I only ever create one "User" object - they probably aren't different at all.  But if my program creates many User objects, #1 would most likely be more efficient and use less memory since all objects will share the same functions.

I really appreciate all of the great answers - Thanks!

答:
If you want to do OOP in JavaScript I'd highly suggest looking up closures.  I began my learning on the subject with these three web pages:

http://www.dustindiaz.com/javascript-private-public-privileged/

http://www.dustindiaz.com/namespace-your-javascript/

http://blog.morrisjohns.com/javascript_closures_for_dummies

The differences between 1, 2, and 3 are as follows:
1) Is an example of adding new methods to an existing object.
2) Is the same as #1 except some methods are included in the object in the User function.
3) Is an example of defining an object using JSON.  The shortcoming is that you cannot use new (at least not with that example) to define new instances of that object.  However you do get the benefit of the convenient JSON coding style.

You should definitely read up on JSON if you don't know it yet.  JavaScript will make a lot more sense when you understand JSON.

edit
If you want to use new in function #3 you can write it as

```<code>function User() {
  return {
    name: "",
    age: 0,
    setName: function(name) {
      this.name = name;
    },
    setAge: function(age) {
      this.age = age;
    },
    getName: function() {
      return this.name;
    },
    getAge: function() {
      return this.age;
    }
  };
}
</code>```

Of course all of those functions and properties would then be public.  To make them private you need to use closures.  For example you could make age and name private with this syntax.

```<code>function User() {
  var age=0;
  var name="";
  return {
    setName: function(name_) {
      name = name_;
    },
    setAge: function(age_) {
      age = age_;
    },
    getName: function() {
      return name;
    },
    getAge: function() {
      return age;
    }
  };
}
</code>```

OwnerDisplayName: BrianH

Title: Object Oriented questions in Javascript

Body:
I've been using javascript for a while, but have never learned the language past the basics.  I am reading John Resig's "Pro Javascript Techniques" - I'm coming up with some questions, but I'm not finding the answers to them in the book or on google, etc.

John gives this example in his book:

Function #1

function User( name, age ){
  this.name = name;
  this.age = age;
}
// Add a new function to the object prototype
User.prototype.getName = function(){
  return this.name;
};
User.prototype.getAge = function(){
  return this.age;
};
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());

I'm still learning about the prototype property, so I tried writing something similar:

Function #2

function User (name, age ) {
  this.name = name;
  this.age = age;
  this.getName = function() {
    return this.name;
  };
  this.getAge = function() {
    return this.age;
  };
}
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());

It doesn't use the prototype property to create the getName and getAge functions, but the output is the same as John's example.

I took it one step further, and created this:

Function #3

var User = {
  name: "",
  age: 0,
  setName: function(name) {
    this.name = name;
  },
  setAge: function(age) {
    this.age = age;
  },
  getName: function() {
    return this.name;
  },
  getAge: function() {
    return this.age;
  }
};
User.setName("Bob");
User.setAge(44);
console.log("User: " + User.getName() + ", Age: " + User.getAge());

Again - it looks different than John's example (and I had to add setter methods), but the output is the same.

Question #1 - what is the difference between the 3 functions?  What is the advantage of the prototype property, and is Function #2 doing anything incorrectly, because it seems more straight forward to code #2 instead of #1 (although I'm sure #1 is doing it better seeing as John created it).

Question #2 - How could I modify function #3 to not use the setName and setAge methods, but still keep the {...} shorthand?  Can the {...} shorthand have constructors?

Thanks in advance for helping me learn!

EDIT
I think my 2nd question was a little confusing. I meant how could I use the {...} shorthand to create a User object, but then after I create the object, say something like:

var user = new User("Bob", 44);

Just like in Function #1 - or is that not possible?

EDIT #2
Wow!  Thanks everyone for the awesome answers.  That really makes it a lot more clear to me.  So if I understand correctly, the difference between #1 and #2 aren't too much.  If I only ever create one "User" object - they probably aren't different at all.  But if my program creates many User objects, #1 would most likely be more efficient and use less memory since all objects will share the same functions.

I really appreciate all of the great answers - Thanks!

LastEditorDisplayName: BrianH

Body:
If you want to do OOP in JavaScript I'd highly suggest looking up closures.  I began my learning on the subject with these three web pages:

http://www.dustindiaz.com/javascript-private-public-privileged/

http://www.dustindiaz.com/namespace-your-javascript/

http://blog.morrisjohns.com/javascript_closures_for_dummies

The differences between 1, 2, and 3 are as follows:
1) Is an example of adding new methods to an existing object.
2) Is the same as #1 except some methods are included in the object in the User function.
3) Is an example of defining an object using JSON.  The shortcoming is that you cannot use new (at least not with that example) to define new instances of that object.  However you do get the benefit of the convenient JSON coding style.

You should definitely read up on JSON if you don't know it yet.  JavaScript will make a lot more sense when you understand JSON.

edit
If you want to use new in function #3 you can write it as

function User() {
  return {
    name: "",
    age: 0,
    setName: function(name) {
      this.name = name;
    },
    setAge: function(age) {
      this.age = age;
    },
    getName: function() {
      return this.name;
    },
    getAge: function() {
      return this.age;
    }
  };
}

Of course all of those functions and properties would then be public.  To make them private you need to use closures.  For example you could make age and name private with this syntax.

function User() {
  var age=0;
  var name="";
  return {
    setName: function(name_) {
      name = name_;
    },
    setAge: function(age_) {
      age = age_;
    },
    getName: function() {
      return name;
    },
    getAge: function() {
      return age;
    }
  };
}


问:
MS SQL Server Row GUID Column
I apologize for asking what seems like a tired question, but no forum response or documentation I've read seems to provide an adequate answer.

What is the purpose of the Row GUID Column property in MS SQL Server 2008?

Let me extend on that. I've seen "Don't use GUID as the PK" repeated as the answer for this question, which seems to be completely unrelated to me. If I set Row GUID Column is it forcing that GUID column to be the primary key or something?

To rephrase my original question: If I have a GUID column in my table that does not play any role in indexing, do I stand to gain anything from setting that GUID column as the Row GUID Column?

答:
RowGUID column is used for replication. It allows the replication engine to merge correctly. When replication is enabled this column will be added to tables that do not already have a RowGUID column.

You will not gain anything by using it unless you are planning to implement replication. It is equivalent to setting newsequentialid() as the default value for a column.

Title: MS SQL Server Row GUID Column


问:
Rails find all order, found 0 results expected 2
I'm having trouble sorting my table based on the votes column, votes is a multivalued attribute so I use count and try to sort it based on that. here is the code

```<code>@topics = Topic.find(:all,:order=>'@topic.votes.count DESC')
</code>```

Rails returns an error that says

```<code>ActiveRecord::RecordNotFound in TopicsController#index
Couldn't find all Topics with 'id': (all, {:order=>"@topic.votes.count DESC"}) (found 0 results, but was looking for 2)
</code>```

Just starting out with rails and still confused with some things, your help will be much appreciated.

答:
this is Rails 2 syntax being used in higher Rails version.

You can do something like this:

```<code>Topic.joins(:votes).group('topics.id').order('count(topics.id) DESC')
</code>```

Body:
I'm having trouble sorting my table based on the votes column, votes is a multivalued attribute so I use count and try to sort it based on that. here is the code

@topics = Topic.find(:all,:order=>'@topic.votes.count DESC')

Rails returns an error that says

ActiveRecord::RecordNotFound in TopicsController#index
Couldn't find all Topics with 'id': (all, {:order=>"@topic.votes.count DESC"}) (found 0 results, but was looking for 2)

Just starting out with rails and still confused with some things, your help will be much appreciated.

Body:
this is Rails 2 syntax being used in higher Rails version.

You can do something like this:

Topic.joins(:votes).group('topics.id').order('count(topics.id) DESC')


问:
Which files to edit for HTML/CSS in my application (ruby)
I made my application with the following introduction:
http://guides.rubyonrails.org/getting_started.html

Now I want to make it more colourful etc (CSS f.eg).
I found now the JavaScript and CSS files, but I dont know which file are responsible for the editing.

[![enter image description here][1]][1]

Which file should I use for editing the websites?

答:
As the name suggests, "Getting Started", that was just the introduction to Rails framework and how MVC works.

At the end, there's a section What's next?. Follow the tutorial link there and all your doubts will be cleared.

Hint: There's much more to Rails..


问:
How to change already compiled .class file without decompile?
I want to change .class file's method. I installed JD Eclipse Decompiler and opened the .class file. I added some codes and save .class file. But, .class file is not changing.

I don't know how to use decompiler. And if is it possible, how to change .class file without using decompiler.

I am using Ubuntu.

Regards

EDIT:

Here is my decompiled code:

```<code>/*     */ package org.hibernate.id;
/*     */
/*     */ import java.io.Serializable;
/*     */ import java.sql.ResultSet;
/*     */ import java.sql.SQLException;
/*     */ import java.util.HashMap;
/*     */ import java.util.Properties;
/*     */ import org.apache.commons.logging.Log;
/*     */ import org.apache.commons.logging.LogFactory;
/*     */ import org.hibernate.HibernateException;
/*     */ import org.hibernate.MappingException;
/*     */ import org.hibernate.dialect.Dialect;
/*     */ import org.hibernate.type.Type;
/*     */ import org.hibernate.util.ReflectHelper;
/*     */
/*     */ public final class IdentifierGeneratorFactory
/*     */ {
/*  25 */   private static final Log log = LogFactory.getLog(IdentifierGeneratorFactory.class);
/*     */
/*  64 */   private static final HashMap GENERATORS = new HashMap();
/*     */
/*  66 */   public static final Serializable SHORT_CIRCUIT_INDICATOR = new Serializable() {
/*     */     public String toString() { return "SHORT_CIRCUIT_INDICATOR";
/*     */     }
/*  66 */   };
/*     */
/*  70 */   public static final Serializable POST_INSERT_INDICATOR = new Serializable() {
/*     */     public String toString() { return "POST_INSERT_INDICATOR";
/*     */     }
/*  70 */   };
/*     */
/*     */   public static Serializable getGeneratedIdentity(ResultSet rs, Type type)
/*     */     throws SQLException, HibernateException, IdentifierGenerationException
/*     */   {
/*  32 */     if (!(rs.next())) {
/*  33 */       throw new HibernateException("The database returned no natively generated identity value");
/*     */     }
/*  35 */     Serializable id = get(rs, type);
/*     */
/*  37 */     if (log.isDebugEnabled()) log.debug("Natively generated identity: " + id);
/*  38 */     return id;
/*     */   }
/*     */
/*     */   public static Serializable get(ResultSet rs, Type type)
/*     */     throws SQLException, IdentifierGenerationException
/*     */   {
/*  45 */     Class clazz = type.getReturnedClass();
/*  46 */     if (clazz == Long.class) {
/*  47 */       return new Long(rs.getLong(1));
/*     */     }
/*  49 */     if (clazz == Integer.class) {
/*  50 */       return new Integer(rs.getInt(1));
/*     */     }
/*  52 */     if (clazz == Short.class) {
/*  53 */       return new Short(rs.getShort(1));
/*     */     }
/*  55 */     if (clazz == String.class) {
/*  56 */       return rs.getString(1);
/*     */     }
                if(clazz == java.math.BigDecimal.class){
                    return rs.getBigDecimal(1);
                }
/*     */
/*  59 */     throw new IdentifierGenerationException("this id generator generates long, integer, short or string78");
/*     */   }
/*     */
/*     */   public static IdentifierGenerator create(String strategy, Type type, Properties params, Dialect dialect)
/*     */     throws MappingException
/*     */   {
/*     */     try
/*     */     {
/*  92 */       Class clazz = getIdentifierGeneratorClass(strategy, dialect);
/*  93 */       IdentifierGenerator idgen = (IdentifierGenerator)clazz.newInstance();
/*  94 */       if (idgen instanceof Configurable) ((Configurable)idgen).configure(type, params, dialect);
/*  95 */       return idgen;
/*     */     }
/*     */     catch (Exception e) {
/*  98 */       throw new MappingException("could not instantiate id generator", e);
/*     */     }
/*     */   }
/*     */
/*     */   public static Class getIdentifierGeneratorClass(String strategy, Dialect dialect) {
/* 103 */     Class clazz = (Class)GENERATORS.get(strategy);
/* 104 */     if ("native".equals(strategy)) clazz = dialect.getNativeIdentifierGeneratorClass();
/*     */     try {
/* 106 */       if (clazz == null) clazz = ReflectHelper.classForName(strategy);
/*     */     }
/*     */     catch (ClassNotFoundException e) {
/* 109 */       throw new MappingException("could not interpret id generator strategy: " + strategy);
/*     */     }
/* 111 */     return clazz;
/*     */   }
/*     */
/*     */   public static Number createNumber(long value, Class clazz) throws IdentifierGenerationException {
/* 115 */     if (clazz == Long.class) {
/* 116 */       return new Long(value);
/*     */     }
/* 118 */     if (clazz == Integer.class) {
/* 119 */       return new Integer((int)value);
/*     */     }
/* 121 */     if (clazz == Short.class) {
/* 122 */       return new Short((short)(int)value);
/*     */     }

/*     */
/* 125 */     throw new IdentifierGenerationException("this id generator generates long, integer, short");
/*     */   }
/*     */
/*     */   static
/*     */   {
/*  75 */     GENERATORS.put("uuid", UUIDHexGenerator.class);
    GENERATORS.put("hilo", TableHiLoGenerator.class);
     GENERATORS.put("assigned", Assigned.class);
     GENERATORS.put("identity", IdentityGenerator.class);
    GENERATORS.put("select", SelectGenerator.class);
    GENERATORS.put("sequence", SequenceGenerator.class);
     GENERATORS.put("seqhilo", SequenceHiLoGenerator.class);
    GENERATORS.put("increment", IncrementGenerator.class);
   GENERATORS.put("foreign", ForeignGenerator.class);
     GENERATORS.put("guid", GUIDGenerator.class);
     GENERATORS.put("uuid.hex", UUIDHexGenerator.class);
     GENERATORS.put("sequence-identity", SequenceIdentityGenerator.class);
   }
 }
</code>```

答:
You can use any decompiler to first decompile the file.

I had once faced a simillar problem where I didn't have source code of the application and had to make a very small change in a file.

Below is what I did:

Extracted the class file from the jar

Opened it in a decompiler (I use JD GUI, you can get it easily from many resources on internet)
You may download it from here

You can actually view all the files in a jar using JD GUI.

Made changes to the file I wanted to and copied all the code from that file

Created a new project in eclipse with only this class (with the same package structure as in the jar), provided the original jar as library and all other dependencies.

Compiled the class, injected the .class file back to the jar from bin folder of my workspace

Tested my change, celebrated it by sipping a cup of coffee :)

Body:
I want to change .class file's method. I installed JD Eclipse Decompiler and opened the .class file. I added some codes and save .class file. But, .class file is not changing.

I don't know how to use decompiler. And if is it possible, how to change .class file without using decompiler.

I am using Ubuntu.

Regards

EDIT:

Here is my decompiled code:

/*     */ package org.hibernate.id;
/*     */
/*     */ import java.io.Serializable;
/*     */ import java.sql.ResultSet;
/*     */ import java.sql.SQLException;
/*     */ import java.util.HashMap;
/*     */ import java.util.Properties;
/*     */ import org.apache.commons.logging.Log;
/*     */ import org.apache.commons.logging.LogFactory;
/*     */ import org.hibernate.HibernateException;
/*     */ import org.hibernate.MappingException;
/*     */ import org.hibernate.dialect.Dialect;
/*     */ import org.hibernate.type.Type;
/*     */ import org.hibernate.util.ReflectHelper;
/*     */
/*     */ public final class IdentifierGeneratorFactory
/*     */ {
/*  25 */   private static final Log log = LogFactory.getLog(IdentifierGeneratorFactory.class);
/*     */
/*  64 */   private static final HashMap GENERATORS = new HashMap();
/*     */
/*  66 */   public static final Serializable SHORT_CIRCUIT_INDICATOR = new Serializable() {
/*     */     public String toString() { return "SHORT_CIRCUIT_INDICATOR";
/*     */     }
/*  66 */   };
/*     */
/*  70 */   public static final Serializable POST_INSERT_INDICATOR = new Serializable() {
/*     */     public String toString() { return "POST_INSERT_INDICATOR";
/*     */     }
/*  70 */   };
/*     */
/*     */   public static Serializable getGeneratedIdentity(ResultSet rs, Type type)
/*     */     throws SQLException, HibernateException, IdentifierGenerationException
/*     */   {
/*  32 */     if (!(rs.next())) {
/*  33 */       throw new HibernateException("The database returned no natively generated identity value");
/*     */     }
/*  35 */     Serializable id = get(rs, type);
/*     */
/*  37 */     if (log.isDebugEnabled()) log.debug("Natively generated identity: " + id);
/*  38 */     return id;
/*     */   }
/*     */
/*     */   public static Serializable get(ResultSet rs, Type type)
/*     */     throws SQLException, IdentifierGenerationException
/*     */   {
/*  45 */     Class clazz = type.getReturnedClass();
/*  46 */     if (clazz == Long.class) {
/*  47 */       return new Long(rs.getLong(1));
/*     */     }
/*  49 */     if (clazz == Integer.class) {
/*  50 */       return new Integer(rs.getInt(1));
/*     */     }
/*  52 */     if (clazz == Short.class) {
/*  53 */       return new Short(rs.getShort(1));
/*     */     }
/*  55 */     if (clazz == String.class) {
/*  56 */       return rs.getString(1);
/*     */     }
                if(clazz == java.math.BigDecimal.class){
                    return rs.getBigDecimal(1);
                }
/*     */
/*  59 */     throw new IdentifierGenerationException("this id generator generates long, integer, short or string78");
/*     */   }
/*     */
/*     */   public static IdentifierGenerator create(String strategy, Type type, Properties params, Dialect dialect)
/*     */     throws MappingException
/*     */   {
/*     */     try
/*     */     {
/*  92 */       Class clazz = getIdentifierGeneratorClass(strategy, dialect);
/*  93 */       IdentifierGenerator idgen = (IdentifierGenerator)clazz.newInstance();
/*  94 */       if (idgen instanceof Configurable) ((Configurable)idgen).configure(type, params, dialect);
/*  95 */       return idgen;
/*     */     }
/*     */     catch (Exception e) {
/*  98 */       throw new MappingException("could not instantiate id generator", e);
/*     */     }
/*     */   }
/*     */
/*     */   public static Class getIdentifierGeneratorClass(String strategy, Dialect dialect) {
/* 103 */     Class clazz = (Class)GENERATORS.get(strategy);
/* 104 */     if ("native".equals(strategy)) clazz = dialect.getNativeIdentifierGeneratorClass();
/*     */     try {
/* 106 */       if (clazz == null) clazz = ReflectHelper.classForName(strategy);
/*     */     }
/*     */     catch (ClassNotFoundException e) {
/* 109 */       throw new MappingException("could not interpret id generator strategy: " + strategy);
/*     */     }
/* 111 */     return clazz;
/*     */   }
/*     */
/*     */   public static Number createNumber(long value, Class clazz) throws IdentifierGenerationException {
/* 115 */     if (clazz == Long.class) {
/* 116 */       return new Long(value);
/*     */     }
/* 118 */     if (clazz == Integer.class) {
/* 119 */       return new Integer((int)value);
/*     */     }
/* 121 */     if (clazz == Short.class) {
/* 122 */       return new Short((short)(int)value);
/*     */     }

/*     */
/* 125 */     throw new IdentifierGenerationException("this id generator generates long, integer, short");
/*     */   }
/*     */
/*     */   static
/*     */   {
/*  75 */     GENERATORS.put("uuid", UUIDHexGenerator.class);
    GENERATORS.put("hilo", TableHiLoGenerator.class);
     GENERATORS.put("assigned", Assigned.class);
     GENERATORS.put("identity", IdentityGenerator.class);
    GENERATORS.put("select", SelectGenerator.class);
    GENERATORS.put("sequence", SequenceGenerator.class);
     GENERATORS.put("seqhilo", SequenceHiLoGenerator.class);
    GENERATORS.put("increment", IncrementGenerator.class);
   GENERATORS.put("foreign", ForeignGenerator.class);
     GENERATORS.put("guid", GUIDGenerator.class);
     GENERATORS.put("uuid.hex", UUIDHexGenerator.class);
     GENERATORS.put("sequence-identity", SequenceIdentityGenerator.class);
   }
 }


问:
wrong tab configuration issue magento with magemonkey
There has been an error processing your request
Wrong tab configuration.</p>

```<code>Trace:
#0 [internal function]: Mage_Adminhtml_Block_Widget_Tabs->addTab('customer_edit_t...', 'monkey/adminhtm...')
#1 /chroot/home/differe1/differentdrop.com/html/app/code/community/Codnitive/Extifcon/Model/Core/Layout.php(132): call_user_func_array(Array, Array)
#2 /chroot/home/differe1/differentdrop.com/html/app/code/community/Codnitive/Extifcon/Model/Core/Layout.php(70): Codnitive_Extifcon_Model_Core_Layout->_runAction(Object(Mage_Core_Model_Layout_Element), Object(Mage_Core_Model_Layout_Element))
#3 /chroot/home/differe1/differentdrop.com/html/app/code/core/Mage/Core/Model/Layout.php(214): Codnitive_Extifcon_Model_Core_Layout->_generateAction(Object(Mage_Core_Model_Layout_Element), Object(Mage_Core_Model_Layout_Element))
#4 /chroot/home/differe1/differentdrop.com/html/app/code/core/Mage/Core/Model/Layout.php(210): Mage_Core_Model_Layout->generateBlocks(Object(Mage_Core_Model_Layout_Element))
#5 /chroot/home/differe1/differentdrop.com/html/app/code/core/Mage/Core/Controller/Varien/Action.php(344): Mage_Core_Model_Layout->generateBlocks()
#6 /chroot/home/differe1/differentdrop.com/html/app/code/core/Mage/Core/Controller/Varien/Action.php(269): Mage_Core_Controller_Varien_Action->generateLayoutBlocks()
#7 /chroot/home/differe1/differentdrop.com/html/app/code/core/Mage/Adminhtml/Controller/Action.php(275): Mage_Core_Controller_Varien_Action->loadLayout(NULL, true, true)
#8 /chroot/home/differe1/differentdrop.com/html/app/code/core/Mage/Adminhtml/controllers/CustomerController.php(98): Mage_Adminhtml_Controller_Action->loadLayout()
#9 /chroot/home/differe1/differentdrop.com/html/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Adminhtml_CustomerController->editAction()
#10 /chroot/home/differe1/differentdrop.com/html/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(254): Mage_Core_Controller_Varien_Action->dispatch('edit')
#11 /chroot/home/differe1/differentdrop.com/html/app/code/core/Mage/Core/Controller/Varien/Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#12 /chroot/home/differe1/differentdrop.com/html/app/code/core/Mage/Core/Model/App.php(365): Mage_Core_Controller_Varien_Front->dispatch()
#13 /chroot/home/differe1/differentdrop.com/html/app/Mage.php(684): Mage_Core_Model_App->run(Array)
#14 /chroot/home/differe1/differentdrop.com/html/index.php(82): Mage::run('', 'store')
#15 {main}
</code>```

答:
For the solution of the Question is :

Please check which others extensions are Dependent on the monkey extension.

So please Disable those extension and check it will working fine without any error.

Body:
There has been an error processing your request
Wrong tab configuration.

Trace:
#0 [internal function]: Mage_Adminhtml_Block_Widget_Tabs->addTab('customer_edit_t...', 'monkey/adminhtm...')
#1 /chroot/home/differe1/differentdrop.com/html/app/code/community/Codnitive/Extifcon/Model/Core/Layout.php(132): call_user_func_array(Array, Array)
#2 /chroot/home/differe1/differentdrop.com/html/app/code/community/Codnitive/Extifcon/Model/Core/Layout.php(70): Codnitive_Extifcon_Model_Core_Layout->_runAction(Object(Mage_Core_Model_Layout_Element), Object(Mage_Core_Model_Layout_Element))
#3 /chroot/home/differe1/differentdrop.com/html/app/code/core/Mage/Core/Model/Layout.php(214): Codnitive_Extifcon_Model_Core_Layout->_generateAction(Object(Mage_Core_Model_Layout_Element), Object(Mage_Core_Model_Layout_Element))
#4 /chroot/home/differe1/differentdrop.com/html/app/code/core/Mage/Core/Model/Layout.php(210): Mage_Core_Model_Layout->generateBlocks(Object(Mage_Core_Model_Layout_Element))
#5 /chroot/home/differe1/differentdrop.com/html/app/code/core/Mage/Core/Controller/Varien/Action.php(344): Mage_Core_Model_Layout->generateBlocks()
#6 /chroot/home/differe1/differentdrop.com/html/app/code/core/Mage/Core/Controller/Varien/Action.php(269): Mage_Core_Controller_Varien_Action->generateLayoutBlocks()
#7 /chroot/home/differe1/differentdrop.com/html/app/code/core/Mage/Adminhtml/Controller/Action.php(275): Mage_Core_Controller_Varien_Action->loadLayout(NULL, true, true)
#8 /chroot/home/differe1/differentdrop.com/html/app/code/core/Mage/Adminhtml/controllers/CustomerController.php(98): Mage_Adminhtml_Controller_Action->loadLayout()
#9 /chroot/home/differe1/differentdrop.com/html/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Adminhtml_CustomerController->editAction()
#10 /chroot/home/differe1/differentdrop.com/html/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(254): Mage_Core_Controller_Varien_Action->dispatch('edit')
#11 /chroot/home/differe1/differentdrop.com/html/app/code/core/Mage/Core/Controller/Varien/Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#12 /chroot/home/differe1/differentdrop.com/html/app/code/core/Mage/Core/Model/App.php(365): Mage_Core_Controller_Varien_Front->dispatch()
#13 /chroot/home/differe1/differentdrop.com/html/app/Mage.php(684): Mage_Core_Model_App->run(Array)
#14 /chroot/home/differe1/differentdrop.com/html/index.php(82): Mage::run('', 'store')
#15 {main}


问:
Find the biggest square in numpy array
I'm trying to solve this algorithm problem: finding the biggest square with only one value in a numpy array.

Example Image :

My code taking too much time. Is there way to improve the speed?

```<code>import numpy as np
answer = 0
def allsame(board):
    memory = board[0,0]
    board = np.matrix(board)
    for i in range(board[0].size):
        for j in range(board[0].size):
            if board[i,j] != memory: return False
    return True

def findLargestSquare(board):
    global answer
    list = []

    a = np.matrix(board)
    if a[0].size == 1 or a[:,1].size==1: return answer
    if a[1].size < a[:,1].size: ran = a[1].size
    else: ran = a[:,1].size
    for i in range(ran+1):
        for j in range(ran+1):
           if a[i:j,i:j].size > 0 and allsame(a[i:j,i:j])==True:
                    if a[i:j,i:j].size > answer:
                       list.append(a[i:j,i:j].size)
                       answer = a[i:j,i:j].size

    findLargestSquare(a[1:])
    return findLargestSquare(a[:,1:])
    return answer

#testBoard = [['x','o','g'],['b','a','j'],['u','q','p']]
testBoard = [['X','O','O','O','X'],['X','O','O','O','O'],['X','X','O','O','O'],['X','X','O','O','O'],['X','X','X','X','X']]
print(findLargestSquare(testBoard))
</code>```

I changed My code to self convolution method.
can you take a look at which part is wrong?

```<code>import numpy as np
import time
answer = 0

def findLargestSquare(board):
    global answer

    a = np.array(board)

    for k in reversed(range(a[0].size + 1)):
        conv_size = k
        for i in range(a[0].size - conv_size + 1):
            num = i
            for j in range(a[0].size - conv_size + 1):
                #print('i:', i, 'j:', j)
                print(a[i:i + conv_size, j:j + conv_size])
                #print('unique: ',np.unique(a[i:i+ conv_size,j:j+conv_size]).size)
                if(np.unique(a[i:i+ conv_size,j:j+conv_size]).size == 1):
                    #print("returning")
                    return len(a[i:i+ conv_size,j:j+conv_size])**2
                num = num + 1
                print("================")
    return len(a[i:i+ conv_size,j:j+conv_size])**2

# testBoard = [['x','o','g'],['b','a','j'],['u','q','p']]
testBoard = [['X', 'O', 'O', 'O', 'X'], ['X', 'O', 'O', 'O', 'O'], ['X', 'X', 'O', 'O', 'O'], ['X', 'X', 'O', 'O', 'O'],
             ['X', 'X', 'X', 'X', 'X']]

print(findLargestSquare(testBoard))
</code>```

答:
there are a few things fundamentally wrong with your code, in the sense that it is not how you should use Python. Try reading some good introductions and examples first. I recommend this book and these scipy lecture notes

let's start from the top

allsame

There are multiple ways to check whether an array has all identical elements

np.unique

numpy has a method to return the unique elements. If all elements are identical, the length of this array should be 1

np.ones

You could take the first element, make an array with np.ones and multiply it with this element. The initial array should equal this new one

findLargestSquare(board)

What exactly is this method supposed to do?

global answer

Why a global?

``findLargestSquare(a[1:])`

This line gets called, but you do nothing with the return value. All it possibly does is change the global answer

list

What happens with this list. PS, don't give variables the name of built-ins

matrix

Why use a = np.matrix(board) Just keep your board as a numpy.array at all times will be the easiest and most efficient. Also a matrix of 0 and 1's will be a lot more efficient than X and 0's

.size

If you want to stop the recursion of the algorithm if the size in one of the 2 directions is 1, 1 in a.shape

Alternative method

If you want to find squares on 1's in a numpy.array of 0's, you could use convolution

array creation

```<code>a = np.zeros((10,10), dtype=int)
ones = ((1, 1), (1, 2), (2, 1), (2, 2), (0, 0), (4, 5))
for point in ones:
    a[point] = 1
</code>```

Kernel creation and convolution

This uses convolution to search whether there is an i by i kernel in the original array

```<code>def find_largest_square_helper(a):
    for i in range(2, min(a.shape)): # changed this to 2, because the 1 is trivial
        kernel = np.ones((i, i), dtype=int)
        if scipy.signal.convolve(a, kernel).max() != i**2:
            return(i-1)
</code>```

If you expect large squares, you can start at the biggest square and then work your way down like this:

```<code>def find_largest_square_helper2(a):
    for i in range(min(a.shape), 0, -1):
        kernel = np.ones((i, i), dtype=int)
        if scipy.signal.convolve(a, kernel).max() == i**2:
            return(i)
</code>```

More than 1 char

When you not only look for the largest square of 1s in an array of 0s, you loop over all the possible characters in the array, and call this function in a set-comprehension. Then look for the max in this set

```<code>def find_largest_square(board):
    a = np.array(board)
    max_squares = {find_largest_square_helper(a==char) for char in np.unique(a)}
    return max(max_squares)
</code>```

Title: Find the biggest square in numpy array

Body:
I'm trying to solve this algorithm problem: finding the biggest square with only one value in a numpy array.

Example Image :

My code taking too much time. Is there way to improve the speed?

import numpy as np
answer = 0
def allsame(board):
    memory = board[0,0]
    board = np.matrix(board)
    for i in range(board[0].size):
        for j in range(board[0].size):
            if board[i,j] != memory: return False
    return True

def findLargestSquare(board):
    global answer
    list = []

    a = np.matrix(board)
    if a[0].size == 1 or a[:,1].size==1: return answer
    if a[1].size  0 and allsame(a[i:j,i:j])==True:
                    if a[i:j,i:j].size > answer:
                       list.append(a[i:j,i:j].size)
                       answer = a[i:j,i:j].size

    findLargestSquare(a[1:])
    return findLargestSquare(a[:,1:])
    return answer

#testBoard = [['x','o','g'],['b','a','j'],['u','q','p']]
testBoard = [['X','O','O','O','X'],['X','O','O','O','O'],['X','X','O','O','O'],['X','X','O','O','O'],['X','X','X','X','X']]
print(findLargestSquare(testBoard))

I changed My code to self convolution method.
can you take a look at which part is wrong?

import numpy as np
import time
answer = 0

def findLargestSquare(board):
    global answer

    a = np.array(board)

    for k in reversed(range(a[0].size + 1)):
        conv_size = k
        for i in range(a[0].size - conv_size + 1):
            num = i
            for j in range(a[0].size - conv_size + 1):
                #print('i:', i, 'j:', j)
                print(a[i:i + conv_size, j:j + conv_size])
                #print('unique: ',np.unique(a[i:i+ conv_size,j:j+conv_size]).size)
                if(np.unique(a[i:i+ conv_size,j:j+conv_size]).size == 1):
                    #print("returning")
                    return len(a[i:i+ conv_size,j:j+conv_size])**2
                num = num + 1
                print("================")
    return len(a[i:i+ conv_size,j:j+conv_size])**2

# testBoard = [['x','o','g'],['b','a','j'],['u','q','p']]
testBoard = [['X', 'O', 'O', 'O', 'X'], ['X', 'O', 'O', 'O', 'O'], ['X', 'X', 'O', 'O', 'O'], ['X', 'X', 'O', 'O', 'O'],
             ['X', 'X', 'X', 'X', 'X']]

print(findLargestSquare(testBoard))

Body:
there are a few things fundamentally wrong with your code, in the sense that it is not how you should use Python. Try reading some good introductions and examples first. I recommend this book and these scipy lecture notes

let's start from the top

allsame

There are multiple ways to check whether an array has all identical elements

np.unique

numpy has a method to return the unique elements. If all elements are identical, the length of this array should be 1

np.ones

You could take the first element, make an array with np.ones and multiply it with this element. The initial array should equal this new one

findLargestSquare(board)

What exactly is this method supposed to do?

global answer

Why a global?

``findLargestSquare(a[1:])`

This line gets called, but you do nothing with the return value. All it possibly does is change the global answer

list

What happens with this list. PS, don't give variables the name of built-ins

matrix

Why use a = np.matrix(board) Just keep your board as a numpy.array at all times will be the easiest and most efficient. Also a matrix of 0 and 1's will be a lot more efficient than X and 0's

.size

If you want to stop the recursion of the algorithm if the size in one of the 2 directions is 1, 1 in a.shape

Alternative method

If you want to find squares on 1's in a numpy.array of 0's, you could use convolution

array creation

a = np.zeros((10,10), dtype=int)
ones = ((1, 1), (1, 2), (2, 1), (2, 2), (0, 0), (4, 5))
for point in ones:
    a[point] = 1

Kernel creation and convolution

This uses convolution to search whether there is an i by i kernel in the original array

def find_largest_square_helper(a):
    for i in range(2, min(a.shape)): # changed this to 2, because the 1 is trivial
        kernel = np.ones((i, i), dtype=int)
        if scipy.signal.convolve(a, kernel).max() != i**2:
            return(i-1)

If you expect large squares, you can start at the biggest square and then work your way down like this:

def find_largest_square_helper2(a):
    for i in range(min(a.shape), 0, -1):
        kernel = np.ones((i, i), dtype=int)
        if scipy.signal.convolve(a, kernel).max() == i**2:
            return(i)

More than 1 char

When you not only look for the largest square of 1s in an array of 0s, you loop over all the possible characters in the array, and call this function in a set-comprehension. Then look for the max in this set

def find_largest_square(board):
    a = np.array(board)
    max_squares = {find_largest_square_helper(a==char) for char in np.unique(a)}
    return max(max_squares)


问:
How to search a string for different types of numbers
I have multiple strings that each contain a year and some text. An example of one string is: "The year is 2004". But, another string may look like this "this was made in 2003.5". How would I check many strings like this and extract the correct number?

答:
Using list comprehension and not using regex

```<code>def convert(e):
    try:
        return float(e)
    except:
        return None

str = "the 1st year is 2004"
m = [e for e in str.split(" ") if len(e) >= 4 and convert(e)]
print m
>>> ['2004']
</code>```

As other people mentioned without knowing what is "correct" number it is difficult to give an answer that fits all the use cases. However, I assumed that here right number is something more than 4 digits long

Body:
Using list comprehension and not using regex

def convert(e):
    try:
        return float(e)
    except:
        return None

str = "the 1st year is 2004"
m = [e for e in str.split(" ") if len(e) >= 4 and convert(e)]
print m
>>> ['2004']

As other people mentioned without knowing what is "correct" number it is difficult to give an answer that fits all the use cases. However, I assumed that here right number is something more than 4 digits long


问:
Query error LIMIT 0,25
This query gives the error LIMIT 0,25 and i don't know why how do i fix this?

```<code>SELECT btigebruikers.voornaam, btigebruikers.achternaam
FROM btigebruikers, friendrequest
WHERE btigebruikers.email = friendrequest.user1 OR btigebruikers.email = friendrequest.user2  AND btigebruikers.email  NOT 'vermesenjonas@hotmail.com' AND friendrequest.status = 1;
</code>```

Database btigebruikers

Database friendrequest

答:
```<code>SELECT
 btigebruikers.voornaam,
 btigebruikers.achternaam
FROM
 btigebruikers, friendrequest
WHERE
 (btigebruikers.email = friendrequest.user1 OR btigebruikers.email=friendrequest.user2)
 AND
 (btigebruikers.email  <> 'vermesenjonas@hotmail.com')
 AND
 friendrequest.status = 1;
</code>```

Title: Query error LIMIT 0,25

Body:
This query gives the error LIMIT 0,25 and i don't know why how do i fix this?

SELECT btigebruikers.voornaam, btigebruikers.achternaam
FROM btigebruikers, friendrequest
WHERE btigebruikers.email = friendrequest.user1 OR btigebruikers.email = friendrequest.user2  AND btigebruikers.email  NOT 'vermesenjonas@hotmail.com' AND friendrequest.status = 1;

Database btigebruikers

Database friendrequest


问:
Elasticsearch 5 Java Client giving "NoNodeAvailableException"
I am using Elasticsearch 5.2 and Spring Boot 1.5.1. I am connecting to it via the Java client in a Spring app. When I connect to it on port 9300 or 9200 and I get NoNodeAvailableException: None of the configured nodes are available. In my Java client, I have set the client.transport.sniff property as true. On sending a request to it via cURL on port 9200, it is working correctly. I have 4 nodes in a single cluster and I cannot connect to any of them. My configuration file has all of the default values in the network division except for network.host which has eth0 inet addr as the value.

I am using Gradle. My dependencies are:

```<code>compile('org.springframework.boot:spring-boot-starter-web')
compile('org.elasticsearch:elasticsearch:5.2.0')
compile('org.elasticsearch.client:transport:5.2.0')
compile('org.apache.logging.log4j:log4j-api:2.7')
compile('org.apache.logging.log4j:log4j-core:2.7')
</code>```

My code for connecting to the Elasticsearch cluster:

```<code>@Bean
public TransportClient elasticClient() {
    org.elasticsearch.common.settings.Settings settings = Settings.builder()
        .put("client.transport.sniff", true)
        .put("cluster.name", "TestCluster")
            .build();
    TransportClient client = null;
    try {
        client = new org.elasticsearch.transport.client.PreBuiltTransportClient(settings)
            .addTransportAddress(new org.elasticsearch.common.transport.InetSocketTransportAddress(
                InetAddress.getByName("54.175.155.56"), 9200));
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    return client;
}
</code>```

My ES logs when ES starts are:

```<code>[2017-02-15T10:37:40,664][INFO ][o.e.t.TransportService   ] [ip-10-0-29-2] publish_address {10.0.29.2:9300}, bound_addresses {10.0.29.2:9300}
[2017-02-15T10:37:40,669][INFO ][o.e.b.BootstrapChecks    ] [ip-10-0-29-2] bound or publishing to a non-loopback or non-link-local address, enforcing bootstrap checks
[2017-02-15T10:37:43,856][INFO ][o.e.c.s.ClusterService   ] [ip-10-0-29-2] detected_master {kafka-stage}{sTIeF8gGTNam0oNW8dkbbA}{TTX6FIRtRp-gDemYY-22Sg}{10.0.20.71}{10.0.20.71:9300}, added {{kafka-stage-2}{jl3oLGgMQ1yxhdMMy65k_g}{ibV8BApjRByUOpDDncddyQ}{10.0.51.31}{10.0.51.31:9300},{ip-10-0-40-144}{t-_THs3wQbC_k9eivDo5eQ}{v-UYoYgXQ265QkdYhtiPYA}{10.0.40.144}{10.0.40.144:9300},{kafka-stage}{sTIeF8gGTNam0oNW8dkbbA}{TTX6FIRtRp-gDemYY-22Sg}{10.0.20.71}{10.0.20.71:9300},}, reason: zen-disco-receive(from master [master {kafka-stage}{sTIeF8gGTNam0oNW8dkbbA}{TTX6FIRtRp-gDemYY-22Sg}{10.0.20.71}{10.0.20.71:9300} committed version [98]])
[2017-02-15T10:37:44,009][INFO ][o.e.h.HttpServer         ] [ip-10-0-29-2] publish_address {10.0.29.2:9200}, bound_addresses {10.0.29.2:9200}
[2017-02-15T10:37:44,009][INFO ][o.e.n.Node               ] [ip-10-0-29-2] started
</code>```

The answers at these questions don't solve my problem:

Java ElasticSearch None of the configured nodes are available

Elasticsearch - NoNodeAvailableException

Elasticsearch NoNodeAvailableException issue

答: Most Probably the answer of this question is clustername may be different from the elasticsearch.yml, do configure that and in elasticsearch it uses two ports: they are 9200 which provides access through http and 9300 is used for accessing Elasticsearch through the internal transport protocol, which is used by Java Transport Client.

Body:
I am using Elasticsearch 5.2 and Spring Boot 1.5.1. I am connecting to it via the Java client in a Spring app. When I connect to it on port 9300 or 9200 and I get NoNodeAvailableException: None of the configured nodes are available. In my Java client, I have set the client.transport.sniff property as true. On sending a request to it via cURL on port 9200, it is working correctly. I have 4 nodes in a single cluster and I cannot connect to any of them. My configuration file has all of the default values in the network division except for network.host which has eth0 inet addr as the value.

I am using Gradle. My dependencies are:

compile('org.springframework.boot:spring-boot-starter-web')
compile('org.elasticsearch:elasticsearch:5.2.0')
compile('org.elasticsearch.client:transport:5.2.0')
compile('org.apache.logging.log4j:log4j-api:2.7')
compile('org.apache.logging.log4j:log4j-core:2.7')

My code for connecting to the Elasticsearch cluster:

@Bean
public TransportClient elasticClient() {
    org.elasticsearch.common.settings.Settings settings = Settings.builder()
        .put("client.transport.sniff", true)
        .put("cluster.name", "TestCluster")
            .build();
    TransportClient client = null;
    try {
        client = new org.elasticsearch.transport.client.PreBuiltTransportClient(settings)
            .addTransportAddress(new org.elasticsearch.common.transport.InetSocketTransportAddress(
                InetAddress.getByName("54.175.155.56"), 9200));
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    return client;
}

My ES logs when ES starts are:

[2017-02-15T10:37:40,664][INFO ][o.e.t.TransportService   ] [ip-10-0-29-2] publish_address {10.0.29.2:9300}, bound_addresses {10.0.29.2:9300}
[2017-02-15T10:37:40,669][INFO ][o.e.b.BootstrapChecks    ] [ip-10-0-29-2] bound or publishing to a non-loopback or non-link-local address, enforcing bootstrap checks
[2017-02-15T10:37:43,856][INFO ][o.e.c.s.ClusterService   ] [ip-10-0-29-2] detected_master {kafka-stage}{sTIeF8gGTNam0oNW8dkbbA}{TTX6FIRtRp-gDemYY-22Sg}{10.0.20.71}{10.0.20.71:9300}, added {{kafka-stage-2}{jl3oLGgMQ1yxhdMMy65k_g}{ibV8BApjRByUOpDDncddyQ}{10.0.51.31}{10.0.51.31:9300},{ip-10-0-40-144}{t-_THs3wQbC_k9eivDo5eQ}{v-UYoYgXQ265QkdYhtiPYA}{10.0.40.144}{10.0.40.144:9300},{kafka-stage}{sTIeF8gGTNam0oNW8dkbbA}{TTX6FIRtRp-gDemYY-22Sg}{10.0.20.71}{10.0.20.71:9300},}, reason: zen-disco-receive(from master [master {kafka-stage}{sTIeF8gGTNam0oNW8dkbbA}{TTX6FIRtRp-gDemYY-22Sg}{10.0.20.71}{10.0.20.71:9300} committed version [98]])
[2017-02-15T10:37:44,009][INFO ][o.e.h.HttpServer         ] [ip-10-0-29-2] publish_address {10.0.29.2:9200}, bound_addresses {10.0.29.2:9200}
[2017-02-15T10:37:44,009][INFO ][o.e.n.Node               ] [ip-10-0-29-2] started

The answers at these questions don't solve my problem:

Java ElasticSearch None of the configured nodes are available

Elasticsearch - NoNodeAvailableException

Elasticsearch NoNodeAvailableException issue