问:
CKEDITOR Using getData()
How to get CKEDITOR first two
 tag value using getData() method.

```<code> var myContent = CKEDITOR.instances.Abody.getData();
</code>```

output

```<code><h1>title</h1> <p>paragraph 1</p> <p>paragraph 2</p>
</code>```

But i need this
 tag values like this.

```<code>var ph1 = paragraph 1
var ph2 = paragraph 2
</code>```

答:
If you are using jquery then you can do something like this.</p>

```<code>var myContent = CKEDITOR.instances.Abody.getData();
var paraList = $(myContent).find('p'); //paraList contains an array of paragraphs now.
$.each(paraList, function(i, node){ console.log( $(node).text());});
</code>```

Title: CKEDITOR Using getData()

Body:
How to get CKEDITOR first two
 tag value using getData() method.

 var myContent = CKEDITOR.instances.Abody.getData();

output

title

paragraph 1

paragraph 2

But i need this
 tag values like this.

var ph1 = paragraph 1
var ph2 = paragraph 2

Body:
If you are using jquery then you can do something like this.

var myContent = CKEDITOR.instances.Abody.getData();
var paraList = $(myContent).find('p'); //paraList contains an array of paragraphs now.
$.each(paraList, function(i, node){ console.log( $(node).text());});


来源: stackexchange

问:
How to update mysql database from csv files in groovy-grails?
I have a table in my database which needs to updates with value for some rows and columns from csv file( this file outside of the grails application). The csv file contains large set of data with map to specific address and city. Some of the address in my application have wrong cities. So I want to get a city from database(grails application db), compare it with the city in csv file, map address to it, and add that address to the application database.

what is the best approach?

答:
For Grails 3 use https://bintray.com/sachinverma/plugins/org.grails.plugins:csv to parse CSV, add the following to build.gradle. The plugin is also available for Grails 2.

```<code>repositories {
    https://bintray.com/sachinverma/plugins/org.grails.plugins:csv
}

dependencies {
    compile "org.grails.plugins:csv:1+"
}
</code>```

Then in your service use like:

```<code>def is
try {
    is = params.csvfile.getInputStream()
    def csvMapReader = new CSVMapReader( new InputStreamReader( is ) )
    csvMapReader.fieldKeys = ["city","address1", "address2"]
    csvMapReader.eachWithIndex { map, idx ->

        def dbEntry = DomainObject.findByAddress1AndAddress2( map.address1, map.address2 )

        if ( map.city != dbEntry.city ) {
            // assuming we're just updating the city on current entry?
            dbEntry.city = map.city
            dbEntry.save()
        }
        // do whatever logic

    }
finally {
    is?.close
}
</code>```

This is of course a simplified version as I don't know you're csv or schema layout.

ContentLicense: CC BY-SA 3.0

Body:
For Grails 3 use https://bintray.com/sachinverma/plugins/org.grails.plugins:csv to parse CSV, add the following to build.gradle. The plugin is also available for Grails 2.

repositories {
    https://bintray.com/sachinverma/plugins/org.grails.plugins:csv
}

dependencies {
    compile "org.grails.plugins:csv:1+"
}

Then in your service use like:

def is
try {
    is = params.csvfile.getInputStream()
    def csvMapReader = new CSVMapReader( new InputStreamReader( is ) )
    csvMapReader.fieldKeys = ["city","address1", "address2"]
    csvMapReader.eachWithIndex { map, idx ->

        def dbEntry = DomainObject.findByAddress1AndAddress2( map.address1, map.address2 )

        if ( map.city != dbEntry.city ) {
            // assuming we're just updating the city on current entry?
            dbEntry.city = map.city
            dbEntry.save()
        }
        // do whatever logic

    }
finally {
    is?.close
}

This is of course a simplified version as I don't know you're csv or schema layout.


问:
To append into jtextarea from another jtextarea using jbutton
I have developed a swing GUI in which I try to populate a text area with the text from another text area using button.

Code:

```<code>private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

jTextArea2.setText(4.0+" "+jTextArea1.getText().trim());
jTextArea1.setText("")
}
</code>```

It is working fine if I enter the text first time in TextArea1 and hit the button to populate the TextArea2. But if I enter a new text in TextArea1 and hit the button instead of appending it to the TextArea2 it replaces the text.

Please suggest me how to correct the same.

答:
You should invoke append no setText

```<code>jTextArea2.append(4.0+" "+jTextArea1.getText().trim());
</code>```

Body:
I have developed a swing GUI in which I try to populate a text area with the text from another text area using button.

Code:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

jTextArea2.setText(4.0+" "+jTextArea1.getText().trim());
jTextArea1.setText("")
}

It is working fine if I enter the text first time in TextArea1 and hit the button to populate the TextArea2. But if I enter a new text in TextArea1 and hit the button instead of appending it to the TextArea2 it replaces the text.

Please suggest me how to correct the same.

Body:
You should invoke append no setText

jTextArea2.append(4.0+" "+jTextArea1.getText().trim());


问:
What are the differences between > and space?
What are the differences between these two styles :

```<code>element1 > element2 {
   ...
}
</code>```

and

```<code>element1 element2 {
   ...
}
</code>```

答:
```<code>element1 element2
</code>```

Selects all elements inside elements

```<code>element1 > element2
</code>```

Selects all elements where the parent is a element

Body:
What are the differences between these two styles :

element1 > element2 {
   ...
}

and

element1 element2 {
   ...
}

Body:
element1 element2

Selects all elements inside elements

element1 > element2

Selects all elements where the parent is a element


问:
Mongo Service running but command line functionalities are not working
I am new to mongo. I am following pluralsight's course to mongo's introduction.

I have installed mongo as a service using command

```<code>C:\Windows\system32>"C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe" --config "C:/mongod.conf" --install
</code>```

Config file consists of  :

```<code>dbpath= C:/pluralsight/db

logpath=C:/pluralsight/mongo-server.log

verbose=vvvvv
</code>```

Then I started the service using

```<code>net start mongodb
</code>```

Inspit eof the service running on my machine, i am not able to run the mongo shell on my system. The course on pluralsight shows the tutor running the shell after the installation, but i am not able to do it. Any reasons why?

答: Try "C:\Program Files\MongoDB\Server\3.4\bin\mongo.exe" instead of just mongo. It doesn't seem to be in your path. If you would like to add it to your path, you can checkout this question here.

Body:
I am new to mongo. I am following pluralsight's course to mongo's introduction.

I have installed mongo as a service using command

C:\Windows\system32>"C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe" --config "C:/mongod.conf" --install

Config file consists of  :

dbpath= C:/pluralsight/db

logpath=C:/pluralsight/mongo-server.log

verbose=vvvvv

Then I started the service using

net start mongodb

Inspit eof the service running on my machine, i am not able to run the mongo shell on my system. The course on pluralsight shows the tutor running the shell after the installation, but i am not able to do it. Any reasons why?


问:
How to inject dispatch into functional React Component?
I need to dispatch an action when an item is clicked within my component. However, I am getting dispatch is undefined when the attendHandler is fired. How do I properly pass dispatch to a component?

This is my action. I am using thunk, so I'm actually return a dispatch.

export function attendEvent(token) {
  const config = {
    headers: { Authorization: token },
  };
  console.log(config);
  return dispatch => axios.post('api/events', config)
  .then((response) => {
    dispatch({ type: 'ATTEND EVENT SUCCESSFUL', payload: response.data });
  })
  .catch((err) => {
    dispatch({ type: 'ATTEND EVENT UNSUCCESSFUL', payload: 'Could not attend event' });
  });
}```
</div>
</div>
</p>

<p>This is my component
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>    import React from 'react';
    import { connect } from 'react-redux';
    import attendEvent from '../actions/eventActions';
    import check from '../assets/hatch_complete.svg';
    import crossout from '../assets/hatch_multiply.svg';

    const Event = (props) => {
      const attendHandler = (e) => {
        e.preventDefault();
        dispatch(attendEvent({
          token: window.localStorage.getItem('token'),
        }));
      };
      return (
        <div className="event">
          <section className="eventdescription">
            <p>{props.title}</p>
            <p>{props.description}</p>
            <p>{props.date}</p>
            <p>{props.owner}</p>
            <p>{props.attendees}</p>
            <p>{props.capacity}</p>
            <p>Attend / unattend</p>
          </section>
          <section className="attend"><img onClick={attendHandler}className="eventgraphic" src={check} alt="" /></section>
          <section className="unattend"><img className="eventgraphic" src={crossout} alt="" /></section>
        </div>
      );
    };

    export default connect(state => ({
      events: state.event.events,
    }))(Event);</code>```

This is my store, in case it is needed for reference. I do not mapDispatchToProps, perhaps that is my problem.

import { applyMiddleware, createStore } from 'redux';
import { createLogger } from 'redux-logger';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

