问:
How to trigger notification when internet is connected for the first time on each day?
So I am facing this problem since 40 days . Tried eveything but nothing is working .

------------------------------------Logic Part---------------------

Logic is I am sending 2 broadcast

1 broadcast every hour to check the hour value .in brodcast receiver class if hour value is 1(i.e Night 1 AM) then set the notificationVariable to 0

1 broadcast is when internet is connected

```<code>    if(internet connected )
   {
     if(hour value is between 7 to 22)
    {
      if(notificationVariable ==0)
      {
        then trigger notification like Wallpaper of the day
        set the notificationVariable value to 1 ( so that it doesn't trigger on 2nd,3rd,4th time when internet is connected)
      }
    }
}
</code>```

------------------------------------End of Logic Part---------------------

------------------------------------Actual Code---------------------

I am setting the alarm in the Launching Acvitivity(MainActivity.java) using shared preference variable to set the alarm only once .

```<code>pref = new PrefManager(getApplicationContext());
    if(pref.getSetAlarmOnce()==0) {
        setAlarm();
        pref.setSetAlarmOnce(1);
    }
</code>```

below function setAlarm is the code for setting alarm in MainActivity.java File

```<code> public int setAlarm() {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    Intent myIntent = new Intent(this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() , AlarmManager.INTERVAL_HOUR, pendingIntent);
    return 0;
}
</code>```

I am using setRepeating because setInexactRepeating was not triggering alarm at all.

then in the broadcast receiver

```<code>    Calendar rightNow = Calendar.getInstance();
    int currentHour = rightNow.get(Calendar.HOUR_OF_DAY);
   if(currentHour==1)
        {
            pref.setNotificationvariable(0);
            NotificationCompat.Builder builder2 = new NotificationCompat.Builder(arg0);
        int color2 = 0xff123456;
        Bitmap icon2 = BitmapFactory.decodeResource(arg0.getResources(), R.mipmap.ic_launcher);
        Notification notification2 = builder2 .setContentTitle("Notification Variable->"+pref.getNotificationvariable())
                .setContentText("Current Hour ->"+currentHour)
                .setColor(color2)
                .setAutoCancel(true)
                .setPriority(Notification.PRIORITY_HIGH)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(icon2)
                .build();
         NotificationManager notificationManager2 = (NotificationManager) arg0.getSystemService(arg0.NOTIFICATION_SERVICE);
        notificationManager2.notify(0, notification2);
    }

if (ConnectivityManager.CONNECTIVITY_ACTION.equals(arg1.getAction())) {
            NetworkInfo networkInfo = arg1.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
                if(currentHour>=7 && currentHour <=22)
                {
                    if(String.valueOf(pref.getNotificationvariable()).equals("0"))
                    {
                        notificationimages = new ArrayList<>();
                        albumsListreceiver=AppController.getInstance().getPrefManger().getCategories();
                        String albumId = albumsListreceiver.get(GenerateRandom(albumsListreceiver.size())).getId();
                        String url = "https://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key=481497b7c813f81b3fbf613f1c9783fb&photoset_id=" + albumId + "&user_id=153679059@N08&format=json";
                        Log.d("alarmreciever",url);
                        StringRequest getRequest1 = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                String s = response.replace("jsonFlickrApi(", "");
                                String snew = s.replace(")", "");
                                Log.d("alarmreciever","hi");
                                try {
                                    JSONObject jsonObject = new JSONObject(snew);
                                    JSONArray entry = jsonObject.getJSONObject("photoset").getJSONArray("photo");
                                    notificationimages.clear();
                                    Log.d("alarmreciever",String.valueOf(entry.length()));
                                    for (int i = 0; i < entry.length(); i++) {
                                        Log.d("alarmreciever","hi");
                                        JSONObject albumObj = (JSONObject) entry.get(i);
                                        Image image = new Image();
                                        String titleOfImage = albumObj.getString("title");
                                        image.setName(titleOfImage);
                                        String photoID = albumObj.getString("id");
                                        String secretID = albumObj.getString("secret");
                                        String farmID = albumObj.getString("farm");
                                        String serverID = albumObj.getString("server");
                                        String imageUrl = "https://farm" + farmID + ".staticflickr.com/" + serverID + "/" + photoID + "_" + secretID + "_b.jpg";
                                        image.setLarge(imageUrl);
                                        notificationimages.add(image);
                                    }
                                    int randompositionToShowImageinNotification=GenerateRandom(notificationimages.size());
                                    Intent notificationIntent = new Intent(arg0, FullScreenActivity.class);
                                    notificationIntent.putExtra("images",notificationimages);
                                    notificationIntent.putExtra("position", randompositionToShowImageinNotification);
                                    notificationIntent.putExtra("started_from","notification");
                                    PendingIntent pendingIntent= PendingIntent.getActivity(arg0,0,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
                                    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                                    NotificationCompat.Builder builder = new NotificationCompat.Builder(arg0);
                                    int color = 0xff123456;
                                    Bitmap icon = BitmapFactory.decodeResource(arg0.getResources(), R.mipmap.ic_launcher);
                                    Notification notification = builder.setContentTitle("Pic of the Day")
                                            .setContentText("Tap this to get Your Pic of the Day Now !")
                                            .setColor(color)
                                            .setAutoCancel(true)
                                            .setSound(defaultSoundUri)
                                            .setPriority(Notification.PRIORITY_HIGH)
                                            .setSmallIcon(R.mipmap.ic_launcher)
                                            .setLargeIcon(icon)
                                            .setContentIntent(pendingIntent).build();
                                    NotificationManager notificationManager = (NotificationManager) arg0.getSystemService(arg0.NOTIFICATION_SERVICE);
                                    notificationManager.notify(0, notification);
                                    pref.setNotificationvariable(1);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                            }
                        });
                        // Remove the url from cache
                        AppController.getInstance().getRequestQueue().getCache().remove(url);
                        // Disable the cache for this url, so that it always fetches updated json
                        getRequest1.setShouldCache(false);
                        // Adding request to request queue
                        AppController.getInstance().addToRequestQueue(getRequest1);
                    }
                }
</code>```

-------------------------------------End of Actual Code------------------------

Now the issue is when i am setting the Alarm to trigger every hour it is triggering but only till night 12 AM .Suppose i Set the alarm at 9.30 AM it will trigger at 10:00,11:00,12:00 PM,1:00PM ,2:00,3:00 and so on till 12:00 AM at night but after that it stops to trigger . Means it is not always triggering at 1:00 AM EVERYDAY to make the notificationVariable to 0 .

Sorry for my bad english .

答:
Done by Setting the Alarm to trigger at 1:00 AM instead of triggering everyhour and checking whether it is 1:00 AM or not .

Changed this

```<code>public int setAlarm() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Intent myIntent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() , AlarmManager.INTERVAL_HOUR, pendingIntent);
return 0;
}
</code>```

to

this

```<code>public int setAlarm() {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, 1);//this is the main change
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    Intent myIntent = new Intent(this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() , AlarmManager.INTERVAL_DAY, pendingIntent);
    return 0;
}
</code>```

Body:
So I am facing this problem since 40 days . Tried eveything but nothing is working .

------------------------------------Logic Part---------------------

Logic is I am sending 2 broadcast

1 broadcast every hour to check the hour value .in brodcast receiver class if hour value is 1(i.e Night 1 AM) then set the notificationVariable to 0

