问:
Updating app widget using AlarmManager
I am trying to update a Widget more frequently than the 30 minute restriction imposed by the 1.6docs. After reading nearly every post in SO, and the developer docs, and various other sources, I thought I had got to a point where i could implement it. And so, I tried, and failed. Since then, I have trawled yet more forums and solutions, and I cannot seem to get it to update.

I have an Update class that sets the AlarmManager:

```<code>public class Update extends Service{

    @Override
    public void onStart(Intent intent, int startId) {
          String currentTemp = Battery.outputTemp;
          String currentLevel = Battery.outputLevel;
          String currentCard = Battery.outputCard;
          String currentInternal = Battery.memory;
          String currentRam = String.valueOf(Battery.outputRam).substring(0, 3) + "MB";

          // Change the text in the widget
          RemoteViews updateViews = new RemoteViews(
          this.getPackageName(), R.layout.main);
          //update temp
          updateViews.setTextViewText(R.id.batteryTemp, currentTemp);
          //update %
          updateViews.setTextViewText(R.id.batteryLevel, currentLevel);
          //update level
          updateViews.setTextViewText(R.id.sdCard, currentCard);
          //update internal memory
          updateViews.setTextViewText(R.id.internal, currentInternal);
          //update ram
          updateViews.setTextViewText(R.id.ram, currentRam);

          ComponentName thisWidget = new ComponentName(this, Widget.class);
          AppWidgetManager manager = AppWidgetManager.getInstance(this);
          manager.updateAppWidget(thisWidget, updateViews);

    }
    @Override
    public IBinder onBind(Intent intent) {
        // no need to bind
        return null;
    }

}
</code>```

This has caused my onReceive in my widget class to fire frequently (i have a toast to see when it fires), yet it carries no intent (the toast is meant to display this as they are received but it is blank).

I cannot figure it out (i'm a relative newb-2 months of slow android dev), and appreciate any insight you guys have.

heres my widget class for reference:

```<code>    public class Widget extends AppWidgetProvider {

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {

        AlarmManager alarmManager;
        Intent intent = new Intent(context, Update.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        cal.add(Calendar.SECOND, 10);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal
                .getTimeInMillis(), 5 * 1000, pendingIntent);

        String currentTemp = Battery.outputTemp;
        String currentLevel = Battery.outputLevel;
        String currentCard = Battery.outputCard;
        String currentInternal = Battery.memory;
        String currentRam = String.valueOf(Battery.outputRam).substring(0, 3)
                + "MB";

        // Change the text in the widget
        RemoteViews updateViews = new RemoteViews(context.getPackageName(),
                R.layout.main);
        // update temp
        updateViews.setTextViewText(R.id.batteryTemp, currentTemp);
        appWidgetManager.updateAppWidget(appWidgetIds, updateViews);
        // update %
        updateViews.setTextViewText(R.id.batteryLevel, currentLevel);
        appWidgetManager.updateAppWidget(appWidgetIds, updateViews);
        // update level
        updateViews.setTextViewText(R.id.sdCard, currentCard);
        appWidgetManager.updateAppWidget(appWidgetIds, updateViews);
        // update internal memory
        updateViews.setTextViewText(R.id.internal, currentInternal);
        appWidgetManager.updateAppWidget(appWidgetIds, updateViews);
        // update ram
        updateViews.setTextViewText(R.id.ram, currentRam);
        appWidgetManager.updateAppWidget(appWidgetIds, updateViews);
        super.onUpdate(context, appWidgetManager, appWidgetIds);

    }

    public void onReceive(Context context, Intent intent) {

        super.onReceive(context, intent);
        Toast
                .makeText(context, intent.getAction() + context,
                        Toast.LENGTH_LONG).show();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            AppWidgetManager appWidgetManager = AppWidgetManager
                    .getInstance(context);
            ComponentName thisAppWidget = new ComponentName(context
                    .getPackageName(), Widget.class.getName());
            int[] appWidgetIds = appWidgetManager
                    .getAppWidgetIds(thisAppWidget);

            onUpdate(context, appWidgetManager, appWidgetIds);
        }

    }
}
</code>```

答:
A little bit modified version of petrnohejl's solution. This one is working in my project. (written in kotlin):

This is part of the Manifest.xml. I added the following actions: AUTO_UPDATE, APPWIDGET_UPDATE, APPWIDGET_ENABLED, APWIDGET_DISABLED.

```<code>                <receiver android:name=".AppWidget">
                    <intent-filter>
                        <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
                        <action android:name="android.appwidget.action.APPWIDGET_ENABLED" />
                        <action android:name="android.appwidget.action.APPWIDGET_DISABLED"/>
                    </intent-filter>
                    <intent-filter>
                        <action android:name="ACTION_AUTO_UPDATE" />
                    </intent-filter>

                    <meta-data
                            android:name="android.appwidget.provider"
                            android:resource="@xml/appwidget_info"/>
                </receiver>
</code>```

This is part of the AppWidget.kt. Here I implemented the onUpdate(), onEnabled(), onDisabled(), onReceive() functions.

```<code>class AppWidget: AppWidgetProvider() {

    override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {

        // There may be multiple widgets active, so update all of them
        for (appWidgetId in appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId)
        }
    }

    override fun onEnabled(context: Context) { // Enter relevant functionality for when the first widget is created

        // start alarm
        val appWidgetAlarm = AppWidgetAlarm(context.applicationContext)
        appWidgetAlarm.startAlarm()
    }

    override fun onDisabled(context: Context) { // Enter relevant functionality for when the last widget is disabled

        // stop alarm only if all widgets have been disabled
        val appWidgetManager = AppWidgetManager.getInstance(context)

        if (appWidgetIds.isEmpty()) {
            // stop alarm
            val appWidgetAlarm = AppWidgetAlarm(context.getApplicationContext())
            appWidgetAlarm.stopAlarm()
        }
    }

    companion object {

        val ACTION_AUTO_UPDATE = "AUTO_UPDATE"

        fun updateAppWidget(context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int) {

        val widgetText = Random.nextInt(0, 100).toString()

            // Construct the RemoteViews object
            val views = RemoteViews(context.packageName, R.layout.appwidget)
            views.setTextViewText(R.id.widget_text, widgetText)

            // Instruct the widget manager to update the widget
            appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.widget_text)
            appWidgetManager.updateAppWidget(appWidgetId, views)
        }
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        super.onReceive(context, intent)

        // Do something

        /*if (intent!!.action == ACTION_AUTO_UPDATE) {
            // DO SOMETHING
        }*/
    }
}
</code>```

And this is the AppWidgetAlarm.kt. Here it is my main modification. The answers didn't help me, but it is working. I set here a repeating alarm. (https://developer.android.com/training/scheduling/alarms)

```<code>class AppWidgetAlarm(private val context: Context?) {
        private val ALARM_ID = 0
        private val INTERVAL_MILLIS : Long = 10000

    fun startAlarm() {
        val calendar: Calendar = Calendar.getInstance()
        calendar.add(Calendar.MILLISECOND, INTERVAL_MILLIS.toInt())

        val alarmIntent = Intent(context, AppWidget::class.java).let { intent ->
            //intent.action = AppWidget.ACTION_AUTO_UPDATE
            PendingIntent.getBroadcast(context, 0, intent, 0)
        }
        with(context!!.getSystemService(Context.ALARM_SERVICE) as AlarmManager) {
           setRepeating(AlarmManager.RTC,calendar.timeInMillis, INTERVAL_MILLIS ,alarmIntent)
        }
    }

    fun stopAlarm() {
        val alarmIntent = Intent(AppWidget.ACTION_AUTO_UPDATE)
        val pendingIntent = PendingIntent.getBroadcast(context, ALARM_ID, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT)
        val alarmManager = context!!.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        alarmManager.cancel(pendingIntent)
    }
}
</code>```

Title: Updating app widget using AlarmManager

Body:
I am trying to update a Widget more frequently than the 30 minute restriction imposed by the 1.6docs. After reading nearly every post in SO, and the developer docs, and various other sources, I thought I had got to a point where i could implement it. And so, I tried, and failed. Since then, I have trawled yet more forums and solutions, and I cannot seem to get it to update.

I have an Update class that sets the AlarmManager:

public class Update extends Service{

    @Override
    public void onStart(Intent intent, int startId) {
          String currentTemp = Battery.outputTemp;
          String currentLevel = Battery.outputLevel;
          String currentCard = Battery.outputCard;
          String currentInternal = Battery.memory;
          String currentRam = String.valueOf(Battery.outputRam).substring(0, 3) + "MB";

          // Change the text in the widget
          RemoteViews updateViews = new RemoteViews(
          this.getPackageName(), R.layout.main);
          //update temp
          updateViews.setTextViewText(R.id.batteryTemp, currentTemp);
          //update %
          updateViews.setTextViewText(R.id.batteryLevel, currentLevel);
          //update level
          updateViews.setTextViewText(R.id.sdCard, currentCard);
          //update internal memory
          updateViews.setTextViewText(R.id.internal, currentInternal);
          //update ram
          updateViews.setTextViewText(R.id.ram, currentRam);

          ComponentName thisWidget = new ComponentName(this, Widget.class);
          AppWidgetManager manager = AppWidgetManager.getInstance(this);
          manager.updateAppWidget(thisWidget, updateViews);

    }
    @Override
    public IBinder onBind(Intent intent) {
        // no need to bind
        return null;
    }

}

This has caused my onReceive in my widget class to fire frequently (i have a toast to see when it fires), yet it carries no intent (the toast is meant to display this as they are received but it is blank).

I cannot figure it out (i'm a relative newb-2 months of slow android dev), and appreciate any insight you guys have.

heres my widget class for reference:

    public class Widget extends AppWidgetProvider {

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {

        AlarmManager alarmManager;
        Intent intent = new Intent(context, Update.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        cal.add(Calendar.SECOND, 10);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal
                .getTimeInMillis(), 5 * 1000, pendingIntent);

        String currentTemp = Battery.outputTemp;
        String currentLevel = Battery.outputLevel;
        String currentCard = Battery.outputCard;
        String currentInternal = Battery.memory;
        String currentRam = String.valueOf(Battery.outputRam).substring(0, 3)
                + "MB";

        // Change the text in the widget
        RemoteViews updateViews = new RemoteViews(context.getPackageName(),
                R.layout.main);
        // update temp
        updateViews.setTextViewText(R.id.batteryTemp, currentTemp);
        appWidgetManager.updateAppWidget(appWidgetIds, updateViews);
        // update %
        updateViews.setTextViewText(R.id.batteryLevel, currentLevel);
        appWidgetManager.updateAppWidget(appWidgetIds, updateViews);
        // update level
        updateViews.setTextViewText(R.id.sdCard, currentCard);
        appWidgetManager.updateAppWidget(appWidgetIds, updateViews);
        // update internal memory
        updateViews.setTextViewText(R.id.internal, currentInternal);
        appWidgetManager.updateAppWidget(appWidgetIds, updateViews);
        // update ram
        updateViews.setTextViewText(R.id.ram, currentRam);
        appWidgetManager.updateAppWidget(appWidgetIds, updateViews);
        super.onUpdate(context, appWidgetManager, appWidgetIds);

    }

    public void onReceive(Context context, Intent intent) {

        super.onReceive(context, intent);
        Toast
                .makeText(context, intent.getAction() + context,
                        Toast.LENGTH_LONG).show();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            AppWidgetManager appWidgetManager = AppWidgetManager
                    .getInstance(context);
            ComponentName thisAppWidget = new ComponentName(context
                    .getPackageName(), Widget.class.getName());
            int[] appWidgetIds = appWidgetManager
                    .getAppWidgetIds(thisAppWidget);

            onUpdate(context, appWidgetManager, appWidgetIds);
        }

    }
}

Body:
A little bit modified version of petrnohejl's solution. This one is working in my project. (written in kotlin):

This is part of the Manifest.xml. I added the following actions: AUTO_UPDATE, APPWIDGET_UPDATE, APPWIDGET_ENABLED, APWIDGET_DISABLED.

                <receiver android:name=".AppWidget">
                    <intent-filter>
                        <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
                        <action android:name="android.appwidget.action.APPWIDGET_ENABLED" />
                        <action android:name="android.appwidget.action.APPWIDGET_DISABLED"/>
                    </intent-filter>
                    <intent-filter>
                        <action android:name="ACTION_AUTO_UPDATE" />
                    </intent-filter>

                    <meta-data
                            android:name="android.appwidget.provider"
                            android:resource="@xml/appwidget_info"/>
                </receiver>

This is part of the AppWidget.kt. Here I implemented the onUpdate(), onEnabled(), onDisabled(), onReceive() functions.

class AppWidget: AppWidgetProvider() {

    override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {

        // There may be multiple widgets active, so update all of them
        for (appWidgetId in appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId)
        }
    }

    override fun onEnabled(context: Context) { // Enter relevant functionality for when the first widget is created

        // start alarm
        val appWidgetAlarm = AppWidgetAlarm(context.applicationContext)
        appWidgetAlarm.startAlarm()
    }

    override fun onDisabled(context: Context) { // Enter relevant functionality for when the last widget is disabled

        // stop alarm only if all widgets have been disabled
        val appWidgetManager = AppWidgetManager.getInstance(context)

        if (appWidgetIds.isEmpty()) {
            // stop alarm
            val appWidgetAlarm = AppWidgetAlarm(context.getApplicationContext())
            appWidgetAlarm.stopAlarm()
        }
    }

    companion object {

        val ACTION_AUTO_UPDATE = "AUTO_UPDATE"

        fun updateAppWidget(context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int) {

        val widgetText = Random.nextInt(0, 100).toString()

            // Construct the RemoteViews object
            val views = RemoteViews(context.packageName, R.layout.appwidget)
            views.setTextViewText(R.id.widget_text, widgetText)

            // Instruct the widget manager to update the widget
            appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.widget_text)
            appWidgetManager.updateAppWidget(appWidgetId, views)
        }
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        super.onReceive(context, intent)

        // Do something

        /*if (intent!!.action == ACTION_AUTO_UPDATE) {
            // DO SOMETHING
        }*/
    }
}

