问:
Why is NHibernate generating schema with the class name as a column?
I'm trying to generate my database from classes using NHibernate, but the schema that's being created contains a column for the class. For the most part this wouldn't matter but one class in particular is causing this to fail... my Order class (because order is a reserved keyword in SQL - yes maybe I should have used a word that wasn't a keyword but that's another issue)

The following mapping file:

```<code><?xml version="1.0" encoding="utf-8" ?>
</code>```

```<code><class name="Order" table="Orders">
    <id name="_persistenceID" column="ID" type="Guid" access="field" unsaved-value="00000000-0000-0000-0000-000000000000">
        <generator class="guid.comb" />
    </id>
    <version name="_persistenceVersion" column="Version" access="field" type="int" unsaved-value="0" />

    <property name="DateDeleted" column="DateDeleted" type="DateTime" />
    <property name="ChangeReason" column="ChangeReason" type="String" not-null="true" />
    <property name="CompletedDate" column="CompletedDate" type="DateTime" />
    <property name="IsDeleted" column="IsDeleted" type="Boolean" />
    <property name="Notes" column="Notes" type="String" />
    <property name="OrderDate" column="OrderDate" type="DateTime" not-null="true" />
    <property name="OrderTotal" column="OrderTotal" type="Decimal" />
    <property name="RequiredDate" column="RequiredDate" type="DateTime" />

    <many-to-one name="Customer" column="Customer" class="Customer" not-null="true" />

    <bag name="OrderDetails" table="OrderDetails" generic="true" cascade="all">
        <key column="OrderDetail" foreign-key="FK_OrderOrderDetails" />
        <one-to-many class="OrderDetail" />
    </bag>

</class>
</code>```

produces the following SQL:

```<code>    create table Orders (
  ID UNIQUEIDENTIFIER not null,
   Version INT not null,
   DateDeleted DATETIME null,
   ChangeReason NVARCHAR(255) not null,
   CompletedDate DATETIME null,
   IsDeleted BIT null,
   Notes NVARCHAR(255) null,
   OrderDate DATETIME not null,
   OrderTotal DECIMAL(19,5) null,
   RequiredDate DATETIME null,
   Customer UNIQUEIDENTIFIER not null,
   Order UNIQUEIDENTIFIER null,
   primary key (ID)
)
</code>```

It's that 2nd to last column (Order) that's causing this to be invalid and highlighted the issue. It is happening on all my other classes - but I've no idea why. What can I do about it?

Edit: 30/11/2010 - The other end of the mapping file:

```<code><hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="TheWorkshop.DomainModel" namespace="TheWorkshop.DomainModel" default-access="field.camelcase-underscore" default-lazy="true">

<class name="OrderDetail" table="OrderDetails">
    <id name="_persistenceID" column="ID" type="Guid" access="field" unsaved-value="00000000-0000-0000-0000-000000000000">
        <generator class="guid.comb" />
    </id>
    <version name="_persistenceVersion" column="Version" access="field" type="int" unsaved-value="0" />

    <property name="AdjustedPrice" column="AdjustedPrice" type="Decimal" not-null="true" />
    <property name="LineCost" column="LineCost" type="Decimal" not-null="true" />
    <property name="Notes" column="Notes" type="String" />
    <property name="Photo" column="Photo" type="String" />
    <property name="Price" column="Price" type="Decimal" not-null="true" />
    <property name="Quantity" column="Quantity" type="int" />

    <many-to-one name="`Order`" column="`Order`" class="Order" not-null="true" />
    <many-to-one name="Product" column="Product" class="Product" not-null="true" />

</class>
</code>```

and that generates the following:

```<code>create table OrderDetails (
ID UNIQUEIDENTIFIER not null,
Version INT not null,
AdjustedPrice DECIMAL(19,5) not null,
LineCost DECIMAL(19,5) not null,
Notes NVARCHAR(255) null,
Photo NVARCHAR(255) null,
Price DECIMAL(19,5) not null,
Quantity INT null,
[Order] UNIQUEIDENTIFIER not null,
Product UNIQUEIDENTIFIER not null,
primary key (ID)
)
</code>```

答:
I think the problem is the key column is set to OrderDetail. The column attribute should contain the name of the foreign key column from the Order table in OrderDetail and I doubt you've named that column OrderDetail. My guess is that it should be OrderID. It may be a bug in schema generation that occurs when a class name is supplied instead of the column name.</p>

```<code><key column="OrderDetail" foreign-key="FK_OrderOrderDetails" />
</code>```

Body:
I'm trying to generate my database from classes using NHibernate, but the schema that's being created contains a column for the class. For the most part this wouldn't matter but one class in particular is causing this to fail... my Order class (because order is a reserved keyword in SQL - yes maybe I should have used a word that wasn't a keyword but that's another issue)

The following mapping file:

<?xml version="1.0" encoding="utf-8" ?>

<class name="Order" table="Orders">
    <id name="_persistenceID" column="ID" type="Guid" access="field" unsaved-value="00000000-0000-0000-0000-000000000000">
        <generator class="guid.comb" />
    </id>
    <version name="_persistenceVersion" column="Version" access="field" type="int" unsaved-value="0" />

    <property name="DateDeleted" column="DateDeleted" type="DateTime" />
    <property name="ChangeReason" column="ChangeReason" type="String" not-null="true" />
    <property name="CompletedDate" column="CompletedDate" type="DateTime" />
    <property name="IsDeleted" column="IsDeleted" type="Boolean" />
    <property name="Notes" column="Notes" type="String" />
    <property name="OrderDate" column="OrderDate" type="DateTime" not-null="true" />
    <property name="OrderTotal" column="OrderTotal" type="Decimal" />
    <property name="RequiredDate" column="RequiredDate" type="DateTime" />

    <many-to-one name="Customer" column="Customer" class="Customer" not-null="true" />

    <bag name="OrderDetails" table="OrderDetails" generic="true" cascade="all">
        <key column="OrderDetail" foreign-key="FK_OrderOrderDetails" />
        <one-to-many class="OrderDetail" />
    </bag>

</class>

produces the following SQL:

    create table Orders (
  ID UNIQUEIDENTIFIER not null,
   Version INT not null,
   DateDeleted DATETIME null,
   ChangeReason NVARCHAR(255) not null,
   CompletedDate DATETIME null,
   IsDeleted BIT null,
   Notes NVARCHAR(255) null,
   OrderDate DATETIME not null,
   OrderTotal DECIMAL(19,5) null,
   RequiredDate DATETIME null,
   Customer UNIQUEIDENTIFIER not null,
   Order UNIQUEIDENTIFIER null,
   primary key (ID)
)

It's that 2nd to last column (Order) that's causing this to be invalid and highlighted the issue. It is happening on all my other classes - but I've no idea why. What can I do about it?

Edit: 30/11/2010 - The other end of the mapping file:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="TheWorkshop.DomainModel" namespace="TheWorkshop.DomainModel" default-access="field.camelcase-underscore" default-lazy="true">

<class name="OrderDetail" table="OrderDetails">
    <id name="_persistenceID" column="ID" type="Guid" access="field" unsaved-value="00000000-0000-0000-0000-000000000000">
        <generator class="guid.comb" />
    </id>
    <version name="_persistenceVersion" column="Version" access="field" type="int" unsaved-value="0" />

    <property name="AdjustedPrice" column="AdjustedPrice" type="Decimal" not-null="true" />
    <property name="LineCost" column="LineCost" type="Decimal" not-null="true" />
    <property name="Notes" column="Notes" type="String" />
    <property name="Photo" column="Photo" type="String" />
    <property name="Price" column="Price" type="Decimal" not-null="true" />
    <property name="Quantity" column="Quantity" type="int" />

    <many-to-one name="`Order`" column="`Order`" class="Order" not-null="true" />
    <many-to-one name="Product" column="Product" class="Product" not-null="true" />

</class>

and that generates the following:

create table OrderDetails (
ID UNIQUEIDENTIFIER not null,
Version INT not null,
AdjustedPrice DECIMAL(19,5) not null,
LineCost DECIMAL(19,5) not null,
Notes NVARCHAR(255) null,
Photo NVARCHAR(255) null,
Price DECIMAL(19,5) not null,
Quantity INT null,
[Order] UNIQUEIDENTIFIER not null,
Product UNIQUEIDENTIFIER not null,
primary key (ID)
)

Body:
I think the problem is the key column is set to OrderDetail. The column attribute should contain the name of the foreign key column from the Order table in OrderDetail and I doubt you've named that column OrderDetail. My guess is that it should be OrderID. It may be a bug in schema generation that occurs when a class name is supplied instead of the column name.

<key column="OrderDetail" foreign-key="FK_OrderOrderDetails" />


来源: stackexchange

问:
What is the best way to backup Brackets plugins?
I know the plugins are installed in

Mac: ~/Library/Application Support/Brackets/extensions/user
Win: C:\Users\\AppData\Roaming\Brackets\extensions\user
Linux: ~/.config/brackets/extensions/user

Otherwise, I can view the location from the menu "Help > Show Extensions Folder".

Is there any better solution than to zip and move it?

答:
Install "Extensions Bulk Installer"

Open up Extensions Bulk Install Shortcut – Ctrl(Cmd)+Alt+M on your version of Brackets, which you want to export.

Click on Export to File

Switch Computers and Import

ContentLicense: CC BY-SA 3.0


问:
Karma requirejs lodash
I am using karma, jasmine, requirejs and lodash. When I started project I got error like this:

```<code>PhantomJS 1.9.8 (Windows 8 0.0.0) ERROR
  Error: Module name "../lodash.js" has not been loaded yet for context: _. Use require([])
  http://requirejs.org/docs/errors.html#notloaded
  at <project_path>/node_modules/requirejs/require.js:143
</code>```

I was not able to google out solution. Only what I found is this closed github issue which didnt helped me.

答: After several try-fail-modifies I found that once I downgraded lodash ~4 to lodash ~3 the error disapeared. This is sufficient solution for me.

Title: Karma requirejs lodash

Body:
I am using karma, jasmine, requirejs and lodash. When I started project I got error like this:

PhantomJS 1.9.8 (Windows 8 0.0.0) ERROR
  Error: Module name "../lodash.js" has not been loaded yet for context: _. Use require([])
  http://requirejs.org/docs/errors.html#notloaded
  at <project_path>/node_modules/requirejs/require.js:143

