问:
Program 'mysql.exe' failed to run: The specified executable is not a valid application
I have problem with mysql command in windows 10. I want to import a file test.sql to test database. I use this command in Windows PowerShell

```<code>.\mysql -u root -p test < test.sql
</code>```

PS return an error with this content

```<code>Program 'mysql.exe' failed to run: The specified executable is not a valid application for this OS platform.At line:1
char:1
+ .\mysql -u root -p
+ ~~~~~~~~~~~~~~~~~~.
At line:1 char:1
+ .\mysql -u root -p
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (:) [], ApplicationFailedException
    + FullyQualifiedErrorId : NativeCommandFailed
</code>```

I tried in windows CMD(also administrate) I get this message This app can't run in your PC

also I find mysql.exe in c/wamp64/bin/mysql/mysql5.7.11/bin
  the size of the app was wierd 0KB.

Is it normal?

what 's the problem?

答:
Well - it is not normal, size of the app should be more than 0kb, depends on the version. My guess is mysql was not installed correctly. Maybe antivirus blocked it during installation?

Try to reinstall WAMP package. Also - when you start WAMP - do this with elevated privileges.

Is your windows 64 bit? Also - if reinstalling the package would not work despite antivirus switched off or even not present, try to download and install 32bit package.

Body:
I have problem with mysql command in windows 10. I want to import a file test.sql to test database. I use this command in Windows PowerShell

.\mysql -u root -p test < test.sql

PS return an error with this content

Program 'mysql.exe' failed to run: The specified executable is not a valid application for this OS platform.At line:1
char:1
+ .\mysql -u root -p
+ ~~~~~~~~~~~~~~~~~~.
At line:1 char:1
+ .\mysql -u root -p
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (:) [], ApplicationFailedException
    + FullyQualifiedErrorId : NativeCommandFailed

I tried in windows CMD(also administrate) I get this message This app can't run in your PC

also I find mysql.exe in c/wamp64/bin/mysql/mysql5.7.11/bin
  the size of the app was wierd 0KB.

Is it normal?

what 's the problem?


来源: stackexchange

问:
ASP.net ViewState encryption and decryption
I heard that .NET framework will encrypt the ViewState using SHA1 or some other algorithm.
So if i know the SHA1 encryption and decryption algorithm can i tamper a ViewState?I mean

a malicious user studies SHA1 encryption algorithm,if he understand that algorith and develops decryption algorithm ,will it open the road of viewstate tampering? or SHA1 or other algorithm uses any random tricks for encryption and decryption?

答:
Encryption implies a key.  Said key is kept on the server, and (barring other, much bigger, security issues) the client never sees it.  Without knowing that key, you aren't even going to be able to view encrypted viewstate, much less change it.

Even without encryption, the server can be told to generate a hash of the viewstate and a key that only the server knows.  Without knowing that key, you can still read the viewstate, but you won't be able to edit it without a whole lot of effort.

Now, it's possible that whatever encryption or hashing algorithm the framework uses, could be broken enough to make tampering easy.  But if it were, you'd hear about it pretty quickly -- as that same algorithm will be used in dozens of other places (there are a few well-known, well-tested algorithms that just about everyone uses).

Short version: If you care about preventing tampering, the stuff built into ASP.net will work pretty well if configured properly.

ContentLicense: CC BY-SA 2.5


问:
Issues with routes after putting my Laravel 5 project online
I have a problem when I put my laravel project online.
I extracted the contents of the public folder to the root and modified the contents of the index.php file accordingly.
but none of my routes are working anymore.
please can anyone help me?
thank you in advance ...</p>

答:
You can't move the public folder of a laravel installation.

Your web server must point to your public folder , usually :

/var/www/website.com/public

ContentLicense: CC BY-SA 3.0


问:
Copy construction in OCaml?
OCaml values are passed by reference as opposed by value. When the values are constant, there is no observable difference between references and values. However, when the value is mutable (such as a struct with mutable fields), I may want to copy it such that when one variable mutates the value, another variable that was set to the former variable is not mutated as well. Can I do this in OCaml?</p>

答:
There are three syntactical ways to introduce mutable values:

define a record with a mutable field;

use some predefined mutable container, such as Array, Bytes, Bigarray;

define a class with a mutable field.

One function to clone them all

There is no such function, that will take any value and will return a clone of it unless you're willing to rely on the unsafe Obj module, or to use the Marshal module. So in pure OCaml, it's not possible to get a bitwise copy of another value, since OCaml is trying to abstract its binary representation from an application. If you really need then the following inefficient implementation may suffice your needs:

```<code>   let clone (type t) (x : t) : t =
     let buf = Marshal.(to_bytes x [No_sharing; Closures]) in
     Marshal.from_bytes buf 0
</code>```

It will not work with values that do not support marshaling, for example with file descriptors, and with custom objects (implemented in C) that doesn't implement the marshaling interface.

Mutable records

There is no base type to which all records belong. So, for each record with a mutable type, you need to provide your own cloner, or you can rely on the clone function above.

Predefined containers

All predefined containers provide the clone function, however, since they all belong to different types, there is no generic function, that will handle them all.

Mutable objects

Object-oriented programming was always tightly connected with mutability. Thus OCaml provides the Oo.copy function that works on all objects since there is an object type <..> to which all other objects belong. So, if you indeed need a generic clone function, then consider using objects.

Title: Copy construction in OCaml?

Body:
There are three syntactical ways to introduce mutable values:

define a record with a mutable field;

use some predefined mutable container, such as Array, Bytes, Bigarray;

define a class with a mutable field.

One function to clone them all

There is no such function, that will take any value and will return a clone of it unless you're willing to rely on the unsafe Obj module, or to use the Marshal module. So in pure OCaml, it's not possible to get a bitwise copy of another value, since OCaml is trying to abstract its binary representation from an application. If you really need then the following inefficient implementation may suffice your needs:

   let clone (type t) (x : t) : t =
     let buf = Marshal.(to_bytes x [No_sharing; Closures]) in
     Marshal.from_bytes buf 0

It will not work with values that do not support marshaling, for example with file descriptors, and with custom objects (implemented in C) that doesn't implement the marshaling interface.

Mutable records

There is no base type to which all records belong. So, for each record with a mutable type, you need to provide your own cloner, or you can rely on the clone function above.

Predefined containers

All predefined containers provide the clone function, however, since they all belong to different types, there is no generic function, that will handle them all.

Mutable objects

Object-oriented programming was always tightly connected with mutability. Thus OCaml provides the Oo.copy function that works on all objects since there is an object type <..> to which all other objects belong. So, if you indeed need a generic clone function, then consider using objects.


问:
Vue.js access imported JSON
I'm new to Vue and I'm importing a json file via axios and it's displaying on the DOM. Now my question is how can I target elements inside the json file in vue, or how can I pass it thru to the new Vue element? I can target it with the computed output function in the vue chrome dev tool. But I just can find a way to get it in to target it inside the new Vue so I can put inside my html. For example how can I pass the data from address --> city?
Here is my Json:

```<code>{
  "restaurant": [
{
  "address": {
    "city": "Berlin",
    "country_code": "DE",
    "id": 12345,
    "latitude": 12345,
    "longitude": 12345,
    "street": "Muster Stra\u00dfe",
    "street_no": "43",
    "zipcode": "12627"
  },
  "chain": {
    "group_name": null,
    "id": 123,
    "key_account": false,
    "name": "XXX"
  },
  "created_ts": "2017-09-15T09:23:37.707020+00:00",
  "custom_data": null,
  "deleted": false,
  "emails": [
    {
      "email": "firstname_883.lastname_883@xxx.com",
      "email_type": "general",
      "id": 123456,
      "imprint": false
    }
  ],
  "global_id": "123456",
  "id": 123456,
  "modified_ts": "2017-11-30T12:10:13.298887+00:00",
  "owner": {
    "business_entity": null,
    "company": "XXX",
    "id": 123456,
    "managing_directors": "",
    "name": "Herr XXX",
    "registration_court": "",
    "registration_number": "",
    "tax_number": ""
  },
  "phones": [
    {
      "id": 123456,
      "imprint": false,
      "phone_number": "+4930123456",
      "phone_type": "fax"
    },
    {
      "id": 123456,
      "imprint": false,
      "phone_number": "+4930123456",
      "phone_type": "phone"
    }
  ],
  "platforms": {
    "LH": {
      "categories": [
        {
          "id": 123,
          "name": "XXX",
          "primary_category": true
        },
        {
          "id": 123,
          "name": "XXX",
          "primary_category": false
        }
      ],
      "custom_data": {
        "cocacola_promotion": false,
        "custom_preorder_minimum_time": "",
        "default_delivery_time": "",
        "express": false,
        "express_refund_logic": "",
        "guaranteed_delivery_time": "",
        "hide_google_places_order_action": true,
        "lh_award": false,
        "ninecookies_live_tracking": false,
        "preorder": true,
        "recommended": false,
        "white_label": "",
        "white_label_external": false,
        "white_label_offline": false
      },
      "deleted": false,
      "id": 123456,
      "key_account": true,
      "last_dowant_sync_ts": null,
      "last_salesforce_sync_ts": null,
      "name": "XXX",
      "online": true,
      "payment_methods": [
        {
          "id": 12,
          "name": "cash",
          "online_payment": false
        },
        {
          "id": 12,
          "name": "online",
          "online_payment": true
        }
      ],
      "platform": "XD",
      "platform_id": "123456",
      "reachable": true,
      "salesforce_id": "123456",
      "slug": "XXX",
      "transmissions": [
        {
          "enabled": true,
          "id": 123,
          "name": "XXX",
          "parameters": {
            "device_id": "XXX",
            "phone_number": "11"
          }
        },
        {
          "enabled": true,
          "id": 123,
          "name": "sms",
          "parameters": {
            "sms_number": "+4930123456"
          }
        }
      ]
    },
    "PDE": {
      "categories": [
        {
          "id": 123,
          "name": "XXX",
          "primary_category": false
        },
        {
          "id": 123,
          "name": "XXX",
          "primary_category": true
        }
      ],
      "custom_data": {
        "brand_promotion_monday": true,
        "brand_promotion_thursday": false,
        "brand_promotion_tuesday": false,
        "brand_promotion_wednesday": true,
        "cocacola_promotion": false,
        "custom_preorder_minimum_time": "",
        "default_delivery_time": "",
        "express": false,
        "express_refund_logic": "",
        "guaranteed_delivery_time": "",
        "hide_google_places_order_action": false,
        "kinder_menu": false,
        "ninecookies_live_tracking": false,
        "pde_anniversary": false,
        "preorder": true,
        "white_label": "",
        "white_label_external": false,
        "white_label_offline": false
      },
      "deleted": false,
      "id": 123456,
      "key_account": true,
      "last_dowant_sync_ts": "2017-11-30T12:20:32.887802+00:00",
      "last_salesforce_sync_ts": null,
      "name": "Pizza Max",
      "online": true,
      "payment_methods": [
        {
          "id": 37,
          "name": "cash",
          "online_payment": false
        },
        {
          "id": 38,
          "name": "online",
          "online_payment": true
        },
        {
          "id": 41,
          "name": "ec_card",
          "online_payment": false
        }
      ],
      "platform": "XXX",
      "platform_id": "123",
      "reachable": true,
      "salesforce_id": "123456",
      "slug": "musterstr-123",
      "transmissions": [
        {
          "enabled": true,
          "id": 123,
          "name": "pos_polling",
          "parameters": {
            "pos_polling_id": "123456",
            "pos_polling_password": "123456",
            "pos_polling_user": "123456"
          }
        },
        {
          "enabled": true,
          "id": 123,
          "name": "sms",
          "parameters": {
            "sms_number": "+4930123456"
          }
        }
      ]
    }
  }

  }]}
</code>```