1 broadcast is when internet is connected

    if(internet connected )
   {
     if(hour value is between 7 to 22)
    {
      if(notificationVariable ==0)
      {
        then trigger notification like Wallpaper of the day
        set the notificationVariable value to 1 ( so that it doesn't trigger on 2nd,3rd,4th time when internet is connected)
      }
    }
}

------------------------------------End of Logic Part---------------------

------------------------------------Actual Code---------------------

I am setting the alarm in the Launching Acvitivity(MainActivity.java) using shared preference variable to set the alarm only once .

pref = new PrefManager(getApplicationContext());
    if(pref.getSetAlarmOnce()==0) {
        setAlarm();
        pref.setSetAlarmOnce(1);
    }

below function setAlarm is the code for setting alarm in MainActivity.java File

 public int setAlarm() {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    Intent myIntent = new Intent(this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() , AlarmManager.INTERVAL_HOUR, pendingIntent);
    return 0;
}

I am using setRepeating because setInexactRepeating was not triggering alarm at all.

then in the broadcast receiver

    Calendar rightNow = Calendar.getInstance();
    int currentHour = rightNow.get(Calendar.HOUR_OF_DAY);
   if(currentHour==1)
        {
            pref.setNotificationvariable(0);
            NotificationCompat.Builder builder2 = new NotificationCompat.Builder(arg0);
        int color2 = 0xff123456;
        Bitmap icon2 = BitmapFactory.decodeResource(arg0.getResources(), R.mipmap.ic_launcher);
        Notification notification2 = builder2 .setContentTitle("Notification Variable->"+pref.getNotificationvariable())
                .setContentText("Current Hour ->"+currentHour)
                .setColor(color2)
                .setAutoCancel(true)
                .setPriority(Notification.PRIORITY_HIGH)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(icon2)
                .build();
         NotificationManager notificationManager2 = (NotificationManager) arg0.getSystemService(arg0.NOTIFICATION_SERVICE);
        notificationManager2.notify(0, notification2);
    }

if (ConnectivityManager.CONNECTIVITY_ACTION.equals(arg1.getAction())) {
            NetworkInfo networkInfo = arg1.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
                if(currentHour>=7 && currentHour <=22)
                {
                    if(String.valueOf(pref.getNotificationvariable()).equals("0"))
                    {
                        notificationimages = new ArrayList<>();
                        albumsListreceiver=AppController.getInstance().getPrefManger().getCategories();
                        String albumId = albumsListreceiver.get(GenerateRandom(albumsListreceiver.size())).getId();
                        String url = "https://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key=481497b7c813f81b3fbf613f1c9783fb&photoset_id=" + albumId + "&user_id=153679059@N08&format=json";
                        Log.d("alarmreciever",url);
                        StringRequest getRequest1 = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                String s = response.replace("jsonFlickrApi(", "");
                                String snew = s.replace(")", "");
                                Log.d("alarmreciever","hi");
                                try {
                                    JSONObject jsonObject = new JSONObject(snew);
                                    JSONArray entry = jsonObject.getJSONObject("photoset").getJSONArray("photo");
                                    notificationimages.clear();
                                    Log.d("alarmreciever",String.valueOf(entry.length()));
                                    for (int i = 0; i < entry.length(); i++) {
                                        Log.d("alarmreciever","hi");
                                        JSONObject albumObj = (JSONObject) entry.get(i);
                                        Image image = new Image();
                                        String titleOfImage = albumObj.getString("title");
                                        image.setName(titleOfImage);
                                        String photoID = albumObj.getString("id");
                                        String secretID = albumObj.getString("secret");
                                        String farmID = albumObj.getString("farm");
                                        String serverID = albumObj.getString("server");
                                        String imageUrl = "https://farm" + farmID + ".staticflickr.com/" + serverID + "/" + photoID + "_" + secretID + "_b.jpg";
                                        image.setLarge(imageUrl);
                                        notificationimages.add(image);
                                    }
                                    int randompositionToShowImageinNotification=GenerateRandom(notificationimages.size());
                                    Intent notificationIntent = new Intent(arg0, FullScreenActivity.class);
                                    notificationIntent.putExtra("images",notificationimages);
                                    notificationIntent.putExtra("position", randompositionToShowImageinNotification);
                                    notificationIntent.putExtra("started_from","notification");
                                    PendingIntent pendingIntent= PendingIntent.getActivity(arg0,0,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
                                    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                                    NotificationCompat.Builder builder = new NotificationCompat.Builder(arg0);
                                    int color = 0xff123456;
                                    Bitmap icon = BitmapFactory.decodeResource(arg0.getResources(), R.mipmap.ic_launcher);
                                    Notification notification = builder.setContentTitle("Pic of the Day")
                                            .setContentText("Tap this to get Your Pic of the Day Now !")
                                            .setColor(color)
                                            .setAutoCancel(true)
                                            .setSound(defaultSoundUri)
                                            .setPriority(Notification.PRIORITY_HIGH)
                                            .setSmallIcon(R.mipmap.ic_launcher)
                                            .setLargeIcon(icon)
                                            .setContentIntent(pendingIntent).build();
                                    NotificationManager notificationManager = (NotificationManager) arg0.getSystemService(arg0.NOTIFICATION_SERVICE);
                                    notificationManager.notify(0, notification);
                                    pref.setNotificationvariable(1);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                            }
                        });
                        // Remove the url from cache
                        AppController.getInstance().getRequestQueue().getCache().remove(url);
                        // Disable the cache for this url, so that it always fetches updated json
                        getRequest1.setShouldCache(false);
                        // Adding request to request queue
                        AppController.getInstance().addToRequestQueue(getRequest1);
                    }
                }

-------------------------------------End of Actual Code------------------------

Now the issue is when i am setting the Alarm to trigger every hour it is triggering but only till night 12 AM .Suppose i Set the alarm at 9.30 AM it will trigger at 10:00,11:00,12:00 PM,1:00PM ,2:00,3:00 and so on till 12:00 AM at night but after that it stops to trigger . Means it is not always triggering at 1:00 AM EVERYDAY to make the notificationVariable to 0 .

Sorry for my bad english .

Body:
Done by Setting the Alarm to trigger at 1:00 AM instead of triggering everyhour and checking whether it is 1:00 AM or not .

Changed this

public int setAlarm() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Intent myIntent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() , AlarmManager.INTERVAL_HOUR, pendingIntent);
return 0;
}

to

this

public int setAlarm() {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, 1);//this is the main change
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    Intent myIntent = new Intent(this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() , AlarmManager.INTERVAL_DAY, pendingIntent);
    return 0;
}


来源: stackexchange

问:
Implementing Pandora FMS for monitoring
So, I'm implementing a monitoring solution in site 6 which will be used to monitor all activity in all sites (from 1 to 6 positioned in two different zones and connected with a switch) and please note that basically all servers use CentOS as an OS.

What is the best practice to implement Pandora FMS positioning it in the DMZ or the LAN part or a Lan to its own ? Should I use remote monitoring or local monitoring ?

Site 6

答:
Inside your PandoraFMS configurarion you could have details about your servers or network arquitecture (ips, os, services runnings, etc) because you need it to monitor your servers...

The best option for me is to place PandoraFMS server in a secure network behind a firewall and use remote monitoring so you can access de DMZ safelly.

Hope it helps!

ContentLicense: CC BY-SA 3.0

Title: Implementing Pandora FMS for monitoring


问:
How to use svg icon set package from node_modules in angular4?
I have found this open source icon package which I installed in my project featherIcons, and is listed inside my_modules directory. However Im trying to use it but I just cant seem to make it work.

The issue is, I think I have to be somehow importing the package but not sure how or where.

app-component.html

Platform

Stix/Taxi

Menu

```
</div>
</div>
</p>

<p><strong><code>app.module.ts</code></strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

import { RoutingModule } from './routing.module';
import { SharedModule } from './shared/shared.module';
import { CatService } from './services/cat.service';
import { UserService } from './services/user.service';
import { AuthService } from './services/auth.service';
import { AuthGuardLogin } from './services/auth-guard-login.service';
import { AuthGuardAdmin } from './services/auth-guard-admin.service';
import { AppComponent } from './app.component';
import { CatsComponent } from './cats/cats.component';
import { AboutComponent } from './about/about.component';
import { RegisterComponent } from './register/register.component';
import { LoginComponent } from './login/login.component';
import { LogoutComponent } from './logout/logout.component';
import { AccountComponent } from './account/account.component';
import { AdminComponent } from './admin/admin.component';
import { NotFoundComponent } from './not-found/not-found.component';

@NgModule({
  declarations: [
    AppComponent,
    CatsComponent,
    AboutComponent,
    RegisterComponent,
    LoginComponent,
    LogoutComponent,
    AccountComponent,
    AdminComponent,
    NotFoundComponent
  ],
  imports: [
    RoutingModule,
    SharedModule
  ],
  providers: [
    AuthService,
    AuthGuardLogin,
    AuthGuardAdmin,
    CatService,
    UserService
  ],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  bootstrap: [AppComponent]
})

export class AppModule { }</code>```

Any help would be appreciated

答:
Solution using angular-feather

The advantage of it being that you cherry pick only the icons that you need, thus reducing bundle size.

Install the package

```<code>npm install angular-feather
</code>```

Import the icons you need

Import the icons a la carte in the angular module of your needs

```<code>import { NgModule } from '@angular/core';

import { FeatherModule } from 'angular-feather';
import { Camera, Heart, Github } from 'angular-feather/icons';

// Select some icons (use an object, not an array)
const icons = {
  Camera,
  Heart,
  Github
};

@NgModule({
  imports: [
    FeatherModule.pick(icons)
  ],
  exports: [
    FeatherModule
  ]
})
export class IconsModule {}
</code>```

Import IconsModule and use component

```<code><i-feather name="heart"></i-feather>
<i-feather name="camera"></i-feather>
</code>```

Stackblitz demo

Body:
I have found this open source icon package which I installed in my project featherIcons, and is listed inside my_modules directory. However Im trying to use it but I just cant seem to make it work.

The issue is, I think I have to be somehow importing the package but not sure how or where.

app-component.html

Platform

Stix/Taxi

Menu

app.module.ts

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

import { RoutingModule } from './routing.module';
import { SharedModule } from './shared/shared.module';
import { CatService } from './services/cat.service';
import { UserService } from './services/user.service';
import { AuthService } from './services/auth.service';
import { AuthGuardLogin } from './services/auth-guard-login.service';
import { AuthGuardAdmin } from './services/auth-guard-admin.service';
import { AppComponent } from './app.component';
import { CatsComponent } from './cats/cats.component';
import { AboutComponent } from './about/about.component';
import { RegisterComponent } from './register/register.component';
import { LoginComponent } from './login/login.component';
import { LogoutComponent } from './logout/logout.component';
import { AccountComponent } from './account/account.component';
import { AdminComponent } from './admin/admin.component';
import { NotFoundComponent } from './not-found/not-found.component';

@NgModule({
  declarations: [
    AppComponent,
    CatsComponent,
    AboutComponent,
    RegisterComponent,
    LoginComponent,
    LogoutComponent,
    AccountComponent,
    AdminComponent,
    NotFoundComponent
  ],
  imports: [
    RoutingModule,
    SharedModule
  ],
  providers: [
    AuthService,
    AuthGuardLogin,
    AuthGuardAdmin,
    CatService,
    UserService
  ],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  bootstrap: [AppComponent]
})

export class AppModule { }

Any help would be appreciated

Body:
Solution using angular-feather

The advantage of it being that you cherry pick only the icons that you need, thus reducing bundle size.

Install the package

npm install angular-feather

Import the icons you need

Import the icons a la carte in the angular module of your needs

import { NgModule } from '@angular/core';

import { FeatherModule } from 'angular-feather';
import { Camera, Heart, Github } from 'angular-feather/icons';

// Select some icons (use an object, not an array)
const icons = {
  Camera,
  Heart,
  Github
};

@NgModule({
  imports: [
    FeatherModule.pick(icons)
  ],
  exports: [
    FeatherModule
  ]
})
export class IconsModule {}

Import IconsModule and use component

<i-feather name="heart"></i-feather>
<i-feather name="camera"></i-feather>

Stackblitz demo

ContentLicense: CC BY-SA 4.0


