问:
Calculate the json's value then show in html
I have a json array:

```<code>[{"value": "1"},{"value": "2"},{"value": "3"},{"value": "4"},{"value": "5"},{"value": "6"}]
</code>```

My code is :

```<code>$.ajax({
    url: "120.58.243.11:8080/needCal/myJson.json",
    dataType: 'json',
    success: function(data) {
        var items = [];
        $.each(data, function(key, value) {
            items.push("<tr>");
            items.push("<td id=''" + key + "''>" + value.value+ < /td>");
            items.push("<td id=''" + key + "''>" + total of values + < /td>");
            items.push("</tr>");
        });
    }
});
</code>```

I want to calculate the values, how to do with that?

答:
A simple way is to use the reduce method:

Something like this:

```<code>var total = arr.reduce(function(t, v) {
    return t += Number(v.value);
}, 0);
</code>```

Body:
I have a json array:

[{"value": "1"},{"value": "2"},{"value": "3"},{"value": "4"},{"value": "5"},{"value": "6"}]

My code is :

$.ajax({
    url: "120.58.243.11:8080/needCal/myJson.json",
    dataType: 'json',
    success: function(data) {
        var items = [];
        $.each(data, function(key, value) {
            items.push("
");
            items.push("" + value.value+ 	");
            items.push("" + total of values + 	");
            items.push("
");
        });
    }
});

I want to calculate the values, how to do with that?

Body:
A simple way is to use the reduce method:

Something like this:

var total = arr.reduce(function(t, v) {
    return t += Number(v.value);
}, 0);


来源: stackexchange

问:
SQL Data Filtering approach
I have a stored procedure that receives 3 parameters that are used to dynamically filter the result set

```<code>create proc MyProc
@Parameter1 int,
@Parameter2 int,
@Paremeter3 int
as
select * from My_table
where
1 = case when @Parameter1 = 0 then 1 when @Parameter1 = Column1 then 1 else 0 end
and
1 = case when @Parameter2 = 0 then 1 when @Parameter2 = Column2 then 1 else 0 end
and
1 = case when @Parameter3 = 0 then 1 when @Parameter3 = Column3 then 1 else 0 end
return
</code>```

The values passed for each parameter can be 0 (for all items) or non-zero for items matching on specific column.

I may have upwards of 20 parameters (example shown only has 3).  Is there a more elegant approach to allow this to scale when the database gets large?

答:
I use a slightly different method to some of the ones listed above and I've not noticed any performance hit.  Instead of passing in 0 for no filter I would use null and I would force it to be the default value of the parameter.

As we give the parameters default values it makes them optional which lends itself to better readability when your calling the procedure.

```<code>create proc myProc
    @Parameter1 int = null,
    @Parameter2 int = null,
    @Paremeter3 int = null
AS
select
    *
from
    TableA
where
    column1 = coalesce(@Parameter1,column1)
    and
    column2 = coalesce(@Parameter2, column2)
    and
    column3 = coalesce(@Parameter3,column3)
</code>```

That said I may well try out the dynamic sql method next time to see if I notice any performance difference

ContentLicense: CC BY-SA 2.5

Title: SQL Data Filtering approach

Body:
I have a stored procedure that receives 3 parameters that are used to dynamically filter the result set

create proc MyProc
@Parameter1 int,
@Parameter2 int,
@Paremeter3 int
as
select * from My_table
where
1 = case when @Parameter1 = 0 then 1 when @Parameter1 = Column1 then 1 else 0 end
and
1 = case when @Parameter2 = 0 then 1 when @Parameter2 = Column2 then 1 else 0 end
and
1 = case when @Parameter3 = 0 then 1 when @Parameter3 = Column3 then 1 else 0 end
return

The values passed for each parameter can be 0 (for all items) or non-zero for items matching on specific column.

I may have upwards of 20 parameters (example shown only has 3).  Is there a more elegant approach to allow this to scale when the database gets large?

Body:
I use a slightly different method to some of the ones listed above and I've not noticed any performance hit.  Instead of passing in 0 for no filter I would use null and I would force it to be the default value of the parameter.

As we give the parameters default values it makes them optional which lends itself to better readability when your calling the procedure.

create proc myProc
    @Parameter1 int = null,
    @Parameter2 int = null,
    @Paremeter3 int = null
AS
select
    *
from
    TableA
where
    column1 = coalesce(@Parameter1,column1)
    and
    column2 = coalesce(@Parameter2, column2)
    and
    column3 = coalesce(@Parameter3,column3)

That said I may well try out the dynamic sql method next time to see if I notice any performance difference


问:
How to avoid Map of Map of Map of Map in Avro schema
There is a requirement for defining Avro Schema for Map of Map of Map of Map (4 level nested map) in my application. I am using keys at every level except the last map (final inner map). I would like to know what are the pros and cons of the schema. Is there any problem with performance?</p>

答:
Always avoid using nested maps.

AVRO file format is schema based. If you use nested map it will become difficult to design a schema. Also avro works based on serialisation technique. If you are going to work with "String" it will work fine but not with the case of other data types.

ContentLicense: CC BY-SA 3.0


问:
how to save or prevent my background service from the force stop or clear task from user
Hello friends i am creating one android app App lock application in which user can lock the application for that i am using one background service which run in background always. My service is run fine in all device but in some new device like OPPO,Redme Mi and Lenovo Mobile there is one advace feature like user can clean all the running task from the cleaner and because of this advance features when user clean all the task my service also stop and app lock will not work so user need to go in application and manual start the service is there any solution to protect my service from this.
one of app lock have this kind of solution
https://play.google.com/store/apps/details?id=com.domobile.applock
This app service is start after the clean task i also want to do same for my application i tried many solution but not getting any result i my service code is as below </p>

```<code>public class MyAppLockService extends Service {
public static int BuildV = 0;
public static final int NOTIFICATION_ID = 11259186;
private static boolean flag;
public static boolean isLauncher;
public static boolean isRunning;
public static ArrayList<String> locked_list;
public static String pack;
public static Thread th;
String currentHomePackage;
private boolean isRefreshedList;
boolean mAllowDestroy;
BroadcastReceiver mReciever;
private boolean mShowNotification;
UsageStatsManager mUsageStatsManager;
ActivityManager manager;
PowerManager pmanager;
SharedPreferences prefs;
public boolean run;
Timer f6t;
TimerTask tt;

class C02221 extends BroadcastReceiver {
    C02221() {
    }

    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(Utils.ACTION_UPDATE)) {
            MyAppLockService.this.refreshList();
        } else if (intent.getAction().equals(Utils.ACTION_STOP_SELF)) {
            MyAppLockService.this.doStopSelf();
        } else if (intent.getAction().equals(Utils.ACTION_REMOVE_APP)) {
            MyAppLockService.this.removeAppFromLockedList(intent
                    .getStringExtra("packName"));
        }
    }
}

@SuppressLint("NewApi")

class C02232 extends TimerTask {
    C02232() {
    }

    @SuppressLint("NewApi")
    public void run() {
        if (Utils.isScreenOn(MyAppLockService.this.pmanager)) {
            MyAppLockService.this.isRefreshedList = false;
            String current = "";
            try {
                current = Utils.getProcess(
                        MyAppLockService.this.mUsageStatsManager,
                        MyAppLockService.this.getApplicationContext());
            } catch (Exception e) {
                current = "";
            }
            if (current != null) {
                if (MyAppLockService.flag
                        && current
                                .equals(MyAppLockService.this.currentHomePackage)) {
                    if (MyAppLockService.this.prefs.getBoolean(
                            "immediately", true)) {
                        MyAppLockService.locked_list = new DBHelper(
                                MyAppLockService.this
                                        .getApplicationContext())
                                .getApsHasStateTrue();
                    }
                    MyAppLockService.flag = false;
                }
                if (!current
                        .equals(MyAppLockService.this.currentHomePackage)
                        && MyAppLockService.locked_list.contains(current)) {
                    Intent it;
                    if (MyAppLockService.BuildV >= 23) {
                        long endTime = System.currentTimeMillis();
                        UsageEvents usageEvents = MyAppLockService.this.mUsageStatsManager
                                .queryEvents(endTime - 10000, endTime);
                        Event event = new Event();
                        while (usageEvents.hasNextEvent()) {
                            usageEvents.getNextEvent(event);
                        }
                        if (current.equals(event.getPackageName())
                                && event.getEventType() == 1) {
                            MyAppLockService.pack = current;
                            if (MyAppLockService.this.prefs.getBoolean(
                                    "isPattern", false)) {
                                MyAppLockService.this
                                        .confirmPattern(current);
                            } else {
                                it = new Intent(
                                        MyAppLockService.this
                                                .getApplicationContext(),
                                        AppLockActivity.class);
                                it.setFlags(DriveFile.MODE_READ_ONLY);
                                MyAppLockService.this
                                        .getApplicationContext()
                                        .startActivity(it);
                            }
                            MyAppLockService.flag = true;
                            return;
                        }
                        return;
                    }
                    MyAppLockService.pack = current;
                    if (MyAppLockService.this.prefs.getBoolean("isPattern",
                            false)) {
                        MyAppLockService.this.confirmPattern(current);
                    } else {
                        it = new Intent(
                                MyAppLockService.this
                                        .getApplicationContext(),
                                AppLockActivity.class);
                        it.setFlags(DriveFile.MODE_READ_ONLY);
                        MyAppLockService.this.getApplicationContext()
                                .startActivity(it);
                    }
                    MyAppLockService.flag = true;
                }
            }
        } else if (!MyAppLockService.this.isRefreshedList) {
            MyAppLockService.this.refreshList();
        }
    }
}

public MyAppLockService() {
    this.run = true;
}

static {
    BuildV = VERSION.SDK_INT;
}

public IBinder onBind(Intent intent) {
    return null;
}

public void onCreate() {

    this.prefs = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());
    this.manager = (ActivityManager) getApplicationContext()
            .getSystemService("activity");
    this.pmanager = (PowerManager) getApplicationContext()
            .getSystemService("power");
    if (BuildV >= 21) {
        this.mUsageStatsManager = (UsageStatsManager) getApplicationContext()
                .getSystemService("usagestats");
    }
    startNotification();
    Intent intent = new Intent("android.intent.action.MAIN");
    intent.addCategory("android.intent.category.HOME");
    this.currentHomePackage = getPackageManager().resolveActivity(intent,
            Cast.MAX_MESSAGE_LENGTH).activityInfo.packageName;
    this.mReciever = new C02221();
    IntentFilter filter = new IntentFilter(Utils.ACTION_UPDATE);
    filter.addAction(Utils.ACTION_STOP_SELF);
    filter.addAction(Utils.ACTION_REMOVE_APP);
    registerReceiver(this.mReciever, filter);
    refreshList();
    this.tt = new C02232();
    this.f6t = new Timer();
    this.f6t.schedule(this.tt, 500, 500);
    super.onCreate();
    Calendar cal = Calendar.getInstance();
    Intent intent12 = new Intent(getBaseContext(),MyAppLockService.class);
    PendingIntent pintent = PendingIntent.getService(getBaseContext(), 0, intent12, 0);
    AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),5, pintent);
}

public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, START_STICKY_COMPATIBILITY, startId);

}

public void onDestroy() {
    try {
        this.f6t.cancel();
        this.tt.cancel();
    } catch (Exception e) {
        e.printStackTrace();
    }

        Intent intent1 = new Intent("com.android.techtrainner");
        intent1.putExtra("yourvalue", "torestore");
        sendBroadcast(intent1);

}

public void refreshList() {
    locked_list = new DBHelper(getApplicationContext())
            .getApsHasStateTrue();
    if (locked_list.size() == 0) {
        doStopSelf();
    }
    this.isRefreshedList = true;
}

@SuppressLint({ "InlinedApi" })
private void startForegroundWithNotification() {
    PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this,
            Calculator_Activity.class), 0);
    String title = getString(R.string.app_name);
    String content = getString(R.string.app_name);
    Builder nb = new Builder(this);
    nb.setSmallIcon(R.drawable.ic_transparent);
    nb.setContentTitle(title);
    nb.setContentText(content);
    nb.setWhen(System.currentTimeMillis());
    nb.setContentIntent(pi);
    nb.setOngoing(true);
    nb.setPriority(0);
    startForeground(NOTIFICATION_ID, nb.build());
}

private void startNotification() {
    startForegroundWithNotification();
    if (!this.mShowNotification) {
        HelperService.removeNotification(this);
    }
}

private void doStopSelf() {
    this.mAllowDestroy = true;
    unregisterReceiver(this.mReciever);
    stopForeground(true);
    stopSelf();
}

private void confirmPattern(String st) {

    Intent pIntent = new Intent(getApplicationContext(),
            ResetActivity.class);
    pIntent.putExtra("isFromReset", true);
    PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),
            12345, pIntent, DriveFile.MODE_READ_ONLY);

    Intent intent = new Intent(LockPatternActivity.ACTION_COMPARE_PATTERN, null,
            getApplicationContext(), LockPatternActivity.class);
    intent.putExtra("packName", st);
    intent.putExtra("isStealthMode", this.prefs.getBoolean(
            AlpSettings.Display.METADATA_STEALTH_MODE, false));
    intent.putExtra("isFromLock", true);
    intent.setFlags(DriveFile.MODE_READ_ONLY);
    intent.addFlags(Cast.MAX_MESSAGE_LENGTH);

    intent.putExtra(LockPatternActivity.EXTRA_PENDING_INTENT_FORGOT_PATTERN, pi);

    startActivity(intent);

}

private void removeAppFromLockedList(String packName) {
    locked_list.remove(packName);
}
</code>```

<p>if there is any solution for it then please help me out thanks in advance </p>

答:
set a variable in service class  to check service is running or not.

let boolRuningService is a variable

Intent intent = new Intent(DashboardScreen.this, ServiceClass.class);
     PendingIntent pintent = PendingIntent.getService(DashboardScreen.this, 0, intent, 0);

```<code>                    if(!ServiceClass.boolRuningService){
                           AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
                        alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
                    }
</code>```

Body:
Hello friends i am creating one android app App lock application in which user can lock the application for that i am using one background service which run in background always. My service is run fine in all device but in some new device like OPPO,Redme Mi and Lenovo Mobile there is one advace feature like user can clean all the running task from the cleaner and because of this advance features when user clean all the task my service also stop and app lock will not work so user need to go in application and manual start the service is there any solution to protect my service from this.
one of app lock have this kind of solution
https://play.google.com/store/apps/details?id=com.domobile.applock
This app service is start after the clean task i also want to do same for my application i tried many solution but not getting any result i my service code is as below

public class MyAppLockService extends Service {
public static int BuildV = 0;
public static final int NOTIFICATION_ID = 11259186;
private static boolean flag;
public static boolean isLauncher;
public static boolean isRunning;
public static ArrayList<String> locked_list;
public static String pack;
public static Thread th;
String currentHomePackage;
private boolean isRefreshedList;
boolean mAllowDestroy;
BroadcastReceiver mReciever;
private boolean mShowNotification;
UsageStatsManager mUsageStatsManager;
ActivityManager manager;
PowerManager pmanager;
SharedPreferences prefs;
public boolean run;
Timer f6t;
TimerTask tt;

class C02221 extends BroadcastReceiver {
    C02221() {
    }

    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(Utils.ACTION_UPDATE)) {
            MyAppLockService.this.refreshList();
        } else if (intent.getAction().equals(Utils.ACTION_STOP_SELF)) {
            MyAppLockService.this.doStopSelf();
        } else if (intent.getAction().equals(Utils.ACTION_REMOVE_APP)) {
            MyAppLockService.this.removeAppFromLockedList(intent
                    .getStringExtra("packName"));
        }
    }
}

@SuppressLint("NewApi")

class C02232 extends TimerTask {
    C02232() {
    }

    @SuppressLint("NewApi")
    public void run() {
        if (Utils.isScreenOn(MyAppLockService.this.pmanager)) {
            MyAppLockService.this.isRefreshedList = false;
            String current = "";
            try {
                current = Utils.getProcess(
                        MyAppLockService.this.mUsageStatsManager,
                        MyAppLockService.this.getApplicationContext());
            } catch (Exception e) {
                current = "";
            }
            if (current != null) {
                if (MyAppLockService.flag
                        && current
                                .equals(MyAppLockService.this.currentHomePackage)) {
                    if (MyAppLockService.this.prefs.getBoolean(
                            "immediately", true)) {
                        MyAppLockService.locked_list = new DBHelper(
                                MyAppLockService.this
                                        .getApplicationContext())
                                .getApsHasStateTrue();
                    }
                    MyAppLockService.flag = false;
                }
                if (!current
                        .equals(MyAppLockService.this.currentHomePackage)
                        && MyAppLockService.locked_list.contains(current)) {
                    Intent it;
                    if (MyAppLockService.BuildV >= 23) {
                        long endTime = System.currentTimeMillis();
                        UsageEvents usageEvents = MyAppLockService.this.mUsageStatsManager
                                .queryEvents(endTime - 10000, endTime);
                        Event event = new Event();
                        while (usageEvents.hasNextEvent()) {
                            usageEvents.getNextEvent(event);
                        }
                        if (current.equals(event.getPackageName())
                                && event.getEventType() == 1) {
                            MyAppLockService.pack = current;
                            if (MyAppLockService.this.prefs.getBoolean(
                                    "isPattern", false)) {
                                MyAppLockService.this
                                        .confirmPattern(current);
                            } else {
                                it = new Intent(
                                        MyAppLockService.this
                                                .getApplicationContext(),
                                        AppLockActivity.class);
                                it.setFlags(DriveFile.MODE_READ_ONLY);
                                MyAppLockService.this
                                        .getApplicationContext()
                                        .startActivity(it);
                            }
                            MyAppLockService.flag = true;
                            return;
                        }
                        return;
                    }
                    MyAppLockService.pack = current;
                    if (MyAppLockService.this.prefs.getBoolean("isPattern",
                            false)) {
                        MyAppLockService.this.confirmPattern(current);
                    } else {
                        it = new Intent(
                                MyAppLockService.this
                                        .getApplicationContext(),
                                AppLockActivity.class);
                        it.setFlags(DriveFile.MODE_READ_ONLY);
                        MyAppLockService.this.getApplicationContext()
                                .startActivity(it);
                    }
                    MyAppLockService.flag = true;
                }
            }
        } else if (!MyAppLockService.this.isRefreshedList) {
            MyAppLockService.this.refreshList();
        }
    }
}

public MyAppLockService() {
    this.run = true;
}

static {
    BuildV = VERSION.SDK_INT;
}

public IBinder onBind(Intent intent) {
    return null;
}

public void onCreate() {

    this.prefs = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());
    this.manager = (ActivityManager) getApplicationContext()
            .getSystemService("activity");
    this.pmanager = (PowerManager) getApplicationContext()
            .getSystemService("power");
    if (BuildV >= 21) {
        this.mUsageStatsManager = (UsageStatsManager) getApplicationContext()
                .getSystemService("usagestats");
    }
    startNotification();
    Intent intent = new Intent("android.intent.action.MAIN");
    intent.addCategory("android.intent.category.HOME");
    this.currentHomePackage = getPackageManager().resolveActivity(intent,
            Cast.MAX_MESSAGE_LENGTH).activityInfo.packageName;
    this.mReciever = new C02221();
    IntentFilter filter = new IntentFilter(Utils.ACTION_UPDATE);
    filter.addAction(Utils.ACTION_STOP_SELF);
    filter.addAction(Utils.ACTION_REMOVE_APP);
    registerReceiver(this.mReciever, filter);
    refreshList();
    this.tt = new C02232();
    this.f6t = new Timer();
    this.f6t.schedule(this.tt, 500, 500);
    super.onCreate();
    Calendar cal = Calendar.getInstance();
    Intent intent12 = new Intent(getBaseContext(),MyAppLockService.class);
    PendingIntent pintent = PendingIntent.getService(getBaseContext(), 0, intent12, 0);
    AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),5, pintent);
}