And this is the AppWidgetAlarm.kt. Here it is my main modification. The answers didn't help me, but it is working. I set here a repeating alarm. (https://developer.android.com/training/scheduling/alarms)

class AppWidgetAlarm(private val context: Context?) {
        private val ALARM_ID = 0
        private val INTERVAL_MILLIS : Long = 10000

    fun startAlarm() {
        val calendar: Calendar = Calendar.getInstance()
        calendar.add(Calendar.MILLISECOND, INTERVAL_MILLIS.toInt())

        val alarmIntent = Intent(context, AppWidget::class.java).let { intent ->
            //intent.action = AppWidget.ACTION_AUTO_UPDATE
            PendingIntent.getBroadcast(context, 0, intent, 0)
        }
        with(context!!.getSystemService(Context.ALARM_SERVICE) as AlarmManager) {
           setRepeating(AlarmManager.RTC,calendar.timeInMillis, INTERVAL_MILLIS ,alarmIntent)
        }
    }

    fun stopAlarm() {
        val alarmIntent = Intent(AppWidget.ACTION_AUTO_UPDATE)
        val pendingIntent = PendingIntent.getBroadcast(context, ALARM_ID, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT)
        val alarmManager = context!!.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        alarmManager.cancel(pendingIntent)
    }
}


来源: stackexchange

问:
localhost works in Edge but not in Chrome
I'm doing an on-line Java course and created a very simple server.  Using Edge as client it works but not with Chrome.  I've tried turning off firewall and some of the things suggested here (WAMP server localhost wont work with Chrome) and elsewhere, but they all seem to be overly complicated changes to Windows files.  Surely there's a config setting somewhere?!

In Edge it's fine, in Chrome it returns this whether I use localhost:999 or 127.0.0.1:999. I've tried other ports too.

This page isn’t working
127.0.0.1 sent an invalid response.
ERR_INVALID_HTTP_RESPONSE

Here is my code in case needed.

```<code>public static void main(String[] args) {
    try (
        ServerSocket aServer = new ServerSocket(999);
        Socket cn = aServer.accept();
         BufferedReader bis = new BufferedReader(new InputStreamReader(cn.getInputStream()));
        BufferedOutputStream bos = new BufferedOutputStream(cn.getOutputStream());)

        {
            String line = bis.readLine();
        while(line != null && !line.equals(""))
        {
            System.out.println(line);
            line = bis.readLine();
        }

        bos.write("Hello from java TCP Server!".getBytes());

    } catch (IOException ex) {
        System.out.println("Error in connnection: " + ex.getMessage());
    }
}
</code>```

Any help appreciated.

答:
Web browsers require that the server speaks HTTP protocol. A proper server response would be:

```<code>BufferedOutputStream bos = new BufferedOutputStream(System.out);

byte[] message="Hello from java TCP Server!".getBytes();

bos.write("HTTP/1.1 200 OK\r\n".getBytes());
bos.write("Content-Type: text/plain\r\n".getBytes());
bos.write(("Content-Length: "+message.length+"\r\n").getBytes());
bos.write("\r\n".getBytes()); // empty line between HTTP header and HTTP content
bos.write(message);

</code>```

You may test your program with another tool that speaks plain TCP sockets. Ich recommend "Netcat" (command: nc). Download for Windows: http://stefanfrings.de/avr_tools/netcat-win32-1.12.zip

ContentLicense: CC BY-SA 4.0

Body:
I'm doing an on-line Java course and created a very simple server.  Using Edge as client it works but not with Chrome.  I've tried turning off firewall and some of the things suggested here (WAMP server localhost wont work with Chrome) and elsewhere, but they all seem to be overly complicated changes to Windows files.  Surely there's a config setting somewhere?!

In Edge it's fine, in Chrome it returns this whether I use localhost:999 or 127.0.0.1:999. I've tried other ports too.

This page isn’t working
127.0.0.1 sent an invalid response.
ERR_INVALID_HTTP_RESPONSE

Here is my code in case needed.

public static void main(String[] args) {
    try (
        ServerSocket aServer = new ServerSocket(999);
        Socket cn = aServer.accept();
         BufferedReader bis = new BufferedReader(new InputStreamReader(cn.getInputStream()));
        BufferedOutputStream bos = new BufferedOutputStream(cn.getOutputStream());)

        {
            String line = bis.readLine();
        while(line != null && !line.equals(""))
        {
            System.out.println(line);
            line = bis.readLine();
        }

        bos.write("Hello from java TCP Server!".getBytes());

    } catch (IOException ex) {
        System.out.println("Error in connnection: " + ex.getMessage());
    }
}

Any help appreciated.

Body:
Web browsers require that the server speaks HTTP protocol. A proper server response would be:

BufferedOutputStream bos = new BufferedOutputStream(System.out);

byte[] message="Hello from java TCP Server!".getBytes();

bos.write("HTTP/1.1 200 OK\r\n".getBytes());
bos.write("Content-Type: text/plain\r\n".getBytes());
bos.write(("Content-Length: "+message.length+"\r\n").getBytes());
bos.write("\r\n".getBytes()); // empty line between HTTP header and HTTP content
bos.write(message);

You may test your program with another tool that speaks plain TCP sockets. Ich recommend "Netcat" (command: nc). Download for Windows: http://stefanfrings.de/avr_tools/netcat-win32-1.12.zip


问:
Laravel Pluck items onto new table rows
I have a table for trips and a table for events. One trip can have many events.
When editing a trip i want to display a table showing the event name, start date end date.

