问:
How to create a UTF-8 string literal in Visual C++ 2008
In VC++ 2003, I could just save the source file as UTF-8 and all strings were used as is. In other words, the following code would print the strings as is to the console. If the source file was saved as UTF-8 then the output would be UTF-8.

```<code>printf("Chinese (Traditional)");
printf("中国語 (繁体)");
printf("중국어 (번체)");
printf("Chinês (Tradicional)");
</code>```

I have saved the file in UTF-8 format with the UTF-8 BOM. However compiling with VC2008 results in:

```<code>warning C4566: character represented by universal-character-name '\uC911'
cannot be represented in the current code page (932)
warning C4566: character represented by universal-character-name '\uAD6D'
cannot be represented in the current code page (932)
etc.
</code>```

The characters causing these warnings are corrupted. The ones that do fit the locale (in this case 932 = Japanese) are converted to the locale encoding, i.e. Shift-JIS.

I cannot find a way to get VC++ 2008 to compile this for me. Note that it doesn't matter what locale I use in the source file. There doesn't appear to be a locale that says "I know what I'm doing, so don't f$%##ng change my string literals". In particular, the useless UTF-8 pseudo-locale doesn't work.

```<code>#pragma setlocale(".65001")
=> error C2175: '.65001' : invalid locale
</code>```

Neither does "C":

```<code>#pragma setlocale("C")
=> see warnings above (in particular locale is still 932)
</code>```

It appears that VC2008 forces all characters into the specified (or default) locale, and that locale cannot be UTF-8. I do not want to change the file to use escape strings like "\xbf\x11..." because the same source is compiled using gcc which can quite happily deal with UTF-8 files.

Is there any way to specify that compilation of the source file should leave string literals untouched?

To ask it differently, what compile flags can I use to specify backward compatibility with VC2003 when compiling the source file. i.e. do not change the string literals, use them byte for byte as they are.

Update

Thanks for the suggestions, but I want to avoid wchar. Since this app deals with strings in UTF-8 exclusively, using wchar would then require me to convert all strings back into UTF-8 which should be unnecessary. All input, output and internal processing is in UTF-8. It is a simple app that works fine as is on Linux and when compiled with VC2003. I want to be able to compile the same app with VC2008 and have it work.

For this to happen, I need VC2008 to not try to convert it to my local machine's locale (Japanese, 932). I want VC2008 to be backward compatible with VC2003. I want a locale or compiler setting that says strings are used as is, essentially as opaque arrays of char, or as UTF-8. It looks like I might be stuck with VC2003 and gcc though, VC2008 is trying to be too smart in this instance.

答:
I had a similar problem compiling UTF-8 narrow (char) string literals and what I discovered is basically I had to have both a UTF-8 BOM and #pragma execution_character_set("utf-8")[1], or neither the BOM nor the pragma [2]. Using one without the other resulted in an incorrect conversion.

I documented the details at https://github.com/jay/compiler_string_test

[1]: Visual Studio 2012 doesn't support execution_character_set. Visual Studio 2010 and 2015 it works fine, and as you know with the patch in 2008 it works fine.

[2]: Some comments in this thread have noted that using neither the BOM nor the pragma may result in an incorrect conversion for developers using a local codepage that is multibyte (eg Japan).

OwnerDisplayName: brofield

Body:
In VC++ 2003, I could just save the source file as UTF-8 and all strings were used as is. In other words, the following code would print the strings as is to the console. If the source file was saved as UTF-8 then the output would be UTF-8.

printf("Chinese (Traditional)");
printf("中国語 (繁体)");
printf("중국어 (번체)");
printf("Chinês (Tradicional)");

I have saved the file in UTF-8 format with the UTF-8 BOM. However compiling with VC2008 results in:

warning C4566: character represented by universal-character-name '\uC911'
cannot be represented in the current code page (932)
warning C4566: character represented by universal-character-name '\uAD6D'
cannot be represented in the current code page (932)
etc.

The characters causing these warnings are corrupted. The ones that do fit the locale (in this case 932 = Japanese) are converted to the locale encoding, i.e. Shift-JIS.

I cannot find a way to get VC++ 2008 to compile this for me. Note that it doesn't matter what locale I use in the source file. There doesn't appear to be a locale that says "I know what I'm doing, so don't f$%##ng change my string literals". In particular, the useless UTF-8 pseudo-locale doesn't work.

#pragma setlocale(".65001")
=> error C2175: '.65001' : invalid locale

Neither does "C":

#pragma setlocale("C")
=> see warnings above (in particular locale is still 932)

It appears that VC2008 forces all characters into the specified (or default) locale, and that locale cannot be UTF-8. I do not want to change the file to use escape strings like "\xbf\x11..." because the same source is compiled using gcc which can quite happily deal with UTF-8 files.

Is there any way to specify that compilation of the source file should leave string literals untouched?

To ask it differently, what compile flags can I use to specify backward compatibility with VC2003 when compiling the source file. i.e. do not change the string literals, use them byte for byte as they are.

Update

Thanks for the suggestions, but I want to avoid wchar. Since this app deals with strings in UTF-8 exclusively, using wchar would then require me to convert all strings back into UTF-8 which should be unnecessary. All input, output and internal processing is in UTF-8. It is a simple app that works fine as is on Linux and when compiled with VC2003. I want to be able to compile the same app with VC2008 and have it work.

For this to happen, I need VC2008 to not try to convert it to my local machine's locale (Japanese, 932). I want VC2008 to be backward compatible with VC2003. I want a locale or compiler setting that says strings are used as is, essentially as opaque arrays of char, or as UTF-8. It looks like I might be stuck with VC2003 and gcc though, VC2008 is trying to be too smart in this instance.

LastEditorDisplayName: brofield


来源: stackexchange

问:
Why am I reviving AttributeError: 'int' object has no attribute 'find'?
```<code>import smtplib

smtpserver = s.connect("mail.btinternet.com", 465)
SMTP.helo("mail.btinternet.com")
SMTP.ehlo("mail.btinternet.com")

file = open("Combo.txt", "r")

for line in file:
    x = line.split(":")
    user = x[0]
    password = x[1]

    s.login(user, password)
    print("[+] Password Found: %s" % password)

    if smtplib.SMTPAuthenticationError:
      print("Incorrect")
</code>```

Here's my code. It checks a list of email/password combinations from a file to see if it is on a specific server (in my case BT).

But I am having trouble with the library names, I am not sure what to use. I checked on python docs but it wasn't clear enough, if someone can tell me as to what is incorrect I would deeply appreciate it.

Error received.
This will also give me errors for the other incorrect library names

```<code>Traceback (most recent call last):
    File "main.py", line 3, in <module>
    smtpserver = s.connect("mail.btinternet.com", 465)
NameError: name 's' is not defined
exited with non-zero status
</code>```

答:
For your problem I think the reason why as to your libraries are not working properly is because you're calling your imported library inconsistently:

e.g. sometimes you type 's.xxxxx', sometimes you type 'SMTPlib.xxxxx' for your module attributes, you should import smtplib as 's'.

So what does this is it stores the library in a short form named 's', so whenever you call a module or use a function from the library, you don't have to type the full '.smtplib' but instead just type a '.s' extension behind the specific function:

```<code>import smtplib as s

smtpserver = s.connect("mail.btinternet.com", 465)
s.helo("mail.btinternet.com")
s.ehlo("mail.btinternet.com")

file = open("Combo.txt", "r")

for line in file:
    x = line.split(":")
    user = x[0]
    password = x[1]

    s.login(user, password)
    print("[+] Password Found: %s" % password)

if s.SMTPAuthenticationError:
    print("Incorrect")
</code>```

Should fix your problems now. remember to call functions from the specific library name in a consistent manner ('s').

ContentLicense: CC BY-SA 3.0

Body:
import smtplib

smtpserver = s.connect("mail.btinternet.com", 465)
SMTP.helo("mail.btinternet.com")
SMTP.ehlo("mail.btinternet.com")

file = open("Combo.txt", "r")

for line in file:
    x = line.split(":")
    user = x[0]
    password = x[1]

    s.login(user, password)
    print("[+] Password Found: %s" % password)

    if smtplib.SMTPAuthenticationError:
      print("Incorrect")

Here's my code. It checks a list of email/password combinations from a file to see if it is on a specific server (in my case BT).

But I am having trouble with the library names, I am not sure what to use. I checked on python docs but it wasn't clear enough, if someone can tell me as to what is incorrect I would deeply appreciate it.

Error received.
This will also give me errors for the other incorrect library names

Traceback (most recent call last):
    File "main.py", line 3, in <module>
    smtpserver = s.connect("mail.btinternet.com", 465)
NameError: name 's' is not defined
exited with non-zero status

Body:
For your problem I think the reason why as to your libraries are not working properly is because you're calling your imported library inconsistently:

e.g. sometimes you type 's.xxxxx', sometimes you type 'SMTPlib.xxxxx' for your module attributes, you should import smtplib as 's'.

So what does this is it stores the library in a short form named 's', so whenever you call a module or use a function from the library, you don't have to type the full '.smtplib' but instead just type a '.s' extension behind the specific function:

import smtplib as s

smtpserver = s.connect("mail.btinternet.com", 465)
s.helo("mail.btinternet.com")
s.ehlo("mail.btinternet.com")

file = open("Combo.txt", "r")

for line in file:
    x = line.split(":")
    user = x[0]
    password = x[1]

    s.login(user, password)
    print("[+] Password Found: %s" % password)

if s.SMTPAuthenticationError:
    print("Incorrect")

Should fix your problems now. remember to call functions from the specific library name in a consistent manner ('s').


问:
Update using subquery
I have SELECT query as below that need to be inserted into table wifi_user_analytic_dy.

```<code>SELECT
  date(acctstarttime)
, round(avg(acctsessiontime),2)average_connected_ap
, calledstationid
FROM ( SELECT acctstarttime, acctsessiontime, calledstationid
   FROM wifi_radacct
   WHERE acctstoptime <> ''
   and date(acctstarttime)= date_trunc('day', now()) -'1 day'::interval
 )a
group by calledstationid, date(acctstarttime)
</code>```

Sample result based on the query :

```<code>| date       | average_connected_ap | calledstationid |
| 2017-12-06 | 1000                 | publica         |
| 2017-12-06 |  800                 | tumis           |
| 2017-12-06 |  500                 | penyet          |
</code>```

The above query is going to find average connection base on date and ap and update into table wifi_user_analytic_dy. Below is the expected result inside table wifi_user_analytic_dy.

```<code>| date       |  ap      | average_connected_duration_ap |
| 2017-12-06 | publica  |     1000                      |
| 2017-12-06 | tumis    |      800                      |
| 2017-12-06 |  penyet  |      500                      |
</code>```

I am trying copy average_connected_ap data from the SELECT query above and update the table wifi_user_analytic_dy at column average_connected_duration_ap.  The UPDATE query below is not produced the correct result. It is copying the same value to all ap.

How can I correct this update query.

