问:
ES6 modules and decorator pattern
I understand that the import statement delivers a read-only binding to a module and I guess it depends on the module loader, but is it intended to be possible to import, decorate and re-export using ES6 modules?

For example, this fails when using rollup.js

test.plugin.js

```<code>import * as d3 from 'd3'
d3.ui = {test: 1};
export default d3;
</code>```

index.js

```<code>import * as d3 from 'd3'
import './src/test.plugin'
</code>```

Rollup error...

```<code>Illegal reassignment to import 'd3'
src\test.plugin.js (6:0)
4:
5: import * as d3 from 'd3'
6: d3.ui = {test: 1};
</code>```

And so does this...

```<code>test.plugin.js
export default (d3) => d3.ui = {test: 1};
</code>```

index.js

```<code>import * as d3 from 'd3'
import test from './src/test.plugin'

test(d3);
</code>```

The first one fails because the imports are immutable and the second because the module resolution is static.

Is it supposed to be possible to use the decorator pattern with ES6 modules?

答:
Update

The problem is that module objects are not extensible. What is extensible is instead an object inside the module object.

Module A

```<code>let mod = { a, b, c };
// Once exported the "mod" object cannot be extended from the outside
export mod;
</code>```

index.js

```<code>// What you are saying here is
import * as mod from "moduleA.js"

// mod cannot be extended here
// mod.b can be extended though
mod.b.ui = {test: 1};
</code>```

Default export

When you do the default export you can extend it as default is effectively a nested property.

Module A

```<code>let mod = { a, b, c };
// Once exported as default
export default mod;
</code>```

index.js

```<code> import mod from "moduleA.js"

 // mod is effectively a prop of the module object, so it can be extended
 mod.d = { ... };
</code>```

In your case you can do the following:

test.plugin.js

```<code>// Import d3 as a composition of props
import * as d3 from 'd3';
// Create a new object using the Object.assign operator
// You can use the spread operator too
const d3plus = Object.assign({ui: () => 'test'}, d3);
// Now d3plus will be extendable!
export default d3plus;
</code>```

index.js

```<code>import d3plus from 'test.plugin.js';

console.log(d3plus.ui);
</code>```

Old wrong answer

This is my answer when I got it wrong reading the spec. To be fair also some other module bundler got it wrong before hand, as es6 modules are pretty hard.

When you have module A and you want to decorate it with new functions/things you have two choices:

Wrap the module A and then use the wrapper only later on

Write decorator functions you apply when you need it (as in your second example).

In the former case you can do:

test.plugin.js

```<code>import * as d3 from 'd3'
d3.ui = {test: 1};
export default d3;
</code>```

index.js

```<code>// Note that using this wrapper makes sure you have the extra stuff all the time
import d3plus from './src/test.plugin';

console.log(d3plus.ui);
</code>```

With the second approach you have to get the result of the decorator operation:

test.plugin.js

```<code>export default (d3) => {
  d3.ui = {test: 1};
  // Do not forget to return the new object
  return d3;
};
</code>```

index.js

```<code>import * as d3 from 'd3'
import pluginify from './src/test.plugin'

// Note that this change is local to this module only
const d3plus = pluginify(d3);
console.log(d3plus.ui);
</code>```

You may use some more tricks to achieve the same result but I would recommend to make it explicit the enrichment process you are applying to the module.

Title: ES6 modules and decorator pattern

Body:
I understand that the import statement delivers a read-only binding to a module and I guess it depends on the module loader, but is it intended to be possible to import, decorate and re-export using ES6 modules?

For example, this fails when using rollup.js

test.plugin.js

import * as d3 from 'd3'
d3.ui = {test: 1};
export default d3;

index.js

import * as d3 from 'd3'
import './src/test.plugin'

Rollup error...

Illegal reassignment to import 'd3'
src\test.plugin.js (6:0)
4:
5: import * as d3 from 'd3'
6: d3.ui = {test: 1};

And so does this...

test.plugin.js
export default (d3) => d3.ui = {test: 1};

index.js

import * as d3 from 'd3'
import test from './src/test.plugin'

test(d3);

The first one fails because the imports are immutable and the second because the module resolution is static.

Is it supposed to be possible to use the decorator pattern with ES6 modules?

Body:
Update

The problem is that module objects are not extensible. What is extensible is instead an object inside the module object.

Module A

let mod = { a, b, c };
// Once exported the "mod" object cannot be extended from the outside
export mod;

index.js

// What you are saying here is
import * as mod from "moduleA.js"

// mod cannot be extended here
// mod.b can be extended though
mod.b.ui = {test: 1};

Default export

When you do the default export you can extend it as default is effectively a nested property.

Module A

let mod = { a, b, c };
// Once exported as default
export default mod;

index.js

 import mod from "moduleA.js"

 // mod is effectively a prop of the module object, so it can be extended
 mod.d = { ... };

In your case you can do the following:

test.plugin.js

// Import d3 as a composition of props
import * as d3 from 'd3';
// Create a new object using the Object.assign operator
// You can use the spread operator too
const d3plus = Object.assign({ui: () => 'test'}, d3);
// Now d3plus will be extendable!
export default d3plus;

index.js

import d3plus from 'test.plugin.js';

console.log(d3plus.ui);

Old wrong answer

This is my answer when I got it wrong reading the spec. To be fair also some other module bundler got it wrong before hand, as es6 modules are pretty hard.

When you have module A and you want to decorate it with new functions/things you have two choices:

Wrap the module A and then use the wrapper only later on

Write decorator functions you apply when you need it (as in your second example).

In the former case you can do:

test.plugin.js

import * as d3 from 'd3'
d3.ui = {test: 1};
export default d3;

index.js

// Note that using this wrapper makes sure you have the extra stuff all the time
import d3plus from './src/test.plugin';

console.log(d3plus.ui);

With the second approach you have to get the result of the decorator operation:

test.plugin.js

export default (d3) => {
  d3.ui = {test: 1};
  // Do not forget to return the new object
  return d3;
};

index.js

import * as d3 from 'd3'
import pluginify from './src/test.plugin'

// Note that this change is local to this module only
const d3plus = pluginify(d3);
console.log(d3plus.ui);

You may use some more tricks to achieve the same result but I would recommend to make it explicit the enrichment process you are applying to the module.


来源: stackexchange

问:
Runtime Exception:Invalid version (expected 2, but 60) or the data in not in 'javabin' format in solr
I am getting a runtime exception when I am making the following simple call to ping my solr at localhost.

```<code>public static void main(String[] args) throws SolrServerException, IOException
    {
        String url = "http://127.0.0.1:8983/solr/#";
        HttpSolrServer solrServer = new HttpSolrServer(url);
        solrServer.ping();

    }
</code>```

The exception log is :

```<code>Exception in thread "main" java.lang.RuntimeException: Invalid version (expected 2, but     60) or the data in not in 'javabin' format
    at org.apache.solr.common.util.JavaBinCodec.unmarshal(JavaBinCodec.java:109)
    at         org.apache.solr.client.solrj.impl.BinaryResponseParser.processResponse(BinaryResponseParser.    java:41)
    at org.apache.solr.client.solrj.impl.HttpSolrServer.request(HttpSolrServer.java:407)
    at org.apache.solr.client.solrj.impl.HttpSolrServer.request(HttpSolrServer.java:180)
    at org.apache.solr.client.solrj.request.SolrPing.process(SolrPing.java:69)
    at org.apache.solr.client.solrj.SolrServer.ping(SolrServer.java:293)
    at com.tradus.LocalSolrDataAdd.main(LocalSolrDataAdd.java:26)
</code>```

Can someone explain how we can get rid of this apparently very weird error.

答: It is usually because the different version between the solr client and solr server.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am getting a runtime exception when I am making the following simple call to ping my solr at localhost.

public static void main(String[] args) throws SolrServerException, IOException
    {
        String url = "http://127.0.0.1:8983/solr/#";
        HttpSolrServer solrServer = new HttpSolrServer(url);
        solrServer.ping();

    }

The exception log is :