public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, START_STICKY_COMPATIBILITY, startId);

}

public void onDestroy() {
    try {
        this.f6t.cancel();
        this.tt.cancel();
    } catch (Exception e) {
        e.printStackTrace();
    }

        Intent intent1 = new Intent("com.android.techtrainner");
        intent1.putExtra("yourvalue", "torestore");
        sendBroadcast(intent1);

}

public void refreshList() {
    locked_list = new DBHelper(getApplicationContext())
            .getApsHasStateTrue();
    if (locked_list.size() == 0) {
        doStopSelf();
    }
    this.isRefreshedList = true;
}

@SuppressLint({ "InlinedApi" })
private void startForegroundWithNotification() {
    PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this,
            Calculator_Activity.class), 0);
    String title = getString(R.string.app_name);
    String content = getString(R.string.app_name);
    Builder nb = new Builder(this);
    nb.setSmallIcon(R.drawable.ic_transparent);
    nb.setContentTitle(title);
    nb.setContentText(content);
    nb.setWhen(System.currentTimeMillis());
    nb.setContentIntent(pi);
    nb.setOngoing(true);
    nb.setPriority(0);
    startForeground(NOTIFICATION_ID, nb.build());
}

private void startNotification() {
    startForegroundWithNotification();
    if (!this.mShowNotification) {
        HelperService.removeNotification(this);
    }
}

private void doStopSelf() {
    this.mAllowDestroy = true;
    unregisterReceiver(this.mReciever);
    stopForeground(true);
    stopSelf();
}

private void confirmPattern(String st) {

    Intent pIntent = new Intent(getApplicationContext(),
            ResetActivity.class);
    pIntent.putExtra("isFromReset", true);
    PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),
            12345, pIntent, DriveFile.MODE_READ_ONLY);

    Intent intent = new Intent(LockPatternActivity.ACTION_COMPARE_PATTERN, null,
            getApplicationContext(), LockPatternActivity.class);
    intent.putExtra("packName", st);
    intent.putExtra("isStealthMode", this.prefs.getBoolean(
            AlpSettings.Display.METADATA_STEALTH_MODE, false));
    intent.putExtra("isFromLock", true);
    intent.setFlags(DriveFile.MODE_READ_ONLY);
    intent.addFlags(Cast.MAX_MESSAGE_LENGTH);

    intent.putExtra(LockPatternActivity.EXTRA_PENDING_INTENT_FORGOT_PATTERN, pi);

    startActivity(intent);

}