```<code>UPDATE wifi_user_analytic_dy B
SET avg_connected_duration_ap = ( select round(avg(wifi_radacct.acctsessiontime),2)
       from wifi_radacct
       where date(acctstarttime)= date_trunc('day', now()) -'1 day'::interval
       )
FROM wifi_radacct A
WHERE A.calledstationid=B.ap and A.date(acctstarttime)= B.date
;
</code>```

Hope someone can advise me.

答:
you could use a CTE. something like:

```<code>WITH C as
( select
   D.ap, D.bate,
   (select round(avg(wifi_radacct.acctsessiontime),2)
   from wifi_radacct
   where date(acctstarttime)= date_trunc('day', now()) -'1 day'::interval) as V
  FROM wifi_radacct A
  JOIN wifi_user_analytic_dy D
  ON A.calledstationid=D.ap and A.date(acctstarttime)= D.date
)
UPDATE wifi_user_analytic_dy B
SET avg_connected_duration_ap = V
FROM C where A.calledstationid=C.ap and A.date(acctstarttime)=C.date
</code>```

but then you don't need the subquery either:

```<code>WITH C as
( select
   D.ap, D.bate,
   round(avg(A.acctsessiontime),2
   from wifi_radacct
   where date(acctstarttime)= date_trunc('day', now()) -'1 day'::interval) as V
  FROM wifi_radacct A
  JOIN wifi_user_analytic_dy D
  ON A.calledstationid=D.ap and A.date(acctstarttime)= D.date
  GROUP BY D.ap,D.date
)
UPDATE wifi_user_analytic_dy B
SET avg_connected_duration_ap = V
FROM C where A.calledstationid=C.ap and A.date(acctstarttime)=C.date
</code>```

and possibly don't need the join.

Title: Update using subquery

Body:
I have SELECT query as below that need to be inserted into table wifi_user_analytic_dy.

SELECT
  date(acctstarttime)
, round(avg(acctsessiontime),2)average_connected_ap
, calledstationid
FROM ( SELECT acctstarttime, acctsessiontime, calledstationid
   FROM wifi_radacct
   WHERE acctstoptime <> ''
   and date(acctstarttime)= date_trunc('day', now()) -'1 day'::interval
 )a
group by calledstationid, date(acctstarttime)

Sample result based on the query :

| date       | average_connected_ap | calledstationid |
| 2017-12-06 | 1000                 | publica         |
| 2017-12-06 |  800                 | tumis           |
| 2017-12-06 |  500                 | penyet          |

The above query is going to find average connection base on date and ap and update into table wifi_user_analytic_dy. Below is the expected result inside table wifi_user_analytic_dy.

| date       |  ap      | average_connected_duration_ap |
| 2017-12-06 | publica  |     1000                      |
| 2017-12-06 | tumis    |      800                      |
| 2017-12-06 |  penyet  |      500                      |

I am trying copy average_connected_ap data from the SELECT query above and update the table wifi_user_analytic_dy at column average_connected_duration_ap.  The UPDATE query below is not produced the correct result. It is copying the same value to all ap.

How can I correct this update query.

UPDATE wifi_user_analytic_dy B
SET avg_connected_duration_ap = ( select round(avg(wifi_radacct.acctsessiontime),2)
       from wifi_radacct
       where date(acctstarttime)= date_trunc('day', now()) -'1 day'::interval
       )
FROM wifi_radacct A
WHERE A.calledstationid=B.ap and A.date(acctstarttime)= B.date
;

Hope someone can advise me.

Body:
you could use a CTE. something like:

WITH C as
( select
   D.ap, D.bate,
   (select round(avg(wifi_radacct.acctsessiontime),2)
   from wifi_radacct
   where date(acctstarttime)= date_trunc('day', now()) -'1 day'::interval) as V
  FROM wifi_radacct A
  JOIN wifi_user_analytic_dy D
  ON A.calledstationid=D.ap and A.date(acctstarttime)= D.date
)
UPDATE wifi_user_analytic_dy B
SET avg_connected_duration_ap = V
FROM C where A.calledstationid=C.ap and A.date(acctstarttime)=C.date

but then you don't need the subquery either:

WITH C as
( select
   D.ap, D.bate,
   round(avg(A.acctsessiontime),2
   from wifi_radacct
   where date(acctstarttime)= date_trunc('day', now()) -'1 day'::interval) as V
  FROM wifi_radacct A
  JOIN wifi_user_analytic_dy D
  ON A.calledstationid=D.ap and A.date(acctstarttime)= D.date
  GROUP BY D.ap,D.date
)
UPDATE wifi_user_analytic_dy B
SET avg_connected_duration_ap = V
FROM C where A.calledstationid=C.ap and A.date(acctstarttime)=C.date

and possibly don't need the join.


问:
SQL Server 2012 - using select * into along with dynamic SQL

Hi I have the the following code:

```<code>use TSQL2012;
go

if OBJECT_ID('Sales.FreightTotals') is not null drop table
Sales.FreightTotals
go

declare @shipperid as nvarchar(max) ='';
declare @dsql as nvarchar(max);
select @shipperid += quotename(shipperid,'')+',' from sales.Orders group by
shipperid;
set @shipperid = LEFT(@shipperid, LEN(@shipperid)-1)

print @shipperid;

set @dsql='
select empid,'+@shipperid+' from
(select empid, shipperid, freight from Sales.Orders )as d
pivot(sum(freight) for shipperid in('+@shipperid+')) as pvt
order by pvt.empid
'
</code>```

print @dsql

--exec sp_executesql @dsql

```<code>select * into Sales.FreightTotals from @dsql;
</code>```

I am trying to use select * into with dynamic pivot as shown above.If I use

```<code>exec sp_executesql @dsql
</code>```

I get the following result the result i am looking for

```<code>empid       1                     2                     3
----------- --------------------- --------------------- --------------------
1           2194.73               3259.99               3381.92
2           2281.09               4350.20               2065.12
3           2491.74               4258.90               4134.10
4           3129.39               4926.73               3290.02
5           1218.27               1991.84               708.60
6           1049.83               1270.42               1460.22
7           1204.60               3155.18               2305.66
8           1889.27               3297.40               2301.21
9           726.41                1734.19               865.66

(9 rows affected)
</code>```

but if I do
    select * into Sales.FreightTotals from @dsql;

i get:

```<code>Msg 1087, Level 16, State 1, Line 26
Must declare the table variable "@dsql".
</code>```

any suggestion as to why this is the case?

答:
Try the following</p>

```<code>set @dsql='
select empid,'+@shipperid+'
into Sales.FreightTotals -- into is here
from
(select empid, shipperid, freight from Sales.Orders )as d
pivot(sum(freight) for shipperid in('+@shipperid+')) as pvt
order by pvt.empid
'

print @dsql -- print for check

exec sp_executesql @dsql
</code>```

Body:
Hi I have the the following code:

use TSQL2012;
go

if OBJECT_ID('Sales.FreightTotals') is not null drop table
Sales.FreightTotals
go

declare @shipperid as nvarchar(max) ='';
declare @dsql as nvarchar(max);
select @shipperid += quotename(shipperid,'')+',' from sales.Orders group by
shipperid;
set @shipperid = LEFT(@shipperid, LEN(@shipperid)-1)

print @shipperid;

set @dsql='
select empid,'+@shipperid+' from
(select empid, shipperid, freight from Sales.Orders )as d
pivot(sum(freight) for shipperid in('+@shipperid+')) as pvt
order by pvt.empid
'

print @dsql

--exec sp_executesql @dsql

select * into Sales.FreightTotals from @dsql;

I am trying to use select * into with dynamic pivot as shown above.If I use

exec sp_executesql @dsql

I get the following result the result i am looking for

empid       1                     2                     3
----------- --------------------- --------------------- --------------------
1           2194.73               3259.99               3381.92
2           2281.09               4350.20               2065.12
3           2491.74               4258.90               4134.10
4           3129.39               4926.73               3290.02
5           1218.27               1991.84               708.60
6           1049.83               1270.42               1460.22
7           1204.60               3155.18               2305.66
8           1889.27               3297.40               2301.21
9           726.41                1734.19               865.66

(9 rows affected)

but if I do
    select * into Sales.FreightTotals from @dsql;

i get:

Msg 1087, Level 16, State 1, Line 26
Must declare the table variable "@dsql".

any suggestion as to why this is the case?

Body:
Try the following

set @dsql='
select empid,'+@shipperid+'
into Sales.FreightTotals -- into is here
from
(select empid, shipperid, freight from Sales.Orders )as d
pivot(sum(freight) for shipperid in('+@shipperid+')) as pvt
order by pvt.empid
'

print @dsql -- print for check

exec sp_executesql @dsql


