答:
It should just be SET model='B-' + model, I think. You need to add the new text to the existing value. The % does nothing in that context. And I think therefore you only need one update statement, because you're prepending the same thing to every row.

```<code>UPDATE spotting SET model = 'B-' + model WHERE model LIKE '7%';
</code>```

Also you should consider adding some input validation to whatever form people are using to input this data, so the numbers are always in the correct format in future.

Title: MySQL Update Query?

Body:
As my project gathers pace I have noticed that some users are inputting Aircraft Models incorrectly - (field is "model") for instance as -

737-8AS
737-8k3
757-222
etc

What I want to do via a query is to run through these and add a leading "B", for instance the above would be changed to:

B737-8AS
B737-8k3
B757-222

What I have in my daily update script is -

/* Set Boeings */
UPDATEspottingSETmodel='B707-%' WHEREmodelLIKE '707-%';
UPDATEspottingSETmodel='B717-%' WHEREmodelLIKE '717-%';
UPDATEspottingSETmodel='B727-%' WHEREmodelLIKE '727-%';
UPDATEspottingSETmodel='B737-%' WHEREmodelLIKE '737-%';
UPDATEspottingSETmodel='B747-%' WHEREmodelLIKE '747-%';
UPDATEspottingSETmodel='B757-%' WHEREmodelLIKE '757-%';
UPDATEspottingSETmodel='B767-%' WHEREmodelLIKE '767-%';
UPDATEspottingSETmodel='B777-%' WHEREmodelLIKE '777-%';
UPDATEspottingSETmodel='B787-%' WHEREmodelLIKE '787-%';

This does edit the data to give the leading "B" but it then drops everything after the B737-

where "737-8AS/W" becomes "B737-" where it should be "B737-8AS/W"

I am guessing this is something simple I am missing.

Body:
It should just be SET model='B-' + model, I think. You need to add the new text to the existing value. The % does nothing in that context. And I think therefore you only need one update statement, because you're prepending the same thing to every row.

UPDATE spotting SET model = 'B-' + model WHERE model LIKE '7%';

Also you should consider adding some input validation to whatever form people are using to input this data, so the numbers are always in the correct format in future.


来源: stackexchange

问:
What am I missing in my OS X Squirrel configuration?
I'm deploying an Electron app with Squirrel on the backend to do updates.  The Windows deployment works just fine, updating from a .nupkg at this sample path:

```<code>https://host/update/win32/1.0.1/RELEASES
</code>```

However, the Mac version (which I'm supplying a .zip file to as per the docs) does not seem to work.  I've run across some contradictory information on the pathing (and have tried them all, plus a great many variations in case there were typos in the docs), but the very latest info I could find is what I'm using now:

```<code>https://host/update/darwin_x64/1.0.1
</code>```

What path should I be using for OS X?  Is there perhaps something about the .zip file that Electron-builder (with the Squirrel module) is creating that might be causing a problem?

答: My code signing environment variables were not getting properly set in my OS X build script, so code signing was not happening.  In order for OS X apps to update via Squirrel, both the new and the old versions MUST be signed.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm deploying an Electron app with Squirrel on the backend to do updates.  The Windows deployment works just fine, updating from a .nupkg at this sample path:

https://host/update/win32/1.0.1/RELEASES

However, the Mac version (which I'm supplying a .zip file to as per the docs) does not seem to work.  I've run across some contradictory information on the pathing (and have tried them all, plus a great many variations in case there were typos in the docs), but the very latest info I could find is what I'm using now:

https://host/update/darwin_x64/1.0.1

What path should I be using for OS X?  Is there perhaps something about the .zip file that Electron-builder (with the Squirrel module) is creating that might be causing a problem?


问:
Django How can i split string using template tag
Hello I want to know that how can I split string of dictionary values

This is my crawler which is returns dictionary data looks like

```<code>data = {
    {0:'http://..., product name, product price'},
    {1:'http://...2, product name2, product price2'},
    {N:'http://...2, product name2, product price n'}
}
</code>```

I want to split these data by comma
 like,

```<code>for value in data.values():
     href, product_name, product_price = str(value).split(",")
</code>```

in Django

This is my crawler.py

```<code>import requests
from urllib import parse
from bs4 import BeautifulSoup

def spider(item_name):
    url_item_name = parse.quote(item_name.encode('euc-kr'))

    url = 'http://search.11st.co.kr/SearchPrdAction.tmall?method=getTotalSearchSeller&isGnb=Y&prdType=&category=&cmd=&pageSize=&lCtgrNo=&mCtgrNo=&sCtgrNo=&dCtgrNo=&fromACK=recent&semanticFromGNB=&gnbTag=TO&schFrom=&schFrom=&ID=&ctgrNo=&srCtgrNo=&keyword=&adUrl=&adKwdTrcNo=&adPrdNo=&targetTab=T&kwd=' + url_item_name
    resp = requests.get(url)
    resp.raise_for_status()

    resp.encoding='euc-kr'
    plain_text = resp.text

    soup = BeautifulSoup(plain_text, 'lxml')
    mytag = soup.find_all(True, {"class": ["sale_price", "list_info"]})
    #for link in soup.select('div.list_info p.info_tit a') :
    data = {}
    count = -1;
    for link in mytag:
        if(link.find('a')):
            count+=1
            href = link.find('a').get('href')
            product_name = link.find('a').string
            data[count] = str(href) + ", " + str(product_name)
        else:
            product_price = link.string
            if(product_price):
                data[count] = data[count] +", " + str(product_price)

    for value in data.values():
        print(value)
    resp.close()

    return data
</code>```

and this is my views

```<code>def post_shop_list(request):
    posts = spider("product name")
    return render(request, 'blog/post_list.html',{'posts' : posts})
</code>```

and this is my post_list.html

```<code>{% for key, value in posts.items %}
    <div>
        <td>{{key}}</td>
        <p>product name :{{value}}</p>
        <h1><a href=href> </a></h1>
        <p>{{ product_price|linebreaksbr}}</p>
    </div>
{% endfor %}
</code>```

Thank you .. !!

答:
Create custom template filter

```<code>from django import template

register = template.Library()

@register.filter(name='split')
def split(value, key):
  """
    Returns the value turned into a list.
  """
  return value.split(key)
</code>```

In Django template you can use it like.

```<code># assuming value = "url, product_name, product_price"
# and you have always these three comma separated items in sequence
{% for key, value in posts.items %}
   <tr>
      {% with value|split:"," as details %}
         {% for p in details %}
            <td>{{ p }}</td>
         {% endfor %}
      {% endwith %}
   </tr>
{% endfor %}
</code>```

UPDATE

You have to also make entry of your tag file in TEMPLATE list in libraries keyword.

```<code>TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            str(APPS_DIR.path('templates')),
        ],
        'OPTIONS': {

            'loaders': [
                ...
            ],

            'context_processors': [
                ...
            ],
            'libraries':{
               # make your file entry here.
               'filter_tags': 'app.templatetags.filter',
            }
        },
    },
]
</code>```

and then load this tag to top of your html file where you want to use split filter

```<code>{% load filter_tags %}
</code>```

Body:
Hello I want to know that how can I split string of dictionary values

This is my crawler which is returns dictionary data looks like

data = {
    {0:'http://..., product name, product price'},
    {1:'http://...2, product name2, product price2'},
    {N:'http://...2, product name2, product price n'}
}

I want to split these data by comma
 like,

for value in data.values():
     href, product_name, product_price = str(value).split(",")

in Django

This is my crawler.py

import requests
from urllib import parse
from bs4 import BeautifulSoup

def spider(item_name):
    url_item_name = parse.quote(item_name.encode('euc-kr'))

    url = 'http://search.11st.co.kr/SearchPrdAction.tmall?method=getTotalSearchSeller&isGnb=Y&prdType=&category=&cmd=&pageSize=&lCtgrNo=&mCtgrNo=&sCtgrNo=&dCtgrNo=&fromACK=recent&semanticFromGNB=&gnbTag=TO&schFrom=&schFrom=&ID=&ctgrNo=&srCtgrNo=&keyword=&adUrl=&adKwdTrcNo=&adPrdNo=&targetTab=T&kwd=' + url_item_name
    resp = requests.get(url)
    resp.raise_for_status()

    resp.encoding='euc-kr'
    plain_text = resp.text

    soup = BeautifulSoup(plain_text, 'lxml')
    mytag = soup.find_all(True, {"class": ["sale_price", "list_info"]})
    #for link in soup.select('div.list_info p.info_tit a') :
    data = {}
    count = -1;
    for link in mytag:
        if(link.find('a')):
            count+=1
            href = link.find('a').get('href')
            product_name = link.find('a').string
            data[count] = str(href) + ", " + str(product_name)
        else:
            product_price = link.string
            if(product_price):
                data[count] = data[count] +", " + str(product_price)

    for value in data.values():
        print(value)
    resp.close()

    return data

and this is my views

def post_shop_list(request):
    posts = spider("product name")
    return render(request, 'blog/post_list.html',{'posts' : posts})

and this is my post_list.html

{% for key, value in posts.items %}

        {{key}}

product name :{{value}}

{{ product_price|linebreaksbr}}

{% endfor %}

Thank you .. !!

Body:
Create custom template filter

from django import template

register = template.Library()

@register.filter(name='split')
def split(value, key):
  """
    Returns the value turned into a list.
  """
  return value.split(key)

In Django template you can use it like.

# assuming value = "url, product_name, product_price"
# and you have always these three comma separated items in sequence
{% for key, value in posts.items %}
   <tr>
      {% with value|split:"," as details %}
         {% for p in details %}
            <td>{{ p }}</td>
         {% endfor %}
      {% endwith %}
   </tr>
{% endfor %}

UPDATE

You have to also make entry of your tag file in TEMPLATE list in libraries keyword.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            str(APPS_DIR.path('templates')),
        ],
        'OPTIONS': {

            'loaders': [
                ...
            ],

            'context_processors': [
                ...
            ],
            'libraries':{
               # make your file entry here.
               'filter_tags': 'app.templatetags.filter',
            }
        },
    },
]

and then load this tag to top of your html file where you want to use split filter

{% load filter_tags %}