I have been using pluck to get data: -

             Trip ID
             Event ID
             Event Name
             Start Date
             End Date

    @foreach($trip->events as $trip->event)

        {{ implode(',', $trip->events()->pluck('trip_id')->toArray()) }}
        {{ implode(', ', $trip->events()->pluck('trip_id')->toArray()) }}
        {{ implode(', ', $trip->events()->pluck('event_name')->toArray()) }}
        {{ implode(', ', $trip->events()->pluck('start_date')->toArray()) }}
        {{ implode(', ', $trip->events()->pluck('end_date')->toArray()) }}

    @endforeach

```

However my table is displaying as three rows which is correct but each row contains all the data.
I want a new table row for each event created for the trip.

答:
Is what you're after something like this perhaps?</p>

```<code><table class="table table-striped table-bordered table-hover">
    <thead class="thead">
        <tr class="warning">
            <th>Trip ID</th>
            <th>Event ID</th>
            <th>Event Name</th>
            <th>Start Date</th>
            <th>End Date</th>
        </tr>
    </thead>
    <tbody>
    @foreach($trip->events as $event)
        <tr>
            <td>{{ $event->trip->id }}</td>
            <td>{{ $event->id }}</td>
            <td>{{ $event->event_name }}</td>
            <td>{{ $event->start_date }}</td>
            <td>{{ $event->end_date }}</td>
        </tr>
    @endforeach
    </tbody>
</table>
</code>```

Title: Laravel Pluck items onto new table rows

Body:
I have a table for trips and a table for events. One trip can have many events.
When editing a trip i want to display a table showing the event name, start date end date.

I have been using pluck to get data: -

             Trip ID
             Event ID
             Event Name
             Start Date
             End Date

    @foreach($trip->events as $trip->event)

        {{ implode(',', $trip->events()->pluck('trip_id')->toArray()) }}
        {{ implode(', ', $trip->events()->pluck('trip_id')->toArray()) }}
        {{ implode(', ', $trip->events()->pluck('event_name')->toArray()) }}
        {{ implode(', ', $trip->events()->pluck('start_date')->toArray()) }}
        {{ implode(', ', $trip->events()->pluck('end_date')->toArray()) }}

    @endforeach

However my table is displaying as three rows which is correct but each row contains all the data.
I want a new table row for each event created for the trip.

Body:
Is what you're after something like this perhaps?

<table class="table table-striped table-bordered table-hover">
    <thead class="thead">
        <tr class="warning">
            <th>Trip ID</th>
            <th>Event ID</th>
            <th>Event Name</th>
            <th>Start Date</th>
            <th>End Date</th>
        </tr>
    </thead>
    <tbody>
    @foreach($trip->events as $event)
        <tr>
            <td>{{ $event->trip->id }}</td>
            <td>{{ $event->id }}</td>
            <td>{{ $event->event_name }}</td>
            <td>{{ $event->start_date }}</td>
            <td>{{ $event->end_date }}</td>
        </tr>
    @endforeach
    </tbody>
</table>


问:
Error in function call from inside return along with jsx
I am trying to make a recursive call for parse directories. My code fails to compile.
Problem in call done as {getSubMenus( dir[objKey].subDir )} inside the second return

Error:
    ')' expected.

```<code>function getSubMenus(dir) {
    if (Object.entries(dir).length === 0 && dir.constructor === Object)
        return;

    return (
        <ul>
            {Object.keys(dir).map((objKey,index) => {
                return (
                    <li>
                        <Link to={`/${dir[objKey].url}`} >{objKey}</Link>
                    </li>
                    {getSubMenus( dir[objKey].subDir )}
                )
            })}
        </ul>
    )
}

return (
    <Layout>
        <h1>Locations</h1>

        {Object.keys(locationMenu).map((objKey,index) => (
            <li>
                <h3><Link to={`/${locationMenu[objKey].url}`}>{objKey}</Link>
                </h3>
                {getSubMenus(locationMenu[objKey].subDir)}
            </li>
        ))}
    </Layout>
);
</code>```

答:
```<code>return (
  <li><Link to={`/${dir[objKey].url}`} >{objKey}</Link></li>
  {getSubMenus( dir[objKey].subDir )}
)
</code>```

Instead of this try to wrap content returned in a Fragment.

```<code>return (
  <React.Fragment>
   <li>
    <Link to={`/${dir[objKey].url}`} >{objKey}</Link>
   </li>
   {getSubMenus( dir[objKey].subDir )}
  </React.Fragment>
)
</code>```

Body:
I am trying to make a recursive call for parse directories. My code fails to compile.
Problem in call done as {getSubMenus( dir[objKey].subDir )} inside the second return

Error:
    ')' expected.

function getSubMenus(dir) {
    if (Object.entries(dir).length === 0 && dir.constructor === Object)
        return;

    return (

            {Object.keys(dir).map((objKey,index) => {
                return (

                        <Link to={`/${dir[objKey].url}`} >{objKey}</Link>

                    {getSubMenus( dir[objKey].subDir )}
                )
            })}

    )
}

return (
    <Layout>

Locations

        {Object.keys(locationMenu).map((objKey,index) => (

<Link to={`/${locationMenu[objKey].url}`}>{objKey}</Link>

                {getSubMenus(locationMenu[objKey].subDir)}

        ))}
    </Layout>
);

Body:
return (
  <li><Link to={`/${dir[objKey].url}`} >{objKey}</Link></li>
  {getSubMenus( dir[objKey].subDir )}
)

Instead of this try to wrap content returned in a Fragment.

return (
  <React.Fragment>
   <li>
    <Link to={`/${dir[objKey].url}`} >{objKey}</Link>
   </li>
   {getSubMenus( dir[objKey].subDir )}
  </React.Fragment>
)


问:
Getting IE to replace a regex with the literal string "$0"
I'm replacing a bunch of values in a regex with dollar amounts.  The problem is that in IE, if I attempt to replace with an amount of $0 (or, theoretically, $1--$9), the replace never occurs since the it's trying to replace a non-existant group:

```<code>'foo'.replace(/f/g, '$0');
</code>```

I want the result of that replacement to be "$0oo", which it is in Chrome & FF, but not IE9 (haven't tried other versions of IE).

Chrome & FF have an "issue" with the following, in that I can't figure out how to replace with a literal $1:

```<code>'foo'.replace(/(f)/g, '$1')
</code>```

答: Write "$$0" to escape the $ sign.

ContentLicense: CC BY-SA 3.0

Body:
I'm replacing a bunch of values in a regex with dollar amounts.  The problem is that in IE, if I attempt to replace with an amount of $0 (or, theoretically, $1--$9), the replace never occurs since the it's trying to replace a non-existant group:

'foo'.replace(/f/g, '$0');

I want the result of that replacement to be "$0oo", which it is in Chrome & FF, but not IE9 (haven't tried other versions of IE).

Chrome & FF have an "issue" with the following, in that I can't figure out how to replace with a literal $1:

'foo'.replace(/(f)/g, '$1')

Body: Write "$$0" to escape the $ sign.


问:
How do I call paint event?
My program draws text on its panel,but if I'd like to remove the text I have to repaint.

How do I call(raise) the paint event by hand?

答:
Maybe this is an old question and that´s the reason why these answers didn't work for me ... using Visual Studio 2019, after some investigating, this is the solution I've found:</p>

```<code>this.InvokePaint(this, new PaintEventArgs(this.CreateGraphics(), this.DisplayRectangle));
</code>```

ContentLicense: CC BY-SA 2.5

Title: How do I call paint event?

Body:
Maybe this is an old question and that´s the reason why these answers didn't work for me ... using Visual Studio 2019, after some investigating, this is the solution I've found:

this.InvokePaint(this, new PaintEventArgs(this.CreateGraphics(), this.DisplayRectangle));


问:
Debugging a simple console game for Java
```<code>import java.util.Scanner;
public class Project3 {
    public static void main(String[] args) {
        Scanner keys = new Scanner(System.in);

System.out.println("Welcome to mini mad libs!"); // word1-word3 are inputs that point out which words from the story need to be replaced.
System.out.printf("Please enter the story: ");
String story = keys.nextLine();
System.out.printf("Please enter the first word type that should be replaced:");
String word1 = keys.nextLine();
System.out.printf("Please enter the second word type that should be replaced:");
String word2 = keys.nextLine();
System.out.printf("Please enter the third word type that should be replaced:");
String word3 = keys.nextLine();
System.out.println();

System.out.println("Ok, the game is ready to play!"); //the replace strings are the new words that are replacing the original words in the story.
System.out.println("Please enter a word type to replace "+word1);
String replace1 = keys.nextLine();
System.out.println("Please enter a word type to replace "+word2);
String replace2 = keys.nextLine();
System.out.println("Please enter a word to replace "+word3);
String replace3 = keys.nextLine();

String storyV2 = story.toLowerCase();
String word1V2 = word1.toLowerCase();
String word2V2 = word2.toLowerCase();
String word3V2 = word3.toLowerCase();

storyV2=storyV2.replaceAll("[.,!]", " ");
int positionOf1= storyV2.indexOf(" "+word1V2+" ");
int positionOf2= storyV2.indexOf(" "+word2V2+" ");
int positionOf3= storyV2.indexOf(" "+word3V2+" ");

int length1 = word1.length();
int length2 = word2.length();
int length3 = word3.length();

String WordMod1 = story.substring(positionOf1,positionOf1+length1);
String WordMod2 = story.substring(positionOf2,positionOf2+length2);
String WordMod3 = story.substring(positionOf3,positionOf3+length3);

String lib = story.replaceFirst(WordMod1, replace1); //lib serves as a string that has a version of the original story replaced by the three words one by one in the next lines below.
lib = lib.replaceFirst(WordMod2, replace2);
lib = lib.replaceFirst(WordMod3, replace3);
System.out.println();
System.out.println("Here is your little mad lib: \n"+ lib);
    }
}
</code>```

Mad libz is a game that replaces selected words from a sentence with other words of your choice. I cannot use if/else statements, loops or anything that is not string methods. My problem seems to be in this part of the code. I'm not too experienced with Java so it might look terrible.

```<code>String WordMod1 = story.substring(positionOf1,positionOf1+length1);
String WordMod2 = story.substring(positionOf2,positionOf2+length2);
String WordMod3 = story.substring(positionOf3,positionOf3+length3);
</code>```

This part is making a substrings that obtain the word in a sentence, for example if I want the word "noun", it looks the standalone word anywhere in the sentence instead of possible getting the word from other words like "pronoun" or "pronounced". PositionOf1 looks for the position between blank spaces and lenghtOf1 is the length of the original word we want to replace.

That is why this is also supposed to be case insensitive so that is why I made string storyV2, its a copy of the original set to lower case.

答:
If you just want to replace one string with another, then why not using the replaceAll() method?

```<code>String story = "...";
String fromWord = "foo";
String toWord = "bar";
String newStory = story.replaceAll(" " + foo + " ", " " + bar + " ");
</code>```

You could use more elaborate regex patterns for finding foo not only enclosed by spaces but all kinds of non-word characters, so you wouldn't need to remove characters like .,; etc. first as you currently do.

Body:
import java.util.Scanner;
public class Project3 {
    public static void main(String[] args) {
        Scanner keys = new Scanner(System.in);

System.out.println("Welcome to mini mad libs!"); // word1-word3 are inputs that point out which words from the story need to be replaced.
System.out.printf("Please enter the story: ");
String story = keys.nextLine();
System.out.printf("Please enter the first word type that should be replaced:");
String word1 = keys.nextLine();
System.out.printf("Please enter the second word type that should be replaced:");
String word2 = keys.nextLine();
System.out.printf("Please enter the third word type that should be replaced:");
String word3 = keys.nextLine();
System.out.println();

System.out.println("Ok, the game is ready to play!"); //the replace strings are the new words that are replacing the original words in the story.
System.out.println("Please enter a word type to replace "+word1);
String replace1 = keys.nextLine();
System.out.println("Please enter a word type to replace "+word2);
String replace2 = keys.nextLine();
System.out.println("Please enter a word to replace "+word3);
String replace3 = keys.nextLine();

String storyV2 = story.toLowerCase();
String word1V2 = word1.toLowerCase();
String word2V2 = word2.toLowerCase();
String word3V2 = word3.toLowerCase();

storyV2=storyV2.replaceAll("[.,!]", " ");
int positionOf1= storyV2.indexOf(" "+word1V2+" ");
int positionOf2= storyV2.indexOf(" "+word2V2+" ");
int positionOf3= storyV2.indexOf(" "+word3V2+" ");

int length1 = word1.length();
int length2 = word2.length();
int length3 = word3.length();

String WordMod1 = story.substring(positionOf1,positionOf1+length1);
String WordMod2 = story.substring(positionOf2,positionOf2+length2);
String WordMod3 = story.substring(positionOf3,positionOf3+length3);

String lib = story.replaceFirst(WordMod1, replace1); //lib serves as a string that has a version of the original story replaced by the three words one by one in the next lines below.
lib = lib.replaceFirst(WordMod2, replace2);
lib = lib.replaceFirst(WordMod3, replace3);
System.out.println();
System.out.println("Here is your little mad lib: \n"+ lib);
    }
}

Mad libz is a game that replaces selected words from a sentence with other words of your choice. I cannot use if/else statements, loops or anything that is not string methods. My problem seems to be in this part of the code. I'm not too experienced with Java so it might look terrible.

String WordMod1 = story.substring(positionOf1,positionOf1+length1);
String WordMod2 = story.substring(positionOf2,positionOf2+length2);
String WordMod3 = story.substring(positionOf3,positionOf3+length3);

This part is making a substrings that obtain the word in a sentence, for example if I want the word "noun", it looks the standalone word anywhere in the sentence instead of possible getting the word from other words like "pronoun" or "pronounced". PositionOf1 looks for the position between blank spaces and lenghtOf1 is the length of the original word we want to replace.

That is why this is also supposed to be case insensitive so that is why I made string storyV2, its a copy of the original set to lower case.

Body:
If you just want to replace one string with another, then why not using the replaceAll() method?

String story = "...";
String fromWord = "foo";
String toWord = "bar";
String newStory = story.replaceAll(" " + foo + " ", " " + bar + " ");

You could use more elaborate regex patterns for finding foo not only enclosed by spaces but all kinds of non-word characters, so you wouldn't need to remove characters like .,; etc. first as you currently do.


问:
Filter an array of repeated objects and get the sum of them
So I have the next information, what I want to achieve is filter the array of objects and sum the qty of the objects repeated

```<code>//Original Data
var data = {
    sublists = [
    { item: 1, qty: 2},
    { item: 2, qty: 2},
    { item: 3, qty: 2},
    { item: 1, qty: 5}
    { item: 3, qty: 3}
    ],
    ...
};
//This is what I want to achieve
var result = {
    sublists = [
    { item: 1, qty: 7},
    { item: 2, qty: 2},
    { item: 3, qty: 5}

    ],
    ...
};
</code>```

So far what I got is the items name that repeat and an object that has the data of this variables

```<code>var repeatedObjects = {
  1: [{ item: 1, qty: 2}, { item: 1, qty: 5}],
  3: [{ item: 3, qty: 2}, { item: 3, qty: 3}]
}
var repeatedItems = [1, 3];
</code>```

But Im stuck at reducing the object so I can get the original data, with just one of the repeated objects and the sum of all of them. Any ideas?

答:
If you fancy using lodash to do this in one line, you could also use this

```<code>const _ = require("lodash");