I was not able to google out solution. Only what I found is this closed github issue which didnt helped me.


问:
Moving uploaded files in Socialengine
I tried moving uploaded file through browse action in socialengine from /public/user/ to /Files/SE/ by using

1.
    $fileobj = new Zend_Cloud_StorageService_Adapter_FileSystem();
    $fileobj->moveItem($sourcePath, $destinationpath);

move_uploaded_file($sourcePath, $destinationpath);
Both of these couldn't move the file. I have checked the paths too they are perfect and works with other frameworks

答: You should use API of Storage module which will allow you to create temporary files (when you need to resize images or convert videos) and then place them into public storage. This files will be tracked in engine4_storage_files table.

Title: Moving uploaded files in Socialengine


问:
OSError: [Errno 65] No route to host. Python 3.5.3
I'm trying to connect to gmail through SMTP, but python is not connecting to the server: smtp.gmail.com. I don't think there is something wrong with my code, but here it is:

```<code>import smtplib
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)

smtpObj.ehlo()
smtpObj.starttls()

smtpObj.login('sending_Email@gmail.com', 'password')
smtpObj.sendmail('sending_Email@gmail.com', 'receiving_Email@gmail.com')
smptObj.quit()
</code>```

I think there is some settings I have to enable, but nothing is working. I am using a mac running OS X Yosemite 10.10.5. Thanks for your help in advance.

This is the error message I am getting.

```<code>Traceback (most recent call last):
File "/Users/jacobgreen/Documents/Comp Programming/Email Hack.py", line 3, in <module>
    smtpObj = smtplib.SMTP("smtp.gmail.com", 587)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/smtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/smtplib.py", line 335, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/smtplib.py", line 306, in _get_socket
    self.source_address)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/socket.py", line 712, in create_connection
    raise err
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/socket.py", line 703, in create_connection
    sock.connect(sa)
OSError: [Errno 65] No route to host
</code>```

答: If this is happening to you, try connecting to a different wifi network and attempt to run the code again. If I find a way to edit the setting on your computer needed to make the code work. I'll post it here</p>

Body:
I'm trying to connect to gmail through SMTP, but python is not connecting to the server: smtp.gmail.com. I don't think there is something wrong with my code, but here it is:

import smtplib
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)

smtpObj.ehlo()
smtpObj.starttls()

smtpObj.login('sending_Email@gmail.com', 'password')
smtpObj.sendmail('sending_Email@gmail.com', 'receiving_Email@gmail.com')
smptObj.quit()

I think there is some settings I have to enable, but nothing is working. I am using a mac running OS X Yosemite 10.10.5. Thanks for your help in advance.

This is the error message I am getting.

Traceback (most recent call last):
File "/Users/jacobgreen/Documents/Comp Programming/Email Hack.py", line 3, in <module>
    smtpObj = smtplib.SMTP("smtp.gmail.com", 587)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/smtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/smtplib.py", line 335, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/smtplib.py", line 306, in _get_socket
    self.source_address)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/socket.py", line 712, in create_connection
    raise err
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/socket.py", line 703, in create_connection
    sock.connect(sa)
OSError: [Errno 65] No route to host


问:
Access media from offline storage after sending it to server like whatsapp
What I Want

I want the media files to be sent to server , once it is sent then read the media file from the local storage (There can be any number of images like whatsapp)

My problems

How do I recognise the images  that has been delete from offline storage.

In Short I wanted to develop and app that works even in offline-mode like whatsapp (for mediafiles , chats text)

If any tutorials please help me to get started

答:
Store media absolute path on local in sqlite and with status isOnline true or false.
Once media is sent to server update its status isOnline to true.
Now show media by path in db when isOnline is false.

If file is deleted, you will get FileNotFoundException and handle it by fetching from server again or place holder image like whatsapp.


问:
Hide (and show) links when div is dynamically resized
I am trying to resize a div when a user decides to hide (or show) particular content. For example, I have a contents page (https://jsfiddle.net/4b1g5jp9/1/), when a user clicks hide, I want the div to resize accordingly, hiding all contents except the actual Contents title.

Also, the 'Show' link should only show if the content is actually hidden and vice versa.

I have tried to adapt some JS based on a similar issue I found online and tried the following approach:

```<code><script language="javascript">
            function toggle() {
                var ele = document.getElementById("contents-list");
                if (ele.style.display == "block") {
                    ele.style.display = "none";
                } else {
                    ele.style.display = "block";
                }
            }
        </script>
</code>```

But the above achieves nothing. Any advice/solution would be appreciated.

答:
By using the event's target we can determine what to show/hide.
If we do it that way, we can use this multiple times on a single page without it messing with each other.

Also, I've used toggle() which basically does the if() you had in your code statement for you.

https://jsfiddle.net/jkrielaars/qhb8ccob/1/

$(document).ready(function() {
 $('.toggle').click( function(event) {
   $(event.target).parents('.contents-list').find('ul').toggle();
   var newText = $(event.target).text() === '[Hide]' ? '[Show]' : '[Hide]';
    $(event.target).text(newText);
  });
});
 ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.contents-list{
    width: 300px;

    background-color: #f4f6f9;
    padding: 15px;
    border: 1px solid #b3b4b5;
}

.contents-list ul{
  list-style-type: none;
  margin: 0;
  padding: 0;
  font-size: 14px;
}

#contents-list ul li{
    text-decoration: none;
}

.contents-list ul li a{
    padding-bottom: 2px;
    text-decoration: none;
}

.contents-list a:visited {
    text-decoration: none; color:blue;
}
.contents-list ul li a:hover{
    text-decoration: underline;
}

.centerContents{
    text-align: center;
}

.toggle{
    font-size: 12px;
}</code>```

 Contents
    [Hide]

  1.  What is Mobility?

  2.  Why Mobility is important

  3.  Other

 Contents
    [Hide]

  1.  What is Mobility?

  2.  Why Mobility is important

  3.  Other

```

Body:
I am trying to resize a div when a user decides to hide (or show) particular content. For example, I have a contents page (https://jsfiddle.net/4b1g5jp9/1/), when a user clicks hide, I want the div to resize accordingly, hiding all contents except the actual Contents title.

Also, the 'Show' link should only show if the content is actually hidden and vice versa.

I have tried to adapt some JS based on a similar issue I found online and tried the following approach:

But the above achieves nothing. Any advice/solution would be appreciated.

Body:
By using the event's target we can determine what to show/hide.
If we do it that way, we can use this multiple times on a single page without it messing with each other.

Also, I've used toggle() which basically does the if() you had in your code statement for you.

https://jsfiddle.net/jkrielaars/qhb8ccob/1/

$(document).ready(function() {
 $('.toggle').click( function(event) {
   $(event.target).parents('.contents-list').find('ul').toggle();
   var newText = $(event.target).text() === '[Hide]' ? '[Show]' : '[Hide]';
    $(event.target).text(newText);
  });
});

.contents-list{
    width: 300px;

    background-color: #f4f6f9;
    padding: 15px;
    border: 1px solid #b3b4b5;
}

.contents-list ul{
  list-style-type: none;
  margin: 0;
  padding: 0;
  font-size: 14px;
}

#contents-list ul li{
    text-decoration: none;
}

.contents-list ul li a{
    padding-bottom: 2px;
    text-decoration: none;
}

.contents-list a:visited {
    text-decoration: none; color:blue;
}
.contents-list ul li a:hover{
    text-decoration: underline;
}

.centerContents{
    text-align: center;
}