Here my code:

```<code><!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>VueJS</title>
    <script src="https://vuejs.org/js/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>

    <div id="app">
        <!-- <p>{{ restaurant }}</p> -->
        <p>{{ restaurant }}</p>

    </div>

    <script>
        var vm = new Vue({
            el: '#app',
            data: {
                restaurant: [],
                address: [],
                city: [],
            },
            mounted: function() {
                this.load();
            },
            methods: {
                load: function() {
                    this.restaurant = '...loading';
                    var vm = this;
                    axios.get('http://localhost:3000/restaurant')
                        .then(function(response) {
                            vm.restaurant = response.data;
                            console.log(vm.restaurant[0].address)
                        })
                        .catch(function(error) {
                            vm.restaurant = 'error' + error;
                        });
                }
            },
            computed: {
                output: function() {
                    return this.restaurant = vm.restaurant[0].address;
                }
            }
        });
    </script>
</body>

</html>
</code>```

Thanks for any help!

答:
restaurant is an array in your case in response. so if you just need address then we can just extract in and use it.

Please check out snippet.

I am replacing ajax call with static data you can easily replace it.

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>VueJS</title>

 0">

Id : {{ restaurant[0].address.id }}

City : {{ restaurant[0].address.city }}

```

Title: Vue.js access imported JSON

Body:
I'm new to Vue and I'm importing a json file via axios and it's displaying on the DOM. Now my question is how can I target elements inside the json file in vue, or how can I pass it thru to the new Vue element? I can target it with the computed output function in the vue chrome dev tool. But I just can find a way to get it in to target it inside the new Vue so I can put inside my html. For example how can I pass the data from address --> city?
Here is my Json:

{
  "restaurant": [
{
  "address": {
    "city": "Berlin",
    "country_code": "DE",
    "id": 12345,
    "latitude": 12345,
    "longitude": 12345,
    "street": "Muster Stra\u00dfe",
    "street_no": "43",
    "zipcode": "12627"
  },
  "chain": {
    "group_name": null,
    "id": 123,
    "key_account": false,
    "name": "XXX"
  },
  "created_ts": "2017-09-15T09:23:37.707020+00:00",
  "custom_data": null,
  "deleted": false,
  "emails": [
    {
      "email": "firstname_883.lastname_883@xxx.com",
      "email_type": "general",
      "id": 123456,
      "imprint": false
    }
  ],
  "global_id": "123456",
  "id": 123456,
  "modified_ts": "2017-11-30T12:10:13.298887+00:00",
  "owner": {
    "business_entity": null,
    "company": "XXX",
    "id": 123456,
    "managing_directors": "",
    "name": "Herr XXX",
    "registration_court": "",
    "registration_number": "",
    "tax_number": ""
  },
  "phones": [
    {
      "id": 123456,
      "imprint": false,
      "phone_number": "+4930123456",
      "phone_type": "fax"
    },
    {
      "id": 123456,
      "imprint": false,
      "phone_number": "+4930123456",
      "phone_type": "phone"
    }
  ],
  "platforms": {
    "LH": {
      "categories": [
        {
          "id": 123,
          "name": "XXX",
          "primary_category": true
        },
        {
          "id": 123,
          "name": "XXX",
          "primary_category": false
        }
      ],
      "custom_data": {
        "cocacola_promotion": false,
        "custom_preorder_minimum_time": "",
        "default_delivery_time": "",
        "express": false,
        "express_refund_logic": "",
        "guaranteed_delivery_time": "",
        "hide_google_places_order_action": true,
        "lh_award": false,
        "ninecookies_live_tracking": false,
        "preorder": true,
        "recommended": false,
        "white_label": "",
        "white_label_external": false,
        "white_label_offline": false
      },
      "deleted": false,
      "id": 123456,
      "key_account": true,
      "last_dowant_sync_ts": null,
      "last_salesforce_sync_ts": null,
      "name": "XXX",
      "online": true,
      "payment_methods": [
        {
          "id": 12,
          "name": "cash",
          "online_payment": false
        },
        {
          "id": 12,
          "name": "online",
          "online_payment": true
        }
      ],
      "platform": "XD",
      "platform_id": "123456",
      "reachable": true,
      "salesforce_id": "123456",
      "slug": "XXX",
      "transmissions": [
        {
          "enabled": true,
          "id": 123,
          "name": "XXX",
          "parameters": {
            "device_id": "XXX",
            "phone_number": "11"
          }
        },
        {
          "enabled": true,
          "id": 123,
          "name": "sms",
          "parameters": {
            "sms_number": "+4930123456"
          }
        }
      ]
    },
    "PDE": {
      "categories": [
        {
          "id": 123,
          "name": "XXX",
          "primary_category": false
        },
        {
          "id": 123,
          "name": "XXX",
          "primary_category": true
        }
      ],
      "custom_data": {
        "brand_promotion_monday": true,
        "brand_promotion_thursday": false,
        "brand_promotion_tuesday": false,
        "brand_promotion_wednesday": true,
        "cocacola_promotion": false,
        "custom_preorder_minimum_time": "",
        "default_delivery_time": "",
        "express": false,
        "express_refund_logic": "",
        "guaranteed_delivery_time": "",
        "hide_google_places_order_action": false,
        "kinder_menu": false,
        "ninecookies_live_tracking": false,
        "pde_anniversary": false,
        "preorder": true,
        "white_label": "",
        "white_label_external": false,
        "white_label_offline": false
      },
      "deleted": false,
      "id": 123456,
      "key_account": true,
      "last_dowant_sync_ts": "2017-11-30T12:20:32.887802+00:00",
      "last_salesforce_sync_ts": null,
      "name": "Pizza Max",
      "online": true,
      "payment_methods": [
        {
          "id": 37,
          "name": "cash",
          "online_payment": false
        },
        {
          "id": 38,
          "name": "online",
          "online_payment": true
        },
        {
          "id": 41,
          "name": "ec_card",
          "online_payment": false
        }
      ],
      "platform": "XXX",
      "platform_id": "123",
      "reachable": true,
      "salesforce_id": "123456",
      "slug": "musterstr-123",
      "transmissions": [
        {
          "enabled": true,
          "id": 123,
          "name": "pos_polling",
          "parameters": {
            "pos_polling_id": "123456",
            "pos_polling_password": "123456",
            "pos_polling_user": "123456"
          }
        },
        {
          "enabled": true,
          "id": 123,
          "name": "sms",
          "parameters": {
            "sms_number": "+4930123456"
          }
        }
      ]
    }
  }

  }]}

Here my code:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>VueJS</title>

{{ restaurant }}

Thanks for any help!

Body:
restaurant is an array in your case in response. so if you just need address then we can just extract in and use it.

Please check out snippet.

I am replacing ajax call with static data you can easily replace it.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>VueJS</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</head>

<body>

    <div id="app">
        <div v-if="restaurant.length > 0">
          <!-- you can also use loop through restaurant -->
          <p>Id : {{ restaurant[0].address.id }}</p>
          <p>City : {{ restaurant[0].address.city }}</p>
        </div>
    </div>

    <script>

        var yourAjaxData = {
          "restaurant": [
          {
            "address": {
              "city": "Berlin",
              "country_code": "DE",
              "id": 12345,
              "latitude": 12345,
              "longitude": 12345,
              "street": "Muster Stra\u00dfe",
              "street_no": "43",
              "zipcode": "12627"
            },
            // your other data goes on and on ...
          }]
        };

        var vm = new Vue({
            el: '#app',
            data: {
                restaurant: []
            },
            mounted: function() {
                this.load();
            },
            methods: {
                load: function() {
                    this.restaurant = '...loading';
                    var vm = this;
                    // ajax call

                    // return data is object
                    // inside it restaurant is key
                    // restaurant's value is array
                    vm.restaurant = yourAjaxData.restaurant;

                }
            },
            computed: {
                output: function() {
                    return this.restaurant = vm.restaurant[0].address;
                }
            }
        });
    </script>
</body>

</html>


问:
C - random numbers array function
I'm trying to create a function that creates an array in size n with random numbers stored inside, I've been trying several option but once i use the array in main, only the first number shows up correctly.

I'm using CodeBlock by the way.

```<code>static int *arr;
int i, num;
printf("enter the length of the array: ");
scanf("%d/n", &num);
arr = get_random_arr(num);

for(i=0;i<num;i++)
{
    printf("outside the function: %d\n", *(arr+i));
}

return 0;