Exception in thread "main" java.lang.RuntimeException: Invalid version (expected 2, but     60) or the data in not in 'javabin' format
    at org.apache.solr.common.util.JavaBinCodec.unmarshal(JavaBinCodec.java:109)
    at         org.apache.solr.client.solrj.impl.BinaryResponseParser.processResponse(BinaryResponseParser.    java:41)
    at org.apache.solr.client.solrj.impl.HttpSolrServer.request(HttpSolrServer.java:407)
    at org.apache.solr.client.solrj.impl.HttpSolrServer.request(HttpSolrServer.java:180)
    at org.apache.solr.client.solrj.request.SolrPing.process(SolrPing.java:69)
    at org.apache.solr.client.solrj.SolrServer.ping(SolrServer.java:293)
    at com.tradus.LocalSolrDataAdd.main(LocalSolrDataAdd.java:26)

Can someone explain how we can get rid of this apparently very weird error.


问:
Showing a Picture in Django Action Stream
I want an action stream notifications each time a user uploads a picture. I get the usual "Actor uploaded a photo on datetime", but I can't figure out how to add the actual picture.

I think it should be an action_object, but I can't get the right iteration to show the actual picture. Photo.objects.get(pk=target) might work, but I can't render it outside the template.

Any ideas?

答:
For anyone searching, I solved this with a template filter:

myapp/templatetags/myapp_tags

```<code>@register.filter
def get_pic(value):
    value = Photo.objects.get(pk=value).photo.url
    return value
</code>```

template.html

```<code>{% for event in stream %}
    <div class="front w3-image">
     <img src="{{ event.target_object_id|get_pic }}" class="w3-image" style="height:inherit" >
            </div>
    {% endfor %}
</code>```

Hope it helps someone

Body:
For anyone searching, I solved this with a template filter:

myapp/templatetags/myapp_tags

@register.filter
def get_pic(value):
    value = Photo.objects.get(pk=value).photo.url
    return value

template.html

{% for event in stream %}
    <div class="front w3-image">
     <img src="{{ event.target_object_id|get_pic }}" class="w3-image" style="height:inherit" >
            </div>
    {% endfor %}

Hope it helps someone


问:
error when using wc -c with file names
I am running this code, that sorts files in the desired folders. If a file name has 13 chars it should run the first statement, else the second.

```<code>for i in *.png; do if [ "$($i | wc -c)" -eq 13 ]; then
    echo cp $i $HOME/Desktop/final/pos_${i:0:1}/${i:0:3}.jpg
else
    echo cp $i $HOME/Desktop/final/pos_${i:0:1}/${i:0:4}.jpg
fi;
done
</code>```

the problem is, that [ "$($i | wc -c)" -eq 13 ] is always 0, but clearly, file names have some length. What is the correct way of evaluating wc -c in an if statement?

答:
Use bash string utilities to get the string length. You don't need wc at all. And double-quote all variables in script to avoid word-splitting done by the shell.

```<code>for i in *.png; do
    if ((${#i} == 13)); then
        echo cp "$i" $HOME/Desktop/final/pos_"${i:0:1}"/"${i:0:3}".jpg
    else
        echo cp "$i" $HOME/Desktop/final/pos_"${i:0:1}"/"${i:0:4}".jpg
    fi
done
</code>```

Title: error when using wc -c with file names

Body:
I am running this code, that sorts files in the desired folders. If a file name has 13 chars it should run the first statement, else the second.

for i in *.png; do if [ "$($i | wc -c)" -eq 13 ]; then
    echo cp $i $HOME/Desktop/final/pos_${i:0:1}/${i:0:3}.jpg
else
    echo cp $i $HOME/Desktop/final/pos_${i:0:1}/${i:0:4}.jpg
fi;
done

the problem is, that [ "$($i | wc -c)" -eq 13 ] is always 0, but clearly, file names have some length. What is the correct way of evaluating wc -c in an if statement?

Body:
Use bash string utilities to get the string length. You don't need wc at all. And double-quote all variables in script to avoid word-splitting done by the shell.