export default createStore(rootReducer, applyMiddleware(thunk, createLogger()));```

答: dispatch is available as props, so it can be called with props.dispatch

Body:
I need to dispatch an action when an item is clicked within my component. However, I am getting dispatch is undefined when the attendHandler is fired. How do I properly pass dispatch to a component?

This is my action. I am using thunk, so I'm actually return a dispatch.

export function attendEvent(token) {
  const config = {
    headers: { Authorization: token },
  };
  console.log(config);
  return dispatch => axios.post('api/events', config)
  .then((response) => {
    dispatch({ type: 'ATTEND EVENT SUCCESSFUL', payload: response.data });
  })
  .catch((err) => {
    dispatch({ type: 'ATTEND EVENT UNSUCCESSFUL', payload: 'Could not attend event' });
  });
}

This is my component

    import React from 'react';
    import { connect } from 'react-redux';
    import attendEvent from '../actions/eventActions';
    import check from '../assets/hatch_complete.svg';
    import crossout from '../assets/hatch_multiply.svg';

    const Event = (props) => {
      const attendHandler = (e) => {
        e.preventDefault();
        dispatch(attendEvent({
          token: window.localStorage.getItem('token'),
        }));
      };
      return (

{props.title}

{props.description}

{props.date}

{props.owner}

{props.attendees}

{props.capacity}

Attend / unattend

      );
    };

    export default connect(state => ({
      events: state.event.events,
    }))(Event);

This is my store, in case it is needed for reference. I do not mapDispatchToProps, perhaps that is my problem.

import { applyMiddleware, createStore } from 'redux';
import { createLogger } from 'redux-logger';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

export default createStore(rootReducer, applyMiddleware(thunk, createLogger()));


问:
Not connect bottom point and top point in a line chart plotly
I am trying to plot this graph 1, which is about a trajectory of an object, if it comes out on one side (bottom), it appears on the other side (top), so I don't want the lines that connect these two points every single time it occurs.
What I want is a picture like 2 using plotly; to achieved this I used 'None' value to indicate the gaps as it's indicated in plotly python line-charts documentation. I have a lot of data in the first picture and it's difficult to change the values to 'None' by hand. Is there a way to do what I want with a big amount of data?</p>

答:
Cause you provide no code or something else I tried a solution for you in javascript.

Here is a jsFiddle that should does your desired behaviour automatically. https://jsfiddle.net/n8v85vL5/

All you must to do is providing the variable yDifferenceOnThatPointsShouldNotConnected which is setted in the example to 500. This means, all points, that have a bigger difference than 500 will not be connected. (respectively the code fill in a null value to achieve that).

So it makes: trace1.x:[1,2], trace1.y: [5,599]

to:trace1.x:[1,1.0001,2], trace1.y: [5,null,599]

Cause we inserted a null value to y we must insert a x value too. At this I add 0.0001 to the xValue before (in example jsFiddle line 34).

hope it helps:-) I guess you need it in python: This should be possible, just change the syntax to python


问:
Android: If I choose minSdkVersion=4 and targetSdkVersion="19" then in which sdk version my android app will be developed?
If I choose minSdkVersion=4 and targetSdkVersion="19" then in which sdk version my android app will be developed?

As if my application is supporting minSDK version=4 then how come it will have feature of SdkVersion=19?

So I'm confused about on which version of sdk my android application will be made if I choose minSdkVersion=4 and targetSdkVersion="19", if it supports all the features starting from version 4 to 19, then how it's doing as in version 4 we don't have features of version 9.

Thanks.

答:
```<code><uses-sdk android:minSdkVersion="integer"
          android:targetSdkVersion="integer"
          android:maxSdkVersion="integer" />
</code>```

contained in:

```<code><manifest>
</code>```

description:

Lets you express an application's compatibility with one or more versions of the Android platform, by means of an API Level integer. The API Level expressed by an application will be compared to the API Level of a given Android system, which may vary among different Android devices.

Despite its name, this element is used to specify the API Level, not the version number of the SDK (software development kit) or Android platform. The API Level is always a single integer. You cannot derive the API Level from its associated Android version number (for example, it is not the same as the major version or the sum of the major and minor versions).

Also read the document about Versioning Your Applications.
attributes:

```<code>android:minSdkVersion
</code>```

An integer designating the minimum API Level required for the application to run. The Android system will prevent the user from installing the application if the system's API Level is lower than the value specified in this attribute. You should always declare this attribute.

Caution: If you do not declare this attribute, the system assumes a default value of "1", which indicates that your application is compatible with all versions of Android. If your application is not compatible with all versions (for instance, it uses APIs introduced in API Level 3) and you have not declared the proper minSdkVersion, then when installed on a system with an API Level less than 3, the application will crash during runtime when attempting to access the unavailable APIs. For this reason, be certain to declare the appropriate API Level in the minSdkVersion attribute.
    android:targetSdkVersion
An integer designating the API Level that the application targets. If not set, the default value equals that given to minSdkVersion.

This attribute informs the system that you have tested against the target version and the system should not enable any compatibility behaviors to maintain your app's forward-compatibility with the target version. The application is still able to run on older versions (down to minSdkVersion).

As Android evolves with each new version, some behaviors and even appearances might change. However, if the API level of the platform is higher than the version declared by your app's targetSdkVersion, the system may enable compatibility behaviors to ensure that your app continues to work the way you expect. You can disable such compatibility behaviors by specifying targetSdkVersion to match the API level of the platform on which it's running. For example, setting this value to "11" or higher allows the system to apply a new default theme (Holo) to your app when running on Android 3.0 or higher and also disables screen compatibility mode when running on larger screens (because support for API level 11 implicitly supports larger screens).

There are many compatibility behaviors that the system may enable based on the value you set for this attribute. Several of these behaviors are described by the corresponding platform versions in the Build.VERSION_CODES reference.

To maintain your application along with each Android release, you should increase the value of this attribute to match the latest API level, then thoroughly test your application on the corresponding platform version.

Introduced in: API Level 4
    android:maxSdkVersion
An integer designating the maximum API Level on which the application is designed to run.

In Android 1.5, 1.6, 2.0, and 2.0.1, the system checks the value of this attribute when installing an application and when re-validating the application after a system update. In either case, if the application's maxSdkVersion attribute is lower than the API Level used by the system itself, then the system will not allow the application to be installed. In the case of re-validation after system update, this effectively removes your application from the device.

To illustrate how this attribute can affect your application after system updates, consider the following example:

An application declaring maxSdkVersion="5" in its manifest is published on Google Play. A user whose device is running Android 1.6 (API Level 4) downloads and installs the app. After a few weeks, the user receives an over-the-air system update to Android 2.0 (API Level 5). After the update is installed, the system checks the application's maxSdkVersion and successfully re-validates it. The application functions as normal. However, some time later, the device receives another system update, this time to Android 2.0.1 (API Level 6). After the update, the system can no longer re-validate the application because the system's own API Level (6) is now higher than the maximum supported by the application (5). The system prevents the application from being visible to the user, in effect removing it from the device.

Warning: Declaring this attribute is not recommended. First, there is no need to set the attribute as means of blocking deployment of your application onto new versions of the Android platform as they are released. By design, new versions of the platform are fully backward-compatible. Your application should work properly on new versions, provided it uses only standard APIs and follows development best practices. Second, note that in some cases, declaring the attribute can result in your application being removed from users' devices after a system update to a higher API Level. Most devices on which your application is likely to be installed will receive periodic system updates over the air, so you should consider their effect on your application before setting this attribute.

Introduced in: API Level 4
Future versions of Android (beyond Android 2.0.1) will no longer check or enforce the maxSdkVersion attribute during installation or re-validation. Google Play will continue to use the attribute as a filter, however, when presenting users with applications available for download.

Body:
<uses-sdk android:minSdkVersion="integer"
          android:targetSdkVersion="integer"
          android:maxSdkVersion="integer" />

contained in:

<manifest>

description:

Lets you express an application's compatibility with one or more versions of the Android platform, by means of an API Level integer. The API Level expressed by an application will be compared to the API Level of a given Android system, which may vary among different Android devices.

Despite its name, this element is used to specify the API Level, not the version number of the SDK (software development kit) or Android platform. The API Level is always a single integer. You cannot derive the API Level from its associated Android version number (for example, it is not the same as the major version or the sum of the major and minor versions).

Also read the document about Versioning Your Applications.
attributes:

android:minSdkVersion

An integer designating the minimum API Level required for the application to run. The Android system will prevent the user from installing the application if the system's API Level is lower than the value specified in this attribute. You should always declare this attribute.

Caution: If you do not declare this attribute, the system assumes a default value of "1", which indicates that your application is compatible with all versions of Android. If your application is not compatible with all versions (for instance, it uses APIs introduced in API Level 3) and you have not declared the proper minSdkVersion, then when installed on a system with an API Level less than 3, the application will crash during runtime when attempting to access the unavailable APIs. For this reason, be certain to declare the appropriate API Level in the minSdkVersion attribute.
    android:targetSdkVersion
An integer designating the API Level that the application targets. If not set, the default value equals that given to minSdkVersion.

This attribute informs the system that you have tested against the target version and the system should not enable any compatibility behaviors to maintain your app's forward-compatibility with the target version. The application is still able to run on older versions (down to minSdkVersion).

As Android evolves with each new version, some behaviors and even appearances might change. However, if the API level of the platform is higher than the version declared by your app's targetSdkVersion, the system may enable compatibility behaviors to ensure that your app continues to work the way you expect. You can disable such compatibility behaviors by specifying targetSdkVersion to match the API level of the platform on which it's running. For example, setting this value to "11" or higher allows the system to apply a new default theme (Holo) to your app when running on Android 3.0 or higher and also disables screen compatibility mode when running on larger screens (because support for API level 11 implicitly supports larger screens).

There are many compatibility behaviors that the system may enable based on the value you set for this attribute. Several of these behaviors are described by the corresponding platform versions in the Build.VERSION_CODES reference.

To maintain your application along with each Android release, you should increase the value of this attribute to match the latest API level, then thoroughly test your application on the corresponding platform version.

Introduced in: API Level 4
    android:maxSdkVersion
An integer designating the maximum API Level on which the application is designed to run.

In Android 1.5, 1.6, 2.0, and 2.0.1, the system checks the value of this attribute when installing an application and when re-validating the application after a system update. In either case, if the application's maxSdkVersion attribute is lower than the API Level used by the system itself, then the system will not allow the application to be installed. In the case of re-validation after system update, this effectively removes your application from the device.

To illustrate how this attribute can affect your application after system updates, consider the following example:

An application declaring maxSdkVersion="5" in its manifest is published on Google Play. A user whose device is running Android 1.6 (API Level 4) downloads and installs the app. After a few weeks, the user receives an over-the-air system update to Android 2.0 (API Level 5). After the update is installed, the system checks the application's maxSdkVersion and successfully re-validates it. The application functions as normal. However, some time later, the device receives another system update, this time to Android 2.0.1 (API Level 6). After the update, the system can no longer re-validate the application because the system's own API Level (6) is now higher than the maximum supported by the application (5). The system prevents the application from being visible to the user, in effect removing it from the device.

Warning: Declaring this attribute is not recommended. First, there is no need to set the attribute as means of blocking deployment of your application onto new versions of the Android platform as they are released. By design, new versions of the platform are fully backward-compatible. Your application should work properly on new versions, provided it uses only standard APIs and follows development best practices. Second, note that in some cases, declaring the attribute can result in your application being removed from users' devices after a system update to a higher API Level. Most devices on which your application is likely to be installed will receive periodic system updates over the air, so you should consider their effect on your application before setting this attribute.

Introduced in: API Level 4
Future versions of Android (beyond Android 2.0.1) will no longer check or enforce the maxSdkVersion attribute during installation or re-validation. Google Play will continue to use the attribute as a filter, however, when presenting users with applications available for download.


问:
How to get values of two columns only when both column values are present using bash script
1

2

3   5

4   6

9

I have two columns, if 2nd column contain no values then skip the row  else I want result like two column values only  when both column values are present

sample output

3 5

4 6

答:
In awk:

```<code>$ awk 'NF==2' file
3 5
4 6
</code>```

NF is the number of fields in awk. Above command prints records where field count equals to 2.

Body:
In awk:

$ awk 'NF==2' file
3 5
4 6

NF is the number of fields in awk. Above command prints records where field count equals to 2.


问:
Google Sheets Query language: can you use other SQL instructions like UPDATE, INSERT…?
I have a Google Sheet where I can select rows using its query language with its SQL-like queries: "SELECT A WHERE B > whatever", etc. I have now, however, a different column with a list of IDs, and I want to update all the rows that appear in that column. In SQL terms, I'm trying to do something like:

```<code>UPDATE sheet SET status='read' WHERE id IN (SELECT ID FROM newcolumn)
</code>```

(I hope I'm making myself clear).

The question is: can you run instructions like UPDATE, DELETE, INSERT in Google's query language? If not, how can I do this?

答:
It's not possible, please look at this reference:
https://developers.google.com/chart/interactive/docs/querylanguage

You could achieve this using scripts. Good start is learning range object.

Body:
I have a Google Sheet where I can select rows using its query language with its SQL-like queries: "SELECT A WHERE B > whatever", etc. I have now, however, a different column with a list of IDs, and I want to update all the rows that appear in that column. In SQL terms, I'm trying to do something like:

UPDATE sheet SET status='read' WHERE id IN (SELECT ID FROM newcolumn)

(I hope I'm making myself clear).

The question is: can you run instructions like UPDATE, DELETE, INSERT in Google's query language? If not, how can I do this?


问:
How to add to POST when loading a subgrid in jqGrid?
How do I add a parameter to the POST variable for the subgrid? All I want to do is add a variable called 'q' to the $_POST for the subgrid.

MY JS code:

```<code>$(function(){
var lastsel;
$("#list").jqGrid({
url:'example.php',
postData:{q:1},
datatype: 'json',
mtype: 'POST',
colNames:['Anchor','Description','Email','Url','In Today','Out Today','In Total','Out Total','Credits','Ratio','Status'],
colModel :[
    {name : 'anchor' , index : 'anchor', width : 55, 'editable':true, 'editoptions':{'size':30}},
    {'name' : 'description' , 'index' : 'description', 'width' : 55, 'editable':true, 'edittype':'textarea', 'editoptions':{'rows':'3','cols':'30'}},
    {'name' : 'email' , 'index' : 'email', 'width' : 55, 'editable':true, 'editoptions':{'size':30}},
    {'name' : 'url' , 'index' : 'url', 'width' : 55, 'editable':true, 'editoptions':{'size':30}},
    {'name' : 'in_today' , 'index' : 'in_today', 'width' : 55, 'align' : 'right'},
    {'name' : 'out_today' , 'index' : 'out_today', 'width' : 55, 'align' : 'right'},
    {'name' : 'in_total' , 'index' : 'in_total', 'width' : 55, 'align' : 'right'},
    {'name' : 'out_total' , 'index' : 'out_total', 'width' : 55, 'align' : 'right'},
    {'name' : 'credits' , 'index' : 'credits', 'width' : 55, 'align' : 'right', 'editable':true, 'editoptions':{'size':30}},
    {'name' : 'ratio' , 'index' : 'ratio', 'width' : 55, 'align' : 'right', 'editable':true, 'editoptions':{'size':30}},
    {'name' : 'status' , 'index' : 'status', 'width' : 55,'align' : 'center', 'editable':true, 'edittype':'checkbox', 'editoptions':{'value':"On:Off"}}
],
pager: '#pager',
rowNum:10,
rowList:[10,20,30],
sortname: 'anchor',
sortorder: 'desc',
viewrecords: true,
caption: 'My first grid',
subGrid: true,
subGridUrl: 'example.php',
subGridModel: [{ name  : ['Game','URL'],width : [200,300],params:['email'] }],
onSelectRow: function(id){
    if(id && id!=lastsel){
        jQuery('#list').jqGrid('restoreRow',lastsel);
        jQuery('#list').jqGrid('editRow',id,true);
        lastsel=id;
    }
},
editurl: "server.php"

});
});
</code>```

MY PHP code:

```<code>mysql_connect('****', '****', '****');
mysql_select_db('********');