.toggle{
    font-size: 12px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="contents-list">
  <div class="centerContents"><b> Contents </b>
    <a class="toggle" href="#hideContents">[Hide]</a>
  </div>
  <br/>
  <ul>
    <li> <a href="#jumpQ1"> 1.  What is Mobility? </a> </li>
    <li> <a href="#jumpQ2"> 2.  Why Mobility is important </a> </li>
    <li> <a href="#jumpQ3"> 3.  Other </a> </li>
  </ul>
</div>

<div class="contents-list">
  <div class="centerContents"><b> Contents </b>
    <a class="toggle" href="#hideContents">[Hide]</a>
  </div>
  <br/>
  <ul>
    <li> <a href="#jumpQ1"> 1.  What is Mobility? </a> </li>
    <li> <a href="#jumpQ2"> 2.  Why Mobility is important </a> </li>
    <li> <a href="#jumpQ3"> 3.  Other </a> </li>
  </ul>
</div>


问:
How to get python list first element id
I have a list

```<code>MENU_Items = [ {  "ID":0x3B08, "Description":"Read Levelling Status\t\t"},
                { "ID":0x3B39, "Description":"Read Air system control module state"},
                { "ID":0x3B3A, "Description":"Read Movement inhibit state\t"},
                { "ID":0x3B3B, "Description":"Read Target height status\t\t"}]
</code>```

Input = 1

MENU_Items[Input - 1]

I am getting the result as below:

```<code>{'ID': 15112, 'Description': 'Read Levelling Status\t\t'}
</code>```

I want to extract only 'ID' as a output

```<code>I am trying something like this MENU_Items[Input - 1].ID
</code>```

Its not working.

答:
MENU_Items[Input - 1] will you first element of array  first element which is a object. ['ID'] instead of .ID will give you id of that object

So, use MENU_Items[Input - 1]['ID']

Title: How to get python list first element id

Body:
I have a list

MENU_Items = [ {  "ID":0x3B08, "Description":"Read Levelling Status\t\t"},
                { "ID":0x3B39, "Description":"Read Air system control module state"},
                { "ID":0x3B3A, "Description":"Read Movement inhibit state\t"},
                { "ID":0x3B3B, "Description":"Read Target height status\t\t"}]

Input = 1

MENU_Items[Input - 1]

I am getting the result as below:

{'ID': 15112, 'Description': 'Read Levelling Status\t\t'}

I want to extract only 'ID' as a output

I am trying something like this MENU_Items[Input - 1].ID

Its not working.


问:
How to detect web page crash (not browser crash) using PHP?
How can we detect through PHP or maybe in node.js or other languages if a web page crashed (without the browser EXITing) so that when a user press the "reload" button on the "Aw Snap" page in chrome certain specific content inside the page can be shown in this particular case (crash case).
In a crash without EXIT, a browser shows per example in Google Chrome the famous "Aw, Snap!"  page.

I don't want to know how to capture if the user refreshed the page or the page reloaded which can be known quite easily with different methods [one example see this PHP this code which can detect if users refreshed the page on major desktop/mobile browsers except IE unfortunately this code does not capture a crash event and the fact that user might request again the same page after a crash.
I tried using "register_shutdown_function", and some other maneuvers using connection PHP functions like "connection_aborted" etc... but with no success. I figure out a sloppy way through the use of session variables but probably there are better clever manoeuvres.

Any help or suggestion would be greatly appreciated. Any solution in nodejs will be also welcomed.

答:
web brower crash because too many process from your browser to PC of Client.
this crash can't detected by php because PHP server scripting. and you have question.., why not use JS for detect crash of browser?, because JS created just for controller website,. if you force to checked that use ajax, node, etc you can't do that, why? because the problem comes suddenly

and detected crash browser from php is impossible.


问:
SQL query return a result on group by expression (Oracle)
When I run the following query, I get a sum of amount per accounting period. However in some accounting periods, I do not have any amount, so naturally, those periods with no sum of amount (null) are not shown in the result set.

I would like to know how to return those with the sum of amount 0 for them.

```<code>SELECT
    ACCOUNTING_PERIOD,
    SUM(RESOURCE_AMOUNT) AS TOTAL,
FROM
    RESOURCE_TBL
GROUP BY
    ACCOUNTING_PERIOD
</code>```

I get the following result set

```<code>accounting_period   TOTAL
-------------------------
1                   234
3                    65
5                   943
6                   299
.                   .
.                   .
.                   .
</code>```

In the above period 2 and 4 is left out since the sum is zero or null but I would like to get

```<code>accounting_period   TOTAL
-------------------------
1                   234
2                     0
3                    65
4                     0
5                   943
6                   299
.                   .
.                   .
.                   .
</code>```

答:
As per the article How do I get SUM function in MySQL to return '0' if no values are found?, please try the following...</p>

```<code>SELECT ACCOUNTING_PERIOD,
       COALESCE( SUM(RESOURCE_AMOUNT), 0 ) AS TOTAL
FROM RESOURCE_TBL
GROUP BY ACCOUNTING_PERIOD;
</code>```

Body:
When I run the following query, I get a sum of amount per accounting period. However in some accounting periods, I do not have any amount, so naturally, those periods with no sum of amount (null) are not shown in the result set.

I would like to know how to return those with the sum of amount 0 for them.

SELECT
    ACCOUNTING_PERIOD,
    SUM(RESOURCE_AMOUNT) AS TOTAL,
FROM
    RESOURCE_TBL
GROUP BY
    ACCOUNTING_PERIOD

I get the following result set

accounting_period   TOTAL
-------------------------
1                   234
3                    65
5                   943
6                   299
.                   .
.                   .
.                   .

In the above period 2 and 4 is left out since the sum is zero or null but I would like to get

accounting_period   TOTAL
-------------------------
1                   234
2                     0
3                    65
4                     0
5                   943
6                   299
.                   .
.                   .
.                   .

Body:
As per the article How do I get SUM function in MySQL to return '0' if no values are found?, please try the following...

SELECT ACCOUNTING_PERIOD,
       COALESCE( SUM(RESOURCE_AMOUNT), 0 ) AS TOTAL
FROM RESOURCE_TBL
GROUP BY ACCOUNTING_PERIOD;


问:
How to pass Ajax Json object to the Controller Class in .Net Core?
We are trying to make a Ajax request to our Core Web API and get the data Json result back to the Controller for further processing, Which include Deserialization of the Json object result, Ajax request is working fine and we are able to get the required Json data in data.

Can anyone here please advise the changes or the alternatives to achieve this?

View (Ajax Request)

```<code>@section scripts
{
<script type="text/javascript">
    $(document).ready(function () {
    GetEventDetails('@Url.Content("~/")');
    });

    function GetEventDetails(contextRoot) {
    $.ajax({
    type: "GET",
    url: contextRoot + "api/EventsAPI",
    dataType: "json",
    success: function (data) {
        debugger;
        var datavalue = data;
        contentType: "application/json";
        //Send data to controller ???
        console.log(data);
    },
    error: function (xhr) {
        alert(xhr.responseText);
    }
    });
    }
</script>
}
</code>```

Controller.cs

```<code>public ActionResult Index()
{
    /*Do all stuff before returning view
    1. Get Json Data from Ajax request
    2. Deserialize the obtained Json Data
    3. return to view
    */
    return View("Index");
}
</code>```

Update:

I have tried the solution given by @J. Doe, but still unable to get the result set. Please check the screenshot and below code..

Ajax Request:

```<code>function GetEventDetails(contextRoot) {
        $.ajax({
            type: "GET",
            url: contextRoot + "api/EventsAPI",
            dataType: "json",
            success: function (data) {
                debugger;
                var datavalue = data;
                contentType: "application/json; charset=utf-8";
                console.log(data);
                var EventJson = data;
                console.log(EventJson);
                $.ajax({
                    type: "POST",
                    url: "@Url.Action("Index")",
                    dataType: "json",
                    data: EventJson,
                    contentType: "application/json; charset=utf-8",
                        //data: EventJson,
                    success: function (data) {
                        alert(data.responseText);
                        console.log('Data received: ');
                        console.log(data.responseText);
                    },
                    failure: function (errMsg) {
                        console.log(errMsg);
                }
            });
    },
    error: function (xhr) {
        alert(xhr.responseText);
    }
});
}
</code>```

Class Properties:

```<code>public class RootObject
{
    public Embedded _embedded { get; set; }
    public Links _links { get; set; }
    public Page page { get; set; }
}
</code>```

Here is Action Result Controller:

```<code>public ActionResult Index(RootObject model)
{
    if (model != null)
    {
        return Json("Success");
    }
    else
    {
        return Json("An Error Has occoured");
    }
    //return View("Index");
}
</code>```

Error Snapshot:

enter image description here

答:
1) Add [FromBody] the controller you are returning to. This will make the controller expect a JSON object.

```<code>[HttpPost]
public ActionResult Index([FromBody]RootObject model)
    {
        if (model != null)
        {
            return Json("Success");
        }
        else
        {
            return Json("An Error Has occoured");
        }
        //return View("Index");
    }
</code>```

2) If this doesn't work you are not posting a correct json object/you are not posting a json object use console.dir(EventJson); to inspect the object you are passing in the console of the browser.

3) How to create a JSON object in JS: https://www.w3schools.com/js/js_json_stringify.asp

Body:
We are trying to make a Ajax request to our Core Web API and get the data Json result back to the Controller for further processing, Which include Deserialization of the Json object result, Ajax request is working fine and we are able to get the required Json data in data.

Can anyone here please advise the changes or the alternatives to achieve this?

View (Ajax Request)

@section scripts
{

}

Controller.cs

public ActionResult Index()
{
    /*Do all stuff before returning view
    1. Get Json Data from Ajax request
    2. Deserialize the obtained Json Data
    3. return to view
    */
    return View("Index");
}

Update:

I have tried the solution given by @J. Doe, but still unable to get the result set. Please check the screenshot and below code..

Ajax Request:

function GetEventDetails(contextRoot) {
        $.ajax({
            type: "GET",
            url: contextRoot + "api/EventsAPI",
            dataType: "json",
            success: function (data) {
                debugger;
                var datavalue = data;
                contentType: "application/json; charset=utf-8";
                console.log(data);
                var EventJson = data;
                console.log(EventJson);
                $.ajax({
                    type: "POST",
                    url: "@Url.Action("Index")",
                    dataType: "json",
                    data: EventJson,
                    contentType: "application/json; charset=utf-8",
                        //data: EventJson,
                    success: function (data) {
                        alert(data.responseText);
                        console.log('Data received: ');
                        console.log(data.responseText);
                    },
                    failure: function (errMsg) {
                        console.log(errMsg);
                }
            });
    },
    error: function (xhr) {
        alert(xhr.responseText);
    }
});
}

Class Properties:

public class RootObject
{
    public Embedded _embedded { get; set; }
    public Links _links { get; set; }
    public Page page { get; set; }
}

Here is Action Result Controller:

public ActionResult Index(RootObject model)
{
    if (model != null)
    {
        return Json("Success");
    }
    else
    {
        return Json("An Error Has occoured");
    }
    //return View("Index");
}

Error Snapshot:

enter image description here

Body:
1) Add [FromBody] the controller you are returning to. This will make the controller expect a JSON object.

[HttpPost]
public ActionResult Index([FromBody]RootObject model)
    {
        if (model != null)
        {
            return Json("Success");
        }
        else
        {
            return Json("An Error Has occoured");
        }
        //return View("Index");
    }

2) If this doesn't work you are not posting a correct json object/you are not posting a json object use console.dir(EventJson); to inspect the object you are passing in the console of the browser.

3) How to create a JSON object in JS: https://www.w3schools.com/js/js_json_stringify.asp


问:
django forms render static text
I am using django form wizard to render a series of forms and in my last screen, I want to show the user a simple screen that says press the save button to continue. So, this last screen has no input elements. I, of course, need it to be part of the wizard workflow. I was wondering if there is a Form element that can be used for something like this or if there is some hack to basically just show this text.

So basically I have something like:

```<code>class FinalForm(Forms.Form):
    text = Forms.CharField(label="Press Save to update the record")

    def __init__(self, *args, **kwargs):
        super(FinalForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()  # crispy-forms bit
</code>```

Here, of course, the CharField renders the text as a label and is an input field. Can it be done that we can have this form only contain some static text?

The urls.py is declared as:

```<code>url(r'^reviewrecord/(?P<pk>\d+)/$', views.ContactWizard.as_view([FirstForm, SecondForm, FinalForm]),
        name='reviewrecord'),
</code>```

答:
You don't need a form with static text! Just create an empty form (a form without any elements) and you can add the text to your html template.

To display the text only on the correct step of the form wizard (i.e the one displaying the empty form) you can use the step number as explained in the docs:

https://django-formtools.readthedocs.io/en/latest/wizard.html#creating-templates-for-the-forms

Title: django forms render static text