for i in *.png; do
    if ((${#i} == 13)); then
        echo cp "$i" $HOME/Desktop/final/pos_"${i:0:1}"/"${i:0:3}".jpg
    else
        echo cp "$i" $HOME/Desktop/final/pos_"${i:0:1}"/"${i:0:4}".jpg
    fi
done


问:
Why I get [Laravel - Undefined variable: users (View..] if I tried to use POST and GET on the same view?
I am trying to make a simple search form using laravel.
the search page is supposed to be the same for results.
but I can't make it work, and i'm not sure why
It works on a different Route but can't get it to work on the same route.

Routes:

```<code>Route::get('searchuser',function(){
return view('searchuser');

 })->middleware('auth');

Route::post('searchuser', function(){
$q = Input::get('name');
$users = App\User::where('name_en','like',$q)->get();

return view('searchuser', ['users' => $users]);

 });
</code>```

Blade:

```<code>                <div class="panel-body">
                    <form class="form-horizontal" role="form" method="POST" action="searchuser">
                    {{ csrf_field() }}

                    <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
                        <label for="name" class="col-md-4 control-label">Name</label>

                        <div class="col-md-6">
                            <input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" placeholder="Search.." required autofocus>

                            @if ($errors->has('name'))
                                <span class="help-block">
                                    <strong>{{ $errors->first('name') }}</strong>
                                </span>
                            @endif
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-md-6 col-md-offset-4">
                            <button type="submit" class="btn btn-primary">
                                Search
                            </button>

                        </div>
                    </div>
                </form>
                <div>
                    @foreach($users as $user)
                        {{$user->name_ar . '<br />'}}
                    @endforeach
                </div>
            </div>
</code>```

答:
You have mismatched the names of your variables. You get the users as $users2 variable in line:

```<code>  $users2 = App\User::where('name_en','like',$q)->get();
</code>```

but then you send variable $users to the view (which does not exist):

```<code>return view('searchuser', ['users' => $users]);
</code>```

Body:
I am trying to make a simple search form using laravel.
the search page is supposed to be the same for results.
but I can't make it work, and i'm not sure why
It works on a different Route but can't get it to work on the same route.

Routes:

Route::get('searchuser',function(){
return view('searchuser');

 })->middleware('auth');

Route::post('searchuser', function(){
$q = Input::get('name');
$users = App\User::where('name_en','like',$q)->get();

return view('searchuser', ['users' => $users]);

 });

Blade:

                    <form class="form-horizontal" role="form" method="POST" action="searchuser">
                    {{ csrf_field() }}

has('name') ? ' has-error' : '' }}">
                        Name

                            <input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" placeholder="Search.." required autofocus>

                            @if ($errors->has('name'))

                                    {{ $errors->first('name') }}

                            @endif

                            <button type="submit" class="btn btn-primary">
                                Search
                            </button>

                </form>

                    @foreach($users as $user)
                        {{$user->name_ar . '
'}}
                    @endforeach

Body:
You have mismatched the names of your variables. You get the users as $users2 variable in line:

  $users2 = App\User::where('name_en','like',$q)->get();

but then you send variable $users to the view (which does not exist):

return view('searchuser', ['users' => $users]);


答:
You have define a $users2 and passed $users to your view

Edit :

i believe your condition should be something like this:

```<code>$users = App\User::where('name_en','like','%' . $q . '%')->get();
</code>```

Title: Why I get [Laravel - Undefined variable: users (View..] if I tried to use POST and GET on the same view?

Body:
You have define a $users2 and passed $users to your view

Edit :

i believe your condition should be something like this:

$users = App\User::where('name_en','like','%' . $q . '%')->get();


问:
is doing (ptr && *ptr) good way to check whether any value assigned to the ptr? mine just keep crashing
Im not really sure that use of ptr&&(*ptr)

At first, I was not sure about is this for checking NULL ptr or existence of assigned value.

But now after running the code below I found that in both way it just doesnt work: runtime error occurred!

Can somebody explain what nasty thing inside is happening?

GCC 5.3.0

```<code>#include <stdio.h>
int main(void){
    int* ptr=NULL;
//    ptr=NULL;
    int res = (ptr && *ptr);

//assigning NULL to *ptr or ptr address results in runtime error. What's happening?
//compiled with gcc.exe (GCC) 5.3.0 on windows

    printf("address: %d \n val: %d \n",ptr,*ptr);
    printf("isNullptr? ptr&& *ptr %d",res);
    return;
}
</code>```

答:
Following line is completely ok, since short-circuiting prevents ptr from being dereferenced if it's equal to NULL.

```<code>int res = (ptr && *ptr);
</code>```

But following code unconditionally dereferences it, leading to a crash.

```<code>int* ptr=NULL;
// ...
printf("address: %p \n val: %d \n",(void *)ptr,*ptr);
//                                             ^~~~
</code>```

Also, please note that a proper way to print a pointer is by using %p instead of %d, and the pointer has to be casted to void *. I've changed your printf() accordingly.

Body:
Im not really sure that use of ptr&&(*ptr)

At first, I was not sure about is this for checking NULL ptr or existence of assigned value.

But now after running the code below I found that in both way it just doesnt work: runtime error occurred!

Can somebody explain what nasty thing inside is happening?

GCC 5.3.0

#include <stdio.h>
int main(void){
    int* ptr=NULL;
//    ptr=NULL;
    int res = (ptr && *ptr);

//assigning NULL to *ptr or ptr address results in runtime error. What's happening?
//compiled with gcc.exe (GCC) 5.3.0 on windows

    printf("address: %d \n val: %d \n",ptr,*ptr);
    printf("isNullptr? ptr&& *ptr %d",res);
    return;
}

Body:
Following line is completely ok, since short-circuiting prevents ptr from being dereferenced if it's equal to NULL.

int res = (ptr && *ptr);

But following code unconditionally dereferences it, leading to a crash.

int* ptr=NULL;
// ...
printf("address: %p \n val: %d \n",(void *)ptr,*ptr);
//                                             ^~~~

Also, please note that a proper way to print a pointer is by using %p instead of %d, and the pointer has to be casted to void *. I've changed your printf() accordingly.


问:
Git: How to maintain two branches of a project and merge only shared data?
Suppose I have two branches of a project IMClient-MacOS and IMClient-Windows, and their code only differs by (let's say) one directory main/.  All the other directories contain system-independent code and are interchangeable.

Some workers work on the Windows version, and some work on the MacOS version.  How do they prevent overwriting changing into the main/ directory when they merge from their counterparts' branch?  Is there a way to merge in Git that will always ignore the OS-dependent directory?

答: You can probably solve your problem with git, but your life will be vastly simpler if you put the system-dependent code in different directories and deal with the cross-platform dependencies in the build system (Makefiles or whatever you use).  Or is there some good reason I've overlooked to have code from different systems share one directory?

OwnerDisplayName: Jake

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Norman Ramsey


问:
Loading A CSS File From Django Template
I have looked through several answers for loading CSS pages. http://docs.djangoproject.com/en/dev/howto/static-files/

Basically, I believe my question should be how do I get staticfiles installed?

I am confused about the settings in settings.py, and I get this error when trying to run collectstatic.

```<code>./manage.py collectstatic
Unknown command: 'collectstatic'
</code>```

In settings.py, I've added

```<code>'django.contrib.staticfiles',
</code>```

to INSTALLED_APS

and

```<code>STATICFILES_DIRS = (
 "/home/amr/django/static_media",
)

STATIC_ROOT = "/home/amr/django/static_media"
</code>```

The error I'm getting is there is no module staticfiles.

答:
It seems like you are running an old version of django, the staticfiles application is included in the latest 1.3-alpha or trunk version. To find out which version of django your project is running on try running the following command on a shell</p>

```<code>$ python -c "import django; print django.get_version()"
</code>```

Title: Loading A CSS File From Django Template

Body:
I have looked through several answers for loading CSS pages. http://docs.djangoproject.com/en/dev/howto/static-files/

Basically, I believe my question should be how do I get staticfiles installed?

I am confused about the settings in settings.py, and I get this error when trying to run collectstatic.

./manage.py collectstatic
Unknown command: 'collectstatic'

In settings.py, I've added

'django.contrib.staticfiles',

to INSTALLED_APS

and

STATICFILES_DIRS = (
 "/home/amr/django/static_media",
)

STATIC_ROOT = "/home/amr/django/static_media"

The error I'm getting is there is no module staticfiles.

Body:
It seems like you are running an old version of django, the staticfiles application is included in the latest 1.3-alpha or trunk version. To find out which version of django your project is running on try running the following command on a shell

$ python -c "import django; print django.get_version()"


答:
What do you think *ptr (in the printf) does? It dereferences a pointer that has been assigned with NULL in the initialization. If you pass a NULL to function expecting non-NULL, your program invokes undefined behavior. The proper way to print addresses is using a %p specifier along with a ptr-to-void:

```<code> if (ptr != NULL)
     printf ("Pointer ptr points to address %p\n", (void *)ptr);
 else
     printf ("ptr is NULL\n");
</code>```

Title: is doing (ptr && *ptr) good way to check whether any value assigned to the ptr? mine just keep crashing

Body:
What do you think *ptr (in the printf) does? It dereferences a pointer that has been assigned with NULL in the initialization. If you pass a NULL to function expecting non-NULL, your program invokes undefined behavior. The proper way to print addresses is using a %p specifier along with a ptr-to-void:

 if (ptr != NULL)
     printf ("Pointer ptr points to address %p\n", (void *)ptr);
 else
     printf ("ptr is NULL\n");


问:
Function is not defined with module.exports on nodejs
I get the error: "login is not defined" on my node.js app, when I try to get the function login in my server.js from a module module1.js which needs data:

```<code>//module1.js
module.exports = (data) => {
   var login = function(data){
      console.log(data)
   }
   exports.login = login;
};

//server.js
var test = require(__dirname + '/app/modules/module1.js')(data);
test.login();
</code>```

答:
When node starts executing module code, both module.exports and exports point to the same object. When you re-assign module.exports, you're specifying another object that will be returned from a module. In you case it's a function (data)=>{...}. The exports variable keeps pointing to the old module object.

You need the following:

```<code>module.exports = (data) => {
   var login = function(){
      console.log(data)
   }
   return {login: login};
};
</code>```

Or this way shorter:

```<code>module.exports = (data) => {
   return {login: function(){
      console.log(data)
   }};
};
</code>```

Or, if you want to export both functions, you need to add them to exports object.

Body:
I get the error: "login is not defined" on my node.js app, when I try to get the function login in my server.js from a module module1.js which needs data:

//module1.js
module.exports = (data) => {
   var login = function(data){
      console.log(data)
   }
   exports.login = login;
};

//server.js
var test = require(__dirname + '/app/modules/module1.js')(data);
test.login();

Body:
When node starts executing module code, both module.exports and exports point to the same object. When you re-assign module.exports, you're specifying another object that will be returned from a module. In you case it's a function (data)=>{...}. The exports variable keeps pointing to the old module object.

You need the following:

module.exports = (data) => {
   var login = function(){
      console.log(data)
   }
   return {login: login};
};

Or this way shorter:

module.exports = (data) => {
   return {login: function(){
      console.log(data)
   }};
};

Or, if you want to export both functions, you need to add them to exports object.


问:
How can I write if/else with Boolean in Bash?
How can I write an 'if then' statement to switch between these to variables as in the following?

```<code>if(switch){
  server_var_shortname=$server_shared_shortname
  server_var=$server_shared
  server_var_bare=$server_shared_bare
} else {
  server_var_shortname=$server_vps_shortname
  server_var=$server_vps
  server_var_bare=$server_vps_bare
}
</code>```

I'm not familiar with Bash syntax and basically just need an 'if/else' statement on a Boolean. Also, can I use true / false values as such? Also how do I do the 'else' statement?

```<code>$switch=true;
if $switch
then
  server_var_shortname=$server_shared_shortname
  server_var=$server_shared
  server_var_bare=$server_shared_bare
fi
</code>```

答:
Here is a good guide for If else. But I want to show a different approach (which you will find also in the link on page 3).

Your coding looks like JavaScript, so I think with Switch you could also mean the case command instead of if. Switch in JavaScript is similar to case within a shell, but there isn't any method to check for Booleans. You can check string values for like true and false, and you can check for numbers.

Example...

```<code>#!/bin/bash
case "$Variable" in
false|0|"")
    echo "Boolean is set to false."
;;
*)
    echo "Boolean is set to true."
;;
esac
</code>```

Addition

Keep in mind, there are many programs and tools that uses Boolean values in different forms.

Two examples...

SQL in general uses numbers as Boolean.

JavaScript uses true and false values.

Meaning: Your Bash script has to know the format of Booleans, before processing them!

ContentLicense: CC BY-SA 4.0

Body:
How can I write an 'if then' statement to switch between these to variables as in the following?

if(switch){
  server_var_shortname=$server_shared_shortname
  server_var=$server_shared
  server_var_bare=$server_shared_bare
} else {
  server_var_shortname=$server_vps_shortname
  server_var=$server_vps
  server_var_bare=$server_vps_bare
}

I'm not familiar with Bash syntax and basically just need an 'if/else' statement on a Boolean. Also, can I use true / false values as such? Also how do I do the 'else' statement?

$switch=true;
if $switch
then
  server_var_shortname=$server_shared_shortname
  server_var=$server_shared
  server_var_bare=$server_shared_bare
fi

Body:
Here is a good guide for If else. But I want to show a different approach (which you will find also in the link on page 3).

Your coding looks like JavaScript, so I think with Switch you could also mean the case command instead of if. Switch in JavaScript is similar to case within a shell, but there isn't any method to check for Booleans. You can check string values for like true and false, and you can check for numbers.

Example...

#!/bin/bash
case "$Variable" in
false|0|"")
    echo "Boolean is set to false."
;;
*)
    echo "Boolean is set to true."
;;
esac

Addition

Keep in mind, there are many programs and tools that uses Boolean values in different forms.

Two examples...

SQL in general uses numbers as Boolean.

JavaScript uses true and false values.

Meaning: Your Bash script has to know the format of Booleans, before processing them!


问:
Inserting text with SendMessage
When I try to paste text in textbox another program, the text is inserted, but the program does not recognize it.

 [DllImport("user32.dll", CharSet = CharSet.Auto)]
 static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
 const uint WM_SETTEXT = 0x000C;

 IntPtr text = Marshal.StringToCoTaskMemUni("100");
 IntPtr thisWindow = FindWindow(null, "AnotherWindow");
 IntPtr handle = FindWindowEx(thisWindow, IntPtr.Zero, "AnotherTextBox", null);
 SendMessage(handle, WM_SETTEXT, IntPtr.Zero, text);
 Marshal.FreeCoTaskMem(text);
```

<p>Maybe I should send to the parent a message that the textbox is updated?
Like this:
</p>

``` //Wrong code, because I do not know how correctly send a message
 SendMessage(handle, WM_COMMAND, EM_SETMODIFY, handle);
```

答:
some Textboxes have been set so that you can not set your text by WM_SETTEXT immediately, especially those which accept digits and perform calculation according these digits. I had similar problem and solved it by bellow code. I applied WM_PASTE, EM_REPLACESEL to conquer that.

```<code>SendMessage(child, WM_SETFOCUS,0 , IntPtr.Zero);  // go to text box
System.Windows.Forms.Clipboard.SetText("1");   // set something in clipboard. it does not matter what it is.
SendMessage(child, WM_PASTE, 0, IntPtr.Zero); // paste to get control of text box
SendMessage(child, WM_SETTEXT, IntPtr.Zero, string.Empty);  // clear textbox to insert your desired text.
SendMessage(child, EM_REPLACESEL, IntPtr.Zero, "your text"); // insert your desired text. i inserted digits as text.
</code>```

you need to Import user32.dll file at first:

```<code>[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
    private static extern int SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, string lParam);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
    private static extern int SendMessage(IntPtr hWnd, uint msg,int  wParam, IntPtr lParam);
</code>```

Title: Inserting text with SendMessage

Body:
When I try to paste text in textbox another program, the text is inserted, but the program does not recognize it.

 [DllImport("user32.dll", CharSet = CharSet.Auto)]
 static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
 const uint WM_SETTEXT = 0x000C;

 IntPtr text = Marshal.StringToCoTaskMemUni("100");
 IntPtr thisWindow = FindWindow(null, "AnotherWindow");
 IntPtr handle = FindWindowEx(thisWindow, IntPtr.Zero, "AnotherTextBox", null);
 SendMessage(handle, WM_SETTEXT, IntPtr.Zero, text);
 Marshal.FreeCoTaskMem(text);

Maybe I should send to the parent a message that the textbox is updated?
Like this:

 //Wrong code, because I do not know how correctly send a message
 SendMessage(handle, WM_COMMAND, EM_SETMODIFY, handle);

Body:
some Textboxes have been set so that you can not set your text by WM_SETTEXT immediately, especially those which accept digits and perform calculation according these digits. I had similar problem and solved it by bellow code. I applied WM_PASTE, EM_REPLACESEL to conquer that.

SendMessage(child, WM_SETFOCUS,0 , IntPtr.Zero);  // go to text box
System.Windows.Forms.Clipboard.SetText("1");   // set something in clipboard. it does not matter what it is.
SendMessage(child, WM_PASTE, 0, IntPtr.Zero); // paste to get control of text box
SendMessage(child, WM_SETTEXT, IntPtr.Zero, string.Empty);  // clear textbox to insert your desired text.
SendMessage(child, EM_REPLACESEL, IntPtr.Zero, "your text"); // insert your desired text. i inserted digits as text.

you need to Import user32.dll file at first:

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
    private static extern int SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, string lParam);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
    private static extern int SendMessage(IntPtr hWnd, uint msg,int  wParam, IntPtr lParam);


答:
Technically, you have undefined behaviour. It is a very bad thing.

(remember that a programming language is a specification written in some report - not a software. For C11, read n1570)

In practice, you get a segmentation fault. You are dereferencing -in your first call to printf- a (null) pointer which is always outside of your virtual address space.

You should compile with all warnings & debug info e.g. with gcc -Wall -g if using GCC. Then use a debugger (gdb) and a memory leak detector like valgrind...

You need to read a lot more. Read carefully several books on programming (perhaps start with SICP), and several books on C programming. You might also want to read about operating systems.


问:
Anything wrong with this design to initialize the array in the DLL?
Lets assume we've got a DLL and there should be an array stored globally in it that's going to be exported, the thing is we want to initialize it by reading some content from a file, so personally I find myself no other way than putting it in a struct to be able to initialize using constructor:

```<code>struct Construction{
 public:
  Construction(){
   //do the initialization thing and read the needed data from the file
  }
  SomeType sTArray[100];
};

__declspec(dllexport) Construction obj();
</code>```

Now where it's going to be used, the programmer can initialize a reference to it and then use the reference like below:

```<code>SomeType (&arrayRef)[100]=obj.sTArray;
</code>```

Now would you think I'm wrong in any context?

答:
Yes, you've set yourself up for a very nasty surprise at some point.

Global object constructors run during the startup of the C runtime for the DLL.

The C runtime startup code runs during DLLMain.

During DLLMain, you are holding the DLL loader lock.

Your object constructor may involve calls to Win32 api's that load other system DLL's.

Tring to load another DLL while already holding the DLL loader lock results in a swift death for your process.

I'd recommend that you hold off on initializing the array until the first attempt to access it, which will require that you expose the array indirectly as the result of a function call:

```<code>struct Construction{
public:
  Construction() : bInit(false) {};
  SomeType* GetArray()
  {
    if(!bInit)
    {
      //do the initialization thing and read the needed data from the file
      bInit = true;
    }
    return sTArray;
  };
private:
  SomeType sTArray[100];
  bool bInit;
};

__declspec(dllexport) Construction obj();
</code>```

Of course, this would need to be split into separate header and implementation files.

Body:
Lets assume we've got a DLL and there should be an array stored globally in it that's going to be exported, the thing is we want to initialize it by reading some content from a file, so personally I find myself no other way than putting it in a struct to be able to initialize using constructor:

struct Construction{
 public:
  Construction(){
   //do the initialization thing and read the needed data from the file
  }
  SomeType sTArray[100];
};

__declspec(dllexport) Construction obj();

Now where it's going to be used, the programmer can initialize a reference to it and then use the reference like below:

SomeType (&arrayRef)[100]=obj.sTArray;

Now would you think I'm wrong in any context?

Body:
Yes, you've set yourself up for a very nasty surprise at some point.

Global object constructors run during the startup of the C runtime for the DLL.

The C runtime startup code runs during DLLMain.

During DLLMain, you are holding the DLL loader lock.

Your object constructor may involve calls to Win32 api's that load other system DLL's.

Tring to load another DLL while already holding the DLL loader lock results in a swift death for your process.

I'd recommend that you hold off on initializing the array until the first attempt to access it, which will require that you expose the array indirectly as the result of a function call:

struct Construction{
public:
  Construction() : bInit(false) {};
  SomeType* GetArray()
  {
    if(!bInit)
    {
      //do the initialization thing and read the needed data from the file
      bInit = true;
    }
    return sTArray;
  };
private:
  SomeType sTArray[100];
  bool bInit;
};

__declspec(dllexport) Construction obj();

Of course, this would need to be split into separate header and implementation files.


答:
```<code>printf("address: %d \n val: %d \n",ptr,*ptr);
</code>```

You have trying to de-referencing a NULL pointer. It's undefined behaviour.

From n1256 - §6.5.3.3 :

Among the invalid values for dereferencing a pointer by the unary *
  operator are a null pointer, an address inappropriately aligned for
  the type of object pointed to, and the address of an object after the
  end of its lifetime.

Body:
printf("address: %d \n val: %d \n",ptr,*ptr);

You have trying to de-referencing a NULL pointer. It's undefined behaviour.

From n1256 - §6.5.3.3 :

Among the invalid values for dereferencing a pointer by the unary *
  operator are a null pointer, an address inappropriately aligned for
  the type of object pointed to, and the address of an object after the
  end of its lifetime.


问:
Laravel: onchange on Form::text
First Laravel Project.
I want to run a script whenever I change the input in my Form::text. So far my code looks like this:

The view:

```<code>@extends('layouts.master')
@section('title', 'Onchange test')
@section('main')
@parent
<script>
function showProduct(str) {
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                var jsonObject = JSON.parse(this.responseText);                document.getElementById("nameHint").innerHTML = jsonObject['name'];
}
        };
        xmlhttp.open("GET","script/getproduct.php?q="+str,true);
        xmlhttp.send();
    }
}
</script>
{{ Form::open(array('url' => '/test'))}}
<table>
<tr>
<td>{{Form::text('barcode', null,['onchange'=>"showProduct(this.value)"])}}</td>
<td>
<td><div id="nameHint">Test</div></td>
</tr>
</table>
@endsection
</code>```

The php

```<code><?php
$q = intval($_GET['q']);

$sql = DB::select('select * from inventory where barcode = ? LIMIT 1', [$q]);
$name = $sql[0]->name;

$test = $name;
echo json_encode(array("name"=> $name));
?>
</code>```

But it's not refreshing (it shows only the deffault "Test") What did I wrong?

答:
Try this

```<code>{!! Form::text('barcode', null,['onchange'=>"showProduct(this.value);"]) !!}
</code>```

Also start form as below

```<code>{!! Form::open(['url' => 'foo/bar']) !!}
//
{!! Form::close() !!}
</code>```

For more follow https://laravelcollective.com/docs/5.3/html

Title: Laravel: onchange on Form::text

Body:
First Laravel Project.
I want to run a script whenever I change the input in my Form::text. So far my code looks like this:

The view:

@extends('layouts.master')
@section('title', 'Onchange test')
@section('main')
@parent

{{ Form::open(array('url' => '/test'))}}

{{Form::text('barcode', null,['onchange'=>"showProduct(this.value)"])}}

Test

@endsection

The php

<?php
$q = intval($_GET['q']);

$sql = DB::select('select * from inventory where barcode = ? LIMIT 1', [$q]);
$name = $sql[0]->name;

$test = $name;
echo json_encode(array("name"=> $name));
?>

But it's not refreshing (it shows only the deffault "Test") What did I wrong?

Body:
Try this

{!! Form::text('barcode', null,['onchange'=>"showProduct(this.value);"]) !!}

Also start form as below

{!! Form::open(['url' => 'foo/bar']) !!}
//
{!! Form::close() !!}

For more follow https://laravelcollective.com/docs/5.3/html


问:
Calculate viewport coordinates given northeast and southwest
I'm using google maps to retrieve the northeast(top-right) and southwest(bottom-left) coordinates of the viewport. How can I calculate the northwest(top-left) and southeast(bottom-right) coordinates?</p>

答:
You just need to combine the relevant parts, so getting the north from northeast and the west from southwest, would yield northwest. Same for southeast.

You mention in the comment that they are actually reversed, that the west is the new east etc. That is more likely a confusion from the fact that the LatLngBounds objects contains SW/NE and not NE/SW.


问:
MAC osx, change datadir mysql, still not working
Hi i am tearing my hair out at this one, i am a noob ill admit when it comes to mysql, i had ir working perfectly on my local Mac HD, i now want to store the databse to my external as the databse could be 100gb,

Mac osx does not seem to have my.cnf as default in /etc location, so i grabed one "my-huge.cnf" ranmed it and stored it in this folder, i now added the datadir = my/new/location
under the field [mysqld] which also contains information such as port and socket,

I also ran cp -R -p /etc/mysql/data /Volumes/Elements/database
to copy my old databse values to the new one, i then changed
datadir = /Volumes/Elements/database

now my database wont work,
i tried to restart mysqld, im getting

```<code>101130 15:13:11 [Warning] '--skip-locking' is deprecated and will be removed in a future release. Please use '--skip-external-locking' instead.
101130 15:13:11 [Warning] Setting lower_case_table_names=2 because file system for /Volumes/Elements/database/ is case insensitive
101130 15:13:11 [Note] Plugin 'FEDERATED' is disabled.
mysqld: Table 'mysql.plugin' doesn't exist
101130 15:13:11 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
101130 15:13:11  InnoDB: Started; log sequence number 0 44233
mysqld: Too many arguments (first extra is 'restart').
Use --verbose --help to get a list of available options
101130 15:13:11 [ERROR] Aborting

101130 15:13:11  InnoDB: Starting shutdown...
101130 15:13:17  InnoDB: Shutdown completed; log sequence number 0 44233
101130 15:13:17 [Note] mysqld: Shutdown complete
</code>```

When i try and access the database "through my java program in eclipse"
i now get
"the last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server."

Im officially at a complete loss

Also i think the issue might be with the socket, as when i type mysql in the terminal i get

```<code>Can't connect to local MySQL server through socket '/tmp/mysql.sock
</code>```

答:
A very simple solution would be to symlink your old MySQL data directory to the new location.

ln -s /Volumes/Elements/database /etc/mysql/data

Body:
Hi i am tearing my hair out at this one, i am a noob ill admit when it comes to mysql, i had ir working perfectly on my local Mac HD, i now want to store the databse to my external as the databse could be 100gb,

Mac osx does not seem to have my.cnf as default in /etc location, so i grabed one "my-huge.cnf" ranmed it and stored it in this folder, i now added the datadir = my/new/location
under the field [mysqld] which also contains information such as port and socket,

I also ran cp -R -p /etc/mysql/data /Volumes/Elements/database
to copy my old databse values to the new one, i then changed
datadir = /Volumes/Elements/database

now my database wont work,
i tried to restart mysqld, im getting

101130 15:13:11 [Warning] '--skip-locking' is deprecated and will be removed in a future release. Please use '--skip-external-locking' instead.
101130 15:13:11 [Warning] Setting lower_case_table_names=2 because file system for /Volumes/Elements/database/ is case insensitive
101130 15:13:11 [Note] Plugin 'FEDERATED' is disabled.
mysqld: Table 'mysql.plugin' doesn't exist
101130 15:13:11 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
101130 15:13:11  InnoDB: Started; log sequence number 0 44233
mysqld: Too many arguments (first extra is 'restart').
Use --verbose --help to get a list of available options
101130 15:13:11 [ERROR] Aborting

101130 15:13:11  InnoDB: Starting shutdown...
101130 15:13:17  InnoDB: Shutdown completed; log sequence number 0 44233
101130 15:13:17 [Note] mysqld: Shutdown complete

When i try and access the database "through my java program in eclipse"
i now get
"the last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server."

Im officially at a complete loss

Also i think the issue might be with the socket, as when i type mysql in the terminal i get

Can't connect to local MySQL server through socket '/tmp/mysql.sock


问:
How to add a spinner in ionic application?
I have made a plunker in which I'm fetching data from a json api but when I try to add loading feature inside my js code the app stops working can someone help?</p>

```<code>var app = angular.module('newsapp', ['ionic']);

app.controller('newscontroller',function($scope, $http){
    $scope.show = function() {
        $ionicLoading.show({
            template: 'Loading...'
        }).then(function(){
            console.log("The loading indicator is now displayed");
        });
    };
    $scope.hide = function(){
        $ionicLoading.hide().then(function(){
            console.log("The loading indicator is now hidden");
        });
    };

    $scope.news =[];
    $scope.show();

    $http({
        method: "GET",
        url: "https://newsapi.org/v1/articles?source=techcrunch&sortBy=latest&apiKey=90b77760d33d4c76af4c6c53862c9e72"
    }).then(function(newsdata){
        angular.forEach(newsdata.data.articles, function(newsarticle) {
            $scope.news.push(newsarticle);
        });
        $scope.lastarticleID = newsdata.data.lastID;
        $scope.hide();
        console.log(newsdata);
    })
});
</code>```

答:
You missed to parse the $ionicLoading reference into your controller. Take a look at this running plnkr.

```<code>var app = angular.module('newsapp', ['ionic']);

app.controller('newscontroller', function ($scope, $http, $ionicLoading, $timeout) {

    $scope.show = function () {
        $ionicLoading.show({
            template: '<img width="32" height="32" src="data:image/gif;base64,[encoded data, 8452 characters]">'
        }).then(function () {
            console.log("The loading indicator is now displayed");
        });
    };
    $scope.hide = function () {
        $ionicLoading.hide().then(function () {
            console.log("The loading indicator is now hidden");
        });
    };

    $scope.news = [];
    $scope.show();

    $timeout(function () {
        $http({
            method: "GET",
            url: "https://newsapi.org/v1/articles?source=techcrunch&sortBy=latest&apiKey=90b77760d33d4c76af4c6c53862c9e72"
        }).then(function (newsdata) {
            angular.forEach(newsdata.data.articles, function (newsarticle) {
                $scope.news.push(newsarticle);
            });
            $scope.lastarticleID = newsdata.data.lastID;
            $scope.hide();
        })
    }, 2500);
});
</code>```

Body:
I have made a plunker in which I'm fetching data from a json api but when I try to add loading feature inside my js code the app stops working can someone help?

var app = angular.module('newsapp', ['ionic']);

app.controller('newscontroller',function($scope, $http){
    $scope.show = function() {
        $ionicLoading.show({
            template: 'Loading...'
        }).then(function(){
            console.log("The loading indicator is now displayed");
        });
    };
    $scope.hide = function(){
        $ionicLoading.hide().then(function(){
            console.log("The loading indicator is now hidden");
        });
    };

    $scope.news =[];
    $scope.show();

    $http({
        method: "GET",
        url: "https://newsapi.org/v1/articles?source=techcrunch&sortBy=latest&apiKey=90b77760d33d4c76af4c6c53862c9e72"
    }).then(function(newsdata){
        angular.forEach(newsdata.data.articles, function(newsarticle) {
            $scope.news.push(newsarticle);
        });
        $scope.lastarticleID = newsdata.data.lastID;
        $scope.hide();
        console.log(newsdata);
    })
});

Body:
You missed to parse the $ionicLoading reference into your controller. Take a look at this running plnkr.

var app = angular.module('newsapp', ['ionic']);

app.controller('newscontroller', function ($scope, $http, $ionicLoading, $timeout) {

    $scope.show = function () {
        $ionicLoading.show({
            template: '<img width="32" height="32" src="data:image/gif;base64,[encoded data, 8452 characters]">'
        }).then(function () {
            console.log("The loading indicator is now displayed");
        });
    };
    $scope.hide = function () {
        $ionicLoading.hide().then(function () {
            console.log("The loading indicator is now hidden");
        });
    };

    $scope.news = [];
    $scope.show();

    $timeout(function () {
        $http({
            method: "GET",
            url: "https://newsapi.org/v1/articles?source=techcrunch&sortBy=latest&apiKey=90b77760d33d4c76af4c6c53862c9e72"
        }).then(function (newsdata) {
            angular.forEach(newsdata.data.articles, function (newsarticle) {
                $scope.news.push(newsarticle);
            });
            $scope.lastarticleID = newsdata.data.lastID;
            $scope.hide();
        })
    }, 2500);
});


问:
PHP Code not working inside javascript
```<code><?php
echo "Value: " .$_GET['val']. "<script>document.write('<?php echo 'It does not work!'; ?>'); </script>";?>
</code>```

above code inside javascript is not giving output while the below code is working well, what am i missing withing the above code?

```<code><script>document.write('<?php echo 'It works!'; ?>'); </script>
</code>```

答:
You dont need to open 'php' twice..

or 'echo' twice..

So that just leaves having matching sets of quotes in the correct sequence.

```<code>echo "Value: " .$_GET['val']. "<script>document.write('It does work!'); </script>";
     ^.......^                ^--------------------------------------------------^
                                                      ^-------------^
</code>```

Title: PHP Code not working inside javascript

Body:
<?php
echo "Value: " .$_GET['val']. "";?>

above code inside javascript is not giving output while the below code is working well, what am i missing withing the above code?

Body:
You dont need to open 'php' twice..

or 'echo' twice..

So that just leaves having matching sets of quotes in the correct sequence.

echo "Value: " .$_GET['val']. "<script>document.write('It does work!'); </script>";
     ^.......^                ^--------------------------------------------------^
                                                      ^-------------^


问:
Error when updating DB: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified
I'm using EF6 and have been making a few changes to my model.
Now all the sudden I get the following error when trying to update my database through the nuget command Update-Database:

A network-related or instance-specific error occurred while
  establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: SQL
  Network Interfaces, error: 26 - Error Locating Server/Instance
  Specified)

I did not change anything in my connection settings (or web.config in general) but here's my connection string:

```<code>  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\LM.DataAccess.mdf;Initial Catalog=LM.DataAccess;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>
</code>```

In Server Explorer -> Data Connections I can access the database without any problems.

What could be the issue here? I tried deleting the database through the SQL Server Object Explorer but I still get the error.

Still need help people.
Would really appreciate if someone could help me out - I've tried everything I could!

答:
Follow step by step:
1./ Create right connect to database in web.config
1./ Right click -> select "Set as default project"
2./ run update-database againt

That's fix.

Body:
I'm using EF6 and have been making a few changes to my model.
Now all the sudden I get the following error when trying to update my database through the nuget command Update-Database:

A network-related or instance-specific error occurred while
  establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: SQL
  Network Interfaces, error: 26 - Error Locating Server/Instance
  Specified)

I did not change anything in my connection settings (or web.config in general) but here's my connection string:

  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\LM.DataAccess.mdf;Initial Catalog=LM.DataAccess;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>

In Server Explorer -> Data Connections I can access the database without any problems.

What could be the issue here? I tried deleting the database through the SQL Server Object Explorer but I still get the error.

Still need help people.
Would really appreciate if someone could help me out - I've tried everything I could!


问:
CSS padding-bottom does not seem to work
I need to put space between the fixed footer and the bottom of the page. I've tried setting a padding for #main-content, but it's not working. Is there a problem here that I failed to see?

CSS

```<code>#main-content {
    position: relative;
    width: 100%;
    padding-left:20px;
    padding-right:20px;
    height: 300px;

    box-sizing:border-box;
    padding-top: 50px;
    padding-bottom: 200px;
}