问:
how to repeat result from math.random in javascript?
just to clarify my question, i need to generate a 2 digits numbers separately to make it set of 6 like this "12,45,24,63,64,1"</p>

```<code><html>
 <head>
    <title>lotto picker</title>

 </head>
 <body>

    <p> I can generate you a lotto numbers to bet right now!</p>
    <button id="generateButton">Generate!</button>

 <script type="text/javascript">
   document.getElementById("generateButton").onclick = function() {

                var msg = " ";
                var lottoNum = Math.floor((Math.random() * 64) + 1);

                alert(lottoNum);

            }
 </script>
 </body>

</html>
</code>```

答:
Here 10 to 89 is the desired range.

Where:

10 is the start number

89 is the number of possible results (10 + start (89) - end (10))

    document.getElementById("generateButton").onclick = function() {
                var msg = " ";
                for(var i = 0 ;i < 6 ; ++i) {
                var lottoNum = Math.floor(Math.random() *89) + 10;
                msg += lottoNum + ", ";
                }
                msg = msg.slice(0, -1);
                alert(msg);
                }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
    <title>lotto picker</title>
</head>

<body>
    <p> I can generate you a lotto numbers to bet right now!</p>
    <button id="generateButton">Generate!</button>
</body></code>```

Body:
just to clarify my question, i need to generate a 2 digits numbers separately to make it set of 6 like this "12,45,24,63,64,1"

    <title>lotto picker</title>

 I can generate you a lotto numbers to bet right now!

    <button id="generateButton">Generate!</button>

Body:
Here 10 to 89 is the desired range.

Where:

10 is the start number

89 is the number of possible results (10 + start (89) - end (10))

    document.getElementById("generateButton").onclick = function() {
                var msg = " ";
                for(var i = 0 ;i < 6 ; ++i) {
                var lottoNum = Math.floor(Math.random() *89) + 10;
                msg += lottoNum + ", ";
                }
                msg = msg.slice(0, -1);
                alert(msg);
                }

<html>
<head>
    <title>lotto picker</title>
</head>

<body>
    <p> I can generate you a lotto numbers to bet right now!</p>
    <button id="generateButton">Generate!</button>
</body>


问:
how to do classification over forecast data
I am new comer to the field of Machine Learning, and I have an excel sheet of this structure:

```<code>Columns = {date, ..., Inflation}
</code>```

the first column is date the next columns are numbers and the last column is inflation which is decimal.

```<code>date ... Inflation
01/06/2016 ... -0.07363739
01/07/2016 ... -0.07363741
</code>```

The problem is that I was asked to apply some classification algorithms over these forecast data such as (Naive Bayes, kNN, SVM, and maybe others as well) and compare the accuracy of these algorithms.

What I didn't understand is how to treat this data from a Classification perspective?

I did some Timeseries over the data with R and it worked, but I still can't apply the classification algorithms:

```<code>dft <- read_excel("./data.xlsx",
                          sheet = 1)
df <- ts(dft$inflation, frequency=12, start=c(2016,6))
plot.ts(df)
fit <- HoltWinters(df, beta=FALSE, gamma=FALSE)
</code>```

Is there any help in how to work with this data for classification with R?
Any help is appreciated

Data sample : https://drive.google.com/open?id=0B1gJg-F8Gb76a1N3NVBXNFd1bjg

答:
You could share some sample lines of your data. So basically what you have is a regression problem. So either you categorize it e.g. bin it to certain categories or use regression approaches, e.g. Linear Regression/ Penalized Regression, Support Vector Regression etc..

In R you can manually categorize your variables (there are also packages) like follows:

```<code>cut_off_high = 0.88
cut_off_low = 0.55

high_inflation = sample_dataframe[which(sample_dataframe$inflation > cut_off),]
medium_inflation = sample_dataframe[which(sample_dataframe$inflation > cut_off_low & sample_dataframe$inflation <= cut_off_high),]
low_inflation = sample_dataframe[which(sample_dataframe$inflation < cut_off_low),]

high_inflation$inflation = "High"
medium_inflation$inflation = "Medium"
low_inflation$inflation = "Low"
</code>```

Now this is just an example so you understand the idea of binning, in reality you'd want to use something like this e.g. Categorize continuous variable with dplyr.

I hope this answers your question, how you could use classification on your dataset. However, since you don't seem to know much regarding ML I'd suggest you stick to some easy regression algorithms so you also avoid multi-class classification problems.

An easy starter would be:

```<code>linear_regression_model = lm(inflation ~ variable_name_1 + variable_name_2 + .. + variable_name_n, data = your_data_frame)
</code>```

However, If you go beyond simple models you will have to face hyperparameters, cross-validation etc. , which you should understand before applying them (you should also understand what a certain model does in order to know which to apply).

I guess stackoverflow does not substitute education, I'd strongly suggest you to educate yourself reasonably well before messing around with models and things you do not understand at all.

If you have a specific question, feel free to ask though.

Body:
I am new comer to the field of Machine Learning, and I have an excel sheet of this structure:

Columns = {date, ..., Inflation}

the first column is date the next columns are numbers and the last column is inflation which is decimal.

date ... Inflation
01/06/2016 ... -0.07363739
01/07/2016 ... -0.07363741

The problem is that I was asked to apply some classification algorithms over these forecast data such as (Naive Bayes, kNN, SVM, and maybe others as well) and compare the accuracy of these algorithms.

What I didn't understand is how to treat this data from a Classification perspective?

I did some Timeseries over the data with R and it worked, but I still can't apply the classification algorithms:

dft <- read_excel("./data.xlsx",
                          sheet = 1)
df <- ts(dft$inflation, frequency=12, start=c(2016,6))
plot.ts(df)
fit <- HoltWinters(df, beta=FALSE, gamma=FALSE)

Is there any help in how to work with this data for classification with R?
Any help is appreciated

Data sample : https://drive.google.com/open?id=0B1gJg-F8Gb76a1N3NVBXNFd1bjg

Body:
You could share some sample lines of your data. So basically what you have is a regression problem. So either you categorize it e.g. bin it to certain categories or use regression approaches, e.g. Linear Regression/ Penalized Regression, Support Vector Regression etc..

In R you can manually categorize your variables (there are also packages) like follows:

cut_off_high = 0.88
cut_off_low = 0.55

high_inflation = sample_dataframe[which(sample_dataframe$inflation > cut_off),]
medium_inflation = sample_dataframe[which(sample_dataframe$inflation > cut_off_low & sample_dataframe$inflation <= cut_off_high),]
low_inflation = sample_dataframe[which(sample_dataframe$inflation < cut_off_low),]

high_inflation$inflation = "High"
medium_inflation$inflation = "Medium"
low_inflation$inflation = "Low"

Now this is just an example so you understand the idea of binning, in reality you'd want to use something like this e.g. Categorize continuous variable with dplyr.

I hope this answers your question, how you could use classification on your dataset. However, since you don't seem to know much regarding ML I'd suggest you stick to some easy regression algorithms so you also avoid multi-class classification problems.

An easy starter would be:

linear_regression_model = lm(inflation ~ variable_name_1 + variable_name_2 + .. + variable_name_n, data = your_data_frame)

However, If you go beyond simple models you will have to face hyperparameters, cross-validation etc. , which you should understand before applying them (you should also understand what a certain model does in order to know which to apply).

I guess stackoverflow does not substitute education, I'd strongly suggest you to educate yourself reasonably well before messing around with models and things you do not understand at all.

If you have a specific question, feel free to ask though.


问:
RadioGroupButton doesn't seem to work with React Starter Kit
Here's a gif of it:
http://www.giphy.com/gifs/3oKIP7arhKhNzNzytq

As you can see, whenever I click on it, it doesn't select.

Here's my exact code which is working in webpack:
https://www.webpackbin.com/bins/-KoaaPYxDno695fiUBMn

But in my starter kit environment, it doesn't seem to work. However, checkboxes seem to work. Any ideas?

```<code>"react": "^15.5.4",
"react-dom": "^15.5.4",
"material-ui": "^0.18.6",
</code>```

EDIT: I also have react-tap-event-plugin and I've called it at the top of my client.js file. Also tried on the top of my Location.js file.

```<code>import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
</code>```

Here's my full dependency list:

```<code>dependencies": {
    "apisauce": "^0.14.0",
    "babel-polyfill": "^6.23.0",
    "bluebird": "^3.5.0",
    "body-parser": "^1.17.2",
    "classnames": "^2.2.5",
    "cookie-parser": "^1.4.3",
    "core-js": "^2.4.1",
    "express": "^4.15.3",
    "express-graphql": "^0.6.6",
    "express-jwt": "^5.3.0",
    "graphql": "^0.10.3",
    "history": "^4.6.3",
    "isomorphic-style-loader": "^2.0.0",
    "jsonwebtoken": "^7.4.1",
    "material-ui": "^0.18.6",
    "node-fetch": "^1.7.1",
    "normalize.css": "^7.0.0",
    "passport": "^0.3.2",
    "passport-facebook": "^2.1.1",
    "pretty-error": "^2.1.1",
    "prop-types": "^15.5.10",
    "query-string": "^4.3.4",
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-tap-event-plugin": "^2.0.1",
    "sequelize": "^4.2.1",
    "serialize-javascript": "^1.3.0",
    "source-map-support": "^0.4.15",
    "sqlite3": "^3.1.8",
    "universal-router": "^3.2.0",
    "whatwg-fetch": "^2.0.3"
  },