const data = [
  {"item": 1, "qty": 2},
  {"item": 2, "qty": 2},
  {"item": 3, "qty": 2},
  {"item": 1, "qty": 5},
  {"item": 3, "qty": 3}
];

const result = _.map(_.groupBy(data, i => i.item), (o, idx) => {
  return {"item": idx, "qty": _.sumBy(o, i => i.qty)};
});

console.log(result);

</code>```

Body:
So I have the next information, what I want to achieve is filter the array of objects and sum the qty of the objects repeated

//Original Data
var data = {
    sublists = [
    { item: 1, qty: 2},
    { item: 2, qty: 2},
    { item: 3, qty: 2},
    { item: 1, qty: 5}
    { item: 3, qty: 3}
    ],
    ...
};
//This is what I want to achieve
var result = {
    sublists = [
    { item: 1, qty: 7},
    { item: 2, qty: 2},
    { item: 3, qty: 5}

    ],
    ...
};

So far what I got is the items name that repeat and an object that has the data of this variables

var repeatedObjects = {
  1: [{ item: 1, qty: 2}, { item: 1, qty: 5}],
  3: [{ item: 3, qty: 2}, { item: 3, qty: 3}]
}
var repeatedItems = [1, 3];

But Im stuck at reducing the object so I can get the original data, with just one of the repeated objects and the sum of all of them. Any ideas?

Body:
If you fancy using lodash to do this in one line, you could also use this

const _ = require("lodash");

const data = [
  {"item": 1, "qty": 2},
  {"item": 2, "qty": 2},
  {"item": 3, "qty": 2},
  {"item": 1, "qty": 5},
  {"item": 3, "qty": 3}
];

const result = _.map(_.groupBy(data, i => i.item), (o, idx) => {
  return {"item": idx, "qty": _.sumBy(o, i => i.qty)};
});

console.log(result);


问:
How to know variables from different..."namespaces"?
How can I reach some variable declared in another place from within an external javascript file ?

Suppose in an html file I have the following

```<code><head>
 <script>
   var a = 'something';
 </script>
<head>
<body>
<iframe src="otherfile.html"/>
</body>
</code>```

and inside otherfile.html, in the  section, I have

```<code>alert(a);
</code>```

How can I make sure I get an alert message saying "something" ?

I think Google Adsense does this, their code is:

```<code><script type="text/javascript"><!--
google_ad_client = "youdontneedtoknowthis";
google_ad_slot = "5404192644";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</code>```

How can the script in http://pagead2.googlesyndication.com/pagead/show_ads.js know those variables (e.g. google_ad_client) ?

答: when a variable is defined without var it is said to exist in global scope. When your JS is loaded into your page, it is aware of any variables that exist globally at that time. So, what google is doing is defining some variables and then loading in an external script.

Body:
How can I reach some variable declared in another place from within an external javascript file ?

Suppose in an html file I have the following

and inside otherfile.html, in the  section, I have

alert(a);

How can I make sure I get an alert message saying "something" ?

I think Google Adsense does this, their code is:

How can the script in http://pagead2.googlesyndication.com/pagead/show_ads.js know those variables (e.g. google_ad_client) ?


问:
Save login form data using php
html webpage screenshotphp code shown on button clickmySql database tableI need to store user login data. i am using phpMyAdmin. When I click on submit button, data is not stored. Instead the php code is shown. Both code files are given below. What I am doing wrong. Help me. I
am unable to store user data using phpmyadmin in xampp.

my html code

```<code>
    <html>
    <head>
    <title>Yahoo Signin And Signup Form</title>
    </head>
    <body>
     <h2 style="color: midnightblue">yahoo!</h2>
     <hr color="magenta">
    <form method="post" action="connect.php" >
    <fieldset style="background:#6495ED;">
    <legend style="padding:20px 0; font-size:20px;">Signup:</legend>
    <label for ="firstName">Enter First Name</label><br>
    <input type="text" placeholder="First name" id="firstName" name ="firstName">
    <br>
    <label for ="lastName">Enter Last Name</label><br>
    <input type="text" placeholder="Last name" id="lastName" name ="lastName">
    <br>
    <label for ="email">Enter Email</label><br>
    <input type="text" placeholder="Email" id="email" name ="email"><br>
    <label for ="password">Enter Password</label><br>
    <input type="password" placeholder="Password" id="password" name ="password">
    <br>
    <label for ="number">Enter Mobile Number</label><br>
    <input placeholder="03---" id="number" name ="number"><br>
    <label for ="date">Enter Date of Birth</label><br>
    <input type="text" placeholder="DD/MM/YY" id="date" name ="date"><br>
    <label for ="gender">Enter Gender</label><br>
    <input type="text" placeholder="Male/Female/Other" id="gender" name
    ="gender"><br>
    <br><button style="background-color:orangered;border-
    color:dodgerblue;color:lightyellow">Signup</button>
    </fielsdet>
    </form>
    </body>
    </html>