footer {
    background-color: #00496b;
    width: 100%;
    bottom: 0;
    position: fixed;
}
</code>```

Instead of getting the desired result, the main contents disappear behind the footer, instead. I want the #main-content to go a little further up. Hope I have explained the problem enough.

答:
In this CSS code:

```<code>#main-content {
    position: relative;
    width: 100%;
    padding-left:20px;
    padding-right:20px;
    height: 300px;
    box-sizing:border-box;
    padding-top: 50px;
    padding-bottom: 200px;
}
</code>```

you have set a fixed height for #main-content due to which the padding-bottom is not effective. Remove height: 300px; property or just replace 300px with auto.

The CSS code should look like this:

```<code>#main-content {
    position: relative;
    width: 100%;
    padding-left:20px;
    padding-right:20px;
    height: auto;  //height is set to auto
    box-sizing:border-box;
    padding-top: 50px;
    padding-bottom: 200px;
}
</code>```

Now, the padding-bottom property should work. Let me know it this helps :)

Body:
I need to put space between the fixed footer and the bottom of the page. I've tried setting a padding for #main-content, but it's not working. Is there a problem here that I failed to see?

CSS

#main-content {
    position: relative;
    width: 100%;
    padding-left:20px;
    padding-right:20px;
    height: 300px;

    box-sizing:border-box;
    padding-top: 50px;
    padding-bottom: 200px;
}

footer {
    background-color: #00496b;
    width: 100%;
    bottom: 0;
    position: fixed;
}

Instead of getting the desired result, the main contents disappear behind the footer, instead. I want the #main-content to go a little further up. Hope I have explained the problem enough.

Body:
In this CSS code:

#main-content {
    position: relative;
    width: 100%;
    padding-left:20px;
    padding-right:20px;
    height: 300px;
    box-sizing:border-box;
    padding-top: 50px;
    padding-bottom: 200px;
}

you have set a fixed height for #main-content due to which the padding-bottom is not effective. Remove height: 300px; property or just replace 300px with auto.

The CSS code should look like this:

#main-content {
    position: relative;
    width: 100%;
    padding-left:20px;
    padding-right:20px;
    height: auto;  //height is set to auto
    box-sizing:border-box;
    padding-top: 50px;
    padding-bottom: 200px;
}

Now, the padding-bottom property should work. Let me know it this helps :)


问:
JavaScript canvas code not working
Here is my JS canvas code for a rectangular ship. If I comment out the switch statement, the ship is visible. On uncommenting the switch statement, the ship doesn't show. What's wrong?    </p>

```<code> var ship = function() {
     this.velocityX = 0;
     this.velocityY = 0;
     this.accelerationX = 0;
     this.accelerationY = 0;
     this.x = width / 2;
     this.y = height / 2;
     this.speed = 4;
     this.angle = 0;

     this.control = function() {
         context.save();
         context.translate(this.x, this.y);

         this.addEventListener("keydown", function(event) {
             switch (event.keyCode) {
                 case 36:
                     this.accelerationX = Math.cos(this.angle) * this.speed;
                     this.accelerationY = Math.sin(this.angle) * this.speed;
                     break;
                 case 38:
                     this.accelerationX = -Math.cos(this.angle) * this.speed;
                     this.accelerationY = -Math.sin(this.angle) * this.speed;
                     break;
                 case 37:
                     this.angle -= 0.5;
                     break;
                 case 40:
                     this.angle += 0.5;
                     break;
             }
         });

         context.rotate(this.angle);
         context.fillStyle = "rgb(255,255,255)";
         context.fillRect(0, 0, 20, 30);
         context.restore();
     };
 };