</code>```

答:
You are most probably missing the react-tap-event-plugin.
Add it with npm install -save react-tap-event-plugin

Body:
Here's a gif of it:
http://www.giphy.com/gifs/3oKIP7arhKhNzNzytq

As you can see, whenever I click on it, it doesn't select.

Here's my exact code which is working in webpack:
https://www.webpackbin.com/bins/-KoaaPYxDno695fiUBMn

But in my starter kit environment, it doesn't seem to work. However, checkboxes seem to work. Any ideas?

"react": "^15.5.4",
"react-dom": "^15.5.4",
"material-ui": "^0.18.6",

EDIT: I also have react-tap-event-plugin and I've called it at the top of my client.js file. Also tried on the top of my Location.js file.

import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();

Here's my full dependency list:

dependencies": {
    "apisauce": "^0.14.0",
    "babel-polyfill": "^6.23.0",
    "bluebird": "^3.5.0",
    "body-parser": "^1.17.2",
    "classnames": "^2.2.5",
    "cookie-parser": "^1.4.3",
    "core-js": "^2.4.1",
    "express": "^4.15.3",
    "express-graphql": "^0.6.6",
    "express-jwt": "^5.3.0",
    "graphql": "^0.10.3",
    "history": "^4.6.3",
    "isomorphic-style-loader": "^2.0.0",
    "jsonwebtoken": "^7.4.1",
    "material-ui": "^0.18.6",
    "node-fetch": "^1.7.1",
    "normalize.css": "^7.0.0",
    "passport": "^0.3.2",
    "passport-facebook": "^2.1.1",
    "pretty-error": "^2.1.1",
    "prop-types": "^15.5.10",
    "query-string": "^4.3.4",
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-tap-event-plugin": "^2.0.1",
    "sequelize": "^4.2.1",
    "serialize-javascript": "^1.3.0",
    "source-map-support": "^0.4.15",
    "sqlite3": "^3.1.8",
    "universal-router": "^3.2.0",
    "whatwg-fetch": "^2.0.3"
  },


问:
Removing/shutdown Firebase in Java app (for hot redepoy)
I tried to use org.springframework.boot:spring-boot-devtools to speed up development.

My project uses Firebase to authenticate some requests. Firebase initialized via:

```<code>@PostConstruct
public void instantiateFirebase() throws IOException {
    FirebaseOptions options = new FirebaseOptions.Builder()
            .setDatabaseUrl(String.format("https://%s.firebaseio.com", configuration.getFirebaseDatabase()))
            .setServiceAccount(serviceJson.getInputStream())
            .build();
    FirebaseApp.initializeApp(options);
}
</code>```

After context reloading on changing .class file Spring reports error:

```<code>Caused by: java.lang.IllegalStateException: FirebaseApp name [DEFAULT] already exists!
    at com.google.firebase.internal.Preconditions.checkState(Preconditions.java:173)
    at com.google.firebase.FirebaseApp.initializeApp(FirebaseApp.java:180)
    at com.google.firebase.FirebaseApp.initializeApp(FirebaseApp.java:160)
</code>```

What Firebase API allow deregister/destroy FirebaseApp that I should use in @PreDestroy?

答:
Looks like it is not possible to disable/shutdown/reinitialize Firebase app.

In my case it is fine to keep that instance in memory without changes.

Depending on your requirements you may use as simple as:

```<code>@PostConstruct
public void instantiateFirebase() throws IOException {
    // We use only FirebaseApp.DEFAULT_APP_NAME, so check is simple.
    if ( ! FirebaseApp.getApps().isEmpty())
        return;

    Resource serviceJson = applicationContext.getResource(String.format("classpath:firebase/%s", configuration.getFirebaseServiceJson()));

    FirebaseOptions options = new FirebaseOptions.Builder()
            .setDatabaseUrl(String.format("https://%s.firebaseio.com", configuration.getFirebaseDatabase()))
            .setServiceAccount(serviceJson.getInputStream())
            .build();
    FirebaseApp.initializeApp(options);
}
</code>```

or filter data like:

```<code>for (FirebaseApp app : FirebaseApp.getApps()) {
    if (app.getName().equals(FirebaseApp.DEFAULT_APP_NAME))
        return;
}
</code>```

Body:
I tried to use org.springframework.boot:spring-boot-devtools to speed up development.

My project uses Firebase to authenticate some requests. Firebase initialized via:

@PostConstruct
public void instantiateFirebase() throws IOException {
    FirebaseOptions options = new FirebaseOptions.Builder()
            .setDatabaseUrl(String.format("https://%s.firebaseio.com", configuration.getFirebaseDatabase()))
            .setServiceAccount(serviceJson.getInputStream())
            .build();
    FirebaseApp.initializeApp(options);
}

After context reloading on changing .class file Spring reports error:

Caused by: java.lang.IllegalStateException: FirebaseApp name [DEFAULT] already exists!
    at com.google.firebase.internal.Preconditions.checkState(Preconditions.java:173)
    at com.google.firebase.FirebaseApp.initializeApp(FirebaseApp.java:180)
    at com.google.firebase.FirebaseApp.initializeApp(FirebaseApp.java:160)

What Firebase API allow deregister/destroy FirebaseApp that I should use in @PreDestroy?

Body:
Looks like it is not possible to disable/shutdown/reinitialize Firebase app.

In my case it is fine to keep that instance in memory without changes.

Depending on your requirements you may use as simple as:

@PostConstruct
public void instantiateFirebase() throws IOException {
    // We use only FirebaseApp.DEFAULT_APP_NAME, so check is simple.
    if ( ! FirebaseApp.getApps().isEmpty())
        return;

    Resource serviceJson = applicationContext.getResource(String.format("classpath:firebase/%s", configuration.getFirebaseServiceJson()));

    FirebaseOptions options = new FirebaseOptions.Builder()
            .setDatabaseUrl(String.format("https://%s.firebaseio.com", configuration.getFirebaseDatabase()))
            .setServiceAccount(serviceJson.getInputStream())
            .build();
    FirebaseApp.initializeApp(options);
}

or filter data like:

for (FirebaseApp app : FirebaseApp.getApps()) {
    if (app.getName().equals(FirebaseApp.DEFAULT_APP_NAME))
        return;
}


问:
Is a function definition an object?
Say I have an object and a function definition:

```<code>var jane = {
    firstName: 'Jane',
    lastName: 'Smith',
    describe: function () {
        return 'Person named '+this.firstName+this.lastName
    },
};

function Car (desc) {
    this.desc = desc;
    this.color = "red";
    this.getInfo = function getInfo() {
        return 'A ' + this.color + ' ' + this.desc + '.';
    };
}
</code>```

I can enumerate over the object's key:value pairs thus:

```<code>obj=jane
for (var prop in obj) {
  console.log(`obj.${prop} = ${obj[prop]}`);
}
</code>```

but this fails for the function definition (same for function expression)

```<code>obj=Car.....
</code>```

If a function definition is an object then why can't I enumerate over it's properties? Is there a way do to it?

Thanks

答:
while Functions are Objects, properties of the this special Object inside a Function are not enumerable in the for...in loop over the Function itself...

if you don't like the new operator which binds this onto a new Object, making it's properties enumerable on that new object, feel free to call it with explicit this argument like this:

```<code>var obj = {};
Car.call(obj);
</code>```

function Car(desc) {
  this.desc = desc;
  this.color = "red";
  this.getInfo = function getInfo() {
    return 'A ' + this.color + ' ' + this.desc + '.';
  };
}

var obj = {};
Car.call(obj);

for (var prop in obj) {
  console.log(`obj.${prop} = ${obj[prop]}`);
}```
</div>
</div>
</p>

<p>One more complicated route starts with parsing the function source code:  <code>Car.toString()</code>:</p>

```function simpleThisInspector(constructorFn) {
  const source = constructorFn.toString()
  const thisProps = {}
  // TODO: nested {} blocks and non-block multiline statements not supported
  const re = /this\.(\w+)\s*=\s*([^;\n{]*(?:\{[^}]*})?)/g  // https://regex101.com/r/aJzgjx/1
  let match
  while(match = re.exec(source)) {
    thisProps[match[1]] = match[2]
  }
  return thisProps
}

var obj = simpleThisInspector(Car)
```

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function simpleThisInspector(constructorFn) {
  const source = constructorFn.toString()
  const thisProps = {}
  // TODO: nested {} blocks and non-block multiline statements not supported
  const re = /this\.(\w+)\s*=\s*([^;\n{]*(?:\{[^}]*})?)/g  // https://regex101.com/r/aJzgjx/1
  let match
  while(match = re.exec(source)) {
    thisProps[match[1]] = match[2]
  }
  return thisProps
}

function Car(desc) {
  this.desc = desc;
  this.color = "red";
  this.getInfo = function getInfo() {
    return 'A ' + this.color + ' ' + this.desc + '.';
  };
}

var obj = simpleThisInspector(Car)