</code>```

my connect.php

```<code>    <?php
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $number = $_POST['number'];
    $date = $_POST['date'];
    $gender = $_POST['gender'];

    // Making Connection with database

    $con = new mysqli('localhost','root','','phpdata');
    if ($con -> connect_error) {
    die('Connection failed :'.$conn -> connect_error);
    }
    else{
    $stmt = $con->query("INSERT INTO signup(firstName, lastName, email, password,
    number, date, gender)
        values(?,?,?,?,?,?,?)");
    $stmt->bind_param("ssssiss",$firstName, $lastName, $email, $password,
    $number, $date, $gender);
    $stmt->execute();
    echo "Sign up successful";
    $stmt->close();
    $con->close();
     }?>
</code>```

答:
here is the code, it works fine with me</p>

```<code><?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$date = $_POST['date'];
$gender = $_POST['gender'];

// Making Connection with database

$con = new mysqli('localhost','root','','phpdata');
if ($con -> connect_error) {
die('Connection failed :'.$conn -> connect_error);
}
else{

$stmt = $con->query("INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
    values("'.$firstName.'","'.$lastName.'","'.$email.'","'.$password.'","'.$number.'","'.$date.'","'.$gender.'")");
if ($con->query($stmt) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$con->close();

}//end of else of connection
?>
</code>```

Title: Save login form data using php

Body:
html webpage screenshotphp code shown on button clickmySql database tableI need to store user login data. i am using phpMyAdmin. When I click on submit button, data is not stored. Instead the php code is shown. Both code files are given below. What I am doing wrong. Help me. I
am unable to store user data using phpmyadmin in xampp.

my html code

    <title>Yahoo Signin And Signup Form</title>

yahoo!

    <form method="post" action="connect.php" >
    <fieldset style="background:#6495ED;">
    <legend style="padding:20px 0; font-size:20px;">Signup:</legend>
    Enter First Name

    <input type="text" placeholder="First name" id="firstName" name ="firstName">

    Enter Last Name

    <input type="text" placeholder="Last name" id="lastName" name ="lastName">

    Enter Email

    <input type="text" placeholder="Email" id="email" name ="email">

    Enter Password

    <input type="password" placeholder="Password" id="password" name ="password">

    Enter Mobile Number

    <input placeholder="03---" id="number" name ="number">

    Enter Date of Birth

    <input type="text" placeholder="DD/MM/YY" id="date" name ="date">

    Enter Gender

    <input type="text" placeholder="Male/Female/Other" id="gender" name
    ="gender">

<button style="background-color:orangered;border-
    color:dodgerblue;color:lightyellow">Signup</button>
    </fielsdet>
    </form>

my connect.php

    <?php
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $number = $_POST['number'];
    $date = $_POST['date'];
    $gender = $_POST['gender'];

    // Making Connection with database

    $con = new mysqli('localhost','root','','phpdata');
    if ($con -> connect_error) {
    die('Connection failed :'.$conn -> connect_error);
    }
    else{
    $stmt = $con->query("INSERT INTO signup(firstName, lastName, email, password,
    number, date, gender)
        values(?,?,?,?,?,?,?)");
    $stmt->bind_param("ssssiss",$firstName, $lastName, $email, $password,
    $number, $date, $gender);
    $stmt->execute();
    echo "Sign up successful";
    $stmt->close();
    $con->close();
     }?>

Body:
here is the code, it works fine with me

<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$date = $_POST['date'];
$gender = $_POST['gender'];

// Making Connection with database

$con = new mysqli('localhost','root','','phpdata');
if ($con -> connect_error) {
die('Connection failed :'.$conn -> connect_error);
}
else{

$stmt = $con->query("INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
    values("'.$firstName.'","'.$lastName.'","'.$email.'","'.$password.'","'.$number.'","'.$date.'","'.$gender.'")");
if ($con->query($stmt) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$con->close();

}//end of else of connection
?>


问:
javascript, diff function returning same string
i was wondering if somebody could help me on my diff function. its supposed to find the diff between 2 inputs. the function takes in 2 arrays so if array 1 has.. "word1", "word2" and array 2 has "word1", "word2", and "word3", it should just return "word3". it works for the most part, but with the certain input below, it doesn't work.

```<code>function diff(a1, a2) {

if (a1.length > a2.length
       || a1.length == a2.length) {
    return [""];
}
a1 = a1.slice(0);
a2 = a2.slice(0);

for (i = 0; i < a1.length; i++) {
    for (k = 0; k < a2.length; k++) {
        if (a1[i] == a2[k]) {
            a1.splice(i, 1);
            a2.splice(k, 1);
        }
    }
}

for (j = 0; j < a2.length; j++) {
    for (p = 0; p < a1.length; p++) {
        if (a2[j] == a1[p]) {
            a2.splice(p, 1);
            a1.splice(j, 1);
        }
    }
}

a1 = a1.concat(a2);
return a1;
}

var s1 = ["one", "two", "three", "four",];
var s2 = ["one", "two", "three", "four", "five"];

document.write(diff(s1, s2));
</code>```

the answer should just return "five", but its returning "four", "four", "five". help would be much appreciated. im super stuck. thanks a bunch!

答:
This comment quickly explains what your code was doing:

```<code>@Crystal, first double loop: at i=0 k=0 "one"=="one" so each is removed; at i=0 k=1 "two"!="three"; at i=0 k=2 "two"!="four"; at 0 3 "two"!="five"; 1 0 "three"!="two"; 1 1 "three"=="three" so each is removed; 1 2 "four"!="five"; no more cycles. In the second double loop: 0 0 "two"=="two" so each is removed; 0 1 is not run because at this point a1 only has "four" so a1.length==1. Thus we concat "four" in a1 with "four" and "five" in a2
</code>```

To get the answer you want, change

```<code>a1.splice(i, 1);
</code>```

to

```<code>a1.splice(i--, 1);
</code>```

And rinse,repeat for the other 3 similar cases within the double loops. So you will have 4 cases of taking the splice and decrementing by one its first argument. This decrementing makes up for the splice's removal.

However, you now only need one of the double loops since that will remove all overlaps.

Also, why do you have a check at the top to filter out the cases of a1 having length greater than or equal to the length of a2? Remove that section as well.

The answer will be "five". You can test very different data if you want, and it should work.

So this might be your program:

```<code>function diff(a1, a2) {

a1 = a1.slice(0);
a2 = a2.slice(0);

for (i = 0; i < a1.length; i++) {
    for (k = 0; k < a2.length; k++) {
        if (a1[i] == a2[k]) {
            a1.splice(i--, 1);
            a2.splice(k--, 1);
        }
    }
}

a1 = a1.concat(a2);
return a1;
}

var s1 = ["one", "two", "seven", "three", "four",];
var s2 = ["one", "two", "four", "five", "six"];

document.write(diff(s1, s2));
</code>```

Body:
i was wondering if somebody could help me on my diff function. its supposed to find the diff between 2 inputs. the function takes in 2 arrays so if array 1 has.. "word1", "word2" and array 2 has "word1", "word2", and "word3", it should just return "word3". it works for the most part, but with the certain input below, it doesn't work.

function diff(a1, a2) {

if (a1.length > a2.length
       || a1.length == a2.length) {
    return [""];
}
a1 = a1.slice(0);
a2 = a2.slice(0);

for (i = 0; i < a1.length; i++) {
    for (k = 0; k < a2.length; k++) {
        if (a1[i] == a2[k]) {
            a1.splice(i, 1);
            a2.splice(k, 1);
        }
    }
}

for (j = 0; j < a2.length; j++) {
    for (p = 0; p < a1.length; p++) {
        if (a2[j] == a1[p]) {
            a2.splice(p, 1);
            a1.splice(j, 1);
        }
    }
}

a1 = a1.concat(a2);
return a1;
}

var s1 = ["one", "two", "three", "four",];
var s2 = ["one", "two", "three", "four", "five"];

document.write(diff(s1, s2));

the answer should just return "five", but its returning "four", "four", "five". help would be much appreciated. im super stuck. thanks a bunch!

Body:
This comment quickly explains what your code was doing:

@Crystal, first double loop: at i=0 k=0 "one"=="one" so each is removed; at i=0 k=1 "two"!="three"; at i=0 k=2 "two"!="four"; at 0 3 "two"!="five"; 1 0 "three"!="two"; 1 1 "three"=="three" so each is removed; 1 2 "four"!="five"; no more cycles. In the second double loop: 0 0 "two"=="two" so each is removed; 0 1 is not run because at this point a1 only has "four" so a1.length==1. Thus we concat "four" in a1 with "four" and "five" in a2

To get the answer you want, change

a1.splice(i, 1);

to

a1.splice(i--, 1);

And rinse,repeat for the other 3 similar cases within the double loops. So you will have 4 cases of taking the splice and decrementing by one its first argument. This decrementing makes up for the splice's removal.

However, you now only need one of the double loops since that will remove all overlaps.

Also, why do you have a check at the top to filter out the cases of a1 having length greater than or equal to the length of a2? Remove that section as well.

The answer will be "five". You can test very different data if you want, and it should work.

So this might be your program:

function diff(a1, a2) {

a1 = a1.slice(0);
a2 = a2.slice(0);

for (i = 0; i < a1.length; i++) {
    for (k = 0; k < a2.length; k++) {
        if (a1[i] == a2[k]) {
            a1.splice(i--, 1);
            a2.splice(k--, 1);
        }
    }
}

a1 = a1.concat(a2);
return a1;
}

var s1 = ["one", "two", "seven", "three", "four",];
var s2 = ["one", "two", "four", "five", "six"];

document.write(diff(s1, s2));


问:
Switch case in order to check if string contains a substring
I have a string and want to check if there is a substring with switch/case. The fnstringCheck returns true for example if the fnstring is dies_ist_ein_test_diagnosen_erfassen.

What's going wrong? Thanks for your hints

```<code> var fnstring = (interim_transcript).toLowerCase().replace(/ /gi, "_");

 console.log('fnstring:', fnstring)
 var fnstringCheck = fnstring.indexOf("diagnosen_erfassen") !== -1;
 console.log(fnstringCheck)

 switch (fnstring) {
    case (fnstring.indexOf("_arztbrief_analysieren") !== -1):
        $('.analyzesBtn').trigger('click');
        break;

    case (fnstring.indexOf("_einleitung_erfassen") !== -1):
        changeSection('einleitung', mergedSource);
        break;

    case (fnstring.indexOf("diagnosen_erfassen") !== -1):
         changeSection('einleitung', mergedSource);
         break;

        ...
</code>```

答:
You need to take true in the switch statement, because the cases returns either true or false. The check uses a Identity/strict equality operator ===.

```<code>var fnstring = (interim_transcript).toLowerCase().replace(/ /gi, "_");

console.log('fnstring:', fnstring)
var fnstringCheck = fnstring.indexOf("diagnosen_erfassen") !== -1;
console.log(fnstringCheck)

switch (true) { // strict comparison
    case fnstring.indexOf("_arztbrief_analysieren") !== -1:
        $('.analyzesBtn').trigger('click');
        break;

    case fnstring.indexOf("_einleitung_erfassen") !== -1:
        changeSection('einleitung', mergedSource);
        break;

    case fnstring.indexOf("diagnosen_erfassen") !== -1:
        changeSection('einleitung', mergedSource);
        break;
}
</code>```

Body:
I have a string and want to check if there is a substring with switch/case. The fnstringCheck returns true for example if the fnstring is dies_ist_ein_test_diagnosen_erfassen.

What's going wrong? Thanks for your hints

 var fnstring = (interim_transcript).toLowerCase().replace(/ /gi, "_");

 console.log('fnstring:', fnstring)
 var fnstringCheck = fnstring.indexOf("diagnosen_erfassen") !== -1;
 console.log(fnstringCheck)

 switch (fnstring) {
    case (fnstring.indexOf("_arztbrief_analysieren") !== -1):
        $('.analyzesBtn').trigger('click');
        break;

    case (fnstring.indexOf("_einleitung_erfassen") !== -1):
        changeSection('einleitung', mergedSource);
        break;

    case (fnstring.indexOf("diagnosen_erfassen") !== -1):
         changeSection('einleitung', mergedSource);
         break;

        ...

Body:
You need to take true in the switch statement, because the cases returns either true or false. The check uses a Identity/strict equality operator ===.

var fnstring = (interim_transcript).toLowerCase().replace(/ /gi, "_");

console.log('fnstring:', fnstring)
var fnstringCheck = fnstring.indexOf("diagnosen_erfassen") !== -1;
console.log(fnstringCheck)

switch (true) { // strict comparison
    case fnstring.indexOf("_arztbrief_analysieren") !== -1:
        $('.analyzesBtn').trigger('click');
        break;

    case fnstring.indexOf("_einleitung_erfassen") !== -1:
        changeSection('einleitung', mergedSource);
        break;

    case fnstring.indexOf("diagnosen_erfassen") !== -1:
        changeSection('einleitung', mergedSource);
        break;
}


问:
App service app gives 404 in incognito mode or clear history
I have an app in the azure app service which has "index.html" setup as a default document in portal and also url rewrites in web-config (see below). If I go to the site with cleared history or chrome incognito mode it gives me a 404. I can hit the url directly on "mysite.com/index.html" and after that "mysite.com" will work too, but brand new browser session always 404.

I also have below in www_root in attempt to force "index.html" to load but no luck, any ideas?

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>

    <rewrite>
      <rules>
        <rule name="Angular Routes" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
          </conditions>
          <action type="Rewrite" url="/index.html" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>```

答: Try by removing '/' in url=/index.html and add appendQueryString="true"</p>


答:
Switch case doesn't work like this. Parameter given to switch is used to compare with each case. In your case switch took a string param and all case is having boolean properties.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

Title: Switch case in order to check if string contains a substring


问:
Typescript: What is the correct type for a Timeout?
What is the correct type when dealing with timers? I have tried Timeout and number

```<code>  let debounceResize: any;
//                     ^ What should this be?
  window.addEventListener('resize', () => {
    clearTimeout(debounceResize);
    debounceResize = setTimeout(calcCanvasSize, 500);
  });
</code>```

答:
For this case, I will give you 2 options:

Define type of debounceResize as return type of setTimeout, use ReturnType native generic.

```<code>let debounceResize: ReturnType<typeof setTimeout>;
</code>```

Use window.setTimeout instead of only setTimeout. window.setTimeout returns a number.

```<code>let debounceResize: number;

debounceResize = window.setTimeout(() => {}, 1000);
</code>```

Body:
What is the correct type when dealing with timers? I have tried Timeout and number

  let debounceResize: any;
//                     ^ What should this be?
  window.addEventListener('resize', () => {
    clearTimeout(debounceResize);
    debounceResize = setTimeout(calcCanvasSize, 500);
  });

Body:
For this case, I will give you 2 options:

Define type of debounceResize as return type of setTimeout, use ReturnType native generic.

let debounceResize: ReturnType<typeof setTimeout>;

Use window.setTimeout instead of only setTimeout. window.setTimeout returns a number.

let debounceResize: number;

debounceResize = window.setTimeout(() => {}, 1000);


问:
Preserve file last modified date time while copying it from source to target
I am trying to copy a file from one location to another. While copying it from source to target, target file is taking current date time. How can i make target file date as same as source file.</p>

```<code>FileInputStream source = new FileInputStream("D:\\test\\test.txt");
OutputStream target = new FileOutputStream("D:\\test.txt");
byte[] buffer = new byte[source.available()];
source.read(buffer);
target.write(buffer);
source.close();
target.close();`
</code>```

答:
Since JDK 7, the following code will make a copy of a file and the copied file will have the same attributes as the original file which means the target file will have the same date as the source file.

java.nio.file.Path source = java.nio.file.Paths.get("D:\\test\\test.txt");
java.nio.file.Path target = java.nio.file.Paths.get("D:\\test.txt");
try {
    java.nio.file.Files.copy(source, target, java.nio.file.StandardCopyOption.COPY_ATTRIBUTES);
}
catch (java.io.IOException x) {
    x.printStackTrace();
}
```

Body:
I am trying to copy a file from one location to another. While copying it from source to target, target file is taking current date time. How can i make target file date as same as source file.

FileInputStream source = new FileInputStream("D:\\test\\test.txt");
OutputStream target = new FileOutputStream("D:\\test.txt");
byte[] buffer = new byte[source.available()];
source.read(buffer);
target.write(buffer);
source.close();
target.close();`


问:
Laravel use condition in query in result
I using laravel as Rest API, I get data from controller:

```<code>$user= User::where('id', $id)->first(['id', 'name', 'phone', 'work', 'address']);
</code>```

result:

```<code>{
  "data": {
    "id": 1,
    "name": "mike shinoda",
    "phone": "0584634425",
    "work": null,
    "address": null
  }
}
</code>```

Now I want get a secret data, it's national ID, I don't want to include this in json data, just want to detect, if it set, return another data. I want if national id is set,

```<code>$user= User::where('id', $id)->first(['id', 'name', 'phone', 'work', 'address', 'national_id']);
</code>```

result:

```<code>{
  "data": {
    "id": 1,
    "name": "mike shinoda",
    "phone": "0584634425",
    "work": null,
    "address": null,
    "national_id": 2115 // I don't want this
  }
}
</code>```

Instead want if national id is set, return data like this:

```<code>{
  "data": {
    "id": 1,
    "name": "mike shinoda",
    "phone": "0584634425",
    "work": null,
    "address": null,
    "verified": true // return this if national id is set
  }
}
</code>```

What I tried:

```<code>  $verified = false;
    $national = User::where('id', $id)
        ->whereNotNull('national_id')
        ->first();
    if($national){
        $verified = true;
    }
    $user= User::where('id', $id)->first(['id', 'name', 'phone', 'work', 'address']);
    $user['verified'] = $verified;
</code>```

But I think it's kinda not clean and don't want to use two query for a simple JSON data, is there a way to do this with one query not two?

答:
you can use DB::raw for with case like below

```<code>$user= User::select('id', 'name', 'phone', 'work', 'address',
DB::raw("(CASE WHEN national_id > 0 THEN 'true' ELSE 'false' END)  AS verified")
)->where('id', $id)->first();
</code>```

Body:
I using laravel as Rest API, I get data from controller:

$user= User::where('id', $id)->first(['id', 'name', 'phone', 'work', 'address']);

result:

{
  "data": {
    "id": 1,
    "name": "mike shinoda",
    "phone": "0584634425",
    "work": null,
    "address": null
  }
}

Now I want get a secret data, it's national ID, I don't want to include this in json data, just want to detect, if it set, return another data. I want if national id is set,

$user= User::where('id', $id)->first(['id', 'name', 'phone', 'work', 'address', 'national_id']);

result:

{
  "data": {
    "id": 1,
    "name": "mike shinoda",
    "phone": "0584634425",
    "work": null,
    "address": null,
    "national_id": 2115 // I don't want this
  }
}

Instead want if national id is set, return data like this:

{
  "data": {
    "id": 1,
    "name": "mike shinoda",
    "phone": "0584634425",
    "work": null,
    "address": null,
    "verified": true // return this if national id is set
  }
}

What I tried:

  $verified = false;
    $national = User::where('id', $id)
        ->whereNotNull('national_id')
        ->first();
    if($national){
        $verified = true;
    }
    $user= User::where('id', $id)->first(['id', 'name', 'phone', 'work', 'address']);
    $user['verified'] = $verified;

But I think it's kinda not clean and don't want to use two query for a simple JSON data, is there a way to do this with one query not two?

Body:
you can use DB::raw for with case like below

$user= User::select('id', 'name', 'phone', 'work', 'address',
DB::raw("(CASE WHEN national_id > 0 THEN 'true' ELSE 'false' END)  AS verified")
)->where('id', $id)->first();


问:
bash script to rename files based on a calculation
I have a file system containing PNG images.  The layout of the filesystem is: ZOOM/X/Y.png where ZOOM, X, and Y are all integers.

I need to change the names of the PNG files.  Basically, I need to convert Y from its current value to 2^ZOOM-Y-1.  I've written a bash script to accomplish this task.  However, I suspect it can be optimized substantially.  (I also suspect that I may have been better off writing it in Perl, but that is another story.)

Here is the script.  Is this about as good as it gets?  Or can the performance be optimized?  Are there tools I can use that would profile the script for me and tell me where I'm spending all my execution time?

```<code>#!/bin/bash

tiles=`ls -d */*/*`

for oldPath in $tiles
do
   oldY=`basename -s .png $oldPath`
   zoomX=`dirname $oldPath`
   zoom=`echo $zoomX | sed 's#\([^\]\)/.*#\1#'`
   newY=`echo 2^$zoom-$oldY-1|bc`
   mv ${zoomX}/${oldY}.png ${zoomX}/${newY}.png
done
</code>```

答:
I see 3 improvements I would do, if it was my script. Whether they have an huge impact - I don't think so.

But you should avoid as hell parsing the output of ls. Maybe this directory is very predictable, from the things found inside, but if I read your script correctly, you can use the globbing with for directly:

```<code>for thisPath in */*/*
</code>```

repeatedly, $(cmd) is better than cmd with the deprecated backticks, which aren't nestable.

```<code>thisDir=$(dirname $thisPath)
</code>```

arithmetic in bash directly:

```<code>newTile=$((2**$zoom-$thisTile-1))
</code>```

as long as you don't need floating point, or output is getting too big.

I don't get the sed-part:

```<code>zoom=`echo $zoomX | sed 's#\([^\]\)/.*#\1#'`
</code>```

Is there something missing after the backslash? A second one? You're searching for something which isn't a backslash, followed by a slash-something? Maybe it could be done purely in bash too.

Body:
I have a file system containing PNG images.  The layout of the filesystem is: ZOOM/X/Y.png where ZOOM, X, and Y are all integers.

I need to change the names of the PNG files.  Basically, I need to convert Y from its current value to 2^ZOOM-Y-1.  I've written a bash script to accomplish this task.  However, I suspect it can be optimized substantially.  (I also suspect that I may have been better off writing it in Perl, but that is another story.)

Here is the script.  Is this about as good as it gets?  Or can the performance be optimized?  Are there tools I can use that would profile the script for me and tell me where I'm spending all my execution time?

#!/bin/bash

tiles=`ls -d */*/*`

for oldPath in $tiles
do
   oldY=`basename -s .png $oldPath`
   zoomX=`dirname $oldPath`
   zoom=`echo $zoomX | sed 's#\([^\]\)/.*#\1#'`
   newY=`echo 2^$zoom-$oldY-1|bc`
   mv ${zoomX}/${oldY}.png ${zoomX}/${newY}.png
done

Body:
I see 3 improvements I would do, if it was my script. Whether they have an huge impact - I don't think so.

But you should avoid as hell parsing the output of ls. Maybe this directory is very predictable, from the things found inside, but if I read your script correctly, you can use the globbing with for directly:

for thisPath in */*/*

repeatedly, $(cmd) is better than cmd with the deprecated backticks, which aren't nestable.

thisDir=$(dirname $thisPath)

arithmetic in bash directly:

newTile=$((2**$zoom-$thisTile-1))

as long as you don't need floating point, or output is getting too big.

I don't get the sed-part:

zoom=`echo $zoomX | sed 's#\([^\]\)/.*#\1#'`

Is there something missing after the backslash? A second one? You're searching for something which isn't a backslash, followed by a slash-something? Maybe it could be done purely in bash too.


问:
Colab : Best way to create a copy/clone of notebook in Goolge Colaboratory
I am using the Goole colab for data analytics and I have several notebooks.

Sometimes I need to quickly make a copy/clone of my working notebook to make some changes and experiment.

So is there a quick easy way to like a shortcut or menu option to do this? other than downloading the notebook as a .ipynb file and loading again with new name?

答:
You can make a copy from the menu

```<code>File > Save a copy in Drive...
</code>```

The new Colab will be named Copy of xxxxx.ipynb. You can click the name and rename it.

Body:
You can make a copy from the menu

File > Save a copy in Drive...

The new Colab will be named Copy of xxxxx.ipynb. You can click the name and rename it.


问:
How to change item color in javascript?
How can I change the item color when being clicked in Javascript? Not allowed to change in HTML nor CSS.

Tried this but not working:

```<code>$("#image1").click(
        function(){
            $(this).css({color:'white'});
        },
        function(){
            $(this).css({color:'black'});
        }
    );
</code>```

However, it does work when I tried the alert function:

```<code>$("#image1").click(
        function(){
            alert("Hello");
        }
    );
</code>```

HTML (item is a dot created in css, 20px):

```<code><div id="funded_courses">
            <span id="image1" class="dot"></span>
            <span id="image2" class="dot"></span>
            <span id="image3" class="dot"></span>
            <span id="image4" class="dot"></span>
</div>
</code>```

答: Try applying background-color instead of color as this is an image.</p>

Title: How to change item color in javascript?

Body:
How can I change the item color when being clicked in Javascript? Not allowed to change in HTML nor CSS.

Tried this but not working:

$("#image1").click(
        function(){
            $(this).css({color:'white'});
        },
        function(){
            $(this).css({color:'black'});
        }
    );

However, it does work when I tried the alert function:

$("#image1").click(
        function(){
            alert("Hello");
        }
    );

HTML (item is a dot created in css, 20px):


问:
how to show timepicker fragment inside another fragment
I've created a custom timepicker fragment by extending dialog fragment. but when I call it from the home fragment the app crashes saying : MainActivity cannot be cast to android.app.TimePickerDialog$OnTimeSetListener

here's my custom timePickerFragment

```<code>public class TimePickerFragment extends DialogFragment{
    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        return new TimePickerDialog(getActivity(), R.style.TimePickerTheme,(TimePickerDialog.OnTimeSetListener) getActivity(),hour,minute,DateFormat.is24HourFormat(getActivity()));
    }
}
</code>```

here's from where I'm calling this fragment:

```<code>public class HomeFragment extends Fragment implements AlarmRecyclerViewListener,TimePickerDialog.OnTimeSetListener{
.
.
.

@Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home,container,false);
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        .
        .
        .
        FloatingActionButton btn = getView().findViewById(R.id.fab_button2);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogFragment timePicker = new TimePickerFragment();
                timePicker.show(getChildFragmentManager(),"time picker");
            }
        });
        @Override
        public void onTimeSet(TimePicker timePicker, int hour, int minute) {
            Log.d("msgg","I'm here");
            Calendar c = Calendar.getInstance();
            c.set(Calendar.HOUR_OF_DAY, hour);
            c.set(Calendar.MINUTE, minute);
            c.set(Calendar.SECOND, 0);
          mAlarmsDBhelperClass.insertAlarm("","⚡","",hour,minute,"ON",0,db);
        startAlarm(c,0,true,hour+minute+1);
       }

}
}
</code>```

答:
Your problem is here

```<code>return new TimePickerDialog(getActivity(), R.style.TimePickerTheme,(TimePickerDialog.OnTimeSetListener) getActivity(),hour,minute,DateFormat.is24HourFormat(getActivity()));
</code>```

you already was implementing TimePickerDialog.OnTimerSetListener in HomeFragment, but in this code you tried to get your listener from parent activity.

I think you should inject your listener object to TimerPickerFragment like below code:

```<code>public class TimePickerFragment extends DialogFragment {
    //Fragments need to empty constructor
    TimePickerFragment(){

    }

    TimePickerFragment(TimePickerDialog.OnTimeSetListener onTimeSetListener){
        this.onTimeSetListener = onTimeSetListener;
    }
    TimePickerDialog.OnTimeSetListener onTimeSetListener;

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        return new TimePickerDialog(getActivity(), R.style.TimePickerTheme,onTimeSetListener,hour,minute, DateFormat.is24HourFormat(getActivity()));
    }
}
</code>```

And in HomeFragment you can create TimePickerFragment instance like below:

```<code>DialogFragment timePicker = new TimePickerFragment(this);

</code>```

Body:
I've created a custom timepicker fragment by extending dialog fragment. but when I call it from the home fragment the app crashes saying : MainActivity cannot be cast to android.app.TimePickerDialog$OnTimeSetListener

here's my custom timePickerFragment

public class TimePickerFragment extends DialogFragment{
    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        return new TimePickerDialog(getActivity(), R.style.TimePickerTheme,(TimePickerDialog.OnTimeSetListener) getActivity(),hour,minute,DateFormat.is24HourFormat(getActivity()));
    }
}

here's from where I'm calling this fragment:

public class HomeFragment extends Fragment implements AlarmRecyclerViewListener,TimePickerDialog.OnTimeSetListener{
.
.
.

@Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home,container,false);
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        .
        .
        .
        FloatingActionButton btn = getView().findViewById(R.id.fab_button2);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogFragment timePicker = new TimePickerFragment();
                timePicker.show(getChildFragmentManager(),"time picker");
            }
        });
        @Override
        public void onTimeSet(TimePicker timePicker, int hour, int minute) {
            Log.d("msgg","I'm here");
            Calendar c = Calendar.getInstance();
            c.set(Calendar.HOUR_OF_DAY, hour);
            c.set(Calendar.MINUTE, minute);
            c.set(Calendar.SECOND, 0);
          mAlarmsDBhelperClass.insertAlarm("","⚡","",hour,minute,"ON",0,db);
        startAlarm(c,0,true,hour+minute+1);
       }

}
}

Body:
Your problem is here

return new TimePickerDialog(getActivity(), R.style.TimePickerTheme,(TimePickerDialog.OnTimeSetListener) getActivity(),hour,minute,DateFormat.is24HourFormat(getActivity()));

you already was implementing TimePickerDialog.OnTimerSetListener in HomeFragment, but in this code you tried to get your listener from parent activity.

I think you should inject your listener object to TimerPickerFragment like below code:

public class TimePickerFragment extends DialogFragment {
    //Fragments need to empty constructor
    TimePickerFragment(){

    }

    TimePickerFragment(TimePickerDialog.OnTimeSetListener onTimeSetListener){
        this.onTimeSetListener = onTimeSetListener;
    }
    TimePickerDialog.OnTimeSetListener onTimeSetListener;

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        return new TimePickerDialog(getActivity(), R.style.TimePickerTheme,onTimeSetListener,hour,minute, DateFormat.is24HourFormat(getActivity()));
    }
}

And in HomeFragment you can create TimePickerFragment instance like below:

DialogFragment timePicker = new TimePickerFragment(this);


问:
How do I add a gui to an already written code?
I am currently working on my Computer Science Internal Assessment and am doing Object-Oriented Programming using java in Netbeans.

I have written the code and the output works as i want it to but I was wondering if there was an easy way to switch from using the output terminal to using a GUI for the user interface.

答:
You are asking to a GUI programming tutorial.

The native GUI of Java is called "Swing" but there are other alternative available.

As an alternative, you may deploy your application on a Java Application server (e.g. "Apache Tomcat") and provide a HTML based web GUI. If you want to go this way, then search for a "Java Servlet" tutorial.

You will then possibly go one step further and use a template engine (like "Freemarker" or "Java Server Faces") instead of producing HTML text by string concatenation.

Now you have the right keywords to google for.

In either case you should know that GUI applications are driven by events. Instead of having loops that ask the user for input, the users clicks on buttons or enters text which is sent to your application by an event handling system. So that means, you will possibly need to rewrite major parts of your program. This will be covered by the tutorials.


问:
How to generate a list with only two 1s and other 0s of the given length?
I have to generate lists that consist of 2 '1's and other elements are '0's. I tried the following code but it does not work:

```<code>count([], _, 0).
count([X|T], X, Y) :- count(T, X, Z), Y is 1+Z.
count([X1|T],X,Z):- X1\=X,count(T,X,Z).

two(X) :- count(X, 1, Counter), Counter =:= 2.
</code>```

Querying length(Vs, 4), Vs ins 0..1, two(Vs). gives nothing.

How to generate such lists properly?
I expect to get something like [1, 1, 0, 0], [1, 0, 1, 0] ... [0, 0, 1, 1].

答:
```<code>twoones(Bs) :-
   Bs ins 0..1,
   sum(Bs, #=, 2).

?- length(Bs,4), twoones(Bs).
   Bs = [_A,_B,_C,_D], clpz:(_A+_B+_C+_D#=2),
      clpz:(_A in 0..1), clpz:(_B in 0..1),
      clpz:(_C in 0..1), clpz:(_D in 0..1).
?- length(Bs,4), twoones(Bs), labeling([], Bs).
   Bs = [0,0,1,1]
;  Bs = [0,1,0,1]
;  Bs = [0,1,1,0]
;  ... .
</code>```

Here, I am using library(clpz) which is the successor to library(clpfd). For simple examples as this, there is not much of a difference.

Body:
I have to generate lists that consist of 2 '1's and other elements are '0's. I tried the following code but it does not work:

count([], _, 0).
count([X|T], X, Y) :- count(T, X, Z), Y is 1+Z.
count([X1|T],X,Z):- X1\=X,count(T,X,Z).

two(X) :- count(X, 1, Counter), Counter =:= 2.

Querying length(Vs, 4), Vs ins 0..1, two(Vs). gives nothing.

How to generate such lists properly?
I expect to get something like [1, 1, 0, 0], [1, 0, 1, 0] ... [0, 0, 1, 1].

Body:
twoones(Bs) :-
   Bs ins 0..1,
   sum(Bs, #=, 2).

?- length(Bs,4), twoones(Bs).
   Bs = [_A,_B,_C,_D], clpz:(_A+_B+_C+_D#=2),
      clpz:(_A in 0..1), clpz:(_B in 0..1),
      clpz:(_C in 0..1), clpz:(_D in 0..1).
?- length(Bs,4), twoones(Bs), labeling([], Bs).
   Bs = [0,0,1,1]
;  Bs = [0,1,0,1]
;  Bs = [0,1,1,0]
;  ... .

Here, I am using library(clpz) which is the successor to library(clpfd). For simple examples as this, there is not much of a difference.


问:
Error "undefined reference to" when I compile a C++ code, but the original makefile code compiles
I downloaded a generic AVL implementation from:
http://sourceforge.net/projects/standardavl/files/standardavl/0.1/

The makefile in this project compiles correctly the code. The compiler produces the follow output:

```<code>g++ -pedantic -Wall -O3 -c standardavl.cpp -o standardavl.o
g++ -pedantic -Wall -O3 -c Point.cpp -o Point.o
g++ -o standardavl  standardavl.o Point.o
g++ -o genpoints genpoints.o Point.o
</code>```

The makefile compiles only "standardavl.cpp", because standartavl includes "AvlTree.h" and this file includes "AvlTree.cpp":

standardavl.cpp

```<code>#include "AvlTree.h"
#include "Point.h"
(...)
</code>```

AvlTree.h

```<code>(...)
#include "AvlTree.cpp"
</code>```

In my project I removed the last line (#include "AvlTree.cpp") from the file AvlTree.h and compiled individually that files. I do not use the file "standardavl.cpp" also. I changed the file Point.h to KeyPair.h and implemented all operators there.

My compiler produces the follow output:

```<code>g++ -pedantic -Wall -O3 -c -o ../lib/CPUTimer.o ../lib/CPUTimer.cpp -I. -I../lib
g++ -pedantic -Wall -O3 -c -o ../lib/AvlTree.o ../lib/AvlTree.cpp -I. -I../lib
g++ -pedantic -Wall -O3 -c -o ../lib/keypair.o ../lib/keypair.cpp -I. -I../lib
g++ -pedantic -Wall -O3 -c -o graph.o graph.cpp -I. -I../lib
g++ -pedantic -Wall -O3 -c -o dijkstra.o dijkstra.cpp -I. -I../lib
g++ -pedantic -Wall -O3 -o ../../q1 ../lib/CPUTimer.o ../lib/AvlTree.o ../lib/keypair.o graph.o dijkstra.o questao1.cpp -I. -I../lib
dijkstra.o: In function 'Dijkstra::executeAvl(int)':
dijkstra.cpp:(.text+0x25d): undefined reference to 'AvlTree<KeyPair, std::less<KeyPair>, nil<KeyPair> >::AvlTree()'
(... a lot of errors like above ...)
collect2: ld returned 1 exit status
make[1]: ** [q1] Erro 1
</code>```

What I am doing wrong here?

答:
Assuming AvlTree.h declares a template class AvlTree<>, and AvlTree.cpp defines the implementation:

You can't define the implementation of template code in a separate translation unit (.cpp) -- it must exist where it is used.  That's why they included it in the header.  Putting the implementation in a .cpp file to be included was just a design choice to keep the .h file concise.

(Well, technically you can put the template definition in a separate translation unit, but you must explicitly instantiate it for the template arguments you'll be using.  I'm guessing that's not what you want to do.)

Body:
I downloaded a generic AVL implementation from:
http://sourceforge.net/projects/standardavl/files/standardavl/0.1/

The makefile in this project compiles correctly the code. The compiler produces the follow output:

g++ -pedantic -Wall -O3 -c standardavl.cpp -o standardavl.o
g++ -pedantic -Wall -O3 -c Point.cpp -o Point.o
g++ -o standardavl  standardavl.o Point.o
g++ -o genpoints genpoints.o Point.o

The makefile compiles only "standardavl.cpp", because standartavl includes "AvlTree.h" and this file includes "AvlTree.cpp":

standardavl.cpp

#include "AvlTree.h"
#include "Point.h"
(...)

AvlTree.h

(...)
#include "AvlTree.cpp"

In my project I removed the last line (#include "AvlTree.cpp") from the file AvlTree.h and compiled individually that files. I do not use the file "standardavl.cpp" also. I changed the file Point.h to KeyPair.h and implemented all operators there.

My compiler produces the follow output:

g++ -pedantic -Wall -O3 -c -o ../lib/CPUTimer.o ../lib/CPUTimer.cpp -I. -I../lib
g++ -pedantic -Wall -O3 -c -o ../lib/AvlTree.o ../lib/AvlTree.cpp -I. -I../lib
g++ -pedantic -Wall -O3 -c -o ../lib/keypair.o ../lib/keypair.cpp -I. -I../lib
g++ -pedantic -Wall -O3 -c -o graph.o graph.cpp -I. -I../lib
g++ -pedantic -Wall -O3 -c -o dijkstra.o dijkstra.cpp -I. -I../lib
g++ -pedantic -Wall -O3 -o ../../q1 ../lib/CPUTimer.o ../lib/AvlTree.o ../lib/keypair.o graph.o dijkstra.o questao1.cpp -I. -I../lib
dijkstra.o: In function 'Dijkstra::executeAvl(int)':
dijkstra.cpp:(.text+0x25d): undefined reference to 'AvlTree<KeyPair, std::less<KeyPair>, nil<KeyPair> >::AvlTree()'
(... a lot of errors like above ...)
collect2: ld returned 1 exit status
make[1]: ** [q1] Erro 1

What I am doing wrong here?