问:
Icon in Navigation Drawer always square :-(
How to make icon in my Navigation Drawer rectangle like original size?</p>

答:
Yes, by default if you are using menu resource with items to populate Navigation drawer it will have equal width and height.

Alternatively, you can create your own listview with custom list_item for Navigation Drawer and use it to populate your own data with your Custom UI.

Please refer this link to do so : Android Nav Drawer


问:
Search by zipcode and show data within specific radius?
Hi I have a database of the US, CANADA zipcodes with latitude and longitude.
I would like to implement search to show listings within specified radius.
How can it be done with Linq to Entity, C#

Thank you for examples

答:
This CodeProject article describes a method to calculate the distance between two zip codes and find all other zip codes within a radius of X miles of a specified zip code:

ZIP Code Utility

In the article is an Access database used but what you're going to use as your ORM and database isn't really the tricky thing here.

ContentLicense: CC BY-SA 2.5


问:
How can I use an 'update' function to 'open' and update if the object is not yet open?
My example is a progress bar

In its simplest form a progress bar is

```<code>bar = ProgressBar.Open()
for item in list:
    bar.Update(count, len(list))
</code>```

I would instead like my calling code to be

```<code>for item in list:
    bar.Update(count, len(list))
</code>```

I want my Update() function to Open() a bar for the caller if one is not open.  The caller doesn't need any other access to the bar than to update it so there's no value in having the meter` handle.

How can I retain state to tell if the Update had been previously called?

I could create a global variable and keep track that way, but I have a gut sense there's a Pythonista way of doing it.

Trying again, but in a way that has no application to stumble on.

The base question is:
I have a function that will be called multiple times.
I want to do something different the first time it is called.
How can a function in Python do that?

In C, that of course would be a...
static variable

I'm just now kinda figuring it out as I type, sorry.

========================

I'm sure all these edits are not how stackoverflow is supposed to work. I'm sorry for not getting it right yet, but am very appreciative of the replies.

Despite it sounding like I'm breaking all the rules of good practices, it's when looked at from the CALLER'S point of view that I had hoped to make an impact.

What if the only thing you needed to do to add a progress meter, even for debugging, to your program was make a call to a progress meter update in the location you want to show progress?

That's the underlying motivation.  Slide in 1-line, get something cool for the trouble.

This progress meter was added to my otherwise boring file de-duplicator by adding just the single call:

```<code>msg = f'Deduplicating {idx} of {total_files} files\n' f'{dup_count} Dupes found\n' f'{small_count} Too small'
not_cancelled = sGUI.ProgressBar('De-dupe', msg, idx, total_files)
</code>```

答:
For what you want, you can use a class:

```<code>class ProgressBar:
    def __init__(self):
        self._opened = False
    def Open(self):
        print("Open")
    def Update(self):
        if self._opened:
            print("Update!")
        else:
            self.Open()
            print("set flag")
            self._opened = True
         print("Update")
</code>```

In action:

```<code>In [32]: bar = ProgressBar()

In [33]: bar.Update()
Open
set flag
Update

In [34]: bar.Update()

Update!
</code>```

Note: I copied your casing so as to make it more clear to you, however, the official Python style would be like this:

```<code>class ProgressBar:
    def __init__(self):
        self._opened = False
    def open(self):
        pass # open stuff
    def update(self):
        if self._opened:
            pass # update stuff
        else:
            self.open()
            self._opened = True
</code>```

Using snake_case for everything except the ClassName.

Body:
My example is a progress bar

In its simplest form a progress bar is

bar = ProgressBar.Open()
for item in list:
    bar.Update(count, len(list))

I would instead like my calling code to be

for item in list:
    bar.Update(count, len(list))

I want my Update() function to Open() a bar for the caller if one is not open.  The caller doesn't need any other access to the bar than to update it so there's no value in having the meter` handle.

How can I retain state to tell if the Update had been previously called?

I could create a global variable and keep track that way, but I have a gut sense there's a Pythonista way of doing it.

Trying again, but in a way that has no application to stumble on.

The base question is:
I have a function that will be called multiple times.
I want to do something different the first time it is called.
How can a function in Python do that?

In C, that of course would be a...
static variable

I'm just now kinda figuring it out as I type, sorry.

========================

I'm sure all these edits are not how stackoverflow is supposed to work. I'm sorry for not getting it right yet, but am very appreciative of the replies.

Despite it sounding like I'm breaking all the rules of good practices, it's when looked at from the CALLER'S point of view that I had hoped to make an impact.

What if the only thing you needed to do to add a progress meter, even for debugging, to your program was make a call to a progress meter update in the location you want to show progress?

That's the underlying motivation.  Slide in 1-line, get something cool for the trouble.

This progress meter was added to my otherwise boring file de-duplicator by adding just the single call:

msg = f'Deduplicating {idx} of {total_files} files\n' f'{dup_count} Dupes found\n' f'{small_count} Too small'
not_cancelled = sGUI.ProgressBar('De-dupe', msg, idx, total_files)

Body:
For what you want, you can use a class:

class ProgressBar:
    def __init__(self):
        self._opened = False
    def Open(self):
        print("Open")
    def Update(self):
        if self._opened:
            print("Update!")
        else:
            self.Open()
            print("set flag")
            self._opened = True
         print("Update")

In action:

In [32]: bar = ProgressBar()

In [33]: bar.Update()
Open
set flag
Update

In [34]: bar.Update()

Update!

Note: I copied your casing so as to make it more clear to you, however, the official Python style would be like this:

class ProgressBar:
    def __init__(self):
        self._opened = False
    def open(self):
        pass # open stuff
    def update(self):
        if self._opened:
            pass # update stuff
        else:
            self.open()
            self._opened = True

Using snake_case for everything except the ClassName.


问:
iPhone X not displaying selection screen from start
I am trying to set a selection image to UITabbar item,

Here is the screenshot.

It works fine on all other screens except iPhoneX

How can i make it appear from y = 0

答:
Note:

Use selectionIndicatorImage property to specify a custom selection
  image. Your image is rendered on top of the tab bar but behind the
  contents of the tab bar item itself. The default value of this
  property is nil, which causes the tab bar to apply a default highlight
  to the selected item

If you are using selectionIndicatorImage for certain purpose put this code in TabBarController class, here i have use viewDidLayoutSubviews because of getting dynamic height of tabbar in both landscape and portrait mode.

```<code> override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        print("current height \(tabBar.frame.size.height)")
        let selTab = UIImage(named: "tab1.png")
        let numberOfTabs: CGFloat = 2.0
        let tabSize = CGSize(width: (self.view.frame.width)/numberOfTabs, height: tabBar.frame.size.height)
        UIGraphicsBeginImageContext(tabSize);
        selTab?.draw(in: CGRect(x: 0, y: 0, width: tabSize.width, height: tabSize.height))
        let reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        tabBar.selectionIndicatorImage = reSizeImage
    }
</code>```

Body:
Note:

Use selectionIndicatorImage property to specify a custom selection
  image. Your image is rendered on top of the tab bar but behind the
  contents of the tab bar item itself. The default value of this
  property is nil, which causes the tab bar to apply a default highlight
  to the selected item

If you are using selectionIndicatorImage for certain purpose put this code in TabBarController class, here i have use viewDidLayoutSubviews because of getting dynamic height of tabbar in both landscape and portrait mode.

 override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        print("current height \(tabBar.frame.size.height)")
        let selTab = UIImage(named: "tab1.png")
        let numberOfTabs: CGFloat = 2.0
        let tabSize = CGSize(width: (self.view.frame.width)/numberOfTabs, height: tabBar.frame.size.height)
        UIGraphicsBeginImageContext(tabSize);
        selTab?.draw(in: CGRect(x: 0, y: 0, width: tabSize.width, height: tabSize.height))
        let reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        tabBar.selectionIndicatorImage = reSizeImage
    }


问:
Constraints not working in TableViewCell
I'm learning how to use CoreData to store images, and I'm making a blog reader. I have a view That shows all the info saved as a list and when you click it takes you to that article. My problem is that I can't make TableViewCells look as intended. I have added the constraints and not a single of them is being placed.

Here are my constraints:

And this is the result:

I've deleted them, cleaned, closed xCode, put them again and the same result. Found this answer, checked and nothing. Also this one. In the same project, I have another TableView and it works fine, any ideas why this is happening? Thanks a lot!

答:
It seems like issue not because of constraints. it because of image to solution for this issue

You have two option to solve this

1) Via code

```<code>cell.YOUR_IMAGE_VIEW.clipsToBounds = true
</code>```

2) Via Interface Builder

Hope this will help you

Body:
It seems like issue not because of constraints. it because of image to solution for this issue

You have two option to solve this

1) Via code

cell.YOUR_IMAGE_VIEW.clipsToBounds = true

2) Via Interface Builder

Hope this will help you


问:
onclick attribute vs onclick in script
Why the difference?

document.getElementById('click').onclick = a.replaceChild(c,b) --- replaces the element without me clicking the button

but onclick="a.replaceChild(c,b)" --- replaces the element only after the button is clicked

```<code><div id="container">
<p id="welcome">no greetings yet</p>
<p id="products">oreo ice-cream</p>
</div>

<button id="click" **onclick="a.replaceChild(c,b)"**>CHANGE</button>

    <script>

        var a = document.getElementById('container');

        var b = document.getElementById('welcome');

        var c = document.createElement('h2');
        c.id = 'new';
        c.innerHTML = "WELCOME";

        **document.getElementById('click').onclick = a.replaceChild(c,b);**

    </script>
</code>```

答:
You don't include the parentheses: you'd assign a parameterless function like document.getElementById('foo')=bar;, not like bar().

The way you're assigning it now actually runs it, which means you're assigning the return value from that function, not its name.

The parameters make it slightly trickier than just naming the function without parentheses.

document.getElementById("click").onclick = function(c, b){return a.replacechild(c,b);}

This'll do what you're looking for. JSFiddle

jQuery's .click() is a good alternative if you're interested in solutions that aren't pure basic javascript. Another may be adding an event listener instead in some cases.

Title: onclick attribute vs onclick in script

Body:
Why the difference?

document.getElementById('click').onclick = a.replaceChild(c,b) --- replaces the element without me clicking the button

but onclick="a.replaceChild(c,b)" --- replaces the element only after the button is clicked

no greetings yet

oreo ice-cream

<button id="click" **onclick="a.replaceChild(c,b)"**>CHANGE</button>


问:
cannot input textarea with CKeditor on Codeigniter
when i want to input textarea with CKeditor , the string is Null , but when i delete class="CKeditor" in textarea the string successfully filled.
i have check in controller and database but it does not matter

My Controller

```<code>function AddNews(){
    $data = array(
        'title_news'            => $this->input->post('title_news'),
        'text'                  => $this->input->post('text_news'),
        'date'                  => $this->input->post('date'),
    );
    $insert = $this->m_news->save($data);
    echo json_encode(array("status" => TRUE));
}
</code>```

My View

```<code><form action="#" id="form" class="form-horizontal">
    <input type="hidden" value="" name="id_news"/>
        <div class="form-body">
            <div class="form-group">
                <label class="control-label col-md-3">Title News </label>
                <div class="col-md-9">
                    <input name="title_news" placeholder="Title Name" class="form-control" type="text"><span class="help-block"></span>
                </div>
            </div>

            <div class="form-group">
                <label class="control-label col-md-3">Title News </label>
                <div class="col-md-9">
                    <textarea class="ckeditor"  name="text_news" rows="3" placeholder="Enter text . . . "></textarea><span class="help-block"></span>
                </div>
            </div>

            <div class="form-group">
                <label class="control-label col-md-3">Date</label>
                <div class="col-md-9">
                    <div class="input-group">
                        <input class="form-control date-picker" name="date" type="text" data-date-format="yyyy-mm-dd" placeholder="yyyy-mm-dd" /><span class="input-group-addon"><i class="fa fa-calendar bigger-110"></i></span>
                    </div>
                </div>
            </div>
            <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
        </div>
    </form>
</code>```

My Ajax Input

```<code>function save()
{
    var formData = new FormData($('#form')[0]);
    $.ajax({
        url : "<?php echo base_url('admin-spot/news/AddNews')?>",
        type: "POST",
        data: formData,
        contentType: false,
        processData: false,
        dataType: "JSON",
        redirect: true,
        success: function(data){
            if(data.status){
                $('#modal_form').modal('hide');
            }
            else
            {}

            error: function (jqXHR, textStatus, errorThrown){
                alert('Error adding / update data');
                $('#btnSave').text('save'); //change button text
                $('#btnSave').attr('disabled',false); //set button enable
            }
        });
    }
</code>```

My Model

```<code>function Save($data)
{
    $sql = $this->db->insert($this->table, $data);
    return $sql;
}
</code>```

hello guys,
when I want to input textarea with CKeditor , the string is Null , but when I delete class="CKeditor" in textarea the string successfully filled.
I have check in controller and database but it does not matter

答:
Add this to your script</p>

```<code>function save()
{
    for (instance in CKEDITOR.instances) {
       CKEDITOR.instances[instance].updateElement();
    }
    var formData = new FormData($('#form')[0]);

    $.ajax({
        ....
    });
}
</code>```

Body:
when i want to input textarea with CKeditor , the string is Null , but when i delete class="CKeditor" in textarea the string successfully filled.
i have check in controller and database but it does not matter

