问:
Ionic 2 : importing custom components / modules with absolute path fails
I'm developing an ionic 2 app with these dependencies:

```<code>"dependencies": {
    "@angular/common": "2.1.1",
    "@angular/compiler": "2.1.1",
    "@angular/compiler-cli": "2.1.1",
    "@angular/core": "2.1.1",
    "@angular/forms": "2.1.1",
    "@angular/http": "2.1.1",
    "@angular/platform-browser": "2.1.1",
    "@angular/platform-browser-dynamic": "2.1.1",
    "@angular/platform-server": "2.1.1",
    "@ionic/storage": "1.1.6",
    "ionic-angular": "^2.0.0-rc.4",
    "ionic-native": "2.2.3",
    "ionicons": "3.0.0",
    "rxjs": "5.0.0-beta.12",
    "zone.js": "0.6.26"
  },
"devDependencies": {
    "@ionic/app-scripts": "0.0.47",
    "typescript": "2.0.6",
    "electron": "^1.4.12",
    "@types/jasmine": "^2.5.38",
    "@types/node": "0.0.2",
    "angular-cli": "^1.0.0-beta.21",
    "codelyzer": "^2.0.0-beta.1"
 }
</code>```

The structure of the app is this one:

```<code>tsconfig.json
webpack.config.json
src
  app
     app.module.ts
  pages
     home
       home.page.ts
     login
  modules
</code>```

When I import a module / Component / Class or whatever from

app.module.ts

using relative paths, theres no problem:

```<code>import { HomePage } from '../pages/home/home.page';
</code>```

I prefer to use absolute paths, but i can't find the way to use them.  I have tried to setup typescript tsconfig.json like this:

```<code>  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "dom",
      "es2015"
    ],
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es5",
    "baseUrl": ".",

     "paths": {
      "*": [
        "*",
        "src/*"
      ]
    }
  }
</code>```

and importing like this:

```<code>import { HomePage } from 'pages/home/home.page';
</code>```

but the typescript compiler gives me this error inside the IDE ( "Cannot find module 'pages/home/home.page'

When executing the ionic app (with ionic serve) this is the error I get:

```<code>Error: Cannot find module "pages/home/home.page"
    at Object.<anonymous> (http://localhost:8100/build/main.js:81745:7)
    at __webpack_require__ (http://localhost:8100/build/main.js:20:30)
    at Object.<anonymous> (http://localhost:8100/build/main.js:104718:70)
    at __webpack_require__ (http://localhost:8100/build/main.js:20:30)
    at http://localhost:8100/build/main.js:66:18
    at http://localhost:8100/build/main.js:69:10
</code>```

The idea I would like to setup is to use absolute paths starting from src/ and then using the folders structure like a namespace path:

So if the path of the component is root/src/pages/home/home.page

Import components using this:

```<code>import { HomePage } from 'pages/home/home.page';
import { LoginPage } from 'pages/login/login.page';
</code>```

The HomePage component is this:

```<code>@Component({
  selector: 'home-page',
  templateUrl: 'home.page.html'
})

export class HomePage {

    // Array of pages for main menu
    pages: Array<{ component: any, name:string }>;

    constructor(public navCtrl: NavController) {
        // set our app's pages
        this.pages = [
            { component: LoginPage, name: 'Login' },
            { component: SyncPage, name: 'Sync Service' },
            { component: FilesPage, name: 'Selecting a file' },
        ];
    }

    gotoPage(page) {
        this.navCtrl.push(page.component);
    }

}
</code>```

Any idea of what I'm doing wrong?

Thanks in advance

答:
I'm having the same issue.
On some preliminar test what seems to be working for me is a slight change on your tsconfig.json:

```<code>"baseUrl": "./src",
"paths": {
  "*": [
    "/src/*"
  ]
}
</code>```

edit: it works on browser, but tscompiler tells that it can't find the modules :|

Body:
I'm developing an ionic 2 app with these dependencies:

"dependencies": {
    "@angular/common": "2.1.1",
    "@angular/compiler": "2.1.1",
    "@angular/compiler-cli": "2.1.1",
    "@angular/core": "2.1.1",
    "@angular/forms": "2.1.1",
    "@angular/http": "2.1.1",
    "@angular/platform-browser": "2.1.1",
    "@angular/platform-browser-dynamic": "2.1.1",
    "@angular/platform-server": "2.1.1",
    "@ionic/storage": "1.1.6",
    "ionic-angular": "^2.0.0-rc.4",
    "ionic-native": "2.2.3",
    "ionicons": "3.0.0",
    "rxjs": "5.0.0-beta.12",
    "zone.js": "0.6.26"
  },
"devDependencies": {
    "@ionic/app-scripts": "0.0.47",
    "typescript": "2.0.6",
    "electron": "^1.4.12",
    "@types/jasmine": "^2.5.38",
    "@types/node": "0.0.2",
    "angular-cli": "^1.0.0-beta.21",
    "codelyzer": "^2.0.0-beta.1"
 }

The structure of the app is this one:

tsconfig.json
webpack.config.json
src
  app
     app.module.ts
  pages
     home
       home.page.ts
     login
  modules

When I import a module / Component / Class or whatever from

app.module.ts

using relative paths, theres no problem:

import { HomePage } from '../pages/home/home.page';

I prefer to use absolute paths, but i can't find the way to use them.  I have tried to setup typescript tsconfig.json like this:

  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "dom",
      "es2015"
    ],
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es5",
    "baseUrl": ".",

     "paths": {
      "*": [
        "*",
        "src/*"
      ]
    }
  }

and importing like this:

import { HomePage } from 'pages/home/home.page';