switch ($_POST['q']) {
case 1:
    $page = $_POST['page'];
    $limit = $_POST['rows'];
    $sidx = $_POST['sidx'];
    $sord = $_POST['sord'];
    if(!$sidx) $sidx =1;

    $sql2 = "SELECT COUNT(id) AS count FROM trades";
    $total = array_shift(mysql_fetch_row(mysql_query($sql2)));

    // calculate the total pages for the query
    $total_pages = ( $total > 0 && $limit > 0) ? ceil($total/$limit) : 0;

    // if for some reasons the requested page is greater than the total
    // set the requested page to total page
    if ($page > $total_pages) $page=$total_pages;

    // calculate the starting position of the rows
    $start = $limit*$page - $limit;

    // if for some reasons start position is negative set it to 0
    // typical case is that the user type 0 for the requested page
    if($start <0) $start = 0;

    // the actual query for the grid data
    $SQL = "SELECT * FROM trades ORDER BY $sidx $sord LIMIT $start , $limit";
    $result = mysql_query( $SQL ) or die("Couldn't execute query.".mysql_error());

    $output->page = $page;
    $output->total = $total_pages;
    $output->records = $total;

    while ($row = mysql_fetch_assoc($result)) {
        switch ($row['status']) {
            case 0:
                $status = 'Off';
                break;
            case 1:
                $status = 'On';
                break;
            case 2:
                $status = 'Approval';
                break;
        }

        $rows[] = array(
                "id" => $row['id'],
                "cell" => array(
                    $row['anchor']
                    ,$row['description']
                    ,$row['email']
                    ,$row['url']
                    ,$row['in_today']
                    ,$row['out_today']
                    ,$row['in_total']
                    ,$row['out_total']
                    ,$row['credits']
                    ,$row['ratio']
                    ,$status
                )
        );
    }
    $output->rows = $rows;
    break;

case 2:
    $id = $_POST['id'];
    $output->id = $id;
    // connect to the database
    $SQL = "SELECT g.title, tp.id, tp.url FROM games AS g, trades_plugs AS tp WHERE tp.trader_id='{$id}' AND g.id = tp.game_id ORDER BY tp.game_id";
    $result = mysql_query( $SQL ) or die("Couldn't execute query.".mysql_error());
    while ($row = mysql_fetch_row($result)) {
        $rows[] = array(
                "id" => $row[1],
                "cell" => array(
                    $row[0]
                    ,$row[2]
                )
        );
    }
    $output->rows = $rows;

    break;
 }

        echo json_encode($output);