Body:
I am using django form wizard to render a series of forms and in my last screen, I want to show the user a simple screen that says press the save button to continue. So, this last screen has no input elements. I, of course, need it to be part of the wizard workflow. I was wondering if there is a Form element that can be used for something like this or if there is some hack to basically just show this text.

So basically I have something like:

class FinalForm(Forms.Form):
    text = Forms.CharField(label="Press Save to update the record")

    def __init__(self, *args, **kwargs):
        super(FinalForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()  # crispy-forms bit

Here, of course, the CharField renders the text as a label and is an input field. Can it be done that we can have this form only contain some static text?

The urls.py is declared as:

url(r'^reviewrecord/(?P<pk>\d+)/$', views.ContactWizard.as_view([FirstForm, SecondForm, FinalForm]),
        name='reviewrecord'),


问:
Twitter bootstrap v3 - button next to input isn't rounded
I copied this code (from the official documentation) and modified it a bit:

```<code><div class="row">
    <div class="col-xs-6 col-xs-offset-3">
        <div class="form-group">
            <div class="input-group">
                <input type="text" class="form-control" placeholder="Email addresses">
                <span class="input-group-btn">
                    <button class="btn btn-primary" type="button">
                        <i class="fa fa-envelope-o" aria-hidden="true"></i>
                        Send
                    </button>
                </span>
            </div>
        </div>
    </div>
</div>
</code>```

The right side of the button isn't rounded as in the source. Result:

What I'm missing?

答:
@No1Lives4Ever your code is working fine. see the below code snippet...

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

                <input type="text" class="form-control" placeholder="Email addresses">

                    <button class="btn btn-primary" type="button">

                        Send
                    </button>

```

Body:
I copied this code (from the official documentation) and modified it a bit:

                <input type="text" class="form-control" placeholder="Email addresses">

                    <button class="btn btn-primary" type="button">

                        Send
                    </button>

The right side of the button isn't rounded as in the source. Result:

What I'm missing?

Body:
@No1Lives4Ever your code is working fine. see the below code snippet...

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
    <div class="col-xs-6 col-xs-offset-3">
        <div class="form-group">
            <div class="input-group">
                <input type="text" class="form-control" placeholder="Email addresses">
                <span class="input-group-btn">
                    <button class="btn btn-primary" type="button">
                        <i class="fa fa-envelope-o" aria-hidden="true"></i>
                        Send
                    </button>
                </span>
            </div>
        </div>
    </div>
</div>


问:
T-SQL round special cases
I need a way to round in T-SQL (SQL Server 2005).

```<code>0.0041 -> 0.005
0.0049 -> 0.005
0.0040 -> 0.004
</code>```

I have tried the following select with ROUND():

```<code>SELECT ROUND(0.004, 3,1) + .001
</code>```

The problem is: it doesn't work with 0.0040 -> 0.004

Title: T-SQL round special cases

Body:
I need a way to round in T-SQL (SQL Server 2005).

0.0041 -> 0.005
0.0049 -> 0.005
0.0040 -> 0.004

I have tried the following select with ROUND():

SELECT ROUND(0.004, 3,1) + .001

The problem is: it doesn't work with 0.0040 -> 0.004

Body:
Try this:

SELECT X
, CEILING(X * 1000) / 1000 AS X4
FROM (
SELECT 0.0041 X UNION ALL
SELECT 0.0049 UNION ALL
SELECT 0.0040 ) A

Output:

X                                       X4
--------------------------------------- ---------------------------------------
0.0041                                  0.005000
0.0049                                  0.005000
0.0040                                  0.004000


问:
Dplyr tally/count by multiple filters
I am trying to create a summarise/filter dplyr pipeline which will be equivalent to the below:

```<code>iris %>%
mutate(Sepal.Area = Sepal.Length * Sepal.Width,
       Petal.Area = Petal.Length * Petal.Width) %>%
  group_by(Species) %>%
      filter(Sepal.Area < 17) %>%
        tally() %>%
      filter(Sepal.Area > 17 & Sepal.Area < 22) %>%
        tally() %>%
      filter(Sepal.Area > 22) %>%
        tally()
</code>```

Or another potential approach:

```<code>iris %>%
  mutate(Sepal.Area = Sepal.Length * Sepal.Width,
         Petal.Area = Petal.Length * Petal.Width) %>%
  group_by(Species) %>%
    summarise(n(Sepal.Area < 17),
              n(Sepal.Area > 17 & Sepal.Area < 22),
              n(Sepal.Area > 22))
</code>```

What is the easiest way to get counts by multiple filters on a grouping?
Or simply run each one and join them later?

答:
you can try cut:

```<code>iris %>%
    mutate(Sepal.Area = Sepal.Length * Sepal.Width,
           Petal.Area = Petal.Length * Petal.Width,
           range = cut(Sepal.Area, breaks = c(0, 17, 22, Inf))) %>%
    group_by(Species, range) %>%
    summarize(count = n())

#      Species    range count
#       <fctr>   <fctr> <int>
# 1     setosa   (0,17]    25
# 2     setosa  (17,22]    22
# 3     setosa (22,Inf]     3
# 4 versicolor   (0,17]    28
# 5 versicolor  (17,22]    21
# 6 versicolor (22,Inf]     1
# 7  virginica   (0,17]    10
# 8  virginica  (17,22]    31
# 9  virginica (22,Inf]     9
</code>```

Title: Dplyr tally/count by multiple filters

Body:
I am trying to create a summarise/filter dplyr pipeline which will be equivalent to the below:

iris %>%
mutate(Sepal.Area = Sepal.Length * Sepal.Width,
       Petal.Area = Petal.Length * Petal.Width) %>%
  group_by(Species) %>%
      filter(Sepal.Area < 17) %>%
        tally() %>%
      filter(Sepal.Area > 17 & Sepal.Area < 22) %>%
        tally() %>%
      filter(Sepal.Area > 22) %>%
        tally()

Or another potential approach:

iris %>%
  mutate(Sepal.Area = Sepal.Length * Sepal.Width,
         Petal.Area = Petal.Length * Petal.Width) %>%
  group_by(Species) %>%
    summarise(n(Sepal.Area < 17),
              n(Sepal.Area > 17 & Sepal.Area < 22),
              n(Sepal.Area > 22))

What is the easiest way to get counts by multiple filters on a grouping?
Or simply run each one and join them later?

Body:
you can try cut:

iris %>%
    mutate(Sepal.Area = Sepal.Length * Sepal.Width,
           Petal.Area = Petal.Length * Petal.Width,
           range = cut(Sepal.Area, breaks = c(0, 17, 22, Inf))) %>%
    group_by(Species, range) %>%
    summarize(count = n())

#      Species    range count
#       <fctr>   <fctr> <int>
# 1     setosa   (0,17]    25
# 2     setosa  (17,22]    22
# 3     setosa (22,Inf]     3
# 4 versicolor   (0,17]    28
# 5 versicolor  (17,22]    21
# 6 versicolor (22,Inf]     1
# 7  virginica   (0,17]    10
# 8  virginica  (17,22]    31
# 9  virginica (22,Inf]     9


问:
Select collection of cells
I need to select a collection of cells in a worksheet. I could find how to select a range, but not when the cells are "isolated".

For example "$D$4", $G$9" ...

My code:

```<code>var excelApp = Globals.ThisAddIn.Application;

List<string> unlockedCells = new List<string>();
foreach (_Excel.Range cells in excelApp.ActiveSheet.UsedRange)
{
    if (!cells.Locked)
    {
        unlockedCells.Add(cells.Address);
    }
}

unlockedCells.ForEach(_c =>
{
    excelApp.Range[_c].Select();
});
</code>```

The problem here is that every time a new range is selected, the previous selection is lost.

Another approach. It doesn't work, raises exception Exception from HRESULT: 0x800A03EC at Microsoft.Office.Interop.Excel._Application.get_Range(Object Cell1, Object Cell2)

The range I get is the following: "$D$8,$E$8,$D$9,$E$9,$D$10,$E$10,$D$11,$E$11,$D$12,$E$12"

```<code>StringBuilder output = new StringBuilder();
...
output.Append(String.Format("{0},", cells.Address));
string rangeDef = output.ToString().Left(output.Length - 1);
excelApp.Range[rangeDef].Select();
</code>```

How could I achieve it?

Office Version 2016

答:
```<code>List<string> cells = new List<string>();
cells.Add("$C$4");
cells.Add("$D$5");
cells.Add("$H$10");

for (int idx = 0; idx < cells.Count; idx++)
    cells[idx] = String.Format("'{0}'!{1}", (excelApp.ActiveSheet as _Excel.Worksheet).Name, cells[idx]);
string rangeDef = String.Format("={0}", String.Join(";", cells));

var sheet = (excelApp.ActiveSheet as _Excel.Worksheet).get_Range(rangeDef, Type.Missing).Select();
</code>```

It seems I was missing the worksheet name.

Title: Select collection of cells

Body:
I need to select a collection of cells in a worksheet. I could find how to select a range, but not when the cells are "isolated".

For example "$D$4", $G$9" ...

My code:

var excelApp = Globals.ThisAddIn.Application;

List<string> unlockedCells = new List<string>();
foreach (_Excel.Range cells in excelApp.ActiveSheet.UsedRange)
{
    if (!cells.Locked)
    {
        unlockedCells.Add(cells.Address);
    }
}

unlockedCells.ForEach(_c =>
{
    excelApp.Range[_c].Select();
});

The problem here is that every time a new range is selected, the previous selection is lost.

Another approach. It doesn't work, raises exception Exception from HRESULT: 0x800A03EC at Microsoft.Office.Interop.Excel._Application.get_Range(Object Cell1, Object Cell2)

The range I get is the following: "$D$8,$E$8,$D$9,$E$9,$D$10,$E$10,$D$11,$E$11,$D$12,$E$12"

StringBuilder output = new StringBuilder();
...
output.Append(String.Format("{0},", cells.Address));
string rangeDef = output.ToString().Left(output.Length - 1);
excelApp.Range[rangeDef].Select();

How could I achieve it?

Office Version 2016

Body:
List<string> cells = new List<string>();
cells.Add("$C$4");
cells.Add("$D$5");
cells.Add("$H$10");

for (int idx = 0; idx < cells.Count; idx++)
    cells[idx] = String.Format("'{0}'!{1}", (excelApp.ActiveSheet as _Excel.Worksheet).Name, cells[idx]);
string rangeDef = String.Format("={0}", String.Join(";", cells));

var sheet = (excelApp.ActiveSheet as _Excel.Worksheet).get_Range(rangeDef, Type.Missing).Select();

It seems I was missing the worksheet name.


问:
AppCompatActivity.onCreate can only be called from within the same library group
After upgrading to appcompat 25.1.0 I've started getting weird errors.

In my code:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
</code>```

I get lint error:

AppCompatActivity.onCreate can only be called from within the same library group (groupId=com.android.support)

How to prevent such behavior?

答:
Disabling the warning in lintOptions doesn't look a good option it's better to suppress inspection at the statement level.

Add this comment above the line of code which gives the warning:

```<code>//noinspection RestrictedApi
</code>```

ContentLicense: CC BY-SA 4.0

Body:
After upgrading to appcompat 25.1.0 I've started getting weird errors.

In my code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

I get lint error:

AppCompatActivity.onCreate can only be called from within the same library group (groupId=com.android.support)

How to prevent such behavior?

Body:
Disabling the warning in lintOptions doesn't look a good option it's better to suppress inspection at the statement level.

Add this comment above the line of code which gives the warning:

//noinspection RestrictedApi


问:
Custom InfoWindow for particular markers
I'm working on cab booking app where I use different type of markers(one for passenger and many for the cabs ) for the passenger marker I don't need a custom InfoWindow , but for the cabs'( where I show different information about them that can possibaly change) I do,therefore I've customed an InfoWindow one using a resource layout file (info_window.xml), but whatever I've tried (even using hideInfoWindow(); ) I couldn't hide the passenger's InfoWindow, also whenever I try to set Text to an InfoWindow TextView the app cruches ,If what I'm trying to  is possible then what I'm doing wrong ? If it is not, is there an other way to show information without using InfoWindows , something similar to this perhaps !
enter image description here knowing that the InfoWindow have been converted to Bitmap I tried also to use Simple information balloon annotation for Android MapView as in this link https://github.com/jgilfelt/android-mapviewballoons but it's deprecated ,What should I use instead !!
Ps:I need to have a clickable button on it.

this is info_window.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:weightSum="1">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tvLatitude"
        android:text="Latitude"
        android:layout_marginRight="15dp"
         />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tvLongitude"
        android:text="Longitude"
        android:layout_marginRight="10dp"/>

</LinearLayout>
</code>```

and those are parts from MapActivity.java

```<code>public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private BroadcastReceiver broadcastReceiver;
GoogleMap map;
static Double latt, lngg;
private String[] perms = {"android.permission.ACCESS_COARSE_LOCATION",
        "android.permission.ACCESS_FINE_LOCATION",
        "android.permission.INTERNET"};
HashMap<Integer, Marker> markerMap = new HashMap<Integer, Marker>();
Marker marker;

 @Override
 protected void onResume() {
    super.onResume();
    if(broadcastReceiver == null){
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                getJSON();
                lngg= intent.getDoubleExtra("longitude",-1);
                latt= intent.getDoubleExtra("latitude",-1);

                Marker m =map.addMarker(new MarkerOptions()
                        .position(new LatLng(latt,lngg))
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.icon2))
                        .title("I'm a passenger"));
                     m.hideInfoWindow();
              //  goToLocationZoom(latt, lngg , 15) ;

            }
        };
    }
    registerReceiver(broadcastReceiver, new IntentFilter("location_update"));

}