but the typescript compiler gives me this error inside the IDE ( "Cannot find module 'pages/home/home.page'

When executing the ionic app (with ionic serve) this is the error I get:

Error: Cannot find module "pages/home/home.page"
    at Object.<anonymous> (http://localhost:8100/build/main.js:81745:7)
    at __webpack_require__ (http://localhost:8100/build/main.js:20:30)
    at Object.<anonymous> (http://localhost:8100/build/main.js:104718:70)
    at __webpack_require__ (http://localhost:8100/build/main.js:20:30)
    at http://localhost:8100/build/main.js:66:18
    at http://localhost:8100/build/main.js:69:10

The idea I would like to setup is to use absolute paths starting from src/ and then using the folders structure like a namespace path:

So if the path of the component is root/src/pages/home/home.page

Import components using this:

import { HomePage } from 'pages/home/home.page';
import { LoginPage } from 'pages/login/login.page';

The HomePage component is this:

@Component({
  selector: 'home-page',
  templateUrl: 'home.page.html'
})

export class HomePage {

    // Array of pages for main menu
    pages: Array<{ component: any, name:string }>;

    constructor(public navCtrl: NavController) {
        // set our app's pages
        this.pages = [
            { component: LoginPage, name: 'Login' },
            { component: SyncPage, name: 'Sync Service' },
            { component: FilesPage, name: 'Selecting a file' },
        ];
    }

    gotoPage(page) {
        this.navCtrl.push(page.component);
    }

}

Any idea of what I'm doing wrong?

Thanks in advance

Body:
I'm having the same issue.
On some preliminar test what seems to be working for me is a slight change on your tsconfig.json:

"baseUrl": "./src",
"paths": {
  "*": [
    "/src/*"
  ]
}

edit: it works on browser, but tscompiler tells that it can't find the modules :|


来源: stackexchange

问:
Elasticsearch Auto complete/Suggestion query on korean/chinese/japanese language
Is is possible to implement a suggestion query in Elasticsearch for non-english languages like korean, chinese, japanese etc..??

I tried using ICU Analysis plugin. Though the ICU tokenizers able to tokenize the non-english languages, it was not helping me out while doing a suggestion / Auto complete query.

答:
Chinese lanugage :
 we have Smartcn plugin that can be installed to elasticsearch.

Japanese Language :
 Using Korumoji plugin we can analyze and run queries on Japanese language.

ContentLicense: CC BY-SA 3.0


问:
adding rows after for loop in python
Hi I am new to python if I want to add row to an empty matrix after for loop in python how would I be able to do so. This is how I do it in Matlab.</p>

```<code>n = 10000;
tic
A = [];
for i = 1:n
  Ai = rand(1,3);
  A = [A;Ai];
end
toc
</code>```

答:
Try to use numpy.random

```<code>import numpy as np
A = np.random.randint(1,4, size=(1000, 3))
</code>```

and A should be the matrix you want.

For example,

```<code>import numpy as np
a = np.random.randint(1,4, size=(10, 3))
</code>```

a looks like:

```<code>array([[1, 3, 3],
       [3, 1, 1],
       [2, 2, 1],
       [3, 2, 3],
       [2, 1, 2],
       [3, 3, 2],
       [2, 1, 2],
       [1, 1, 2],
       [2, 1, 1],
       [1, 1, 3]])
</code>```

Title: adding rows after for loop in python

Body:
Hi I am new to python if I want to add row to an empty matrix after for loop in python how would I be able to do so. This is how I do it in Matlab.

n = 10000;
tic
A = [];
for i = 1:n
  Ai = rand(1,3);
  A = [A;Ai];
end
toc

Body:
Try to use numpy.random

import numpy as np
A = np.random.randint(1,4, size=(1000, 3))

and A should be the matrix you want.

For example,

import numpy as np
a = np.random.randint(1,4, size=(10, 3))

a looks like:

array([[1, 3, 3],
       [3, 1, 1],
       [2, 2, 1],
       [3, 2, 3],
       [2, 1, 2],
       [3, 3, 2],
       [2, 1, 2],
       [1, 1, 2],
       [2, 1, 1],
       [1, 1, 3]])


问:
No Such table error(while the table is already exist)... in sqlite database android
Android Monitor:

```<code> android.database.sqlite.SQLiteException:
        no such table: dates (code 1): ,
    while compiling: SELECT dateId FROM dates
</code>```

This is my dates table:

```<code>   db.execSQL("CREATE TABLE "+Date_TABLE+"("+
                KEY_DATE_ID+" INTEGER PRIMARY KEY, "+
                KEY_DATE+" DATE);"
        );
</code>```

答:
You miss a space after the Date_TABLE, should be:

```<code>db.execSQL("CREATE TABLE "+Date_TABLE+" ("+
            KEY_DATE_ID+" INTEGER PRIMARY KEY, "+
            KEY_DATE+" DATE);"
    );
</code>```

This way it creates the table properly.

Let me know if it hepls!

Body:
Android Monitor:

 android.database.sqlite.SQLiteException:
        no such table: dates (code 1): ,
    while compiling: SELECT dateId FROM dates

This is my dates table:

   db.execSQL("CREATE TABLE "+Date_TABLE+"("+
                KEY_DATE_ID+" INTEGER PRIMARY KEY, "+
                KEY_DATE+" DATE);"
        );

Body:
You miss a space after the Date_TABLE, should be:

db.execSQL("CREATE TABLE "+Date_TABLE+" ("+
            KEY_DATE_ID+" INTEGER PRIMARY KEY, "+
            KEY_DATE+" DATE);"
    );

This way it creates the table properly.

Let me know if it hepls!


问:
Destination SMTP server does not want to receive message body
I am using software named send blaster, am using gmail smtp server but it does not allows me to send more then 500 mails, is there any one who knows how can i over come form this prob... need help is there any stmp server or software that can send unlimited mails.</p>

答:
<s>The Best Free mailing solution according to my experience is spark post which gives you 100k emails for free, But do remember when you're using free 3rd party services, you're using shared servers, therefore if other free users send spam from the shared ip, your mail will probably be sent to spam as well, hence I recommend Implementing your own smtp server or going for a paid plan. </s>

UPDATE

After some research it seems sparkpost no longer offer this free package. But there are no good alternatives. Closest I can find is Mailgun, And best case scenario would be if you send from an AWS EC2 server in which case you get 62000 free mail per month SES.

P.S : These are subject to change, and only valid at the time of the update. Down voting this post will not help change company policy.

ContentLicense: CC BY-SA 4.0


问:
I can't understand how the time complexity will be calculated in these 2 cases
Here is the first algorithm. It is not in any proper syntax:

```<code>for(i=1;i<=n;i++)
  {for(j=1;j<=i;j++)
       for(k=1;k<=100;k++)
        {printf("hello")
         }
        }
      }
</code>```

In this case we calculate the time complexity as O(n^2) by seeing the total number of times the printf statement will be executed. So, we add the number of times the k loop will run for each i from 1 to n.

2nd code:

```<code>{int n=(2)^(2)^k //read as 2 to the power 2 to the power k
 for (i=1;i<=n;i++)
 {j=2
  while(j<=n)
  {j=j^2
   printf("hello")
  }
 }
}
</code>```

Here we get the time complexity as O(n(loglogn)). We see that the nth loop will be executed n(k+1) times. We substituted the value of k and got the time complexity.

I dont understand why we didn't add the total number of times the print statement got executed to calculate the time complexity in the 2nd code like we did in the first code. We only saw how many times it runs in the nth loop to calculate the answer.

答:
You need to clear your basics. The time complexity of first loop is O(N^2) and its totally unrelated to printf statement. Its about the total number of iterations of you innermost loop.

Your innermost loop in code 1 runs 100*(N^2) which is O(N^2) , the answer would remain the same even when your code 1 is:

```<code>for(i=1;i<=n;i++)
  {for(j=1;j<=i;j++)
       for(k=1;k<=100;k++)
        {
         }
        }
      }
</code>```

So, as long as your innermost loop has no statement or statement that takes O(1) time, the answer remains the same.

For you second code: while loop always runs log(logn) times and outer loop always runs n times , therefore time complexity is O(nlog(logn)) , because that is the total number of iterations of innermost(while) loop.

Body:
Here is the first algorithm. It is not in any proper syntax:

for(i=1;i<=n;i++)
  {for(j=1;j<=i;j++)
       for(k=1;k<=100;k++)
        {printf("hello")
         }
        }
      }

In this case we calculate the time complexity as O(n^2) by seeing the total number of times the printf statement will be executed. So, we add the number of times the k loop will run for each i from 1 to n.

2nd code:

{int n=(2)^(2)^k //read as 2 to the power 2 to the power k
 for (i=1;i<=n;i++)
 {j=2
  while(j<=n)
  {j=j^2
   printf("hello")
  }
 }
}

Here we get the time complexity as O(n(loglogn)). We see that the nth loop will be executed n(k+1) times. We substituted the value of k and got the time complexity.

I dont understand why we didn't add the total number of times the print statement got executed to calculate the time complexity in the 2nd code like we did in the first code. We only saw how many times it runs in the nth loop to calculate the answer.

Body:
You need to clear your basics. The time complexity of first loop is O(N^2) and its totally unrelated to printf statement. Its about the total number of iterations of you innermost loop.

Your innermost loop in code 1 runs 100*(N^2) which is O(N^2) , the answer would remain the same even when your code 1 is:

for(i=1;i<=n;i++)
  {for(j=1;j<=i;j++)
       for(k=1;k<=100;k++)
        {
         }
        }
      }

So, as long as your innermost loop has no statement or statement that takes O(1) time, the answer remains the same.

For you second code: while loop always runs log(logn) times and outer loop always runs n times , therefore time complexity is O(nlog(logn)) , because that is the total number of iterations of innermost(while) loop.


问:
Regex on io.Text RDD using scala
I have a problem. I need to extract some data from a file like this:

```<code>(3269,
<page>
<title>Anarchism</title>
<ns>0</ns>
<id>12</id>
<revision>...
)
(194712,
<page>
<title>AssistiveTechnology</title>
<ns>0</ns>
<id>23</id>..
) etc...
</code>```

This file was generated using:

```<code>val conf = new Configuration
conf.set("textinputformat.record.delimiter", "</page>")
val rdd=sc.newAPIHadoopFile("sample.bz2", classOf[TextInputFormat], classOf[LongWritable], classOf[Text], conf)
rdd.map{case (k,v) => (k.get(), new String(v.copyBytes()))}
</code>```

I need to obtain the title content. Im using regex but the output file still remains empty. My code is like this:

```<code>val xx = rdd.map(x => x._2).filter(x => x.matches(".*<title>([A-Za-z]+)<\\/title>.*"))
</code>```

I also try with these:

```<code>".*<title>([A-Za-z]+)</title>.*"
</code>```

And using this:

```<code>val reg = ".*<title>([\\w]+)</title>.*".r
val xx = rdd.map(x => x._2).filter(x => reg.pattern.matcher(x).matches)
</code>```

I create the .jar using sbt and running with spark-submit.

BTW, using spark-shell it works :S

I need your help please. Thanks.

答:
You could use built-in Scala support for XML. Something like

import scala.xml._

  rdd.map(x => (XML.loadString(x._2) \ "title").text)

Title: Regex on io.Text RDD using scala

Body:
I have a problem. I need to extract some data from a file like this:

(3269,
<page>
<title>Anarchism</title>
<ns>0</ns>
<id>12</id>
<revision>...
)
(194712,
<page>
<title>AssistiveTechnology</title>
<ns>0</ns>
<id>23</id>..
) etc...

This file was generated using:

val conf = new Configuration
conf.set("textinputformat.record.delimiter", "</page>")
val rdd=sc.newAPIHadoopFile("sample.bz2", classOf[TextInputFormat], classOf[LongWritable], classOf[Text], conf)
rdd.map{case (k,v) => (k.get(), new String(v.copyBytes()))}

I need to obtain the title content. Im using regex but the output file still remains empty. My code is like this:

val xx = rdd.map(x => x._2).filter(x => x.matches(".*<title>([A-Za-z]+)<\\/title>.*"))

I also try with these:

".*<title>([A-Za-z]+)</title>.*"

And using this:

val reg = ".*<title>([\\w]+)</title>.*".r
val xx = rdd.map(x => x._2).filter(x => reg.pattern.matcher(x).matches)

I create the .jar using sbt and running with spark-submit.

BTW, using spark-shell it works :S

I need your help please. Thanks.


问:
If button is not pressed again within 10 seconds, send alert
I have a button ("check") which starts a countdown that, when in reaches zero, the phone vibrates.  Pressing "check" again turns off the vibration and the process starts over. Pressing "alert" at any time sends an SMS to a pre-designated number.  That is my code so far, and as far as that goes, it's working fine. But I would like to connect these functions so that, once the vibration starts, the user has ten seconds to tap "check" and restart the timer, or else the "alert" function will start, sending an SMS.  How would I go about this? Would I need to make another countdown timer?

"check" button code so far:

```<code>check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                vibe.cancel();
                if (countDownTimer != null)
                    countDownTimer.cancel();

                countDownTimer = new CountDownTimer(timerTime * 1000, 1000) {

                    @Override
                    public void onTick(long milliseconds) {
                        long minutes = milliseconds / 60000;
                        long seconds = (milliseconds / 1000) % 60;
                        minsLeft.setText(getString(R.string.minutes) + (int) (minutes) + "  seconds:" + (int) (seconds));

                    }

                    @Override
                    public void onFinish() {
                        minsLeft.setText("Are You OK?");
                        long[] pattern = {100, 1000, 100, 2};
                        vibe.vibrate(pattern, 1);
                    }
                }.start();
            }
        });
    }
</code>```

"alert" button code (this would be called if "check" wasn't pressed again):

    public void onAlertClick(View view) {
        Toast sent = Toast.makeText(getApplicationContext(), "Alert Sent", Toast.LENGTH_SHORT);
        Toast permissions = Toast.makeText(getApplicationContext(), "Please change app permissions in settings", Toast.LENGTH_SHORT);

        try {
            SmsManager.getDefault().sendTextMessage(getString(R.string.smsNumber), null,
                    getString(R.string.smsMessage), null, null);
            sent.show();

        } catch (Exception e) {
            permissions.show();
        }
    }
```

答:
what I would do, is create a dialog fragment when the first timer finishes, then in that dialog fragment have another timer that counts down 10 seconds - if the dialog timer hits 0, then execute your alert method:

(p.s. you can nest this class inside your main class so you can call upon your first countdown timer easier)

```<code>public static class SessionExpiringDialog extends DialogFragment {
    CountDownTimer countDownTimer2;
    public SessionExpiringDialog() {
        super();
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();
        final View view = inflater.inflate(R.layout.session_dialog, null);
        final TextView sessionText = (TextView) view.findViewById(R.id.session_text);
        countDownTimer2 = new CountDownTimer2(11000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                long diffSeconds = millisUntilFinished / 1000 % 60;
                sessionText.setText("SMS Alert will be sent in: " + diffSeconds + " seconds.");
            }

            @Override
            public void onFinish() {
                onAlertClick(view);
            }
        };
        countDownTimer2.start();
        builder.setView(view);
        builder.setMessage("Alert SMS Pending").setTitle("ATTENTION:")
                .setPositiveButton("I'm OKAY!", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        countDownTimer2.cancel();
                        countDownTimer.start();
                        dismiss();
                    }
                });
        return builder.create();
    }
}
</code>```

this code assumes a layout xml exists called res/layout/session_dialog.xml:

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

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/session_text"
    android:textSize="20sp"
    android:textStyle="bold"
    android:layout_gravity="center"

    />

</LinearLayout>
</code>```

then to call this code, put it in the onFinish() method of your first countdowntimer:

```<code>check.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            vibe.cancel();
            if (countDownTimer != null)
                countDownTimer.cancel();

            countDownTimer = new CountDownTimer(timerTime * 1000, 1000) {

                @Override
                public void onTick(long milliseconds) {
                    long minutes = milliseconds / 60000;
                    long seconds = (milliseconds / 1000) % 60;
                    minsLeft.setText(getString(R.string.minutes) + (int) (minutes) + "  seconds:" + (int) (seconds));

                }

                @Override
                public void onFinish() {
                    minsLeft.setText("Are You OK?");
                    long[] pattern = {100, 1000, 100, 2};
                    vibe.vibrate(pattern, 1);
                    SessionExpiringDialog sessionExpiringDialog = new SessionExpiringDialog();
                    sessionExpiringDialog.setCancelable(false);
                    sessionExpiringDialog.show(getSupportFragmentManager(), "tag");
                }
            }.start();
        }
    });
}
</code>```

lastly, I didn't see why you're passing a view in your onAlertClick() method, but I went ahead and included it in my pasted code

Body:
I have a button ("check") which starts a countdown that, when in reaches zero, the phone vibrates.  Pressing "check" again turns off the vibration and the process starts over. Pressing "alert" at any time sends an SMS to a pre-designated number.  That is my code so far, and as far as that goes, it's working fine. But I would like to connect these functions so that, once the vibration starts, the user has ten seconds to tap "check" and restart the timer, or else the "alert" function will start, sending an SMS.  How would I go about this? Would I need to make another countdown timer?

"check" button code so far:

check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                vibe.cancel();
                if (countDownTimer != null)
                    countDownTimer.cancel();

                countDownTimer = new CountDownTimer(timerTime * 1000, 1000) {

                    @Override
                    public void onTick(long milliseconds) {
                        long minutes = milliseconds / 60000;
                        long seconds = (milliseconds / 1000) % 60;
                        minsLeft.setText(getString(R.string.minutes) + (int) (minutes) + "  seconds:" + (int) (seconds));

                    }

                    @Override
                    public void onFinish() {
                        minsLeft.setText("Are You OK?");
                        long[] pattern = {100, 1000, 100, 2};
                        vibe.vibrate(pattern, 1);
                    }
                }.start();
            }
        });
    }