My Controller

function AddNews(){
    $data = array(
        'title_news'            => $this->input->post('title_news'),
        'text'                  => $this->input->post('text_news'),
        'date'                  => $this->input->post('date'),
    );
    $insert = $this->m_news->save($data);
    echo json_encode(array("status" => TRUE));
}

My View

<form action="#" id="form" class="form-horizontal">
    <input type="hidden" value="" name="id_news"/>

                Title News

                    <input name="title_news" placeholder="Title Name" class="form-control" type="text">

                Title News

                    <textarea class="ckeditor"  name="text_news" rows="3" placeholder="Enter text . . . "></textarea>

                Date

                        <input class="form-control date-picker" name="date" type="text" data-date-format="yyyy-mm-dd" placeholder="yyyy-mm-dd" />

            <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>

    </form>

My Ajax Input

function save()
{
    var formData = new FormData($('#form')[0]);
    $.ajax({
        url : "<?php echo base_url('admin-spot/news/AddNews')?>",
        type: "POST",
        data: formData,
        contentType: false,
        processData: false,
        dataType: "JSON",
        redirect: true,
        success: function(data){
            if(data.status){
                $('#modal_form').modal('hide');
            }
            else
            {}

            error: function (jqXHR, textStatus, errorThrown){
                alert('Error adding / update data');
                $('#btnSave').text('save'); //change button text
                $('#btnSave').attr('disabled',false); //set button enable
            }
        });
    }

My Model

function Save($data)
{
    $sql = $this->db->insert($this->table, $data);
    return $sql;
}

hello guys,
when I want to input textarea with CKeditor , the string is Null , but when I delete class="CKeditor" in textarea the string successfully filled.
I have check in controller and database but it does not matter

Body:
Add this to your script

function save()
{
    for (instance in CKEDITOR.instances) {
       CKEDITOR.instances[instance].updateElement();
    }
    var formData = new FormData($('#form')[0]);

    $.ajax({
        ....
    });
}


问:
How to navigate within a View Group
Within HTML you can navigate internally within a page using:

```<code><a href="#someElement">Go To Element</a>
</code>```

What is the equivalent in an Android App?

I have an Activity with a lot of text and headlines separating the text pieces. I want the user to be able to click somewhere and thereby navigate to a specific headline, so they don't have to scroll too much themselves.

How can I achieve this?

答:
You can try use

scrollTo() method from ScrollView

and you can get the coordinates of the element using View.getLocationOnScreen() or getLocationInWindow()

like this:

```<code>int[] theCoorndiates = new int[2];

yourView.getLocationOnScreen(theCoordinates);

scrollView.scrollTo(theCoordinates[0], theCoordinates[1]);
</code>```

just adjust them to your code

references:
https://developer.android.com/reference/android/widget/ScrollView.html#scrollTo%28int,%20int%29
https://developer.android.com/reference/android/view/View.html#getLocationOnScreen(int[])

Title: How to navigate within a View Group

Body:
Within HTML you can navigate internally within a page using:

Go To Element

What is the equivalent in an Android App?

I have an Activity with a lot of text and headlines separating the text pieces. I want the user to be able to click somewhere and thereby navigate to a specific headline, so they don't have to scroll too much themselves.

How can I achieve this?

Body:
You can try use

scrollTo() method from ScrollView

and you can get the coordinates of the element using View.getLocationOnScreen() or getLocationInWindow()

like this:

int[] theCoorndiates = new int[2];

yourView.getLocationOnScreen(theCoordinates);

scrollView.scrollTo(theCoordinates[0], theCoordinates[1]);

just adjust them to your code

references:
https://developer.android.com/reference/android/widget/ScrollView.html#scrollTo%28int,%20int%29
https://developer.android.com/reference/android/view/View.html#getLocationOnScreen(int[])


问:
MySQL Workbench - Error in MySQL syntax
The MySQL workbench is a great tool, but you have to keep your head on as it does no error checking whatsoever.

So, it generated this SQL syntax to create a table and it won't work.
And I can't figure out WHY

It gives me this error:

```<code>#1064 - You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version
for the right syntax to use near
') NULL DEFAULT NULL , `maaltijd` TINYINT(1) NOT NULL ,
`cheques` TINYINT(1'
at line 14
</code>```

This is the query:

```<code>    CREATE  TABLE IF NOT EXISTS `nascholing`.`aanvraag` (
      `aanvraagId` INT(11) NOT NULL AUTO_INCREMENT ,
      `userId` BIGINT(20) NOT NULL ,
      `creationDate` DATETIME NULL DEFAULT NULL ,
      `vakGroep` INT(11) NULL DEFAULT NULL ,
      `personeelType` INT(11) NOT NULL ,
      `leeftijd` INT(11) NULL DEFAULT NULL ,
      `thema` VARCHAR(255) NOT NULL ,
      `intern` TINYINT(1) NULL DEFAULT -1 ,
      `duur` INT(11) NOT NULL ,
      `tijdens` INT(11) NULL DEFAULT NULL ,
      `type` INT(11) NULL DEFAULT NULL ,
      `voor` INT(11) NOT NULL ,
      `kost` DOUBLE(11) NULL DEFAULT NULL ,
      `maaltijd` TINYINT(1) NOT NULL ,
      `cheques` TINYINT(1) NOT NULL ,
      `betalingsmethode` INT(11) NOT NULL ,
      `aanschafBoek` TINYINT(1) NOT NULL ,
      `kostBoek` DOUBLE(11) NULL DEFAULT NULL ,
      PRIMARY KEY (`aanvraagId`) ,
      UNIQUE INDEX `aanvraagId_UNIQUE` (`aanvraagId` ASC) ,
      INDEX `fk_aanvraag_user1` (`userId` ASC) ,
      INDEX `fk_aanvraag_duur1` (`duur` ASC) ,
      INDEX `fk_aanvraag_tijdens1` (`tijdens` ASC) ,
      INDEX `fk_aanvraag_type1` (`type` ASC) ,
      INDEX `fk_aanvraag_vakGroep1` (`vakGroep` ASC) ,
      INDEX `fk_aanvraag_voorEmail1` (`voor` ASC) ,
      INDEX `fk_aanvraag_betalingsMethode1` (`betalingsmethode` ASC) ,
      CONSTRAINT `fk_aanvraag_user1`
        FOREIGN KEY (`userId` )
        REFERENCES `nascholing`.`user` (`userId` )
        ON DELETE NO ACTION
        ON UPDATE NO ACTION,
      CONSTRAINT `fk_aanvraag_duur1`
        FOREIGN KEY (`duur` )
        REFERENCES `nascholing`.`duur` (`duurId` )
        ON DELETE NO ACTION
        ON UPDATE NO ACTION,
      CONSTRAINT `fk_aanvraag_tijdens1`
        FOREIGN KEY (`tijdens` )
        REFERENCES `nascholing`.`tijdens` (`tijdensId` )
        ON DELETE NO ACTION
        ON UPDATE NO ACTION,
      CONSTRAINT `fk_aanvraag_type1`
        FOREIGN KEY (`type` )
        REFERENCES `nascholing`.`type` (`typeId` )
        ON DELETE NO ACTION
        ON UPDATE NO ACTION,
      CONSTRAINT `fk_aanvraag_vakGroep1`
        FOREIGN KEY (`vakGroep` )
        REFERENCES `nascholing`.`vakGroep` (`vakGroepId` )
        ON DELETE NO ACTION
        ON UPDATE NO ACTION,
      CONSTRAINT `fk_aanvraag_voorEmail1`
        FOREIGN KEY (`voor` )
        REFERENCES `nascholing`.`voorEmail` (`voorEmailId` )
        ON DELETE NO ACTION
        ON UPDATE NO ACTION,
      CONSTRAINT `fk_aanvraag_betalingsMethode1`
        FOREIGN KEY (`betalingsmethode` )
        REFERENCES `nascholing`.`betalingsMethode` (`betalingsMethodeId` )
        ON DELETE NO ACTION
        ON UPDATE NO ACTION)
    ENGINE = InnoDB
    DEFAULT CHARACTER SET = utf8
    COLLATE = utf8_general_ci;
</code>```

答: Remove the length of the kost column.

Title: MySQL Workbench - Error in MySQL syntax

Body:
The MySQL workbench is a great tool, but you have to keep your head on as it does no error checking whatsoever.

So, it generated this SQL syntax to create a table and it won't work.
And I can't figure out WHY

It gives me this error:

#1064 - You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version
for the right syntax to use near
') NULL DEFAULT NULL , `maaltijd` TINYINT(1) NOT NULL ,
`cheques` TINYINT(1'
at line 14

This is the query:

    CREATE  TABLE IF NOT EXISTS `nascholing`.`aanvraag` (
      `aanvraagId` INT(11) NOT NULL AUTO_INCREMENT ,
      `userId` BIGINT(20) NOT NULL ,
      `creationDate` DATETIME NULL DEFAULT NULL ,
      `vakGroep` INT(11) NULL DEFAULT NULL ,
      `personeelType` INT(11) NOT NULL ,
      `leeftijd` INT(11) NULL DEFAULT NULL ,
      `thema` VARCHAR(255) NOT NULL ,
      `intern` TINYINT(1) NULL DEFAULT -1 ,
      `duur` INT(11) NOT NULL ,
      `tijdens` INT(11) NULL DEFAULT NULL ,
      `type` INT(11) NULL DEFAULT NULL ,
      `voor` INT(11) NOT NULL ,
      `kost` DOUBLE(11) NULL DEFAULT NULL ,
      `maaltijd` TINYINT(1) NOT NULL ,
      `cheques` TINYINT(1) NOT NULL ,
      `betalingsmethode` INT(11) NOT NULL ,
      `aanschafBoek` TINYINT(1) NOT NULL ,
      `kostBoek` DOUBLE(11) NULL DEFAULT NULL ,
      PRIMARY KEY (`aanvraagId`) ,
      UNIQUE INDEX `aanvraagId_UNIQUE` (`aanvraagId` ASC) ,
      INDEX `fk_aanvraag_user1` (`userId` ASC) ,
      INDEX `fk_aanvraag_duur1` (`duur` ASC) ,
      INDEX `fk_aanvraag_tijdens1` (`tijdens` ASC) ,
      INDEX `fk_aanvraag_type1` (`type` ASC) ,
      INDEX `fk_aanvraag_vakGroep1` (`vakGroep` ASC) ,
      INDEX `fk_aanvraag_voorEmail1` (`voor` ASC) ,
      INDEX `fk_aanvraag_betalingsMethode1` (`betalingsmethode` ASC) ,
      CONSTRAINT `fk_aanvraag_user1`
        FOREIGN KEY (`userId` )
        REFERENCES `nascholing`.`user` (`userId` )
        ON DELETE NO ACTION
        ON UPDATE NO ACTION,
      CONSTRAINT `fk_aanvraag_duur1`
        FOREIGN KEY (`duur` )
        REFERENCES `nascholing`.`duur` (`duurId` )
        ON DELETE NO ACTION
        ON UPDATE NO ACTION,
      CONSTRAINT `fk_aanvraag_tijdens1`
        FOREIGN KEY (`tijdens` )
        REFERENCES `nascholing`.`tijdens` (`tijdensId` )
        ON DELETE NO ACTION
        ON UPDATE NO ACTION,
      CONSTRAINT `fk_aanvraag_type1`
        FOREIGN KEY (`type` )
        REFERENCES `nascholing`.`type` (`typeId` )
        ON DELETE NO ACTION
        ON UPDATE NO ACTION,
      CONSTRAINT `fk_aanvraag_vakGroep1`
        FOREIGN KEY (`vakGroep` )
        REFERENCES `nascholing`.`vakGroep` (`vakGroepId` )
        ON DELETE NO ACTION
        ON UPDATE NO ACTION,
      CONSTRAINT `fk_aanvraag_voorEmail1`
        FOREIGN KEY (`voor` )
        REFERENCES `nascholing`.`voorEmail` (`voorEmailId` )
        ON DELETE NO ACTION
        ON UPDATE NO ACTION,
      CONSTRAINT `fk_aanvraag_betalingsMethode1`
        FOREIGN KEY (`betalingsmethode` )
        REFERENCES `nascholing`.`betalingsMethode` (`betalingsMethodeId` )
        ON DELETE NO ACTION
        ON UPDATE NO ACTION)
    ENGINE = InnoDB
    DEFAULT CHARACTER SET = utf8
    COLLATE = utf8_general_ci;

Body: Remove the length of the kost column.


问:
How overflow property in CSS actually works?
I have few queries related to overflow property in CSS-
Check this below code snippet,

.outer-div {
    display: flex;
    position: relative;
    height: 3.5em;
    width: 20%;
    border: 2px solid #000000a3;
    margin-left: 300px;
    align-items: center;
    border: 1px solid green;
}
.inner-div {
 border: 1px solid blue;
    position: absolute;
    right: 1%;
    font-size: 40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
</head>
<body>
  <div class = "outer-div">
    <div class = "inner-div">HelloWorld</div>
  </div>
</body></code>```

In the above snippet, the inner-div container is overflowing in the x-direction and not in y-direction. But if I add overflow: scroll, then it adds a scroll bar in both directions(fine till here), but I am able to use the scroll bar of y-direction and not x-direction, despite the fact that the inner-div container is overflowing in the x-direction. Why is it so?
Check this snippet,

.outer-div {
    display: flex;
    position: relative;
    height: 3.5em;
    width: 20%;
    border: 2px solid #000000a3;
    margin-left: 300px;
    align-items: center;
    border: 1px solid green;
    overflow: scroll;
}
.inner-div {
 border: 1px solid blue;
    position: absolute;
    right: 1%;
    font-size: 40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
</head>
<body>
  <div class = "outer-div">
    <div class = "inner-div">HelloWorld</div>
  </div>
</body>
</html></code>```

My last query is, if I separate the text with a hyphen(-) or a space, why it breaks into 2 lines and not continue in the same line? I know it may be because of the size of my outer container but why not it splits when I enter text without spaces? Check below,

.outer-div {
    display: flex;
    position: relative;
    height: 3.5em;
    width: 20%;
    border: 2px solid #000000a3;
    margin-left: 300px;
    align-items: center;
    border: 1px solid green;
}
.inner-div {
 border: 1px solid blue;
    position: absolute;
    right: 1%;
    font-size: 40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
</head>
<body>
  <div class = "outer-div">
    <div class = "inner-div">Hello World</div>
  </div>
</body>
</html></code>```

Thanks a lot for giving your time and for your help!

答:
The inner-div class gives the position: absolute property to the div. This makes the inner div independent of parent div's size and will always keep overflowing out until you explicitly specify the height and width of the parent container and also stop anchoring the inner-div (using right, top, left and bottom). By not anchoring the inner-div, the purposes of absolutely positioned elements is sort of defeated. You can get back the horizontal scroll bar by removing right but you probably don't want that to happen.

In a nutshell, absolutely positioned elements are not a part of the flow and are living in another dimension (they aren't visible for the parent div).

That's how word wrapping works. If the words of a line don't fit into the width, the words are shifted to the next line after it encounters a white-space. If you don't want the words to warp after a space, you should either use non-breaking spaces (Ex: ) or use white-space: nowrap;.

Body:
I have few queries related to overflow property in CSS-
Check this below code snippet,

.outer-div {
    display: flex;
    position: relative;
    height: 3.5em;
    width: 20%;
    border: 2px solid #000000a3;
    margin-left: 300px;
    align-items: center;
    border: 1px solid green;
}
.inner-div {
 border: 1px solid blue;
    position: absolute;
    right: 1%;
    font-size: 40px;
}

HelloWorld

In the above snippet, the inner-div container is overflowing in the x-direction and not in y-direction. But if I add overflow: scroll, then it adds a scroll bar in both directions(fine till here), but I am able to use the scroll bar of y-direction and not x-direction, despite the fact that the inner-div container is overflowing in the x-direction. Why is it so?
Check this snippet,

.outer-div {
    display: flex;
    position: relative;
    height: 3.5em;
    width: 20%;
    border: 2px solid #000000a3;
    margin-left: 300px;
    align-items: center;
    border: 1px solid green;
    overflow: scroll;
}
.inner-div {
 border: 1px solid blue;
    position: absolute;
    right: 1%;
    font-size: 40px;
}

HelloWorld

My last query is, if I separate the text with a hyphen(-) or a space, why it breaks into 2 lines and not continue in the same line? I know it may be because of the size of my outer container but why not it splits when I enter text without spaces? Check below,

.outer-div {
    display: flex;
    position: relative;
    height: 3.5em;
    width: 20%;
    border: 2px solid #000000a3;
    margin-left: 300px;
    align-items: center;
    border: 1px solid green;
}
.inner-div {
 border: 1px solid blue;
    position: absolute;
    right: 1%;
    font-size: 40px;
}

Hello World

Thanks a lot for giving your time and for your help!

Body:
The inner-div class gives the position: absolute property to the div. This makes the inner div independent of parent div's size and will always keep overflowing out until you explicitly specify the height and width of the parent container and also stop anchoring the inner-div (using right, top, left and bottom). By not anchoring the inner-div, the purposes of absolutely positioned elements is sort of defeated. You can get back the horizontal scroll bar by removing right but you probably don't want that to happen.

In a nutshell, absolutely positioned elements are not a part of the flow and are living in another dimension (they aren't visible for the parent div).

That's how word wrapping works. If the words of a line don't fit into the width, the words are shifted to the next line after it encounters a white-space. If you don't want the words to warp after a space, you should either use non-breaking spaces (Ex:&nbsp;) or use white-space: nowrap;.


问:
How to force GMail show link in list
Several services, for example github, bitbucket and some ticket services able to send email which contain inlist link in GMail. Like that:

Inside they just put link.

How it is possible to do the same programmatically?

答: I think I found the right answer. The right name of this feature is Go-To Action. It’s possible to add it programmatically using microdata or JSON-LD. More details in documentation</p>

Title: How to force GMail show link in list


问:
how to add multiple values in React Native cross-cookie
I am trying to create array in cookies . so it can be updated on every click. I have created cookies but don't no  how can i add multiple values in cookies.
my code is :

```<code> import cookie from 'cross-cookie';
    handlePressProduct(id) {
    cookie.set('cart', { product_id: 1234 ,qty: 1,customer_id: isuerID},{product_id: id ,qty: 2})
      .then(() => console.log('cookie set!'));

        cookie.get('cart')
      .then(value => alert(value));
    }
</code>```

how can i use multiple values in cookies ?

答:
I have tried this and its working fine for me .</p>

```<code> var data = {};
         data[id] = {product_id: id ,qty: 1,customer_id: isuerID};

        cookie.set(data)
        .then(() => console.log('cookies set!'));
});

  cookie.getAll().then(function(cookies){

     alert(JSON.stringify(cookies))

     })
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create array in cookies . so it can be updated on every click. I have created cookies but don't no  how can i add multiple values in cookies.
my code is :

 import cookie from 'cross-cookie';
    handlePressProduct(id) {
    cookie.set('cart', { product_id: 1234 ,qty: 1,customer_id: isuerID},{product_id: id ,qty: 2})
      .then(() => console.log('cookie set!'));

        cookie.get('cart')
      .then(value => alert(value));
    }

how can i use multiple values in cookies ?

Body:
I have tried this and its working fine for me .

 var data = {};
         data[id] = {product_id: id ,qty: 1,customer_id: isuerID};

        cookie.set(data)
        .then(() => console.log('cookies set!'));
});

  cookie.getAll().then(function(cookies){

     alert(JSON.stringify(cookies))

     })