问:
springboot+mybatis Exception : org.springframework.beans.factory.NoSuchBeanDefinitionException
I got the following exception:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [pers.panxin.springboot.demo.mapper.UserMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Controller :

```<code>@Controller
public class HelloController {

    @Autowired
    private UserService userService;

    @RequestMapping("/userList")
    @ResponseBody
    public String getAllUser(){
        return "userList : "+userService.getAllUser().toString();//+list.toString();
    }

}
</code>```

Service:

```<code>public interface UserService {

    public String getString();

    public List<User> getAllUser();

}
</code>```

ServiceImpl:

```<code>@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public String getString() {
        return "something else ... ";
    }

    @Override
    public List<User> getAllUser() {
        return userMapper.getAllUser();
    }
}
</code>```

Mapper Interface:

```<code>@Service
public interface UserMapper {

    /**
     * @return
     */
    public List<User> getAllUser();

}
</code>```

Application's main class

```<code>@ComponentScan
@EnableAutoConfiguration
@SpringBootApplication
public class ApplicationStarter {

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

}
</code>```

how the exception happened or something wrong in my code?

答:
Add MappedTypes along with @MapperScan with

Code looks like the below

@MappedTypes({UserMapper.class})

@MapperScan("package.where.mappers.are.located")

Body:
I got the following exception:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [pers.panxin.springboot.demo.mapper.UserMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Controller :

@Controller
public class HelloController {

    @Autowired
    private UserService userService;

    @RequestMapping("/userList")
    @ResponseBody
    public String getAllUser(){
        return "userList : "+userService.getAllUser().toString();//+list.toString();
    }

}

Service:

public interface UserService {

    public String getString();

    public List<User> getAllUser();

}

ServiceImpl:

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public String getString() {
        return "something else ... ";
    }

    @Override
    public List<User> getAllUser() {
        return userMapper.getAllUser();
    }
}

Mapper Interface:

@Service
public interface UserMapper {

    /**
     * @return
     */
    public List<User> getAllUser();

}

Application's main class

@ComponentScan
@EnableAutoConfiguration
@SpringBootApplication
public class ApplicationStarter {

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

}

how the exception happened or something wrong in my code?


问:
How do I format a Microsoft JSON date?
I'm taking my first crack at Ajax with jQuery. I'm getting my data onto my page, but I'm having some trouble with the JSON data that is returned for Date data types. Basically, I'm getting a string back that looks like this:

```<code>/Date(1224043200000)/
</code>```

From someone totally new to JSON - How do I format this to a short date format? Should this be handled somewhere in the jQuery code? I've tried the jQuery.UI.datepicker plugin using $.datepicker.formatDate() without any success.

FYI: Here's the solution I came up with using a combination of the answers here:

```<code>function getMismatch(id) {
  $.getJSON("Main.aspx?Callback=GetMismatch",
    { MismatchId: id },

    function (result) {
      $("#AuthMerchId").text(result.AuthorizationMerchantId);
      $("#SttlMerchId").text(result.SettlementMerchantId);
      $("#CreateDate").text(formatJSONDate(Date(result.AppendDts)));
      $("#ExpireDate").text(formatJSONDate(Date(result.ExpiresDts)));
      $("#LastUpdate").text(formatJSONDate(Date(result.LastUpdateDts)));
      $("#LastUpdatedBy").text(result.LastUpdateNt);
      $("#ProcessIn").text(result.ProcessIn);
    }
  );

  return false;
}

function formatJSONDate(jsonDate) {
  var newDate = dateFormat(jsonDate, "mm/dd/yyyy");
  return newDate;
}
</code>```

This solution got my object from the callback method and displayed the dates on the page properly using the date format library.

答:
The simplest way I can suggest is using regex on JS as:

```<code>//Only use [0] if you are sure that the string matches the pattern
//Otherwise, verify if 'match' returns something
"/Date(1512488018202)/".match(/\d+/)[0]
</code>```

OwnerDisplayName: Mark Struzinski

Title: How do I format a Microsoft JSON date?

Body:
I'm taking my first crack at Ajax with jQuery. I'm getting my data onto my page, but I'm having some trouble with the JSON data that is returned for Date data types. Basically, I'm getting a string back that looks like this:

/Date(1224043200000)/

From someone totally new to JSON - How do I format this to a short date format? Should this be handled somewhere in the jQuery code? I've tried the jQuery.UI.datepicker plugin using $.datepicker.formatDate() without any success.

FYI: Here's the solution I came up with using a combination of the answers here:

function getMismatch(id) {
  $.getJSON("Main.aspx?Callback=GetMismatch",
    { MismatchId: id },

    function (result) {
      $("#AuthMerchId").text(result.AuthorizationMerchantId);
      $("#SttlMerchId").text(result.SettlementMerchantId);
      $("#CreateDate").text(formatJSONDate(Date(result.AppendDts)));
      $("#ExpireDate").text(formatJSONDate(Date(result.ExpiresDts)));
      $("#LastUpdate").text(formatJSONDate(Date(result.LastUpdateDts)));
      $("#LastUpdatedBy").text(result.LastUpdateNt);
      $("#ProcessIn").text(result.ProcessIn);
    }
  );

  return false;
}

function formatJSONDate(jsonDate) {
  var newDate = dateFormat(jsonDate, "mm/dd/yyyy");
  return newDate;
}

This solution got my object from the callback method and displayed the dates on the page properly using the date format library.

LastEditorDisplayName: unwind

Body:
The simplest way I can suggest is using regex on JS as:

//Only use [0] if you are sure that the string matches the pattern
//Otherwise, verify if 'match' returns something
"/Date(1512488018202)/".match(/\d+/)[0]


问:
Best way to capture error from database firebase javascript
I have this code, but i don't know how capture a error.

```<code>  const coleccionRef = database.ref('test');
  coleccionRef.on('value', snapshot => {
    snapshot.val();
  });
</code>```

Any idea?

答:
If your client doesn't have permission to read from the reference, Firebase will invoke the (optional) second callback that you can pass in to on(). E.g.

```<code>const coleccionRef = database.ref('test');
coleccionRef.on('value', snapshot => {
  snapshot.val();
}, error => {
    console.error(error);
});
</code>```

I recommend reading the Firebase reference documentation for finding more tidbits like this.

Body:
I have this code, but i don't know how capture a error.

  const coleccionRef = database.ref('test');
  coleccionRef.on('value', snapshot => {
    snapshot.val();
  });

Any idea?

Body:
If your client doesn't have permission to read from the reference, Firebase will invoke the (optional) second callback that you can pass in to on(). E.g.

const coleccionRef = database.ref('test');
coleccionRef.on('value', snapshot => {
  snapshot.val();
}, error => {
    console.error(error);
});

I recommend reading the Firebase reference documentation for finding more tidbits like this.


问:
Div with the heigh of 100% extends beyond the visible area of the page
Seems to be a very basic concept but I do not understand why when I set the div's height to 100% it extends beyond the visible area of the page. My page is like this:

<!DOCTYPE html>

```

When I open it in the browser, the browser adds a vertical scroller to the page and my div extends beyond the bottom:

If I scroll down a little, I do see the bottom of the div:

But why does my div with the height of 100% extends beyond the bottom of the page?

答:
There is a default margin for the body in most browser stylesheets which causes this. You can reset the margin as shown below

html,
body {
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en-US" style="height: 100%;">

<head></head>

<body style="height: 100%;">
  <div style="height: 100%; background-color: red"> </div>
</body>

</html></code>```

Body:
Seems to be a very basic concept but I do not understand why when I set the div's height to 100% it extends beyond the visible area of the page. My page is like this:

<!DOCTYPE html>

When I open it in the browser, the browser adds a vertical scroller to the page and my div extends beyond the bottom:

If I scroll down a little, I do see the bottom of the div:

But why does my div with the height of 100% extends beyond the bottom of the page?

Body:
There is a default margin for the body in most browser stylesheets which causes this. You can reset the margin as shown below

html,
body {
  margin: 0;
}

<!DOCTYPE html>
<html lang="en-US" style="height: 100%;">

<head></head>

<body style="height: 100%;">
  <div style="height: 100%; background-color: red">&nbsp;</div>
</body>

</html>


问:
Meteor error 'cannot declare let twice' when minifying
When minifying meteor app, safari on IOS 10 throws the following error

```<code>SyntaxError: Cannot declare a let variable twice: 't'.
</code>```

I have tried to remove standart-minifier and added abernix:standart-minifier as it was recommended  on this comment - they work fine on all the other browsers but on safari ios10 it crashes.

Do you have any recommendations?

Thanks a lot

Edit:

I ended up removing minify packages as it was mentioned here however it definitely not a long-term solution.

答:
The solution to this ios10 safari bug is
here

Problem is caused by minify default option

```<code>safari10:false
</code>```

to solve the problem

find these files

/Users/USER/.meteor/packages/abernix_standard-minifier-js/.2.1.0.1v4h096++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/abernix_minifier-js/node_modules/uglify-es/lib/minify.js

and

/Users/USER/.meteor/packages/abernix_minifier-js/.2.1.0.106pai4++os+web.browser+web.cordova/npm/node_modules/uglify-es/lib/minify.js

then find the following lines and change it as "safari10:true"

```<code>if (options.mangle) {
        options.mangle = defaults(options.mangle, {
            cache: null,
            eval: false,
            ie8: false,
            keep_classnames: false,
            keep_fnames: false,
            properties: false,
            reserved: [],
            safari10: true,
            toplevel: false,
        }, true);
    }
</code>```

Body:
When minifying meteor app, safari on IOS 10 throws the following error

SyntaxError: Cannot declare a let variable twice: 't'.

I have tried to remove standart-minifier and added abernix:standart-minifier as it was recommended  on this comment - they work fine on all the other browsers but on safari ios10 it crashes.

Do you have any recommendations?

Thanks a lot

Edit:

I ended up removing minify packages as it was mentioned here however it definitely not a long-term solution.

Body:
The solution to this ios10 safari bug is
here

Problem is caused by minify default option

safari10:false

to solve the problem

find these files

/Users/USER/.meteor/packages/abernix_standard-minifier-js/.2.1.0.1v4h096++os+web.browser+web.cordova/plugin.minifyStdJS.os/npm/node_modules/meteor/abernix_minifier-js/node_modules/uglify-es/lib/minify.js

and

/Users/USER/.meteor/packages/abernix_minifier-js/.2.1.0.106pai4++os+web.browser+web.cordova/npm/node_modules/uglify-es/lib/minify.js

then find the following lines and change it as "safari10:true"

if (options.mangle) {
        options.mangle = defaults(options.mangle, {
            cache: null,
            eval: false,
            ie8: false,
            keep_classnames: false,
            keep_fnames: false,
            properties: false,
            reserved: [],
            safari10: true,
            toplevel: false,
        }, true);
    }


问:
Progress dialog inside async task not working
The progress dialog does not show up when the file is downloading in background. After uploading the file to the database the activity remains as it is as if nothing is happening! A progress dialog is necessary while the file is uploading.

```<code>public class MainActivity extends AppCompatActivity {
    ProgressDialog pd;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICKFILE_REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){
            pd=new ProgressDialog(this);
            Common common=new Common();
            MyTask myTask=common.new MyTask(pd);

            myTask.execute();
        }
    }
</code>```

Asynctask:

```<code>class MyTask extends AsyncTask<Void, Void, Void> {
    ProgressDialog pd;

    public MyTask(ProgressDialog pd) {
        this.pd = pd;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd.setMessage("Uploading . . .");
        pd.show();
        pd.setCancelable(false);
    }

    @Override
    protected Void doInBackground(Void... voids) {
        //download file
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        pd.dismiss();
    }
}
</code>```

I searched all the answer of stack overflow but nothing helped me! Any help is appreciated.

答: Progress Dialog is deprecated anyway, may be  you can use progress bar in your xml with visibility:gone, and when you are about to start download change its visilbility to visible and when it is finished set again it go gone

Body:
The progress dialog does not show up when the file is downloading in background. After uploading the file to the database the activity remains as it is as if nothing is happening! A progress dialog is necessary while the file is uploading.

public class MainActivity extends AppCompatActivity {
    ProgressDialog pd;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICKFILE_REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){
            pd=new ProgressDialog(this);
            Common common=new Common();
            MyTask myTask=common.new MyTask(pd);

            myTask.execute();
        }
    }