private void removeAppFromLockedList(String packName) {
    locked_list.remove(packName);
}

if there is any solution for it then please help me out thanks in advance

Body:
set a variable in service class  to check service is running or not.

let boolRuningService is a variable

Intent intent = new Intent(DashboardScreen.this, ServiceClass.class);
     PendingIntent pintent = PendingIntent.getService(DashboardScreen.this, 0, intent, 0);

                    if(!ServiceClass.boolRuningService){
                           AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
                        alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
                    }


问:
Navigate between views in Xamarin (visual studio) PCL project
I cant find a way to implement an onClick event on a button that will allow the application to navigate between the login and the second view.

How can I do that ?

Here is what i did

I created a method in my LoginViewModel.cs file that should redirect me to the second view.

```<code> class LoginViewModel
{
 private async Task SecondView_Click()
        {
            App.Current.MainPage = new NavigationPage(new SecondView());
        }
}
</code>```

Then I've defined a BindingContext in my Login.cs

```<code> public partial class Login : ContentPage
    {
        public Login()
        {
            InitializeComponent();
            BindingContext = new LoginViewModel();
        }
    }
</code>```

Then I define a button in my Login.xaml that has a binded command property

```<code> <StackLayout
        VerticalOptions="CenterAndExpand">
        <Entry StyleId="UsernameEntry"
               Placeholder="Username"
               Text="{Binding Username}" />
        <Entry StyleId="PasswordEntry"
               Placeholder="password"
               Text="{Binding Password}" />
        <Button
            StyleId="btn_connexion"
            Text="Connexion"
            Command="{Binding connexion}" />
        <Button
            StyleId="btn_testSecondView"
            Text="Test 2nd View"
                Command="{Binding SecondView_Click}"></Button>
    </StackLayout>
</code>```

答:
This works for me

PAGE 1 XAML

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TestRelativeLayout.MyPage1"
             Title="TabbedPage">
             <StackLayout>
                <Button Clicked="Handle_Clicked" Text = "Press">

        </Button>
    </StackLayout>
</ContentPage>
</code>```

PAGE 1 XAML.CS

```<code>using Xamarin.Forms;

namespace TestRelativeLayout
{
    public partial class MyPage1 : ContentPage
    {
        public MyPage1()
        {
            InitializeComponent();
        }

        public void Handle_Clicked(object sender, System.EventArgs e)
        {
            Application.Current.MainPage = new NavigationPage(new MyPage2());
        }
    }
}
</code>```

Try to remove

```<code>private async Task
</code>```

and use

```<code>void

private async Task SecondView_Click()
        {
            App.Current.MainPage = new NavigationPage(new SecondView());
        }
</code>```

Body:
I cant find a way to implement an onClick event on a button that will allow the application to navigate between the login and the second view.

How can I do that ?

Here is what i did

I created a method in my LoginViewModel.cs file that should redirect me to the second view.

 class LoginViewModel
{
 private async Task SecondView_Click()
        {
            App.Current.MainPage = new NavigationPage(new SecondView());
        }
}

Then I've defined a BindingContext in my Login.cs

 public partial class Login : ContentPage
    {
        public Login()
        {
            InitializeComponent();
            BindingContext = new LoginViewModel();
        }
    }

Then I define a button in my Login.xaml that has a binded command property

 <StackLayout
        VerticalOptions="CenterAndExpand">
        <Entry StyleId="UsernameEntry"
               Placeholder="Username"
               Text="{Binding Username}" />
        <Entry StyleId="PasswordEntry"
               Placeholder="password"
               Text="{Binding Password}" />
        <Button
            StyleId="btn_connexion"
            Text="Connexion"
            Command="{Binding connexion}" />
        <Button
            StyleId="btn_testSecondView"
            Text="Test 2nd View"
                Command="{Binding SecondView_Click}"></Button>
    </StackLayout>

Body:
This works for me

PAGE 1 XAML

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TestRelativeLayout.MyPage1"
             Title="TabbedPage">
             <StackLayout>
                <Button Clicked="Handle_Clicked" Text = "Press">

        </Button>
    </StackLayout>
</ContentPage>

PAGE 1 XAML.CS

using Xamarin.Forms;

namespace TestRelativeLayout
{
    public partial class MyPage1 : ContentPage
    {
        public MyPage1()
        {
            InitializeComponent();
        }

        public void Handle_Clicked(object sender, System.EventArgs e)
        {
            Application.Current.MainPage = new NavigationPage(new MyPage2());
        }
    }
}

Try to remove

private async Task

and use

void

private async Task SecondView_Click()
        {
            App.Current.MainPage = new NavigationPage(new SecondView());
        }


问:
Java 2d Array print out index at certain element
Lets say i got this :

```<code>int b[][];
b = new int[4][4];
for (int i = 0; i < b.length; i++) {
    for (int j = 0; j < b[i].length; j++) {
        b[i][j] = (Math.random() * 10);
    }
}
</code>```

And i want to print out at which [i][j] the value is < 5, how would i do this?

答:
You are knowing the for loop but not knowing the if statement is something weird.

But still for your knowledge
You can try out something like this

```<code>public class SomeClass{

    public static void main(String[] args){
        Double b[][]  = new Double [4][4];

        for(int i=0; i<b.length; i++ ){
                    for(int j=0;j<b[i].length;j++){
                     b[i][j]=(Math.random()*10);
                     if(b[i][j] < 5){
                        System.out.println("\n[i][j] = "+"["+i+"]["+j+"]\t result = "+b[i][j]);
                     }
                }
                }

    }

}
</code>```

Body:
Lets say i got this :

int b[][];
b = new int[4][4];
for (int i = 0; i < b.length; i++) {
    for (int j = 0; j < b[i].length; j++) {
        b[i][j] = (Math.random() * 10);
    }
}

And i want to print out at which [i][j] the value is < 5, how would i do this?

Body:
You are knowing the for loop but not knowing the if statement is something weird.

But still for your knowledge
You can try out something like this

public class SomeClass{

    public static void main(String[] args){
        Double b[][]  = new Double [4][4];

        for(int i=0; i<b.length; i++ ){
                    for(int j=0;j<b[i].length;j++){
                     b[i][j]=(Math.random()*10);
                     if(b[i][j] < 5){
                        System.out.println("\n[i][j] = "+"["+i+"]["+j+"]\t result = "+b[i][j]);
                     }
                }
                }

    }

}


问:
Keyboard output to multiple programs simultaneously?
My issue currently is that of emulating keystroke input to an arbitrary program (such as a running game).

Currently I am using win32 libraries on Windows to find windows (win32gui.FindWindow) and grab focus (via win32gui.SetForegroundWindow), then send keyboard input (win32api.keybd_event).

This works if I am only sending input to a single program, but I wish to parallelize, playing multiple games simultaneously. This does not work with my current method as both applications demand "focus" for the keys to go to the right application, thus interfering with each other.

Ideally I would like something that sends input to a given window, that does not require focus , and is independent of input given to other windows or the currently focused window.

答: My understanding is, only the foreground window get the focus and can handle keyboard input to play. Not sure in make sense to send input to background window or not....</p>


问:
ORA-12505, TNS: listener does not currently know of SID given in connect descriptor Vendor code 12505
i have just installed my Oracle Sql Developer 11g , and when I'm starting to make a new database connection and it failed so im configuring the ora files(tnsnames.ora and LISTENER.ora) but their contents are not same as the ora files that shown at the tutorials when I'm researching. So is this the right content of a tnsnames.ora and LISTENER.ora file? Thank you for answering..

```<code>this is my tnsnames.ora

# This file contains the syntax information for
# the entries to be put in any tnsnames.ora file
# The entries in this file are need based.
# There are no defaults for entries in this file
# that Sqlnet/Net3 use that need to be overridden
#
# Typically you could have two tnsnames.ora files
# in the system, one that is set for the entire system
# and is called the system tnsnames.ora file, and a
# second file that is used by each user locally so that
# he can override the definitions dictated by the system
# tnsnames.ora file.

# The entries in tnsnames.ora are an alternative to using
# the names server with the onames adapter.
# They are a collection of aliases for the addresses that
# the listener(s) is(are) listening for a database or
# several databases.

# The following is the general syntax for any entry in
# a tnsnames.ora file. There could be several such entries
# tailored to the user's needs.