"alert" button code (this would be called if "check" wasn't pressed again):

    public void onAlertClick(View view) {
        Toast sent = Toast.makeText(getApplicationContext(), "Alert Sent", Toast.LENGTH_SHORT);
        Toast permissions = Toast.makeText(getApplicationContext(), "Please change app permissions in settings", Toast.LENGTH_SHORT);

        try {
            SmsManager.getDefault().sendTextMessage(getString(R.string.smsNumber), null,
                    getString(R.string.smsMessage), null, null);
            sent.show();

        } catch (Exception e) {
            permissions.show();
        }
    }

Body:
what I would do, is create a dialog fragment when the first timer finishes, then in that dialog fragment have another timer that counts down 10 seconds - if the dialog timer hits 0, then execute your alert method:

(p.s. you can nest this class inside your main class so you can call upon your first countdown timer easier)

public static class SessionExpiringDialog extends DialogFragment {
    CountDownTimer countDownTimer2;
    public SessionExpiringDialog() {
        super();
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();
        final View view = inflater.inflate(R.layout.session_dialog, null);
        final TextView sessionText = (TextView) view.findViewById(R.id.session_text);
        countDownTimer2 = new CountDownTimer2(11000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                long diffSeconds = millisUntilFinished / 1000 % 60;
                sessionText.setText("SMS Alert will be sent in: " + diffSeconds + " seconds.");
            }

            @Override
            public void onFinish() {
                onAlertClick(view);
            }
        };
        countDownTimer2.start();
        builder.setView(view);
        builder.setMessage("Alert SMS Pending").setTitle("ATTENTION:")
                .setPositiveButton("I'm OKAY!", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        countDownTimer2.cancel();
                        countDownTimer.start();
                        dismiss();
                    }
                });
        return builder.create();
    }
}

this code assumes a layout xml exists called res/layout/session_dialog.xml:

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

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/session_text"
    android:textSize="20sp"
    android:textStyle="bold"
    android:layout_gravity="center"

    />

</LinearLayout>

then to call this code, put it in the onFinish() method of your first countdowntimer:

check.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            vibe.cancel();
            if (countDownTimer != null)
                countDownTimer.cancel();

            countDownTimer = new CountDownTimer(timerTime * 1000, 1000) {

                @Override
                public void onTick(long milliseconds) {
                    long minutes = milliseconds / 60000;
                    long seconds = (milliseconds / 1000) % 60;
                    minsLeft.setText(getString(R.string.minutes) + (int) (minutes) + "  seconds:" + (int) (seconds));

                }

                @Override
                public void onFinish() {
                    minsLeft.setText("Are You OK?");
                    long[] pattern = {100, 1000, 100, 2};
                    vibe.vibrate(pattern, 1);
                    SessionExpiringDialog sessionExpiringDialog = new SessionExpiringDialog();
                    sessionExpiringDialog.setCancelable(false);
                    sessionExpiringDialog.show(getSupportFragmentManager(), "tag");
                }
            }.start();
        }
    });
}

lastly, I didn't see why you're passing a view in your onAlertClick() method, but I went ahead and included it in my pasted code


问:
Difference between SPList.ContentTypesEnabled and SPList.AllowContentTypes?
What is the difference between SPList.ContentTypesEnabled and SPList.AllowContentTypes?

答:
SPList.ContentTypesEnabled

Gets or sets a Boolean value specifying whether content types are enabled for the list.

AllowContentTypes

Returns true if the list supports content types.

The first one can be used to get and set while the second one lets you know wether the list supports content types or not so that you can set the first one accordingly to enable content types.

ContentLicense: CC BY-SA 2.5


问:
install laravel on appserv without using php artisan serv
I have installed laravel project via composer in

```<code>c:/projectname
</code>```

When I want to work on the project I open msdos and write PHP artisan serv. Also, I have already appserv server on the computer.

How can I install laravel project on appserv and work with it on appserv?

How can I install the project on appserv  and access it without writing PHP artisan serv?

How can in export it to cpanel?

my appserv version is AppServ 8.6.0, my laravel version is 5.3.

答: You have installed the laravel But can't access the main page?If so,you can access localhost/your-laravel-folder/public to see the main page.</p>

Body:
I have installed laravel project via composer in

c:/projectname

When I want to work on the project I open msdos and write PHP artisan serv. Also, I have already appserv server on the computer.

How can I install laravel project on appserv and work with it on appserv?

How can I install the project on appserv  and access it without writing PHP artisan serv?

How can in export it to cpanel?

my appserv version is AppServ 8.6.0, my laravel version is 5.3.


问:
Amazon API does not always return product values.
I'm building a site on Wordpress which is going to be using Amazon API to grab price, title and image link after inputing Amazon ASIN.

I got it working with the script I have found (pasted below) but it works only about 5 out of 6 times. Every so often the API returns price as 0.00 and empty title and image link.

Is there something I am missing? I was prepared to use CRON job to auto update products on my website periodically but with this bug some products will be pretty much "reset" to 0.00 price.

Any help would be appreciated.

code here:

```<code>    <?php

        $amazon_asin = get_post_meta( get_the_ID(), 'amazon_asin', true);
        $response = getAmazonPrice("co.uk", $amazon_asin);

    function getAmazonPrice($region, $asin) {

        $xml = aws_signed_request($region, array(
            "Operation" => "ItemLookup",
            "ItemId" => $asin,
            "IncludeReviewsSummary" => False,
            "ResponseGroup" => "Medium,OfferSummary",
        ));

        $item = $xml->Items->Item;
        $title = htmlentities((string) $item->ItemAttributes->Title);
        $url = htmlentities((string) $item->DetailPageURL);
        $image = htmlentities((string) $item->MediumImage->URL);
        $price = htmlentities((string) $item->OfferSummary->LowestNewPrice->Amount);
        $code = htmlentities((string) $item->OfferSummary->LowestNewPrice->CurrencyCode);
        $qty = htmlentities((string) $item->OfferSummary->TotalNew);

        if ($qty !== "0") {
            $response = array(
                "code" => $code,
                "price" => number_format((float) ($price / 100), 2, '.', ''),
                "image" => $image,
                "url" => $url,
                "title" => $title
            );
        }

        return $response;
    }

    function getPage($url) {

        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_FAILONERROR, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $html = curl_exec($curl);
        curl_close($curl);
        return $html;
    }

    function aws_signed_request($region, $params) {

        $public_key = get_option('public_key');
        $private_key = get_option('private_key');

        $method = "GET";
        $host = "ecs.amazonaws." . $region;
        $host = "webservices.amazon." . $region;
        $uri = "/onca/xml";

        $params["Service"] = "AWSECommerceService";
        $params["AssociateTag"] = get_option('associate_tag'); // Put your Affiliate Code here
        $params["AWSAccessKeyId"] = $public_key;
        $params["Timestamp"] = gmdate("Y-m-d\TH:i:s\Z");
        $params["Version"] = "2011-08-01";

        ksort($params);

        $canonicalized_query = array();
        foreach ($params as $param => $value) {
            $param = str_replace("%7E", "~", rawurlencode($param));
            $value = str_replace("%7E", "~", rawurlencode($value));
            $canonicalized_query[] = $param . "=" . $value;
        }

        $canonicalized_query = implode("&", $canonicalized_query);

        $string_to_sign = $method . "\n" . $host . "\n" . $uri . "\n" . $canonicalized_query;
        $signature = base64_encode(hash_hmac("sha256", $string_to_sign, $private_key, True));
        $signature = str_replace("%7E", "~", rawurlencode($signature));

        $request = "http://" . $host . $uri . "?" . $canonicalized_query . "&Signature=" . $signature;
        $response = getPage($request);

        var_dump($response);

        $pxml = @simplexml_load_string($response);
        if ($pxml === False) {
            return False;// no xml
        } else {
            return $pxml;
        }
    }

?>
</code>```

答:
Well, it seems to be a problem with Amazon Product API. If you make the same request several times, then it should either always work or not work at all.

You can ask on Amazon Product API forums about the problem: https://forums.aws.amazon.com/forum.jspa?forumID=9

You can also update your code so it does not update the product price if the title is missing from Amazon API response

Body:
I'm building a site on Wordpress which is going to be using Amazon API to grab price, title and image link after inputing Amazon ASIN.

I got it working with the script I have found (pasted below) but it works only about 5 out of 6 times. Every so often the API returns price as 0.00 and empty title and image link.

Is there something I am missing? I was prepared to use CRON job to auto update products on my website periodically but with this bug some products will be pretty much "reset" to 0.00 price.

Any help would be appreciated.