Asynctask:

class MyTask extends AsyncTask<Void, Void, Void> {
    ProgressDialog pd;

    public MyTask(ProgressDialog pd) {
        this.pd = pd;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd.setMessage("Uploading . . .");
        pd.show();
        pd.setCancelable(false);
    }

    @Override
    protected Void doInBackground(Void... voids) {
        //download file
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        pd.dismiss();
    }
}

I searched all the answer of stack overflow but nothing helped me! Any help is appreciated.


问:
SQL RowVersion incrementing before data has been augmented in Trigger
I've just started using T-SQL's RowVersion and I've noticed something very interesting. I created a Proc to update a table with a RowVersion column and at the end of this proc I print out a humanreadable date representation of RowVersion. I also added a Trigger which updates data in the table and prints out RowVersion before and after. It's given some interesting results...

From Insert Proc after data is inserted = 1900-01-01 05:43:13.373

From start of Trigger before we change any data =  1900-01-01 05:43:13.377

From end of trigger after data has changed = 1900-01-01 05:43:13.377

The start of the trigger value for the RowVersion column has changed from the end of the proc value for the RowVersion Column despite the fact we have not augmented any data yet. It's also the same as the end of the Trigger. Why is this? Is it something to do with the sequencing of SQL statement execution? Any help understanding this would be appreciated. The proc and trigger are listed below:

```<code>CREATE PROCEDURE [dbo].[TestRowVersionProc]
AS
    INSERT INTO TestRowversion (ID, Number)
    VALUES ('6', '6')

    DECLARE @rv DATETIME
    SELECT @rv = GenerationNumber FROM TestRowversion WHERE ID = '6'
    SELECT CONVERT(VARCHAR(50), @rv , 121)
GO

CREATE TRIGGER [dbo].[TestRowversion_AfterInsertUpdate] ON [dbo].[TestRowversion] AFTER INSERT,UPDATE
AS
    if @@rowcount = 0 return
    set nocount on

    DECLARE @rv DATETIME
    SELECT @rv = GenerationNumber FROM TestRowversion WHERE ID = '6'
    SELECT CONVERT(VARCHAR(50), @rv , 121)

    DECLARE @Id NVARCHAR(1)
    SELECT @Id = ID FROM inserted

    UPDATE TestRowversion
    SET Number = 'FromTrigger'
    WHERE ID = '6'

    SELECT @rv = GenerationNumber FROM TestRowversion WHERE ID = '6'
    SELECT CONVERT(VARCHAR(50), @rv , 121)

GO
</code>```

答:
https://learn.microsoft.com/en-us/sql/t-sql/data-types/rowversion-transact-sql

The rowversion data type is just an incrementing number and does not preserve a date or a time.

Each database has a counter that is incremented for each insert or update operation that is performed on a table that contains a rowversion column within the database. This counter is the database rowversion. This tracks a relative time within a database, not an actual time that can be associated with a clock.

DATETIME Accuracy    Rounded to increments of .000, .003, or .007 seconds

Body:
I've just started using T-SQL's RowVersion and I've noticed something very interesting. I created a Proc to update a table with a RowVersion column and at the end of this proc I print out a humanreadable date representation of RowVersion. I also added a Trigger which updates data in the table and prints out RowVersion before and after. It's given some interesting results...

From Insert Proc after data is inserted = 1900-01-01 05:43:13.373

From start of Trigger before we change any data =  1900-01-01 05:43:13.377

From end of trigger after data has changed = 1900-01-01 05:43:13.377

The start of the trigger value for the RowVersion column has changed from the end of the proc value for the RowVersion Column despite the fact we have not augmented any data yet. It's also the same as the end of the Trigger. Why is this? Is it something to do with the sequencing of SQL statement execution? Any help understanding this would be appreciated. The proc and trigger are listed below:

CREATE PROCEDURE [dbo].[TestRowVersionProc]
AS
    INSERT INTO TestRowversion (ID, Number)
    VALUES ('6', '6')

    DECLARE @rv DATETIME
    SELECT @rv = GenerationNumber FROM TestRowversion WHERE ID = '6'
    SELECT CONVERT(VARCHAR(50), @rv , 121)
GO

CREATE TRIGGER [dbo].[TestRowversion_AfterInsertUpdate] ON [dbo].[TestRowversion] AFTER INSERT,UPDATE
AS
    if @@rowcount = 0 return
    set nocount on

    DECLARE @rv DATETIME
    SELECT @rv = GenerationNumber FROM TestRowversion WHERE ID = '6'
    SELECT CONVERT(VARCHAR(50), @rv , 121)

    DECLARE @Id NVARCHAR(1)
    SELECT @Id = ID FROM inserted

    UPDATE TestRowversion
    SET Number = 'FromTrigger'
    WHERE ID = '6'

    SELECT @rv = GenerationNumber FROM TestRowversion WHERE ID = '6'
    SELECT CONVERT(VARCHAR(50), @rv , 121)

GO


问:
Can't get php/html pages to display characters with accents (é, á ) correctly
I can't get my php/html pages to display characters with accents (é, á ) correctly. My database is set up correctly. When I run show variables like 'char% I get satisfactory output:

```<code>character_set_client        utf8
character_set_connection    utf8
character_set_database      utf8
character_set_filesystem    binary
character_set_results       utf8
character_set_server        utf8
character_set_system        utf8
character_sets_dir      /usr/share/mysql/charsets/
</code>```

Data is encoded and stored correctly in the DB when I insert it from a form on my site.

But something weird happens on my display page.

If I put header('Content-Type: text/html; charset=utf-8'); at the top just inside the php opening tag, data from my DB is displayed correctly but characters that I type manually into the page within HTML tags (as Table Column Headers or just descriptive para text) display with rubbish: �.

If I REMOVE header('Content-Type: text/html; charset=utf-8'); from the top of the page, data from my DB is displayed INCORRECTLY but the text that I write into the page within HTML is fine.

I've tried everything I know. Has anyone come across this before?

答:
The only thing I can think of in addition to what you've done on the server side is to add:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

To the  tag in your html file.

Body:
I can't get my php/html pages to display characters with accents (é, á ) correctly. My database is set up correctly. When I run show variables like 'char% I get satisfactory output:

character_set_client        utf8
character_set_connection    utf8
character_set_database      utf8
character_set_filesystem    binary
character_set_results       utf8
character_set_server        utf8
character_set_system        utf8
character_sets_dir      /usr/share/mysql/charsets/

Data is encoded and stored correctly in the DB when I insert it from a form on my site.

But something weird happens on my display page.

If I put header('Content-Type: text/html; charset=utf-8'); at the top just inside the php opening tag, data from my DB is displayed correctly but characters that I type manually into the page within HTML tags (as Table Column Headers or just descriptive para text) display with rubbish: �.

If I REMOVE header('Content-Type: text/html; charset=utf-8'); from the top of the page, data from my DB is displayed INCORRECTLY but the text that I write into the page within HTML is fine.

I've tried everything I know. Has anyone come across this before?

Body:
The only thing I can think of in addition to what you've done on the server side is to add:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

To the <head> tag in your html file.


问:
How to delete posts without featured images in wordpress via mysql?
How can posts without featured-images be removed via mysql in wordpress ?

I tried this code but it delete all posts which include featured-images also. I just want to remove posts only that without featured-images.

```<code>DELETE FROM wp_posts WHERE ID not in (select post_id as p from wp_postmeta where meta_key like "_wp_attached_file")
</code>```

答:
The problem you're running into is that you are pulling back the 'post_id' for all sorts of things.

The meta_key value you want is "_thumbnail_id" which will have the parent post stored in post_id.

DELETE at your own peril, you might try a SELECT instead of DELETE first to make sure this does what you really want:

```<code>DELETE FROM wp_posts WHERE ID not in (select post_id as p from wp_postmeta where meta_key like "_thumbnail_id");
</code>```

UPDATE:  Here is my validation test.

Created a new post (7161), then added a feature image.

```<code>mysql> select * from wp_postmeta where post_id IN(7161,7162);
+---------+---------+---------------+---------------------+
| meta_id | post_id | meta_key      | meta_value          |
+---------+---------+---------------+---------------------+
|   12533 |    7161 | _edit_lock    | 1512581739:1        |
|   12534 |    7161 | _edit_last    | 1                   |
|   12549 |    7161 | _thumbnail_id | 7115                |
|   12543 |    7161 | CODE1         |                     |
|   12544 |    7161 | _CODE1        | field_57e4293a9238c |
|   12545 |    7161 | CODE3         |                     |
|   12546 |    7161 | _CODE3        | field_57e4297c9238d |
|   12547 |    7161 | CODE2         |                     |
|   12548 |    7161 | _CODE2        | field_57e42ceb508ff |
</code>```

Created a clone of the wp_posts table

```<code>create table wp_posts_test like wp_posts;
  Query OK, 0 rows affected (0.01 sec)
</code>```

and loaded it with live data from wp_posts.

```<code>insert into wp_posts_test select * from wp_posts;
  Query OK, 6938 rows affected (0.30 sec)
</code>```

Then ran my test query to delete anything without a featured image:

```<code>delete from wp_posts_test WHERE ID NOT IN (select post_id from wp_postmeta where meta_key="_thumbnail_id");
   Query OK, 6937 rows affected (0.37 sec)
</code>```

Checked the table, and there is only one record, and it's the post I wanted to keep:

```<code>select * from wp_posts_test \G

*************************** 1. row ***************************
                   ID: 7161
          post_author: 1
            post_date: 2017-12-06 09:29:20
        post_date_gmt: 2017-12-06 17:29:20
         post_content: This is just a test post to see if the featured image OR the post is nuked using a mysql hack.   Standby for destruction.
           post_title: Feature Image Test Post
        post_category: 0
         post_excerpt:
          post_status: publish
       comment_status: open
          ping_status: open
        post_password:
            post_name: feature-image-test-post
              to_ping:
               pinged:
        post_modified: 2017-12-06 09:35:18
    post_modified_gmt: 2017-12-06 17:35:18
post_content_filtered:
          post_parent: 0
                 guid: http://blog.daviddemartini.com/?p=7161
           menu_order: 0
            post_type: post
       post_mime_type:
        comment_count: 0
</code>```