</code>```

答:
I don't use PHP myself, but I can say that the client part works correct. I verified that during the loading of the grid will be POSTed the following data

```<code>q=1&_search=false&nd=1291068269374&rows=10&page=1&sidx=anchor&sord=desc
</code>```

So the data are exactly like you want.

ContentLicense: CC BY-SA 2.5

Body:
How do I add a parameter to the POST variable for the subgrid? All I want to do is add a variable called 'q' to the $_POST for the subgrid.

MY JS code:

$(function(){
var lastsel;
$("#list").jqGrid({
url:'example.php',
postData:{q:1},
datatype: 'json',
mtype: 'POST',
colNames:['Anchor','Description','Email','Url','In Today','Out Today','In Total','Out Total','Credits','Ratio','Status'],
colModel :[
    {name : 'anchor' , index : 'anchor', width : 55, 'editable':true, 'editoptions':{'size':30}},
    {'name' : 'description' , 'index' : 'description', 'width' : 55, 'editable':true, 'edittype':'textarea', 'editoptions':{'rows':'3','cols':'30'}},
    {'name' : 'email' , 'index' : 'email', 'width' : 55, 'editable':true, 'editoptions':{'size':30}},
    {'name' : 'url' , 'index' : 'url', 'width' : 55, 'editable':true, 'editoptions':{'size':30}},
    {'name' : 'in_today' , 'index' : 'in_today', 'width' : 55, 'align' : 'right'},
    {'name' : 'out_today' , 'index' : 'out_today', 'width' : 55, 'align' : 'right'},
    {'name' : 'in_total' , 'index' : 'in_total', 'width' : 55, 'align' : 'right'},
    {'name' : 'out_total' , 'index' : 'out_total', 'width' : 55, 'align' : 'right'},
    {'name' : 'credits' , 'index' : 'credits', 'width' : 55, 'align' : 'right', 'editable':true, 'editoptions':{'size':30}},
    {'name' : 'ratio' , 'index' : 'ratio', 'width' : 55, 'align' : 'right', 'editable':true, 'editoptions':{'size':30}},
    {'name' : 'status' , 'index' : 'status', 'width' : 55,'align' : 'center', 'editable':true, 'edittype':'checkbox', 'editoptions':{'value':"On:Off"}}
],
pager: '#pager',
rowNum:10,
rowList:[10,20,30],
sortname: 'anchor',
sortorder: 'desc',
viewrecords: true,
caption: 'My first grid',
subGrid: true,
subGridUrl: 'example.php',
subGridModel: [{ name  : ['Game','URL'],width : [200,300],params:['email'] }],
onSelectRow: function(id){
    if(id && id!=lastsel){
        jQuery('#list').jqGrid('restoreRow',lastsel);
        jQuery('#list').jqGrid('editRow',id,true);
        lastsel=id;
    }
},
editurl: "server.php"

});
});

MY PHP code:

mysql_connect('****', '****', '****');
mysql_select_db('********');

switch ($_POST['q']) {
case 1:
    $page = $_POST['page'];
    $limit = $_POST['rows'];
    $sidx = $_POST['sidx'];
    $sord = $_POST['sord'];
    if(!$sidx) $sidx =1;

    $sql2 = "SELECT COUNT(id) AS count FROM trades";
    $total = array_shift(mysql_fetch_row(mysql_query($sql2)));

    // calculate the total pages for the query
    $total_pages = ( $total > 0 && $limit > 0) ? ceil($total/$limit) : 0;

    // if for some reasons the requested page is greater than the total
    // set the requested page to total page
    if ($page > $total_pages) $page=$total_pages;

    // calculate the starting position of the rows
    $start = $limit*$page - $limit;

    // if for some reasons start position is negative set it to 0
    // typical case is that the user type 0 for the requested page
    if($start <0) $start = 0;

    // the actual query for the grid data
    $SQL = "SELECT * FROM trades ORDER BY $sidx $sord LIMIT $start , $limit";
    $result = mysql_query( $SQL ) or die("Couldn't execute query.".mysql_error());

    $output->page = $page;
    $output->total = $total_pages;
    $output->records = $total;

    while ($row = mysql_fetch_assoc($result)) {
        switch ($row['status']) {
            case 0:
                $status = 'Off';
                break;
            case 1:
                $status = 'On';
                break;
            case 2:
                $status = 'Approval';
                break;
        }

        $rows[] = array(
                "id" => $row['id'],
                "cell" => array(
                    $row['anchor']
                    ,$row['description']
                    ,$row['email']
                    ,$row['url']
                    ,$row['in_today']
                    ,$row['out_today']
                    ,$row['in_total']
                    ,$row['out_total']
                    ,$row['credits']
                    ,$row['ratio']
                    ,$status
                )
        );
    }
    $output->rows = $rows;
    break;

case 2:
    $id = $_POST['id'];
    $output->id = $id;
    // connect to the database
    $SQL = "SELECT g.title, tp.id, tp.url FROM games AS g, trades_plugs AS tp WHERE tp.trader_id='{$id}' AND g.id = tp.game_id ORDER BY tp.game_id";
    $result = mysql_query( $SQL ) or die("Couldn't execute query.".mysql_error());
    while ($row = mysql_fetch_row($result)) {
        $rows[] = array(
                "id" => $row[1],
                "cell" => array(
                    $row[0]
                    ,$row[2]
                )
        );
    }
    $output->rows = $rows;

    break;
 }

        echo json_encode($output);

Body:
I don't use PHP myself, but I can say that the client part works correct. I verified that during the loading of the grid will be POSTed the following data

q=1&_search=false&nd=1291068269374&rows=10&page=1&sidx=anchor&sord=desc

So the data are exactly like you want.


问:
Bootstrap Carousel Not Responding (Jquery placed correctly)
I am currently facing issues in regards to Bootstrap's carousel not responding the navigation buttons being pressed. The majority of my search answers was that Jquery was not correctly BEFORE the Bootstrap CDN. I have tried even copy-pasting other snippets of code from answers and the navigation button still does not respond correctly to clicks.

```<code><head>
<meta charset="utf-8">
<title><!--title--></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css" type="text/css"/>
</head>
</code>```

Only the first image loads correctly, and the carousel seems to be "frozen."

Any help would be greatly appreciated.

Fiddle: https://jsfiddle.net/7dv1wm1w/

答:
You have not included the bootstrap.min.js

Updated fiddle: https://jsfiddle.net/yogesh214/7dv1wm1w/1/

Body:
I am currently facing issues in regards to Bootstrap's carousel not responding the navigation buttons being pressed. The majority of my search answers was that Jquery was not correctly BEFORE the Bootstrap CDN. I have tried even copy-pasting other snippets of code from answers and the navigation button still does not respond correctly to clicks.

<meta charset="utf-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css" type="text/css"/>

Only the first image loads correctly, and the carousel seems to be "frozen."

Any help would be greatly appreciated.

Fiddle: https://jsfiddle.net/7dv1wm1w/

Body:
You have not included the bootstrap.min.js

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" type="text/javascript></script>

Updated fiddle: https://jsfiddle.net/yogesh214/7dv1wm1w/1/


问:
I want to get result in one line. I don't need new dimensions
```<code>   (1:)`(3:)@.(1&=)"0 i.2
1 3
   (1:,2:)`(3:)@.(1&=)"0 i.2
1 2
3 0
</code>```

I want to get

```<code>1 2 3
</code>```

Without new dimensions. Without zeros.

答:
You could have used (1:,2:,3:) 'ignored argument' to form the list, but that doesn't address why you were using @.

Dane's comment about boxing intermediate results and then razing the resulting list is relevant if you want to merge irregularly shaped results. (Which might be what you were trying for, here.)

Body:
   (1:)`(3:)@.(1&=)"0 i.2
1 3
   (1:,2:)`(3:)@.(1&=)"0 i.2
1 2
3 0

I want to get

1 2 3

Without new dimensions. Without zeros.


问:
Getting specific character values from argv[] and making a new const char
I am certain this has been answered before, but I cannot wrap my head around the answers. I am doing an entry C course and there is a provided header, cs50.h, that has the string type in it. So while I have been using it, I am not quite sure how it works.

My goal is to get the characters at argv[1][0] and argv[1][1] into a const char *variable. While I know the answer definitely involves pointers and addresses, I have not been able to find the successful combination. I am asking here in hope that someone can show me the right way with my own code so I can learn how to go about it.

UPDATE I am trying to get the first two char characters from the second (i.e. first string that isn't the file name) thus, argv[1][0] and argv[1][1] So the given input will be something like this helloworld and I just want 'h' and 'e'. I do not know how to combine 'h' and 'e' from the argv array into a const char *variable, which is the requested format I need to pass it to another function.

```<code>#include <stdio.h>
#include <cs50.h>
#include <string.h>

int main(int argc, string argv[])
{

    string saltget[2] = { &argv[1][0] , &argv[1][1] };
    printf("%s\n", saltget);

}
</code>```

答:
Are you sure that you want to convert argv[1][0] and argv[1][1] instead of argv[1][0] and argv[2][0]? I think this code will work for argv[1][0] and argv[1][1].

```<code>int main(int argc, char* argv[])//argv[1] = hello argv[2] = world
{

    const char* saltget[2] = { &argv[1][0] , &argv[1][1] };
    printf("%s\n", saltget[0]);//hello
    printf("%s\n", saltget[1]);//ello

}
</code>```

If you want to convert argv[1][0] and argv[2][0], you can simply change int main(int argc, char* argv[]) to int main(int argc, const char* argv[])

Body:
I am certain this has been answered before, but I cannot wrap my head around the answers. I am doing an entry C course and there is a provided header, cs50.h, that has the string type in it. So while I have been using it, I am not quite sure how it works.

My goal is to get the characters at argv[1][0] and argv[1][1] into a const char *variable. While I know the answer definitely involves pointers and addresses, I have not been able to find the successful combination. I am asking here in hope that someone can show me the right way with my own code so I can learn how to go about it.

UPDATE I am trying to get the first two char characters from the second (i.e. first string that isn't the file name) thus, argv[1][0] and argv[1][1] So the given input will be something like this helloworld and I just want 'h' and 'e'. I do not know how to combine 'h' and 'e' from the argv array into a const char *variable, which is the requested format I need to pass it to another function.

#include <stdio.h>
#include <cs50.h>
#include <string.h>

int main(int argc, string argv[])
{

    string saltget[2] = { &argv[1][0] , &argv[1][1] };
    printf("%s\n", saltget);

}

Body:
Are you sure that you want to convert argv[1][0] and argv[1][1] instead of argv[1][0] and argv[2][0]? I think this code will work for argv[1][0] and argv[1][1].

int main(int argc, char* argv[])//argv[1] = hello argv[2] = world
{

    const char* saltget[2] = { &argv[1][0] , &argv[1][1] };
    printf("%s\n", saltget[0]);//hello
    printf("%s\n", saltget[1]);//ello

}

If you want to convert argv[1][0] and argv[2][0], you can simply change int main(int argc, char* argv[]) to int main(int argc, const char* argv[])


答:
```<code>SELECT EmpId, Yr, Sales,
    CASE WHEN ROW_NUMBER() OVER (PARTITION BY EmpId ORDER BY yr) % 2 = 0
    THEN sales + lag(sales, 1, 0) OVER (PARTITION BY empid ORDER BY yr)
    ELSE sales
    END AS TotalSales2