<alias>= [ (DESCRIPTION_LIST =  # Optional depending on whether u have
                # one or more descriptions
                # If there is just one description, unnecessary ]
      (DESCRIPTION=
        [ (SDU=2048) ]  # Optional, defaults to 2048
                # Can take values between 512 and 32K
        [ (ADDRESS_LIST=    # Optional depending on whether u have
                # one or more addresses
                # If there is just one address, unnecessary ]
          (ADDRESS=
        [ (COMMUNITY=<community_name>) ]
        (PROTOCOL=tcp)
        (HOST=<hostname>)
        (PORT=<portnumber (1521 is a standard port used)>)
          )
          [ (ADDRESS=
          (PROTOCOL=ipc)
          (KEY=<ipckey (PNPKEY is a standard key used)>)
        )
          ]
          [ (ADDRESS=
          [ (COMMUNITY=<community_name>) ]
          (PROTOCOL=decnet)
          (NODE=<nodename>)
          (OBJECT=<objectname>)
        )
          ]
              ... # More addresses
        [ ) ] # Optional depending on whether ADDRESS_LIST is used or not
        [ (CONNECT_DATA=
        (SID=orcl)
        [ (GLOBAL_NAME=<global_database_name>) ]
          )
        ]
        [ (SOURCE_ROUTE=yes) ]
      )
      (DESCRIPTION=
        [ (SDU=2048) ]  # Optional, defaults to 2048
                # Can take values between 512 and 32K
        [ (ADDRESS_LIST= ]  # Optional depending on whether u have more
                # than one address or not
                # If there is just one address, unnecessary
          (ADDRESS
        [ (COMMUNITY=<community_name>) ]
        (PROTOCOL=tcp)
        (HOST=<hostname>)
        (PORT=<portnumber (1521 is a standard port used)>)
          )
          [ (ADDRESS=
          (PROTOCOL=ipc)
          (KEY=<ipckey (PNPKEY is a standard key used)>)
             )
          ]
          ...       # More addresses
        [ ) ]       # Optional depending on whether ADDRESS_LIST
                # is being used
        [ (CONNECT_DATA=
        (SID=orcl)
        [ (GLOBAL_NAME=<global_database_name>) ]
          )
        ]
        [ (SOURCE_ROUTE=yes) ]
      )
      [ (CONNECT_DATA=
          (SID=orcl)
                [ (GLOBAL_NAME=<global_database_name>) ]
        )
      ]
      ...   # More descriptions
    [ ) ]   # Optional depending on whether DESCRIPTION_LIST is used or not
</code>```

AND

```<code>this is my tnsnames.ora

# copyright (c) 1997 by the Oracle Corporation
#
# NAME
#   listener.ora
# FUNCTION
#   Network Listener startup parameter file example
# NOTES
#   This file contains all the parameters for listener.ora,
#   and could be used to configure the listener by uncommenting
#   and changing values.  Multiple listeners can be configured
#   in one listener.ora, so listener.ora parameters take the form
#   of SID_LIST_<lsnr>, where <lsnr> is the name of the listener
#   this parameter refers to.  All parameters and values are
#   case-insensitive.

# <lsnr>
#   This parameter specifies both the name of the listener, and
#   it listening address(es). Other parameters for this listener
#   us this name in place of <lsnr>.  When not specified,
#   the name for <lsnr> defaults to "LISTENER", with the default
#   address value as shown below.
#
# LISTENER =
#  (ADDRESS_LIST=
#   (ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1521))
#   (ADDRESS=(PROTOCOL=ipc)(KEY=PNPKEY)))

# SID_LIST_<lsnr>
#   List of services the listener knows about and can connect
#   clients to.  There is no default.  See the Net8 Administrator's
#   Guide for more information.
#
# SID_LIST_LISTENER=
#   (SID_LIST=
#   (SID_DESC=
#           #BEQUEATH CONFIG
#          (GLOBAL_DBNAME=salesdb.mycompany)
#          (SID_NAME=sid1)
#          (ORACLE_HOME=/private/app/oracle/product/8.0.3)
#           #PRESPAWN CONFIG
#         (PRESPAWN_MAX=20)
#     (PRESPAWN_LIST=
#           (PRESPAWN_DESC=(PROTOCOL=tcp)(POOL_SIZE=2)(TIMEOUT=1))
#         )
#        )
#       )

# PASSWORDS_<lsnr>
#   Specifies a password to authenticate stopping the listener.
#   Both encrypted and plain-text values can be set.  Encrypted passwords
#   can be set and stored using lsnrctl.
#     LSNRCTL> change_password
#       Will prompt for old and new passwords, and use encryption both
#       to match the old password and to set the new one.
#     LSNRCTL> set password
#   Will prompt for the new password, for authentication with
#       the listener. The password must be set before running the next
#       command.
#     LSNRCTL> save_config
#       Will save the changed password to listener.ora. These last two
#       steps are not necessary if SAVE_CONFIG_ON_STOP_<lsnr> is ON.
#       See below.
#
# Default: NONE
#
# PASSWORDS_LISTENER = 20A22647832FB454      # "foobar"

# SAVE_CONFIG_ON_STOP_<lsnr>
#   Tells the listener to save configuration changes to listener.ora when
#   it shuts down.  Changed parameter values will be written to the file,
#   while preserving formatting and comments.
# Default: OFF
# Values: ON/OFF
#
# SAVE_CONFIG_ON_STOP_LISTENER = ON

# USE_PLUG_AND_PLAY_<lsnr>
#   Tells the listener to contact an Onames server and register itself
#   and its services with Onames.
# Values: ON/OFF
# Default: OFF
#
# USE_PLUG_AND_PLAY_LISTENER = ON

# LOG_FILE_<lsnr>
#   Sets the name of the listener's log file.  The .log extension
#   is added automatically.
# Default=<lsnr>
#
# LOG_FILE_LISTENER = lsnr

# LOG_DIRECTORY_<lsnr>
#   Sets the directory for the listener's log file.
# Default: <oracle_home>/network/log
#
# LOG_DIRECTORY_LISTENER = /private/app/oracle/product/8.0.3/network/log

# TRACE_LEVEL_<lsnr>
#   Specifies desired tracing level.
# Default: OFF
# Values: OFF/USER/ADMIN/SUPPORT/0-16
#
# TRACE_LEVEL_LISTENER = SUPPORT

# TRACE_FILE_<lsnr>
#   Sets the name of the listener's trace file. The .trc extension
#   is added automatically.
# Default: <lsnr>
#
# TRACE_FILE_LISTENER = lsnr

# TRACE_DIRECTORY_<lsnr>
#   Sets the directory for the listener's trace file.
# Default: <oracle_home>/network/trace
#
# TRACE_DIRECTORY_LISTENER=/private/app/oracle/product/8.0.3/network/trace
# CONNECT_TIMEOUT_<lsnr>
#   Sets the number of seconds that the listener waits to get a
#   valid database query after it has been started.
# Default: 10
#
# CONNECT_TIMEOUT_LISTENER=10
</code>```

答:
Ping the database ip if it is listening then confirm your system hostname , that it must be same as in your tnsname.ora file.
After that conenction depends on the following highlighted areas that must be correctly entered.enter image description here </p>

Body:
i have just installed my Oracle Sql Developer 11g , and when I'm starting to make a new database connection and it failed so im configuring the ora files(tnsnames.ora and LISTENER.ora) but their contents are not same as the ora files that shown at the tutorials when I'm researching. So is this the right content of a tnsnames.ora and LISTENER.ora file? Thank you for answering..

this is my tnsnames.ora

# This file contains the syntax information for
# the entries to be put in any tnsnames.ora file
# The entries in this file are need based.
# There are no defaults for entries in this file
# that Sqlnet/Net3 use that need to be overridden
#
# Typically you could have two tnsnames.ora files
# in the system, one that is set for the entire system
# and is called the system tnsnames.ora file, and a
# second file that is used by each user locally so that
# he can override the definitions dictated by the system
# tnsnames.ora file.

# The entries in tnsnames.ora are an alternative to using
# the names server with the onames adapter.
# They are a collection of aliases for the addresses that
# the listener(s) is(are) listening for a database or
# several databases.

# The following is the general syntax for any entry in
# a tnsnames.ora file. There could be several such entries
# tailored to the user's needs.

<alias>= [ (DESCRIPTION_LIST =  # Optional depending on whether u have
                # one or more descriptions
                # If there is just one description, unnecessary ]
      (DESCRIPTION=
        [ (SDU=2048) ]  # Optional, defaults to 2048
                # Can take values between 512 and 32K
        [ (ADDRESS_LIST=    # Optional depending on whether u have
                # one or more addresses
                # If there is just one address, unnecessary ]
          (ADDRESS=
        [ (COMMUNITY=<community_name>) ]
        (PROTOCOL=tcp)
        (HOST=<hostname>)
        (PORT=<portnumber (1521 is a standard port used)>)
          )
          [ (ADDRESS=
          (PROTOCOL=ipc)
          (KEY=<ipckey (PNPKEY is a standard key used)>)
        )
          ]
          [ (ADDRESS=
          [ (COMMUNITY=<community_name>) ]
          (PROTOCOL=decnet)
          (NODE=<nodename>)
          (OBJECT=<objectname>)
        )
          ]
              ... # More addresses
        [ ) ] # Optional depending on whether ADDRESS_LIST is used or not
        [ (CONNECT_DATA=
        (SID=orcl)
        [ (GLOBAL_NAME=<global_database_name>) ]
          )
        ]
        [ (SOURCE_ROUTE=yes) ]
      )
      (DESCRIPTION=
        [ (SDU=2048) ]  # Optional, defaults to 2048
                # Can take values between 512 and 32K
        [ (ADDRESS_LIST= ]  # Optional depending on whether u have more
                # than one address or not
                # If there is just one address, unnecessary
          (ADDRESS
        [ (COMMUNITY=<community_name>) ]
        (PROTOCOL=tcp)
        (HOST=<hostname>)
        (PORT=<portnumber (1521 is a standard port used)>)
          )
          [ (ADDRESS=
          (PROTOCOL=ipc)
          (KEY=<ipckey (PNPKEY is a standard key used)>)
             )
          ]
          ...       # More addresses
        [ ) ]       # Optional depending on whether ADDRESS_LIST
                # is being used
        [ (CONNECT_DATA=
        (SID=orcl)
        [ (GLOBAL_NAME=<global_database_name>) ]
          )
        ]
        [ (SOURCE_ROUTE=yes) ]
      )
      [ (CONNECT_DATA=
          (SID=orcl)
                [ (GLOBAL_NAME=<global_database_name>) ]
        )
      ]
      ...   # More descriptions
    [ ) ]   # Optional depending on whether DESCRIPTION_LIST is used or not

AND

this is my tnsnames.ora

# copyright (c) 1997 by the Oracle Corporation
#
# NAME
#   listener.ora
# FUNCTION
#   Network Listener startup parameter file example
# NOTES
#   This file contains all the parameters for listener.ora,
#   and could be used to configure the listener by uncommenting
#   and changing values.  Multiple listeners can be configured
#   in one listener.ora, so listener.ora parameters take the form
#   of SID_LIST_<lsnr>, where <lsnr> is the name of the listener
#   this parameter refers to.  All parameters and values are
#   case-insensitive.

# <lsnr>
#   This parameter specifies both the name of the listener, and
#   it listening address(es). Other parameters for this listener
#   us this name in place of <lsnr>.  When not specified,
#   the name for <lsnr> defaults to "LISTENER", with the default
#   address value as shown below.
#
# LISTENER =
#  (ADDRESS_LIST=
#   (ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1521))
#   (ADDRESS=(PROTOCOL=ipc)(KEY=PNPKEY)))

# SID_LIST_<lsnr>
#   List of services the listener knows about and can connect
#   clients to.  There is no default.  See the Net8 Administrator's
#   Guide for more information.
#
# SID_LIST_LISTENER=
#   (SID_LIST=
#   (SID_DESC=
#           #BEQUEATH CONFIG
#          (GLOBAL_DBNAME=salesdb.mycompany)
#          (SID_NAME=sid1)
#          (ORACLE_HOME=/private/app/oracle/product/8.0.3)
#           #PRESPAWN CONFIG
#         (PRESPAWN_MAX=20)
#     (PRESPAWN_LIST=
#           (PRESPAWN_DESC=(PROTOCOL=tcp)(POOL_SIZE=2)(TIMEOUT=1))
#         )
#        )
#       )

# PASSWORDS_<lsnr>
#   Specifies a password to authenticate stopping the listener.
#   Both encrypted and plain-text values can be set.  Encrypted passwords
#   can be set and stored using lsnrctl.
#     LSNRCTL> change_password
#       Will prompt for old and new passwords, and use encryption both
#       to match the old password and to set the new one.
#     LSNRCTL> set password
#   Will prompt for the new password, for authentication with
#       the listener. The password must be set before running the next
#       command.
#     LSNRCTL> save_config
#       Will save the changed password to listener.ora. These last two
#       steps are not necessary if SAVE_CONFIG_ON_STOP_<lsnr> is ON.
#       See below.
#
# Default: NONE
#
# PASSWORDS_LISTENER = 20A22647832FB454      # "foobar"

# SAVE_CONFIG_ON_STOP_<lsnr>
#   Tells the listener to save configuration changes to listener.ora when
#   it shuts down.  Changed parameter values will be written to the file,
#   while preserving formatting and comments.
# Default: OFF
# Values: ON/OFF
#
# SAVE_CONFIG_ON_STOP_LISTENER = ON

# USE_PLUG_AND_PLAY_<lsnr>
#   Tells the listener to contact an Onames server and register itself
#   and its services with Onames.
# Values: ON/OFF
# Default: OFF
#
# USE_PLUG_AND_PLAY_LISTENER = ON

# LOG_FILE_<lsnr>
#   Sets the name of the listener's log file.  The .log extension
#   is added automatically.
# Default=<lsnr>
#
# LOG_FILE_LISTENER = lsnr

# LOG_DIRECTORY_<lsnr>
#   Sets the directory for the listener's log file.
# Default: <oracle_home>/network/log
#
# LOG_DIRECTORY_LISTENER = /private/app/oracle/product/8.0.3/network/log

# TRACE_LEVEL_<lsnr>
#   Specifies desired tracing level.
# Default: OFF
# Values: OFF/USER/ADMIN/SUPPORT/0-16
#
# TRACE_LEVEL_LISTENER = SUPPORT

# TRACE_FILE_<lsnr>
#   Sets the name of the listener's trace file. The .trc extension
#   is added automatically.
# Default: <lsnr>
#
# TRACE_FILE_LISTENER = lsnr

# TRACE_DIRECTORY_<lsnr>
#   Sets the directory for the listener's trace file.
# Default: <oracle_home>/network/trace
#
# TRACE_DIRECTORY_LISTENER=/private/app/oracle/product/8.0.3/network/trace
# CONNECT_TIMEOUT_<lsnr>
#   Sets the number of seconds that the listener waits to get a
#   valid database query after it has been started.
# Default: 10
#
# CONNECT_TIMEOUT_LISTENER=10


问:
"The given ColumnMapping does not match up with any column in the source or destination" while importing Excel into SQL Server using C#
I am getting an error

The given ColumnMapping does not match up with any column in the source or destination

with the following code

```<code>private void button1_Click_1(object sender, EventArgs e)
{
    of1.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";

    if ((of1.ShowDialog()) == System.Windows.Forms.DialogResult.OK)
    {
        imagepath = of1.FileName; //file path
        textBox1.Text = imagepath.ToString();
    }
}

private void loadbtn_Click(object sender, EventArgs e)
{
    string ssqltable = comboBox1.GetItemText(comboBox1.SelectedItem);
    string myexceldataquery = "select * from ["+ ssqltable + "$]";

    try
    {
        OleDbConnection oconn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+imagepath+";Extended Properties='Excel 12.0 Xml; HDR=YES;IMEX=1;';");
        string ssqlconnectionstring = "Data Source=.;Initial Catalog=Bioxcell;Integrated Security=true";

        OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oconn);
        oconn.Open();

        OleDbDataReader dr = oledbcmd.ExecuteReader();

        SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
        bulkcopy.DestinationTableName = ssqltable;

        while (dr.Read())
        {
            bulkcopy.WriteToServer(dr);
        }

        oconn.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }

    /* DisplayingData DD = new DisplayingData();
    DD.Show();*/
}
</code>```

I think SQL Server is case sensitive and I copied the same column names but the same error ..

Is there any way around this?

答:
Use SqlBulkCopy.ColumnMapping like this

```<code>for (int i = 0; i < dr.FieldCount; i++) {
    bulkcopy.ColumnMappings.Add(i, i);
}
</code>```

I just created a test table and a test file, according to your images. It worked fine for me, but would only add the first row of data.

Maybe you should make use of a DataTable and try again:

```<code>DataTable dt = new DataTable();
dt.Load(oledbcmd.ExecuteReader());
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
for(int i = 0; i < dt.Columns.Count; i++){
    bulkcopy.ColumnMappings.Add(i,i);
}
bulkcopy.WriteToServer(dt);
</code>```

When I tried it like that all my test rows got added to the database.

Body:
I am getting an error

The given ColumnMapping does not match up with any column in the source or destination

with the following code

private void button1_Click_1(object sender, EventArgs e)
{
    of1.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";

    if ((of1.ShowDialog()) == System.Windows.Forms.DialogResult.OK)
    {
        imagepath = of1.FileName; //file path
        textBox1.Text = imagepath.ToString();
    }
}

private void loadbtn_Click(object sender, EventArgs e)
{
    string ssqltable = comboBox1.GetItemText(comboBox1.SelectedItem);
    string myexceldataquery = "select * from ["+ ssqltable + "$]";

    try
    {
        OleDbConnection oconn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+imagepath+";Extended Properties='Excel 12.0 Xml; HDR=YES;IMEX=1;';");
        string ssqlconnectionstring = "Data Source=.;Initial Catalog=Bioxcell;Integrated Security=true";

        OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oconn);
        oconn.Open();

        OleDbDataReader dr = oledbcmd.ExecuteReader();

        SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
        bulkcopy.DestinationTableName = ssqltable;

        while (dr.Read())
        {
            bulkcopy.WriteToServer(dr);
        }

        oconn.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }

    /* DisplayingData DD = new DisplayingData();
    DD.Show();*/
}

I think SQL Server is case sensitive and I copied the same column names but the same error ..

Is there any way around this?

Body:
Use SqlBulkCopy.ColumnMapping like this

for (int i = 0; i < dr.FieldCount; i++) {
    bulkcopy.ColumnMappings.Add(i, i);
}

I just created a test table and a test file, according to your images. It worked fine for me, but would only add the first row of data.

Maybe you should make use of a DataTable and try again:

DataTable dt = new DataTable();
dt.Load(oledbcmd.ExecuteReader());
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
for(int i = 0; i < dt.Columns.Count; i++){
    bulkcopy.ColumnMappings.Add(i,i);
}
bulkcopy.WriteToServer(dt);

When I tried it like that all my test rows got added to the database.


问:
Oracle PL/SQL : to_date() format not considered
When I execute this in PL/SQL Developer :

```<code>SELECT to_date('29/03/17 14:05','DD/MM/RR HH24:MI')  FROM dual;
</code>```

Here's what I get :

```<code>3/29/2017 2:05:00 PM
</code>```

How is this possible ? I use HH24 but it seems like it's HH that's being used instead. The day and month are also not in the format I entered.

答:
(N.B. This answer is more to give more clarity to the other answers but it's too long for a comment.)

Oracle stores DATEs (and TIMESTAMPs etc) in its own specific format. Us humans represent dates in a variety of different formats and we deal with strings. Even us humans can get confused over what a date string represents, given no context - e.g. 03/09/2017 - is that the 3rd of September, 2017 or the 9th of March 2017?

So, when you pass a date into Oracle, you need to convert it into Oracle's date format by passing a string in and telling Oracle what the date format of that string is. This can be done using to_date() or via the DATE literal (which is always in yyyy-mm-dd format).

Conversely, when you want to read something that's stored in Oracle's DATE datatype, you need to tell Oracle how you want it to be displayed, which you can do by using to_char() with the appropriate format mask.

If you fail to explicitly convert the string-to-a-date or date-to-a-string, then Oracle uses the format specified in the NLS_DATE_FORMAT to decide how to do the conversion.

In your case, you didn't specify how you wanted your date to be displayed, so Oracle has to use to_char() along with the format contained in your NLS_DATE_FORMAT in order to display the date as a string, and clearly that's different to the format you passed the date-string in as.

Body:
When I execute this in PL/SQL Developer :

SELECT to_date('29/03/17 14:05','DD/MM/RR HH24:MI')  FROM dual;

Here's what I get :

3/29/2017 2:05:00 PM

How is this possible ? I use HH24 but it seems like it's HH that's being used instead. The day and month are also not in the format I entered.


问:
variable in function nor returning values after else statement
Im new with Python and my function is not working as expected. Im trying to save some values in a list list_alt[i] but if i call the values outside the if or else statements i get only None.</p>

```<code>import os.path
import xlrd
import sys
import argparse