1 row in set (0.00 sec)

It looks like it works perfectly fine to me, if you wanted to remove all the records from wp_posts that didn't have an association to a featured image.   Why it might not be working for you, is a mystery to me.

Body:
How can posts without featured-images be removed via mysql in wordpress ?

I tried this code but it delete all posts which include featured-images also. I just want to remove posts only that without featured-images.

DELETE FROM wp_posts WHERE ID not in (select post_id as p from wp_postmeta where meta_key like "_wp_attached_file")

Body:
The problem you're running into is that you are pulling back the 'post_id' for all sorts of things.

The meta_key value you want is "_thumbnail_id" which will have the parent post stored in post_id.

DELETE at your own peril, you might try a SELECT instead of DELETE first to make sure this does what you really want:

DELETE FROM wp_posts WHERE ID not in (select post_id as p from wp_postmeta where meta_key like "_thumbnail_id");

UPDATE:  Here is my validation test.

Created a new post (7161), then added a feature image.

mysql> select * from wp_postmeta where post_id IN(7161,7162);
+---------+---------+---------------+---------------------+
| meta_id | post_id | meta_key      | meta_value          |
+---------+---------+---------------+---------------------+
|   12533 |    7161 | _edit_lock    | 1512581739:1        |
|   12534 |    7161 | _edit_last    | 1                   |
|   12549 |    7161 | _thumbnail_id | 7115                |
|   12543 |    7161 | CODE1         |                     |
|   12544 |    7161 | _CODE1        | field_57e4293a9238c |
|   12545 |    7161 | CODE3         |                     |
|   12546 |    7161 | _CODE3        | field_57e4297c9238d |
|   12547 |    7161 | CODE2         |                     |
|   12548 |    7161 | _CODE2        | field_57e42ceb508ff |

Created a clone of the wp_posts table

create table wp_posts_test like wp_posts;
  Query OK, 0 rows affected (0.01 sec)

and loaded it with live data from wp_posts.

insert into wp_posts_test select * from wp_posts;
  Query OK, 6938 rows affected (0.30 sec)

Then ran my test query to delete anything without a featured image:

delete from wp_posts_test WHERE ID NOT IN (select post_id from wp_postmeta where meta_key="_thumbnail_id");
   Query OK, 6937 rows affected (0.37 sec)

Checked the table, and there is only one record, and it's the post I wanted to keep:

select * from wp_posts_test \G

*************************** 1. row ***************************
                   ID: 7161
          post_author: 1
            post_date: 2017-12-06 09:29:20
        post_date_gmt: 2017-12-06 17:29:20
         post_content: This is just a test post to see if the featured image OR the post is nuked using a mysql hack.   Standby for destruction.
           post_title: Feature Image Test Post
        post_category: 0
         post_excerpt:
          post_status: publish
       comment_status: open
          ping_status: open
        post_password:
            post_name: feature-image-test-post
              to_ping:
               pinged:
        post_modified: 2017-12-06 09:35:18
    post_modified_gmt: 2017-12-06 17:35:18
post_content_filtered:
          post_parent: 0
                 guid: http://blog.daviddemartini.com/?p=7161
           menu_order: 0
            post_type: post
       post_mime_type:
        comment_count: 0

1 row in set (0.00 sec)

It looks like it works perfectly fine to me, if you wanted to remove all the records from wp_posts that didn't have an association to a featured image.   Why it might not be working for you, is a mystery to me.


问:
beaconinfo.getforobserved always returning an empty response
Here is my request.

```<code>POST https://proximitybeacon.googleapis.com/v1beta1/beaconinfo:getforobserved?key=<API_KEY>
</code>```

with POST data

```<code> {
  "observations": [
    {
      "advertisedId": {
        "type": "EDDYSTONE",
        "id": "XcM0h/AuR31AWAEXxV59Xw=="
      },
      "timestampMs": "2017-11-28T12:11:23.045123456Z"
    }
  ],
  "namespacedTypes": [
    "*"
    ]
}
</code>```

I've checked the beacon dashboard to see if the beacon has any attachments to it. It has a nearby notification attachment which I want to fetch using this method.

The beaconID in hex is 5dc33487f02e477d40580117c55e7d5f.

I referred to this guide for help but it seems the request they are making is wrong considering the namespacedTypes should be an array and it is a string in the blog.

Here is the documentation for the API.

UPDATE:

If I do a Proximity API list attachment call I get the following result for the same beacon

```<code>[
   {
      "data":"eyJ1cmwiOiAiaHR0cHM6Ly9xLmVkZHkucHJvLzhsMkl3SiIsICJkZXNjcmlwdGlvbiI6ICJTb21lIiwgInRpdGxlIjogIlNvbWUifQ==",
      "creationTimeMs":"2017-12-01T18:15:37.418Z",
      "attachmentName":"beacons/3!5dc33487f02e477d40580117c55e7d5f/attachments/58dad403-7a99-4085-b338-5fe0b6660abd",
      "namespacedType":"com.google.nearby/en"
   }
]
</code>```

Does this mean there is something wrong with the beaconinfo:getforobserved API call?

答:
My understanding is that getforobserved cannot fetch nearby notification attachments but only the attachments defined under the "Attachments" sections in Beacon Dashboard (consisting of a namespace, type and value). The documentation says that getforobserved accepts * to specify all types in all namespaces owned by the client. For nearby notification attachments the namespace is com.google.nearby which is not owned by client. This is my best understanding but I'm not 100% sure about it.

In any case, your getforobserved request looks correct to me. You can verify that the request works correctly by either:

1) Removing the "namespacedTypes" completely from the POST data. In this case the request will not return any attachments but it should return beacon info, so you should get a non-empty answer if the request is otherwise OK.

2) Add an attachment (the other type instead of nearby notification) to the beacon and see if the request returns something. The API will return empty if namespacedTypes is defined but there are no attachments.

Android devices can get nearby notifications automatically if they are enabled on the phone, so typically there should not be need to request the nearby attachments manually. If you want to maintain nearby notification attachments through the API, you can use the other methods provided in the API (such as the list method). If you want to scan for beacons and fetch attachments, I would use the normal attachments which offers more flexibility with the content.

Body:
Here is my request.

POST https://proximitybeacon.googleapis.com/v1beta1/beaconinfo:getforobserved?key=<API_KEY>

with POST data

 {
  "observations": [
    {
      "advertisedId": {
        "type": "EDDYSTONE",
        "id": "XcM0h/AuR31AWAEXxV59Xw=="
      },
      "timestampMs": "2017-11-28T12:11:23.045123456Z"
    }
  ],
  "namespacedTypes": [
    "*"
    ]
}

I've checked the beacon dashboard to see if the beacon has any attachments to it. It has a nearby notification attachment which I want to fetch using this method.

The beaconID in hex is 5dc33487f02e477d40580117c55e7d5f.

I referred to this guide for help but it seems the request they are making is wrong considering the namespacedTypes should be an array and it is a string in the blog.

Here is the documentation for the API.

UPDATE:

If I do a Proximity API list attachment call I get the following result for the same beacon

[
   {
      "data":"eyJ1cmwiOiAiaHR0cHM6Ly9xLmVkZHkucHJvLzhsMkl3SiIsICJkZXNjcmlwdGlvbiI6ICJTb21lIiwgInRpdGxlIjogIlNvbWUifQ==",
      "creationTimeMs":"2017-12-01T18:15:37.418Z",
      "attachmentName":"beacons/3!5dc33487f02e477d40580117c55e7d5f/attachments/58dad403-7a99-4085-b338-5fe0b6660abd",
      "namespacedType":"com.google.nearby/en"
   }
]

Does this mean there is something wrong with the beaconinfo:getforobserved API call?


问:
Keras shows no Improvements to training speed with GPU (partial GPU usage?!)
I am trying to train my model on a GPU instead of a CPU on an AWS p2.xlarge instance from my Jupyter Notebook. I am using tensorflow-gpu backend (only tensorflow-gpu was installed and mentioned in requirements.txt and not tensorflow).

I am not seeing any speed improvements when training models on these instances compared to using a CPU, infact I am getting training speeds per epoch that is almost same as I am getting on my 4-core  laptop CPU (p2.xlarge also has 4 vCPUs with a Tesla K80 GPU). I am not sure if i need to do some changes to my code to accommodate faster/parallel processing that GPU can offer. I am pasting below my code for my model:

```<code>model = Sequential()
model.add(recurrent.LSTM(64, input_shape=(X_np.shape[1], X_np.shape[2]),
                        return_sequences=True))
model.add(recurrent.LSTM(64, return_sequences = False))
model.add(core.Dropout(0.1))
model.add(core.Dense(3, activation='softmax'))
model.compile(loss = 'categorical_crossentropy', optimizer = 'rmsprop', metrics=['accuracy'])

model.fit(X_np, y_np, epochs=100, validation_split=0.25)
</code>```

Also interestingly the GPU seems to be utilizing between 50%-60% of its processing power and almost all of its memory every time I check for GPU status using nvidia-smi (but both fall to 0% and 1MiB respectively when not training):

```<code>+-----------------------------------------------------------------------------+
| NVIDIA-SMI 384.81                 Driver Version: 384.81                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  Tesla K80           On   | 00000000:00:1E.0 Off |                    0 |
| N/A   47C    P0    73W / 149W |  10919MiB / 11439MiB |     52%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      1665      C   ...ubuntu/aDash/MLenv/bin/python 10906MiB |
+-----------------------------------------------------------------------------+
</code>```

Also if you'd like to see my logs about using the GPU from Jupyter Notebook:

```<code>[I 04:21:59.390 NotebookApp] Kernel started: c17bc4d1-fa15-4b0e-b5f0-87f90e56bf65
[I 04:22:02.241 NotebookApp] Adapting to protocol v5.1 for kernel c17bc4d1-fa15-4b0e-b5f0-87f90e56bf65
2017-11-30 04:22:32.403981: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA
2017-11-30 04:22:33.653681: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:892] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2017-11-30 04:22:33.654041: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1030] Found device 0 with properties:
name: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235
pciBusID: 0000:00:1e.0
totalMemory: 11.17GiB freeMemory: 11.10GiB
2017-11-30 04:22:33.654070: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1120] Creating TensorFlow device (/device:GPU:0) -> (device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7)
2017-11-30 04:22:34.014329: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1120] Creating TensorFlow device (/device:GPU:0) -> (device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7)
Device mapping:
/job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7
2017-11-30 04:22:34.015339: I tensorflow/core/common_runtime/direct_session.cc:299] Device mapping:
/job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7

2017-11-30 04:23:22.426895: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1120] Creating TensorFlow device (/device:GPU:0) -> (device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7)
</code>```