FROM sales
</code>```

Lag returns the previous row's value - when row_number() is even, add the current row's value to the previous row - otherwise, just show the sales for the current row. Partition each by EmpId, order each by yr - output matches the expected.

Also, thanks so much for adding the DDL/sample data.

Title: Running count for each 2 rows

Body:
I am trying to calculate running count for each 2 rows like below,

CREATE TABLE sales
(
     EmpId INT,
     Yr INT,
     Sales DECIMAL(8,2)
)

INSERT INTO sales (EmpId, Yr, Sales)
VALUES (1, 2005, 12000), (1, 2006, 18000), (1, 2007, 25000),
       (1, 2008, 25000), (1, 2009, 25000),
       (2, 2005, 15000), (2, 2006, 6000), (2, 2007, 6000)

SELECT
    EmpId, Yr, sales,
    SUM(Sales) OVER (PARTITION BY empid ORDER BY empid ROWS BETWEEN 2 PRECEDING AND CURRENT ROW ) AS TotalSales2
FROM
    sales

Output:

EmpId   Yr      sales   TotalSales2
-----------------------------------
  1     2005    12000      12000
  1     2006    18000      30000
  1     2007    25000      55000
  1     2008    25000      68000
  1     2009    25000      75000
  2     2005    15000      15000
  2     2006     6000      21000
  2     2007     6000      27000

But expected output:

EmpId   Yr     Sales    TotalSales2
-----------------------------------
  1     2005    12000   12000
  1     2006    18000   30000
  1     2007    25000   25000
  1     2008    25000   50000
  1     2009    25000   25000
  2     2005    15000   15000
  2     2006     6000   21000
  2     2007     6000    6000

What am I doing wrong in this query?

Note: SQL Servre version is 2012.

Body:
SELECT EmpId, Yr, Sales,
    CASE WHEN ROW_NUMBER() OVER (PARTITION BY EmpId ORDER BY yr) % 2 = 0
    THEN sales + lag(sales, 1, 0) OVER (PARTITION BY empid ORDER BY yr)
    ELSE sales
    END AS TotalSales2
FROM sales

Lag returns the previous row's value - when row_number() is even, add the current row's value to the previous row - otherwise, just show the sales for the current row. Partition each by EmpId, order each by yr - output matches the expected.

Also, thanks so much for adding the DDL/sample data.


问:
HTML5 Background Color fill too big
When I try to make an HTML background color fill for a div, it ends up with a huge amount of extra space at the bottom - I want to make a sort of header, but it becomes really wide. Can someone help me with this?

My HTML is

```<code><div class="header">
    <h1>Welcome to My Site</h1>
</div>
</code>```

My CSS is

```<code>div.header{
  background-color:grey;
}
</code>```

Thanks!

答:
I advise you to use bootstrap, there is lots of community support and documentation and you can even override colors and styles for yourself.

Bootstrap well class could work for you.

```<code><div class="well">
  Look, I'm in a well!
</div>
</code>```

Or the jumbotron for bigger impact.

```<code><div class="jumbotron">
  <h1>Jumbotron</h1>
  <p>This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p>
  <p><a class="btn btn-primary btn-lg">Learn more</a></p>
</div>
</code>```

Title: HTML5 Background Color fill too big

Body:
When I try to make an HTML background color fill for a div, it ends up with a huge amount of extra space at the bottom - I want to make a sort of header, but it becomes really wide. Can someone help me with this?

My HTML is

Welcome to My Site

My CSS is

div.header{
  background-color:grey;
}

Thanks!

Body:
I advise you to use bootstrap, there is lots of community support and documentation and you can even override colors and styles for yourself.

Bootstrap well class could work for you.

<div class="well">
  Look, I'm in a well!
</div>

Or the jumbotron for bigger impact.

<div class="jumbotron">
  <h1>Jumbotron</h1>
  <p>This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p>
  <p><a class="btn btn-primary btn-lg">Learn more</a></p>
</div>


问:
iText add new page
How can you add a new page to an iText document? document.newPage(); doesn't seem to work.

I am using iText with RTF support from http://sourceforge.net/projects/itextrtf/

Part of my code:

```<code>Font titleFont = new Font(Font.COURIER, 14, Font.BOLD);
document.add(new Paragraph("Title1", titleFont));

Table table = new Table(4);
table.setBorderWidth(0);

// Filling table

document.add(table);

document.newPage();

document.add(new Paragraph("Title2", titleFont));

Table table = new Table(4);
table.setBorderWidth(0);

// Filling table

document.add(table);
</code>```

答:
RTF is no longer supported by iText, as the main author of the relevant code moved on to other projects... or was transformed into a frog... or something.  Anyway, I recommend you seek a new RTF library, or perhaps start maintaining it yourself?

At any rate, the Source Is Available, and I suspect the RTFDocument/RTFWriter ignores newPage().  Nope.  RtfWriter2.java:

```<code>/**
 * Adds a page break
 *
 * @return <code>false</code>
 */
public boolean newPage() {
    rtfDoc.add(new RtfNewPage(rtfDoc));
    return true;
}
</code>```

which should just write "//page" into the output file.  Is it there?

Title: iText add new page

Body:
How can you add a new page to an iText document? document.newPage(); doesn't seem to work.

I am using iText with RTF support from http://sourceforge.net/projects/itextrtf/

Part of my code:

Font titleFont = new Font(Font.COURIER, 14, Font.BOLD);
document.add(new Paragraph("Title1", titleFont));

Table table = new Table(4);
table.setBorderWidth(0);

// Filling table

document.add(table);

document.newPage();

document.add(new Paragraph("Title2", titleFont));

Table table = new Table(4);
table.setBorderWidth(0);

// Filling table

document.add(table);

Body:
RTF is no longer supported by iText, as the main author of the relevant code moved on to other projects... or was transformed into a frog... or something.  Anyway, I recommend you seek a new RTF library, or perhaps start maintaining it yourself?

At any rate, the Source Is Available, and I suspect the RTFDocument/RTFWriter ignores newPage().  Nope.  RtfWriter2.java:

/**
 * Adds a page break
 *
 * @return <code>false</code>
 */
public boolean newPage() {
    rtfDoc.add(new RtfNewPage(rtfDoc));
    return true;
}

which should just write "//page" into the output file.  Is it there?


问:
How do you add authentication to a Controller on CakePHP
how do you safely add authentication on CakePHP for a controller? I am following the BookMarker tutorial and want to add the same type of authentication for the login but on the UserController. This is kind of more of a formatting question, but I am not sure what to type in to be able to display that, especially without corrupting the code. Any answers will be greatly appreciated!</p>

```<code><?php

// src/Controller/UsersController.php

namespace App\Controller;

use App\Controller\AppController;
use Cake\Event\Event;

class UsersController extends AppController
{
 public function articles()

{

}
public function index()
{
    $this->set('users', $this->paginate($this->Users->find('all')));    }

public function view($id)
{
    $user = $this->Users->get($id);
    $this->set(compact('user'));
}

public function add()
{
    $user = $this->Users->newEntity();
    if ($this->request->is('post')) {
        $user = $this->Users->patchEntity($user, $this->request->getData());
        if ($this->Users->save($user)) {
            $this->Flash->success(__('The user has been saved.'));
            return $this->redirect(['action' => 'add']);
        }
        $this->Flash->error(__('Unable to add the user.'));
    }
    $this->set('user', $user);
}

public function beforeFilter(Event $event)
{
    parent::beforeFilter($event);
    // Allow users to register and logout.
    // You should not add the "login" action to allow list. Doing so would
    // cause problems with normal functioning of AuthComponent.
    $this->Auth->allow(['add', 'logout']);
}

public function login()
{
    if ($this->request->is('post')) {
        $user = $this->Auth->identify();
        if ($user) {
            $this->Auth->setUser($user);
            return $this->redirect($this->Auth->redirectUrl());
        }
        $this->Flash->error(__('Invalid username or password, try again'));
    }
}

public function logout()
{
    return $this->redirect($this->Auth->logout());
}

}
</code>```

答:
assuming you are using cakephp3 , hope this will help you out
create initialize action in UsersController like this

```<code>public function initialize()
{
   parent::initialize();
    $this->loadComponent('Auth', [
        'authenticate' => [
            'Form' => [
                'fields' => [
                    'username' => 'email',
                    'password' => 'password'
                ]
            ]
        ],
        'loginAction' => [
            'controller' => 'Users',
            'action' => 'login'
        ],
        'unauthorizedRedirect' => $this->referer() // If unauthorized, return them to page they were just on
    ]);

    // Allow the display action so our pages controller
    // continues to work.
    $this->Auth->allow(['display']);
}
</code>```

In bookmark tutorial they keep this code in the appController and all the controllers normally extend this controller so auth component is loaded for all the controllers but as you want the auth component to be used in UsersController so this code will load the Auth Component for your UsersController only

Body:
how do you safely add authentication on CakePHP for a controller? I am following the BookMarker tutorial and want to add the same type of authentication for the login but on the UserController. This is kind of more of a formatting question, but I am not sure what to type in to be able to display that, especially without corrupting the code. Any answers will be greatly appreciated!

<?php

// src/Controller/UsersController.php

namespace App\Controller;

use App\Controller\AppController;
use Cake\Event\Event;

class UsersController extends AppController
{
 public function articles()

{

}
public function index()
{
    $this->set('users', $this->paginate($this->Users->find('all')));    }

public function view($id)
{
    $user = $this->Users->get($id);
    $this->set(compact('user'));
}

public function add()
{
    $user = $this->Users->newEntity();
    if ($this->request->is('post')) {
        $user = $this->Users->patchEntity($user, $this->request->getData());
        if ($this->Users->save($user)) {
            $this->Flash->success(__('The user has been saved.'));
            return $this->redirect(['action' => 'add']);
        }
        $this->Flash->error(__('Unable to add the user.'));
    }
    $this->set('user', $user);
}

public function beforeFilter(Event $event)
{
    parent::beforeFilter($event);
    // Allow users to register and logout.
    // You should not add the "login" action to allow list. Doing so would
    // cause problems with normal functioning of AuthComponent.
    $this->Auth->allow(['add', 'logout']);
}

public function login()
{
    if ($this->request->is('post')) {
        $user = $this->Auth->identify();
        if ($user) {
            $this->Auth->setUser($user);
            return $this->redirect($this->Auth->redirectUrl());
        }
        $this->Flash->error(__('Invalid username or password, try again'));
    }
}

public function logout()
{
    return $this->redirect($this->Auth->logout());
}

}

Body:
assuming you are using cakephp3 , hope this will help you out
create initialize action in UsersController like this

public function initialize()
{
   parent::initialize();
    $this->loadComponent('Auth', [
        'authenticate' => [
            'Form' => [
                'fields' => [
                    'username' => 'email',
                    'password' => 'password'
                ]
            ]
        ],
        'loginAction' => [
            'controller' => 'Users',
            'action' => 'login'
        ],
        'unauthorizedRedirect' => $this->referer() // If unauthorized, return them to page they were just on
    ]);

    // Allow the display action so our pages controller
    // continues to work.
    $this->Auth->allow(['display']);
}

In bookmark tutorial they keep this code in the appController and all the controllers normally extend this controller so auth component is loaded for all the controllers but as you want the auth component to be used in UsersController so this code will load the Auth Component for your UsersController only


问:
Angular 2 Dropdown Options Default Value
In Angular 1 I could select the default option for a drop down box using the following:

```<code><select
    data-ng-model="carSelection"
    data-ng-options = "x.make for x in cars" data-ng-selected="$first">