</code>```

答:
I made that code using yours to test your ideas. That script works solo without any addidtions but still needs improvements. Maybe some of my corrections will be useful for you:</p>

```<code><html>
<head>

</head>
<body>
  <canvas id="canvas" style="border: 1px solid black;"></canvas>
<script>
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var resistance = 0.8;
canvas.width = 400;
canvas.height = 400;

 var ship = function() {
     this.velocityX = 0;
     this.velocityY = 0;
     this.accelerationX = 0;
     this.accelerationY = 0;
     this.x = canvas.width / 2;
     this.y = canvas.height / 2;
     this.speed = 0.5;
     this.angle = 0;

     this.control = function() {
           context.clearRect(0,0,canvas.width,canvas.height);
        this.velocityX += this.accelerationX;
        this.velocityY += this.accelerationY;
      //  context.beginPath();
        context.save();
        context.translate(this.x, this.y);
        this.velocityX *= resistance;
        this.velocityY *= resistance;
        this.x += this.velocityX;
         this.y += this.velocityY;
         context.rotate(this.angle);
        // context.fillStyle = "rgb(255,255,255)";

         context.fillRect(0, 0, 30, 20);
         context.restore();
         this.accelerationX = 0;
         this.accelerationY = 0;
     };
 };

  var s = new ship();
  var keyMap = [];
    setInterval(function(){s.control();}, 1);
     setInterval(function(){move();}, 1);