Please suggest what could be the problem. Thanks a ton for looking at this anyways!

答:
The bottleneck in your case is transferring data to and from the GPU. The best way to speed up your computation (and maximize your GPU usage) is to load as much of your data as your memory can hold at once. Since you have plenty of memory, you can put all your data at once, by doing:

```<code>model.fit(X_np, y_np, epochs=100, validation_split=0.25, batch_size=X_np.shape[0])
</code>```

(You should also probably increase the number of epochs when doing this).

Note however that there are advantages to minibatching (e.g. better handling of local minima), so you should probably consider choosing a batch_size somewhere in between.

Body:
I am trying to train my model on a GPU instead of a CPU on an AWS p2.xlarge instance from my Jupyter Notebook. I am using tensorflow-gpu backend (only tensorflow-gpu was installed and mentioned in requirements.txt and not tensorflow).

I am not seeing any speed improvements when training models on these instances compared to using a CPU, infact I am getting training speeds per epoch that is almost same as I am getting on my 4-core  laptop CPU (p2.xlarge also has 4 vCPUs with a Tesla K80 GPU). I am not sure if i need to do some changes to my code to accommodate faster/parallel processing that GPU can offer. I am pasting below my code for my model:

model = Sequential()
model.add(recurrent.LSTM(64, input_shape=(X_np.shape[1], X_np.shape[2]),
                        return_sequences=True))
model.add(recurrent.LSTM(64, return_sequences = False))
model.add(core.Dropout(0.1))
model.add(core.Dense(3, activation='softmax'))
model.compile(loss = 'categorical_crossentropy', optimizer = 'rmsprop', metrics=['accuracy'])

model.fit(X_np, y_np, epochs=100, validation_split=0.25)

Also interestingly the GPU seems to be utilizing between 50%-60% of its processing power and almost all of its memory every time I check for GPU status using nvidia-smi (but both fall to 0% and 1MiB respectively when not training):

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 384.81                 Driver Version: 384.81                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  Tesla K80           On   | 00000000:00:1E.0 Off |                    0 |
| N/A   47C    P0    73W / 149W |  10919MiB / 11439MiB |     52%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      1665      C   ...ubuntu/aDash/MLenv/bin/python 10906MiB |
+-----------------------------------------------------------------------------+

Also if you'd like to see my logs about using the GPU from Jupyter Notebook:

[I 04:21:59.390 NotebookApp] Kernel started: c17bc4d1-fa15-4b0e-b5f0-87f90e56bf65
[I 04:22:02.241 NotebookApp] Adapting to protocol v5.1 for kernel c17bc4d1-fa15-4b0e-b5f0-87f90e56bf65
2017-11-30 04:22:32.403981: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA
2017-11-30 04:22:33.653681: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:892] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2017-11-30 04:22:33.654041: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1030] Found device 0 with properties:
name: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235
pciBusID: 0000:00:1e.0
totalMemory: 11.17GiB freeMemory: 11.10GiB
2017-11-30 04:22:33.654070: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1120] Creating TensorFlow device (/device:GPU:0) -> (device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7)
2017-11-30 04:22:34.014329: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1120] Creating TensorFlow device (/device:GPU:0) -> (device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7)
Device mapping:
/job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7
2017-11-30 04:22:34.015339: I tensorflow/core/common_runtime/direct_session.cc:299] Device mapping:
/job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7

2017-11-30 04:23:22.426895: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1120] Creating TensorFlow device (/device:GPU:0) -> (device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7)

Please suggest what could be the problem. Thanks a ton for looking at this anyways!

Body:
The bottleneck in your case is transferring data to and from the GPU. The best way to speed up your computation (and maximize your GPU usage) is to load as much of your data as your memory can hold at once. Since you have plenty of memory, you can put all your data at once, by doing:

model.fit(X_np, y_np, epochs=100, validation_split=0.25, batch_size=X_np.shape[0])

(You should also probably increase the number of epochs when doing this).

Note however that there are advantages to minibatching (e.g. better handling of local minima), so you should probably consider choosing a batch_size somewhere in between.


问:
Typescript: Partial<this> as parameter type not work

I'm trying to make the following code compile, but it fails in C.inc method  with message:

```<code>error TS2345: Argument of type '{ counter: number; }' is not assignable to parameter of type 'Partial<this>'.
</code>```

The Code fails to compile:

```<code>class B {
    clone(diff: Partial<this>): this {
        return this; // omit the implementation.
    }
}

class C extends B {
    counter = 0;
    inc() {
        return this.clone({
            counter: this.counter + 1
        })
    }
}
</code>```

But the following code can compile (without the C.inc method):

```<code>let c = new C();
c.clone({ counter: c.counter + 1 });
</code>```

I want to know why.

答:
I don't know why Partial<this> doesn't work, but Pick works:

```<code>class B {
    clone<K extends keyof this>(diff: Pick<this, K>): this {
        return this; // omit the implementation.
    }
}

class C extends B {
    counter = 0;
    inc() {
        return this.clone({
            counter: this.counter + 1
        })
    }
}
</code>```

I would love to know the reason!

Body:
I'm trying to make the following code compile, but it fails in C.inc method  with message:

error TS2345: Argument of type '{ counter: number; }' is not assignable to parameter of type 'Partial<this>'.

The Code fails to compile:

class B {
    clone(diff: Partial<this>): this {
        return this; // omit the implementation.
    }
}

class C extends B {
    counter = 0;
    inc() {
        return this.clone({
            counter: this.counter + 1
        })
    }
}

But the following code can compile (without the C.inc method):

let c = new C();
c.clone({ counter: c.counter + 1 });

I want to know why.

Body:
I don't know why Partial<this> doesn't work, but <a href="http://www.typescriptlang.org/play/#src=class%20B%20%7B%0D%0A%20%20%20%20clone%3CK%20extends%20keyof%20this%3E(diff%3A%20Pick%3Cthis%2C%20K%3E)%3A%20this%20%7B%0D%0A%20%20%20%20%20%20%20%20return%20this%3B%20%2F%2F%20omit%20the%20implementation.%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Aclass%20C%20extends%20B%20%7B%0D%0A%20%20%20%20counter%20%3D%200%3B%0D%0A%20%20%20%20inc()%20%7B%0D%0A%20%20%20%20%20%20%20%20return%20this.clone(%7B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20counter%3A%20this.counter%20%2B%201%0D%0A%20%20%20%20%20%20%20%20%7D)%0D%0A%20%20%20%20%7D%0D%0A%7D" rel="nofollow noreferrer">Pick works:

class B {
    clone<K extends keyof this>(diff: Pick<this, K>): this {
        return this; // omit the implementation.
    }
}

class C extends B {
    counter = 0;
    inc() {
        return this.clone({
            counter: this.counter + 1
        })
    }
}

I would love to know the reason!


问:
Angular Controller doesn't seem to work
I'm building a simple Sigle Page Application with AngularJs, which retrieves data stored on a server-based application.
Below are the files I'm using:

index.html:

```<code><!DOCTYPE html>
<html ng-app="Js-Users-App">

<head>
    <meta charset="utf-8">
    <title>Js Users</title>
    <!-- Compiled and minified CSS -->
    <link rel="stylesheet" href="node_modules/materialize-css/dist/css/materialize.min.css">
    <!--Import Google Icon Font-->
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    <link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>

</head>
<body>
    <nav class="white" role="navigation">
        <div class="nav-wrapper container">
            <a id="logo-container" href="#/" class="brand-logo">Js Users</a>
            <ul class="right hide-on-med-and-down">
                <li><a href="#/add">Add</a></li>
            </ul>

            <ul id="nav-mobile" class="side-nav">
                <li><a href="#/add">Add</a></li>
            </ul>
            <a href="#" data-activates="nav-mobile" class="button-collapse"><i class="material-icons">menu</i></a>
        </div>
    </nav>

    <div class="container">
        <div ng-view></div>
    </div>

    <script src="node_modules/angular/angular.min.js"></script>
    <script src="node_modules/angular-route/angular-route.min.js"></script>
    <script src="node_modules/jquery/dist/jquery.min.js"></script>
    <script src="node_modules/materialize-css/dist/js/materialize.min.js"></script>

    <script type="text/javascript" src="app/app.js"></script>
    <script type="text/javascript" src="app/main/main.js"></script>
    <script type="text/javascript" src="app/user-data-factory/user-data-factory.js"></script>

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

main.html:

```<code><div class="page-header">
   <h2 id="tables">Pagination in Angular Js</h2>
</div>
<div ng-controller="UsersList">
    <table class="table striped">
        <thead>
            <tr>
                <th>Last Name</th>
                <th>First Name</th>
                <th>Created At</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="user in users">
                <td>{{user.last_name}}</td>
                <td>{{user.first_name}}</td>
                <td>{{user.created_at}}</td>
                <td>{{user.status}}</td>
            </tr>
        </tbody>
    </table>
</div>
</code>```

main.js:

```<code>angular.module('Js-Users-App', []).controller('UsersList', UsersList);

function UsersList($scope){
    $scope.users = [];

    userDataFactory.userList().then(function(response) {
        $scope.users = response.data;
    });
}
</code>```

user-data-factory.js:

```<code>angular.module('Js-Users-App').factory('userDataFactory', userDataFactory);

function userDataFactory($http) {
    return {
        userList: userList
    };

    function userList() {
        return $http.get("users.json").then(complete).catch(failed);
    }

    function complete(response) {
        return response;
    }

    function failed(error) {
        console.log(error.statusText);
    }
}
</code>```

app.js:

```<code>var app = angular.module("Js-Users-App", ["ngRoute"]).config(config);

function config($routeProvider) {

    $routeProvider
    .when("/", {
      templateUrl: "app/main/main.html"
    })
    .when("/add", {
      templateUrl: "app/addUser/addUser.html"
    })
    .otherwise({
      redirectTo: "/"
    });
}
</code>```

I have started a server, but the application is showing only the navigation bar, without the table. I've also checked the console, but it doesn't show any error or warning. Moreover, I've tried to print some messages on with console.log, however, no message is shown.
The application is running on a simple web server, started with python -m SimpleHTTPServer.
I've checked everywhere, but it doesn't seem there is any typo. Also, the paths of the files seem to be correct.
Where do you think is the problem? I'm still new to AngularJs, so, probably, I can't debug properly. Thanks.

答:
As said in comments, you need to inject userDataFactory as a dependency in your controller.

And then, don't forget to inject dependencies with $inject.

Additionnal point, no need to specify an array of dependencies injection in your module usage. angular.module('Js-Users-App', []) becomes     angular.module('Js-Users-App').

```<code>angular.module('Js-Users-App').controller('UsersList', UsersList);

UsersList.$inject = ['$scope', 'userDataFactory'];