for (var prop in obj) {
  console.log(`obj.${prop} = ${obj[prop]}`);
}</code>```

Title: Is a function definition an object?

Body:
Say I have an object and a function definition:

var jane = {
    firstName: 'Jane',
    lastName: 'Smith',
    describe: function () {
        return 'Person named '+this.firstName+this.lastName
    },
};

function Car (desc) {
    this.desc = desc;
    this.color = "red";
    this.getInfo = function getInfo() {
        return 'A ' + this.color + ' ' + this.desc + '.';
    };
}

I can enumerate over the object's key:value pairs thus:

obj=jane
for (var prop in obj) {
  console.log(`obj.${prop} = ${obj[prop]}`);
}

but this fails for the function definition (same for function expression)

obj=Car.....

If a function definition is an object then why can't I enumerate over it's properties? Is there a way do to it?

Thanks

Body:
while Functions are Objects, properties of the this special Object inside a Function are not enumerable in the for...in loop over the Function itself...

if you don't like the new operator which binds this onto a new Object, making it's properties enumerable on that new object, feel free to call it with explicit this argument like this:

var obj = {};
Car.call(obj);

function Car(desc) {
  this.desc = desc;
  this.color = "red";
  this.getInfo = function getInfo() {
    return 'A ' + this.color + ' ' + this.desc + '.';
  };
}

var obj = {};
Car.call(obj);

for (var prop in obj) {
  console.log(`obj.${prop} = ${obj[prop]}`);
}

One more complicated route starts with parsing the function source code:  Car.toString():

function simpleThisInspector(constructorFn) {
  const source = constructorFn.toString()
  const thisProps = {}
  // TODO: nested {} blocks and non-block multiline statements not supported
  const re = /this\.(\w+)\s*=\s*([^;\n{]*(?:\{[^}]*})?)/g  // https://regex101.com/r/aJzgjx/1
  let match
  while(match = re.exec(source)) {
    thisProps[match[1]] = match[2]
  }
  return thisProps
}

var obj = simpleThisInspector(Car)

function simpleThisInspector(constructorFn) {
  const source = constructorFn.toString()
  const thisProps = {}
  // TODO: nested {} blocks and non-block multiline statements not supported
  const re = /this\.(\w+)\s*=\s*([^;\n{]*(?:\{[^}]*})?)/g  // https://regex101.com/r/aJzgjx/1
  let match
  while(match = re.exec(source)) {
    thisProps[match[1]] = match[2]
  }
  return thisProps
}

function Car(desc) {
  this.desc = desc;
  this.color = "red";
  this.getInfo = function getInfo() {
    return 'A ' + this.color + ' ' + this.desc + '.';
  };
}

var obj = simpleThisInspector(Car)

for (var prop in obj) {
  console.log(`obj.${prop} = ${obj[prop]}`);
}


问:
My function isn't returning a value
My program is supposed to calculate the price of items (customers get a discount off regular price of the item if they purchase 10 or more of the item). It's all working well except for the int Product::fulfillOrder(int orderq) function. It says a value must be returned, but the orderq should be returning a value for the function to use (I believe I did it right). Here's the code for the problem function:

```<code>int Product::fulfillOrder(int orderq)
{
    if (orderq < 0)
    {
        cout << "Error" << endl;
        orderq = 0;
        cout << "Shipped: " << orderq << endl;
    }

    else if (orderq <= Quantity)
    {
        orderq = Quantity;
        Quantity -= orderq;
        cout << "Shipped: " << orderq << endl;
    }
    else
    {
        orderq = Quantity;
        orderq = 0;
        cout << "Shipped: " << orderq << endl;
    }
}
</code>```

答:
I think you need to add

return orderq;

at the end of the function.

Title: My function isn't returning a value

Body:
My program is supposed to calculate the price of items (customers get a discount off regular price of the item if they purchase 10 or more of the item). It's all working well except for the int Product::fulfillOrder(int orderq) function. It says a value must be returned, but the orderq should be returning a value for the function to use (I believe I did it right). Here's the code for the problem function:

int Product::fulfillOrder(int orderq)
{
    if (orderq < 0)
    {
        cout << "Error" << endl;
        orderq = 0;
        cout << "Shipped: " << orderq << endl;
    }

    else if (orderq <= Quantity)
    {
        orderq = Quantity;
        Quantity -= orderq;
        cout << "Shipped: " << orderq << endl;
    }
    else
    {
        orderq = Quantity;
        orderq = 0;
        cout << "Shipped: " << orderq << endl;
    }
}


问:
pathInfo() acting weird when receiving blob appended to FormData
I am a bit confused, is this an expected behaviour?

Javascript - Sample 01

```<code>    function convertCanvasToImage() {
                    var temp_ctx, temp_canvas;
                    temp_canvas = document.createElement('canvas');
                    temp_ctx = temp_canvas.getContext('2d');
                    temp_canvas.width = windowWidth;
                    temp_canvas.height = windowWidth;
                    temp_ctx.drawImage(ctx.canvas, cutoutWidth, cutoutWidth, windowWidth, windowWidth, 0, 0, windowWidth, windowWidth);

                    var multiPart = new FormData();
                    temp_canvas.toBlob(function (blob) {

                        //Tilføjer blob til form objektet
                        multiPart.append('pernille', blob, ".jpg");

                        //Ajax kaldet
                        var http = new XMLHttpRequest();
                        var url = "ajax.php";
                        http.open("POST", url, true);
                        http.onreadystatechange = function () {
                            if (http.readyState === 4 && http.status === 200) {
                                alert(this.responseText);
                                console.log(this.responseText);
                            }
                        };
                        http.send(multiPart);
                    }, "image/jpeg");
                }
</code>```

Javascript - Sample 02

```<code>        function convertCanvasToImage() {
            var temp_ctx, temp_canvas;
            temp_canvas = document.createElement('canvas');
            temp_ctx = temp_canvas.getContext('2d');
            temp_canvas.width = windowWidth;
            temp_canvas.height = windowWidth;
            temp_ctx.drawImage(ctx.canvas, cutoutWidth, cutoutWidth, windowWidth, windowWidth, 0, 0, windowWidth, windowWidth);

            var multiPart = new FormData();
            temp_canvas.toBlob(function (blob) {

                //Tilføjer blob til form objektet
                multiPart.append('pernille', blob, "pernille");

                //Ajax kaldet
                var http = new XMLHttpRequest();
                var url = "ajax.php";
                http.open("POST", url, true);
                http.onreadystatechange = function () {
                    if (http.readyState === 4 && http.status === 200) {
                        alert(this.responseText);
                        console.log(this.responseText);
                    }
                };
                http.send(multiPart);
            }, "image/jpeg");
        }
</code>```

Ajax

```<code>    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $file = current($_FILES);
            $nameparts = pathinfo($file['name']);

            echo "```";
            echo '$_POST';
            print_r($_POST);
            echo '$_FILES';
            print_r($file);
            echo 'pathinfo';
            print_r($nameparts);
            echo "```";
    }
</code>```

The difference of the two javascript functions are these two lines

Func 01

```<code>    multiPart.append('pernille', blob, ".jpeg");
</code>```

Func 02

```<code>    multiPart.append('pernille', blob, "pernille");
</code>```

Javascript sample 01 will output this from the AJAX call
There is no filename?

```<code>    ```$_POSTArray
    (
    )
    $_FILESArray
    (
        [name] => .jpg
        [type] => image/jpeg
        [tmp_name] => /home/xch07.wi2/tmp/phpZ6zxv2
        [error] => 0
        [size] => 17713
    )
    pathinfoArray
    (
        [dirname] => .
        [basename] => .jpg
        [extension] => jpg
        [filename] =>
    )
    ```
</code>```

Javascript sample 02 will output this from the AJAX call There is a filename but no extension?

```<code>```$_POSTArray
(
)
$_FILESArray
(
    [name] => pernille
    [type] => image/jpeg
    [tmp_name] => /home/xch07.wi2/tmp/phpaKQwU4
    [error] => 0
    [size] => 17601
)
pathinfoArray
(
    [dirname] => .
    [basename] => pernille
    [filename] => pernille
)
```
</code>```

答:
It is not acting weird, rather, you are using FormData.append() method incorrectly.

Correct form should be :

```<code>multiPart.append('pernille',   blob,   'pernille.jpeg');
                     ^           ^            ^
                 field-name  data-value   file-name
</code>```

You need to append the file extension with the filename itself.

Refer here to learn more.

Body:
I am a bit confused, is this an expected behaviour?

Javascript - Sample 01

    function convertCanvasToImage() {
                    var temp_ctx, temp_canvas;
                    temp_canvas = document.createElement('canvas');
                    temp_ctx = temp_canvas.getContext('2d');
                    temp_canvas.width = windowWidth;
                    temp_canvas.height = windowWidth;
                    temp_ctx.drawImage(ctx.canvas, cutoutWidth, cutoutWidth, windowWidth, windowWidth, 0, 0, windowWidth, windowWidth);

                    var multiPart = new FormData();
                    temp_canvas.toBlob(function (blob) {

                        //Tilføjer blob til form objektet
                        multiPart.append('pernille', blob, ".jpg");

                        //Ajax kaldet
                        var http = new XMLHttpRequest();
                        var url = "ajax.php";
                        http.open("POST", url, true);
                        http.onreadystatechange = function () {
                            if (http.readyState === 4 && http.status === 200) {
                                alert(this.responseText);
                                console.log(this.responseText);
                            }
                        };
                        http.send(multiPart);
                    }, "image/jpeg");
                }

Javascript - Sample 02

        function convertCanvasToImage() {
            var temp_ctx, temp_canvas;
            temp_canvas = document.createElement('canvas');
            temp_ctx = temp_canvas.getContext('2d');
            temp_canvas.width = windowWidth;
            temp_canvas.height = windowWidth;
            temp_ctx.drawImage(ctx.canvas, cutoutWidth, cutoutWidth, windowWidth, windowWidth, 0, 0, windowWidth, windowWidth);

            var multiPart = new FormData();
            temp_canvas.toBlob(function (blob) {

                //Tilføjer blob til form objektet
                multiPart.append('pernille', blob, "pernille");

                //Ajax kaldet
                var http = new XMLHttpRequest();
                var url = "ajax.php";
                http.open("POST", url, true);
                http.onreadystatechange = function () {
                    if (http.readyState === 4 && http.status === 200) {
                        alert(this.responseText);
                        console.log(this.responseText);
                    }
                };
                http.send(multiPart);
            }, "image/jpeg");
        }

Ajax

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $file = current($_FILES);
            $nameparts = pathinfo($file['name']);

            echo "
";
            echo '$_POST';
            print_r($_POST);
            echo '$_FILES';
            print_r($file);
            echo 'pathinfo';
            print_r($nameparts);
            echo "
";
    }

The difference of the two javascript functions are these two lines

Func 01

    multiPart.append('pernille', blob, ".jpeg");

Func 02

    multiPart.append('pernille', blob, "pernille");

Javascript sample 01 will output this from the AJAX call
There is no filename?

$_POSTArray
    (
    )
    $_FILESArray
    (
        [name] => .jpg
        [type] => image/jpeg
        [tmp_name] => /home/xch07.wi2/tmp/phpZ6zxv2
        [error] => 0
        [size] => 17713
    )
    pathinfoArray
    (
        [dirname] => .
        [basename] => .jpg
        [extension] => jpg
        [filename] =>
    )

Javascript sample 02 will output this from the AJAX call There is a filename but no extension?

$_POSTArray
(
)
$_FILESArray
(
    [name] => pernille
    [type] => image/jpeg
    [tmp_name] => /home/xch07.wi2/tmp/phpaKQwU4
    [error] => 0
    [size] => 17601
)
pathinfoArray
(
    [dirname] => .
    [basename] => pernille
    [filename] => pernille
)

Body:
It is not acting weird, rather, you are using FormData.append() method incorrectly.

Correct form should be :

multiPart.append('pernille',   blob,   'pernille.jpeg');
                     ^           ^            ^
                 field-name  data-value   file-name

You need to append the file extension with the filename itself.

Refer here to learn more.


问:
Compile-time and runtime casting c#
I was wondering why some casts in C# are checked at compile-time whereas in other cases the responsibility is dumped on CLR. Like above both are incorrect but handled in a different way.

```<code>class Base { }
class Derived : Base { }
class Other { }