class BackgroundTask extends AsyncTask<Void,Void,String>{
    String JSON_STRING;
    String json_url ;
    @Override
    protected void onPreExecute() {

        json_url="http://frequentative-hicko.000webhostapp.com/FetchLocAndId.php";
    }

    @Override
    protected String doInBackground(Void... voids) {

        try {
            URL url = new URL(json_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader= new BufferedReader( new InputStreamReader(inputStream));
            StringBuilder stringBuilder= new StringBuilder();
            while( (JSON_STRING = bufferedReader.readLine()) != null ){

                stringBuilder.append(JSON_STRING+"\n");
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return stringBuilder.toString().trim();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String response) {
        TextView textView =(TextView) findViewById(R.id.textView2);
      //  textView.setText(response); //JSON Format

        // System.out.println("json_string="+json_string);
        if(response== null){

            Toast.makeText(getApplicationContext(),response,Toast.LENGTH_LONG);

        }
        else {

            try {
                JSONObject jsonObject = new JSONObject(response);
                JSONArray jsonArray = jsonObject.getJSONArray("response");
                int i=0 ;
                int id,e;
                Double lt,lg;
                while (i<jsonArray.length()) {
                    JSONObject jo = jsonArray.getJSONObject(i);
                    e=  jo.getInt("etat");

                    id= jo.getInt("driver_id");

                    lt=jo.getDouble("latitude");

                    lg= jo.getDouble("longitude");

                     if(e==0){
                         marker = markerMap.get(id);
                         if(marker != null){
                             marker.remove();
                             markerMap.remove(id);
                         }else
                         {
                             markerMap.remove(id);
                         }
                     }else{
 map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

                             // Use default InfoWindow frame
                             @Override
                             public View getInfoWindow(Marker arg0) {

                       return null;
                             }

                             // Defines the contents of the InfoWindow
                             @Override
                             public View getInfoContents(Marker arg0) {

                                 // Getting view from the layout file info_window_layout
                                 View v = getLayoutInflater().inflate(R.layout.info_window, null);

                                 // Getting the position from the marker
                                 TextView tvLatitude= (TextView) findViewById(R.id.tvLatitude);
                                tvLatitude.setText("Latitude ");
                                 // Returning the view containing InfoWindow contents
                                 return v;

                             }
                         });
                         if (markerMap.containsKey(id)) {

                    // Update the location.
                    marker = markerMap.get(id);
                    marker.remove();
                    markerMap.remove(id); //added
                    MarkerOptions markerOpt = new MarkerOptions()
                            .title("route_direct").position(new LatLng(lt,lg)).visible(true);
                    marker = map.addMarker(markerOpt);
                    markerMap.put(id, marker);

                    } else {

                        MarkerOptions markerOpt = new MarkerOptions()
                                .title("route_direct").position(new     LatLng(lt, lg)).visible(true);

                        marker = map.addMarker(markerOpt);
                        markerMap.put(id, marker);

                    }}

                    i++;}

                    }catch (JSONException e) {
            e.printStackTrace();
            AlertDialog.Builder nbuilder = new AlertDialog.Builder(MapActivity.this);
            nbuilder.setMessage("Erreur")
                    .setNegativeButton("Retry", null)
                    .create()
                    .show();
            }

        }

   }
   }
   }
</code>```

this the error I got

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
              Process: androidloginandregistration.inducesmile.com.ataxiapp, PID: 7484
              java.lang.NullPointerException
                  at androidloginandregistration.inducesmile.com.ataxiapp.MapActivity$BackgroundTask$1.getInfoWindow(MapActivity.java:331)
                  at com.google.android.gms.maps.GoogleMap$7.zzh(Unknown Source)
                  at com.google.android.gms.maps.internal.zzd$zza.onTransact(Unknown Source)
                  at android.os.Binder.transact(Binder.java:361)
                  at com.google.android.gms.maps.internal.p.a(:com.google.android.gms.DynamiteModulesB:94)
                  at com.google.maps.api.android.lib6.impl.by.a(:com.google.android.gms.DynamiteModulesB:89)
                  at com.google.maps.api.android.lib6.impl.by.a(:com.google.android.gms.DynamiteModulesB:124)
                  at com.google.maps.api.android.lib6.gmm6.api.e.a(:com.google.android.gms.DynamiteModulesB:188)
                  at com.google.maps.api.android.lib6.gmm6.api.g.c(:com.google.android.gms.DynamiteModulesB:200)
                  at com.google.maps.api.android.lib6.impl.db.g(:com.google.android.gms.DynamiteModulesB:23225)
                  at com.google.maps.api.android.lib6.impl.dd.b(:com.google.android.gms.DynamiteModulesB:304)
                  at com.google.maps.api.android.lib6.gmm6.api.e.a(:com.google.android.gms.DynamiteModulesB:242)
                  at com.google.maps.api.android.lib6.gmm6.vector.m.a(:com.google.android.gms.DynamiteModulesB:4070)
                  at com.google.maps.api.android.lib6.gmm6.vector.af.c(:com.google.android.gms.DynamiteModulesB:611)
                  at com.google.maps.api.android.lib6.gmm6.vector.df.onSingleTapConfirmed(:com.google.android.gms.DynamiteModulesB:236)
                  at com.google.maps.api.android.lib6.impl.gesture.g.onSingleTapConfirmed(:com.google.android.gms.DynamiteModulesB:189)
                  at com.google.maps.api.android.lib6.impl.gesture.i.handleMessage(:com.google.android.gms.DynamiteModulesB:132)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:136)
                  at android.app.ActivityThread.main(ActivityThread.java:5476)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:515)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
                  at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
I'm giving the steps here

Inflate your view in onCreate

```<code>public class MapActivity extends AppCompatActivity implements    OnMapReadyCallback {
 ...
 View v;
 ...

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState, 0);
    v = getLayoutInflater().inflate(R.layout.info_window, null);
}
</code>```

Remove your logic from getInfoContents and add in getInfoWindow

```<code>map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

                     // Use default InfoWindow frame
                     @Override
                     public View getInfoWindow(Marker arg0) {

                         // Getting the position from the marker
                         TextView tvLatitude= (TextView) v.findViewById(R.id.tvLatitude);
                        tvLatitude.setText("Latitude ");
                         // Returning the view containing InfoWindow contents

                      return v;
                     }

                     // Defines the contents of the InfoWindow
                     @Override
                     public View getInfoContents(Marker arg0) {
                      if (marker != null && marker.isInfoWindowShown()){
                         marker.hideInfoWindow();
                      }
                      return null;
                    }
                 });