code here:

    <?php

        $amazon_asin = get_post_meta( get_the_ID(), 'amazon_asin', true);
        $response = getAmazonPrice("co.uk", $amazon_asin);

    function getAmazonPrice($region, $asin) {

        $xml = aws_signed_request($region, array(
            "Operation" => "ItemLookup",
            "ItemId" => $asin,
            "IncludeReviewsSummary" => False,
            "ResponseGroup" => "Medium,OfferSummary",
        ));

        $item = $xml->Items->Item;
        $title = htmlentities((string) $item->ItemAttributes->Title);
        $url = htmlentities((string) $item->DetailPageURL);
        $image = htmlentities((string) $item->MediumImage->URL);
        $price = htmlentities((string) $item->OfferSummary->LowestNewPrice->Amount);
        $code = htmlentities((string) $item->OfferSummary->LowestNewPrice->CurrencyCode);
        $qty = htmlentities((string) $item->OfferSummary->TotalNew);

        if ($qty !== "0") {
            $response = array(
                "code" => $code,
                "price" => number_format((float) ($price / 100), 2, '.', ''),
                "image" => $image,
                "url" => $url,
                "title" => $title
            );
        }

        return $response;
    }

    function getPage($url) {

        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_FAILONERROR, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $html = curl_exec($curl);
        curl_close($curl);
        return $html;
    }

    function aws_signed_request($region, $params) {

        $public_key = get_option('public_key');
        $private_key = get_option('private_key');

        $method = "GET";
        $host = "ecs.amazonaws." . $region;
        $host = "webservices.amazon." . $region;
        $uri = "/onca/xml";

        $params["Service"] = "AWSECommerceService";
        $params["AssociateTag"] = get_option('associate_tag'); // Put your Affiliate Code here
        $params["AWSAccessKeyId"] = $public_key;
        $params["Timestamp"] = gmdate("Y-m-d\TH:i:s\Z");
        $params["Version"] = "2011-08-01";

        ksort($params);

        $canonicalized_query = array();
        foreach ($params as $param => $value) {
            $param = str_replace("%7E", "~", rawurlencode($param));
            $value = str_replace("%7E", "~", rawurlencode($value));
            $canonicalized_query[] = $param . "=" . $value;
        }

        $canonicalized_query = implode("&", $canonicalized_query);

        $string_to_sign = $method . "\n" . $host . "\n" . $uri . "\n" . $canonicalized_query;
        $signature = base64_encode(hash_hmac("sha256", $string_to_sign, $private_key, True));
        $signature = str_replace("%7E", "~", rawurlencode($signature));

        $request = "http://" . $host . $uri . "?" . $canonicalized_query . "&Signature=" . $signature;
        $response = getPage($request);

        var_dump($response);

        $pxml = @simplexml_load_string($response);
        if ($pxml === False) {
            return False;// no xml
        } else {
            return $pxml;
        }
    }

?>


问:
PowerShell dir /ah not working?
When I try dir /ah under Windows 10 I get the following:

```<code>PS C:\Users\Robert\dev\fiedz> dir /ah
dir : Cannot find path 'C:\ah' because it does not exist.
At line:1 char:1
+ dir /ah
+ ~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\ah:String) [Get-ChildItem], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
</code>```

Any idea why ?

答:
try it :</p>

```<code> Get-ChildItem -Hidden
</code>```

Title: PowerShell dir /ah not working?

Body:
When I try dir /ah under Windows 10 I get the following:

PS C:\Users\Robert\dev\fiedz> dir /ah
dir : Cannot find path 'C:\ah' because it does not exist.
At line:1 char:1
+ dir /ah
+ ~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\ah:String) [Get-ChildItem], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

Any idea why ?

Body:
try it :

 Get-ChildItem -Hidden


问:
How to create table using angular from inside request callback function
I'm trying to create a table using angular. The problem is that I need to create that table based on JSON response from my http request (at which point I call the responseHandler function below:

```<code>function call(){
    $.ajax({
        url: url
        , type: "GET"
        , success: function (response, status, xhr) {

            responseHandler(response);
        }
        , error: function (xhr, status, error) {}
    });
}

 function responseHandler(response) {
    var data = angular.fromJson(response);
    var user = angular.fromJson(data['users']);
    userdata = user['data'];// this is correctly assigning the data I
                                // need to the variable userdata
    var tApp = angular.module('tApp', []);
    tApp.controller('tCtrl', ['$scope', function ($scope) {

        $scope.userdata = userdata;
        $("#usertable").css("visibility", "visible");
    }]);
 }
</code>```

Here is my html:

```<code><div ng-app="tApp" ng-controller="tCtrl" class="tab-content clearfix" id='tCtrl'>
<table id='usertable' border="1">
                        <tr ng-repeat="x in userdata">
                            <td>{{x.name}}</td>
                            <td>{{x.id}}</td>
                            <td>{{x.picture.data.url}}</td>
                        </tr>
                    </table>
</div>
</code>```

I keep getting the angular.js:14516 Error: [$controller:ctrlreg] error.
So it seems my controller is not being recognize by angular. Any ideas?

Thank you!

答:
Looks like your angular module and controller are declared only on success. But you are using ng-controller in your view. So if the request fails, you're in trouble :)

When AngularJS sees an ng-controller directive, but cannot find the matching controller, it throws that error. Here is more info on the error

But in general, there are issues with your code:

you should use angular's $http module to make http calls. You should not use jquery because it will not trigger a digest cycle once a response is received and angular will not know anything about the api call.

you should not create your angular module inside another function, just create it globally

Body:
I'm trying to create a table using angular. The problem is that I need to create that table based on JSON response from my http request (at which point I call the responseHandler function below:

function call(){
    $.ajax({
        url: url
        , type: "GET"
        , success: function (response, status, xhr) {

            responseHandler(response);
        }
        , error: function (xhr, status, error) {}
    });
}

 function responseHandler(response) {
    var data = angular.fromJson(response);
    var user = angular.fromJson(data['users']);
    userdata = user['data'];// this is correctly assigning the data I
                                // need to the variable userdata
    var tApp = angular.module('tApp', []);
    tApp.controller('tCtrl', ['$scope', function ($scope) {

        $scope.userdata = userdata;
        $("#usertable").css("visibility", "visible");
    }]);
 }

Here is my html:

                            {{x.name}}
                            {{x.id}}
                            {{x.picture.data.url}}

I keep getting the angular.js:14516 Error: [$controller:ctrlreg] error.
So it seems my controller is not being recognize by angular. Any ideas?

Thank you!


问:
How to manage fragments in backstack?
I am trying to manage fragments in a very simple way. I have created a utility class that's adding fragments to the backstack and when we press the back button, the previous fragment shows up. I am OK with that. But, when I am trying to clear out all the fragments, and show up the root fragment, I am not able to do so properly. Following is my utility class:

```<code>public class FragmentUtil {
private FragmentUtil() {
}

public static void animatedReplace(FragmentActivity activity, int containerId, Fragment fragment, Bundle args, boolean addToBackStack){
    FragmentTransaction transaction=activity.getSupportFragmentManager().beginTransaction();
    fragment.setArguments(args);
    if(addToBackStack){
        transaction.addToBackStack(fragment.getClass().getName());
    }
    transaction.setCustomAnimations(R.anim.slide_from_right, R.anim.slide_to_left,R.anim.slide_from_left,R.anim.slide_to_right);
    transaction.replace(containerId,fragment);
    transaction.commit();
}

public static void clearBackStackToHome(FragmentActivity activity){
    FragmentManager manager = activity.getSupportFragmentManager();
    manager.popBackStack(DashboardFragment.class.getName(),FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
</code>```

When I want to another fragment I just pass "true" for addToStack in animatedReplace method. When I want to clear the backstack I pass "false" and call the clearBackStackToHome method. Can anybody help me what I am doing wrong?

答:
Yes, you can manage fragment back press in onBackPressed() method of your MainActivity.
just override onBackPressed() , and check backStack count, if the count is zero then navigate to your root fragment or exit from app. Also, you can implement your code according to check which fragment in back stack.

```<code>@Override
public void onBackPressed() {

    FragmentManager fm = getSupportFragmentManager();
    int count = fm.getBackStackEntryCount();
    if (count >= 1) {
        if (fm.findFragmentById(R.id.main_container) instanceof yourFragment) {

            super.onBackPressed();

        }
    } else {
        // Show your root fragment  here
    }

}
</code>```

Title: How to manage fragments in backstack?

Body:
I am trying to manage fragments in a very simple way. I have created a utility class that's adding fragments to the backstack and when we press the back button, the previous fragment shows up. I am OK with that. But, when I am trying to clear out all the fragments, and show up the root fragment, I am not able to do so properly. Following is my utility class:

public class FragmentUtil {
private FragmentUtil() {
}

public static void animatedReplace(FragmentActivity activity, int containerId, Fragment fragment, Bundle args, boolean addToBackStack){
    FragmentTransaction transaction=activity.getSupportFragmentManager().beginTransaction();
    fragment.setArguments(args);
    if(addToBackStack){
        transaction.addToBackStack(fragment.getClass().getName());
    }
    transaction.setCustomAnimations(R.anim.slide_from_right, R.anim.slide_to_left,R.anim.slide_from_left,R.anim.slide_to_right);
    transaction.replace(containerId,fragment);
    transaction.commit();
}

public static void clearBackStackToHome(FragmentActivity activity){
    FragmentManager manager = activity.getSupportFragmentManager();
    manager.popBackStack(DashboardFragment.class.getName(),FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}

When I want to another fragment I just pass "true" for addToStack in animatedReplace method. When I want to clear the backstack I pass "false" and call the clearBackStackToHome method. Can anybody help me what I am doing wrong?

Body:
Yes, you can manage fragment back press in onBackPressed() method of your MainActivity.
just override onBackPressed() , and check backStack count, if the count is zero then navigate to your root fragment or exit from app. Also, you can implement your code according to check which fragment in back stack.

@Override
public void onBackPressed() {

    FragmentManager fm = getSupportFragmentManager();
    int count = fm.getBackStackEntryCount();
    if (count >= 1) {
        if (fm.findFragmentById(R.id.main_container) instanceof yourFragment) {

            super.onBackPressed();

        }
    } else {
        // Show your root fragment  here
    }

}


问:
Powershell Sort and transpose data based on particular column
I am new to powershell. I have a data which is in columnar format, which needs to be converted into rows by sorting it numerically.

Input data:

```<code>Fruit month amount
1apple jan 10
3blueberry jan 20
4mango jan 30
2banana jan 50
1apple feb 20
3blueberry feb 50
4mango feb 80
2banana feb 95
</code>```

Desired Output:

```<code>Fruit JanAmount FebAmount
1apple 10 20
2banana 50 95
3blueberry 20 50
4mango 30 80
</code>```

Can anyone pls help me with this?

答:
As long as there are no whitespace in the fruit-names then you can read the file as CSV with whitespace as delimiter. Then merge them using Group-Object and Add-Member to dynamically add x months. Ex:

```<code>Import-Csv -Path $InSort -Delimiter " " |
#Group all records per fruit
Group-Object Fruit |
#Sort by fruitname
Sort-Object Name |
#Process each group (fruit) to merge the rows
ForEach-Object {
    #Create object (row) per fruit
    $obj = New-Object -TypeName psobject -Property @{
        Fruit = $_.Name
    }

    #For each record (month), add amount column
    $_.Group | ForEach-Object {
        #Turn month-value into TitleCase (first letter uppercase)
        $month = (Get-Culture).TextInfo.ToTitleCase($_.Month)
        #Add amount-column per record (month)
        Add-Member -InputObject $obj -MemberType NoteProperty -Name "$($Month)Amount" -Value $_.Amount
    }

    #Output new objects
    $obj
} | Export-CSV -Path newfile.csv -NoTypeInformation -Delimiter " "
</code>```

Output:

```<code>Fruit      JanAmount FebAmount
-----      --------- ---------
1apple     10        20
2banana    50        95
3blueberry 20        50
4mango     30        80
</code>```

Body:
I am new to powershell. I have a data which is in columnar format, which needs to be converted into rows by sorting it numerically.

Input data:

Fruit month amount
1apple jan 10
3blueberry jan 20
4mango jan 30
2banana jan 50
1apple feb 20
3blueberry feb 50
4mango feb 80
2banana feb 95

Desired Output:

Fruit JanAmount FebAmount
1apple 10 20
2banana 50 95
3blueberry 20 50
4mango 30 80

Can anyone pls help me with this?

Body:
As long as there are no whitespace in the fruit-names then you can read the file as CSV with whitespace as delimiter. Then merge them using Group-Object and Add-Member to dynamically add x months. Ex:

Import-Csv -Path $InSort -Delimiter " " |
#Group all records per fruit
Group-Object Fruit |
#Sort by fruitname
Sort-Object Name |
#Process each group (fruit) to merge the rows
ForEach-Object {
    #Create object (row) per fruit
    $obj = New-Object -TypeName psobject -Property @{
        Fruit = $_.Name
    }

    #For each record (month), add amount column
    $_.Group | ForEach-Object {
        #Turn month-value into TitleCase (first letter uppercase)
        $month = (Get-Culture).TextInfo.ToTitleCase($_.Month)
        #Add amount-column per record (month)
        Add-Member -InputObject $obj -MemberType NoteProperty -Name "$($Month)Amount" -Value $_.Amount
    }

    #Output new objects
    $obj
} | Export-CSV -Path newfile.csv -NoTypeInformation -Delimiter " "

Output:

Fruit      JanAmount FebAmount
-----      --------- ---------
1apple     10        20
2banana    50        95
3blueberry 20        50
4mango     30        80


问:
Error in Turtle recursion
I'm attempting to use Turtle Graphics to make a fractal via recursion, but for some reason my code seems to not return the Turtle back to the origin.
My code is as follows

```<code>public static void sun(Turtle t, double radius) {
for ( int i = 0; i < 360; i++ ) {
    t.forward( radius * .0174 );
    t.left( 1 );
}
    t.penup();
    t.left(90);
    t.forward(radius);
    //t.fill();
    t.pendown();
for (int i = 0; i < 8; i++) {
    t.forward(2*radius);
    t.backward(2*radius);
    t.left(45);
}
t.penup();
t.backward(radius);
t.right(90);
t.pendown();
}

public static void fractalSun(Turtle t, double r, int level) {
int color;
if (level == 0) {
  t.color(255, 0, 0);
  sun(t, r);
}
else {
  sun(t, r);
  t.left(90);
  t.forward(r);
  t.right(90);
  t.forward(r * 2);
  t.right(90);
  fractalSun(t, r/4, level -1);
  t.left(90);
  t.backward(r * 2);
 }
}
</code>```

The code compiles successfully, but produces this image:
Screenshot

My goal would be for the turtle to return to the center of each 'sun' but something isn't working.

答:
Although the sun() method returns the turtle to where it started, the fractalSun() method leaves the turtle to the center of the figure.  So whether fractalSun() calls itself or sun() it has to make adjustments.  Here's an update fix with fewer changes (mostly deletions):

Change this final block of code in sun():

```<code>t.penup();
t.backward(radius);
t.right(90);
t.pendown();
</code>```

to be simply one statement:

```<code>// t.penup();
// t.backward(radius);
t.right(90);
// t.pendown();
</code>```

Drop three lines of code from fractalSun() and change the arguments to the final function call:

```<code>public static void fractalSun(Turtle t, double r, int level) {

    if (level == 0) {
        t.color(255, 0, 0);

        sun(t, r);
    } else {
        sun(t, r);

        // t.left(90);
        // t.forward(r);
        // t.right(90);

        t.forward(r * 2);
        t.right(90);
        fractalSun(t, r / 4, level - 1);
        t.left(90);
        t.backward(r * 2 + r / 4);  // added a term to the equation
    }
}
</code>```

OUTPUT

Note: I simulated this using Python turtle so you may need to tweak my Java code if it's amiss.

Title: Error in Turtle recursion

Body:
I'm attempting to use Turtle Graphics to make a fractal via recursion, but for some reason my code seems to not return the Turtle back to the origin.
My code is as follows

public static void sun(Turtle t, double radius) {
for ( int i = 0; i < 360; i++ ) {
    t.forward( radius * .0174 );
    t.left( 1 );
}
    t.penup();
    t.left(90);
    t.forward(radius);
    //t.fill();
    t.pendown();
for (int i = 0; i < 8; i++) {
    t.forward(2*radius);
    t.backward(2*radius);
    t.left(45);
}
t.penup();
t.backward(radius);
t.right(90);
t.pendown();
}

public static void fractalSun(Turtle t, double r, int level) {
int color;
if (level == 0) {
  t.color(255, 0, 0);
  sun(t, r);
}
else {
  sun(t, r);
  t.left(90);
  t.forward(r);
  t.right(90);
  t.forward(r * 2);
  t.right(90);
  fractalSun(t, r/4, level -1);
  t.left(90);
  t.backward(r * 2);
 }
}

The code compiles successfully, but produces this image:
Screenshot

My goal would be for the turtle to return to the center of each 'sun' but something isn't working.

Body:
Although the sun() method returns the turtle to where it started, the fractalSun() method leaves the turtle to the center of the figure.  So whether fractalSun() calls itself or sun() it has to make adjustments.  Here's an update fix with fewer changes (mostly deletions):

Change this final block of code in sun():

t.penup();
t.backward(radius);
t.right(90);
t.pendown();

to be simply one statement:

// t.penup();
// t.backward(radius);
t.right(90);
// t.pendown();

Drop three lines of code from fractalSun() and change the arguments to the final function call:

public static void fractalSun(Turtle t, double r, int level) {

    if (level == 0) {
        t.color(255, 0, 0);

        sun(t, r);
    } else {
        sun(t, r);

        // t.left(90);
        // t.forward(r);
        // t.right(90);

        t.forward(r * 2);
        t.right(90);
        fractalSun(t, r / 4, level - 1);
        t.left(90);
        t.backward(r * 2 + r / 4);  // added a term to the equation
    }
}

OUTPUT

Note: I simulated this using Python turtle so you may need to tweak my Java code if it's amiss.


问:
CI Session Destroy after redirection
I have three parallel websites on a single IP and all are using CI. So, I am facing a problem while login process. When I trying to login it will destroy all my set session and resultant I am not able to login into my admin panel.

Please suggest on it and thanks in advance.

答: After looking into the situation I figured out the problem. The problem was in the configuration file and with the permissions to the system folder.</p>

Title: CI Session Destroy after redirection


问:
Support with Logic Gate Simulation program in Python
I'm trying to create a logic gate simulation program in python so that a user can choose the type of logic gate they want to simulate. Once chosen, they can then enter the inputs and the program should return the value of the output from the chosen logic gate to the user.

This is what I have so far:

```<code>print ("Logic Gate Simulation")

def AND (a,b):

    if a == 1 and b == 1:
        return 1
    else:
        return 0

def NAND (a,b):
    if a == 1 and b == 1:
        return 0
    else:
        return 1

def OR(a,b):
    if a == 1:
        return 1
    elif b == 1:
        return 1
    else:
        return 0

def NOR (a,b):
    if a != b:
        return 1
    else:
        return 1

def Main():
    question = input("what type of gate do you want to simulate - OR, AND  or NAND?  ")

    if question == 'AND':
        a = input("enter value for input 1")
        b = input("enter value for input 2")
        x= AND(a,b)
        print (x)

    else:
        print ("")
Main()
</code>```

When I run the program and enter AND, inputs 1 and 1 it still returns 0 and I cant see why.

答:
this works:

```<code>def AND (a,b):
    a=int(a)
    b=int(b)
    if a == 1 and b == 1:
        return 1
    else:
        return 0
</code>```

you have to tell python that a and b are integers - (there are better ways of doing that than the method shown)

Body:
I'm trying to create a logic gate simulation program in python so that a user can choose the type of logic gate they want to simulate. Once chosen, they can then enter the inputs and the program should return the value of the output from the chosen logic gate to the user.

This is what I have so far:

print ("Logic Gate Simulation")

def AND (a,b):

    if a == 1 and b == 1:
        return 1
    else:
        return 0

def NAND (a,b):
    if a == 1 and b == 1:
        return 0
    else:
        return 1

def OR(a,b):
    if a == 1:
        return 1
    elif b == 1:
        return 1
    else:
        return 0

def NOR (a,b):
    if a != b:
        return 1
    else:
        return 1

def Main():
    question = input("what type of gate do you want to simulate - OR, AND  or NAND?  ")

    if question == 'AND':
        a = input("enter value for input 1")
        b = input("enter value for input 2")
        x= AND(a,b)
        print (x)

    else:
        print ("")
Main()

When I run the program and enter AND, inputs 1 and 1 it still returns 0 and I cant see why.

Body:
this works:

def AND (a,b):
    a=int(a)
    b=int(b)
    if a == 1 and b == 1:
        return 1
    else:
        return 0

you have to tell python that a and b are integers - (there are better ways of doing that than the method shown)


问:
Avoiding double borders in nested panelGrids/dataTables in JSF
I am working on a web application and using nested tables quite a bit to achieve the needed layout.  Unfortunately, I am unable to avoid drawing the borders on the nested table cells.  I've tried using CSS and border-collapse: collapse; but that doesn't work.  I'm no wiz at CSS but here's a sample of what I have:

table { border-collapse: collapse; width: 75%; }
table.innerTable { width: 100%; border-collapse: collapse; }
td { border: 1px solid black; border-collapse: collapse; }
th { background-color: #6699FF; color: black; }
td { background-color: #d1d1ff; color: #101030; text-align: center;}
.capAttribute { font-weight: bold; }
```

<pre class="lang-xhtml prettyprint-override"><code><h:panelGrid columns="2">
  <h:outputText value="Start Time (MM-dd-yyyy HH:mm)" styleClass="capAttribute"/>
  <h:panelGrid columns="2" >
    <h:inputText id="starttime" value="#timeBean.targetTime.timeStart}"
      converterMessage="Please enter a date in the specified format.">
      <f:convertDateTime pattern="MM-dd-yyyy HH:mm" />
    </h:inputText>
    <h:message for="starttime"/>
  </h:panelGrid>
  <h:outputText value="End Time (MM-dd-yyyy HH:mm)" styleClass="capAttribute"/>
  <h:panelGrid columns="2" >
    <h:inputText id="endtime" value="#{timeBean.targetTime.timeEnd}"
      converterMessage="Please enter a date in the specified format.">
      <f:convertDateTime pattern="MM-dd-yyyy HH:mm" />
    </h:inputText>
    <h:message for="endtime"/>
  </h:panelGrid>
</h:panelGrid>
</code>```

Is there any way to get rid of the border around the inner panelGrid's cells without getting rid of the outer borders?

答:
Add

```<code>table table td { border: 0; }
</code>```

to your CSS.

You can even make it more specific by giving the inner table a CSS class.

```<code><h:panelGrid styleClass="innertable">
</code>```

with

```<code>table.innertable td { border: 0; }
</code>```

Body:
I am working on a web application and using nested tables quite a bit to achieve the needed layout.  Unfortunately, I am unable to avoid drawing the borders on the nested table cells.  I've tried using CSS and border-collapse: collapse; but that doesn't work.  I'm no wiz at CSS but here's a sample of what I have:

table { border-collapse: collapse; width: 75%; }
table.innerTable { width: 100%; border-collapse: collapse; }
td { border: 1px solid black; border-collapse: collapse; }
th { background-color: #6699FF; color: black; }
td { background-color: #d1d1ff; color: #101030; text-align: center;}
.capAttribute { font-weight: bold; }

<h:panelGrid columns="2">
  <h:outputText value="Start Time (MM-dd-yyyy HH:mm)" styleClass="capAttribute"/>
  <h:panelGrid columns="2" >
    <h:inputText id="starttime" value="#timeBean.targetTime.timeStart}"
      converterMessage="Please enter a date in the specified format.">
      <f:convertDateTime pattern="MM-dd-yyyy HH:mm" />
    </h:inputText>
    <h:message for="starttime"/>
  </h:panelGrid>
  <h:outputText value="End Time (MM-dd-yyyy HH:mm)" styleClass="capAttribute"/>
  <h:panelGrid columns="2" >
    <h:inputText id="endtime" value="#{timeBean.targetTime.timeEnd}"
      converterMessage="Please enter a date in the specified format.">
      <f:convertDateTime pattern="MM-dd-yyyy HH:mm" />
    </h:inputText>
    <h:message for="endtime"/>
  </h:panelGrid>
</h:panelGrid>

Is there any way to get rid of the border around the inner panelGrid's cells without getting rid of the outer borders?

Body:
Add

table table td { border: 0; }

to your CSS.

You can even make it more specific by giving the inner table a CSS class.

<h:panelGrid styleClass="innertable">

with

table.innertable td { border: 0; }


问:
Launcher activity not starting
My launcher activity not starting can any body tell me whats the problem.

I also have a service in it.
Any help is appreciated Please help i am stuck and don't know what to do.

Here is  the code of Manifest

```<code> <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pelicans.abc.abc">
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

<uses-feature android:name="android.hardware.camera" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <activity android:name=".Permiss"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".MainActivity"
        android:screenOrientation="portrait">
        <meta-data
            android:name="android.app.searchable"
            android:resource="@xml/searchable">
        </meta-data>
    </activity>

    <service
        android:name=".Service.FeatureService"
        android:enabled="true">
    </service>

    <receiver android:name=".Receiver.RestartService"
        android:enabled="true"
        android:exported="true"
        android:label="RestartServiceWhenStopped">

        <intent-filter>
            <action android:name="Restart_Service"></action>
        </intent-filter>
    </receiver>
</application>
</manifest>
</code>```

Launcher activity is not called in any version of android.

答:
Try this :
I think remove this:

```<code><intent-filter>
        <action android:name="Restart_Service"></action>
    </intent-filter>
</code>```

//need to modified

```<code> <meta-data
        android:name="android.app.searchable"  //it must contain package name and .searchable
        android:resource="@xml/searchable">
    </meta-data>
</code>```

OR

```<code><intent-filter>
        <action android:name=".Restart_Service"></action> //add dot
    </intent-filter>
</code>```

Title: Launcher activity not starting

Body:
My launcher activity not starting can any body tell me whats the problem.

I also have a service in it.
Any help is appreciated Please help i am stuck and don't know what to do.

Here is  the code of Manifest

 <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pelicans.abc.abc">
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

<uses-feature android:name="android.hardware.camera" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <activity android:name=".Permiss"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".MainActivity"
        android:screenOrientation="portrait">
        <meta-data
            android:name="android.app.searchable"
            android:resource="@xml/searchable">
        </meta-data>
    </activity>

    <service
        android:name=".Service.FeatureService"
        android:enabled="true">
    </service>

    <receiver android:name=".Receiver.RestartService"
        android:enabled="true"
        android:exported="true"
        android:label="RestartServiceWhenStopped">

        <intent-filter>
            <action android:name="Restart_Service"></action>
        </intent-filter>
    </receiver>
</application>
</manifest>

Launcher activity is not called in any version of android.

Body:
Try this :
I think remove this:

<intent-filter>
        <action android:name="Restart_Service"></action>
    </intent-filter>

//need to modified

 <meta-data
        android:name="android.app.searchable"  //it must contain package name and .searchable
        android:resource="@xml/searchable">
    </meta-data>

OR

<intent-filter>
        <action android:name=".Restart_Service"></action> //add dot
    </intent-filter>


问:
Is it safe to enable ”Access-Control-Allow-Origin: *“ (wildcard) for a public and readonly webservice?
Enabling CORS has several security issues:

CSRF

exposure of protected data

But are there any issues for a public and readonly webservice to enable global CORS?

```<code>Access-Control-Allow-Origin: *
</code>```

My assumptions:

CSRF is not relevant, because webservice is readonly.

stealing of protected data is not relevant, because webservice is public.

答:
If it is a public API then CORS should be enabled for all requests.
One of the best security approach for public APIs is using app keys in request headers.</p>

Body:
Enabling CORS has several security issues:

CSRF

exposure of protected data

But are there any issues for a public and readonly webservice to enable global CORS?

Access-Control-Allow-Origin: *

My assumptions:

CSRF is not relevant, because webservice is readonly.

stealing of protected data is not relevant, because webservice is public.


问:
locationManager didUpdateLocations fires twice on device, only once on simulator
Same code, I'm assuming that the device is actually updating the location twice for some reason, even though I only call startUpdatingLocation() once and I run some stopUpdatingLocations() inside of didUpdateLocations

```<code>func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    manager.stopUpdatingLocation()
    let loc: CLLocation = locations[locations.count - 1]
    let id = 0
    let type = 0
    let number = 0

    createNewDataPoint(id, loc: loc, type: type, number: number)
}
</code>```

In this case, createNewDataPoint gets called twice, creating 2 new datapoints.  It only happens once in the simulator, so I'm assuming it has something to do with the actual device and the GPS since the simulator fakes its location.

startUpdatingLocation() is only in my code one time, on a button.  Basically, you click the button, go go manager.startUpdatingLocations(), didUpdateLocations hits once on simulator, twice on device (identical coordinates) and it creates 2 new data points.

The only other code that mentions anything related is setting the accuracy, filter, authorization requests, and the previously mentioned startUpdatingLocation().  Is there something I can do to make sure I'm not creating twice as many data points as necessary?

答:
@Zumry Mohamed 's solution is right

i try the code like this:

```<code>- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {

   [self.locationManager stopUpdatingLocation];
   self.locationManager.delegate = nil;
   self.locationManager = nil;
}
</code>```

finally this delegate is called only once, i understand now why the problem is occurred, just because manager call the stopUpdatingLocationmethod but system doesn't help us to make the delegate invalid, so we can receive the callback every time location updates due to your desiredAccuracy and distanceFilter property settings of your CLLocationManager, so the final solution is just like what @Zumry Mohamed said, we can manually set the delegate to nil when we stopUpdateLocation. hope it will help you understand what happens why this could solve the problem.

Body:
Same code, I'm assuming that the device is actually updating the location twice for some reason, even though I only call startUpdatingLocation() once and I run some stopUpdatingLocations() inside of didUpdateLocations

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    manager.stopUpdatingLocation()
    let loc: CLLocation = locations[locations.count - 1]
    let id = 0
    let type = 0
    let number = 0

    createNewDataPoint(id, loc: loc, type: type, number: number)
}

In this case, createNewDataPoint gets called twice, creating 2 new datapoints.  It only happens once in the simulator, so I'm assuming it has something to do with the actual device and the GPS since the simulator fakes its location.

startUpdatingLocation() is only in my code one time, on a button.  Basically, you click the button, go go manager.startUpdatingLocations(), didUpdateLocations hits once on simulator, twice on device (identical coordinates) and it creates 2 new data points.

The only other code that mentions anything related is setting the accuracy, filter, authorization requests, and the previously mentioned startUpdatingLocation().  Is there something I can do to make sure I'm not creating twice as many data points as necessary?

Body:
@Zumry Mohamed 's solution is right

i try the code like this:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {

   [self.locationManager stopUpdatingLocation];
   self.locationManager.delegate = nil;
   self.locationManager = nil;
}

finally this delegate is called only once, i understand now why the problem is occurred, just because manager call the stopUpdatingLocationmethod but system doesn't help us to make the delegate invalid, so we can receive the callback every time location updates due to your desiredAccuracy and distanceFilter property settings of your CLLocationManager, so the final solution is just like what @Zumry Mohamed said, we can manually set the delegate to nil when we stopUpdateLocation. hope it will help you understand what happens why this could solve the problem.


问:
How do you reuse the Statement in JDBC after reconnecting to the database?
My JDBC connection to the MySQL database expires after 10 seconds of inactivity. After I reconnect, I can't do any queries, it keeps on asking me if I wanna reconnect as if the connection is still closed.

I have:

 1. a global Statement called st,

 2. a global ResultSet called rs,

 3. a global connection called conn,

 4. a method setConnection that sets up the connection,

 5. a method checkConnection that checks if the connection is alive and if not it calls the setConnection method to establish a new one,

 6. a button that calls checkConnection and if the boolean returned is true, it executes a query

```<code>private Connection conn = null;
private Statement st=null;
private ResultSet rs=null;

    public void setConnection(){
             host="localhost";
             database="test";
             username="testtest";
             password="testtest";
             String url = "jdbc:mysql://" + host + "/" +database+ "";
             try {
                 Class.forName ("com.mysql.jdbc.Driver");
                 conn = DriverManager.getConnection (url, username, password);
                 System.out.println("Succesfuly connected to the database!");

             } catch(Exception e){
                 System.out.println("Failed to connect to the database.");
                 e.printStackTrace();
             }
        }

    private boolean checkConnection(){
            try {
                ResultSet cc = st.executeQuery("SELECT 1");
                return true;
            } catch (SQLException e) {
                int n = JOptionPane.showConfirmDialog(
                        frame,
                        "The connection was closed, reconnect?",
                        "Database security measure",
                        JOptionPane.YES_NO_OPTION);
                if(n == JOptionPane.YES_OPTION){
                    try {
                        conn.close();
                    } catch (SQLException e1) {
                        e1.printStackTrace();
                    }
                      setConnection();
                    } else if ( n == JOptionPane.NO_OPTION){
                        frame.setVisible(false);
                        new LoginWindowB();
                    }
                return false;
            }
        }
    btn1.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    if(checkConnection()){
                        try {
                            rs = st.executeQuery("SELECT * FROM " + selectedTable);
                            loadData(rs);

                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    } else {

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

How can I handle this reconnect matter and why do the query not work after setting up a new connection?

答:
How do you reuse the Statement in JDBC after reconnecting to the database?

You can't.

I have:
  1. a global Statement called st

Wrong already. You can't have global statements. Statements are coextensive with the connections they are created from. You should have a local variable `Statement. It cannot possibly be global.

a global ResultSet called rs

Wrong again. A ResultSet is coterminous with the Statement it is created from. It should be a local variable. It cannot possibly be global.

a global connection called conn

Wrong again. You should be using a connection pool, and have a *local variable conn.

a method setConnection that sets up the connection

Wrong again. It should be a method getConnection() that returns a new connection.

a method checkConnection that checks if the connection is alive and if not it calls the setConnection method to establish a new one

Wrong again. This method should not even exist. This is the job of the connection pool.

a button that calls checkConnection and if the boolean returned is true, it executes a query

Wrong again. It should be a button that:

gets a connection from getConnection()

creates a statement with Connection.createStatement() or Connection.prepareStatement()

Executes the statement, traverses the ResultSet, and populates whatever it has to populate with the result rows.

Body:
My JDBC connection to the MySQL database expires after 10 seconds of inactivity. After I reconnect, I can't do any queries, it keeps on asking me if I wanna reconnect as if the connection is still closed.

I have:

 1. a global Statement called st,

 2. a global ResultSet called rs,

 3. a global connection called conn,

 4. a method setConnection that sets up the connection,

 5. a method checkConnection that checks if the connection is alive and if not it calls the setConnection method to establish a new one,

 6. a button that calls checkConnection and if the boolean returned is true, it executes a query

private Connection conn = null;
private Statement st=null;
private ResultSet rs=null;

    public void setConnection(){
             host="localhost";
             database="test";
             username="testtest";
             password="testtest";
             String url = "jdbc:mysql://" + host + "/" +database+ "";
             try {
                 Class.forName ("com.mysql.jdbc.Driver");
                 conn = DriverManager.getConnection (url, username, password);
                 System.out.println("Succesfuly connected to the database!");

             } catch(Exception e){
                 System.out.println("Failed to connect to the database.");
                 e.printStackTrace();
             }
        }

    private boolean checkConnection(){
            try {
                ResultSet cc = st.executeQuery("SELECT 1");
                return true;
            } catch (SQLException e) {
                int n = JOptionPane.showConfirmDialog(
                        frame,
                        "The connection was closed, reconnect?",
                        "Database security measure",
                        JOptionPane.YES_NO_OPTION);
                if(n == JOptionPane.YES_OPTION){
                    try {
                        conn.close();
                    } catch (SQLException e1) {
                        e1.printStackTrace();
                    }
                      setConnection();
                    } else if ( n == JOptionPane.NO_OPTION){
                        frame.setVisible(false);
                        new LoginWindowB();
                    }
                return false;
            }
        }
    btn1.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    if(checkConnection()){
                        try {
                            rs = st.executeQuery("SELECT * FROM " + selectedTable);
                            loadData(rs);

                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    } else {

                    }
                }
            });

How can I handle this reconnect matter and why do the query not work after setting up a new connection?


问:
PHP EMAIL Generation not working when POST Method is used
I've made a page which will receive 3 variables and send email according to the data being sent to that page. But when I send the data from a form I get HTTP ERROR 500 when POST is used.
The same code is working when GET Method is used and when data is sent in the url. What could be the mistake?</p>

```<code><!doctype html>
<html>
<head>
<title>MAIL</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<div>
<?php

 $emailTo=$_POST['to_address'];
 $subject=$_POST['subject'];
 $body="$_POST['body'];
 $headers="From: myemail@mysite.com";

 if (mail($emailTo, $subject, $body, $headers)) {

 echo "Mail sent successfully!";

 } else {

 echo "Mail not sent!";

 }

?>
</div>
</body>
</html>
</code>```

答:
500 means internal Server-Error. Mostly there is a mistake in the source code.

Switch

```<code>$body="$_POST['body'];
</code>```

To

```<code>$body=$_POST['body'];
</code>```

You should really really escape your parameters for the mail function. Have a look at this answer:

escape mail fucntion

Body:
I've made a page which will receive 3 variables and send email according to the data being sent to that page. But when I send the data from a form I get HTTP ERROR 500 when POST is used.
The same code is working when GET Method is used and when data is sent in the url. What could be the mistake?

<!doctype html>

<title>MAIL</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />

<?php

 $emailTo=$_POST['to_address'];
 $subject=$_POST['subject'];
 $body="$_POST['body'];
 $headers="From: myemail@mysite.com";

 if (mail($emailTo, $subject, $body, $headers)) {

 echo "Mail sent successfully!";

 } else {

 echo "Mail not sent!";

 }

?>

Body:
500 means internal Server-Error. Mostly there is a mistake in the source code.

Switch

$body="$_POST['body'];

To

$body=$_POST['body'];

You should really really escape your parameters for the mail function. Have a look at this answer:

escape mail fucntion


问:
PNG Transparency in IE6 problem
I know this is a bit of a silly question, but I can't work out how to make a transparent PNG work in IE6. I've tried several things, but they haven't worked. I was wondering if anyone could let me know of a suitable hack?

Thanks in advance,

AD72

答: The PNG form of image is Post Notational Graphic and is primarily described in a law in the era of Queen Victoria of England and therefore is primarily for use in Great Britain. The software for creating and displaying a PNG image is sourced from and protected by England and the different display software versions required for all browsers and different and new browser versions and content environments may not have been commissioned to be done and the incompatibilities could persist for some time. Originally the agreement was with MS and the IE browser only for displaying PNG and it is possible a number of unofficial hacks and decodes have been developed for other browsers with varying success. PNG is officially and completely renderable only when used in a defined list of nations and provinces.   </p>

Title: PNG Transparency in IE6 problem


问:
window.location.search query as JSON
Is there a better way to convert a URL's location.search as an object? Maybe just more efficient or trimmed down? I'm using jQuery, but pure JS can work too.</p>

```<code>var query = window.location.search.substring(1), queryPairs = query.split('&'), queryJSON = {};
$.each(queryPairs, function() { queryJSON[this.split('=')[0]] = this.split('=')[1]; });
</code>```

答:
JSON Parse after stringify does the job of converting to a json with array data.

?key1=val1&key2[]=val2.1&key2[]=val2.2&key2[]=val2.3&

```<code>{
     'key1' : 'val1',
     'key2' : [ 'val2.1', 'val2.2', 'val2.3' ]
}
</code>```

function QueryParamsToJSON() {
    var list = location.search.slice(1).split('&'),
        result = {};

    list.forEach(function(keyval) {
        keyval = keyval.split('=');
        var key = keyval[0];
        if (/\[[0-9]*\]/.test(key) === true) {
            var pkey = key.split(/\[[0-9]*\]/)[0];
            if (typeof result[pkey] === 'undefined') {
                result[pkey] = [];
            }
            result[pkey].push(decodeURIComponent(keyval[1] || ''));
        } else {
            result[key] = decodeURIComponent(keyval[1] || '');
        }
    });

    return JSON.parse(JSON.stringify(result));
}

var query_string = QueryParamsToJSON();```

Title: window.location.search query as JSON

Body:
Is there a better way to convert a URL's location.search as an object? Maybe just more efficient or trimmed down? I'm using jQuery, but pure JS can work too.

var query = window.location.search.substring(1), queryPairs = query.split('&'), queryJSON = {};
$.each(queryPairs, function() { queryJSON[this.split('=')[0]] = this.split('=')[1]; });

Body:
JSON Parse after stringify does the job of converting to a json with array data.

?key1=val1&key2[]=val2.1&key2[]=val2.2&key2[]=val2.3&

{
     'key1' : 'val1',
     'key2' : [ 'val2.1', 'val2.2', 'val2.3' ]
}

function QueryParamsToJSON() {
    var list = location.search.slice(1).split('&'),
        result = {};

    list.forEach(function(keyval) {
        keyval = keyval.split('=');
        var key = keyval[0];
        if (/\[[0-9]*\]/.test(key) === true) {
            var pkey = key.split(/\[[0-9]*\]/)[0];
            if (typeof result[pkey] === 'undefined') {
                result[pkey] = [];
            }
            result[pkey].push(decodeURIComponent(keyval[1] || ''));
        } else {
            result[key] = decodeURIComponent(keyval[1] || '');
        }
    });

    return JSON.parse(JSON.stringify(result));
}

var query_string = QueryParamsToJSON();


问:
using a custom jQuery validation class
I have some custom validation I'd like to do with jQuery. jQuery validation comes out of the box with a 'required' class. This means that I can have a script declaring

```<code>$('form').validate()
</code>```

and the next textbox will validate correctly, based on the class 'required' I add to it:

```<code><input type="text" value="" name="flowstatus" id="flowstatus" class="required">
</code>```

My new validation rule is: the text in a textbox should be between 15 and 50 chars long. Is there a way to create my own custom rule/class to implement something like

```<code><input type="text" value="" name="flowstatus" id="flowstatus" class="from15to50">
</code>```

Note: This is NOT what I need:

```<code>('form').validate({
    rules: {
        flowstatus: {required: true, minlength: 15, maxlength: 50}
}});
</code>```

This last script is too tightly coupled to the fields I want to validate.

答:
I'm pretty sure that you can add an attribute to the desired element defining its min and max lengths. Something like:

```<code><input type="text" value="" name="flowstatus" id="flowstatus" class="required" minlength="15" maxlength="50">
</code>```

I'm not quite sure about the custom class solution, however.

Title: using a custom jQuery validation class

Body:
I have some custom validation I'd like to do with jQuery. jQuery validation comes out of the box with a 'required' class. This means that I can have a script declaring

$('form').validate()

and the next textbox will validate correctly, based on the class 'required' I add to it:

<input type="text" value="" name="flowstatus" id="flowstatus" class="required">

My new validation rule is: the text in a textbox should be between 15 and 50 chars long. Is there a way to create my own custom rule/class to implement something like

<input type="text" value="" name="flowstatus" id="flowstatus" class="from15to50">

Note: This is NOT what I need:

('form').validate({
    rules: {
        flowstatus: {required: true, minlength: 15, maxlength: 50}
}});

This last script is too tightly coupled to the fields I want to validate.

Body:
I'm pretty sure that you can add an attribute to the desired element defining its min and max lengths. Something like:

<input type="text" value="" name="flowstatus" id="flowstatus" class="required" minlength="15" maxlength="50">

I'm not quite sure about the custom class solution, however.


问:
Is this script safe to use?
1- I found this script most-simple-ajax-chat-ever during a browsing, I would like to add it to my vBulletin forum as a chat section with members and I would like to know if it safe to use it or not ?

2- Can I protect chat.txt from access via .htaccess ?

答:
For quick reference: It's safe but not secure. It's not the best way to end up with a chat system. You can check up other system which use database for storing and retrieving the messages. Of course you can protect the text file using .htaccess but believe me you shouldn't use this script.

Detailed reference: There are two  ways to follow up, one if you are a programmer then you should probably create own script for the same. You can use a MySQL database for the storage and probably a login system for different users. It will suck some time but you'll get something what is specially for you! If you have some bucks then you can get it professionally made.
The other way goes if you are not a programmer [which I think because you thought of taking a reference for the script] then you should check some good chat systems either open source or paid ones which have a better security and user management. I recommend using

BoomChat @ http://www.myboomchat.com/boomword [It's worth a go!]

Frug @ https://github.com/Frug/AJAX-Chat [Heard a lot about it]

Title: Is this script safe to use?


问:
How to make Data File Handling functions in a private header file? (To be edited)
EDIT: This question is to be edited, please stop reading. Don't waste your time! Thank you

I’m doing High School Turbo C++. I tried making a header file containing a function to search a binary file.
My Headerfile program is:  alpha.h

```<code>#ifndef ALPHA_H
#define ALPHA_H

#if !defined __FSTREAM_H
#include<fstream.h>
#endif

#if !defined __PROCESS_H
#include<process.h>
#endif

void searchclass(char* & buf, int, char *);

#endif
</code>```

According to some research that I did on the internet, I found out that the definitions will go in a separate program not in the main header file. So this is that program: ALPHA.CPP

```<code>#include<process.h>
#include<fstream.h>
#include"alpha.h"

//All the Definations of the alpha.h header file go here

void searchclass(char* & buf, int s_var, char * file)
{
    ifstream fin;
    fin.open(file, ios::binary);
    if(!fin)
    {
    cout<<"Error 404: File not found";
    exit(-1);
    }
    while(!fin.read((char*)buf, sizeof(buf)))
    if(buf.getint()==s_var)
        cout<<"\n\nRecord Found!";
        buf.show();
    fin.close();
}
</code>```

Keep in mind that I'm trying to write a function that can help me search a random binary file storing records in form of classes for some specific int variable. So it should be able to take in an object of any class and perform a search in it.

This is the program I wrote to check my header file.  A_TEST.CPP

```<code>#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include"alpha.h"
#include<string.h>

class stu
{   int rn;
    char name[20];
public:
void show()   //Display Function
{
   cout<<"\n\tStudent Details:";
   cout<<"\nName: "<<name;
   cout<<"\nRoll No.: "<<rn;
}
stu()       //constructor
{
  rn = 6;
  strcpy(name,"Random Name");
}
int getint()            //return function
{
  return rn;
}
};

char* returnfile()
{ char file[10];
  strcpy(file,"file.dat");
  return file;
}

void main()
{
    clrscr();
    int search_var=6;
    stu S1;
    char file[10];
    strcpy(file, "test.dat");
    ofstream fout;
    fout.open(file, ios::binary);
    fout.write((char*)&S1, sizeof(S1));
    fout.close();

    searchclass((char*)& S1, search_var, file);

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

On compiling A_TEST.CPP (above program), I get the warning:

Warning A_TEST.CPP 45: Temporary used for parameter 'buf' in call to
'searchclass(char * &,int,char *)'

On linking, it gives me this error:

Linking A_TEST.EXE

Linker Error: Undefined symbol searchclass(char nearnear&,int,char
near) in module A_TEST.CPP

I don't think that the ALPHA.CPP file is getting linked with the alpha.h file, and if I compile ALPHA.CPP file it gives me the following errors:

Error ALPHA.CPP 17: Structure required on left side of . or .*

Error ALPHA.CPP 19: Structure required on left side of . or .*

Warning ALPHA.CPP 21: Parameter 's_var' is never used

答:
In ALPHA.CPP 17 and 19, you can't write code like that, because int type hasn't getint() or show() methods. If you want to check int in the buffer, you should convert pointer into "int*" first, try below code:</p>

```<code>int count = fin.read((char*)buf, sizeof(buf));
for (int i = 0; i<(count-4); ++i) {
    if (*(int *)(buf + i) == s_var) {
        cout << "\n\nRecord Found!";
        break;
    }
}
</code>```

Body:
EDIT: This question is to be edited, please stop reading. Don't waste your time! Thank you

I’m doing High School Turbo C++. I tried making a header file containing a function to search a binary file.
My Headerfile program is:  alpha.h

#ifndef ALPHA_H
#define ALPHA_H

#if !defined __FSTREAM_H
#include<fstream.h>
#endif

#if !defined __PROCESS_H
#include<process.h>
#endif

void searchclass(char* & buf, int, char *);

#endif

According to some research that I did on the internet, I found out that the definitions will go in a separate program not in the main header file. So this is that program: ALPHA.CPP

#include<process.h>
#include<fstream.h>
#include"alpha.h"

//All the Definations of the alpha.h header file go here

void searchclass(char* & buf, int s_var, char * file)
{
    ifstream fin;
    fin.open(file, ios::binary);
    if(!fin)
    {
    cout<<"Error 404: File not found";
    exit(-1);
    }
    while(!fin.read((char*)buf, sizeof(buf)))
    if(buf.getint()==s_var)
        cout<<"\n\nRecord Found!";
        buf.show();
    fin.close();
}

Keep in mind that I'm trying to write a function that can help me search a random binary file storing records in form of classes for some specific int variable. So it should be able to take in an object of any class and perform a search in it.

This is the program I wrote to check my header file.  A_TEST.CPP

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include"alpha.h"
#include<string.h>

class stu
{   int rn;
    char name[20];
public:
void show()   //Display Function
{
   cout<<"\n\tStudent Details:";
   cout<<"\nName: "<<name;
   cout<<"\nRoll No.: "<<rn;
}
stu()       //constructor
{
  rn = 6;
  strcpy(name,"Random Name");
}
int getint()            //return function
{
  return rn;
}
};

char* returnfile()
{ char file[10];
  strcpy(file,"file.dat");
  return file;
}

void main()
{
    clrscr();
    int search_var=6;
    stu S1;
    char file[10];
    strcpy(file, "test.dat");
    ofstream fout;
    fout.open(file, ios::binary);
    fout.write((char*)&S1, sizeof(S1));
    fout.close();

    searchclass((char*)& S1, search_var, file);

    getch();
}

On compiling A_TEST.CPP (above program), I get the warning:

Warning A_TEST.CPP 45: Temporary used for parameter 'buf' in call to
'searchclass(char * &,int,char *)'

On linking, it gives me this error:

Linking A_TEST.EXE

Linker Error: Undefined symbol searchclass(char nearnear&,int,char
near) in module A_TEST.CPP

I don't think that the ALPHA.CPP file is getting linked with the alpha.h file, and if I compile ALPHA.CPP file it gives me the following errors:

Error ALPHA.CPP 17: Structure required on left side of . or .*

Error ALPHA.CPP 19: Structure required on left side of . or .*

Warning ALPHA.CPP 21: Parameter 's_var' is never used

Body:
In ALPHA.CPP 17 and 19, you can't write code like that, because int type hasn't getint() or show() methods. If you want to check int in the buffer, you should convert pointer into "int*" first, try below code:

int count = fin.read((char*)buf, sizeof(buf));
for (int i = 0; i<(count-4); ++i) {
    if (*(int *)(buf + i) == s_var) {
        cout << "\n\nRecord Found!";
        break;
    }
}


问:
Data sync algorithm based on timing
I have a problem related to data sync:

I have a source that sequentially emit data to my computer. Assume we call each data named V. V has a unique ID and contains 2 items A and B, each A or B has only a string data call ID. B is optional, that is a V can contain only A.
V will emit A and B to computer independently via 2 tcp sockets or 2 message queues. ID of V is not emited and has no sense for sync, only be used for manual check later.
Interval delay between each V can vary from minimum 500ms to 15 minutes.

E.g, source V1(A1, B1), V2(A2), V3(A3, B3)
These emit to computer via 2 queues QA(A1, A2, A3) and QB(B1, B3).

How can I sync data A and B of V at the consumers of 2 those queues as source entry sequence order?
Required: B must be sync to exact V, A can be in wrong V. E.g, after syncing, V1 must contains B1, V2 must have no B. V3 must contains B3.

Is there any sync algorithm based on timing for solving this problem.

Thank you very much!

答:
Ok as long as we know that there is an ID for each V  it is trival to build a data persistence level to take care of data syncing.

I would use a caching database ( e.g redis) to store each V emmited. On each socket listen for a new value A or B, check if the corresponding V exist in the DB, if it doesn't exist create a new key using V ID, else if it exist add the newly received value to the relevant V.

Using a different layer for data syncing will give you the advantage of not having to worry about the interval delay between each V.

Update:

Since we don't have any source of info to link the emitted data i.e A and B other than time, I would still use Redis to create a new entry for each V whenever A is sent , then on the socket listening for B data I will have a notify function if a new A has been registered, if that function triggered I will fetch the new entry and place a timer, if a new B data received I will place it with that entry. The notify function  will place a timer too, so if it exceeds the max time of 15 minutes. It will not use that entry,  or if a new A has been registered it will use the new one instead of the one fetched before.

Title: Data sync algorithm based on timing


答:
you're having a typo here -> $body="$_POST['body']; /* double quotes not closed */
plus : you should really check the POST data and sanitize as it's not secured at all</p>

Title: PHP EMAIL Generation not working when POST Method is used