document.onkeydown = keydown;
document.onkeyup = keyup;

function move()
{
    if(keyMap[38])
  {
                     s.accelerationX = Math.cos(s.angle) * s.speed;
                    s.accelerationY = Math.sin(s.angle) * s.speed;
  }
    if(keyMap[40])
  {

                     s.accelerationX = -Math.cos(s.angle) * s.speed;
                     s.accelerationY = -Math.sin(s.angle) * s.speed;
  }
     if(keyMap[37])
  {
                     s.angle -= 0.05;
  }
     if(keyMap[39])
  {
                    s.angle += 0.05;
  }
}

function keydown(e)
{
    keyMap[e.keyCode] = true;
}

function keyup(e)
{
    keyMap[e.keyCode] = false;
}

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

Title: JavaScript canvas code not working

Body:
Here is my JS canvas code for a rectangular ship. If I comment out the switch statement, the ship is visible. On uncommenting the switch statement, the ship doesn't show. What's wrong?

 var ship = function() {
     this.velocityX = 0;
     this.velocityY = 0;
     this.accelerationX = 0;
     this.accelerationY = 0;
     this.x = width / 2;
     this.y = height / 2;
     this.speed = 4;
     this.angle = 0;

     this.control = function() {
         context.save();
         context.translate(this.x, this.y);

         this.addEventListener("keydown", function(event) {
             switch (event.keyCode) {
                 case 36:
                     this.accelerationX = Math.cos(this.angle) * this.speed;
                     this.accelerationY = Math.sin(this.angle) * this.speed;
                     break;
                 case 38:
                     this.accelerationX = -Math.cos(this.angle) * this.speed;
                     this.accelerationY = -Math.sin(this.angle) * this.speed;
                     break;
                 case 37:
                     this.angle -= 0.5;
                     break;
                 case 40:
                     this.angle += 0.5;
                     break;
             }
         });

         context.rotate(this.angle);
         context.fillStyle = "rgb(255,255,255)";
         context.fillRect(0, 0, 20, 30);
         context.restore();
     };
 };