问:
How to add design dependency in android studio 3.0. its not working in standard way
```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.rohit.ironman"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner"android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.0.0-beta1'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:0.5'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.android.support:design:26.1.1'
}
</code>```

I have also tried-

Implementation 'com.android.support:design:26.1.1'
instead of

compile 'com.android.support:design:26.1.1'
but still the gradle sync fails

my gradle version is 4.1

android plugin version is 3.0.1

答:
You are using Google's support library as dependancy. And when you upgrade to Android Studio 3.0, Google's maven repository central is required if you want to use these library.

See this link for more details: https://developer.android.com/studio/build/dependencies.html#google-maven

Simply follow the migration instruction, add google() in the build.gradle file and sync again.

```<code>allprojects {
repositories {
    google()

    // If you're using a version of Gradle lower than 4.1, you must instead use:
    // maven {
    //     url 'https://maven.google.com'
    // }
    // An alternative URL is 'https://dl.google.com/dl/android/maven2/'
}
</code>```

}

Body:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.rohit.ironman"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner"android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.0.0-beta1'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:0.5'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.android.support:design:26.1.1'
}

I have also tried-

Implementation 'com.android.support:design:26.1.1'
instead of

compile 'com.android.support:design:26.1.1'
but still the gradle sync fails

my gradle version is 4.1

android plugin version is 3.0.1

Body:
You are using Google's support library as dependancy. And when you upgrade to Android Studio 3.0, Google's maven repository central is required if you want to use these library.

See this link for more details: https://developer.android.com/studio/build/dependencies.html#google-maven

Simply follow the migration instruction, add google() in the build.gradle file and sync again.

allprojects {
repositories {
    google()

    // If you're using a version of Gradle lower than 4.1, you must instead use:
    // maven {
    //     url 'https://maven.google.com'
    // }
    // An alternative URL is 'https://dl.google.com/dl/android/maven2/'
}

}


问:
Camera action-Crop not Working Nougat
I am trying to crop an image from camera on 7.0 device. I have written the crop function using android intents and exposed my file via file providers to avoid FileUriExposedException.

The problems is after opening camera, crop tool doesn't show up and in my imageview nothing is displayed.

Here's my crop function code:

```<code>private void cropImage() {

    try {
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        cropIntent.setDataAndType(uri, "image/*");
        cropIntent.putExtra("crop", "true");
        cropIntent.putExtra("outputX", 200);
        cropIntent.putExtra("outputY", 200);
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        cropIntent.putExtra("scale", true);
        cropIntent.putExtra("return-data", true);

        startActivityForResult(cropIntent, CROP_CODE);
    } catch (ActivityNotFoundException aex) {
        aex.printStackTrace();
        Toast.makeText(this, "Current Device Has No Crop Support", Toast.LENGTH_LONG).show();
    }

}
</code>```

and my camera intent code here:

```<code>private void photoDialog() {
    final CharSequence[] imgOptions = {"Take Photo", "Select from Gallery"};

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Choose Image Options");
    builder.setItems(imgOptions, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            if (imgOptions[i].equals("Take Photo")) {
                try {
                    Intent camIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    file = new File(Environment.getExternalStorageDirectory(), "tmp_" + String.valueOf(System.currentTimeMillis()));
                    Log.d("MainActivity", "File Saved in:\t" + file.getAbsolutePath().toString());

                    if (Build.VERSION.SDK_INT > 23) {
                        uri = FileProvider.getUriForFile(MainActivity.this, getString(R.string.file_prov_authority), file);
                    } else {
                        uri = Uri.fromFile(file);
                    }

                    camIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    camIntent.putExtra("return-data", "true");
                    startActivityForResult(camIntent, CAM_CODE);

                } catch (ActivityNotFoundException ex) {
                    ex.printStackTrace();
                }
            } else if (imgOptions[i].equals("Select from Gallery")) {
                Intent galIntent = new Intent(Intent.ACTION_GET_CONTENT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(Intent.createChooser(galIntent, "Open With"), GAL_CODE);
            }
        }
    });
</code>```

When I try to set the imageview directly from camera bitmap, I get this exception too:

```<code>Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' on a null object reference
</code>```

My activity result code:

```<code> @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAM_CODE && resultCode == RESULT_OK) {
        Bitmap bitmap = (Bitmap) data.getExtras().get("data");
        img_camera.setImageBitmap(bitmap);
        cropImage();
    }

    else if (requestCode == GAL_CODE && resultCode == RESULT_OK) {
        if (data != null) {
            uri = data.getData();
            img_camera.setImageURI(uri);
            cropImage();
        }
    }

    else if (requestCode == CROP_CODE) {
        Bundle photo_extras = data.getExtras();
        Bitmap bitmap = photo_extras.getParcelable("data");

        img_camera.setImageBitmap(bitmap);

    }

}
</code>```

My crop from gallery code works perfectly though it is the same function.

Can anyone help me out with cropping camera image on Nougat devices as I have crawled every blog and YT video and ntn has worked so far. Thanks.

答:
I think your problem lies in your image's name. Try to name it with .jpg as:

```<code>file = new File(Environment.getExternalStorageDirectory(), "tmp_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
</code>```

And your error exception come from this line:

```<code>Bitmap bitmap = (Bitmap) data.getExtras().get("data");
</code>```

Change it to:

```<code>Bundle bundle = data.getExtras();
Bitmap bitmap = bundle.getParcelable("data");
</code>```

If it's not work, try my code (it's work for me. And I hope it's work for you too):

```<code>//Define constants:
private static final int PERMISSION_CAMERA_CODE = 1;
private static final int PERMISSION_STORE_CODE = 2;
private static final int REQUEST_CODE_TAKE_IMAGE = 3;
private static final int REQUEST_CODE_CHOOSE_IMAGE = 4;
private static final int REQUEST_CODE_CROP_AVATAR = 5;
private static final int REQUEST_CODE_CROP_COVER = 6;

private void openCamera() {

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra("android.intent.extras.CAMERA_FACING", 1);

    file = new File(Environment.getExternalStorageDirectory(), "file" + String.valueOf(System.currentTimeMillis()) + ".jpg");
    uri = Uri.fromFile(file);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    intent.putExtra("return-data", true);

    startActivityForResult(intent, REQUEST_CODE_TAKE_IMAGE);
}

private void openGallery() {

    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(Intent.createChooser(intent, "Select image from your gallery"), REQUEST_CODE_CHOOSE_IMAGE);

}
</code>```

Then:

```<code> @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_CODE_TAKE_IMAGE && resultCode == Activity.RESULT_OK) {
        cropImage();

    } else if (requestCode == REQUEST_CODE_CHOOSE_IMAGE && resultCode == Activity.RESULT_OK) {
        if (data != null) {
            uri = data.getData();
            cropImage();

        }

    } else if (requestCode == REQUEST_CODE_CROP_AVATAR && resultCode == Activity.RESULT_OK) {

        if (data != null) {

            Bundle bundle = data.getExtras();
            Bitmap bitmap = bundle.getParcelable("data");

            ivAvatar.setImageBitmap(bitmap);
        }

    }
}

private void cropImage() {
    Intent cropIntent = new Intent("com.android.camera.action.CROP");

    cropIntent.setDataAndType(uri, "image/*");
    cropIntent.putExtra("crop", true);
    cropIntent.putExtra("outputX", 180);
    cropIntent.putExtra("outputY", 180);

    cropIntent.putExtra("aspectX", 3);
    cropIntent.putExtra("aspectY", 3);
    cropIntent.putExtra("scaleUpIfNeeded", true);
    cropIntent.putExtra("return-data", true);
    startActivityForResult(cropIntent, REQUEST_CODE_CROP_AVATAR);

}
</code>```

Title: Camera action-Crop not Working Nougat

Body:
I am trying to crop an image from camera on 7.0 device. I have written the crop function using android intents and exposed my file via file providers to avoid FileUriExposedException.

The problems is after opening camera, crop tool doesn't show up and in my imageview nothing is displayed.

Here's my crop function code:

private void cropImage() {

    try {
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        cropIntent.setDataAndType(uri, "image/*");
        cropIntent.putExtra("crop", "true");
        cropIntent.putExtra("outputX", 200);
        cropIntent.putExtra("outputY", 200);
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        cropIntent.putExtra("scale", true);
        cropIntent.putExtra("return-data", true);

        startActivityForResult(cropIntent, CROP_CODE);
    } catch (ActivityNotFoundException aex) {
        aex.printStackTrace();
        Toast.makeText(this, "Current Device Has No Crop Support", Toast.LENGTH_LONG).show();
    }

}

and my camera intent code here:

private void photoDialog() {
    final CharSequence[] imgOptions = {"Take Photo", "Select from Gallery"};

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Choose Image Options");
    builder.setItems(imgOptions, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            if (imgOptions[i].equals("Take Photo")) {
                try {
                    Intent camIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    file = new File(Environment.getExternalStorageDirectory(), "tmp_" + String.valueOf(System.currentTimeMillis()));
                    Log.d("MainActivity", "File Saved in:\t" + file.getAbsolutePath().toString());

                    if (Build.VERSION.SDK_INT > 23) {
                        uri = FileProvider.getUriForFile(MainActivity.this, getString(R.string.file_prov_authority), file);
                    } else {
                        uri = Uri.fromFile(file);
                    }

                    camIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    camIntent.putExtra("return-data", "true");
                    startActivityForResult(camIntent, CAM_CODE);

                } catch (ActivityNotFoundException ex) {
                    ex.printStackTrace();
                }
            } else if (imgOptions[i].equals("Select from Gallery")) {
                Intent galIntent = new Intent(Intent.ACTION_GET_CONTENT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(Intent.createChooser(galIntent, "Open With"), GAL_CODE);
            }
        }
    });

When I try to set the imageview directly from camera bitmap, I get this exception too:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' on a null object reference

My activity result code:

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAM_CODE && resultCode == RESULT_OK) {
        Bitmap bitmap = (Bitmap) data.getExtras().get("data");
        img_camera.setImageBitmap(bitmap);
        cropImage();
    }

    else if (requestCode == GAL_CODE && resultCode == RESULT_OK) {
        if (data != null) {
            uri = data.getData();
            img_camera.setImageURI(uri);
            cropImage();
        }
    }

    else if (requestCode == CROP_CODE) {
        Bundle photo_extras = data.getExtras();
        Bitmap bitmap = photo_extras.getParcelable("data");

        img_camera.setImageBitmap(bitmap);

    }

}

My crop from gallery code works perfectly though it is the same function.

Can anyone help me out with cropping camera image on Nougat devices as I have crawled every blog and YT video and ntn has worked so far. Thanks.

Body:
I think your problem lies in your image's name. Try to name it with .jpg as:

file = new File(Environment.getExternalStorageDirectory(), "tmp_" + String.valueOf(System.currentTimeMillis()) + ".jpg");

And your error exception come from this line:

Bitmap bitmap = (Bitmap) data.getExtras().get("data");

Change it to:

Bundle bundle = data.getExtras();
Bitmap bitmap = bundle.getParcelable("data");

If it's not work, try my code (it's work for me. And I hope it's work for you too):

//Define constants:
private static final int PERMISSION_CAMERA_CODE = 1;
private static final int PERMISSION_STORE_CODE = 2;
private static final int REQUEST_CODE_TAKE_IMAGE = 3;
private static final int REQUEST_CODE_CHOOSE_IMAGE = 4;
private static final int REQUEST_CODE_CROP_AVATAR = 5;
private static final int REQUEST_CODE_CROP_COVER = 6;

private void openCamera() {

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra("android.intent.extras.CAMERA_FACING", 1);

    file = new File(Environment.getExternalStorageDirectory(), "file" + String.valueOf(System.currentTimeMillis()) + ".jpg");
    uri = Uri.fromFile(file);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    intent.putExtra("return-data", true);

    startActivityForResult(intent, REQUEST_CODE_TAKE_IMAGE);
}

private void openGallery() {

    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(Intent.createChooser(intent, "Select image from your gallery"), REQUEST_CODE_CHOOSE_IMAGE);

}

Then:

 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_CODE_TAKE_IMAGE && resultCode == Activity.RESULT_OK) {
        cropImage();

    } else if (requestCode == REQUEST_CODE_CHOOSE_IMAGE && resultCode == Activity.RESULT_OK) {
        if (data != null) {
            uri = data.getData();
            cropImage();

        }

    } else if (requestCode == REQUEST_CODE_CROP_AVATAR && resultCode == Activity.RESULT_OK) {

        if (data != null) {

            Bundle bundle = data.getExtras();
            Bitmap bitmap = bundle.getParcelable("data");

            ivAvatar.setImageBitmap(bitmap);
        }

    }
}

private void cropImage() {
    Intent cropIntent = new Intent("com.android.camera.action.CROP");

    cropIntent.setDataAndType(uri, "image/*");
    cropIntent.putExtra("crop", true);
    cropIntent.putExtra("outputX", 180);
    cropIntent.putExtra("outputY", 180);

    cropIntent.putExtra("aspectX", 3);
    cropIntent.putExtra("aspectY", 3);
    cropIntent.putExtra("scaleUpIfNeeded", true);
    cropIntent.putExtra("return-data", true);
    startActivityForResult(cropIntent, REQUEST_CODE_CROP_AVATAR);

}