</select>
</code>```

In Angular 2 I have:

```<code><select class="form-control" [(ngModel)]="selectedWorkout" (ngModelChange)="updateWorkout($event)">
    <option *ngFor="#workout of workouts">{{workout.name}}</option>
</select>
</code>```

How could I select a default option given my option data is:

[{name: 'arm'}, {name: 'back'}, {name:'leg'}] and my value I to default on on is back?

答:
```<code><select class="form-control" name='someting' [ngModel]="selectedWorkout" (ngModelChange)="updateWorkout($event)">
    <option value="{{workout.name}}" *ngFor="#workout of workouts">{{workout.name}}</option>
</select>
</code>```

If you are using form there should be name field inside select tag.

All you need to do is just add value to the option tag.

selectedWorkout value should be "back" , and its done.

Body:
In Angular 1 I could select the default option for a drop down box using the following:

<select
    data-ng-model="carSelection"
    data-ng-options = "x.make for x in cars" data-ng-selected="$first">
</select>

In Angular 2 I have:

<select class="form-control" [(ngModel)]="selectedWorkout" (ngModelChange)="updateWorkout($event)">
    <option *ngFor="#workout of workouts">{{workout.name}}</option>
</select>

How could I select a default option given my option data is:

[{name: 'arm'}, {name: 'back'}, {name:'leg'}] and my value I to default on on is back?

Body:
<select class="form-control" name='someting' [ngModel]="selectedWorkout" (ngModelChange)="updateWorkout($event)">
    <option value="{{workout.name}}" *ngFor="#workout of workouts">{{workout.name}}</option>
</select>

If you are using form there should be name field inside select tag.

All you need to do is just add value to the option tag.

selectedWorkout value should be "back" , and its done.


问:
Smoothing the parallax scrolling of a background image
I've done a bit of research and written a simple bit of jQuery that scrolls the background at a slightly different pace to the foreground, creating a parallaxing effect as you scroll down a website.

Unfortunately it's a bit jerky.

Here's the basic layout of the HMTL:

```<code><body>
    <section>
        Site content goes here.
    </section>
</body>
</code>```

Here's the CSS:

```<code>body {
    background-image: url('../images/bg.png');
    background-repeat: repeat-y;
    background-position: 50% 0;
}
</code>```

Here's the JS:

```<code>$(window).scroll(function () {
    $("body").css("background-position","50% " + ($(this).scrollTop() / 2) + "px");
});
</code>```

https://jsfiddle.net/JohnnyWalkerDesign/ksw5a0Lp/

Pretty simple, but my problem is that it's a bit jerky when you scroll, even on a powerful computer.

Is there a way to make the background parallax animate smoothly?

答:
To make it smooth put the image on a separate div and move the whole element using transform: translate - then you will get really smooth results.

Here is a little example doing something a little bit different but using translate to give you the idea:

HTML:

```<code><div id="wrapper">
     <div id="content">Foreground content</div>
</div>
</code>```

CSS:

```<code>@-webkit-keyframes MOVE-BG {
    0% {
        transform: translate(0%, 0%);
        -webkit-transform: translate(0%, 0%);
    }
    50% {
        transform: translate(-250px, 0%);
        -webkit-transform: translate(-250px, 0%);
    }
    100% {
        transform: translate(0%, 0%);
        -webkit-transform: translate(0%, 0%);
    }
}