Body:
I made that code using yours to test your ideas. That script works solo without any addidtions but still needs improvements. Maybe some of my corrections will be useful for you:

<html>
<head>

</head>
<body>
  <canvas id="canvas" style="border: 1px solid black;"></canvas>
<script>
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var resistance = 0.8;
canvas.width = 400;
canvas.height = 400;

 var ship = function() {
     this.velocityX = 0;
     this.velocityY = 0;
     this.accelerationX = 0;
     this.accelerationY = 0;
     this.x = canvas.width / 2;
     this.y = canvas.height / 2;
     this.speed = 0.5;
     this.angle = 0;

     this.control = function() {
           context.clearRect(0,0,canvas.width,canvas.height);
        this.velocityX += this.accelerationX;
        this.velocityY += this.accelerationY;
      //  context.beginPath();
        context.save();
        context.translate(this.x, this.y);
        this.velocityX *= resistance;
        this.velocityY *= resistance;
        this.x += this.velocityX;
         this.y += this.velocityY;
         context.rotate(this.angle);
        // context.fillStyle = "rgb(255,255,255)";

         context.fillRect(0, 0, 30, 20);
         context.restore();
         this.accelerationX = 0;
         this.accelerationY = 0;
     };
 };

  var s = new ship();
  var keyMap = [];
    setInterval(function(){s.control();}, 1);
     setInterval(function(){move();}, 1);

document.onkeydown = keydown;
document.onkeyup = keyup;

function move()
{
    if(keyMap[38])
  {
                     s.accelerationX = Math.cos(s.angle) * s.speed;
                    s.accelerationY = Math.sin(s.angle) * s.speed;
  }
    if(keyMap[40])
  {

                     s.accelerationX = -Math.cos(s.angle) * s.speed;
                     s.accelerationY = -Math.sin(s.angle) * s.speed;
  }
     if(keyMap[37])
  {
                     s.angle -= 0.05;
  }
     if(keyMap[39])
  {
                    s.angle += 0.05;
  }
}