答:
"document.getElementById('click').onclick" is just returning the state onClick whenever that line runs. Probably at page load time.

What you want to do is add an event listener which will listen for a change in the .onclick state. Then call your function with that.

This is what the onClick attribute is doing. Its generally advisable to use an event listener so you cna clearly separate your content from your JS logic.

Title: onclick attribute vs onclick in script


问:
Does `python setup.py test` install dependencies or not?
At first it looks like test dependencies are being installed (Processing coverage-4.4.2-py3.5.egg) and then all of a sudden they aren't (The 'coverage' module is not installed). What's going wrong?

```<code>(DictORM) 14:15 john@john:~/git/DictORM(master)$ python setup.py test --run-coverage
running green
Searching for coveralls
Best match: coveralls 1.2.0
Processing coveralls-1.2.0-py3.5.egg

Using /home/john/repos/git/DictORM/.eggs/coveralls-1.2.0-py3.5.egg
Searching for coverage
Best match: coverage 4.4.2
Processing coverage-4.4.2-py3.5.egg

Using /home/john/repos/git/DictORM/.eggs/coverage-4.4.2-py3.5.egg
Searching for docopt>=0.6.1
Best match: docopt 0.6.2
Processing docopt-0.6.2-py3.5.egg

Using /home/john/repos/git/DictORM/.eggs/docopt-0.6.2-py3.5.egg
Fatal: The 'coverage' module is not installed.  Have you run 'pip install coverage' ???
</code>```

答: It does.  An import error in this environment was caused by green not actually specifying coverage as an extra dependency.  We decided to just make it a required dependency in 2.12.0 which fixes this issue.  The bug fix was discussed here.</p>

Body:
At first it looks like test dependencies are being installed (Processing coverage-4.4.2-py3.5.egg) and then all of a sudden they aren't (The 'coverage' module is not installed). What's going wrong?

(DictORM) 14:15 john@john:~/git/DictORM(master)$ python setup.py test --run-coverage
running green
Searching for coveralls
Best match: coveralls 1.2.0
Processing coveralls-1.2.0-py3.5.egg

Using /home/john/repos/git/DictORM/.eggs/coveralls-1.2.0-py3.5.egg
Searching for coverage
Best match: coverage 4.4.2
Processing coverage-4.4.2-py3.5.egg

Using /home/john/repos/git/DictORM/.eggs/coverage-4.4.2-py3.5.egg
Searching for docopt>=0.6.1
Best match: docopt 0.6.2
Processing docopt-0.6.2-py3.5.egg

Using /home/john/repos/git/DictORM/.eggs/docopt-0.6.2-py3.5.egg
Fatal: The 'coverage' module is not installed.  Have you run 'pip install coverage' ???


问:
How to use iostream in VxWorks?
I am developing programs for VxWorks using Tornado 2.2. I meet some problem when I try to use cout. My code is here:

```<code>#include <iostream>
using namespace std;
void main()
{
    cout << "Hi" << endl;
}
</code>```

The project can be compiled without error. But when I try to download the .out file to the target machine (mounted on VMware), I got the following error:

What's the problem and how to solve it?

答: That's some old tech you got there... Check you kernel configuration for various CPLUS options - you're missing something.</p>

Title: How to use iostream in VxWorks?

Body:
I am developing programs for VxWorks using Tornado 2.2. I meet some problem when I try to use cout. My code is here:

#include <iostream>
using namespace std;
void main()
{
    cout << "Hi" << endl;
}

The project can be compiled without error. But when I try to download the .out file to the target machine (mounted on VMware), I got the following error:

What's the problem and how to solve it?


问:
PYQT4 - How do I compile and import a qrc file into my program?
I'm having trouble importing a resource file. I'm using pyqt4 with monkey studio and I am trying to import a png image. When I run the program I get an import error like

ImportError: No module named icon_rc

I know that I have to compile it using pyrcc4 but I don't understand how to do this can anybody help please. It would be very helpful to have an answer that fully explains how to compile the resource file so I can import it.

答:
you could try with pyside as well like:

--- pyside-rcc -o input.qrc output.py


问:
Why is my function running without asking for the input first?
So I am trying to work on a project for school and I wanted to create a prompt function that would allow me to enter in the question, type of prompt, the function that it would run if the input was "Y", and the response string it would output if the user replied "N".
This is my code:

```<code>#Will Steve Become a Millionaire?
#Interactive Fiction
#Zachary Williams

##Type 0 prompt = Y/N, Type 1 prompt = Int input.

def prompt(question, qType, yFunction, nResponse):
    print(question)

    answer=input()

    if qType==0:

        if answer=="Y" or answer=="y":
            yFunction()

        elif answer=="N" or answer=="n":
            print(nResponse)

        if answer=="X":
            print("test")

        else:
            print("\"" + answer + "\" is not one of the options. Please type \"Y\" or \"N\".")

    elif qType==1:
        print("test")

    else:
        print("Error creating prompt.")

##Start the story.
def start_program():
    print("It was 3:45 AM on a Saturday night. The only light in the room shone upon Steve's face, coming from the screen of his laptop, which he had been staring at for almost 12 hours straight. This was nothing new for Steve, but then an email popped up.")

    prompt("\nWould you like to read the email? (Y/N)", 0, open_email(), "Steve closed the notification. It was time to go to bed.")

def opening():
    print("Will Steve Become a Millionaire?")

    prompt("Starting the program.", 0, start_program(), "Okay then.")

def open_email():
    print("\nSteve opened the email.")
    print("\n\"I am Prince Kufour Otumfuo,\" the email read, \"I am transferring $75,000,000 USD to the United States, and need your help to transport it into the country. If you help me do so, I will only have you transfer $65,000,000 to my account, leaving you with $10,000,000 to keep. If you would be so kind, please reply to this email.\"")

opening()
</code>```

Currently, this is what it returns when I run the program:

Will Steve Become a Millionaire?
It was 3:45 AM on a Saturday night. The only light in the room shone upon Steve's face, coming from the screen of his laptop, which he had been staring at for almost 12 hours straight. This was nothing new for Steve, but then an email popped up.

Steve opened the email.

"I am Prince Kufour Otumfuo," the email read, "I am transferring $75,000,000 USD to the United States, and need your help to transport it into the country. If you help me do so, I will only have you transfer $65,000,000 to my account, leaving you with $10,000,000 to keep. If you would be so kind, please reply to this email."

Would you like to read the email? (Y/N)

Where it says "Steve opened the email." it should be asking "Would you like to read the email? (Y/N)", Instead, it's asking that after it prints it out. I'm very confused on why this is. Sorry if I didn't format this properly, I have never posted on here before.

Thanks!

答:
You need to ask input there something like this:

```<code>#Will Steve Become a Millionaire?
#Interactive Fiction
#Zachary Williams

##Type 0 prompt = Y/N, Type 1 prompt = Int input.

def prompt(question, qType, yFunction, nResponse):

  print("y",question)

  answer=input()

  if qType==0:

    if answer=="Y" or answer=="y":
      yFunction()

    elif answer=="N" or answer=="n":
      print(nResponse)

    if answer=="X":
      print("test")

    else:
      print("\"" + answer + "\" is not one of the options. Please type \"Y\" or \"N\".")

  elif qType==1:
    print("test")

  else:
    print("Error creating prompt.")

##Start the story.
def start_program():
  print("It was 3:45 AM on a Saturday night. The only light in the room shone upon Steve's face, coming from the screen of his laptop, which he had been staring at for almost 12 hours straight. This was nothing new for Steve, but then an email popped up.")

  input_1=input("\nWould you like to read the email? (Y/N)")

  if input_1 == "Y" or input_1 == "y":
      open_email()

  elif input_1 == "N" or input_1 == "n":
      print('Okay then')

  if input_1 == "X":
      print("test")

def opening():
  print("Will Steve Become a Millionaire?")

  prompt("Starting the program.", 0, start_program(), "Okay then.")

def open_email():
  print("\nSteve opened the email.")
  print("\n\"I am Prince Kufour Otumfuo,\" the email read, \"I am transferring $75,000,000 USD to the United States, and need your help to transport it into the country. If you help me do so, I will only have you transfer $65,000,000 to my account, leaving you with $10,000,000 to keep. If you would be so kind, please reply to this email.\"")

opening()
</code>```

or call a function like function  instead of function()

```<code>#Will Steve Become a Millionaire?
#Interactive Fiction
#Zachary Williams

##Type 0 prompt = Y/N, Type 1 prompt = Int input.

def prompt(question, qType, yFunction, nResponse):

  print("y",question)

  answer=input()

  if qType==0:

    if answer=="Y" or answer=="y":
      yFunction()

    elif answer=="N" or answer=="n":
      print(nResponse)

    if answer=="X":
      print("test")

    else:
      print("\"" + answer + "\" is not one of the options. Please type \"Y\" or \"N\".")

  elif qType==1:
    print("test")

  else:
    print("Error creating prompt.")

##Start the story.
def start_program():
  print("It was 3:45 AM on a Saturday night. The only light in the room shone upon Steve's face, coming from the screen of his laptop, which he had been staring at for almost 12 hours straight. This was nothing new for Steve, but then an email popped up.")

  prompt("\nWould you like to read the email? (Y/N)", 0, open_email, "Steve closed the notification. It was time to go to bed.")

def opening():
  print("Will Steve Become a Millionaire?")

  prompt("Starting the program.", 0, start_program(), "Okay then.")

def open_email():
  print("\nSteve opened the email.")
  print("\n\"I am Prince Kufour Otumfuo,\" the email read, \"I am transferring $75,000,000 USD to the United States, and need your help to transport it into the country. If you help me do so, I will only have you transfer $65,000,000 to my account, leaving you with $10,000,000 to keep. If you would be so kind, please reply to this email.\"")

opening()
</code>```

Body:
So I am trying to work on a project for school and I wanted to create a prompt function that would allow me to enter in the question, type of prompt, the function that it would run if the input was "Y", and the response string it would output if the user replied "N".
This is my code:

#Will Steve Become a Millionaire?
#Interactive Fiction
#Zachary Williams

##Type 0 prompt = Y/N, Type 1 prompt = Int input.

def prompt(question, qType, yFunction, nResponse):
    print(question)

    answer=input()

    if qType==0:

        if answer=="Y" or answer=="y":
            yFunction()

        elif answer=="N" or answer=="n":
            print(nResponse)

        if answer=="X":
            print("test")

        else:
            print("\"" + answer + "\" is not one of the options. Please type \"Y\" or \"N\".")

    elif qType==1:
        print("test")

    else:
        print("Error creating prompt.")

##Start the story.
def start_program():
    print("It was 3:45 AM on a Saturday night. The only light in the room shone upon Steve's face, coming from the screen of his laptop, which he had been staring at for almost 12 hours straight. This was nothing new for Steve, but then an email popped up.")

    prompt("\nWould you like to read the email? (Y/N)", 0, open_email(), "Steve closed the notification. It was time to go to bed.")