def readExcel():
     workbook = xlrd.open_workbook(path)
     sheet = workbook.sheet_by_index(0)
     sheet = workbook.sheet_by_index(0)
     j=0
     for row in range(sheet.nrows):
          j += 1
     rownumber=j
     print (rownumber)

     k=0
     i=0
     list_alt=[None]*j
     list_neu=[None]*j
     while (i<j-10):
          #get first row values
          temp = sheet.cell_value(k,0).replace('www.website.com/','')
          #get second row values
          temp2 = sheet.cell_value(k,1)
          if "http:" in temp2:
               temp2 = sheet.cell_value(k,1).replace('http:','https:')
               list_neu[i]=temp2
               list_alt[i]=temp
               k+=0
               i+=1
          else:
               list_neu[i]=temp2
               list_alt[i]=temp
               #i can print the values here
               print (list_alt[i])
               print (list_neu[i])
               i+=1
               k+=1

          #I cant print for the values here anymore
          print (list_alt[i])
          print (list_neu[i])
          print (i)

     return list_alt, list_neu
</code>```

答:
If you got IndexError, It should be caused by i is increased before use by indexing list_alt[i].

```<code>import os.path
import xlrd
import sys
import argparse

def readExcel():
workbook = xlrd.open_workbook(path)
sheet = workbook.sheet_by_index(0)
sheet = workbook.sheet_by_index(0)
j=0
for row in range(sheet.nrows):
    j += 1
rownumber=j
print (rownumber)

k=0
i=0
list_alt=[None]*j
list_neu=[None]*j
while (i<j-10):
    temp = sheet.cell_value(k,0).replace('www.website.com/','')
    temp2 = sheet.cell_value(k,1)
    if "http:" in temp2:
        temp2 = sheet.cell_value(k,1).replace('http:','https:')
        list_neu[i]=temp2
        list_alt[i]=temp
        k+=0
        # variable i is increased.
        i+=1
    elif "http" not in temp2:
        print ("not there")
        k+=1
    else:
        list_neu[i]=temp2
        list_alt[i]=temp
        print (list_alt[i])
        print (list_neu[i])
        # variable i is increased.
        i+=1
        k+=1

    # variable i is increased before.
    # you may purpose to read list_alt[i-1].
    print (list_alt[i])
    print (i)