function keydown(e)
{
    keyMap[e.keyCode] = true;
}

function keyup(e)
{
    keyMap[e.keyCode] = false;
}

</script>
</body>
</html>


问:
Facebook Audience Network returns "unknown error" when loading an ad
I'm trying to integrate Facebook native ads in my Android app. Whenever I load an ad with my placement id I get an error code of -1: unknown error inside the onError method.

When I try other placement ids it works fine. Does anyone has any clue what could cause an unknown error?

Here is my code:

```<code>AbstractAdListener adListener = new AbstractAdListener() {
        @Override
        public void onError(Ad ad, AdError adError) {
            Log.d("MyApp", "Failed to load ad from Facebook Audience Network: " + adError.getErrorMessage());
        }

        @Override
        public void onAdLoaded(Ad ad) {
            // Show Ad
        }
}

NativeAd nativeAd = new NativeAd(context, adUnitId);
native.setAdListener(adListener);
native.loadAd();
</code>```

答:
This issue because of Facebook SDK version changes. Make sure that you have used latest SDK version without minor version code.

I have replace old gradle with this one and it's worked for me

```<code>compile 'com.facebook.android:audience-network-sdk:4.+'
</code>```

Body:
I'm trying to integrate Facebook native ads in my Android app. Whenever I load an ad with my placement id I get an error code of -1: unknown error inside the onError method.

When I try other placement ids it works fine. Does anyone has any clue what could cause an unknown error?

Here is my code:

AbstractAdListener adListener = new AbstractAdListener() {
        @Override
        public void onError(Ad ad, AdError adError) {
            Log.d("MyApp", "Failed to load ad from Facebook Audience Network: " + adError.getErrorMessage());
        }

        @Override
        public void onAdLoaded(Ad ad) {
            // Show Ad
        }
}

NativeAd nativeAd = new NativeAd(context, adUnitId);
native.setAdListener(adListener);
native.loadAd();

Body:
This issue because of Facebook SDK version changes. Make sure that you have used latest SDK version without minor version code.

I have replace old gradle with this one and it's worked for me

compile 'com.facebook.android:audience-network-sdk:4.+'


问:
Customizing a TextBox to look like a textblock in UWP
I am new to XAML and Blend but here Is what I am trying to do. I am developing an application where I need to place a TextBox (or any input control ) but is shouldn't have the properties of a TextBox. Please refer the image below.

I want help to implement the below mentioned functionalities.

On TAP - It should let me edit the values, without highlighting the background area - the thing that usually TextBoxes do

I don't need any border

Once i stop editing and tap outside the control , it should look like a TextBlock, tapping it again let you edit normally

答:
You have two (easy) options:

You can create a Grid element and put a TextBlock and TextBox inside, so they overlap. You then set the Opacity of the TextBox to 0.01 (do not hide completely, as it won't work then)

You can modify the Properties of the TextBox element in VisualStudio by just setting the Background to Transparent for both in and out of focus. You also can set the Border to be Transparent in the Properties.


问:
Scanner + System.in stop condition
I'm reading a file with Scanner + System.in. My command in Linux looks like:

```<code>cat -A test.txt | java -jar test.jar
</code>```

I'm reading input like:

```<code>Scanner input = new Scanner(System.in);

    while (input.hasNextLine())
    {
        String log_line = input.nextLine();
    }
</code>```

The question is.. How I can stop reading when the end of file is reached?

答:
It seems that problem is -A option, not Your java code (it works correctly on plain files):

```<code>$ echo -e "foo\nbar" | java -jar Test.jar
foo
bar
$
</code>```

Maybe test.txt contains some non-printable chars that Scanner can't handle...

Title: Scanner + System.in stop condition

Body:
I'm reading a file with Scanner + System.in. My command in Linux looks like:

cat -A test.txt | java -jar test.jar

I'm reading input like:

Scanner input = new Scanner(System.in);

    while (input.hasNextLine())
    {
        String log_line = input.nextLine();
    }

The question is.. How I can stop reading when the end of file is reached?

Body:
It seems that problem is -A option, not Your java code (it works correctly on plain files):

$ echo -e "foo\nbar" | java -jar Test.jar
foo
bar
$

Maybe test.txt contains some non-printable chars that Scanner can't handle...


问:
Item position by css?
I am new to html and css. Sorry this too easy question, maybe stupit. vid2 under the vid1, it's ok. But, I try to put vid3 rigth of to vid1. But It isn't working.

Actually, I am tring to do something like that;

index.html;

[vid1]   [vid3]  [vid5]

[vid2]   [vid4]  [vid6]

Could you help me to fix code. Thank you.

.vid1
    {
    position: absolute; overflow:hidden; left: 10px; top: 10px; z-index:0;
    }
    .vid2
    {
    position : absolute; overflow:hidden; left::20px; top:180px;  z-index:0;
    }
    .vid3
    {
    position : absolute; overflow:hidden; left::200px; top:10px;  z-index:0;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><iframe class="vid1" src="http://www.youtube.com/embed/r9dsH8H-4P8" frameborder="0" allowfullscreen></iframe>
<iframe class="vid2"  src="http://www.youtube.com/embed/i7sxqaC062A" frameborder="0" allowfullscreen></iframe>
<iframe class="vid3"  src="http://www.youtube.com/embed/YeJQBbtjgK8" frameborder="0" allowfullscreen></iframe></code>```

答:
CSS for .vid3 as below

```<code>.vid3
{
position: relative;
overflow: hidden;
z-index: 0;
float: right;
right: 700;
}
</code>```

Hope it helps.

Title: Item position by css?

Body:
CSS for .vid3 as below

.vid3
{
position: relative;
overflow: hidden;
z-index: 0;
float: right;
right: 700;
}

Hope it helps.


问:
UITableView and custom UITableViewCell using .xib
In my app I am using a custom tableViewCell using a xib file. I create the .xib file outlet the labels etc to my TableViewCell class

In my ViewController the code I used to populate and show the cell on the table view is as follows:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let transaction = statementArray[indexPath.row]
    let cell = Bundle.main.loadNibNamed("StatementCell", owner: self, options: nil)?.first as! StatementCell

    cell.transAmount.text = String(transaction.transAmount)
    cell.transDesc.text = transaction.transDesc
    cell.transFees.text = String(transaction.transFees)

    return cell
}
</code>```

I am aware that the way tableViews work is that they reuse the cell that goes off the screen. Is the way i am loading the .xib and populating the cell correct? Or do I have to add something to my code?

答:
First you need to register your custom cell with UITableView

```<code>yourTableView.register(UINib(nibName: "StatementCell", bundle: nil), forCellReuseIdentifier: "cellIdentifier")
</code>```

then in UITableView Delegate method cellForRowAt you need to write

```<code>let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath) as! StatementCell
cell.textLabel?.text = "Sample Project"
return cell
</code>```

now you can access your UITableViewCell properties with cell.propertyName

and you must take care that  "cellIdentifier" and "forCellReuseIdentifier" both value must be same.

Body:
In my app I am using a custom tableViewCell using a xib file. I create the .xib file outlet the labels etc to my TableViewCell class

In my ViewController the code I used to populate and show the cell on the table view is as follows:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let transaction = statementArray[indexPath.row]
    let cell = Bundle.main.loadNibNamed("StatementCell", owner: self, options: nil)?.first as! StatementCell

    cell.transAmount.text = String(transaction.transAmount)
    cell.transDesc.text = transaction.transDesc
    cell.transFees.text = String(transaction.transFees)

    return cell
}

I am aware that the way tableViews work is that they reuse the cell that goes off the screen. Is the way i am loading the .xib and populating the cell correct? Or do I have to add something to my code?

Body:
First you need to register your custom cell with UITableView

yourTableView.register(UINib(nibName: "StatementCell", bundle: nil), forCellReuseIdentifier: "cellIdentifier")

then in UITableView Delegate method cellForRowAt you need to write

let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath) as! StatementCell
cell.textLabel?.text = "Sample Project"
return cell

now you can access your UITableViewCell properties with cell.propertyName

and you must take care that  "cellIdentifier" and "forCellReuseIdentifier" both value must be same.