static void Main(string[] args)
{
    Derived d = (Derived)new Base();     //Runtime       InvalidCastException
    Derived d = (Derived)new Other();    //Compile-time  Cannot convert type...
}
</code>```

While reading "C# in depth" I've found the information on this topic where autor says:

  "If the compiler spots that it’s actually impossible for that cast to work, it’ll trigger a compilation error—and if it’s theoretically allowed but actually incorrect at execution time, the CLR will throw an exception."

Does 'theoretically' mean connected by inheritance hierarchy (some another affinity between objects ?) or it is compiler's internal business?

答:
Upcasts can be checked at compile time - the type system guarantees that the cast succeeds.

Downcasts cannot (in general) be checked at compile time, so they are always checked at runtime.

Unrelated types cannot be cast to each other.

The compiler considers only the static types. The runtime checks the dynamic (runtime) type.
Looking at your examples:

```<code>Other x = new Other();
Derived d = (Derived)x;
</code>```

The static type of x is Other. This is unrelated to Derived so the cast fails at compile time.

```<code>Base x = new Base();
Derived d = (Derived)x;
</code>```

The static type of x is now Base. Something of type Base might have dynamic type Derived, so this is a downcast. In general the compiler can't know from the static type of x if it the runtime type is Base, Derived, of some other subclass of Base. So the decision of whether the cast is allowed is left to the runtime.

ContentLicense: CC BY-SA 2.5

Title: Compile-time and runtime casting c#

Body:
I was wondering why some casts in C# are checked at compile-time whereas in other cases the responsibility is dumped on CLR. Like above both are incorrect but handled in a different way.

class Base { }
class Derived : Base { }
class Other { }

static void Main(string[] args)
{
    Derived d = (Derived)new Base();     //Runtime       InvalidCastException
    Derived d = (Derived)new Other();    //Compile-time  Cannot convert type...
}

While reading "C# in depth" I've found the information on this topic where autor says:

  "If the compiler spots that it’s actually impossible for that cast to work, it’ll trigger a compilation error—and if it’s theoretically allowed but actually incorrect at execution time, the CLR will throw an exception."

Does 'theoretically' mean connected by inheritance hierarchy (some another affinity between objects ?) or it is compiler's internal business?

Body:
Upcasts can be checked at compile time - the type system guarantees that the cast succeeds.

Downcasts cannot (in general) be checked at compile time, so they are always checked at runtime.

Unrelated types cannot be cast to each other.

The compiler considers only the static types. The runtime checks the dynamic (runtime) type.
Looking at your examples:

Other x = new Other();
Derived d = (Derived)x;

The static type of x is Other. This is unrelated to Derived so the cast fails at compile time.

Base x = new Base();
Derived d = (Derived)x;

The static type of x is now Base. Something of type Base might have dynamic type Derived, so this is a downcast. In general the compiler can't know from the static type of x if it the runtime type is Base, Derived, of some other subclass of Base. So the decision of whether the cast is allowed is left to the runtime.


问:
Error while installing lxml through pip: Microsoft Visual C++ 14.0 is required
I am on a windows 10 machine and recently moved from python 2.7 to 3.5. When trying to install lxml through pip, it stops and throws this error message-

building 'lxml.etree' extension

  error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

I have a working copy of VS 2015 installed. When I try to install the visual cpp tools through that link, it says that Microsoft Visual Studio 2015 is already installed on the machine. I also tried installing visual studio c++ 2015 redistributables, both 64 and 32 bit versions, but both of them say that there's another version of the product already installed.

typing set in the command prompt includes this -

VS140COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\

Which means that the path is set.

This is probably the only resource I could find on SO, but the answer suggests rolling back to Python 3.4.3 from 3.5. Has anybody resolved problems of this kind?

Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)

EDIT: I managed to install it using the precompiled binary (Thanks Paul), but I would still like to know what's causing this.

答:
First:

```<code>pip install wheel
</code>```

Second： go to http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml
and download proper wheel.

pip install the file you downloaded (.whl).

Body:
First:

pip install wheel

Second： go to http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml
and download proper wheel.

pip install the file you downloaded (.whl).


问:
How to automatically resize the vagrant disk image size for linux guests?
There are numerous steps online for manually increasing the vagrant disk size, for example: link

It would be great if the resize could be done automatically in the Vagrantfile, something like this:

```<code>  config.vm.provider :virtualbox do |vb|
    if first_up      # only run on the first 'up' command
      disk_uuid = ?  # how to get the disk_uuid?
      vb.customize ["modifyhd", disk_uuid, "--resize", "15360"]
      config.vm.provision "shell", path: "resize2fs -p -F /dev/sda"
    end
  end
</code>```

Question: How can I find out the disk uuid in a cross platform way?

Question: Is this all that is required to resize the guest's disk?

答:
There is a vagrant-disksize plugin.

You can install it by executing:

vagrant plugin install vagrant-disksize

Then you can include it in the Vagrantfile like this:

Vagrant.configure('2') do |config|
  config.vm.box = 'ubuntu/xenial64'
  config.disksize.size = '50GB'
end
```

Its limited at the moment only to the first disk.

Body:
There are numerous steps online for manually increasing the vagrant disk size, for example: link

It would be great if the resize could be done automatically in the Vagrantfile, something like this:

  config.vm.provider :virtualbox do |vb|
    if first_up      # only run on the first 'up' command
      disk_uuid = ?  # how to get the disk_uuid?
      vb.customize ["modifyhd", disk_uuid, "--resize", "15360"]
      config.vm.provision "shell", path: "resize2fs -p -F /dev/sda"
    end
  end

Question: How can I find out the disk uuid in a cross platform way?

Question: Is this all that is required to resize the guest's disk?

Body:
There is a vagrant-disksize plugin.

You can install it by executing:

vagrant plugin install vagrant-disksize

Then you can include it in the Vagrantfile like this:

Vagrant.configure('2') do |config|
  config.vm.box = 'ubuntu/xenial64'
  config.disksize.size = '50GB'
end

Its limited at the moment only to the first disk.


问:
Monitor ESXI from pandora fms
I'm looking for a tool to monitor my servers, Pandora FMS (free version) seems to be good for my needs, but I want to be sure about something;
- is it possible to monitor Esxi virtual machines from the free version or not ? </p>

答: Yes, you can use local or remote monitoring to gather data from your virtual machine in a OS level</p>

Title: Monitor ESXI from pandora fms


问:
Why .remove() doesn't remove the element?
Here is my code:

```<code>$(document).ready(function(){
  $('a').bind('mouseenter', function() {
    var self = $(this);
    this.iid = setTimeout(function() {
      var tag_name = self.text(),
          top      = self.position().top + self.outerHeight(true),
          left     = self.position().left;
      $('body').append("<div class='tag_info'>Some explanations about "+tag_name+"</div>");
      $(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
    }, 525);
  }).bind('mouseleave', function(){
    if(this.iid){
      clearTimeout(this.iid)
      remove($('.tag_info'));
    }
  });
});
</code>```

As you see in the fiddle I've provided, when your mouse leaves the tag, that black box still exists. Why? And how can I remove it?

答:
Use the below code instead.</p>

```<code>$('.tag_info').remove();
</code>```

Body:
Here is my code:

$(document).ready(function(){
  $('a').bind('mouseenter', function() {
    var self = $(this);
    this.iid = setTimeout(function() {
      var tag_name = self.text(),
          top      = self.position().top + self.outerHeight(true),
          left     = self.position().left;
      $('body').append("
Some explanations about "+tag_name+"
");
      $(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
    }, 525);
  }).bind('mouseleave', function(){
    if(this.iid){
      clearTimeout(this.iid)
      remove($('.tag_info'));
    }
  });
});

As you see in the fiddle I've provided, when your mouse leaves the tag, that black box still exists. Why? And how can I remove it?

Body:
Use the below code instead.

$('.tag_info').remove();


问:
Bind ViewModel to CustomControl
My Main window has a sidebar menu. When an item on the menu is clicked, I will render that item's page (UserControl) on a ContentControl. Here is what it looks like.

My MainViewModel

```<code>public MainViewModel()
{
    SystemMenu = new List<SystemMenuViewModel>();
    SystemMenu.Add(new SystemMenuViewModel("Dashboard", new Dashboard()));
    SystemMenu.Add(new SystemMenuViewModel("Appointments", new Dashboard()));
    SystemMenu.Add(new SystemMenuViewModel("Reports", new Reports()));
    SystemMenu.Add(new SystemMenuViewModel("Configuration", new Configuration()));
}

private string _windowTitle = GlobalVariables.WindowTitleDefault;
private string _currentPage = "Dashboard";

public string WindowTitle
{
    get { return _windowTitle; }
    set
    {
    _windowTitle = value;
    NotifyOfPropertyChange(() => WindowTitle);
    }
}

public string CurrentPage
{
    get { return _currentPage; }
    set
    {
    _currentPage = value;
    NotifyOfPropertyChange(() => CurrentPage);
    }
}

public List<SystemMenuViewModel> SystemMenu { get; set; }
</code>```

My SystemMenuViewModel

```<code>private string _name;
private object _content;

public SystemMenuViewModel(string name, object content)
{
    _name = name;
    Content = content;
}

public string Name
{
    get { return _name; }
    set { this.MutateVerbose(ref _name, value, RaisePropertyChanged()); }
}

public object Content
{
    get { return _content; }
    set { this.MutateVerbose(ref _content, value, RaisePropertyChanged()); }
}

public event PropertyChangedEventHandler PropertyChanged;

private Action<PropertyChangedEventArgs> RaisePropertyChanged()
{
    return args => PropertyChanged?.Invoke(this, args);
}
</code>```

My MainView on the rendering part

```<code><ContentControl Content="{Binding ElementName=lstSystemMenu, Path=SelectedItem.Content}" />
</code>```

My main problem is that I am just rendering the Content on my MainView without actually invoking or binding its ViewModel.

I am sure that there is something wrong on my implementation of the MVVM framework. Kindly enlighten me on what part did I go wrong and what's the best way to implement this one.

答:
Have a look at this : https://msdn.microsoft.com/en-us/magazine/dd419663.aspx
Can't find the source zip, but the article has plenty of code samples.

What you need is to bind your ContentControl's Content property to a ViewModel/Model object, and use DataTemplates to create the correct page depending on the datacontext. The datatemplates just need to be stored in a ResourceDictionary, either the ContentControl's or some upper level control (or even the app). The DataTemplates must have a DataType set for this to work.

Also, as suggested in the comments on your question, the viewmodels shouldn't have a "content" property of type object. It looks like your "content" property is a view object or something. Can't know without you showing us more code.
The ViewModel should not reference any View object. But the View can reference ViewModel classes in the code-behind or in the XAML.

There are two ways to bind to the "current selection".
Either use the "current selected" info from the view list (SelectedItem for example), or add a property in the MainViewModel (ex: SelectedViewModel, and then bind the ContentControl to this property.

Title: Bind ViewModel to CustomControl

Body:
My Main window has a sidebar menu. When an item on the menu is clicked, I will render that item's page (UserControl) on a ContentControl. Here is what it looks like.

My MainViewModel

public MainViewModel()
{
    SystemMenu = new List<SystemMenuViewModel>();
    SystemMenu.Add(new SystemMenuViewModel("Dashboard", new Dashboard()));
    SystemMenu.Add(new SystemMenuViewModel("Appointments", new Dashboard()));
    SystemMenu.Add(new SystemMenuViewModel("Reports", new Reports()));
    SystemMenu.Add(new SystemMenuViewModel("Configuration", new Configuration()));
}

private string _windowTitle = GlobalVariables.WindowTitleDefault;
private string _currentPage = "Dashboard";

public string WindowTitle
{
    get { return _windowTitle; }
    set
    {
    _windowTitle = value;
    NotifyOfPropertyChange(() => WindowTitle);
    }
}

public string CurrentPage
{
    get { return _currentPage; }
    set
    {
    _currentPage = value;
    NotifyOfPropertyChange(() => CurrentPage);
    }
}

public List<SystemMenuViewModel> SystemMenu { get; set; }

My SystemMenuViewModel

private string _name;
private object _content;

public SystemMenuViewModel(string name, object content)
{
    _name = name;
    Content = content;
}

public string Name
{
    get { return _name; }
    set { this.MutateVerbose(ref _name, value, RaisePropertyChanged()); }
}

public object Content
{
    get { return _content; }
    set { this.MutateVerbose(ref _content, value, RaisePropertyChanged()); }
}

public event PropertyChangedEventHandler PropertyChanged;

private Action<PropertyChangedEventArgs> RaisePropertyChanged()
{
    return args => PropertyChanged?.Invoke(this, args);
}

My MainView on the rendering part

<ContentControl Content="{Binding ElementName=lstSystemMenu, Path=SelectedItem.Content}" />

My main problem is that I am just rendering the Content on my MainView without actually invoking or binding its ViewModel.

I am sure that there is something wrong on my implementation of the MVVM framework. Kindly enlighten me on what part did I go wrong and what's the best way to implement this one.


问:
Angular2 http.post: Create promise with subscribe
I´m trying do create a function, that returns a Promise as the code: (someprovider.ts)

```<code>postToPaymentApi(url:string, data:string, options:RequestOptions, order:Order):Promise<any>{
let result =  this.http.post(url, data, options).map(res => res.json())
  .subscribe(data => {
    // all my logic here!
    });
  }, error => {
    console.log(error)
  })

  return new Promise((resolve)=>{
    resolve(result)
  })
</code>```

}

The problem is, when I call this function, I do not get the data, because this post take a few seconds to finish and I get the promise before the post finish.

```<code>this.postToPaymentApi(url, data, options, order).then(data => {
    console.log(data);
  })
</code>```

What Am I doing wrong?

答:
if you want to create a function that return promise, your function should be :</p>

```<code>postToPaymentApi(url:string, data:string, options:RequestOptions, order:Order):Promise<any >{
   return new Promise((resolve, reject) => {
          this.http.post(url, data, options)
           .map(res => res.json())
           .subscribe(data => {
             resolve(data);
            }
           }, error => {
             console.log(error)
             reject({error: error});
           });
        });
}
</code>```

Body:
I´m trying do create a function, that returns a Promise as the code: (someprovider.ts)

postToPaymentApi(url:string, data:string, options:RequestOptions, order:Order):Promise<any>{
let result =  this.http.post(url, data, options).map(res => res.json())
  .subscribe(data => {
    // all my logic here!
    });
  }, error => {
    console.log(error)
  })

  return new Promise((resolve)=>{
    resolve(result)
  })

}

The problem is, when I call this function, I do not get the data, because this post take a few seconds to finish and I get the promise before the post finish.

this.postToPaymentApi(url, data, options, order).then(data => {
    console.log(data);
  })

What Am I doing wrong?

Body:
if you want to create a function that return promise, your function should be :

postToPaymentApi(url:string, data:string, options:RequestOptions, order:Order):Promise<any >{
   return new Promise((resolve, reject) => {
          this.http.post(url, data, options)
           .map(res => res.json())
           .subscribe(data => {
             resolve(data);
            }
           }, error => {
             console.log(error)
             reject({error: error});
           });
        });
}


问:
What problems could disabling Java bytecode verification cause?
This answer says that verification is used to ensure that Java bytecode "follows Java language rules for safety".

If this verification were not performed, unsafe bytecode would be allowed to run. What problems could this cause?

Are there any situations in which disabling bytecode verification would be acceptable?

答: It is highly recommended not to use "-Xverify:none" options  in production environment as it disables byte code verification and lead to random crashes. Please check detailed blog here</p>


问:
Difference in abstract class implementation in c# and php
I've been working with PHP for a while now I am trying to explore the world of c#.I was trying to understand the abstract class implementation in c sharp.I've found some fluctuation in behavior in both languages.That's why I am posting it here so that I can get a better insight of abstract class implementation in C#.

Both PHP and C# extends abstract class.That means all the class that extends from abstract class must implement the abstract methods as well as inherit non-abstract public methods from abstract class.

The problem arises while accessing the property of child class from a method of the abstract class. In PHP getHairColor() can access the public hair property. But in C# getHairColor() can't access the public hair property of the class that extends from abstract class.

I think as the Male class extends Person class, it also inherits the getHairColor() method from the parent class.So, it should be able to access the hair property. Here PHP implementation makes more sense than C#. Can I get a proper explanation for different behavior for a similar concept in two different languages?

PHP:

```<code>abstract class Person{
    abstract public function setHairColor($color);

    public function getHairColor(){
        return $this->hair;  // $this->hair is accessible from here
    }
}

class Male extends Person{
    public $hair;

    public function setHairColor($color){
        $this->hair = $color;
    }

}

$male1 = new Male();
$male1->setHairColor("black");
echo $male1->getHairColor(); // access hair property
</code>```

C#:

```<code>abstract class Person
{
    public abstract void setHairColor(string hair);

    public string getHairColor()
    {
        return this.hair; // this.hair is not accessible from here
    }

}

class Male : Person
{
    public string hair;

    public override void setHairColor(string hair)
    {
        this.hair = hair;
    }
}

Male male1 = new Male();
male1.setHairColor("black");
Console.WriteLine(male1.getHairColor()); // can not access hair property
</code>```

答:
C# has static typing. That's why you can't access a field or property that is declared in a subclass. You have to declare Hair as an abstract property in Person and implement it in the subclass:

```<code>    abstract class Person
    {
        public abstract void SetHairColor(string hair);

        public abstract string Hair { get; }

        public string getHairColor()
        {
            return this.Hair; // now it is accessible
        }

    }

    class Male : Person
    {
        private string _Hair;
        public override string Hair { get { return _Hair; } }

        public override void SetHairColor(string hair)
        {
            this._Hair = hair;
        }
    }
</code>```

You can also implement SetHairColor as setter of the property Hair:

```<code>    abstract class Person
    {
        public abstract string Hair { get; set; }

        public string getHairColor()
        {
            return this.Hair; // now it is accessible
        }

    }

    class Male : Person
    {
        private string _Hair;
        public override string Hair
        {
            get { return _Hair; }
            set { _Hair = value }
        }
    }
</code>```

Body:
I've been working with PHP for a while now I am trying to explore the world of c#.I was trying to understand the abstract class implementation in c sharp.I've found some fluctuation in behavior in both languages.That's why I am posting it here so that I can get a better insight of abstract class implementation in C#.