return list_alt, list_neu
</code>```

I do hope my answer is helpful. :D

Body:
Im new with Python and my function is not working as expected. Im trying to save some values in a list list_alt[i] but if i call the values outside the if or else statements i get only None.

import os.path
import xlrd
import sys
import argparse

def readExcel():
     workbook = xlrd.open_workbook(path)
     sheet = workbook.sheet_by_index(0)
     sheet = workbook.sheet_by_index(0)
     j=0
     for row in range(sheet.nrows):
          j += 1
     rownumber=j
     print (rownumber)

     k=0
     i=0
     list_alt=[None]*j
     list_neu=[None]*j
     while (i<j-10):
          #get first row values
          temp = sheet.cell_value(k,0).replace('www.website.com/','')
          #get second row values
          temp2 = sheet.cell_value(k,1)
          if "http:" in temp2:
               temp2 = sheet.cell_value(k,1).replace('http:','https:')
               list_neu[i]=temp2
               list_alt[i]=temp
               k+=0
               i+=1
          else:
               list_neu[i]=temp2
               list_alt[i]=temp
               #i can print the values here
               print (list_alt[i])
               print (list_neu[i])
               i+=1
               k+=1

          #I cant print for the values here anymore
          print (list_alt[i])
          print (list_neu[i])
          print (i)

     return list_alt, list_neu

Body:
If you got IndexError, It should be caused by i is increased before use by indexing list_alt[i].

import os.path
import xlrd
import sys
import argparse

def readExcel():
workbook = xlrd.open_workbook(path)
sheet = workbook.sheet_by_index(0)
sheet = workbook.sheet_by_index(0)
j=0
for row in range(sheet.nrows):
    j += 1
rownumber=j
print (rownumber)

k=0
i=0
list_alt=[None]*j
list_neu=[None]*j
while (i<j-10):
    temp = sheet.cell_value(k,0).replace('www.website.com/','')
    temp2 = sheet.cell_value(k,1)
    if "http:" in temp2:
        temp2 = sheet.cell_value(k,1).replace('http:','https:')
        list_neu[i]=temp2
        list_alt[i]=temp
        k+=0
        # variable i is increased.
        i+=1
    elif "http" not in temp2:
        print ("not there")
        k+=1
    else:
        list_neu[i]=temp2
        list_alt[i]=temp
        print (list_alt[i])
        print (list_neu[i])
        # variable i is increased.
        i+=1
        k+=1

    # variable i is increased before.
    # you may purpose to read list_alt[i-1].
    print (list_alt[i])
    print (i)

return list_alt, list_neu

I do hope my answer is helpful. :D


问:
AEM social Communities Handlebars context
I'm trying to get a context named userAdmin from within the handlebars framework for AEM Social Communities. The userAdmin context checks if the logged in user is a member or a moderator.

We already have this code within /libs/social/console/components/hbs/sitenavbar/sitenavbar.hbs at line number 54. With the below userAdmin context the Administration link appears only if the logged in user is a moderator/Community Admin

```<code>{{#if userAdmin}}
    <li><a href="{{adminUrl}}">{{i18n "Administration"}}</a></li>
{{/if}}
</code>```

Problem

I'm not able to fetch the same userAdmin context within /libs/social/messaging/components/hbs/messagebox/buttons.hbs at line number 36 where I want to the new message button only if the logged in user is a moderator/Community Admin

```<code>{{#if userAdmin}} //Here the context is not available within the buttons.hbs
   <input type='submit' class='actionbuttons' id='newMessageButton' name='{{properties.replyURL}}' value='{{i18n "+ New Message"}}' />
{{/if}}
</code>```

Could you please help me to figure out a way to get the context available in sitenavbar to any other SCF component like messagebox or forums. I've also tried using options like {{../userAdmin}} and {{@root userAdmin}}

Any suggestion or help would be great.

答:
This data (or getter) is exposed through the SocialComponent for this resource type. Only few objects are implicit available globally. So you need to define your own social component and implement (or extend existing component if some bundle exports it) such a getter. You can refer to the example scf projects (for example here) in github or look also in the adobe documentation.

You can find all objects available in the context of the current path by appending .social.json (e.g. /content/community-components/en/forum/jcr:content/content/forum.social.json).This will expose all the variables (context) that can be used inside the template.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to get a context named userAdmin from within the handlebars framework for AEM Social Communities. The userAdmin context checks if the logged in user is a member or a moderator.

We already have this code within /libs/social/console/components/hbs/sitenavbar/sitenavbar.hbs at line number 54. With the below userAdmin context the Administration link appears only if the logged in user is a moderator/Community Admin

{{#if userAdmin}}

{{i18n "Administration"}}

{{/if}}

Problem

I'm not able to fetch the same userAdmin context within /libs/social/messaging/components/hbs/messagebox/buttons.hbs at line number 36 where I want to the new message button only if the logged in user is a moderator/Community Admin

{{#if userAdmin}} //Here the context is not available within the buttons.hbs
   <input type='submit' class='actionbuttons' id='newMessageButton' name='{{properties.replyURL}}' value='{{i18n "+ New Message"}}' />
{{/if}}

Could you please help me to figure out a way to get the context available in sitenavbar to any other SCF component like messagebox or forums. I've also tried using options like {{../userAdmin}} and {{@root userAdmin}}

Any suggestion or help would be great.


问:
XSLT apply templates conditioning
I've an issue in apply templates , consider my xml will be like this ,
enter code here

```<code><card>
   <pre/>
<main>
  <step1/>
  <step1/>
  <panels>
    <panel/>
    <panel/>
  </panels>
  <step1/>
<main>
 </card>
</code>```

Inside main all the step1 will be started with 1. and  increment in further step.Now when the panel comes , it should take each panel as a step and it'll start as 3. , 4. next step1 will be 5.

problem is when if i apply templates for step1 in the mainfunc  , it's applying for all the step1. so the step1 after the panel also will come in the first place . I want to apply temaplates for the step1 to 3rd step1. then apply panel and then apply the last step1.step1 counts are not always same , they differ.

currently ive something like this ,

```<code><xsl:template match="mainfunc">
    <xsl:apply-templates select="step1"/>
    <xsl:if test="contains($wcType,'P')">
    <xsl:apply-templates select="panels"/>
    </xsl:if>
.....
</code>```

how to modify to apply the templates in sequence order , also numbering the panel as 3.

答:
This is a bit of a guess, as I am not entirely clear what you want to do, but I think what you could do is this...

```<code><xsl:apply-templates select="step1|panels[contains($wcType,'P')]"/>
</code>```

The | symbol is the union operator, and the union of nodes will be selected in document order. So, it will select the first step1, then the panels, then the next step1.

For example, this XSLT...

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" indent="yes" />

    <xsl:variable name="wcType" select="'Pie'" />

    <xsl:template match="main">
        <xsl:apply-templates select="step1|panels[contains($wcType,'P')]"/>
    </xsl:template>

    <xsl:template match="step1|panel">
        <xsl:copy>
            <xsl:number count="step1|panel" level="any" />
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>
</code>```

When applied to this XML...

```<code><card>
  <main>
    <step1/>
    <step1/>
    <panels>
      <panel/>
      <panel/>
    </panels>
    <step1/>
  </main>
</card>
</code>```

The following is output

```<code><step1>1</step1>
<step1>2</step1>
  <panel>3</panel>
  <panel>4</panel>
<step1>5</step1>
</code>```

Title: XSLT apply templates conditioning

Body:
I've an issue in apply templates , consider my xml will be like this ,
enter code here

<card>

  <step1/>
  <step1/>
  <panels>
    <panel/>
    <panel/>
  </panels>
  <step1/>

 </card>

Inside main all the step1 will be started with 1. and  increment in further step.Now when the panel comes , it should take each panel as a step and it'll start as 3. , 4. next step1 will be 5.

problem is when if i apply templates for step1 in the mainfunc  , it's applying for all the step1. so the step1 after the panel also will come in the first place . I want to apply temaplates for the step1 to 3rd step1. then apply panel and then apply the last step1.step1 counts are not always same , they differ.

currently ive something like this ,

<xsl:template match="mainfunc">
    <xsl:apply-templates select="step1"/>
    <xsl:if test="contains($wcType,'P')">
    <xsl:apply-templates select="panels"/>
    </xsl:if>
.....

how to modify to apply the templates in sequence order , also numbering the panel as 3.

Body:
This is a bit of a guess, as I am not entirely clear what you want to do, but I think what you could do is this...

<xsl:apply-templates select="step1|panels[contains($wcType,'P')]"/>

The | symbol is the union operator, and the union of nodes will be selected in document order. So, it will select the first step1, then the panels, then the next step1.

For example, this XSLT...

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" indent="yes" />

    <xsl:variable name="wcType" select="'Pie'" />

    <xsl:template match="main">
        <xsl:apply-templates select="step1|panels[contains($wcType,'P')]"/>
    </xsl:template>

    <xsl:template match="step1|panel">
        <xsl:copy>
            <xsl:number count="step1|panel" level="any" />
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

When applied to this XML...

<card>
  <main>
    <step1/>
    <step1/>
    <panels>
      <panel/>
      <panel/>
    </panels>
    <step1/>
  </main>
</card>

The following is output

<step1>1</step1>
<step1>2</step1>
  <panel>3</panel>
  <panel>4</panel>
<step1>5</step1>


问:
Return function pointing to local var in php
```<code>class Person{

     var $name = "Omer";

     function get_name(){
         return $this->name;//Why not $this->$name ?
     }
}
</code>```

Thanks

答: If you use $this->$name it will actually look for a property in $this with the name of whatever $name is equal to. So, in your example, $this->$name would look for $this->Omer.

Body:
class Person{

     var $name = "Omer";

     function get_name(){
         return $this->name;//Why not $this->$name ?
     }
}

Thanks


问:
PJSIP record voice from mic only device to a wav file via conference bridge
I have a device which has mic (capture) only capability. I want to record the voice from that device to wav file.

When i do following step

```<code>wav = pjmedia_wav_writer_port_create
snd_port = pjmedia_snd_port_create_rec (NOTE: PJMEDIA_DIR_CAPTURE only)
pjmedia_snd_port_connect(snd_port , wav)
</code>```

the voice is getting recorded into wav file

But when i do

```<code>wav = pjmedia_wav_writer_port_create
snd_port = pjmedia_snd_port_create_rec (NOTE: PJMEDIA_DIR_CAPTURE only)
conf = pjmedia_conf_create
pjmedia_snd_port_connect(snd_port , conf)
pjmedia_conf_add_port(conf, wav)
</code>```

the voice is not getting recoded into wav file

i get following debug messages from pjmedia

```<code>sound:0     pjsip      80 samples reduced, buf_cnt=161
sound:0     pjsip      80 samples reduced, buf_cnt=161
sound:0     pjsip      80 samples reduced, buf_cnt=161
sound:0     pjsip      80 samples reduced, buf_cnt=161
sound:0     pjsip      80 samples reduced, buf_cnt=161
sound:0     pjsip      80 samples reduced, buf_cnt=161
</code>```

答:
I think you should not connect pjmedia_snd_port (microphone) to both wav file and conference bridge (directly).

If you want to record to a file and using it in a conference bridge, It's better to connect sound device to a conference bridge and then create a rec port (pjmedia_port). Attach rec port to conference bridge and do some routing with pjmedia_conf_connect_port.

Your debug message show because, if you want to using conference bridge, you have to connect it to a sound device with following function (pjmedia_snd_port_create or pjmedia_snd_port_create_player). Do not only connect microphone to conference bridge. Because conference bridge need some synchronization that use snd player to work.

Body:
I have a device which has mic (capture) only capability. I want to record the voice from that device to wav file.

When i do following step

wav = pjmedia_wav_writer_port_create
snd_port = pjmedia_snd_port_create_rec (NOTE: PJMEDIA_DIR_CAPTURE only)
pjmedia_snd_port_connect(snd_port , wav)

the voice is getting recorded into wav file

But when i do

wav = pjmedia_wav_writer_port_create
snd_port = pjmedia_snd_port_create_rec (NOTE: PJMEDIA_DIR_CAPTURE only)
conf = pjmedia_conf_create
pjmedia_snd_port_connect(snd_port , conf)
pjmedia_conf_add_port(conf, wav)

the voice is not getting recoded into wav file

i get following debug messages from pjmedia

sound:0     pjsip      80 samples reduced, buf_cnt=161
sound:0     pjsip      80 samples reduced, buf_cnt=161
sound:0     pjsip      80 samples reduced, buf_cnt=161
sound:0     pjsip      80 samples reduced, buf_cnt=161
sound:0     pjsip      80 samples reduced, buf_cnt=161
sound:0     pjsip      80 samples reduced, buf_cnt=161


答:
```<code> select a.Reference, a.ModifiedDate as StartDate,
        coalesce(min(b.ModifiedDate),9999-12-31 00:00:00.000)  as EndDate
 from source_table as a
 left join source_table as b
 on a.reference = b.reference and a.ModifiedDate < b.ModifiedDate
 group by a.Reference, a.ModifiedDate
</code>```

Title: Complex SQL transformation

Body:
This is my source table

Reference   ModifiedDate
------------------------------------
1023175     2017-03-03 16:02:01.723
1023175     2017-03-07 07:59:49.283
1023175     2017-03-12 11:14:40.230

Ineed the following output

Reference   StartDate                 EndDate
---------------------------------------------
1023175   2017-03-03 16:02:01.723     2017-03-07 07:59:49.283
1023175   2017-03-07 07:59:49.283     2017-03-12 11:14:40.230
1023175   2017-03-12 11:14:40.230     9999-12-31 00:00:00.000 (last record should have this value)

Any suggestions on how this can be achieved?


问:
Android Visible view
we are using this code to visible view :

```<code>btnviewarray[x].setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int secid=v.getId();
        for(int zt=0;bzt<dcountlinks;bzt++)
        {
            if(mybtnids[zt]==secid)
            {
                myid=zt;
            }
        }
        //Toast.makeText(getActivity(), dcountpeople[myid], Toast.LENGTH_LONG).show();
        lnralllinksview.VISIBLE(View.GONE);
        lnrallpeopleview.VISIBLE(View.GONE);
    }
});
</code>```

when this code running we are getting Method call Excepted error

答:
Wrong

```<code> lnralllinksview.VISIBLE(View.GONE);
 lnrallpeopleview.VISIBLE(View.GONE);
</code>```

Perfect

```<code>lnralllinksview.setVisibility(View.GONE);
lnrallpeopleview.setVisibility(View.GONE);
</code>```

FYI

Read setVisibility

Title: Android Visible view

Body:
we are using this code to visible view :

btnviewarray[x].setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int secid=v.getId();
        for(int zt=0;bzt<dcountlinks;bzt++)
        {
            if(mybtnids[zt]==secid)
            {
                myid=zt;
            }
        }
        //Toast.makeText(getActivity(), dcountpeople[myid], Toast.LENGTH_LONG).show();
        lnralllinksview.VISIBLE(View.GONE);
        lnrallpeopleview.VISIBLE(View.GONE);
    }
});

when this code running we are getting Method call Excepted error

Body:
Wrong

 lnralllinksview.VISIBLE(View.GONE);
 lnrallpeopleview.VISIBLE(View.GONE);

Perfect

lnralllinksview.setVisibility(View.GONE);
lnrallpeopleview.setVisibility(View.GONE);

FYI

Read setVisibility


问:
help with a two table linq query
I want to display categories and subcategories like so:

Category 1

  Subcategory 1

  Subcategory 2

  Subcategory 3

Category 2

  Subcategory 5

  Subcategory 6

  Subcategory 7

In other words, foreach category, display the subcategories that belong to each one underneath.

My two tables are like so:

Category-

CategoryID

Name

SubCategory-

SubCategoryID

SubCategoryName

CategoryID

I have a foreign key from category to subcategory a one to many.

Here is where I got in the code, which display all sub categories foreach category.

```<code>public void displayLinqCategory()
{
    MyDataContext dbm = new MyDataContext();

    var q = from category in dbm.Categories
            join subCat in dbm.SubCategories
            on category.CategoryID equals subCat.CategoryID
            select new { category.Name, subCat.SubCategoryName };

    resultSpan.InnerHtml += "<table>";
    foreach (var c in q)
    {
        resultSpan.InnerHtml += "<tr><td>" + c.Name + "</td></tr>";
        foreach (var s in q)
        {
            resultSpan.InnerHtml += "<tr><td>   " + s.SubCategoryName + "</td></td>";
        }

    }
    resultSpan.InnerHtml += "</table>";
}
</code>```

答:
As you can see, there are a number of "right" answers. Here's how I'd do it:

```<code>// Data access belongs in its own area. Don't do it alongside HTML generation.
// Program to an interface so you can mock this repository in unit tests.
public interface ICategoryInfoRepository {
    IEnumerable<CategoryInfo> GetCategoryInfo();
}

public class CategoryInfo {
    public string CategoryName {get;set;}
    public IEnumerable<string> SubCategoryNames {get;set;}
}

public class CategoryInfoRepository : ICategoryInfoRepository
{
    public IEnumerable<CategoryInfo> GetCategoryInfo()
    {
        // The 'using' clause ensures that your context will be disposed
        // in a timely manner.
        using (var dbm = new MyDataContext())
        {
            // This query makes it pretty clear what you're selecting.
            // The groupings are implied.
            var q = from category in dbm.Categories
                    select new {
                        CategoryName = category.Name,
                        SubCategoryNames =
                            from subcategory in category.SubCategories
                            select subcategory.Name
                    };
            // Make sure all the data is in memory before disposing the context
            return q.ToList();
        }
    }
}
// Since all this method does is convert its input into a string, it would
// be very easy to unit-test.
public string GetCategoriesHtml(IEnumerable<CategoryInfo> categoryInfos) {
    // A StringBuilder will make this HTML generation go much faster
    var sb = new StringBuilder();
    // Don't use tables to represent non-tabular data.
    // This is a list, so let's make it a list.
    // Use CSS to format it to your liking.
    sb.Append("<ul>");
    foreach(var categoryInfo in categoryInfos)
    {
        sb.Append("<li>").Append(categoryInfo.CategoryName).Append("<ul>");
        foreach(var subCategoryName in categoryInfo.SubCategoryNames)
        {
            sb.Append("<li>").Append(subCategoryName).Append("</li>");
        }
        sb.Append("</ul></li>");
    }
    sb.Append("</ul>");
    return sb.ToString();
}

public void DisplayLinqCategory()
{
    // The repository would ideally be provided via dependency injection.
    var categoryInfos = _categoryInfoRepository.GetCategoryInfo();
    resultSpan.InnerHtml = GetCategoriesHtml(categoryInfos);
}
</code>```

I've made various "improvements" that would make sense in a long-term, real-world project. Feel free to ignore the ones that don't make sense for your particular situation.

Title: help with a two table linq query

Body:
I want to display categories and subcategories like so:

Category 1

  Subcategory 1

  Subcategory 2

  Subcategory 3

Category 2

  Subcategory 5

  Subcategory 6

  Subcategory 7

In other words, foreach category, display the subcategories that belong to each one underneath.

My two tables are like so:

Category-

CategoryID

Name

SubCategory-

SubCategoryID

SubCategoryName

CategoryID

I have a foreign key from category to subcategory a one to many.

Here is where I got in the code, which display all sub categories foreach category.

public void displayLinqCategory()
{
    MyDataContext dbm = new MyDataContext();

    var q = from category in dbm.Categories
            join subCat in dbm.SubCategories
            on category.CategoryID equals subCat.CategoryID
            select new { category.Name, subCat.SubCategoryName };

    resultSpan.InnerHtml += "
";
    foreach (var c in q)
    {
        resultSpan.InnerHtml += "
" + c.Name + "
";
        foreach (var s in q)
        {
            resultSpan.InnerHtml += "
   " + s.SubCategoryName + "		";
        }

    }
    resultSpan.InnerHtml += "
";
}

Body:
As you can see, there are a number of "right" answers. Here's how I'd do it:

// Data access belongs in its own area. Don't do it alongside HTML generation.
// Program to an interface so you can mock this repository in unit tests.
public interface ICategoryInfoRepository {
    IEnumerable<CategoryInfo> GetCategoryInfo();
}

public class CategoryInfo {
    public string CategoryName {get;set;}
    public IEnumerable<string> SubCategoryNames {get;set;}
}

public class CategoryInfoRepository : ICategoryInfoRepository
{
    public IEnumerable<CategoryInfo> GetCategoryInfo()
    {
        // The 'using' clause ensures that your context will be disposed
        // in a timely manner.
        using (var dbm = new MyDataContext())
        {
            // This query makes it pretty clear what you're selecting.
            // The groupings are implied.
            var q = from category in dbm.Categories
                    select new {
                        CategoryName = category.Name,
                        SubCategoryNames =
                            from subcategory in category.SubCategories
                            select subcategory.Name
                    };
            // Make sure all the data is in memory before disposing the context
            return q.ToList();
        }
    }
}
// Since all this method does is convert its input into a string, it would
// be very easy to unit-test.
public string GetCategoriesHtml(IEnumerable<CategoryInfo> categoryInfos) {
    // A StringBuilder will make this HTML generation go much faster
    var sb = new StringBuilder();
    // Don't use tables to represent non-tabular data.
    // This is a list, so let's make it a list.
    // Use CSS to format it to your liking.
    sb.Append("<ul>");
    foreach(var categoryInfo in categoryInfos)
    {
        sb.Append("<li>").Append(categoryInfo.CategoryName).Append("<ul>");
        foreach(var subCategoryName in categoryInfo.SubCategoryNames)
        {
            sb.Append("<li>").Append(subCategoryName).Append("</li>");
        }
        sb.Append("</ul></li>");
    }
    sb.Append("</ul>");
    return sb.ToString();
}

public void DisplayLinqCategory()
{
    // The repository would ideally be provided via dependency injection.
    var categoryInfos = _categoryInfoRepository.GetCategoryInfo();
    resultSpan.InnerHtml = GetCategoriesHtml(categoryInfos);
}

I've made various "improvements" that would make sense in a long-term, real-world project. Feel free to ignore the ones that don't make sense for your particular situation.


问:
How are Windows symbolic links treated by the apps?
I thought that symbolic links in Windows 10 behave similarly to Linux symlinks, i.e., they are transparent to the apps. However, I'm confused by the actual behavior.

As an example, I've both softlinked and hardlinked the same CSS file:

```<code>$ mklink softlinked.css Default.css
symbolic link created for softlinked.css <<===>> Default.css

$ mklink /H hardlinked.css Default.css
Hardlink created for hardlinked.css <<===>> Default.css
</code>```

The hardlink behaves predictably (is indistinguishable from the original file) but I don't understand the soft linked one. See for example this:

Also, when the CSS is consumed by the Caret editor, the hardlinked stylesheet works fine:

while the softlinked is broken:

The questions are:

How do the symbolic links actually behave on Windows?

Can soft links be made transparent to the apps? By transparent, I mean the app would always see the file as being on the symlinked path (...\symlinked.css) and never resolve to the original path (...\Default.css). Is there some Windows registry settings or something?

答:
They should be transparent to most apps but some apps are to clever for their own good.

They might pass FILE_FLAG_OPEN_REPARSE_POINT to CreateFile, or be too aggressive when "verifying" file attributes and choke on FILE_ATTRIBUTE_REPARSE_POINT.

In your specific case, I'm guessing the advanced editor should use FOS_NODEREFERENCELINKS in their open dialog. The CSS switcher might be using FILE_FLAG_OPEN_REPARSE_POINT and you should be able to verify that with Process monitor.

There is no magical registry entry you can use, you have to contact the application authors.

Body:
I thought that symbolic links in Windows 10 behave similarly to Linux symlinks, i.e., they are transparent to the apps. However, I'm confused by the actual behavior.

As an example, I've both softlinked and hardlinked the same CSS file:

$ mklink softlinked.css Default.css
symbolic link created for softlinked.css <<===>> Default.css

$ mklink /H hardlinked.css Default.css
Hardlink created for hardlinked.css <<===>> Default.css

The hardlink behaves predictably (is indistinguishable from the original file) but I don't understand the soft linked one. See for example this:

Also, when the CSS is consumed by the Caret editor, the hardlinked stylesheet works fine:

while the softlinked is broken:

The questions are:

How do the symbolic links actually behave on Windows?

Can soft links be made transparent to the apps? By transparent, I mean the app would always see the file as being on the symlinked path (...\symlinked.css) and never resolve to the original path (...\Default.css). Is there some Windows registry settings or something?


问:
Run-time error 1004 Application-defined or Object-defined error when setting Formula property
This works fine:

```<code>Sub Button1_Click()

    Dim strFormulas(1 To 3) As Variant

    With ThisWorkbook.Sheets("TRANSFORM")
        strFormulas(1) = "=SUM(A2:B2)"
        strFormulas(2) = "=PRODUCT(A2:B2)"
        strFormulas(3) = "=A2/B2"

        .Range("A4:G4").Formula = strFormulas
        .Range("A4:G20").FillDown
    End With

End Sub
</code>```

But this doesn't work - everything is the same besides strFormulas(1):

```<code>Sub Button1_Click()

    Dim strFormulas(1 To 3) As Variant

    With ThisWorkbook.Sheets("TRANSFORM")
        strFormulas(1) = "=IF(NOT(IMPORT!A4=''),VLOOKUP(IMPORT!A4,'VL1'!$Q$4:$R$26,2,FALSE),'-')"
        strFormulas(2) = "=PRODUCT(A2:B2)"
        strFormulas(3) = "=A2/B2"

        .Range("A4:G4").Formula = strFormulas
        .Range("A4:G20").FillDown
    End With

End Sub
</code>```

I get this error:

Run-time error 1004 Application-defined or Object-defined error

I think it may be because I'm trying to pull values from another worksheet in strFormulas(1).

I did my research and couldn't find a solution. Can anyone see what the problem is?

答:
You got apostrophes ' in the strFormulas(1) where there should be quotation marks ". So, it should be more something like

```<code>strFormulas(1) = "=IF(NOT(IMPORT!A4=""""),VLOOKUP(IMPORT!A4,""VL1""!$Q$4:$R$26,2,FALSE),""-"")"
</code>```

Just replace all ' within the formula with two quotation marks "".

Body:
This works fine:

Sub Button1_Click()

    Dim strFormulas(1 To 3) As Variant

    With ThisWorkbook.Sheets("TRANSFORM")
        strFormulas(1) = "=SUM(A2:B2)"
        strFormulas(2) = "=PRODUCT(A2:B2)"
        strFormulas(3) = "=A2/B2"

        .Range("A4:G4").Formula = strFormulas
        .Range("A4:G20").FillDown
    End With

End Sub

But this doesn't work - everything is the same besides strFormulas(1):

Sub Button1_Click()

    Dim strFormulas(1 To 3) As Variant

    With ThisWorkbook.Sheets("TRANSFORM")
        strFormulas(1) = "=IF(NOT(IMPORT!A4=''),VLOOKUP(IMPORT!A4,'VL1'!$Q$4:$R$26,2,FALSE),'-')"
        strFormulas(2) = "=PRODUCT(A2:B2)"
        strFormulas(3) = "=A2/B2"

        .Range("A4:G4").Formula = strFormulas
        .Range("A4:G20").FillDown
    End With

End Sub

I get this error:

Run-time error 1004 Application-defined or Object-defined error

I think it may be because I'm trying to pull values from another worksheet in strFormulas(1).

I did my research and couldn't find a solution. Can anyone see what the problem is?

Body:
You got apostrophes ' in the strFormulas(1) where there should be quotation marks ". So, it should be more something like

strFormulas(1) = "=IF(NOT(IMPORT!A4=""""),VLOOKUP(IMPORT!A4,""VL1""!$Q$4:$R$26,2,FALSE),""-"")"

Just replace all ' within the formula with two quotation marks "".


问:
Show Password icon in TextInputLayout touching the base line
I had some problem with my show password icon in TextInputLayout with android:inputType="textPassword". Right now it is showing like this

As you can see the show password icon is touching the base line.
I want something like this

You can see the gap between them.

The xml sode for implementing TextInputLayout is given below:

```<code><android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/TextLabelSNA"
    app:layout_constraintTop_toBottomOf="@+id/mailSave"
    app:layout_constraintBottom_toBottomOf="parent"
    android:layout_marginBottom="16dp"
    android:layout_marginTop="16dp"
    android:layout_marginStart="16dp"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginLeft="16dp"
    android:layout_marginEnd="16dp"
    app:layout_constraintRight_toRightOf="parent"
    android:layout_marginRight="16dp"
    android:id="@+id/tilOp"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintVertical_bias="0.0">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:inputType="textPassword"
        android:hint="Old Password"
        android:ems="10"
        android:textColor="#0A0B12"
        android:id="@+id/oldPassword"/>
</android.support.design.widget.TextInputLayout>
</code>```

style used is:

```<code><style name="TextLabelSNA" parent="Widget.Design.TextInputLayout">
    <!-- Hint color and label color in FALSE state -->
    <item name="android:textColorHint">@color/hintBlack</item>
    <item name="android:textSize">16sp</item>
    <!-- Label color in TRUE state and bar color FALSE and TRUE State -->
    <item name="colorAccent">@color/hintBlack</item>
    <item name="colorControlNormal">@color/hintBlack</item>
    <item name="colorControlActivated">@color/hintBlack</item>
</style>
</code>```

Please Help..!!!

答:
just add app:passwordToggleEnabled="true" in your textinputlayout</p>

```<code><android.support.design.widget.TextInputLayout
            app:layout_widthPercent="90%"
            android:layout_height="wrap_content"
            android:hint="@string/password"
            android:textColorHint="@android:color/white"
            app:passwordToggleEnabled="true"
            app:passwordToggleTint="@android:color/white">

            <android.support.v7.widget.AppCompatEditText
                android:id="@+id/et_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:textColor="@android:color/white"
                android:visibility="gone"
                 />

        </android.support.design.widget.TextInputLayout>
</code>```

Body:
I had some problem with my show password icon in TextInputLayout with android:inputType="textPassword". Right now it is showing like this

As you can see the show password icon is touching the base line.
I want something like this

You can see the gap between them.

The xml sode for implementing TextInputLayout is given below:

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/TextLabelSNA"
    app:layout_constraintTop_toBottomOf="@+id/mailSave"
    app:layout_constraintBottom_toBottomOf="parent"
    android:layout_marginBottom="16dp"
    android:layout_marginTop="16dp"
    android:layout_marginStart="16dp"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginLeft="16dp"
    android:layout_marginEnd="16dp"
    app:layout_constraintRight_toRightOf="parent"
    android:layout_marginRight="16dp"
    android:id="@+id/tilOp"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintVertical_bias="0.0">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:inputType="textPassword"
        android:hint="Old Password"
        android:ems="10"
        android:textColor="#0A0B12"
        android:id="@+id/oldPassword"/>
</android.support.design.widget.TextInputLayout>

style used is:

Please Help..!!!

Body:
just add app:passwordToggleEnabled="true" in your textinputlayout

<android.support.design.widget.TextInputLayout
            app:layout_widthPercent="90%"
            android:layout_height="wrap_content"
            android:hint="@string/password"
            android:textColorHint="@android:color/white"
            app:passwordToggleEnabled="true"
            app:passwordToggleTint="@android:color/white">

            <android.support.v7.widget.AppCompatEditText
                android:id="@+id/et_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:textColor="@android:color/white"
                android:visibility="gone"
                 />

        </android.support.design.widget.TextInputLayout>


问:
Grails, horizontal scroll of page, how can I do that
I have a view where a lot of data is displayed in a table. I have to have a big screen to see it all but can not count on that users always have that size as I have.
But unfortunately my grails project doesn't support horizontal scroll so if your screen isn't wide enough, you aren't able to see the rightmost part.

What can I do to get the view scroll horizontal?
I use version 3.2.4 of grails.

答:
Add the following style to your gsp, overflow is discussed here:</p>

```<code><style type="text/css">
    table {
        display: block;
        overflow-x: auto;
    }
</style>
</code>```

Body:
Add the following style to your gsp, overflow is discussed here:

<style type="text/css">
    table {
        display: block;
        overflow-x: auto;
    }
</style>


问:
Use C# EF objects in AngularJS code
I am currently working on an angularjs application with entity framework. I am facing a situation which I am sure is very common and everyone must have faced it.
I have c# entity classes generated by EF and I want to use those in my angularjs code. To be precise, I have angularjs forms which map to those EF classes. The EF classes have FK relationships and also also one-to-many relationships between them.

I want to know if there is a way to correctly represent the EF classes along with their FK relationship in AngularJS which would then be mapped to UI?

I searched on google and I can see people suggesting to use factories in such scenarios, but I am not sure if that is the correct approach to follow and if it will handle complex scenarios which i mentioned above.

Can anyone please advice on this issue like what is the industry standard for such scenarios and how everyone does it?

I am sure I am missing something

Thanks in advance.

答:
Remember that Angular is a frontend framework and should be treated as a layer that could be independent of the backend.

The Angular way of doing what you want is to have Angular services which will make get or put requests to your C#-EF endpoints to do whatever operations you may need.

For example if you have the Customer class in C#, you should have an action that returns all the Customers (e.g. http://example.com/Customers) as a JSON object, and then in Angular you make a call to this action and build an Angular model and deal with it within Angular.

Simultaneously, if you want to save data, you would just make a put request to your edit customer URL (e.g. http://example.com/Customer/102319) with whatever changed fields you have.

All the EF stuff including FK, many-many relationships, validations, etc.. you have to deal with within the C# world, although you can (and probably should) do it as well within the Angular world.

Title: Use C# EF objects in AngularJS code