function UsersList($scope, userDataFactory){
    $scope.users = [];

    userDataFactory.userList().then(function(response) {
        $scope.users = response.data;
    });
}
</code>```

Title: Angular Controller doesn't seem to work

Body:
I'm building a simple Sigle Page Application with AngularJs, which retrieves data stored on a server-based application.
Below are the files I'm using:

index.html:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Js Users</title>

    <link rel="stylesheet" href="node_modules/materialize-css/dist/css/materialize.min.css">

    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    <link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>

            Js Users

Add

Add

            menu

main.html:

Pagination in Angular Js

                Last Name
                First Name
                Created At
                Status

                {{user.last_name}}
                {{user.first_name}}
                {{user.created_at}}
                {{user.status}}

main.js:

angular.module('Js-Users-App', []).controller('UsersList', UsersList);

function UsersList($scope){
    $scope.users = [];

    userDataFactory.userList().then(function(response) {
        $scope.users = response.data;
    });
}

user-data-factory.js:

angular.module('Js-Users-App').factory('userDataFactory', userDataFactory);

function userDataFactory($http) {
    return {
        userList: userList
    };

    function userList() {
        return $http.get("users.json").then(complete).catch(failed);
    }

    function complete(response) {
        return response;
    }

    function failed(error) {
        console.log(error.statusText);
    }
}

app.js:

var app = angular.module("Js-Users-App", ["ngRoute"]).config(config);

function config($routeProvider) {

    $routeProvider
    .when("/", {
      templateUrl: "app/main/main.html"
    })
    .when("/add", {
      templateUrl: "app/addUser/addUser.html"
    })
    .otherwise({
      redirectTo: "/"
    });
}

I have started a server, but the application is showing only the navigation bar, without the table. I've also checked the console, but it doesn't show any error or warning. Moreover, I've tried to print some messages on with console.log, however, no message is shown.
The application is running on a simple web server, started with python -m SimpleHTTPServer.
I've checked everywhere, but it doesn't seem there is any typo. Also, the paths of the files seem to be correct.
Where do you think is the problem? I'm still new to AngularJs, so, probably, I can't debug properly. Thanks.

Body:
As said in comments, you need to inject userDataFactory as a dependency in your controller.

And then, don't forget to inject dependencies with $inject.

Additionnal point, no need to specify an array of dependencies injection in your module usage. angular.module('Js-Users-App', []) becomes     angular.module('Js-Users-App').

angular.module('Js-Users-App').controller('UsersList', UsersList);

UsersList.$inject = ['$scope', 'userDataFactory'];

function UsersList($scope, userDataFactory){
    $scope.users = [];

    userDataFactory.userList().then(function(response) {
        $scope.users = response.data;
    });
}


答: Try changing your file encoding to UTF-8. Notepad++, SciTE, PhpStorm and many others can do it.</p>

Title: Can't get php/html pages to display characters with accents (é, á ) correctly


问:
How do I receive this code in php? And how do I consume it?
I'm working on a website project to consume a web service, how do I receive this in php and how do I consume it? Thank you for helping out. I need to connect to their API, send the XML file genrerated in my website and then receive the response. http://www.safaricom.co.ke/business/corporate/m-pesa-payments-services/m-pesa-api for the api</p>

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:c2b="http://cps.huawei.com/cpsinterface/c2bpayment">
   <soapenv:Header/>
   <soapenv:Body>
      <c2b:C2BPaymentConfirmationRequest>
         <TransactionType>PayBill</TransactionType>
         <TransID>1234560000007031</TransID>
         <TransTime>20140227082020</TransTime>
         <TransAmount>123.00</TransAmount>
         <BusinessShortCode>12345</BusinessShortCode>
         <BillRefNumber>TX1001</BillRefNumber>
         <InvoiceNumber></InvoiceNumber>
         <OrgAccountBalance>12345.00</OrgAccountBalance>
<ThirdPartyTransID></ThirdPartyTransID>
<MSISDN>254722703614</MSISDN>
         <KYCInfo>
            <KYCName>[Personal Details][First Name]</KYCName>
            <KYCValue>Hoiyor</KYCValue>
        </KYCInfo>
        <KYCInfo>
            <KYCName>[Personal Details][Middle Name]</KYCName>
            <KYCValue>G</KYCValue>
        </KYCInfo>
        <KYCInfo>
            <KYCName>[Personal Details][Last Name]</KYCName>
            <KYCValue>Chen</KYCValue>
        </KYCInfo>
      </c2b:C2BPaymentConfirmationRequest>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

答: Safaricom has released M-Pesa APIs as RESTful APIs accessible through their developer portal . You need not use the M-Pesa SOAP APIs.</p>

Body:
I'm working on a website project to consume a web service, how do I receive this in php and how do I consume it? Thank you for helping out. I need to connect to their API, send the XML file genrerated in my website and then receive the response. http://www.safaricom.co.ke/business/corporate/m-pesa-payments-services/m-pesa-api for the api

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:c2b="http://cps.huawei.com/cpsinterface/c2bpayment">
   <soapenv:Header/>
   <soapenv:Body>
      <c2b:C2BPaymentConfirmationRequest>
         <TransactionType>PayBill</TransactionType>
         <TransID>1234560000007031</TransID>
         <TransTime>20140227082020</TransTime>
         <TransAmount>123.00</TransAmount>
         <BusinessShortCode>12345</BusinessShortCode>
         <BillRefNumber>TX1001</BillRefNumber>
         <InvoiceNumber></InvoiceNumber>
         <OrgAccountBalance>12345.00</OrgAccountBalance>
<ThirdPartyTransID></ThirdPartyTransID>
<MSISDN>254722703614</MSISDN>
         <KYCInfo>
            <KYCName>[Personal Details][First Name]</KYCName>
            <KYCValue>Hoiyor</KYCValue>
        </KYCInfo>
        <KYCInfo>
            <KYCName>[Personal Details][Middle Name]</KYCName>
            <KYCValue>G</KYCValue>
        </KYCInfo>
        <KYCInfo>
            <KYCName>[Personal Details][Last Name]</KYCName>
            <KYCValue>Chen</KYCValue>
        </KYCInfo>
      </c2b:C2BPaymentConfirmationRequest>
   </soapenv:Body>
</soapenv:Envelope>


问:
load image from url in tableview cell from alamofire swift
I am trying to load image from json using Alomofire and swiftyJSON. Json is dictionary:

```<code>{"name": {"image": "https://...",}}
</code>```

Alamorefire and SwiftyJSON

```<code>var imageLoad: String!