#wrapper {
    width: 300px;
    height: 368px;
    overflow: hidden;
}
#content {
    width: 550px;
    height: 368px;
    background: url(http://www.gstatic.com/webp/gallery/1.jpg) 0% 0% repeat;
    text-align: center;
    font-size: 26px;
    color: #000;

    -webkit-animation-name: MOVE-BG;
    -webkit-animation-duration: 10s;
    -webkit-animation-timing-function: linear;
    -webkit-animation-iteration-count: infinite;
}
</code>```

and the fiddle: http://jsfiddle.net/piotku/kbqsLjfL/

from within javascript (using jQuery) you would have to use something like:

```<code>$(".element").css("transform", 'translateY(' + ($(this).scrollTop() / 2) + 'px)');
</code>```

or in vanillaJS:

```<code>backgroundElement.style.transform = 'translateY(' + ($(this).scrollTop() / 2) + 'px)';
</code>```

Body:
I've done a bit of research and written a simple bit of jQuery that scrolls the background at a slightly different pace to the foreground, creating a parallaxing effect as you scroll down a website.

Unfortunately it's a bit jerky.

Here's the basic layout of the HMTL:

        Site content goes here.

Here's the CSS:

body {
    background-image: url('../images/bg.png');
    background-repeat: repeat-y;
    background-position: 50% 0;
}

Here's the JS:

$(window).scroll(function () {
    $("body").css("background-position","50% " + ($(this).scrollTop() / 2) + "px");
});

https://jsfiddle.net/JohnnyWalkerDesign/ksw5a0Lp/

Pretty simple, but my problem is that it's a bit jerky when you scroll, even on a powerful computer.

Is there a way to make the background parallax animate smoothly?

Body:
To make it smooth put the image on a separate div and move the whole element using transform: translate - then you will get really smooth results.

Here is a little example doing something a little bit different but using translate to give you the idea:

HTML:

<div id="wrapper">
     <div id="content">Foreground content</div>
</div>

CSS:

@-webkit-keyframes MOVE-BG {
    0% {
        transform: translate(0%, 0%);
        -webkit-transform: translate(0%, 0%);
    }
    50% {
        transform: translate(-250px, 0%);
        -webkit-transform: translate(-250px, 0%);
    }
    100% {
        transform: translate(0%, 0%);
        -webkit-transform: translate(0%, 0%);
    }
}

#wrapper {
    width: 300px;
    height: 368px;
    overflow: hidden;
}
#content {
    width: 550px;
    height: 368px;
    background: url(http://www.gstatic.com/webp/gallery/1.jpg) 0% 0% repeat;
    text-align: center;
    font-size: 26px;
    color: #000;

    -webkit-animation-name: MOVE-BG;
    -webkit-animation-duration: 10s;
    -webkit-animation-timing-function: linear;
    -webkit-animation-iteration-count: infinite;
}

and the fiddle: http://jsfiddle.net/piotku/kbqsLjfL/

from within javascript (using jQuery) you would have to use something like:

$(".element").css("transform", 'translateY(' + ($(this).scrollTop() / 2) + 'px)');

or in vanillaJS:

backgroundElement.style.transform = 'translateY(' + ($(this).scrollTop() / 2) + 'px)';


答:
Firstly, you need to know what these mean.

minSdkVersion signifies the minimum SDK version (which in turn, refers to the version of Android) that your app needs to support it.
targetSdkVersion signifies the optimal SDK version (the version of Android you actually meant the app for) that your app runs on.

However, there's a third setting you missed out on.

compileSdkVersion is the thing that you are looking for. When you set compileSdkVersion to a value (that's between the minSdkVersion and targetSdkVersion) that points to a valid SDK, your app will compile with that SDK as the preferred SDK.

Check out any project's sample build.gradle file to understand how this works. I've linked one below:
https://github.com/googlesamples/android-UniversalMusicPlayer/blob/master/mobile/build.gradle

Title: Android: If I choose minSdkVersion=4 and targetSdkVersion="19" then in which sdk version my android app will be developed?

Body:
If I choose minSdkVersion=4 and targetSdkVersion="19" then in which sdk version my android app will be developed?

As if my application is supporting minSDK version=4 then how come it will have feature of SdkVersion=19?

So I'm confused about on which version of sdk my android application will be made if I choose minSdkVersion=4 and targetSdkVersion="19", if it supports all the features starting from version 4 to 19, then how it's doing as in version 4 we don't have features of version 9.

Thanks.


问:
How to send a file from one email to another email id in PHP?
I have PHP code where i code for sending attached file via email from one email id to another email id, But the name ,message ,email_id all send but not attached file sended.

```<code><?php

   $name=$_REQUEST['name'];
   $email_id=$_REQUEST['email_id'];
   $message=$_REQUEST['message'];
   $attached_file=$_REQUEST['attached_file'];
   $name= mysql_real_escape_string($name);
   $email_id = mysql_real_escape_string($email_id);
   if(isset($_REQUEST['submit']))
   {
    $sql="select * from user where BINARY name = BINARY '$name' AND
     BINARY email_id = BINARY '$email_id' and status='1'";
   $qex=mysql_query($sql);
   $numrow=mysql_num_rows($qex);
   $res=mysql_fetch_array($qex);
   if($numrow==1)
  {
    $_SESSION['name']=$res['name'];
   $_SESSION['email_id']=$res['email_id'];

        $email_to .= "nehamitta919@gmail.com";
        $email_subject="A user send Tariffs file to their Client";
        $email_from="neha@studioscue.in";

        $email_message = "User Attached File Successfully send     ".$time."\n\n";

        $email_message .= "User Name  : ".$name."\n\n";
        $email_message .= "User Email: ".$email_id."\n\n";
        $email_message .= "User Message: ".$message."\n\n";
        $email_message .= "User Send File: ".$attached_file."\n\n";

        $headers = 'From: '.$email_from."\r\n".
        'Reply-To: '.$email_from."\r\n" .
        'X-Mailer: PHP/' . phpversion();
        @mail($email_to, $email_subject, $email_message, $headers);

        ?>
</code>```

html code :

```<code><form class="form-horizontal" method="post" enctype="multipart/form-data">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label for="inputEmail3" class="col-sm-4 control-label">User name</font></label>
                            <div class="col-sm-4">
                                <input type="text" class="form-control" id="inputEmail3" placeholder="Name" required
                                name="name" value="<?Php echo $uvw['name']; ?>">
                            </div>
                            </div>
                        </div>
                    </div><!----row-------->
                    <br>
                    <br>
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label for="inputEmail3" class="col-sm-4 control-label">User Email Id<br><strong>(Send From)</strong></font></label>
                        <div class="col-sm-4">
                            <input type="text" class="form-control" id="inputEmail3" ng-model="email_id" placeholder="email" required
                            name="email_id" value="<?Php echo $uvw['email_id']; ?>">
                        </div>
                        </div>
                    </div>
                </div><!----row-------->
                <br>
                <br>
            <div class="row">
                <div class="col-md-12">
                    <div class="form-group">
                        <label for="inputEmail3" class="col-sm-4 control-label">Send To</font></label>
                    <div class="col-sm-4">
                        <select required class="form-control" id="client_id" name="client_id" ng-model="client_id">
                                          <option required="required" selected="" hidden="" value="">Select Your Client Email Id</option>
                                           <?php
                        $id= $_SESSION['id'];
                        $qex = mysql_query("select * from client where status!='4' and status!='0' and client.user_id='$id'");
                                            while ($res = mysql_fetch_array($qex)) {
                                                ?>
                                                <option value="<?php echo trim($res['group_id']); ?>">
                                                    <?php
                                                    echo trim($res['group_id']);
                                                    ?>
                                                </option>
                                            <?php }
                                            ?>

                    </select>
                </div>
                </div>
            </div>
        </div><!----row-------->
        <br />
        <br />
        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <label for="inputEmail3" class="col-sm-4 control-label">Message</font></label>
                <div class="col-sm-4">
                    <textarea class="form-control" id="inputEmail3" placeholder="Message" required style="height: 50px;"
                    name="message"></textarea>
                </div>
                </div>
            </div>
        </div><!----row-------->
        <br>
        <br>
    <div class="row"
        <div class="col-md-12">
            <div class="form-group">
                <label for="inputEmail3" class="img-rounded col-sm-4 control-label animate-css-css" >Attach File</font></label>
            <div class="col-sm-3">
                <input type="file"name="attached_file" id="attached_file" required>
            </div>
            </div>
        </div><!----row-------->
        <br>
        <br />
    <div class="form-group">
        <div class="col-sm-offset-5 col-sm-5">
            <button type="submit" class="btn btn-primary col-md-5" name="submit">Send File</button>
        </div>

    </div>
            </form>
</code>```

Please check & reply me. what am i missing.
Thanks & Regards
Ankit

答:
try this code,mention your file name as attachment... </p>

```<code> <?php
        ini_set('max_execution_time', 300);

        $to = "example@gmail.com";
$subject= "Contact Mail";

$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";

         $headers = "From:<developer@gmail.com>"."\r\n" .
         "MIME-Version: 1.0\r\n" .
            "Content-Type: multipart/mixed;\r\n" .
            " boundary=\"{$mime_boundary}\"";

         $message = "This is a multi-part message in MIME format.\n\n" .
            "--{$mime_boundary}\n" .
            "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
            "Content-Transfer-Encoding: 7bit\n\n" .
            "Contact Details"."\n".
         "Name :". $_POST['name']."\n".
          "email :". $_POST['email']."\n";

 $message.="comments :". $_POST['comments']."\n"
 ."\n\n";

         foreach($_FILES as $userfile)
         {
            $tmp_name = $userfile['tmp_name'];
            $type = $userfile['application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
            $name = $userfile['name'];
            $size = $userfile['size'];

            if (file_exists($tmp_name))
            {
               if(is_uploaded_file($tmp_name))
               {
                  $file = fopen($tmp_name,'rb');

                  $data = fread($file,filesize($tmp_name));

                  fclose($file);

                  $data = chunk_split(base64_encode($data));
               }

               $message .= "--{$mime_boundary}\n" .
                  "Content-Type: {$type};\n" .
                  " name=\"{$name}\"\n" .
                  "Content-Disposition: attachment;\n" .
                  " filename=\"{$fileatt_name}\"\n" .
                  "Content-Transfer-Encoding: base64\n\n" .
               $data . "\n\n";
            }
         }

         $message.="--{$mime_boundary}--\n";

         if (mail($to, $subject, $message, $headers)){
         echo "<script>alert('Mail sent Successfully');</script>";
            echo "<script>window.location = 'contact.php';</script>";

         } else {
            echo "<script>alert('Mail Not Send');</script>";
            echo "<script>window.location = 'contact.php';</script>";

        }
        ?>
</code>```

Body:
I have PHP code where i code for sending attached file via email from one email id to another email id, But the name ,message ,email_id all send but not attached file sended.

<?php

   $name=$_REQUEST['name'];
   $email_id=$_REQUEST['email_id'];
   $message=$_REQUEST['message'];
   $attached_file=$_REQUEST['attached_file'];
   $name= mysql_real_escape_string($name);
   $email_id = mysql_real_escape_string($email_id);
   if(isset($_REQUEST['submit']))
   {
    $sql="select * from user where BINARY name = BINARY '$name' AND
     BINARY email_id = BINARY '$email_id' and status='1'";
   $qex=mysql_query($sql);
   $numrow=mysql_num_rows($qex);
   $res=mysql_fetch_array($qex);
   if($numrow==1)
  {
    $_SESSION['name']=$res['name'];
   $_SESSION['email_id']=$res['email_id'];

        $email_to .= "nehamitta919@gmail.com";
        $email_subject="A user send Tariffs file to their Client";
        $email_from="neha@studioscue.in";

        $email_message = "User Attached File Successfully send     ".$time."\n\n";

        $email_message .= "User Name  : ".$name."\n\n";
        $email_message .= "User Email: ".$email_id."\n\n";
        $email_message .= "User Message: ".$message."\n\n";
        $email_message .= "User Send File: ".$attached_file."\n\n";

        $headers = 'From: '.$email_from."\r\n".
        'Reply-To: '.$email_from."\r\n" .
        'X-Mailer: PHP/' . phpversion();
        @mail($email_to, $email_subject, $email_message, $headers);

        ?>

html code :

<form class="form-horizontal" method="post" enctype="multipart/form-data">

                                User name

                                <input type="text" class="form-control" id="inputEmail3" placeholder="Name" required
                                name="name" value="<?Php echo $uvw['name']; ?>">

                            User Email Id
(Send From)

                            <input type="text" class="form-control" id="inputEmail3" ng-model="email_id" placeholder="email" required
                            name="email_id" value="<?Php echo $uvw['email_id']; ?>">

                        Send To

                        <select required class="form-control" id="client_id" name="client_id" ng-model="client_id">
                                          <option required="required" selected="" hidden="" value="">Select Your Client Email Id</option>
                                           <?php
                        $id= $_SESSION['id'];
                        $qex = mysql_query("select * from client where status!='4' and status!='0' and client.user_id='$id'");
                                            while ($res = mysql_fetch_array($qex)) {
                                                ?>
                                                <option value="<?php echo trim($res['group_id']); ?>">
                                                    <?php
                                                    echo trim($res['group_id']);
                                                    ?>
                                                </option>
                                            <?php }
                                            ?>

                    </select>

                    Message

                    <textarea class="form-control" id="inputEmail3" placeholder="Message" required style="height: 50px;"
                    name="message"></textarea>

    <div class="row"

                Attach File

                <input type="file"name="attached_file" id="attached_file" required>

            <button type="submit" class="btn btn-primary col-md-5" name="submit">Send File</button>

            </form>

Please check & reply me. what am i missing.
Thanks & Regards
Ankit

Body:
try this code,mention your file name as attachment...

 <?php
        ini_set('max_execution_time', 300);

        $to = "example@gmail.com";
$subject= "Contact Mail";

$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";

         $headers = "From:<developer@gmail.com>"."\r\n" .
         "MIME-Version: 1.0\r\n" .
            "Content-Type: multipart/mixed;\r\n" .
            " boundary=\"{$mime_boundary}\"";

         $message = "This is a multi-part message in MIME format.\n\n" .
            "--{$mime_boundary}\n" .
            "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
            "Content-Transfer-Encoding: 7bit\n\n" .
            "Contact Details"."\n".
         "Name :". $_POST['name']."\n".
          "email :". $_POST['email']."\n";

 $message.="comments :". $_POST['comments']."\n"
 ."\n\n";

         foreach($_FILES as $userfile)
         {
            $tmp_name = $userfile['tmp_name'];
            $type = $userfile['application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
            $name = $userfile['name'];
            $size = $userfile['size'];

            if (file_exists($tmp_name))
            {
               if(is_uploaded_file($tmp_name))
               {
                  $file = fopen($tmp_name,'rb');

                  $data = fread($file,filesize($tmp_name));

                  fclose($file);

                  $data = chunk_split(base64_encode($data));
               }

               $message .= "--{$mime_boundary}\n" .
                  "Content-Type: {$type};\n" .
                  " name=\"{$name}\"\n" .
                  "Content-Disposition: attachment;\n" .
                  " filename=\"{$fileatt_name}\"\n" .
                  "Content-Transfer-Encoding: base64\n\n" .
               $data . "\n\n";
            }
         }

         $message.="--{$mime_boundary}--\n";

         if (mail($to, $subject, $message, $headers)){
         echo "<script>alert('Mail sent Successfully');</script>";
            echo "<script>window.location = 'contact.php';</script>";

         } else {
            echo "<script>alert('Mail Not Send');</script>";
            echo "<script>window.location = 'contact.php';</script>";

        }
        ?>


问:
How many watchers we can have at max in a single page in an angular applicaiton without affecting the performance?
How many watchers or scope variable can be kept in a page without affecting its performance of the page loading. Whether there is any limit for the scopes which used in terms of number or memory size?</p>

答:
You can have as many watchers as you want.

There is no finite numbers of watchers, if you register 1000 watchers those will all work, if you register 10000 watchers, they will still all work.

I know some blogs mention 2500 watchers being the number after which performance will start degrading. I have never tested this, but I try to keep my watcher count as low as possible anyways.

In my current project which I joined half way through certain pages have around 3.5k watchers and the page works just fine.

All that being said, having too many watchers WILL affect performance.


问:
Are my subclasses causing memory leaks?
I'm subclassing UINavigationController and UITableview and for some reason, my views are leaking memory, although I've implemented all of the proper methods and release calls. When I use the native class instead of a subclass, everything works just fine, without leaking.

EDIT:

Here's my superclass header:

```<code>//
//  MBAbstractViewController.h
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface MBAbstractViewController : UIViewController {
    IBOutlet UIImageView *backgroundImageView;
    NSString *announcementText;
}

@property (nonatomic, retain) NSString *type;
@property (nonatomic, retain) NSDictionary *options;
@property (nonatomic, retain) NSString *announcementText;

-(void) setAnnouncementText:(NSString *)text;

@end
</code>```

Superclass implementation:

```<code>//
//  MBAbstractViewController.m
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import "MBAbstractViewController.h"

@implementation MBAbstractViewController

@synthesize type, options, announcementText;

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    UIColor *clearColor = [[UIColor alloc] colorWithAlphaComponent:0.0];
    [self.view setBackgroundColor: clearColor];
    [clearColor release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||  interfaceOrientation == UIInterfaceOrientationLandscapeRight){
        return YES;
    }else{
        return NO;
    }
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;

}

- (void)dealloc {
    [announcementText release];
    [options release];
    [type release];
    [super dealloc];
}

@end
</code>```

Here's my subclass header:

```<code>//
//  MBAnnouncementViewController.h
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "MBAbstractViewController.h"

@interface MBAnnouncementViewController : MBAbstractViewController {
    IBOutlet UILabel *announcement;
}

- (void) setAnnouncementText:(NSString *)text withSize:(CGFloat)size;

@end
</code>```

and the subclass implementation:

```<code>        //
//  MBAnnouncementViewController.m
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import "MBAnnouncementViewController.h"
#import "Constants.h"[

@implementation MBAnnouncementViewController

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

    [announcement setText:announcementText];

    UIImage *slideImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[[NSString stringWithFormat:@"%@_slide", kTheme]description] ofType:@"png"]];
    [backgroundImageView setImage:slideImage];
    [slideImage release];

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc. that aren't in use.
}