Both PHP and C# extends abstract class.That means all the class that extends from abstract class must implement the abstract methods as well as inherit non-abstract public methods from abstract class.

The problem arises while accessing the property of child class from a method of the abstract class. In PHP getHairColor() can access the public hair property. But in C# getHairColor() can't access the public hair property of the class that extends from abstract class.

I think as the Male class extends Person class, it also inherits the getHairColor() method from the parent class.So, it should be able to access the hair property. Here PHP implementation makes more sense than C#. Can I get a proper explanation for different behavior for a similar concept in two different languages?

PHP:

abstract class Person{
    abstract public function setHairColor($color);

    public function getHairColor(){
        return $this->hair;  // $this->hair is accessible from here
    }
}

class Male extends Person{
    public $hair;

    public function setHairColor($color){
        $this->hair = $color;
    }

}

$male1 = new Male();
$male1->setHairColor("black");
echo $male1->getHairColor(); // access hair property

C#:

abstract class Person
{
    public abstract void setHairColor(string hair);

    public string getHairColor()
    {
        return this.hair; // this.hair is not accessible from here
    }

}

class Male : Person
{
    public string hair;

    public override void setHairColor(string hair)
    {
        this.hair = hair;
    }
}

Male male1 = new Male();
male1.setHairColor("black");
Console.WriteLine(male1.getHairColor()); // can not access hair property

Body:
C# has static typing. That's why you can't access a field or property that is declared in a subclass. You have to declare Hair as an abstract property in Person and implement it in the subclass:

    abstract class Person
    {
        public abstract void SetHairColor(string hair);

        public abstract string Hair { get; }

        public string getHairColor()
        {
            return this.Hair; // now it is accessible
        }

    }

    class Male : Person
    {
        private string _Hair;
        public override string Hair { get { return _Hair; } }

        public override void SetHairColor(string hair)
        {
            this._Hair = hair;
        }
    }

You can also implement SetHairColor as setter of the property Hair:

    abstract class Person
    {
        public abstract string Hair { get; set; }

        public string getHairColor()
        {
            return this.Hair; // now it is accessible
        }

    }

    class Male : Person
    {
        private string _Hair;
        public override string Hair
        {
            get { return _Hair; }
            set { _Hair = value }
        }
    }


问:
django no matching url with parameters
When the login process is complete, I am trying to redirect the user to their profile page, I am passing the user id to the url, although I get the below error.

Reverse for 'index' with arguments '(2,)' not found. 1 pattern(s) tried: [u'profiles/profile/(?P/d+)/$']

login redirect

```<code>return redirect('profiles:index',user.id)
</code>```

url expression

```<code> url(r'^profile/(?P<user_id>/d+)/$', views.index, name='index'),
</code>```

login view

```<code>def Login(request):
    form = LoginForm()
    regForm = SignUpForm()

    if request.method == 'POST':
        user = authenticate(username=request.POST['login_username'], password=request.POST['login_password'])

        if user is not None:
            login(request, user)
            if 'next' in request.POST:
                return redirect(request.POST['next'])
            #print '----------------------'
            #print user.id
            return redirect('profiles:index',user.id)
        else:
            return render(request, 'index.html',{'error':'The username and password didnt match','form':form,'regForm':regForm})
    else:
         return render(request, 'index.html',{'form':form,'regForm':regForm})
</code>```

Main url

```<code>from django.contrib import admin

from authentication import views
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^$', views.index, name="index"),
        url(r'^authentication/', include('authentication.urls')),
        url(r'^emails/', include('emails.urls')),
        url(r'^profiles/', include('profiles.urls')),
    ]
</code>```

答:
There is a typo in your url pattern. You should use \d+ in the regex to match digits (note the backslash).

```<code>url(r'^profile/(?P<user_id>\d+)/$', views.index, name='index'),
</code>```

Title: django no matching url with parameters

Body:
When the login process is complete, I am trying to redirect the user to their profile page, I am passing the user id to the url, although I get the below error.

Reverse for 'index' with arguments '(2,)' not found. 1 pattern(s) tried: [u'profiles/profile/(?P/d+)/$']

login redirect

return redirect('profiles:index',user.id)

url expression

 url(r'^profile/(?P<user_id>/d+)/$', views.index, name='index'),

login view

def Login(request):
    form = LoginForm()
    regForm = SignUpForm()

    if request.method == 'POST':
        user = authenticate(username=request.POST['login_username'], password=request.POST['login_password'])

        if user is not None:
            login(request, user)
            if 'next' in request.POST:
                return redirect(request.POST['next'])
            #print '----------------------'
            #print user.id
            return redirect('profiles:index',user.id)
        else:
            return render(request, 'index.html',{'error':'The username and password didnt match','form':form,'regForm':regForm})
    else:
         return render(request, 'index.html',{'form':form,'regForm':regForm})

Main url

from django.contrib import admin

from authentication import views
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^$', views.index, name="index"),
        url(r'^authentication/', include('authentication.urls')),
        url(r'^emails/', include('emails.urls')),
        url(r'^profiles/', include('profiles.urls')),
    ]

Body:
There is a typo in your url pattern. You should use \d+ in the regex to match digits (note the backslash).

url(r'^profile/(?P<user_id>\d+)/$', views.index, name='index'),


问:
How many processes (including the parent) will be created assuming each fork successfully executes
I believe that this creates 5 processes; however, I need verification. These questions often stump me. Thanks for the help!               </p>

```<code>void forktest()
{
   printf("L0\n");
   if (fork() != 0)
   {
       printf("L1\n");
       if (fork() != 0)
       {
           printf("L2\n");
           fork();
       }
   }
   printf("Bye\n");
}
</code>```

答:
```<code>main
   |
   |
fork  --- (first child)
   |
   |
fork  --- (second child)
   |
   |
fork  --- (third child)
</code>```

```<code>void forktest()
{
   printf("L0\n");
   if (fork() != 0) <----- first child, only parent goes inside the if
   {
       printf("L1\n");
       if (fork() != 0) <------ second child, only parent goes inside the if
       {
           printf("L2\n");
           fork();       <------ third child
       }
   }
   printf("Bye\n");
}
</code>```

That is, 3 processes created by main.

Body:
I believe that this creates 5 processes; however, I need verification. These questions often stump me. Thanks for the help!

void forktest()
{
   printf("L0\n");
   if (fork() != 0)
   {
       printf("L1\n");
       if (fork() != 0)
       {
           printf("L2\n");
           fork();
       }
   }
   printf("Bye\n");
}

Body:
main
   |
   |
fork  --- (first child)
   |
   |
fork  --- (second child)
   |
   |
fork  --- (third child)

void forktest()
{
   printf("L0\n");
   if (fork() != 0) <----- first child, only parent goes inside the if
   {
       printf("L1\n");
       if (fork() != 0) <------ second child, only parent goes inside the if
       {
           printf("L2\n");
           fork();       <------ third child
       }
   }
   printf("Bye\n");
}

That is, 3 processes created by main.


问:
get original template before replaced by the angularjs directive
How can I get the original markup before getting replaced by angular js directives? This question has already been asked, but I am posting this as the solutions don't work for me and also I want to know if the angular js team may have introduced any new methods for this.

This is what I have tried so far:

```<code>  function $block($compile) {

    var html = '<div>new content</div>';

    return {
      restrict: 'E',
      template: function(element, attrs) {
        console.log(element); // still getting the new element
        return html;
      },
      link: function(scope, element, attrs) {
           console.log(element)
      }
    };

  }

  angular.module('directive', [])
    .directive('myDirective', $block);
</code>```

How can I get the old template and then replace it with the new one?

答:
  angular.module('directive', [])
    .directive('myDirective', function(){
      return {
      restrict: 'A',
      template: '
new content
',
      link: function(scope, element, attrs) {
      },
      compile:function(scope,element){
      console.log(element.$$element[0].outerHTML)

      }
    };
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<html>
<body ng-app="directive">
<div style="background-color:red;" my-directive>Hello</div>
</body>
</html></code>```

Body:
How can I get the original markup before getting replaced by angular js directives? This question has already been asked, but I am posting this as the solutions don't work for me and also I want to know if the angular js team may have introduced any new methods for this.

This is what I have tried so far:

  function $block($compile) {

    var html = '
new content
';

    return {
      restrict: 'E',
      template: function(element, attrs) {
        console.log(element); // still getting the new element
        return html;
      },
      link: function(scope, element, attrs) {
           console.log(element)
      }
    };

  }

  angular.module('directive', [])
    .directive('myDirective', $block);

How can I get the old template and then replace it with the new one?

Body:
  angular.module('directive', [])
    .directive('myDirective', function(){
      return {
      restrict: 'A',
      template: '<div>new content</div>',
      link: function(scope, element, attrs) {
      },
      compile:function(scope,element){
      console.log(element.$$element[0].outerHTML)

      }
    };
    });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<html>
<body ng-app="directive">
<div style="background-color:red;" my-directive>Hello</div>
</body>
</html>


问:
What are zeromq use cases?
Could you give some examples of zeromq?</p>

答:
Let's say you want to have a bulletin board of some kind. You want to allow only some people to see it, by subscribing to the bulleting board.

This can be done using the publisher/subscriber model of ZeroMQ.

Now, let's say you need to send some asynchronous messages. That is, when a message is sent from system A and needs to get to system B, it is guaranteed to be delivered later, even if systems A and B cannot communicate at the moment when that message is sent. You can imagine a use case being SMS messages.

This can be done using asynchronous messaging model of ZeroMQ.

Basically, any JMS compliant solution like ZeroMQ will allow you to reliably broadcast or send a "message", whatever that message may be, to some other party with as little hassle as possible.

Title: What are zeromq use cases?

Body: Could you give some examples of zeromq?