</code>```

Body:
I'm working on cab booking app where I use different type of markers(one for passenger and many for the cabs ) for the passenger marker I don't need a custom InfoWindow , but for the cabs'( where I show different information about them that can possibaly change) I do,therefore I've customed an InfoWindow one using a resource layout file (info_window.xml), but whatever I've tried (even using hideInfoWindow(); ) I couldn't hide the passenger's InfoWindow, also whenever I try to set Text to an InfoWindow TextView the app cruches ,If what I'm trying to  is possible then what I'm doing wrong ? If it is not, is there an other way to show information without using InfoWindows , something similar to this perhaps !
enter image description here knowing that the InfoWindow have been converted to Bitmap I tried also to use Simple information balloon annotation for Android MapView as in this link https://github.com/jgilfelt/android-mapviewballoons but it's deprecated ,What should I use instead !!
Ps:I need to have a clickable button on it.

this is info_window.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:weightSum="1">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tvLatitude"
        android:text="Latitude"
        android:layout_marginRight="15dp"
         />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tvLongitude"
        android:text="Longitude"
        android:layout_marginRight="10dp"/>

</LinearLayout>

and those are parts from MapActivity.java

public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private BroadcastReceiver broadcastReceiver;
GoogleMap map;
static Double latt, lngg;
private String[] perms = {"android.permission.ACCESS_COARSE_LOCATION",
        "android.permission.ACCESS_FINE_LOCATION",
        "android.permission.INTERNET"};
HashMap<Integer, Marker> markerMap = new HashMap<Integer, Marker>();
Marker marker;

 @Override
 protected void onResume() {
    super.onResume();
    if(broadcastReceiver == null){
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                getJSON();
                lngg= intent.getDoubleExtra("longitude",-1);
                latt= intent.getDoubleExtra("latitude",-1);

                Marker m =map.addMarker(new MarkerOptions()
                        .position(new LatLng(latt,lngg))
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.icon2))
                        .title("I'm a passenger"));
                     m.hideInfoWindow();
              //  goToLocationZoom(latt, lngg , 15) ;

            }
        };
    }
    registerReceiver(broadcastReceiver, new IntentFilter("location_update"));

}

class BackgroundTask extends AsyncTask<Void,Void,String>{
    String JSON_STRING;
    String json_url ;
    @Override
    protected void onPreExecute() {

        json_url="http://frequentative-hicko.000webhostapp.com/FetchLocAndId.php";
    }

    @Override
    protected String doInBackground(Void... voids) {

        try {
            URL url = new URL(json_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader= new BufferedReader( new InputStreamReader(inputStream));
            StringBuilder stringBuilder= new StringBuilder();
            while( (JSON_STRING = bufferedReader.readLine()) != null ){

                stringBuilder.append(JSON_STRING+"\n");
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return stringBuilder.toString().trim();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String response) {
        TextView textView =(TextView) findViewById(R.id.textView2);
      //  textView.setText(response); //JSON Format

        // System.out.println("json_string="+json_string);
        if(response== null){

            Toast.makeText(getApplicationContext(),response,Toast.LENGTH_LONG);

        }
        else {

            try {
                JSONObject jsonObject = new JSONObject(response);
                JSONArray jsonArray = jsonObject.getJSONArray("response");
                int i=0 ;
                int id,e;
                Double lt,lg;
                while (i<jsonArray.length()) {
                    JSONObject jo = jsonArray.getJSONObject(i);
                    e=  jo.getInt("etat");

                    id= jo.getInt("driver_id");

                    lt=jo.getDouble("latitude");

                    lg= jo.getDouble("longitude");

                     if(e==0){
                         marker = markerMap.get(id);
                         if(marker != null){
                             marker.remove();
                             markerMap.remove(id);
                         }else
                         {
                             markerMap.remove(id);
                         }
                     }else{
 map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

                             // Use default InfoWindow frame
                             @Override
                             public View getInfoWindow(Marker arg0) {

                       return null;
                             }

                             // Defines the contents of the InfoWindow
                             @Override
                             public View getInfoContents(Marker arg0) {

                                 // Getting view from the layout file info_window_layout
                                 View v = getLayoutInflater().inflate(R.layout.info_window, null);

                                 // Getting the position from the marker
                                 TextView tvLatitude= (TextView) findViewById(R.id.tvLatitude);
                                tvLatitude.setText("Latitude ");
                                 // Returning the view containing InfoWindow contents
                                 return v;

                             }
                         });
                         if (markerMap.containsKey(id)) {

                    // Update the location.
                    marker = markerMap.get(id);
                    marker.remove();
                    markerMap.remove(id); //added
                    MarkerOptions markerOpt = new MarkerOptions()
                            .title("route_direct").position(new LatLng(lt,lg)).visible(true);
                    marker = map.addMarker(markerOpt);
                    markerMap.put(id, marker);

                    } else {

                        MarkerOptions markerOpt = new MarkerOptions()
                                .title("route_direct").position(new     LatLng(lt, lg)).visible(true);

                        marker = map.addMarker(markerOpt);
                        markerMap.put(id, marker);

                    }}

                    i++;}

                    }catch (JSONException e) {
            e.printStackTrace();
            AlertDialog.Builder nbuilder = new AlertDialog.Builder(MapActivity.this);
            nbuilder.setMessage("Erreur")
                    .setNegativeButton("Retry", null)
                    .create()
                    .show();
            }

        }

   }
   }
   }

this the error I got

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: androidloginandregistration.inducesmile.com.ataxiapp, PID: 7484
              java.lang.NullPointerException
                  at androidloginandregistration.inducesmile.com.ataxiapp.MapActivity$BackgroundTask$1.getInfoWindow(MapActivity.java:331)
                  at com.google.android.gms.maps.GoogleMap$7.zzh(Unknown Source)
                  at com.google.android.gms.maps.internal.zzd$zza.onTransact(Unknown Source)
                  at android.os.Binder.transact(Binder.java:361)
                  at com.google.android.gms.maps.internal.p.a(:com.google.android.gms.DynamiteModulesB:94)
                  at com.google.maps.api.android.lib6.impl.by.a(:com.google.android.gms.DynamiteModulesB:89)
                  at com.google.maps.api.android.lib6.impl.by.a(:com.google.android.gms.DynamiteModulesB:124)
                  at com.google.maps.api.android.lib6.gmm6.api.e.a(:com.google.android.gms.DynamiteModulesB:188)
                  at com.google.maps.api.android.lib6.gmm6.api.g.c(:com.google.android.gms.DynamiteModulesB:200)
                  at com.google.maps.api.android.lib6.impl.db.g(:com.google.android.gms.DynamiteModulesB:23225)
                  at com.google.maps.api.android.lib6.impl.dd.b(:com.google.android.gms.DynamiteModulesB:304)
                  at com.google.maps.api.android.lib6.gmm6.api.e.a(:com.google.android.gms.DynamiteModulesB:242)
                  at com.google.maps.api.android.lib6.gmm6.vector.m.a(:com.google.android.gms.DynamiteModulesB:4070)
                  at com.google.maps.api.android.lib6.gmm6.vector.af.c(:com.google.android.gms.DynamiteModulesB:611)
                  at com.google.maps.api.android.lib6.gmm6.vector.df.onSingleTapConfirmed(:com.google.android.gms.DynamiteModulesB:236)
                  at com.google.maps.api.android.lib6.impl.gesture.g.onSingleTapConfirmed(:com.google.android.gms.DynamiteModulesB:189)
                  at com.google.maps.api.android.lib6.impl.gesture.i.handleMessage(:com.google.android.gms.DynamiteModulesB:132)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:136)
                  at android.app.ActivityThread.main(ActivityThread.java:5476)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:515)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
                  at dalvik.system.NativeStart.main(Native Method)

Body:
I'm giving the steps here

Inflate your view in onCreate

public class MapActivity extends AppCompatActivity implements    OnMapReadyCallback {
 ...
 View v;
 ...

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState, 0);
    v = getLayoutInflater().inflate(R.layout.info_window, null);
}

Remove your logic from getInfoContents and add in getInfoWindow

map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

                     // Use default InfoWindow frame
                     @Override
                     public View getInfoWindow(Marker arg0) {

                         // Getting the position from the marker
                         TextView tvLatitude= (TextView) v.findViewById(R.id.tvLatitude);
                        tvLatitude.setText("Latitude ");
                         // Returning the view containing InfoWindow contents

                      return v;
                     }

                     // Defines the contents of the InfoWindow
                     @Override
                     public View getInfoContents(Marker arg0) {
                      if (marker != null && marker.isInfoWindowShown()){
                         marker.hideInfoWindow();
                      }
                      return null;
                    }
                 });


问:
How to import basic symbols in java IDEs
I am using jGRASP and I want to use this symbol: ≥  in my string statement.

```<code>System.out.println("symbol for greater or equal then is ≥");
</code>```

but the problem is I cant copy paste the symbol to the IDE. it gives me weird content:

```<code>PrFont34Bin0BinSub0Frac0Def1Margin0Margin0Jc1Indent1440Lim0Lim1?
</code>```

I can use => but that looks vague for human viewing.

答:
You can \u escape them.

```<code>System.out.println("symbol for greater or equal then is \u2265");
</code>```

Btw, one quick and easy way to get the hex of a symbol if you're copying and pasting is to open http://squarefree.com/shell/shell.html and do something like

```<code>'≥'.charCodeAt(0).toString(16)
</code>```

which should print out the hex.  Then pad that to 4 digits and stick \u in front.
This works for all non-supplemental unicode characters in java except for quotes and newlines.

ContentLicense: CC BY-SA 2.5

Body:
I am using jGRASP and I want to use this symbol: ≥  in my string statement.

System.out.println("symbol for greater or equal then is ≥");

but the problem is I cant copy paste the symbol to the IDE. it gives me weird content:

PrFont34Bin0BinSub0Frac0Def1Margin0Margin0Jc1Indent1440Lim0Lim1?

I can use => but that looks vague for human viewing.

Body:
You can \u escape them.

System.out.println("symbol for greater or equal then is \u2265");

Btw, one quick and easy way to get the hex of a symbol if you're copying and pasting is to open http://squarefree.com/shell/shell.html and do something like

'≥'.charCodeAt(0).toString(16)

which should print out the hex.  Then pad that to 4 digits and stick \u in front.
This works for all non-supplemental unicode characters in java except for quotes and newlines.


问:
Get all comments help, API returns a 403 error
These are the headers I send with my get request to https://oauth.reddit.com/api/morechildren in python, however I get hit with a 403 error each time I try it. In the #code it seems like either the link is incorrect or that I'm not 'allowed' to see it. </p>

```<code>('User-Agent', 'python:xxxxx:xxxxx by (by /u/XXXXXXXXXXXX)')
('Authorization', 'bearer <TOKEN>')
('children', <comma seperated list of ID36s for comments>)
('link_id', 't3_<ID36>')
('sort', 'confidence')
('api_type', 'json')
</code>```

答: You need to send the parameters in POST form values rather than JSON. Here's some examples.</p>

Body:
These are the headers I send with my get request to https://oauth.reddit.com/api/morechildren in python, however I get hit with a 403 error each time I try it. In the #code it seems like either the link is incorrect or that I'm not 'allowed' to see it.

('User-Agent', 'python:xxxxx:xxxxx by (by /u/XXXXXXXXXXXX)')
('Authorization', 'bearer <TOKEN>')
('children', <comma seperated list of ID36s for comments>)
('link_id', 't3_<ID36>')
('sort', 'confidence')
('api_type', 'json')


问:
Jsoup is not Correctly Working
Hello guys i have an problem by Jsoup it is not working and i have no idea to figured it out here is the Code

```<code>    private void getWebsite() {
    Document doc = null;
    try {
        doc = Jsoup.connect("http://www.jean-clermont-schule.de/seite/90384/vertretungsplan.html").get();
        Elements newsHeadlines = doc.select("content");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

And here is an Picture

答: Your code you provided is valid and compiles so the error is likely outside of what you've shown us. Looking at your picture, I guess you've imported the wrong Document class. Check your imports. </p>

Title: Jsoup is not Correctly Working

Body:
Hello guys i have an problem by Jsoup it is not working and i have no idea to figured it out here is the Code

    private void getWebsite() {
    Document doc = null;
    try {
        doc = Jsoup.connect("http://www.jean-clermont-schule.de/seite/90384/vertretungsplan.html").get();
        Elements newsHeadlines = doc.select("content");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

And here is an Picture


问:
=sum(IIF with mid and InStr
How do I combine these two expressions?

I'd like to put

```<code>=mid(Fields!Created_By.Value , InStr(Fields!Created_By.Value,"|")+1)
</code>```

inside the following expression:

```<code>=sum(IIf(Fields!Issue_Status.Value = "New Report", 1, 0),"Incident_Log")
</code>```

答:
Resolved with my problem with:</p>

```<code>=sum(

    iif(mid(Fields!Created_By.Value , InStr(Fields!Created_By.Value,"\")+1)=mid(User!UserID , InStr(User!UserID,"\")+1)
            ,iif(Fields!Issue_Status.Value <> "Closed",1,0)
                    ,0)

,"My_Data_Source")
</code>```

Title: =sum(IIF with mid and InStr

Body:
How do I combine these two expressions?

I'd like to put

=mid(Fields!Created_By.Value , InStr(Fields!Created_By.Value,"|")+1)

inside the following expression:

=sum(IIf(Fields!Issue_Status.Value = "New Report", 1, 0),"Incident_Log")

Body:
Resolved with my problem with:

=sum(

    iif(mid(Fields!Created_By.Value , InStr(Fields!Created_By.Value,"\")+1)=mid(User!UserID , InStr(User!UserID,"\")+1)
            ,iif(Fields!Issue_Status.Value <> "Closed",1,0)
                    ,0)

,"My_Data_Source")


问:
Identify if point is in the polygon
As per my requirement, I am drawing polygons on google map shown in the image below.(using maps v2)

Now I need to show an alert when user enters that particular polygons.

How to identify if my current location is with in the polygon.
(Need optimized way without draining battery)

Thanks in advance.

答:
I found ray-casting method unreliable but I ended up using the PolyUtil from google maps.

You need the dependency compile 'com.google.maps.android:android-maps-utils:0.5'

And then the method looks like this

```<code>PolyUtil.containsLocation(userLocation, polyPointsList, false);
</code>```

EDIT

This is the description of this method found in source code

Computes whether the given point lies inside the specified polygon. The polygon is always considered closed, regardless of whether the last point equals the first or not. Inside is defined as not containing the South Pole -- the South Pole is always outside. The polygon is formed of great circle segments if geodesic is true, and of rhumb (loxodromic) segments otherwise.

Title: Identify if point is in the polygon

Body:
I found ray-casting method unreliable but I ended up using the PolyUtil from google maps.

You need the dependency compile 'com.google.maps.android:android-maps-utils:0.5'

And then the method looks like this

PolyUtil.containsLocation(userLocation, polyPointsList, false);

EDIT

This is the description of this method found in source code

Computes whether the given point lies inside the specified polygon. The polygon is always considered closed, regardless of whether the last point equals the first or not. Inside is defined as not containing the South Pole -- the South Pole is always outside. The polygon is formed of great circle segments if geodesic is true, and of rhumb (loxodromic) segments otherwise.


问:
Use Ajax post call in codeigniter cause Internal Server Error
This is the error message found on google chrome:

POST http://localhost/display/register/registerUser 500 (Internal Server Error)

My project file name is "display".

One controller file named "register" ,it has a function called "registerUser". All it does is getting user's input, and compare it with database to see if the name is used or not, if valid store it into database and give them a success message, if not valid give a error message.

```<code>$username=$this->input->post('name');
    $password=$this->input->post('password');

    $result=$this->user->checkExistUser($username);

    if(!$result){

        $data=array(
            'username'=>$username,
            'password'=>md5($password)
            );

    $this->user->register($data);

    echo "<script>alert('You have success registered');</script>";
    $this->load->view('home_view');
    }
    else{

        echo "<script>alert('Sorry, this email address has been used!');</script>";
        $this->load->view('registerView');
    }
</code>```

This is my view file named registerView

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome to Stock game</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js">
</script>

</head>
<body>

<div id="container">
<h1>Welcome to Stock game!</h1>

<div id="body">
    <p>This is the register page</p>

</div>

<div>

    <form  name="userform" id="userform" >
    <input type="text" name="name" placeholder="Name"/>
    <input type="text" name="password" placeholder="Password"/>

    <button name="submit" value="submit">Register</button>
    </form>
</div>
    <script type="text/javascript">
    $(document).ready(function(){
        $('form#userform').on('submit',function(e){
            e.preventDefault();

    var name=$("#name").val();
    var password=$("#password").val();
    $.ajax({

        type:'POST',
        url:'register/registerUser',
        data:
        {'name':JSON.stringify(name),'password':JSON.stringify(password)},
        dataType:'JSON',
        success: function(response){
            if(response=="success"){
                alert("Yes login");
            }
        },
       error: function (xhr, ajaxOptions, thrownError) {
       alert(xhr.status);
       alert(xhr.responseText);
       alert(thrownError);
   }
   });
        });
    });
    </script>
    </div>
    <br/>
    </body>
    </html>
</code>```

I have tested the controller and model class with a simple form post(form action=xxx, method=post) and it is no error.
I searched almost every stackoverflow questions about this, but i still cannot fix it, I hope someone can help me.

答:
You cannot load a view in ajax call

```<code>$this->load->view('home_view');
</code>```

the above is wrong in the controller

change the controller to this code

```<code>$username=$this->input->post('name');
$password=$this->input->post('password');

$result=$this->user->checkExistUser($username);

if(!$result){

    $data=array(
        'username'=>$username,
        'password'=>md5($password)
        );

$this->user->register($data);

echo "1";

}
else{
    echo "0";
}
</code>```

in view file change your code to the below code

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome to Stock game</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

</head>
<body>

<div id="container">
<h1>Welcome to Stock game!</h1>

<div id="body">
    <p>This is the register page</p>

</div>

<div>

    <form  name="userform" id="userform" >
    <input type="text" name="name" placeholder="Name"/>
    <input type="text" name="password" placeholder="Password"/>

    <button name="submit" value="submit">Register</button>
    </form>
</div>
    <script type="text/javascript">
    $(document).ready(function(){
        $('form#userform').on('submit',function(e){
            e.preventDefault();

    var name=$("#name").val();
    var password=$("#password").val();
    $.ajax({

        type:'POST',
        url:'<?php echo base_url()."register/registerUser"; ?>',
        data: {'name':name,'password':password},
        success: function(response){
            if(response=='0'){
                alert("Failed");
           // with the result you can redirect to the view that is in controller
            window.href.location = '<?php echo base_url()."yoursuccesscontroller/yoursuccessfunction"; ?>';
            }
            else {
                alert('Success');
            //with failure
            window.href.location = '<?php echo base_url()."yourfailurecontroller/yourfailurefunction"; ?>';
            }
        }

   });
        });
    });
    </script>
    </div>
    <br/>
    </body>
    </html>
</code>```

with the result you can redirect to the view that is in controller

Body:
This is the error message found on google chrome:

POST http://localhost/display/register/registerUser 500 (Internal Server Error)

My project file name is "display".

One controller file named "register" ,it has a function called "registerUser". All it does is getting user's input, and compare it with database to see if the name is used or not, if valid store it into database and give them a success message, if not valid give a error message.

$username=$this->input->post('name');
    $password=$this->input->post('password');

    $result=$this->user->checkExistUser($username);

    if(!$result){

        $data=array(
            'username'=>$username,
            'password'=>md5($password)
            );

    $this->user->register($data);

    echo "";
    $this->load->view('home_view');
    }
    else{

        echo "";
        $this->load->view('registerView');
    }

This is my view file named registerView

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>

<meta charset="utf-8">
<title>Welcome to Stock game</title>

Welcome to Stock game!

This is the register page

    <form  name="userform" id="userform" >
    <input type="text" name="name" placeholder="Name"/>
    <input type="text" name="password" placeholder="Password"/>

    <button name="submit" value="submit">Register</button>
    </form>

I have tested the controller and model class with a simple form post(form action=xxx, method=post) and it is no error.
I searched almost every stackoverflow questions about this, but i still cannot fix it, I hope someone can help me.

Body:
You cannot load a view in ajax call

$this->load->view('home_view');

the above is wrong in the controller

change the controller to this code

$username=$this->input->post('name');
$password=$this->input->post('password');

$result=$this->user->checkExistUser($username);

if(!$result){

    $data=array(
        'username'=>$username,
        'password'=>md5($password)
        );

$this->user->register($data);

echo "1";

}
else{
    echo "0";
}

in view file change your code to the below code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome to Stock game</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

</head>
<body>

<div id="container">
<h1>Welcome to Stock game!</h1>

<div id="body">
    <p>This is the register page</p>

</div>

<div>

    <form  name="userform" id="userform" >
    <input type="text" name="name" placeholder="Name"/>
    <input type="text" name="password" placeholder="Password"/>

    <button name="submit" value="submit">Register</button>
    </form>
</div>
    <script type="text/javascript">
    $(document).ready(function(){
        $('form#userform').on('submit',function(e){
            e.preventDefault();

    var name=$("#name").val();
    var password=$("#password").val();
    $.ajax({

        type:'POST',
        url:'<?php echo base_url()."register/registerUser"; ?>',
        data: {'name':name,'password':password},
        success: function(response){
            if(response=='0'){
                alert("Failed");
           // with the result you can redirect to the view that is in controller
            window.href.location = '<?php echo base_url()."yoursuccesscontroller/yoursuccessfunction"; ?>';
            }
            else {
                alert('Success');
            //with failure
            window.href.location = '<?php echo base_url()."yourfailurecontroller/yourfailurefunction"; ?>';
            }
        }

   });
        });
    });
    </script>
    </div>
    <br/>
    </body>
    </html>

with the result you can redirect to the view that is in controller


问:
Collapse 4 bootstrap columns into 2
Considering this footer:   </p>

```<code><footer id="footer" class="dark" style="background-color:#220E2F !important;">
      <div id="footer-container_k" style="margin: auto; display:block;" class="row">
        <div class="col-md-2 col-xs-6 col-md-offset-2" style="position: relative; left:8%;" id="first">
          <div class="buffer">
            <a href="/about"><p>About</p></a>
            <!--<a href="/careers"><p>Careers</p></a>-->
            <a href="/press"><p>Press</p></a>
                <a href="/blog"><p>Blog</p></a>
          </div>
        </div>
        <div class="col-md-2 col-xs-6" style="position: relative; left:2%;" id="second">
          <div class="buffer">
            <a href="/contact"><p>Contact</p></a>
            <a href="https://support.domeha.com/hc/en-us" target="_blank"><p>Support</p></a>
            <a href="http://www.elexausa.com/" target="_blank"><p>Elexa USA</p></a>
            <a href="#" id="footer_modal_button"></a>
          </div>
        </div>
        <div class="col-md-2 col-xs-6" style="position: relative; right:4%;" id="third">
          <div class="buffer">
            <a href="/shop"><p>Z-Wave Products</p></a>
            <a href="https://domeha.com/guardian" target="blank" ><p>Guardian Products</p></a>
            <a href="/how-tos"><p>How-Tos</p></a>
            <!--<a href="/news" target="blank" ><p>Dome News</p></a>-->
          </div>
        </div>
        <div class="col-md-2 col-xs-6" style="position: relative; right:10%;" id="last">
          <div class="buffer">
            <a href="https://www.youtube.com/channel/UCuqjZpsNcaWkbH6T1_PTQ3Q" target="blank" ><p>YouTube</p></a>
            <a href="https://www.facebook.com/DomeByElexa" target="blank" ><p>Facebook</p></a>
            <a href="https://twitter.com/DomeByElexa" target="blank" ><p>Twitter</p></a>
            <a href="https://www.linkedin.com/company/16181754"target="blank" ><p>LinkedIn</p></a>
          </div>
        </div>
      </div>
</code>```

<p>How would I refactor this to collapse into two columns instead of one without positioning them, like I am now? Positioning seems hacky and seems to break very easily. </p>

答:
Remove all the extra styles you added on and they will stack. However the order will be wrong because of the stacking. To reorder try the push and pull approach, mobile first.

http://www.bootply.com/DoMgBuRpDj

```<code><div class="col-md-2 col-xs-6 col-md-push-2" id="third">..</div>
 <div class="col-md-2 col-xs-6 col-md-pull-2" id="second">...</div>
</code>```

Title: Collapse 4 bootstrap columns into 2

Body:
Considering this footer:

About

Press

Blog

Contact

Support

Elexa USA

Z-Wave Products

Guardian Products

How-Tos

YouTube

Facebook

Twitter

LinkedIn

How would I refactor this to collapse into two columns instead of one without positioning them, like I am now? Positioning seems hacky and seems to break very easily.

Body:
Remove all the extra styles you added on and they will stack. However the order will be wrong because of the stacking. To reorder try the push and pull approach, mobile first.

http://www.bootply.com/DoMgBuRpDj

<div class="col-md-2 col-xs-6 col-md-push-2" id="third">..</div>
 <div class="col-md-2 col-xs-6 col-md-pull-2" id="second">...</div>


问:
Different UIImage sizes in custom UITableViewCell
I am downloading a number of images from the internet, from several different locations, all with unknown and differing dimensions.

I have successfully got them all lazy loading nicely and appearing when downloaded in the custom UITableViewCell I created, which has a UIImageView (cellImageView width 320, height 100) inside it.

I am setting the Table's cell and resizing the row height like so:

```<code>- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath
{
    ImageDownloader *download = [imagesModel.downloads objectAtIndex:[indexPath row]];

    if (download.image)
    {
        CGFloat scaleFactor = 320.0f / download.image.size.width;
        CGFloat heightScaled = (scaleFactor * download.image.size.height);

        return heightScaled;
    }
        return 100.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ImageTableCell *cell = (ImageTableCell *)[tableView dequeueReusableCellWithIdentifier:[ImageTableCell reuseIdentifier]];

    if (cell == nil)
    {
        [[NSBundle mainBundle] loadNibNamed:@"ImageTableCell" owner:self options:nil];
        cell = loadCell;
        self.loadCell = nil;
    }
    ImageDownloader *download = [imagesModel.downloads objectAtIndex:[indexPath row]];

    if (download.image == nil)
    {
        download.delegate = self;
    }

    cell.cellImageView.image = download.image;

    return cell;
}
</code>```

Problem is I can't get the cells to display correctly. I have played around with the contentMode of the UIImageView and found the AspectFill works OK but pushes everything upwards causing clipping and masking and stretches some images when they shouldnt be. Using Top solves the vertical problem but the TableViewCell then doesn't fit the image (the image is too big sometimes.

Is the solution is to resize the Table's row, the custom TableViewCell, the UIImage and UIImage? And maybe create my own scaling functionality?

答: Turns out the custom TableViewCell, it's view and the UIImageView were all slightly different heights, giving it the messed up results.</p>

Body:
I am downloading a number of images from the internet, from several different locations, all with unknown and differing dimensions.

I have successfully got them all lazy loading nicely and appearing when downloaded in the custom UITableViewCell I created, which has a UIImageView (cellImageView width 320, height 100) inside it.

I am setting the Table's cell and resizing the row height like so:

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath
{
    ImageDownloader *download = [imagesModel.downloads objectAtIndex:[indexPath row]];

    if (download.image)
    {
        CGFloat scaleFactor = 320.0f / download.image.size.width;
        CGFloat heightScaled = (scaleFactor * download.image.size.height);

        return heightScaled;
    }
        return 100.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ImageTableCell *cell = (ImageTableCell *)[tableView dequeueReusableCellWithIdentifier:[ImageTableCell reuseIdentifier]];

    if (cell == nil)
    {
        [[NSBundle mainBundle] loadNibNamed:@"ImageTableCell" owner:self options:nil];
        cell = loadCell;
        self.loadCell = nil;
    }
    ImageDownloader *download = [imagesModel.downloads objectAtIndex:[indexPath row]];

    if (download.image == nil)
    {
        download.delegate = self;
    }

    cell.cellImageView.image = download.image;

    return cell;
}

Problem is I can't get the cells to display correctly. I have played around with the contentMode of the UIImageView and found the AspectFill works OK but pushes everything upwards causing clipping and masking and stretches some images when they shouldnt be. Using Top solves the vertical problem but the TableViewCell then doesn't fit the image (the image is too big sometimes.

Is the solution is to resize the Table's row, the custom TableViewCell, the UIImage and UIImage? And maybe create my own scaling functionality?


问:
Uncaught Error: [ng:btstrpd]
I am facing the following error in my AngularJS application:

Uncaught Error: [ng:btstrpd]
  http://errors.angularjs.org/1.2.26/ng/btstrpd?p0=document

Someone can help me?

答: After some time researching i found the solution for my problem. I have the AngularJS Batarang Chrome Extension installed on my browser and when it is activated i receive a javascript error. When i deactivate it, the error stops to appear.

Title: Uncaught Error: [ng:btstrpd]


问:
nUnit Assert.Throws TestCase attribute
I have a test method like this: </p>

```<code>[TestCase(16486, "BobBank2.site16486.1", "16486.1")]
[TestCase(16441, "BobBank2.site16441.1", "16441.1")]
[TestCase(16443, "BobBank2.site16443.1", "16443.1")]
public async Task CheckUserAccountLinkStatusTest(int providerId, string username, string userKey)
</code>```

<p>I need to make sure that the first case (16486) throws an error, always. Is it possible to modify the TestCase attribute to do this? </p>

答:
You could check

```<code>if(providerId==16486)
{
    Assert.Throws(...
}
</code>```

but it would be better to have two separate tests, one that checks for the exception when it is expected and one that asserts that there is no exception when there shouldn't be.

Title: nUnit Assert.Throws TestCase attribute

Body:
I have a test method like this:

[TestCase(16486, "BobBank2.site16486.1", "16486.1")]
[TestCase(16441, "BobBank2.site16441.1", "16441.1")]
[TestCase(16443, "BobBank2.site16443.1", "16443.1")]
public async Task CheckUserAccountLinkStatusTest(int providerId, string username, string userKey)

I need to make sure that the first case (16486) throws an error, always. Is it possible to modify the TestCase attribute to do this?

Body:
You could check

if(providerId==16486)
{
    Assert.Throws(...
}

but it would be better to have two separate tests, one that checks for the exception when it is expected and one that asserts that there is no exception when there shouldn't be.