def opening():
    print("Will Steve Become a Millionaire?")

    prompt("Starting the program.", 0, start_program(), "Okay then.")

def open_email():
    print("\nSteve opened the email.")
    print("\n\"I am Prince Kufour Otumfuo,\" the email read, \"I am transferring $75,000,000 USD to the United States, and need your help to transport it into the country. If you help me do so, I will only have you transfer $65,000,000 to my account, leaving you with $10,000,000 to keep. If you would be so kind, please reply to this email.\"")

opening()

Currently, this is what it returns when I run the program:

Will Steve Become a Millionaire?
It was 3:45 AM on a Saturday night. The only light in the room shone upon Steve's face, coming from the screen of his laptop, which he had been staring at for almost 12 hours straight. This was nothing new for Steve, but then an email popped up.

Steve opened the email.

"I am Prince Kufour Otumfuo," the email read, "I am transferring $75,000,000 USD to the United States, and need your help to transport it into the country. If you help me do so, I will only have you transfer $65,000,000 to my account, leaving you with $10,000,000 to keep. If you would be so kind, please reply to this email."

Would you like to read the email? (Y/N)

Where it says "Steve opened the email." it should be asking "Would you like to read the email? (Y/N)", Instead, it's asking that after it prints it out. I'm very confused on why this is. Sorry if I didn't format this properly, I have never posted on here before.

Thanks!

Body:
You need to ask input there something like this:

#Will Steve Become a Millionaire?
#Interactive Fiction
#Zachary Williams

##Type 0 prompt = Y/N, Type 1 prompt = Int input.

def prompt(question, qType, yFunction, nResponse):

  print("y",question)

  answer=input()

  if qType==0:

    if answer=="Y" or answer=="y":
      yFunction()

    elif answer=="N" or answer=="n":
      print(nResponse)

    if answer=="X":
      print("test")

    else:
      print("\"" + answer + "\" is not one of the options. Please type \"Y\" or \"N\".")

  elif qType==1:
    print("test")

  else:
    print("Error creating prompt.")

##Start the story.
def start_program():
  print("It was 3:45 AM on a Saturday night. The only light in the room shone upon Steve's face, coming from the screen of his laptop, which he had been staring at for almost 12 hours straight. This was nothing new for Steve, but then an email popped up.")

  input_1=input("\nWould you like to read the email? (Y/N)")

  if input_1 == "Y" or input_1 == "y":
      open_email()

  elif input_1 == "N" or input_1 == "n":
      print('Okay then')

  if input_1 == "X":
      print("test")

def opening():
  print("Will Steve Become a Millionaire?")

  prompt("Starting the program.", 0, start_program(), "Okay then.")

def open_email():
  print("\nSteve opened the email.")
  print("\n\"I am Prince Kufour Otumfuo,\" the email read, \"I am transferring $75,000,000 USD to the United States, and need your help to transport it into the country. If you help me do so, I will only have you transfer $65,000,000 to my account, leaving you with $10,000,000 to keep. If you would be so kind, please reply to this email.\"")

opening()

or call a function like function  instead of function()

#Will Steve Become a Millionaire?
#Interactive Fiction
#Zachary Williams

##Type 0 prompt = Y/N, Type 1 prompt = Int input.

def prompt(question, qType, yFunction, nResponse):

  print("y",question)

  answer=input()

  if qType==0:

    if answer=="Y" or answer=="y":
      yFunction()

    elif answer=="N" or answer=="n":
      print(nResponse)

    if answer=="X":
      print("test")

    else:
      print("\"" + answer + "\" is not one of the options. Please type \"Y\" or \"N\".")

  elif qType==1:
    print("test")

  else:
    print("Error creating prompt.")

##Start the story.
def start_program():
  print("It was 3:45 AM on a Saturday night. The only light in the room shone upon Steve's face, coming from the screen of his laptop, which he had been staring at for almost 12 hours straight. This was nothing new for Steve, but then an email popped up.")

  prompt("\nWould you like to read the email? (Y/N)", 0, open_email, "Steve closed the notification. It was time to go to bed.")

def opening():
  print("Will Steve Become a Millionaire?")

  prompt("Starting the program.", 0, start_program(), "Okay then.")

def open_email():
  print("\nSteve opened the email.")
  print("\n\"I am Prince Kufour Otumfuo,\" the email read, \"I am transferring $75,000,000 USD to the United States, and need your help to transport it into the country. If you help me do so, I will only have you transfer $65,000,000 to my account, leaving you with $10,000,000 to keep. If you would be so kind, please reply to this email.\"")

opening()


问:
jQuery Keycode help
How could I run a simple function when a key is pressed using jQuery. So for example if a user pressed the 'Q' key which is 81 in JavaScript it would run a function.</p>

答:
One approach:

```<code>$(window).keydown(
    function(e){
        if (e.keyCode == 113 || e.keyCode == 81) { // 113 = q, 81 = Q
            // do this
        }
    });
</code>```

JS Fiddle demo

jQuery API references:

keydown()

Title: jQuery Keycode help

Body:
One approach:

$(window).keydown(
    function(e){
        if (e.keyCode == 113 || e.keyCode == 81) { // 113 = q, 81 = Q
            // do this
        }
    });

JS Fiddle demo

jQuery API references:

keydown()


问:
When try to call /shutdown on springboot, requeries authorization header instead just correct shutdown application
I have app on spring-boot
added

```<code>endpoints.shutdown.enabled=true
endpoints.shutdown.sensitive=false
</code>```

to application.properties

and try to call:

```<code> curl -i -X POST devapp583.netcracker.com:26810/shutdown
</code>```

But requres Auth header instead just shutting down:

```<code>{"errorCode":403,"userMessage":"No 'Authorization' header","stacktrace":null,"remoteMessage":null}
</code>```

答:
It seems like a bug, take a look here. (If you use @EnableResourceServer)

According to the docs for 1.3 for health access restrictions, a
  non-sensitive health endpoint should allow anonymous access. However,
  this stops working if the @EnableResourceServer annotation is found.
  When the OAuth2 resource server is enabled, even non-sensitive
  endpoints require full authentication.

Also there you can find a workaround:

I did manage to work around the problem for the health endpoint by
  adding the following bean definition.

```<code>@Bean
ResourceServerConfigurer resourceServerConfigurer() {
    new ResourceServerConfigurerAdapter() {
        @Override
        void configure(ResourceServerSecurityConfigurer resources)
                throws Exception {
            resources.resourceId('blah')
        }

        @Override
        void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
            // allow anonymous access to health check endpoint
                    .antMatchers("/manage/health").permitAll()
            // everything else requires authentication
                    .anyRequest().authenticated()
        }
    }
}
</code>```

However I have not tried it myself

Body:
I have app on spring-boot
added

endpoints.shutdown.enabled=true
endpoints.shutdown.sensitive=false

to application.properties

and try to call:

 curl -i -X POST devapp583.netcracker.com:26810/shutdown

But requres Auth header instead just shutting down:

{"errorCode":403,"userMessage":"No 'Authorization' header","stacktrace":null,"remoteMessage":null}

Body:
It seems like a bug, take a look here. (If you use @EnableResourceServer)

According to the docs for 1.3 for health access restrictions, a
  non-sensitive health endpoint should allow anonymous access. However,
  this stops working if the @EnableResourceServer annotation is found.
  When the OAuth2 resource server is enabled, even non-sensitive
  endpoints require full authentication.

Also there you can find a workaround:

I did manage to work around the problem for the health endpoint by
  adding the following bean definition.

@Bean
ResourceServerConfigurer resourceServerConfigurer() {
    new ResourceServerConfigurerAdapter() {
        @Override
        void configure(ResourceServerSecurityConfigurer resources)
                throws Exception {
            resources.resourceId('blah')
        }

        @Override
        void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
            // allow anonymous access to health check endpoint
                    .antMatchers("/manage/health").permitAll()
            // everything else requires authentication
                    .anyRequest().authenticated()
        }
    }
}

However I have not tried it myself


问:
Provisioning Profiles With Multiple Schemes & Push Notifications
I followed the following article to enable the same app to be installed on the same device multiple times for each environment (dev, uat, release):

https://medium.com/@danielgalasko/run-multiple-versions-of-your-app-on-the-same-device-using-xcode-configurations-1fd3a220c608

I've run into an issue I'm not sure how to fix. We now have a unique bundle ID for each environment. We need to distribute each flavour of the app to users so we need both a distribution and a development provision profile. Because we have multiple schemes each with their own bundle ID we need provisioning profiles for each scheme (can't use wildcards due to push notification entitlement). I'll need to check in the distribution provisioning profiles to our repo as we use bitrise for CI and it'll need a distribution prov profile to archive the app, so each time we want to cut a local build and run it on device we'll need to change the provisioning profile to the dev variant and remember to not check those changes in to the repo.

This seems a bit backwards, is there a more efficient way to handle this scenario?

答:
I would recommend that you just create the APP ID individually for all schemes required in your Apple Enterprise / Developer Account.

Then just make sure all the APP ID are enabled with Push notifications for the Development and Distribution both. Distribution is sufficient i suppose.

Now in your Xcode let the Option in all schemes be set to Automatic provisioning so you get rid of a headache to make profiles in Account always, Xcode will handle this.

Now tell your server guy to handle .p12 for APNS Distribution cert smartly with passwords set for each and trigger push for each app it should be okay. Make sure he selected SANDBOX if its Development APNS cert given, or LIVE Mode if its Distribution cert was given.


问:
Importing caffe results in ImportError: "No module named google.protobuf.internal" (import enum_type_wrapper)
I installed Anaconda Python on my machine.  When I start the Python Interpreter and type "import caffe" in the Python shell, I get the following error:

```<code>ImportError: No module named google.protobuf.internal
</code>```

I have the following files:

```<code>wire_format_lite_inl.h
wire_format_lite.h
wire_format.h
unknown_field_set.h
text_format.h
service.h
repeated_field.h
reflection_ops.h
message_lite.h
message.h
generated_message_util.h
extension_set.h
descriptor.proto
descriptor.h
generated_message_reflection.h
generated_enum_reflection.h
dynamic_message.h
descriptor.pb.h
descriptor_database.h
</code>```

What files do I need so the import will work?  Is there an "internal.h" file that is required?

答: If you are using Anaconda, do conda install protobuf

Body:
I installed Anaconda Python on my machine.  When I start the Python Interpreter and type "import caffe" in the Python shell, I get the following error:

ImportError: No module named google.protobuf.internal

I have the following files:

wire_format_lite_inl.h
wire_format_lite.h
wire_format.h
unknown_field_set.h
text_format.h
service.h
repeated_field.h
reflection_ops.h
message_lite.h
message.h
generated_message_util.h
extension_set.h
descriptor.proto
descriptor.h
generated_message_reflection.h
generated_enum_reflection.h
dynamic_message.h
descriptor.pb.h
descriptor_database.h

What files do I need so the import will work?  Is there an "internal.h" file that is required?