int *get_random_arr(int num)
{
    int temp_arr[num];
    int i;
    srand((unsigned)time(NULL));

    for (i=0;i<num;i++)
    {
        temp_arr[i] = rand() % 1001 ;
        printf("inside the function: %d\n",temp_arr[i]);
    }

    return temp_arr;
}
</code>```

and this is the code that compiles:

```<code>enter the length of the array: 3
inside the function: 224
inside the function: 774
inside the function: 60
outside the function: 224
outside the function: 2686648
outside the function: 1977872892
</code>```

Thank's to "coderredoc" his answer was the solution i was looking for

答:
```<code>scanf("%d/n", &num);
</code>```

You have to enter the number followed by / and n. This is not what you want. You wanted this

```<code>scanf("%d\n", &num);
</code>```

But here the scanf reads the number in num but then the reading continues until nonwhitespace character followed by \n is found. You don't need the \n here.

Also returning return temp_arr; and using it outside it's scope is UB.

The array temp_arr has automatic storage duration meaning its lifetime will end after the function ends. Accessing it outside its scope is undefined behavior which is precisely what you did.

Something like this

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int *get_random_arr(int num)
{
    if( num <= 0){
        fprintf(stderr, "%s\n", "Error in the number: num >= 1");
        exit(1);
    }
    int *temp_arr = (int*)malloc( sizeof *temp_arr *num);
    if( !temp_arr ){
        fprintf(stderr, "%s\n", "Error in malloc");
        exit(1);
    }

    srand((unsigned)time(NULL));

    for(size_t i=0;i<num;i++)
    {
        temp_arr[i] = rand() % 1001 ;
        printf("inside the function: %d\n",temp_arr[i]);
    }
    return temp_arr;
}
int main(){
    static int *arr;
    int num;
    printf("enter the length of the array: ");
    if( scanf("%d", &num) != 1){
        fprintf(stderr, "%s\n","Error in input" );
        exit(1);
    }
    arr = get_random_arr(num);

    for(size_t i=0;i<num;i++)
    {
        printf("outside the function: %d\n", *(arr+i));
    }
    free(arr);

    return 0;
}
</code>```

The code tries to show a possible way to achieve what you wanted. Dynamically allocated memories lifetimes extends beyond the scope of the function. That's why it works. Note the free() - which is used to free the dynamically allocated memory.

Title: C - random numbers array function

Body:
I'm trying to create a function that creates an array in size n with random numbers stored inside, I've been trying several option but once i use the array in main, only the first number shows up correctly.

I'm using CodeBlock by the way.

static int *arr;
int i, num;
printf("enter the length of the array: ");
scanf("%d/n", &num);
arr = get_random_arr(num);

for(i=0;i<num;i++)
{
    printf("outside the function: %d\n", *(arr+i));
}

return 0;

int *get_random_arr(int num)
{
    int temp_arr[num];
    int i;
    srand((unsigned)time(NULL));

    for (i=0;i<num;i++)
    {
        temp_arr[i] = rand() % 1001 ;
        printf("inside the function: %d\n",temp_arr[i]);
    }

    return temp_arr;
}

and this is the code that compiles:

enter the length of the array: 3
inside the function: 224
inside the function: 774
inside the function: 60
outside the function: 224
outside the function: 2686648
outside the function: 1977872892

Thank's to "coderredoc" his answer was the solution i was looking for

Body:
scanf("%d/n", &num);

You have to enter the number followed by / and n. This is not what you want. You wanted this

scanf("%d\n", &num);

But here the scanf reads the number in num but then the reading continues until nonwhitespace character followed by \n is found. You don't need the \n here.

Also returning return temp_arr; and using it outside it's scope is UB.

The array temp_arr has automatic storage duration meaning its lifetime will end after the function ends. Accessing it outside its scope is undefined behavior which is precisely what you did.

Something like this

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int *get_random_arr(int num)
{
    if( num <= 0){
        fprintf(stderr, "%s\n", "Error in the number: num >= 1");
        exit(1);
    }
    int *temp_arr = (int*)malloc( sizeof *temp_arr *num);
    if( !temp_arr ){
        fprintf(stderr, "%s\n", "Error in malloc");
        exit(1);
    }

    srand((unsigned)time(NULL));

    for(size_t i=0;i<num;i++)
    {
        temp_arr[i] = rand() % 1001 ;
        printf("inside the function: %d\n",temp_arr[i]);
    }
    return temp_arr;
}
int main(){
    static int *arr;
    int num;
    printf("enter the length of the array: ");
    if( scanf("%d", &num) != 1){
        fprintf(stderr, "%s\n","Error in input" );
        exit(1);
    }
    arr = get_random_arr(num);

    for(size_t i=0;i<num;i++)
    {
        printf("outside the function: %d\n", *(arr+i));
    }
    free(arr);

    return 0;
}

The code tries to show a possible way to achieve what you wanted. Dynamically allocated memories lifetimes extends beyond the scope of the function. That's why it works. Note the free() - which is used to free the dynamically allocated memory.


问:
AngularJS $window: how can it be beneficial in unit testing? (compared to using window)
While the official docs says,

While window is globally available in JavaScript, it causes testability problems, because it is a global variable. In AngularJS we always refer to it through the $window service, so it may be overridden, removed or mocked for testing.

I still cannot make sense of it.  How can I benefit from $window in my unit tests code? In my snippet below, I can spy/mock and make use of the native window object, with or without $window. How does it cause testability problems?

```<code>angular.module('messagePopper', [])
  .factory('popper', function popperFactory($window) {
    return {
      popupMessage(message) {
        alert(message);
      },

      popupMessageWith$window(message) {
        $window.alert(message);
      }
    };
  });

describe('messagePopper: popper service', () => {
  let $injector;
  let $window;
  let popper;

  beforeEach(() => {
    module('messagePopper');

    inject((_$injector_) => {
      $injector = _$injector_;
      $window = $injector.get('$window');
      popper = $injector.get('popper');
    });
  });

  it('should popupMessage correctly', () => {
    const message = 'welcome glenn@foodie.net';

    const alertMock = spyOn(window, 'alert');

    popper.popupMessage(message);

    expect(alertMock)
      .toHaveBeenCalledWith(message);
  });

  it('should popupMessageWith$window correctly', () => {
    const message = 'welcome glenn@foodie.net';

    const alertMock = spyOn($window, 'alert');

    popper.popupMessageWith$window(message);

    expect(alertMock)
      .toHaveBeenCalledWith(message);
  });
});
</code>```

Fiddle here: https://jsfiddle.net/glenn/x42uex66.

答: While using the global window object works, there might be times where a test will fail, causing the windows object to not be cleaned up for the next test. In which case you would suddenly see a lot of tests failing for seemingly no reason, instead of just the one test that caused the issue. </p>

Body:
While the official docs says,

While window is globally available in JavaScript, it causes testability problems, because it is a global variable. In AngularJS we always refer to it through the $window service, so it may be overridden, removed or mocked for testing.

I still cannot make sense of it.  How can I benefit from $window in my unit tests code? In my snippet below, I can spy/mock and make use of the native window object, with or without $window. How does it cause testability problems?

angular.module('messagePopper', [])
  .factory('popper', function popperFactory($window) {
    return {
      popupMessage(message) {
        alert(message);
      },

      popupMessageWith$window(message) {
        $window.alert(message);
      }
    };
  });

describe('messagePopper: popper service', () => {
  let $injector;
  let $window;
  let popper;

  beforeEach(() => {
    module('messagePopper');

    inject((_$injector_) => {
      $injector = _$injector_;
      $window = $injector.get('$window');
      popper = $injector.get('popper');
    });
  });

  it('should popupMessage correctly', () => {
    const message = 'welcome glenn@foodie.net';

    const alertMock = spyOn(window, 'alert');

    popper.popupMessage(message);

    expect(alertMock)
      .toHaveBeenCalledWith(message);
  });

  it('should popupMessageWith$window correctly', () => {
    const message = 'welcome glenn@foodie.net';

    const alertMock = spyOn($window, 'alert');

    popper.popupMessageWith$window(message);

    expect(alertMock)
      .toHaveBeenCalledWith(message);
  });
});

Fiddle here: https://jsfiddle.net/glenn/x42uex66.


答:
The first and foremost, in your code, temp_arr is local to the function get_random_arr(). Once the function finishes, the returned address is not valid anymore!

The moment you try to use the returned value, it causes undefined behavior, as the accessed memory is invalid in the context of the caller.

That said, not checking the return value of scanf() also posses a problem. In case scanf() fails, you'll be end up using an unitialized value.

Title: C - random numbers array function


问:
If input is not the specific type, print.. (Python)
I would like to add an "if" statement to my code. If "guess" is not an integer, print ("You did not enter a number, please re-enter") and then repeat the code from the input area instead of the starting point. The following is my attempt, however when I enter a non-int at guess input, ValueError appears. Thanks in advance!

```<code>#This is a guess the number game.
import random
print ("Hello, what is your name?")
name = input()

print ("Well, " + name + " I am thinking of a number between 1 and 20, please take a guess.")
secretNumber = random.randint(1,20)

#Establish that they get 6 tries without specifically telling them
for guessesTaken in range(1, 7):
    guess = int(input())
    if type(guess) != int:
        print ("You did not enter a number, please re-enter")
        continue

    if guess < secretNumber:
        print ("The number you guessed was too low")
    elif guess > secretNumber:
        print ("The number you guessed was too high")
    else:
        break

if guess == secretNumber:
    print ("Oh yeah, you got it")
else:
    print ("Bad luck, try again next time, the number I am thinking is " + str(secretNumber))

print ("You took " + str(guessesTaken) + " guesses.")
</code>```

答:
Use a try and except:

```<code>for guessesTaken in range(1, 7):
    try:
        guess = int(input())
    except ValueError:
        print ("You did not enter a number, please re-enter")
        continue
</code>```

So you try to convert the input into an integer. If this does not work, Python will throw an ValueError. You catch this error and ask the user try again.

Body:
I would like to add an "if" statement to my code. If "guess" is not an integer, print ("You did not enter a number, please re-enter") and then repeat the code from the input area instead of the starting point. The following is my attempt, however when I enter a non-int at guess input, ValueError appears. Thanks in advance!

#This is a guess the number game.
import random
print ("Hello, what is your name?")
name = input()

print ("Well, " + name + " I am thinking of a number between 1 and 20, please take a guess.")
secretNumber = random.randint(1,20)

#Establish that they get 6 tries without specifically telling them
for guessesTaken in range(1, 7):
    guess = int(input())
    if type(guess) != int:
        print ("You did not enter a number, please re-enter")
        continue

    if guess < secretNumber:
        print ("The number you guessed was too low")
    elif guess > secretNumber:
        print ("The number you guessed was too high")
    else:
        break

if guess == secretNumber:
    print ("Oh yeah, you got it")
else:
    print ("Bad luck, try again next time, the number I am thinking is " + str(secretNumber))

print ("You took " + str(guessesTaken) + " guesses.")

Body:
Use a try and except:

for guessesTaken in range(1, 7):
    try:
        guess = int(input())
    except ValueError:
        print ("You did not enter a number, please re-enter")
        continue

So you try to convert the input into an integer. If this does not work, Python will throw an ValueError. You catch this error and ask the user try again.


问:
Running protractor tests iwithin Jenkins - looking for some inspiration
so - I have an application which needs 3 command prompt windows open to run - this is for angular (npm start), node (node server) and webdriver (webdriver-manager start) to run.  If I do this without jenkins then I can run protractor tests using the normal "protractor " command and all works well.

I thought I'd try putting this into Jenkins (on my windows instance)

So I created a new freestyle project and had the application code checked out from git (as normal) and then used individual "Execute Windows batch command" steps for each of the steps (npm install, npm start, node server, webdriver-amanger update, webdriver-manager start, protractor )

Has anyone got experience of Node and angular with jenkins and is this the best way to run these tests?

答:
Please try something like this. You should modify accoding to what commands you want to run.

on Windows:
Step 1.

npm install

Step 2.

start npm start

Step 3. (will sleep 2 seconds)

ping -n 2 127.0.0.1 >nul

Step 4.

node node_modules/protractor/bin/protractor protractor.conf.js

On Linux:

npm install

this will start and move on without waiting for it to finish

npm start &

will wait for selenium to start

while ! curl http://localhost:4444/wd/hub/status &>/dev/null; do :;
  done

and at last

npm test

package.json example:

```<code>"scripts": {
    "postinstall": "node node_modules/protractor/bin/webdriver-manager update",
    "pretest": "npm run tsc",
    "test": "npm run protractor",
    "protractor": "node node_modules/protractor/bin/protractor",
    "start": "node node_modules/protractor/bin/webdriver-manager",
    "tsc": "node node_modules/typescript/bin/tsc"
},
</code>```

https://github.com/andriyze/proTR/blob/master/package.json

Body:
Please try something like this. You should modify accoding to what commands you want to run.

on Windows:
Step 1.

npm install

Step 2.

start npm start

Step 3. (will sleep 2 seconds)

ping -n 2 127.0.0.1 >nul

Step 4.

node node_modules/protractor/bin/protractor protractor.conf.js

On Linux:

npm install

this will start and move on without waiting for it to finish

npm start &

will wait for selenium to start

while ! curl http://localhost:4444/wd/hub/status &>/dev/null; do :;
  done

and at last

npm test

package.json example:

"scripts": {
    "postinstall": "node node_modules/protractor/bin/webdriver-manager update",
    "pretest": "npm run tsc",
    "test": "npm run protractor",
    "protractor": "node node_modules/protractor/bin/protractor",
    "start": "node node_modules/protractor/bin/webdriver-manager",
    "tsc": "node node_modules/typescript/bin/tsc"
},

https://github.com/andriyze/proTR/blob/master/package.json


问:
C#: loop through array of numbers and put consecutive numbers in one array, and all other numbers else in other array
I have an unsorted array of numbers. Most numbers in this array are consecutive (1, 2, 3, 4, 5,...) but sometimes there's a number in it that's higher than the rest.

```<code>int highestNumber = int.MinValue;
int secondHighestNumber = int.MinValue;

int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 1207, 7, 8, 9, 1803, 10, 11, , 9000, 9001 };
int counter = 0;

foreach (int number in arr) {
    if (number > highestNumber) {
        secondHighestNumber = highestNumber;
        highestNumber = number;
    }
    else if (number > secondHighestNumber) secondHighestNumber = number;
}
</code>```

When I run the code, it'll tell me 9001 is the highest number and 9000 the second highest. But I want to change it so that I get an array of all the numbers from 1 to 11, with all the consecutive numbers that only have a difference of one, and a second array with all the larger numbers: 1207, 1803, 9000 and 9001.

9000 and 9001 shouldn't be in the first array, because the difference between these numbers and the rest is too high. So the end result should look like this:

```<code>int[] arr1 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
int[] arr2 = new int[] { 1207, 1803, 9000, 9001 };
</code>```

Some background info on what the purpose of this is:

Cient creates articles and each article has an article number that is created by looking up what the highest article number is in the "articles" table so far (e.g. 20), then the number of the new article is that number + 1 (e.g. 21); So an increment per number. However the client wishes to be able to sometimes add articles and input the article number he desires for the article, so let's say for the last article he created he inputted 7000 as article number. If he he then creates another article after that, I have to continue with that list of incrementing numbers. So unless the client changes the value of the next article again, the next new article should have 22 as article number (and not 7001).

Any help would be greatly appreciated as I've been stuck on trying to figure this out for a while now.

答:
I'm not sure if you are just wanting to get the next number you should use or you want the 2 sets.  If you want the two sets, I would do this:</p>

```<code>int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 1207, 7, 8, 9, 1803, 10, 11, , 9000, 9001 };
int counter = 0;
List<int> l1 = new List<int>();
List<int> l2 = new List<int>();

foreach (int number in arr) {
    if(l1.Count==0 || l1[l1.Count-1] == (number -1))
        l1.Add(number);
    else
        l2.Add(number);
}
</code>```

Body:
I have an unsorted array of numbers. Most numbers in this array are consecutive (1, 2, 3, 4, 5,...) but sometimes there's a number in it that's higher than the rest.

int highestNumber = int.MinValue;
int secondHighestNumber = int.MinValue;

int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 1207, 7, 8, 9, 1803, 10, 11, , 9000, 9001 };
int counter = 0;

foreach (int number in arr) {
    if (number > highestNumber) {
        secondHighestNumber = highestNumber;
        highestNumber = number;
    }
    else if (number > secondHighestNumber) secondHighestNumber = number;
}

When I run the code, it'll tell me 9001 is the highest number and 9000 the second highest. But I want to change it so that I get an array of all the numbers from 1 to 11, with all the consecutive numbers that only have a difference of one, and a second array with all the larger numbers: 1207, 1803, 9000 and 9001.

9000 and 9001 shouldn't be in the first array, because the difference between these numbers and the rest is too high. So the end result should look like this:

int[] arr1 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
int[] arr2 = new int[] { 1207, 1803, 9000, 9001 };

Some background info on what the purpose of this is:

Cient creates articles and each article has an article number that is created by looking up what the highest article number is in the "articles" table so far (e.g. 20), then the number of the new article is that number + 1 (e.g. 21); So an increment per number. However the client wishes to be able to sometimes add articles and input the article number he desires for the article, so let's say for the last article he created he inputted 7000 as article number. If he he then creates another article after that, I have to continue with that list of incrementing numbers. So unless the client changes the value of the next article again, the next new article should have 22 as article number (and not 7001).

Any help would be greatly appreciated as I've been stuck on trying to figure this out for a while now.

Body:
I'm not sure if you are just wanting to get the next number you should use or you want the 2 sets.  If you want the two sets, I would do this:

int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 1207, 7, 8, 9, 1803, 10, 11, , 9000, 9001 };
int counter = 0;
List<int> l1 = new List<int>();
List<int> l2 = new List<int>();

foreach (int number in arr) {
    if(l1.Count==0 || l1[l1.Count-1] == (number -1))
        l1.Add(number);
    else
        l2.Add(number);
}


问:
dplyr: want to add only 1 y column during a join, not all y columns
I need to join a table with itself in order to realize inheritance of a value in one column, as follows:
There are two types of rows, base and dep (for "dependent").
All rows have a key, but dep rows also have a basekey referring to a base row. There is a column val and any number of other columns.

My goal: Obtain all dep rows, with their val replaced by the val of the corresponding base row.

Here is an example:

```<code>library(tidyverse)

tb = tribble(
    ~key, ~type, ~basekey, ~val, ~col5, ~colN,
    "a", "base", NA,       17,   1,      100,
    "b", "base", NA,       21,   4,      130,
    "d", "dep",  "a",      NA,   11,     320,
    "g", "dep",  "a",      NA,   14,     420,
    "n", "dep",  "a",      NA,   13,     230,
    "y", "dep",  "b",      NA,   66,     665
)
</code>```

My actual data has a few hundred rows and N=20 columns, so runtime or memory performance is not an issue, but operations requiring a complete column list should be avoided.

sqldf

Previously, I used the sqldf package, which can express my requirement nicely:

```<code>sqldf("select tb.*, tb2.val as baseval
       from tb, tb as tb2
       where tb2.key = tb.basekey")
</code>```

The result is almost exactly what I want; I only need to map baseval to val or live with the longer name (which is OK for me):

```<code>  key type basekey val col5 colN baseval
1   d  dep       a  NA   11  320      17
2   g  dep       a  NA   14  420      17
3   n  dep       a  NA   13  230      17
4   y  dep       b  NA   66  665      21
</code>```

dplyr

But then I started learning ggplot2 and encountered the tidyverse.
After some reading, I decided to throw myself into its arms and rework my code according to its readable and tidy style.