Alamofire.request(.GET, url).responseJSON { (response) -> Void in
    if let value = response.result.value {
    let json = JSON(value)

    if let jsonDict = json.dictionary {

        let image = jsonDict["name"]!["image"].stringValue
        print(image) // https://....
        self.imageLoad = image
    }
    self.tableView.reloadData()
    }
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TVCell

// Configure the cell...

cell.imageTableView.image = UIImage(named: imageLoad) // not working "fatal error: unexpectedly found nil while unwrapping an Optional value"
</code>```

If anyone can help? If there is another way feel free to write.

答:
I share a code implemented using Swift 3 and AlamofireImage:

```<code>import UIKit
import AlamofireImage

class MovieViewCell: UICollectionViewCell {

@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var overviewLabel: UILabel!
@IBOutlet weak var posterView: UIImageView!

 func configure(for movie: Movie) {
    titleLabel.text = movie.title
    overviewLabel.text = movie.overview

    let url = URL(string: movie.poster_path!)!
    posterView.af_setImage(withURL: url)
 }

 override func prepareForReuse() {
    super.prepareForReuse()

    posterView.af_cancelImageRequest()
    posterView.image = nil
 }
}
</code>```

Also, you will need Cocoapods:

```<code>platform :ios, '10.0'

inhibit_all_warnings!
use_frameworks!

target 'MovieApp' do
  pod 'Alamofire', '~> 4.5'
  pod 'AlamofireImage', '~> 3.3'
end
</code>```

Official documentation AlamofireImage and an ImageCell.swift example

Body:
I am trying to load image from json using Alomofire and swiftyJSON. Json is dictionary:

{"name": {"image": "https://...",}}

Alamorefire and SwiftyJSON

var imageLoad: String!

Alamofire.request(.GET, url).responseJSON { (response) -> Void in
    if let value = response.result.value {
    let json = JSON(value)

    if let jsonDict = json.dictionary {

        let image = jsonDict["name"]!["image"].stringValue
        print(image) // https://....
        self.imageLoad = image
    }
    self.tableView.reloadData()
    }
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TVCell

// Configure the cell...

cell.imageTableView.image = UIImage(named: imageLoad) // not working "fatal error: unexpectedly found nil while unwrapping an Optional value"

If anyone can help? If there is another way feel free to write.

Body:
I share a code implemented using Swift 3 and AlamofireImage:

import UIKit
import AlamofireImage

class MovieViewCell: UICollectionViewCell {

@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var overviewLabel: UILabel!
@IBOutlet weak var posterView: UIImageView!

 func configure(for movie: Movie) {
    titleLabel.text = movie.title
    overviewLabel.text = movie.overview

    let url = URL(string: movie.poster_path!)!
    posterView.af_setImage(withURL: url)
 }

 override func prepareForReuse() {
    super.prepareForReuse()

    posterView.af_cancelImageRequest()
    posterView.image = nil
 }
}

Also, you will need Cocoapods:

platform :ios, '10.0'

inhibit_all_warnings!
use_frameworks!

target 'MovieApp' do
  pod 'Alamofire', '~> 4.5'
  pod 'AlamofireImage', '~> 3.3'
end

Official documentation AlamofireImage and an ImageCell.swift example


问:
Java- String index out of bounds exception " String index out of Range"
I am new to java, and going to bite the bullet by asking what is I am sure, a dumb question. I created some methods, and simply wanted to call them in main. I am getting an error for the while loop in the main method. The compiler is saying " Exception in thread main java.lang.StringIndexOutOfBoundsException: String index out of range:0 at java.lang.String.charAt(String.java:686) at Project3.main(Project3.java:61)

Any help would be greatly appreciated. Thanks. Full Code is below:

```<code>import javax.swing.JOptionPane;
import java.util.Scanner;
public class Project3
{
public static void main(String[] args)
{
 int iScore1;  //first variable input by user to calc average
 int iScore2;  //second variable input by user to calc average
 int iScore3;  //third variable input by user to calc average
 double dAverage; //returned average from the three test scores
 char cLetterGrade; //letter grade associated with the average
 double dGPA;  //the GPA associated with the letter grade
 char cIterate = 'Y';  // loop check
 String strAgain;   //string user inputs after being asked to run again

 System.out.print(createWelcomeMessage());

 //pause in program
 pressAnyKey();

 while (cIterate == 'Y')
 {
 //prompt user for test scores
 System.out.print("\n\nPlease enter the first test score: ");
 Scanner keys = new Scanner(System.in);
 iScore1 = keys.nextInt();

 System.out.print("\nPlease enter the second test score: ");
 iScore2 = keys.nextInt();

 System.out.print("\nPlease enter the third test score: ");
 iScore3 = keys.nextInt();

 //calculate average from the three test scores
 dAverage = calcAverage(iScore1, iScore2,iScore3);
 System.out.print("\nThe average of the three scores is: " + dAverage);

 //pause in program
 pressAnyKey();

 //get letter grade associated with the average
 cLetterGrade = getLetterGrade(dAverage);
 System.out.print("\nThe letter grade associated with the average is " + cLetterGrade);

 //pause in program
 pressAnyKey();

 //get the GPA associated with the letter grade
 dPGA = calcGPA(cLetterGrade);
 System.out.print("\nThe GPA associated with the GPA is "+ dGPA);

 //pause in program
 pressAnyKey();

 System.out.print("\nDo you want to run again?(Y or N):_\b");
 strAgain = keys.nextLine;
 strAgain = strAgain.toUpperCase();
 cIterate = strAgain.charAt(0);
 }//end while

 //display ending message to user
 System.out.print(createEndingMessage());

 }//end main method
}//end class Project3

public static String createWelcomeMessage()
{
 String strWelcome;
 strWelcome = "Why hello there!\n";
 return strWelcome;
}//end createWelcomeMessage()

public static String createEndingMessage()
{
 String strSalutation;
 strSalutation = "See you later!\n";
 return strSalutation;
}//end createEndingMessage()

public static void pressAnyKey()
{
 JOptionPane.showMessageDialog(null, "Press any key to continue: ");
}//end pressAnyKey()

public static int getTestSCore()
{
 int iScore;
 System.out.print("Enter a test score: ");
 Scanner keys = new Scanner(System.in);
 iScore = keys.nextInt();
 return iScore;
}//end getTestSCore()

public static int calcAverage(int iNum1, int iNum2, int iNum3)
{
 double dAverage;
 dAverage = ((double)iNum1 + (double)iNum2 + (double)iNum3) / (double)3.0;
 return dAverage;
}//end calcAverage(int iNum1, int iNum2, int iNum3)

public static char getLetterGrade(double dGrade)
{
 char cLetter;

 if (dGrade <60)
 {
  cLetter = 'F';
 }
 else if (dGrade >=60 && dGrade <70)
 {
  cLetter = 'D';
 }
 else if (dGrade >=70 && dGrade <80)
 {
  cLetter = 'C';
 }
 else if (dGrade >=80 && dGrade <90)
 {
  cLetter = 'B';
 }
 else if (dGrade >=90)
 {
  cLetter = 'A';
 }

 return cLetter;
}//end getLetterGrade(double dGrade)

public static double calcGPA(char cLetterGrade)
{
 double dGPA;

 if (cLetterGrade == 'A')
 {
  dGPA = 4.0;
 }
 else if (cLetterGrade == 'B')
 {
  dGPA = 3.0;
 }
 else if (cLetterGrade == 'C')
 {
  dGPA = 2.0;
 }
 else if (cLetterGrade == 'D')
 {
  dGPA = 1.0;
 }
 else
 {
  dGPA = 0.0;
 }
 return dGPA;
}//end calcGPA(char cLetterGrade)
</code>```

答: If you move line 67 or so, it's the line that ends the class. Move it to the end, and that brings it down to three errors. One of those three errors is a misspelling, the one about keys.nextLine needs ()  --> keys.nextLine()   and the last error is that the method header returns an int, not a double. Doing this does generate another error, but if you set cLetter to a space in single quotes, ' ' then the code compiles.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am new to java, and going to bite the bullet by asking what is I am sure, a dumb question. I created some methods, and simply wanted to call them in main. I am getting an error for the while loop in the main method. The compiler is saying " Exception in thread main java.lang.StringIndexOutOfBoundsException: String index out of range:0 at java.lang.String.charAt(String.java:686) at Project3.main(Project3.java:61)

Any help would be greatly appreciated. Thanks. Full Code is below:

import javax.swing.JOptionPane;
import java.util.Scanner;
public class Project3
{
public static void main(String[] args)
{
 int iScore1;  //first variable input by user to calc average
 int iScore2;  //second variable input by user to calc average
 int iScore3;  //third variable input by user to calc average
 double dAverage; //returned average from the three test scores
 char cLetterGrade; //letter grade associated with the average
 double dGPA;  //the GPA associated with the letter grade
 char cIterate = 'Y';  // loop check
 String strAgain;   //string user inputs after being asked to run again

 System.out.print(createWelcomeMessage());

 //pause in program
 pressAnyKey();

 while (cIterate == 'Y')
 {
 //prompt user for test scores
 System.out.print("\n\nPlease enter the first test score: ");
 Scanner keys = new Scanner(System.in);
 iScore1 = keys.nextInt();

 System.out.print("\nPlease enter the second test score: ");
 iScore2 = keys.nextInt();

 System.out.print("\nPlease enter the third test score: ");
 iScore3 = keys.nextInt();

 //calculate average from the three test scores
 dAverage = calcAverage(iScore1, iScore2,iScore3);
 System.out.print("\nThe average of the three scores is: " + dAverage);

 //pause in program
 pressAnyKey();

 //get letter grade associated with the average
 cLetterGrade = getLetterGrade(dAverage);
 System.out.print("\nThe letter grade associated with the average is " + cLetterGrade);

 //pause in program
 pressAnyKey();

 //get the GPA associated with the letter grade
 dPGA = calcGPA(cLetterGrade);
 System.out.print("\nThe GPA associated with the GPA is "+ dGPA);

 //pause in program
 pressAnyKey();

 System.out.print("\nDo you want to run again?(Y or N):_\b");
 strAgain = keys.nextLine;
 strAgain = strAgain.toUpperCase();
 cIterate = strAgain.charAt(0);
 }//end while

 //display ending message to user
 System.out.print(createEndingMessage());

 }//end main method
}//end class Project3

public static String createWelcomeMessage()
{
 String strWelcome;
 strWelcome = "Why hello there!\n";
 return strWelcome;
}//end createWelcomeMessage()

public static String createEndingMessage()
{
 String strSalutation;
 strSalutation = "See you later!\n";
 return strSalutation;
}//end createEndingMessage()

public static void pressAnyKey()
{
 JOptionPane.showMessageDialog(null, "Press any key to continue: ");
}//end pressAnyKey()

public static int getTestSCore()
{
 int iScore;
 System.out.print("Enter a test score: ");
 Scanner keys = new Scanner(System.in);
 iScore = keys.nextInt();
 return iScore;
}//end getTestSCore()

public static int calcAverage(int iNum1, int iNum2, int iNum3)
{
 double dAverage;
 dAverage = ((double)iNum1 + (double)iNum2 + (double)iNum3) / (double)3.0;
 return dAverage;
}//end calcAverage(int iNum1, int iNum2, int iNum3)

public static char getLetterGrade(double dGrade)
{
 char cLetter;

 if (dGrade <60)
 {
  cLetter = 'F';
 }
 else if (dGrade >=60 && dGrade <70)
 {
  cLetter = 'D';
 }
 else if (dGrade >=70 && dGrade <80)
 {
  cLetter = 'C';
 }
 else if (dGrade >=80 && dGrade <90)
 {
  cLetter = 'B';
 }
 else if (dGrade >=90)
 {
  cLetter = 'A';
 }

 return cLetter;
}//end getLetterGrade(double dGrade)

public static double calcGPA(char cLetterGrade)
{
 double dGPA;

 if (cLetterGrade == 'A')
 {
  dGPA = 4.0;
 }
 else if (cLetterGrade == 'B')
 {
  dGPA = 3.0;
 }
 else if (cLetterGrade == 'C')
 {
  dGPA = 2.0;
 }
 else if (cLetterGrade == 'D')
 {
  dGPA = 1.0;
 }
 else
 {
  dGPA = 0.0;
 }
 return dGPA;
}//end calcGPA(char cLetterGrade)


问:
Xcode 8.2: Unable to load configuration data from specified path / permission error in Mac OSX App:
I have a Mac OSX app that I have previously been able to test - however when I run tests now - it will work once and then fail with the error below in the console.  I need to do some drastic things to get it working:

If I

change the location of my Derived Data folder

and clean build folder - then it will usually work again once or twice before but when I run tests again it will happen again.

Any ideas of what I can do to fix it permanently - below is pretty much Greek to me..

I have tried the following:

moving the derived data into Documents

installing new Xcode from Appstore.

Deleting and re-adding Certificates and profiles

2017-01-15 16:41:51.247064 XXXXXX[51736:892136] Unable to load
  configuration data from specified path
  /var/folders/59/7ylv57053bv3c0rbbcc1mcg40000gp/T/com.apple.dt.XCTest/FDF2A461-45D7-4E64-B650-602DF0725CA7/remote-container/tmp/XXXXXXTests-FDF2A461-45D7-4E64-B650-602DF0725CA7.xctestconfiguration;
  error: You don’t have permission. 2017-01-15 16:41:51.247221
  XXXXXX[51736:892136] IDEBundleInjection Arguments: (
      "/Users/XXXXXX/XXXXXX/XXXXXX/XXXXXX-eghnritsumpbbqgylbzrxqfximew/Build/Products/Debug/XXXXXX.app/Contents/MacOS/XXXXXX",
      "-NSTreatUnknownArgumentsAsOpen",
      NO,
      "-ApplePersistenceIgnoreState",
      YES ) 2017-01-15 16:41:51.248336 XXXXXX[51736:892136] IDEBundleInjection Environment: {
      "APP_SANDBOX_CONTAINER_ID" = "com.XXXXXX.XXXXXX";
      "Apple_PubSub_Socket_Render" = "/private/tmp/com.apple.launchd.hKPiBBDAAG/Render";
      "CFFIXED_USER_HOME" = "/Users/XXXXX/Library/Containers/com.XXXXXX.XXXXXX/Data";
      "DTX_CONNECTION_SERVICES_PATH" = "/Applications/Xcode.app/Contents/SharedFrameworks/DTXConnectionServices.framework";
      "DYLD_FRAMEWORK_PATH" = "/Users/XXXXX/XXX/XXXXXXX/XXXXXX-eghnritsumpbbqgylbzrxqfximew/Build/Products/Debug:/Users/XXXXX/XXX/XXXXXXX/XXXXXX-eghnritsumpbbqgylbzrxqfximew/Build/Products/Debug:/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Frameworks";
      "DYLD_INSERT_LIBRARIES" = "";
      "DYLD_LIBRARY_PATH" = "/Users/XXXXX/XXX/XXXXXXX/XXXXXX-eghnritsumpbbqgylbzrxqfximew/Build/Products/Debug:/Users/XXXXX/XXX/XXXXXXX/XXXXXX-eghnritsumpbbqgylbzrxqfximew/Build/Products/Debug:/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Frameworks";
      HOME = "/Users/XXXXX/Library/Containers/com.grant.XXXXXX/Data";
      LOGNAME = XXXXX;
      MallocNanoZone = 1;
      NSUnbufferedIO = YES;
      "OS_ACTIVITY_DT_MODE" = YES;
      PATH = "/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin";
      PWD = "/Users/XXXXX/XXX/XXXXXXX/XXXXXX-eghnritsumpbbqgylbzrxqfximew/Build/Products/Debug";
      SHELL = "/bin/bash";
      "SSH_AUTH_SOCK" = "/private/tmp/com.apple.launchd.dNK7oacOAX/Listeners";
      TMPDIR = "/var/folders/59/7ylv57053bv3c0rbbcc1mcg40000gp/T/com.grant.XXXXXX/";
      USER = XXXXX;
      XCInjectBundleInto = "/Users/XXXXX/XXX/XXXXXXX/XXXXXX-eghnritsumpbbqgylbzrxqfximew/Build/Products/Debug/XXXXXX.app/Contents/MacOS/XXXXXX";
      "XCODE_DBG_XPC_EXCLUSIONS" = "com.apple.dt.xctestSymbolicator";
      XCTestConfigurationFilePath = "/var/folders/59/7ylv57053bv3c0rbbcc1mcg40000gp/T/com.apple.dt.XCTest/FDF2A461-45D7-4E64-B650-602DF0725CA7/remote-container/tmp/XXXXXXTests-FDF2A461-45D7-4E64-B650-602DF0725CA7.xctestconfiguration";
      "XPC_FLAGS" = 0x0;
      "XPC_SERVICE_NAME" = "com.apple.dt.Xcode.23100";
      "__CF_USER_TEXT_ENCODING" = "0x1F6:0x0:0x2";
      "__XCODE_BUILT_PRODUCTS_DIR_PATHS" = "/Users/XXXXX/XXX/XXXXXXX/XXXXXX-eghnritsumpbbqgylbzrxqfximew/Build/Products/Debug";
      "__XPC_DYLD_FRAMEWORK_PATH" = "/Users/XXXXX/XXX/XXXXXXX/XXXXXX-eghnritsumpbbqgylbzrxqfximew/Build/Products/Debug";
      "__XPC_DYLD_LIBRARY_PATH" = "/Users/XXXXX/XXX/XXXXXXX/XXXXXX-eghnritsumpbbqgylbzrxqfximew/Build/Products/Debug";
  }

答:
In Xcode 9 I found a solution, that worked for me.

Go to Xcode > File > Project Settings... (or Workspace Settings...)

Select New Build System (Preview) as Build System under Shared Settings.

Make sure to select Use Shared Setting under Per-User Project Settings.


问:
HTML Table not full width td
For some reason I can not get the td with 100% inside the table and align the text as center.

How can I make the  full width, so it full the 600px of the table obove?

JSFIDDLE: https://jsfiddle.net/61s1cdyo/1/

CODE:

```<code><table class="table-bestelling-content" cellpadding="0" cellspacing="0" border="0" width="100%" style="background-color:#ffffff">
  <tr class="details">
      <td align="center">
      <table  class="table-bestelling-content" cellpadding="0" cellspacing="0" border="0" width="100%" style="background-color:#ffffff; max-width: 600px; display: block;">
        <tr align="center" class="header">
              <td class="order-details">
                    <h1 style="text-align: left; display: table-cell; padding: 10px 0px;">ORDER DETAILS</h1>
                </td>
        </tr>
      </table>
    </td>
  </tr>
</table>
</code>```

答:
There is a max-width: 600px inline setting for the nested table. If you erase that, it's 100% wide:

https://jsfiddle.net/b594a5d5/1/

Title: HTML Table not full width td

Body:
For some reason I can not get the td with 100% inside the table and align the text as center.

How can I make the  full width, so it full the 600px of the table obove?

JSFIDDLE: https://jsfiddle.net/61s1cdyo/1/

CODE:

ORDER DETAILS


问:
Getting expression too complex error .please correct me if i have done thing wrong
```<code>let b0 = UInt32(block[block.startIndex + 0 + (0 << 2)]) << 0 | UInt32(block[block.startIndex + 1 + (0 << 2)]) << 8 | UInt32(block[block.startIndex + 2 + (0 << 2)]) << 16
        b0 = b0 | UInt32(block[block.startIndex + 3 + (0 << 2)]) << 24
    let  b1 = UInt32(block[block.startIndex + 0 + (1 << 2)]) << 0 | UInt32(block[block.startIndex + 1 + (1 << 2)]) << 8 | UInt32(block[block.startIndex + 2 + (1 << 2)]) << 16
        b1 = b1 | UInt32(block[block.startIndex + 3 + (1 << 2)]) << 24
    let b2 = UInt32(block[block.startIndex + 0 + (2 << 2)]) << 0 | UInt32(block[block.startIndex + 1 + (2 << 2)]) << 8 | UInt32(block[block.startIndex + 2 + (2 << 2)]) << 16
        b2 = b2 | UInt32(block[block.startIndex + 3 + (2 << 2)]) << 24
    let b3 = UInt32(block[block.startIndex + 0 + (3 << 2)]) << 0 | UInt32(block[block.startIndex + 1 + (3 << 2)]) << 8 | UInt32(block[block.startIndex + 2 + (3 << 2)]) << 16
        b3 = b3 | UInt32(block[block.startIndex + 3 + (3 << 2)]) << 24
</code>```

答:
If you just format this code properly, you'll see there's a very clear pattern:

```<code>let start = block.startIndex

let b0 = UInt32(block[start + 0 + (0 << 2)]) << 0
       | UInt32(block[start + 1 + (0 << 2)]) << 8
       | UInt32(block[start + 2 + (0 << 2)]) << 16
       | UInt32(block[start + 3 + (0 << 2)]) << 24

let  b1 = UInt32(block[start + 0 + (1 << 2)]) << 0
        | UInt32(block[start + 1 + (1 << 2)]) << 8
        | UInt32(block[start + 2 + (1 << 2)]) << 16
        | UInt32(block[start + 3 + (1 << 2)]) << 24

let b2 = UInt32(block[start + 0 + (2 << 2)]) << 0
       | UInt32(block[start + 1 + (2 << 2)]) << 8
       | UInt32(block[start + 2 + (2 << 2)]) << 16
       | UInt32(block[start + 3 + (2 << 2)]) << 24

let b3 = UInt32(block[start + 0 + (3 << 2)]) << 0
       | UInt32(block[start + 1 + (3 << 2)]) << 8
       | UInt32(block[start + 2 + (3 << 2)]) << 16
       | UInt32(block[start + 3 + (3 << 2)]) << 24
</code>```

Each b constant is just the numbers 0...3 transformed in similar ways, all bitwise-OR'ed together. Sounds like a job for map/reduce:

```<code>let start = block.startIndex
let b0 = (0...3).lazy.map{ UInt32(block[start + $0 + (0 << $0)]) << $0 * 8 }.reduce(0, |)
let b1 = (0...3).lazy.map{ UInt32(block[start + $0 + (1 << $0)]) << $0 * 8 }.reduce(0, |)
let b2 = (0...3).lazy.map{ UInt32(block[start + $0 + (2 << $0)]) << $0 * 8 }.reduce(0, |)
let b3 = (0...3).lazy.map{ UInt32(block[start + $0 + (3 << $0)]) << $0 * 8 }.reduce(0, |)
</code>```

This can be even further simplified, if you made a b array with 4 elements, rather than 4 seperate b# variables:

```<code>let start = block.startIndex
let b = (0...3).map{ x -> UInt32 in
    fatalError("I don't know what the number x represents, so I just named it x. Give it a better name.")
    return (0...3).lazy
                  .map{ UInt32(block[start + $0 + (x << $0)]) << $0*8 }
                  .reduce(0, |)
}
</code>```

Body:
If you just format this code properly, you'll see there's a very clear pattern:

let start = block.startIndex

let b0 = UInt32(block[start + 0 + (0 << 2)]) << 0
       | UInt32(block[start + 1 + (0 << 2)]) << 8
       | UInt32(block[start + 2 + (0 << 2)]) << 16
       | UInt32(block[start + 3 + (0 << 2)]) << 24

let  b1 = UInt32(block[start + 0 + (1 << 2)]) << 0
        | UInt32(block[start + 1 + (1 << 2)]) << 8
        | UInt32(block[start + 2 + (1 << 2)]) << 16
        | UInt32(block[start + 3 + (1 << 2)]) << 24

let b2 = UInt32(block[start + 0 + (2 << 2)]) << 0
       | UInt32(block[start + 1 + (2 << 2)]) << 8
       | UInt32(block[start + 2 + (2 << 2)]) << 16
       | UInt32(block[start + 3 + (2 << 2)]) << 24

let b3 = UInt32(block[start + 0 + (3 << 2)]) << 0
       | UInt32(block[start + 1 + (3 << 2)]) << 8
       | UInt32(block[start + 2 + (3 << 2)]) << 16
       | UInt32(block[start + 3 + (3 << 2)]) << 24

Each b constant is just the numbers 0...3 transformed in similar ways, all bitwise-OR'ed together. Sounds like a job for map/reduce:

let start = block.startIndex
let b0 = (0...3).lazy.map{ UInt32(block[start + $0 + (0 << $0)]) << $0 * 8 }.reduce(0, |)
let b1 = (0...3).lazy.map{ UInt32(block[start + $0 + (1 << $0)]) << $0 * 8 }.reduce(0, |)
let b2 = (0...3).lazy.map{ UInt32(block[start + $0 + (2 << $0)]) << $0 * 8 }.reduce(0, |)
let b3 = (0...3).lazy.map{ UInt32(block[start + $0 + (3 << $0)]) << $0 * 8 }.reduce(0, |)

This can be even further simplified, if you made a b array with 4 elements, rather than 4 seperate b# variables:

let start = block.startIndex
let b = (0...3).map{ x -> UInt32 in
    fatalError("I don't know what the number x represents, so I just named it x. Give it a better name.")
    return (0...3).lazy
                  .map{ UInt32(block[start + $0 + (x << $0)]) << $0*8 }
                  .reduce(0, |)
}


问:
Should i create a new route or have a variable to decide what operation to do?
I am making a route for showing transactions to the users now for this, I have a route transactions but I am using this route for showing filtered transactions.

Now the question is should I make the same route for both fetching All Transactions and Filtered Transactions(It is self-broken into many categories) or should I have a different route for both of them ??

I mean will there be any performance enhancement if I will use any one of the approach or there will be no difference (which I think is).

答:
From a RESTFUL point of view, if your transactions are always splitted into categories, I think you could have

/transactions

for all transactions and

/category/:categoryId/transactions

for the transactions of one category.

But, if you are going to get transactions of several categories at once, probably it will be a better approach to have only

/transactions?categories=categoryId1&categoryId2....

and with query parameters filtering by categories.