- (void) setAnnouncementText:(NSString *)text withSize:(CGFloat)size{
    UIFont *font = [[UIFont alloc] fontWithSize:size];
    [announcement setFont:font];
    [font release];
    [announcement setText:text];

}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [announcementText release];
    [super dealloc];
}

@end
</code>```

What could be causing memory leaks in a subclass? Am I missing something? (There is more relevant code here.)

答:
In your subclass, I notice that you have an "announcement" variable that doesn't seem to show up in your superclass.

I'm assuming that your superclass has the following variables:

```<code>type
options
announcementText
</code>```

While your subclass has an additional variable:

```<code>announcement
</code>```

In your dealloc of the subclass, you release announcementText (which is also released in the superclass), not announcement, which is probably the cause of your leakage.

Title: Are my subclasses causing memory leaks?

Body:
I'm subclassing UINavigationController and UITableview and for some reason, my views are leaking memory, although I've implemented all of the proper methods and release calls. When I use the native class instead of a subclass, everything works just fine, without leaking.

EDIT:

Here's my superclass header:

//
//  MBAbstractViewController.h
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface MBAbstractViewController : UIViewController {
    IBOutlet UIImageView *backgroundImageView;
    NSString *announcementText;
}

@property (nonatomic, retain) NSString *type;
@property (nonatomic, retain) NSDictionary *options;
@property (nonatomic, retain) NSString *announcementText;

-(void) setAnnouncementText:(NSString *)text;

@end

Superclass implementation:

//
//  MBAbstractViewController.m
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import "MBAbstractViewController.h"

@implementation MBAbstractViewController

@synthesize type, options, announcementText;

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    UIColor *clearColor = [[UIColor alloc] colorWithAlphaComponent:0.0];
    [self.view setBackgroundColor: clearColor];
    [clearColor release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||  interfaceOrientation == UIInterfaceOrientationLandscapeRight){
        return YES;
    }else{
        return NO;
    }
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;

}

- (void)dealloc {
    [announcementText release];
    [options release];
    [type release];
    [super dealloc];
}

@end

Here's my subclass header:

//
//  MBAnnouncementViewController.h
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "MBAbstractViewController.h"

@interface MBAnnouncementViewController : MBAbstractViewController {
    IBOutlet UILabel *announcement;
}

- (void) setAnnouncementText:(NSString *)text withSize:(CGFloat)size;

@end

and the subclass implementation:

        //
//  MBAnnouncementViewController.m
//  GabbaiHD
//
//  Created by Moshe Berman on 11/24/10.
//  Copyright 2010 MosheBerman.com. All rights reserved.
//

#import "MBAnnouncementViewController.h"
#import "Constants.h"[

@implementation MBAnnouncementViewController

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

    [announcement setText:announcementText];

    UIImage *slideImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[[NSString stringWithFormat:@"%@_slide", kTheme]description] ofType:@"png"]];
    [backgroundImageView setImage:slideImage];
    [slideImage release];

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc. that aren't in use.
}

- (void) setAnnouncementText:(NSString *)text withSize:(CGFloat)size{
    UIFont *font = [[UIFont alloc] fontWithSize:size];
    [announcement setFont:font];
    [font release];
    [announcement setText:text];

}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [announcementText release];
    [super dealloc];
}

@end

What could be causing memory leaks in a subclass? Am I missing something? (There is more relevant code here.)

Body:
In your subclass, I notice that you have an "announcement" variable that doesn't seem to show up in your superclass.

I'm assuming that your superclass has the following variables:

type
options
announcementText

While your subclass has an additional variable:

announcement

In your dealloc of the subclass, you release announcementText (which is also released in the superclass), not announcement, which is probably the cause of your leakage.


问:
php cake find() using OR condition
I need a basic "or" in my if else condition in php cake.

```<code>$oTourRecords =  $this->Record->find('all', array(
    'conditions' => array(
        'record.builder_name' => 'rey',
            'or' => array(
                'record.builder_name' => 'norbert',
            )
         )
     )
);
</code>```

basically i need to get if the record contain builder_name = rey or "norbert"
this one returns null.

答:
Try</p>

```<code>$oTourRecords =  $this->Record->find('all', array(
            'conditions' => array(
                'OR' => array(
                        'record.builder_name' => 'norbert',
                        'record.builder_name' => 'rey',
                    )
            )
         ));
</code>```

Title: php cake find() using OR condition

Body:
I need a basic "or" in my if else condition in php cake.

$oTourRecords =  $this->Record->find('all', array(
    'conditions' => array(
        'record.builder_name' => 'rey',
            'or' => array(
                'record.builder_name' => 'norbert',
            )
         )
     )
);

basically i need to get if the record contain builder_name = rey or "norbert"
this one returns null.

Body:
Try

$oTourRecords =  $this->Record->find('all', array(
            'conditions' => array(
                'OR' => array(
                        'record.builder_name' => 'norbert',
                        'record.builder_name' => 'rey',
                    )
            )
         ));


问:
Rubocop MutableConstant not observing frozen string literal comment
I'm using RuboCop 0.46.0 and Ruby 2.3.1.

.rubocop.yml

```<code>Style/FrozenStringLiteralComment:
  EnforcedStyle: always
</code>```

constant.rb

```<code># frozen_string_literal: true

MY_CONSTANT = 'mystring'
</code>```

When run, rubocop -D returns this:

```<code>Inspecting 1 file
C

Offenses:

constant.rb:3:15: C: Style/MutableConstant: Freeze mutable objects assigned to constants.
MY_CONSTANT = 'mystring'
              ^^^^^^^^^^

1 file inspected, 1 offense detected
</code>```

Is there a reason MutableConstant isn't observing my frozen string literal comment?

答:
Not every check makes sense for all Ruby versions. Tell RuboCop the Ruby version to check against.

Add the following to your .rubocop.yml:

```<code>AllCops:
  TargetRubyVersion: 2.3
</code>```

Body:
I'm using RuboCop 0.46.0 and Ruby 2.3.1.

.rubocop.yml

Style/FrozenStringLiteralComment:
  EnforcedStyle: always

constant.rb

# frozen_string_literal: true

MY_CONSTANT = 'mystring'

When run, rubocop -D returns this:

Inspecting 1 file
C

Offenses:

constant.rb:3:15: C: Style/MutableConstant: Freeze mutable objects assigned to constants.
MY_CONSTANT = 'mystring'
              ^^^^^^^^^^

1 file inspected, 1 offense detected

Is there a reason MutableConstant isn't observing my frozen string literal comment?

Body:
Not every check makes sense for all Ruby versions. Tell RuboCop the Ruby version to check against.

Add the following to your .rubocop.yml:

AllCops:
  TargetRubyVersion: 2.3


问:
Render samer result using DOM API as document.write?
I have this function:

```<code>  function getScript(src) {
    document.write('<' + 'script src="' + src + '"' +
                   ' type="text/javascript"><' + '/script>');
  }
</code>```

Due to constrains, I can't use document.write. not supported in xhtml(implemented in firefox). Is there some other way to write it? For example using "DOM API"? I use jquery.

答:
If you just want to get/execute a script, use $.getScript(), like this:

```<code>$.getScript(src);
</code>```

..really just replace your getScript() calls with $.getScript() and do away with the function.  What this does is call $.ajax() with a dataType of "script", which creates a

Body:
I have this function:

  function getScript(src) {
    document.write('<' + 'script src="' + src + '"' +
                   ' type="text/javascript"><' + '/script>');
  }

Due to constrains, I can't use document.write. not supported in xhtml(implemented in firefox). Is there some other way to write it? For example using "DOM API"? I use jquery.

Body:
If you just want to get/execute a script, use $.getScript(), like this:

$.getScript(src);

..really just replace your getScript() calls with $.getScript() and do away with the function.  What this does is call $.ajax() with a dataType of "script", which creates a <script> element and appends it to the <head>, similar to what your code in the question is trying to do writing it in the document.