readr and tibble worked like a charm, but with dplyr I am not yet entirely happy; my use case appears to be one that is not supported well (maybe it's just that my thinking is not taking the best route yet).

I need to do a left join, but although all I want is the val column, there appears to be no method (as of dplyr 0.7.4) for suppressing the others:

```<code>tbj = left_join(filter(tb, type=='dep'), tb, by=c(basekey='key'))
</code>```

which gives me this:

```<code># A tibble: 4 x 11
    key type.x basekey val.x col5.x colN.x type.y basekey.y val.y col5.y colN.y
  <chr>  <chr>   <chr> <dbl>  <dbl>  <dbl>  <chr>     <chr> <dbl>  <dbl>  <dbl>
1     d    dep       a    NA     11    320   base      <NA>    17      1    100
2     g    dep       a    NA     14    420   base      <NA>    17      1    100
3     n    dep       a    NA     13    230   base      <NA>    17      1    100
4     y    dep       b    NA     66    665   base      <NA>    21      4    130
</code>```

Whew! To get what I want, I now need to

Map val.y to val.

Kick out all the other *.y columns

Kick out val.x

Rename the other *.x columns to remove the suffix

This sounds laborious.
How to do it best?
Is this even the right approach or is there a more dplyr-ish way to achieve my goal?

答:
Depending on how exactly one wants to match the original requirement, repairing the result tbj of the question's join is possible with medium effort (Method 1).
But a more appropriate approach may be to pre-process the tibbles some more before doing the join (Method 2).

Method 1

One can use select to keep the special columns and "all of the *.x stuff", but remove "all of the *.y stuff", and then remove val.x and delete the .x suffixes; like this

```<code>tbjs = select(tbj, key, type=type.x, basekey, baseval=val.y,
              ends_with(".x"))
select_all(select(tbjs, -val.x), funs(sub('\\.x', '', .)))

# A tibble: 4 x 6
    key  type basekey baseval  col5  colN
  <chr> <chr>   <chr>   <dbl> <dbl> <dbl>
1     d   dep       a      17    11   320
2     g   dep       a      17    14   420
3     n   dep       a      17    13   230
4     y   dep       b      21    66   665
</code>```

Not super-obvious, but not too bad either.

Method 2

One can avoid getting those many y columns in the first place by preparing the y tibble to contain only what's needed:

```<code>tb2 = select(tb, key, val)
tbj2 = left_join(filter(tb, type=='dep'), tb2, by=c(basekey='key'))
</code>```

This yields a result that is only one-and-a-half columns off:

```<code># A tibble: 4 x 7
    key  type basekey val.x  col5  colN val.y
  <chr> <chr>   <chr> <dbl> <dbl> <dbl> <dbl>
1     d   dep       a    NA    11   320    17
2     g   dep       a    NA    14   420    17
3     n   dep       a    NA    13   230    17
4     y   dep       b    NA    66   665    21
</code>```

Then get rid of val.x, rename val.y, and voila!:

```<code>tbjs2 = rename(select(tbj2, -val.x), val=val.y)

# A tibble: 4 x 6
    key  type basekey  col5  colN   val
  <chr> <chr>   <chr> <dbl> <dbl> <dbl>
1     d   dep       a    11   320    17
2     g   dep       a    14   420    17
3     n   dep       a    13   230    17
4     y   dep       b    66   665    21
</code>```

As this works without sub, I'd say it is the more dplyr-like solution.
Also, when the data gets large it will be more efficient, because the intermediate tibble is much smaller.

Body:
I need to join a table with itself in order to realize inheritance of a value in one column, as follows:
There are two types of rows, base and dep (for "dependent").
All rows have a key, but dep rows also have a basekey referring to a base row. There is a column val and any number of other columns.

My goal: Obtain all dep rows, with their val replaced by the val of the corresponding base row.

Here is an example:

library(tidyverse)

tb = tribble(
    ~key, ~type, ~basekey, ~val, ~col5, ~colN,
    "a", "base", NA,       17,   1,      100,
    "b", "base", NA,       21,   4,      130,
    "d", "dep",  "a",      NA,   11,     320,
    "g", "dep",  "a",      NA,   14,     420,
    "n", "dep",  "a",      NA,   13,     230,
    "y", "dep",  "b",      NA,   66,     665
)

My actual data has a few hundred rows and N=20 columns, so runtime or memory performance is not an issue, but operations requiring a complete column list should be avoided.

sqldf

Previously, I used the sqldf package, which can express my requirement nicely:

sqldf("select tb.*, tb2.val as baseval
       from tb, tb as tb2
       where tb2.key = tb.basekey")

The result is almost exactly what I want; I only need to map baseval to val or live with the longer name (which is OK for me):

  key type basekey val col5 colN baseval
1   d  dep       a  NA   11  320      17
2   g  dep       a  NA   14  420      17
3   n  dep       a  NA   13  230      17
4   y  dep       b  NA   66  665      21

dplyr

But then I started learning ggplot2 and encountered the tidyverse.
After some reading, I decided to throw myself into its arms and rework my code according to its readable and tidy style.

readr and tibble worked like a charm, but with dplyr I am not yet entirely happy; my use case appears to be one that is not supported well (maybe it's just that my thinking is not taking the best route yet).

I need to do a left join, but although all I want is the val column, there appears to be no method (as of dplyr 0.7.4) for suppressing the others:

tbj = left_join(filter(tb, type=='dep'), tb, by=c(basekey='key'))

which gives me this:

# A tibble: 4 x 11
    key type.x basekey val.x col5.x colN.x type.y basekey.y val.y col5.y colN.y
  <chr>  <chr>   <chr> <dbl>  <dbl>  <dbl>  <chr>     <chr> <dbl>  <dbl>  <dbl>
1     d    dep       a    NA     11    320   base      <NA>    17      1    100
2     g    dep       a    NA     14    420   base      <NA>    17      1    100
3     n    dep       a    NA     13    230   base      <NA>    17      1    100
4     y    dep       b    NA     66    665   base      <NA>    21      4    130

Whew! To get what I want, I now need to

Map val.y to val.

Kick out all the other *.y columns

Kick out val.x

Rename the other *.x columns to remove the suffix

This sounds laborious.
How to do it best?
Is this even the right approach or is there a more dplyr-ish way to achieve my goal?

Body:
Depending on how exactly one wants to match the original requirement, repairing the result tbj of the question's join is possible with medium effort (Method 1).
But a more appropriate approach may be to pre-process the tibbles some more before doing the join (Method 2).

Method 1

One can use select to keep the special columns and "all of the *.x stuff", but remove "all of the *.y stuff", and then remove val.x and delete the .x suffixes; like this

tbjs = select(tbj, key, type=type.x, basekey, baseval=val.y,
              ends_with(".x"))
select_all(select(tbjs, -val.x), funs(sub('\\.x', '', .)))

# A tibble: 4 x 6
    key  type basekey baseval  col5  colN
  <chr> <chr>   <chr>   <dbl> <dbl> <dbl>
1     d   dep       a      17    11   320
2     g   dep       a      17    14   420
3     n   dep       a      17    13   230
4     y   dep       b      21    66   665

Not super-obvious, but not too bad either.

Method 2

One can avoid getting those many y columns in the first place by preparing the y tibble to contain only what's needed:

tb2 = select(tb, key, val)
tbj2 = left_join(filter(tb, type=='dep'), tb2, by=c(basekey='key'))

This yields a result that is only one-and-a-half columns off:

# A tibble: 4 x 7
    key  type basekey val.x  col5  colN val.y
  <chr> <chr>   <chr> <dbl> <dbl> <dbl> <dbl>
1     d   dep       a    NA    11   320    17
2     g   dep       a    NA    14   420    17
3     n   dep       a    NA    13   230    17
4     y   dep       b    NA    66   665    21

Then get rid of val.x, rename val.y, and voila!:

tbjs2 = rename(select(tbj2, -val.x), val=val.y)

# A tibble: 4 x 6
    key  type basekey  col5  colN   val
  <chr> <chr>   <chr> <dbl> <dbl> <dbl>
1     d   dep       a    11   320    17
2     g   dep       a    14   420    17
3     n   dep       a    13   230    17
4     y   dep       b    66   665    21

As this works without sub, I'd say it is the more dplyr-like solution.
Also, when the data gets large it will be more efficient, because the intermediate tibble is much smaller.


问:
Indoor tracking app using IMU
I am trying to create an Android indoor tracking App using IMU.

Right now my app is based on accelerometer and software sensor ROTATION_VECTOR which is suposed to by created by fusing data from ACCELEROMETER, GEOMAGNETIC_FIELD and GYROSCOPE. I am using accelerometer for detecting steps and ROTATION_VECTOR sensor for orientation. When the step is detected, I take the data from ROTATION VECTOR, calculate the angle difference between starting and curent angle, calculate the new coordinates and display the new location.(I use steps with fixed length)

The problematic part is the accuarcy of the orientation. I read some papers which suggest use Kalman filter, However it's still a mystery for me how to implement it.

I would be very gratefull if someone help me with this problem. Suggest some tutorials how to understand Kalman filter, or show me the way how to improve the accuracy of my app.

Thanks a lot.

My code:

```<code>package com.example.jozef.gyrouhol;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import java.lang.Math;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

public class Gyro extends AppCompatActivity implements SensorEventListener {

    private SensorManager mSensorManager;
    private Sensor mRotationSensor, mStepSensor;

    private static final int SENSOR_DELAY = 1000;
    private static final int FROM_RADS_TO_DEGS = -57;
    private double norming;

    private ObjectHandler mData;

    private int count = 0;
    private int pmin = 0, pmax=0;
    private long actualTime = 0;

    private float mStartingAngle;
    private HouseBackground myView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        myView = new HouseBackground(this);
        setContentView(myView);

        try {

            mSensorManager = (SensorManager) getSystemService(Activity.SENSOR_SERVICE);
            mRotationSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
            mStepSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            mSensorManager.registerListener(this, mRotationSensor, SENSOR_DELAY);
            mSensorManager.registerListener(this,mStepSensor,SENSOR_DELAY);
        }
        catch (Exception e) {
            Toast.makeText(this, "Hardware compatibility issue", Toast.LENGTH_LONG).show();
        }

        mData = new ObjectHandler();
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onSensorChanged(SensorEvent event) {

        if (event.sensor == mRotationSensor) {

            update(event.values);
        }

        if(event.sensor == mStepSensor) {

            norming = Math.sqrt((event.values[0]*event.values[0])+(event.values[1]*event.values[1])+(event.values[2]*event.values[2]));
            stepCount(norming);
        }
    }

    private void update(float[] vectors) {

        float[] rotationMatrix = new float[9];
        SensorManager.getRotationMatrixFromVector(rotationMatrix, vectors);

        float[] orientation = new float[3];
        SensorManager.getOrientation(rotationMatrix, orientation);

        float xdeg =  orientation[0]* FROM_RADS_TO_DEGS;
        mData.ObjectHandlersetAngle(xdeg);
    }

    protected void onPause() {

        mSensorManager.unregisterListener((SensorEventListener) this);
        super.onPause();
    }

    public void stepCount (double mNorming){
        if (norming > 10.403 )

            pmax = 1;

        if (norming < 8.45)

            pmin = 1;

        if (pmax == 1 && pmin == 1) {

            if (count == 0){
                count++;
                actualTime = System.currentTimeMillis();
                if(mStartingAngle == 0)
                {
                    mStartingAngle = mData.ObjectHandlergetAngle();
                }
                myView.newPointAdd((int) (myView.getLastX()-Math.round(93*Math.cos(Math.toRadians(mData.ObjectHandlergetAngle()-mStartingAngle))) ), (int) (myView.getLastY()-Math.round(93*Math.sin(Math.toRadians(mData.ObjectHandlergetAngle()-mStartingAngle)))));

            }

            else {
                if (System.currentTimeMillis() - actualTime > 400) {
                    count++;
                    actualTime = System.currentTimeMillis();
                    int xnew = (int) (myView.getLastX()-Math.round(93*Math.cos(Math.toRadians(mData.ObjectHandlergetAngle()-mStartingAngle))));
                    int ynew = (int) (myView.getLastY()-Math.round(93*Math.sin(Math.toRadians(mData.ObjectHandlergetAngle()-mStartingAngle))));
                    myView.newPointAdd(xnew,ynew);
                }
            }

            pmin = 0;
            pmax = 0;
        }
    }
}
</code>```

答:
```<code>@Override
public void onSensorChanged(SensorEvent event) {

    final float alpha = 0.97f;

    synchronized (this) {
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {

            mGravity[0] = alpha * mGravity[0] + (1 - alpha)
                    * event.values[0];
            mGravity[1] = alpha * mGravity[1] + (1 - alpha)
                    * event.values[1];
            mGravity[2] = alpha * mGravity[2] + (1 - alpha)
                    * event.values[2];
        }

        if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {

            mGeomagnetic[0] = alpha * mGeomagnetic[0] + (1 - alpha)
                    * event.values[0];
            mGeomagnetic[1] = alpha * mGeomagnetic[1] + (1 - alpha)
                    * event.values[1];
            mGeomagnetic[2] = alpha * mGeomagnetic[2] + (1 - alpha)
                    * event.values[2];

        }

        float R[] = new float[9];
        float I[] = new float[9];
        boolean success = SensorManager.getRotationMatrix(R, I, mGravity,
                mGeomagnetic);
        if (success) {
            float orientation[] = new float[3];
            SensorManager.getOrientation(R, orientation);
            float azimuth = orientation[0]; //in radians
            azimuth = azimuth * 360 / (2 * (float) Math.PI); // -180 to 180

        }
    }
}
</code>```

Title: Indoor tracking app using IMU

Body:
I am trying to create an Android indoor tracking App using IMU.

Right now my app is based on accelerometer and software sensor ROTATION_VECTOR which is suposed to by created by fusing data from ACCELEROMETER, GEOMAGNETIC_FIELD and GYROSCOPE. I am using accelerometer for detecting steps and ROTATION_VECTOR sensor for orientation. When the step is detected, I take the data from ROTATION VECTOR, calculate the angle difference between starting and curent angle, calculate the new coordinates and display the new location.(I use steps with fixed length)

The problematic part is the accuarcy of the orientation. I read some papers which suggest use Kalman filter, However it's still a mystery for me how to implement it.

I would be very gratefull if someone help me with this problem. Suggest some tutorials how to understand Kalman filter, or show me the way how to improve the accuracy of my app.

Thanks a lot.

My code:

package com.example.jozef.gyrouhol;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import java.lang.Math;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

public class Gyro extends AppCompatActivity implements SensorEventListener {

    private SensorManager mSensorManager;
    private Sensor mRotationSensor, mStepSensor;

    private static final int SENSOR_DELAY = 1000;
    private static final int FROM_RADS_TO_DEGS = -57;
    private double norming;

    private ObjectHandler mData;

    private int count = 0;
    private int pmin = 0, pmax=0;
    private long actualTime = 0;

    private float mStartingAngle;
    private HouseBackground myView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        myView = new HouseBackground(this);
        setContentView(myView);

        try {

            mSensorManager = (SensorManager) getSystemService(Activity.SENSOR_SERVICE);
            mRotationSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
            mStepSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            mSensorManager.registerListener(this, mRotationSensor, SENSOR_DELAY);
            mSensorManager.registerListener(this,mStepSensor,SENSOR_DELAY);
        }
        catch (Exception e) {
            Toast.makeText(this, "Hardware compatibility issue", Toast.LENGTH_LONG).show();
        }

        mData = new ObjectHandler();
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onSensorChanged(SensorEvent event) {

        if (event.sensor == mRotationSensor) {

            update(event.values);
        }

        if(event.sensor == mStepSensor) {

            norming = Math.sqrt((event.values[0]*event.values[0])+(event.values[1]*event.values[1])+(event.values[2]*event.values[2]));
            stepCount(norming);
        }
    }

    private void update(float[] vectors) {

        float[] rotationMatrix = new float[9];
        SensorManager.getRotationMatrixFromVector(rotationMatrix, vectors);

        float[] orientation = new float[3];
        SensorManager.getOrientation(rotationMatrix, orientation);

        float xdeg =  orientation[0]* FROM_RADS_TO_DEGS;
        mData.ObjectHandlersetAngle(xdeg);
    }

    protected void onPause() {

        mSensorManager.unregisterListener((SensorEventListener) this);
        super.onPause();
    }

    public void stepCount (double mNorming){
        if (norming > 10.403 )

            pmax = 1;

        if (norming < 8.45)

            pmin = 1;

        if (pmax == 1 && pmin == 1) {

            if (count == 0){
                count++;
                actualTime = System.currentTimeMillis();
                if(mStartingAngle == 0)
                {
                    mStartingAngle = mData.ObjectHandlergetAngle();
                }
                myView.newPointAdd((int) (myView.getLastX()-Math.round(93*Math.cos(Math.toRadians(mData.ObjectHandlergetAngle()-mStartingAngle))) ), (int) (myView.getLastY()-Math.round(93*Math.sin(Math.toRadians(mData.ObjectHandlergetAngle()-mStartingAngle)))));

            }

            else {
                if (System.currentTimeMillis() - actualTime > 400) {
                    count++;
                    actualTime = System.currentTimeMillis();
                    int xnew = (int) (myView.getLastX()-Math.round(93*Math.cos(Math.toRadians(mData.ObjectHandlergetAngle()-mStartingAngle))));
                    int ynew = (int) (myView.getLastY()-Math.round(93*Math.sin(Math.toRadians(mData.ObjectHandlergetAngle()-mStartingAngle))));
                    myView.newPointAdd(xnew,ynew);
                }
            }

            pmin = 0;
            pmax = 0;
        }
    }
}


问:
Data frame column: Convert only numbers to int, words to remain as strings
As shown in the screenshot below, I have 2 columns in an excel file. I'm trying to reduce the precision of the number fields eg 100.54000000000001 to 100.540. The number is stored as string, so when I convert it to float using

```<code>df['Unnamed: 5'] = pd.to_numeric(df['Unnamed: 5'], errors='coerce')
</code>```

it converts strings to NaN. Can anyone help me with issue? I'm trying to convert only numbers to int, and words should remain strings.

EDIT: It would be acceptable to convert the numeric values back to string after rounding them.  My code is as follows:

```<code>>>> import pandas as pd
>>> import numpy as np
>>> xl = pd.ExcelFile("WSJ_template.xls")
>>> xl.sheet_names
[u'losers', u'winners']
>>> dfw = xl.parse("winners")
>>> dfw.head()
<output>
>>> dfw = dfw.apply(pd.to_numeric, errors='coerce').combine_first(dfw)
>>> dfw = dfw.replace(np.nan, '', regex=True)
>>> dfw
<output>
</code>```

答:
As you already identified, we're best off using pd.DataFrame.apply.  The only difference is rather than using a built-in function, we'll define our own.

We'll start off by filling the DataFrame (this is a placeholder, you already have this covered):

```<code>df = pd.DataFrame(columns=['Unnamed: 5', 'Unnamed: 6'],
                  data=[['NaN', 'NaN'],
                        ['Average', 'Weekly'],
                        ['100.540000000001', '0.2399999999999999'],
                        ['99.3299999999998', '0.1700000000000001'],
                        ['95.4800000000004', 'change'],
                        ['bid', '1.929999999999999']])
</code>```

Now we define a function to use to convert values.  This function should try to cast to float and if it works, return the rounded value.  If it doesn't work, just return the original value.  Here's one possible route:

```<code>def round_only_nums(val):
    try:
        return '%s' % round(float(val), 3)
    except:
        return val
</code>```

Next, let's apply that the columns that need processing:

```<code>cols_to_process = ['Unnamed: 5', 'Unnamed: 6']
for col in cols_to_process:
    df[col] = df[col].apply(round_only_nums)
</code>```

And our results:

```<code>>>> df
  Unnamed: 5 Unnamed: 6
0        nan        nan
1    Average     Weekly
2     100.54       0.24
3      99.33       0.17
4      95.48     change
5        bid       1.93
</code>```

Body:
As shown in the screenshot below, I have 2 columns in an excel file. I'm trying to reduce the precision of the number fields eg 100.54000000000001 to 100.540. The number is stored as string, so when I convert it to float using

df['Unnamed: 5'] = pd.to_numeric(df['Unnamed: 5'], errors='coerce')

it converts strings to NaN. Can anyone help me with issue? I'm trying to convert only numbers to int, and words should remain strings.

EDIT: It would be acceptable to convert the numeric values back to string after rounding them.  My code is as follows:

>>> import pandas as pd
>>> import numpy as np
>>> xl = pd.ExcelFile("WSJ_template.xls")
>>> xl.sheet_names
[u'losers', u'winners']
>>> dfw = xl.parse("winners")
>>> dfw.head()
<output>
>>> dfw = dfw.apply(pd.to_numeric, errors='coerce').combine_first(dfw)
>>> dfw = dfw.replace(np.nan, '', regex=True)
>>> dfw
<output>

Body:
As you already identified, we're best off using pd.DataFrame.apply.  The only difference is rather than using a built-in function, we'll define our own.

We'll start off by filling the DataFrame (this is a placeholder, you already have this covered):

df = pd.DataFrame(columns=['Unnamed: 5', 'Unnamed: 6'],
                  data=[['NaN', 'NaN'],
                        ['Average', 'Weekly'],
                        ['100.540000000001', '0.2399999999999999'],
                        ['99.3299999999998', '0.1700000000000001'],
                        ['95.4800000000004', 'change'],
                        ['bid', '1.929999999999999']])

Now we define a function to use to convert values.  This function should try to cast to float and if it works, return the rounded value.  If it doesn't work, just return the original value.  Here's one possible route:

def round_only_nums(val):
    try:
        return '%s' % round(float(val), 3)
    except:
        return val

Next, let's apply that the columns that need processing:

cols_to_process = ['Unnamed: 5', 'Unnamed: 6']
for col in cols_to_process:
    df[col] = df[col].apply(round_only_nums)

And our results:

>>> df
  Unnamed: 5 Unnamed: 6
0        nan        nan
1    Average     Weekly
2     100.54       0.24
3      99.33       0.17
4      95.48     change
5        bid       1.93


问:
Query ranges for numbers in an array
Given N input integers, and M query ranges, output the set of integers that fall within each query range (both bounds are inclusive). For example:

```<code>N = [-10, -1, -2, 0, 0, 8, 12, 16]
M = [(-100, 0), (2, 5), (13, 18)]
</code>```

The answer/output would then be:

```<code>[-10, -1, -2, 0, 0]
[]
[16]
</code>```

I've been trying to think of optimal solutions to this, and am struggling to come up with something that's better than O(N*M) at worst case. The approaches I've considered so far are:

Brute Force - For each query, check every digit in N and see if it falls within the range.

Presorted Input - Sort the input digits (O(NlogN)), and then do the above. Can do bounds checks for queries that are completely out of range, and remove the need to iterate (i.e. querying (0, 2) for a list like [5, 6, 7]). This still involves iterating though, and at worst case is still O(NM) (right?)

Hash Set - Add each value in the input array into a hash set, and then for each possible integer value within the query range, check if it exists in the hash set. This works for smaller ranges, but basically is the same thing -> it's O(MX) where X is the length of the query range. So if you have a query range that's huge (i.e. (-10000000, 10000000)), it wouldn't scale.

I would love to hear/learn about solutions that are better! (An alternative to this question is determining the # of digits that are within each query range, as opposed to outputting the digits).

Please let me know!

答:
I would suggest sorting the ranges rather than the input numbers, then simply checking whether any given input matches a range Even better if you can get the ranges before the list of numbers., that way you could only iterate the numbers once (as you read them).

You still have to iterate the input number list (nothing is going to help you there), but the range list should be smaller than the numbers list and so both the sort and search will be faster.

Title: Query ranges for numbers in an array

Body:
Given N input integers, and M query ranges, output the set of integers that fall within each query range (both bounds are inclusive). For example:

N = [-10, -1, -2, 0, 0, 8, 12, 16]
M = [(-100, 0), (2, 5), (13, 18)]

The answer/output would then be:

[-10, -1, -2, 0, 0]
[]
[16]

I've been trying to think of optimal solutions to this, and am struggling to come up with something that's better than O(N*M) at worst case. The approaches I've considered so far are:

Brute Force - For each query, check every digit in N and see if it falls within the range.

Presorted Input - Sort the input digits (O(NlogN)), and then do the above. Can do bounds checks for queries that are completely out of range, and remove the need to iterate (i.e. querying (0, 2) for a list like [5, 6, 7]). This still involves iterating though, and at worst case is still O(NM) (right?)

Hash Set - Add each value in the input array into a hash set, and then for each possible integer value within the query range, check if it exists in the hash set. This works for smaller ranges, but basically is the same thing -> it's O(MX) where X is the length of the query range. So if you have a query range that's huge (i.e. (-10000000, 10000000)), it wouldn't scale.

I would love to hear/learn about solutions that are better! (An alternative to this question is determining the # of digits that are within each query range, as opposed to outputting the digits).

Please let me know!


问:
Neither "import" nor "require" works
I'm using Noty version 3 https://github.com/needim/noty. According to the documentation I should use require or import.

```<code>import Noty from 'noty';

new Noty({
    text: 'Notification text'
}).show();

// or

const Noty = require('noty');

new Noty({
    text: 'Notification text'
}).show();
</code>```

But none works. Even in the last version of Chrome.

When I'm using require:

Uncaught ReferenceError: require is not defined

And when import:

Uncaught SyntaxError: Unexpected token import

答:
First, I don't agree with giving thumbs down to questions. I thought where was no such thing as a stupid question.

That said, you can definitely use import or require. You're just going to have to use something like Browserify to make them work.

If you really want to get that way, I've got a repo here that I just set up to try out Noty stuff

Title: Neither "import" nor "require" works

Body:
I'm using Noty version 3 https://github.com/needim/noty. According to the documentation I should use require or import.

import Noty from 'noty';

new Noty({
    text: 'Notification text'
}).show();

// or

const Noty = require('noty');

new Noty({
    text: 'Notification text'
}).show();

But none works. Even in the last version of Chrome.

When I'm using require:

Uncaught ReferenceError: require is not defined

And when import:

Uncaught SyntaxError: Unexpected token import


问:
Boto3 ec2 describe_instances always returns empty
I have a very simple sandbox I'm trying to get to work so I can use it in a bigger application:

```<code>ec2_client = boto3.client(
    'ec2',
    aws_access_key_id=ACCESS_KEY,
    aws_secret_access_key=SECRET_KEY)

response = ec2_client.describe_instances()
print(response)
</code>```

and it results in...

```<code>{
  'Reservations': [],
  'ResponseMetadata': {
    'RequestId': '2c28e8aa-da6d-4ca4-8ea7-f672518cac9f',
    'HTTPStatusCode': 200,
    'HTTPHeaders': {
      'content-type': 'text/xml;charset=UTF-8',
      'transfer-encoding': 'chunked',
      'vary': 'Accept-Encoding',
      'date': 'Thu, 07 Dec 2017 16:44:30 GMT',
      'server': 'AmazonEC2'
  },
  'RetryAttempts': 0}
}
</code>```

But the problem is no matter how many times I run this Reservations is ALWAYS empty :(.

In AWS consonle I can CLEARLLY see an instance is running...

I tried starting more instances, restarting the instances I had running. I put my initial script in a loop and ran it on repeat while I did this looking for any sign of the Reservations array actually having data.

I double checked that my aws ACCESS_KEY and SECRET_KEY are both correct and pointing to the correct account. They are.

I have no clue why this is. Its so simple and should be working. I'm new to AWS so any help is appreciated.

答:
The problem is that somehow boto3 was using a region that my instance was not running in. The solution was to specify the region when initializing the client:

```<code>ec2_client = boto3.client(
    'ec2',
    region_name='us-east-2',
    aws_access_key_id=ACCESS_KEY,
    aws_secret_access_key=SECRET_KEY)
</code>```

All credit to @kichik for telling me where to look!

Body:
I have a very simple sandbox I'm trying to get to work so I can use it in a bigger application:

ec2_client = boto3.client(
    'ec2',
    aws_access_key_id=ACCESS_KEY,
    aws_secret_access_key=SECRET_KEY)

response = ec2_client.describe_instances()
print(response)

and it results in...

{
  'Reservations': [],
  'ResponseMetadata': {
    'RequestId': '2c28e8aa-da6d-4ca4-8ea7-f672518cac9f',
    'HTTPStatusCode': 200,
    'HTTPHeaders': {
      'content-type': 'text/xml;charset=UTF-8',
      'transfer-encoding': 'chunked',
      'vary': 'Accept-Encoding',
      'date': 'Thu, 07 Dec 2017 16:44:30 GMT',
      'server': 'AmazonEC2'
  },
  'RetryAttempts': 0}
}

But the problem is no matter how many times I run this Reservations is ALWAYS empty :(.

In AWS consonle I can CLEARLLY see an instance is running...

I tried starting more instances, restarting the instances I had running. I put my initial script in a loop and ran it on repeat while I did this looking for any sign of the Reservations array actually having data.

I double checked that my aws ACCESS_KEY and SECRET_KEY are both correct and pointing to the correct account. They are.

I have no clue why this is. Its so simple and should be working. I'm new to AWS so any help is appreciated.

Body:
The problem is that somehow boto3 was using a region that my instance was not running in. The solution was to specify the region when initializing the client:

ec2_client = boto3.client(
    'ec2',
    region_name='us-east-2',
    aws_access_key_id=ACCESS_KEY,
    aws_secret_access_key=SECRET_KEY)

All credit to @kichik for telling me where to look!


问:
Reading 2-D array from a file
I have a 2-D int array in file 'array.txt'. I am trying to read all the elements in the file in a two dimensional array. I am having problem in copying. It shows all the elements having value '0' after copying instead their original value. Please help me.
My code is : </p>

```<code>import java.util.*;
import java.lang.*;
import java.io.*;

public class appMainNineSix {

    /**
     * @param args
     */
    public static void main(String[] args)
        throws java.io.FileNotFoundException{
        // TODO Auto-generated method stub
        Scanner input = new Scanner (new File("src/array.txt"));
        int m = 3;
        int n = 5;
        int[][] a = new int [m][n];
        while (input.next()!=null){
            for (int i=0;i<m;i++){
                for (int j=0;j<n;j++)
                    a[i][j]= input.nextInt();
            }

        }
        //print the input matrix
        System.out.println("The input sorted matrix is : ");
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++)
                System.out.println(a[i][j]);
        }

    }

}
</code>```

答:
Start simple...

change:

```<code>for (int j=0;j<n;j++)
    a[i][j]= input.nextInt();
</code>```

to:

```<code>for (int j=0;j<n;j++)
{
    int value;

    value = input.nextInt();
    a[i][j] = value;
    System.out.println("value[" + i + "][" + j + " = " + value);
}
</code>```

And make sure that the values are read in.

Also, you should not call next without first calling (and checking) hasNext (or nextInt/hasNextInt).

Title: Reading 2-D array from a file

Body:
I have a 2-D int array in file 'array.txt'. I am trying to read all the elements in the file in a two dimensional array. I am having problem in copying. It shows all the elements having value '0' after copying instead their original value. Please help me.
My code is :

import java.util.*;
import java.lang.*;
import java.io.*;

public class appMainNineSix {

    /**
     * @param args
     */
    public static void main(String[] args)
        throws java.io.FileNotFoundException{
        // TODO Auto-generated method stub
        Scanner input = new Scanner (new File("src/array.txt"));
        int m = 3;
        int n = 5;
        int[][] a = new int [m][n];
        while (input.next()!=null){
            for (int i=0;i<m;i++){
                for (int j=0;j<n;j++)
                    a[i][j]= input.nextInt();
            }

        }
        //print the input matrix
        System.out.println("The input sorted matrix is : ");
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++)
                System.out.println(a[i][j]);
        }

    }

}

Body:
Start simple...

change:

for (int j=0;j<n;j++)
    a[i][j]= input.nextInt();

to:

for (int j=0;j<n;j++)
{
    int value;

    value = input.nextInt();
    a[i][j] = value;
    System.out.println("value[" + i + "][" + j + " = " + value);
}

And make sure that the values are read in.

Also, you should not call next without first calling (and checking) hasNext (or nextInt/hasNextInt).


问:
How to remove elements in a vector that match some element in another vector
I want to remove elements in a vector v2 that match the elements in another vector v1, where each element in v1 has a corresponding element in v2 but not vice versa.

My idea is to use std::vector::erase, std::remove_if and std::find like this:

```<code>std::vector<int> v1{ 6, 2, 4 };
std::vector<int> v2{ 8, 2, 9, 4, 5, 3, 7, 1, 6 };

v2.erase(
  std::remove_if(v2.begin(), v2.end()
  , [&v1](auto& item)
  {
    return std::find(v1.begin(), v1.end(), item) != v1.end();
  })
);
</code>```

Which works.  However, I wonder if I could do without matching those that have already been matched as this is a 1:1 relationship when going from v1 -> v2.  v1 will be blown away afterwards, so it can be modified.

答:
If you are allowed to modify v1, then something like the following would work:

```<code>v2.erase(
  std::remove_if(v2.begin(), v2.end(),
    [&v1](auto& item) {
      auto it = std::find(v1.begin(), v1.end(), item);
      if (it != v1.end()) {
        v1.erase(it);
        return true;
      }
      return false;
    }
  ), v2.end());
</code>```

Edit 1: Sort v1 first, then use std::lower_bound for O(log n) search speed instead of O(n).

Edit 2: Store v1's elements into an std::unordered_set to make erase and find O(1) amortized instead.

Edit 3: Added bugfix regarding erase as mentioned by Yakk.

Body:
I want to remove elements in a vector v2 that match the elements in another vector v1, where each element in v1 has a corresponding element in v2 but not vice versa.

My idea is to use std::vector::erase, std::remove_if and std::find like this:

std::vector<int> v1{ 6, 2, 4 };
std::vector<int> v2{ 8, 2, 9, 4, 5, 3, 7, 1, 6 };

v2.erase(
  std::remove_if(v2.begin(), v2.end()
  , [&v1](auto& item)
  {
    return std::find(v1.begin(), v1.end(), item) != v1.end();
  })
);

Which works.  However, I wonder if I could do without matching those that have already been matched as this is a 1:1 relationship when going from v1 -> v2.  v1 will be blown away afterwards, so it can be modified.

Body:
If you are allowed to modify v1, then something like the following would work:

v2.erase(
  std::remove_if(v2.begin(), v2.end(),
    [&v1](auto& item) {
      auto it = std::find(v1.begin(), v1.end(), item);
      if (it != v1.end()) {
        v1.erase(it);
        return true;
      }
      return false;
    }
  ), v2.end());

Edit 1: Sort v1 first, then use std::lower_bound for O(log n) search speed instead of O(n).

Edit 2: Store v1's elements into an std::unordered_set to make erase and find O(1) amortized instead.

Edit 3: Added bugfix regarding erase as mentioned by Yakk.


问:
How can I print the possible combinations of a list in Python?
My list is:

```<code>groupA=['Russia', 'Egypt', 'Saudi Arabia', 'Uruguay']
</code>```

So I want to print all the unique combinations of teams that will play each other:

```<code>Russia Vs. Egypt
Russia Vs. Saudi Arabia
Russia Vs. Uruguay
Egypt Vs. Saudi Arabia
Egypt Vs. Uruguay
Saudi Arabia Vs. Uruguay
</code>```

Can I do this with a for loop?

答:
This can do the trick:</p>

```<code>groupA = ['Russia', 'Egypt', 'Saudi Arabia', 'Uruguay']
for index, country in enumerate(groupA):
    for rival in groupA[index+1:]:
        print('%s vs %s'%(country, rival) )
</code>```

Body:
My list is:

groupA=['Russia', 'Egypt', 'Saudi Arabia', 'Uruguay']

So I want to print all the unique combinations of teams that will play each other:

Russia Vs. Egypt
Russia Vs. Saudi Arabia
Russia Vs. Uruguay
Egypt Vs. Saudi Arabia
Egypt Vs. Uruguay
Saudi Arabia Vs. Uruguay

Can I do this with a for loop?

Body:
This can do the trick:

groupA = ['Russia', 'Egypt', 'Saudi Arabia', 'Uruguay']
for index, country in enumerate(groupA):
    for rival in groupA[index+1:]:
        print('%s vs %s'%(country, rival) )


问:
Show only one side of 3D object Threejs
I have pb with threeJS obj, I loaded 3d object and want show only one side of this object not full,

```<code>  export function loadObjWithMaterial(mtlFile, objFile, imgPath) {
  let mtlLoader = new MTLLoader();
  mtlLoader.setTexturePath(imgPath);

  let url = mtlFile;
  return new Promise((resolve, reject) => {
    mtlLoader.load(url, materials => {
      materials.preload();
      let objLoader = new OBJLoader();
      objLoader.setMaterials(materials);
      objLoader.load(objFile, object => resolve(object));
      objLoader.load(objFile, function(object){
          resolve(object)
      });
    });
  });
}
</code>```

and now I tried to show only one side of the object and add this one

```<code>mtlLoader.setMaterialOptions({side: 1});
</code>```

seems now it should show only one side of object but its not.

what i want

what i have now

答:
You can try this one. Anyway 'THREE.FrontSide' is the default value for the side property.

```<code>mtlLoader.setMaterialOptions( { side : THREE.FrontSide } );
</code>```

Here you can see the documentation

ContentLicense: CC BY-SA 4.0

Title: Show only one side of 3D object Threejs

Body:
I have pb with threeJS obj, I loaded 3d object and want show only one side of this object not full,

  export function loadObjWithMaterial(mtlFile, objFile, imgPath) {
  let mtlLoader = new MTLLoader();
  mtlLoader.setTexturePath(imgPath);

  let url = mtlFile;
  return new Promise((resolve, reject) => {
    mtlLoader.load(url, materials => {
      materials.preload();
      let objLoader = new OBJLoader();
      objLoader.setMaterials(materials);
      objLoader.load(objFile, object => resolve(object));
      objLoader.load(objFile, function(object){
          resolve(object)
      });
    });
  });
}

and now I tried to show only one side of the object and add this one

mtlLoader.setMaterialOptions({side: 1});

seems now it should show only one side of object but its not.

what i want

what i have now

Body:
You can try this one. Anyway 'THREE.FrontSide' is the default value for the side property.

mtlLoader.setMaterialOptions( { side : THREE.FrontSide } );

Here you can see the documentation


问:
Laravel 5.5 - Deep Relations calling by -->
I now spent hours googling and experimenting on trying to get an relation with two intermediate tables working.
My database looks like this:
(apt_id is apartment_id in real, was shorter to write)

I have every relation one away setup correctly with belongsTo and and hasMany:
EXAMPLE FROM House.php

```<code>    public function user()
{
    return $this->belongsTo('App\User');
}

public function apartments()
{
    return $this->hasMany('App\Apartment');
}
</code>```

Isn't there a way to access these relations like:

```<code>$house->apartments->tenants->entries
</code>```

in Blade:

```<code>@foreach ( $house->apartments->tenants->entries as $entry )
</code>```

, since I want to display all house entries on house.show (Blade View)

The only way it's working is by using a bunch of foreach inside each others... :/ and they define the order...

Using my wanted relation calling produces:

```<code>Property [tenants] does not exist on this collection instance.
</code>```

displayed on the page.

Greetings,
Pat

答:
I don't think you can achieve what you want using the code you posted, because when calling, for example, $house->apartments it returns a Collection object. So, it is not dealing with database anymore, that's why you would need to use a bunch of @foreachs.

I don't know if this is the best way to solve this, or if it will help you in your actual problem, but you could think this problem backwards and try something like this:

```<code>$entries = \App\Entry::whereHas('tenants', function($q) use ($house) {
            $q->whereHas('apartments', function($q1) use ($house) {
                $q1->where('apartments.house_id', $house->id);
            });
        })->get();
</code>```

And in the view:

```<code>@foreach ($entries as $entry)
    {{ $entry->tenant->apartment->house->name }}
@endforeach
</code>```

Body:
I now spent hours googling and experimenting on trying to get an relation with two intermediate tables working.
My database looks like this:
(apt_id is apartment_id in real, was shorter to write)

I have every relation one away setup correctly with belongsTo and and hasMany:
EXAMPLE FROM House.php

    public function user()
{
    return $this->belongsTo('App\User');
}

public function apartments()
{
    return $this->hasMany('App\Apartment');
}

Isn't there a way to access these relations like:

$house->apartments->tenants->entries

in Blade:

@foreach ( $house->apartments->tenants->entries as $entry )

, since I want to display all house entries on house.show (Blade View)

The only way it's working is by using a bunch of foreach inside each others... :/ and they define the order...

Using my wanted relation calling produces:

Property [tenants] does not exist on this collection instance.

displayed on the page.

Greetings,
Pat

Body:
I don't think you can achieve what you want using the code you posted, because when calling, for example, $house->apartments it returns a Collection object. So, it is not dealing with database anymore, that's why you would need to use a bunch of @foreachs.

I don't know if this is the best way to solve this, or if it will help you in your actual problem, but you could think this problem backwards and try something like this:

$entries = \App\Entry::whereHas('tenants', function($q) use ($house) {
            $q->whereHas('apartments', function($q1) use ($house) {
                $q1->where('apartments.house_id', $house->id);
            });
        })->get();

And in the view:

@foreach ($entries as $entry)
    {{ $entry->tenant->apartment->house->name }}
@endforeach


问:
Create a large file with a given size with a pattern in Linux
In Linux how can I create a large file with a given text or hex pattern (Like DEADBEEFDEADBEEFDEADBEEF ....)

I know dd can be used to create large files but it doesn't write desired text or hex pattern

```<code>dd if=/dev/urandom of=/tmp/bigfile bs=blocksize count=size
</code>```

or

```<code>dd if=/dev/zero of=/tmp/bigfile bs=blocksize count=size
</code>```

Quickly create a large file on a Linux system?

How to create a file with a given size in Linux?

答:
```<code>while true ; do printf "DEADBEEF"; done | dd of=/tmp/bigfile bs=blocksize count=size iflag=fullblock
</code>```

Body:
In Linux how can I create a large file with a given text or hex pattern (Like DEADBEEFDEADBEEFDEADBEEF ....)

I know dd can be used to create large files but it doesn't write desired text or hex pattern

dd if=/dev/urandom of=/tmp/bigfile bs=blocksize count=size

or

dd if=/dev/zero of=/tmp/bigfile bs=blocksize count=size

Quickly create a large file on a Linux system?

How to create a file with a given size in Linux?