问:
Linking Multiple Columns from two tables via Primary Key
I'm working on designing a system of tables that will let me create a small planner of sorts. The planner itself is an HTML table that draws on two different MySQL tables.

The tables are:

```<code>Table_1 (date_id, suggestion_1, suggestion_2, suggestion_3, ...)

Table_2 (song_id, song_title, ...)
</code>```

The "date_id" column of Table 1 is filled with a calendar of, well, dates, each of which has its own group of suggestions. In each row of Table 1, the cells of the suggestion columns are each individually filled with a single identification number ("1293", "1185", "0984") drawn from the "song_id" column in Table 2.

I'm trying to figure out how to generate an HTML table that lists the date and the suggestions, but instead of just numbers, displays the song titles from the second table. (There's other information about the songs that I want to display, too, which is why I've got two tables instead of just 1).

The HTML table should ultimately look like this:

HTML_Table (calendar date, song title a, song title b, song title c)

I'm relatively new to PHP/MySQL, (and self-taught, at that - well, I have a book) so it's taken me most of the day to figure out how I should've defined my issue - I understand now that I need to reference the Primary Key in the second table. My problem is how do I do that? I'm trying to figure out if I should use a JOIN of some kind, but I'm no good at them whatsoever, new as I am.

The book I'm using gave an example function for a specific instance of this, which I modified for my personal use:

```<code>//convert the number of the 1st suggestion into a title
function get_suggest1($suggest_a) {
global $db;
$query = 'SELECT
    song_title
    FROM
    draftsongref
    WHERE
    song_id = ' . $suggest_a;
    $result = mysql_query($query, $db) or die(mysql_error($db));
$row = mysql_fetch_assoc($result);
extract($row);
return $song_title;
}
</code>```

Below that, I also included:

```<code>//retrieve the suggestions for the mass
$query = 'SELECT
    date_id, suggestion_1
FROM
    draft_suggestions
ORDER BY
    date_id ASC';
$result = mysql_query($query, $db) or die (mysql_error($db));
...
// loop through the results
while ($row = mysql_fetch_assoc($result)) {
extract($row);
$suggest1 = get_suggest1($suggest_a);
</code>```

...so I could use the $suggest1 variable to output the specific song_title for the given suggestion. My problem is that, whenever I ran that function, I would receive an error message.

```<code>You have an error in your SQL syntax;
check the manual that corresponds to your
MySQL server version for the right syntax
to use near '' at line 6
</code>```

Now, I've so far managed to figure out that it's referring to this:

```<code>WHERE
    song_id = ' . $suggest_a;
</code>```

And, more specifically, to the " = ' . $suggest_a;" part, but I simply can't figure out how to fix that particular issue. Maybe its an assumption of mine (does it matter if the variable argument $suggest_a have a certain name?), or maybe its an error in the function's design - when I used the original example, it worked, though the original argument/variable had had no other correspondant.

Now, I understand that's a fair bit different than the JOIN table I mentioned, but that's the closest I've been able to come to figuring out how to aciheve this. Any help granted would be appreciated.

答:
Well, this is embarrassing - I've solved my own problem. It wasn't a function definition issue, per se, so much as it was an output issue.

```<code>// loop through the results
while ($row = mysql_fetch_assoc($result)) {
extract($row);
$suggest1 = get_suggest1($suggest_a);
</code>```

I was mistakenly using the same argument variable from defining the function ($suggest_a) rather than doing anything with any queried information.

```<code>//retrieve the suggestions
$query = 'SELECT
    date_id, suggestion_1
FROM
    draft_suggestions
ORDER BY
    date_id ASC';
$result = mysql_query($query, $db) or die (mysql_error($db));
</code>```

I should've instead dropped the proper column's variable into the use of the function:

```<code>// loop through the results
while ($row = mysql_fetch_assoc($result)) {
extract($row);
$suggest1 = get_suggest1($suggestion_1);
</code>```

It didn't work because it had nothing to output. Once I gave it something to use, it worked fine.

In any case, thank you to Jim Garrison for the tips on table structure - I'll be sure to take advantage of that the next time this comes up.

Body:
I'm working on designing a system of tables that will let me create a small planner of sorts. The planner itself is an HTML table that draws on two different MySQL tables.

The tables are:

Table_1 (date_id, suggestion_1, suggestion_2, suggestion_3, ...)

Table_2 (song_id, song_title, ...)

The "date_id" column of Table 1 is filled with a calendar of, well, dates, each of which has its own group of suggestions. In each row of Table 1, the cells of the suggestion columns are each individually filled with a single identification number ("1293", "1185", "0984") drawn from the "song_id" column in Table 2.

I'm trying to figure out how to generate an HTML table that lists the date and the suggestions, but instead of just numbers, displays the song titles from the second table. (There's other information about the songs that I want to display, too, which is why I've got two tables instead of just 1).

The HTML table should ultimately look like this:

HTML_Table (calendar date, song title a, song title b, song title c)

I'm relatively new to PHP/MySQL, (and self-taught, at that - well, I have a book) so it's taken me most of the day to figure out how I should've defined my issue - I understand now that I need to reference the Primary Key in the second table. My problem is how do I do that? I'm trying to figure out if I should use a JOIN of some kind, but I'm no good at them whatsoever, new as I am.

The book I'm using gave an example function for a specific instance of this, which I modified for my personal use:

//convert the number of the 1st suggestion into a title
function get_suggest1($suggest_a) {
global $db;
$query = 'SELECT
    song_title
    FROM
    draftsongref
    WHERE
    song_id = ' . $suggest_a;
    $result = mysql_query($query, $db) or die(mysql_error($db));
$row = mysql_fetch_assoc($result);
extract($row);
return $song_title;
}

Below that, I also included:

//retrieve the suggestions for the mass
$query = 'SELECT
    date_id, suggestion_1
FROM
    draft_suggestions
ORDER BY
    date_id ASC';
$result = mysql_query($query, $db) or die (mysql_error($db));
...
// loop through the results
while ($row = mysql_fetch_assoc($result)) {
extract($row);
$suggest1 = get_suggest1($suggest_a);

...so I could use the $suggest1 variable to output the specific song_title for the given suggestion. My problem is that, whenever I ran that function, I would receive an error message.

You have an error in your SQL syntax;
check the manual that corresponds to your
MySQL server version for the right syntax
to use near '' at line 6

Now, I've so far managed to figure out that it's referring to this:

WHERE
    song_id = ' . $suggest_a;

And, more specifically, to the " = ' . $suggest_a;" part, but I simply can't figure out how to fix that particular issue. Maybe its an assumption of mine (does it matter if the variable argument $suggest_a have a certain name?), or maybe its an error in the function's design - when I used the original example, it worked, though the original argument/variable had had no other correspondant.

Now, I understand that's a fair bit different than the JOIN table I mentioned, but that's the closest I've been able to come to figuring out how to aciheve this. Any help granted would be appreciated.

Body:
Well, this is embarrassing - I've solved my own problem. It wasn't a function definition issue, per se, so much as it was an output issue.

// loop through the results
while ($row = mysql_fetch_assoc($result)) {
extract($row);
$suggest1 = get_suggest1($suggest_a);

I was mistakenly using the same argument variable from defining the function ($suggest_a) rather than doing anything with any queried information.

//retrieve the suggestions
$query = 'SELECT
    date_id, suggestion_1
FROM
    draft_suggestions
ORDER BY
    date_id ASC';
$result = mysql_query($query, $db) or die (mysql_error($db));

I should've instead dropped the proper column's variable into the use of the function:

// loop through the results
while ($row = mysql_fetch_assoc($result)) {
extract($row);
$suggest1 = get_suggest1($suggestion_1);

It didn't work because it had nothing to output. Once I gave it something to use, it worked fine.

In any case, thank you to Jim Garrison for the tips on table structure - I'll be sure to take advantage of that the next time this comes up.


来源: stackexchange

问:
Python Lambda Function not producing an output for AWS Eventbridge
Basically, I use this Example Python code snippet for Slack from an example python Lambda function provided by aws.

```<code>#!/usr/bin/python3.6
import urllib3
import json
http = urllib3.PoolManager()
def lambda_handler(event, context):
    url = "https://hooks.slack.com/services/xxxxxxx"
    msg = {
        "channel": "aws-events",
        "username": "Event_Notifier",
        "text": event['Records'][0]['Sns']['Message'],
        "icon_emoji": ""
    }

    encoded_msg = json.dumps(msg).encode('utf-8')
    resp = http.request('POST',url, body=encoded_msg)
    print({
        "message": event['Records'][0]['Sns']['Message'],
        "status_code": resp.status,
        "response": resp.data
    })
</code>```

Unfortunately, the above code does not produce any output and does not send messages to the slack channel.

So we made some adjustment as follows, and now it sends a generic message(that we set) always whenever there is an event, but not a meaningful message for the team and it does not help really to find the correct event on the message itself. The team have to go to the aws control panel each time to check what event the trigger was for.

```<code>#!/usr/bin/python3.6
import urllib3
import json
http = urllib3.PoolManager()
def lambda_handler(event, context):
    print(event)
    url = "https://hooks.slack.com/services/xxxxxxx"
    msg = {
        "channel": "aws-events",
        "username": "Event_Notifier",
        #"text": event['Records'][0]['Sns']['Message'],
        "text": "Upcoming Events, check here https://phd.aws.amazon.com/phd/home?region=eu-west-1#/event-log",
        "icon_emoji": ""
    }

    encoded_msg = json.dumps(msg).encode('utf-8')
    resp = http.request('POST',url, body=encoded_msg)
    print({
        #"message": event['Records'][0]['Sns']['Message'],
        "message": "Upcoming Events, check here https://phd.aws.amazon.com/phd/home?region=eu-west-1#/event-log",
        "status_code": resp.status,
        "response": resp.data
    })
</code>```

Now, we have made further changes, but it stopped fully now.

```<code>#!/usr/bin/python3.6
import urllib3
import json
http = urllib3.PoolManager()

def lambda_handler(event, context):
    print(event)
    url = "https://hooks.slack.com/services/xxxxxxx"
    last_event = event['Records'][0]['Sns']['Message']

    msg = {
        "channel": "aws-events",
        "username": "Event_Notifier",
        "text": "Upcoming Events, check here https://phd.aws.amazon.com/phd/home?region=eu-west-1#/event-log" + "```\n" + str(last_event) + "\n```",
        "icon_emoji": ""
    }

    encoded_msg = json.dumps(msg).encode('utf-8')
    resp = http.request('POST',url, body=encoded_msg)

    print({
        "message": "Upcoming Events, check here https://phd.aws.amazon.com/phd/home?region=eu-west-1#/event-log" + "```\n" + str(last_event) + "\n```",
        "status_code": resp.status,
        "response": resp.data
    })
</code>```

Now it is going clueless how to make it properly work with the Amazon EventBridge.

答:
Let me know if you are doing a similar type of this:

https://www.cloudkaramchari.com/blog/receive-email-in-aws-ses-and-save-in-dynamodb/

If yes, then we can customise your lambda to achieve the goal.

ContentLicense: CC BY-SA 4.0

Body:
Basically, I use this Example Python code snippet for Slack from an example python Lambda function provided by aws.

#!/usr/bin/python3.6
import urllib3
import json
http = urllib3.PoolManager()
def lambda_handler(event, context):
    url = "https://hooks.slack.com/services/xxxxxxx"
    msg = {
        "channel": "aws-events",
        "username": "Event_Notifier",
        "text": event['Records'][0]['Sns']['Message'],
        "icon_emoji": ""
    }

    encoded_msg = json.dumps(msg).encode('utf-8')
    resp = http.request('POST',url, body=encoded_msg)
    print({
        "message": event['Records'][0]['Sns']['Message'],
        "status_code": resp.status,
        "response": resp.data
    })

Unfortunately, the above code does not produce any output and does not send messages to the slack channel.

So we made some adjustment as follows, and now it sends a generic message(that we set) always whenever there is an event, but not a meaningful message for the team and it does not help really to find the correct event on the message itself. The team have to go to the aws control panel each time to check what event the trigger was for.

#!/usr/bin/python3.6
import urllib3
import json
http = urllib3.PoolManager()
def lambda_handler(event, context):
    print(event)
    url = "https://hooks.slack.com/services/xxxxxxx"
    msg = {
        "channel": "aws-events",
        "username": "Event_Notifier",
        #"text": event['Records'][0]['Sns']['Message'],
        "text": "Upcoming Events, check here https://phd.aws.amazon.com/phd/home?region=eu-west-1#/event-log",
        "icon_emoji": ""
    }

    encoded_msg = json.dumps(msg).encode('utf-8')
    resp = http.request('POST',url, body=encoded_msg)
    print({
        #"message": event['Records'][0]['Sns']['Message'],
        "message": "Upcoming Events, check here https://phd.aws.amazon.com/phd/home?region=eu-west-1#/event-log",
        "status_code": resp.status,
        "response": resp.data
    })

Now, we have made further changes, but it stopped fully now.

#!/usr/bin/python3.6
import urllib3
import json
http = urllib3.PoolManager()

def lambda_handler(event, context):
    print(event)
    url = "https://hooks.slack.com/services/xxxxxxx"
    last_event = event['Records'][0]['Sns']['Message']

    msg = {
        "channel": "aws-events",
        "username": "Event_Notifier",
        "text": "Upcoming Events, check here https://phd.aws.amazon.com/phd/home?region=eu-west-1#/event-log" + "```\n" + str(last_event) + "\n```",
        "icon_emoji": ""
    }

    encoded_msg = json.dumps(msg).encode('utf-8')
    resp = http.request('POST',url, body=encoded_msg)

    print({
        "message": "Upcoming Events, check here https://phd.aws.amazon.com/phd/home?region=eu-west-1#/event-log" + "```\n" + str(last_event) + "\n```",
        "status_code": resp.status,
        "response": resp.data
    })

Now it is going clueless how to make it properly work with the Amazon EventBridge.


问:
Javascript selecting nth element but excluding some elements
Consider the following markup:

```<code><div class="body">
     <p>...<p>
     <p>...<p>
     <blockquote>
          <p>...<p>
     </blockquote>
     <p>...<p>
     <p>...<p>
</div>
</code>```

I want to select the first
 element. I can do this with:

```<code>$( ".body p:nth-child(1)
</code>```

However if I wanted to select the 3rd
 (excluding the blockquote) this will not work:

```<code>$( ".body p:nth-child(3)
</code>```

I tried using nth-type, but if I do:

```<code>$( ".body p:nth-of-type(1)
</code>```

It will select the first
 in the body and also the next p in block quote.

I need to be able to exclude or ignore the blockquote. Would it work if I read the dom into a variable and removed the blockquote before calling nth-child?

答:
If you just want to get the nth-direct child of an element with a specific tag (doesn't work with classnames, ids etc.) you can use :nth-of-type. Example:

$(".body p:nth-of-type(3)")[0].textContent = "Here";```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="body">
  <p>...</p>
  <p>...</p>
  <blockquote>
    <p>...</p>
  </blockquote>
  <p>...</p>
  <p>...</p>
</div></code>```

Unfortunately you can't yet get the nth element specifying a certain condition with pure css selectors, however you could just get the 3rd element of the array. Example:

$(".body p")[2].textContent = "Changed Overall 3rd";
$(".body>p")[2].textContent = "Changed Direct 3rd";```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="body">
  <p>...</p>
  <p>...</p>
  <blockquote>
    <p>...</p>
  </blockquote>
  <p>...</p>
  <p>...</p>
</div></code>```

Body:
Consider the following markup:

...

...

...

...

...

I want to select the first
 element. I can do this with:

$( ".body p:nth-child(1)

However if I wanted to select the 3rd
 (excluding the blockquote) this will not work:

$( ".body p:nth-child(3)

I tried using nth-type, but if I do:

$( ".body p:nth-of-type(1)

It will select the first
 in the body and also the next p in block quote.

I need to be able to exclude or ignore the blockquote. Would it work if I read the dom into a variable and removed the blockquote before calling nth-child?

Body:
If you just want to get the nth-direct child of an element with a specific tag (doesn't work with classnames, ids etc.) you can use :nth-of-type. Example:

$(".body p:nth-of-type(3)")[0].textContent = "Here";

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="body">
  <p>...</p>
  <p>...</p>
  <blockquote>
    <p>...</p>
  </blockquote>
  <p>...</p>
  <p>...</p>
</div>

Unfortunately you can't yet get the nth element specifying a certain condition with pure css selectors, however you could just get the 3rd element of the array. Example:

$(".body p")[2].textContent = "Changed Overall 3rd";
$(".body>p")[2].textContent = "Changed Direct 3rd";

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="body">
  <p>...</p>
  <p>...</p>
  <blockquote>
    <p>...</p>
  </blockquote>
  <p>...</p>
  <p>...</p>
</div>


问:
How can i pause media player when the device is locekd
Hello right now when I'm playing the media player and if the device is locked it still continue playing the audio I want that when the  screen is off the media player to pause  also when the app is running in the background ( onPause )

what can I do

MainActivity.java  // The audio play onClick is in the last

```<code>public class MainActivity extends AppCompatActivity {
    MediaPlayer player1;
    MediaPlayer player2;
    SeekBar seekBar1;
    SeekBar seekBar2;
    TextView elapsedTimeLable1;
    TextView elapsedTimeLable2;
    TextView remainingTimeLable1;
    TextView remainingTimeLable2;
    ImageView play1;
    ImageView play2;
    int totalTime1;
    int totalTime2;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // PlayButton    *  The ButtonClick is in the last if you want to jump directly there  *

        play1 = findViewById(R.id.playbtn1);
        play2 = findViewById(R.id.playbtn2);

        // TimeLables

        elapsedTimeLable1 = findViewById(R.id.cTime1);
        elapsedTimeLable2 = findViewById(R.id.cTime2);
        remainingTimeLable1 = findViewById(R.id.tTime1);
        remainingTimeLable2 = findViewById(R.id.tTime2);

        // MediaPlayer

        player1 = MediaPlayer.create(this, R.raw.dog_howl);
        player1.setLooping(true);
        player1.seekTo(0);
        totalTime1 = player1.getDuration();
        player2 = MediaPlayer.create(this, R.raw.dog_bark);
        player2.setLooping(true);
        player2.seekTo(0);
        totalTime2 = player2.getDuration();

        //SeekBar

        seekBar1 = findViewById(R.id.seekbar1);
        seekBar2 = findViewById(R.id.seekbar2);
        seekBar1.setMax(totalTime1);
        seekBar2.setMax(totalTime2);

        seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress1, boolean fromUser1) {
                if (fromUser1) {
                    player1.seekTo(progress1);
                    seekBar1.setProgress(progress1);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress2, boolean fromUser2) {
                if (fromUser2) {
                    player2.seekTo(progress2);
                    seekBar2.setProgress(progress2);
                }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        // Thread (Update SeekBar & TimeLabel)
        new Thread(() -> {
            while (player1 != null) {
                try {
                    Message msg = new Message();
                    msg.what = player1.getCurrentPosition();
                    handler1.sendMessage(msg);
                    Thread.sleep(1000);
                } catch (InterruptedException ignored) {

                }
            }
        }).start();

        new Thread(() -> {
            while (player2 != null) {
                try {
                    Message msg = new Message();
                    msg.what = player2.getCurrentPosition();
                    handler2.sendMessage(msg);
                    Thread.sleep(1000);
                } catch (InterruptedException ignored) {

                }
            }
        }).start();

        // Admob Banner Ad

        MobileAds.initialize(this, initializationStatus -> {
        });

        AdView mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

        // Caution dialog

        SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
        boolean firstStart = preferences.getBoolean("firstStart", true);
        if (firstStart) {

            showDialog();
        }

    }

    // Caution dialog
    private void showDialog() {
        new AlertDialog.Builder(this)
                .setTitle("Caution!")
                .setMessage("In case you're wearing any kind of headphones please remove it before playing the ' Howl ' audio")
                .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .create().show();
        SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("firstStart", false);
        editor.apply();
    }

    @SuppressLint("HandlerLeak")
    private final Handler handler1 = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(@NonNull Message msg) {
            int currentPosition1 = msg.what;
            //Update SeekBar
            seekBar1.setProgress(currentPosition1);
            // Update Timelable
            String elapsedTime1 = createTimerLable1(currentPosition1);
            elapsedTimeLable1.setText(elapsedTime1);
            String remainingTime1 = createTimerLable1(totalTime1 - currentPosition1);
            remainingTimeLable1.setText("- " + remainingTime1);

        }
    };
    @SuppressLint("HandlerLeak")
    private final Handler handler2 = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(@NonNull Message msg) {
            int currentPosition2 = msg.what;
            // Update SeekBar
            seekBar2.setProgress(currentPosition2);
            // Update Timelable
            String elapsedTime2 = createTimerLable2(currentPosition2);
            elapsedTimeLable2.setText(elapsedTime2);
            String remainingTime2 = createTimerLable2(totalTime2 - currentPosition2);
            remainingTimeLable2.setText("- " + remainingTime2);

        }
    };

    public String createTimerLable1(int duration) {
        String timerLabel1 = "";
        int min = duration / 1000 / 60;
        int sec = duration / 1000 % 60;
        timerLabel1 += min + ":";
        if (sec < 10) timerLabel1 += "0";
        timerLabel1 += sec;
        return timerLabel1;

    }

    public String createTimerLable2(int duration) {
        String timerLabel2 = "";
        int min = duration / 1000 / 60;
        int sec = duration / 1000 % 60;
        timerLabel2 += min + ":";
        if (sec < 10) timerLabel2 += "0";
        timerLabel2 += sec;
        return timerLabel2;

    }

    public void playBtnClick1(View view) {

        if (player2.isPlaying()) {
            player2.pause();
            play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

        if (!player1.isPlaying()) {
            // Stoping
            player1.start();
            play1.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
        } else {
            // Playing
            player1.pause();
            play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

    }

    public void playBtnClick2(View view) {

        if (player1.isPlaying()) {
            player1.pause();
            play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

        if (!player2.isPlaying()) {
            // Stoping
            player2.start();
            play2.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
        } else {
            // Playing
            player2.pause();
            play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

    }

}
</code>```

答:
Try to pause it onPause() function as follows</p>
```<code> @Override
    protected void onPause() {
        super.onPause();

        if (player1!= null) {
            player1.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (player1!= null) {
            player1.start();
        }
    }
</code>```

Body:
Hello right now when I'm playing the media player and if the device is locked it still continue playing the audio I want that when the  screen is off the media player to pause  also when the app is running in the background ( onPause )

what can I do

MainActivity.java  // The audio play onClick is in the last

public class MainActivity extends AppCompatActivity {
    MediaPlayer player1;
    MediaPlayer player2;
    SeekBar seekBar1;
    SeekBar seekBar2;
    TextView elapsedTimeLable1;
    TextView elapsedTimeLable2;
    TextView remainingTimeLable1;
    TextView remainingTimeLable2;
    ImageView play1;
    ImageView play2;
    int totalTime1;
    int totalTime2;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // PlayButton    *  The ButtonClick is in the last if you want to jump directly there  *

        play1 = findViewById(R.id.playbtn1);
        play2 = findViewById(R.id.playbtn2);

        // TimeLables

        elapsedTimeLable1 = findViewById(R.id.cTime1);
        elapsedTimeLable2 = findViewById(R.id.cTime2);
        remainingTimeLable1 = findViewById(R.id.tTime1);
        remainingTimeLable2 = findViewById(R.id.tTime2);

        // MediaPlayer

        player1 = MediaPlayer.create(this, R.raw.dog_howl);
        player1.setLooping(true);
        player1.seekTo(0);
        totalTime1 = player1.getDuration();
        player2 = MediaPlayer.create(this, R.raw.dog_bark);
        player2.setLooping(true);
        player2.seekTo(0);
        totalTime2 = player2.getDuration();

        //SeekBar

        seekBar1 = findViewById(R.id.seekbar1);
        seekBar2 = findViewById(R.id.seekbar2);
        seekBar1.setMax(totalTime1);
        seekBar2.setMax(totalTime2);

        seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress1, boolean fromUser1) {
                if (fromUser1) {
                    player1.seekTo(progress1);
                    seekBar1.setProgress(progress1);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress2, boolean fromUser2) {
                if (fromUser2) {
                    player2.seekTo(progress2);
                    seekBar2.setProgress(progress2);
                }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        // Thread (Update SeekBar & TimeLabel)
        new Thread(() -> {
            while (player1 != null) {
                try {
                    Message msg = new Message();
                    msg.what = player1.getCurrentPosition();
                    handler1.sendMessage(msg);
                    Thread.sleep(1000);
                } catch (InterruptedException ignored) {

                }
            }
        }).start();

        new Thread(() -> {
            while (player2 != null) {
                try {
                    Message msg = new Message();
                    msg.what = player2.getCurrentPosition();
                    handler2.sendMessage(msg);
                    Thread.sleep(1000);
                } catch (InterruptedException ignored) {

                }
            }
        }).start();

        // Admob Banner Ad

        MobileAds.initialize(this, initializationStatus -> {
        });

        AdView mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

        // Caution dialog

        SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
        boolean firstStart = preferences.getBoolean("firstStart", true);
        if (firstStart) {

            showDialog();
        }

    }

    // Caution dialog
    private void showDialog() {
        new AlertDialog.Builder(this)
                .setTitle("Caution!")
                .setMessage("In case you're wearing any kind of headphones please remove it before playing the ' Howl ' audio")
                .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .create().show();
        SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("firstStart", false);
        editor.apply();
    }

    @SuppressLint("HandlerLeak")
    private final Handler handler1 = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(@NonNull Message msg) {
            int currentPosition1 = msg.what;
            //Update SeekBar
            seekBar1.setProgress(currentPosition1);
            // Update Timelable
            String elapsedTime1 = createTimerLable1(currentPosition1);
            elapsedTimeLable1.setText(elapsedTime1);
            String remainingTime1 = createTimerLable1(totalTime1 - currentPosition1);
            remainingTimeLable1.setText("- " + remainingTime1);

        }
    };
    @SuppressLint("HandlerLeak")
    private final Handler handler2 = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(@NonNull Message msg) {
            int currentPosition2 = msg.what;
            // Update SeekBar
            seekBar2.setProgress(currentPosition2);
            // Update Timelable
            String elapsedTime2 = createTimerLable2(currentPosition2);
            elapsedTimeLable2.setText(elapsedTime2);
            String remainingTime2 = createTimerLable2(totalTime2 - currentPosition2);
            remainingTimeLable2.setText("- " + remainingTime2);

        }
    };

    public String createTimerLable1(int duration) {
        String timerLabel1 = "";
        int min = duration / 1000 / 60;
        int sec = duration / 1000 % 60;
        timerLabel1 += min + ":";
        if (sec < 10) timerLabel1 += "0";
        timerLabel1 += sec;
        return timerLabel1;

    }

    public String createTimerLable2(int duration) {
        String timerLabel2 = "";
        int min = duration / 1000 / 60;
        int sec = duration / 1000 % 60;
        timerLabel2 += min + ":";
        if (sec < 10) timerLabel2 += "0";
        timerLabel2 += sec;
        return timerLabel2;

    }

    public void playBtnClick1(View view) {

        if (player2.isPlaying()) {
            player2.pause();
            play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

        if (!player1.isPlaying()) {
            // Stoping
            player1.start();
            play1.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
        } else {
            // Playing
            player1.pause();
            play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

    }

    public void playBtnClick2(View view) {

        if (player1.isPlaying()) {
            player1.pause();
            play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

        if (!player2.isPlaying()) {
            // Stoping
            player2.start();
            play2.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
        } else {
            // Playing
            player2.pause();
            play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

    }

}

Body:
Try to pause it onPause() function as follows

 @Override
    protected void onPause() {
        super.onPause();

        if (player1!= null) {
            player1.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (player1!= null) {
            player1.start();
        }
    }


问:
Using paste and sum inside a for-loop
I need to compare a character string to multiple others and tried to do it the following way:

```<code>empty = character(0)
ps_2 = c("h2","h3")
ps_3 = c("h3", "h4")
visible = ("h2")

i = 2
ps_t = empty
ps_t <- append(ps_t, sum(visible %in% paste("ps_", i, sep="")))
</code>```

With the intention to write a loop instead of i = 2, in order to cycle trough ps_2,ps_3,...

However I think it's not working since the paste() command returns a string instead of the character string with the name: ps_2.
How can I fix this?

Thanks for the time and effort!

Kind regards,

A fellow datafanatic!

答:
The function you need is get(), which gets the value of the object.

```<code>ps_t <- ps_t = NULL

sapply(2:3, function(i) append(ps_t, sum(visible %in% get(paste0("ps_", i)))))
</code>```

Or simply:

```<code>sapply(2:3, function(i) sum(visible %in% get(paste0("ps_", i))))
</code>```

Output

```<code>[1] 1 0
</code>```

Title: Using paste and sum inside a for-loop

Body:
I need to compare a character string to multiple others and tried to do it the following way:

empty = character(0)
ps_2 = c("h2","h3")
ps_3 = c("h3", "h4")
visible = ("h2")

i = 2
ps_t = empty
ps_t <- append(ps_t, sum(visible %in% paste("ps_", i, sep="")))

With the intention to write a loop instead of i = 2, in order to cycle trough ps_2,ps_3,...

However I think it's not working since the paste() command returns a string instead of the character string with the name: ps_2.
How can I fix this?

Thanks for the time and effort!

Kind regards,

A fellow datafanatic!

Body:
The function you need is get(), which gets the value of the object.

ps_t <- ps_t = NULL

sapply(2:3, function(i) append(ps_t, sum(visible %in% get(paste0("ps_", i)))))

Or simply:

sapply(2:3, function(i) sum(visible %in% get(paste0("ps_", i))))

Output

[1] 1 0


问:
DB2 Community edition on higher core count server
If I run DB2 community edition on a higher core count server will IBM want to charge me for more cores or will the software simply use only 4 cores and 16gb of memory?</p>

答:
unlike ORACLE, IBM DB2 manage the licence limit in their code. the database will never use more memory nor more CPU that you licence allow.

you can use it safely :)


问:
Writing a query for Ivanti database survey
I wrote a query to help output the survey questions on a database within a particular time frame but it keeps giving me an error. The code is:

SELECT *
FROM FRS_SURVEYRESULTS
WHERE Identifier = (SELECT RecId
                    FROM Incident
                    WHERE ClosedDateTime BETWEEN '2021-01-30 12:46:56.270' AND '2022-01-30 12:46:56.270');
```

The error it gives me is

What I'm trying to achieve is to output all the FRS_SURVEYRESULTS within that time range.

答:
use this for One RecId

```<code>select * from FRS_SURVEYRESULTS
where Identifier = (select top 1 RecId FROM Incident
                    WHERE ClosedDateTime BETWEEN
                    '2021-01-30 12:46:56.270' AND '2022-01-30 12:46:56.270')
</code>```

use this For All RecId

```<code>
select * from FRS_SURVEYRESULTS
where Identifier in (select RecId FROM Incident
                      WHERE ClosedDateTime BETWEEN
                      '2021-01-30 12:46:56.270' AND '2022-01-30 12:46:56.270')

</code>```

Body:
I wrote a query to help output the survey questions on a database within a particular time frame but it keeps giving me an error. The code is:

SELECT *
FROM FRS_SURVEYRESULTS
WHERE Identifier = (SELECT RecId
                    FROM Incident
                    WHERE ClosedDateTime BETWEEN '2021-01-30 12:46:56.270' AND '2022-01-30 12:46:56.270');

The error it gives me is

What I'm trying to achieve is to output all the FRS_SURVEYRESULTS within that time range.

Body:
use this for One RecId

select * from FRS_SURVEYRESULTS
where Identifier = (select top 1 RecId FROM Incident
                    WHERE ClosedDateTime BETWEEN
                    '2021-01-30 12:46:56.270' AND '2022-01-30 12:46:56.270')

use this For All RecId

select * from FRS_SURVEYRESULTS
where Identifier in (select RecId FROM Incident
                      WHERE ClosedDateTime BETWEEN
                      '2021-01-30 12:46:56.270' AND '2022-01-30 12:46:56.270')


问:
Retrieve results only where ALL keywords match Laravel
I am trying to pull users based on their tags where ALL keywords match.

Take this working code:

```<code>$search_terms = array('keyword 1', 'keyword 2', 'keyword 3', 'keyword 4');

$search_results = User::where('user_type_id', 1)
    ->where('approved', 1)
    ->whereHas('tags', function ($q) use($search_terms) {
        $q->whereIn('name', $search_terms);
    })->get();
</code>```

At the minute I am using whereIn() to do this, but it will pull users even if they have 1 match out of all the inputted keywords. So if we have keyword 1, keyword 2, keyword 3, keyword 4. The query should only pull results where ALL the keywords are matched in the tags table for a given user.

答:
I think this will work, could you please check</p>
```<code>$search_terms = array('keyword 1', 'keyword 2', 'keyword 3', 'keyword 4');

$search_results = User::where('user_type_id', 1)
    ->where('approved', 1)
    ->whereHas("tags", function($q) use ($search_terms) {
        $q->whereIn("name", $search_terms);
        }, "=", count($search_terms));
    ->get();
</code>```

Body:
I am trying to pull users based on their tags where ALL keywords match.

Take this working code:

$search_terms = array('keyword 1', 'keyword 2', 'keyword 3', 'keyword 4');

$search_results = User::where('user_type_id', 1)
    ->where('approved', 1)
    ->whereHas('tags', function ($q) use($search_terms) {
        $q->whereIn('name', $search_terms);
    })->get();

At the minute I am using whereIn() to do this, but it will pull users even if they have 1 match out of all the inputted keywords. So if we have keyword 1, keyword 2, keyword 3, keyword 4. The query should only pull results where ALL the keywords are matched in the tags table for a given user.

Body:
I think this will work, could you please check

$search_terms = array('keyword 1', 'keyword 2', 'keyword 3', 'keyword 4');

$search_results = User::where('user_type_id', 1)
    ->where('approved', 1)
    ->whereHas("tags", function($q) use ($search_terms) {
        $q->whereIn("name", $search_terms);
        }, "=", count($search_terms));
    ->get();


问:
ERROR: "(" is not valid at this position for this server version, expecting an indentifier
ERROR STATEMENT:

CALCULATE_LATE_FEE_AND_TAX(:NEW.ACT_RET_DT_TIME, :NEW.RET_DT_TIME,
:NEW.REG_NUM,:NEW.AMOUNT, totalLateFee, totalTax)

THE WHOLE CODE IS:

```<code>CREATE TRIGGER GENERATE_BILLING
AFTER
UPDATE
    ON BOOKING_DETAILS FOR EACH ROW BEGIN IF (
        IFNULL(TO_CHAR(NEW.ACT_RET_DT_TIME), 'NULL') <> 'NULL'
        AND NEW.BOOKING_STATUS = 'R'
    ) THEN BEGIN DECLARE lastBillId VARCHAR(45);DECLARE newBillId VARCHAR(45);DECLARE discountAmt DECIMAL(19, 4);DECLARE totalLateFee VARCHAR(4000);DECLARE totalTax DECIMAL(19, 4);DECLARE totalAmountBeforeDiscount DECIMAL(19, 4);DECLARE finalAmount DECIMAL(19, 4);
SELECT
    BILL_ID INTO lastBillId
FROM
    (
        SELECT
            BILL_ID,
            ROWNUM AS RN
        FROM
            BILLING_DETAILS
    )
WHERE
    RN = (
        SELECT
            MAX(ROWNUM)
        FROM
            BILLING_DETAILS
    );
SET
    newBillId = CONCAT(
        'BL',
        IFNULL(TO_CHAR(TO_NUMBER(SUBSTR(lastBillId, 3)) + 1), '')
    );CALCULATE_LATE_FEE_AND_TAX(
        NEW.ACT_RET_DT_TIME,
        NEW.RET_DT_TIME,
        NEW.REG_NUM,
        NEW.AMOUNT,
        totalLateFee,
        totalTax
    );
SET
    totalAmountBeforeDiscount = NEW.AMOUNT + totalLateFee + totalTax;CALCULATE_DISCOUNT_AMOUNT(
        NEW.DL_NUM,
        totalAmountBeforeDiscount,
        NEW.DISCOUNT_CODE,
        discountAmt
    );
SET
    finalAmount = totalAmountBeforeDiscount - discountAmt;
INSERT INTO
    BILLING_DETAILS (
        BILL_ID,
        BILL_DATE,
        BILL_STATUS,
        DISCOUNT_AMOUNT,
        TOTAL_AMOUNT,
        TAX_AMOUNT,
        BOOKING_ID,
        TOTAL_LATE_FEE
    )
VALUES
    (
        newBillId,
        str_to_date(SYSDATE(), '%Y-%m-%d'),
        'P',
        discountAmt,
        finalAmount,
        totalTax,
        NEW.BOOKING_ID,
        totalLateFee
    );
END;
</code>```

答:
You have a number of errors including the function invocation and the missing end and missing end if;

I have no idea what your trigger is supposed to do but this synataxes.

```<code>DROP TRIGGER IF EXISTS T;
DELIMITER $$

CREATE TRIGGER T AFTER UPDATE ON BOOKING_DETAILS
FOR EACH ROW
BEGIN
IF(IFNULL(TO_CHAR(NEW.ACT_RET_DT_TIME), 'NULL') <> 'NULL' AND NEW.BOOKING_STATUS = 'R') THEN
 BEGIN
    DECLARE lastBillId VARCHAR(45);
    DECLARE newBillId VARCHAR(45);
    DECLARE discountAmt DECIMAL(19, 4);
    DECLARE totalLateFee VARCHAR(4000);
    DECLARE totalTax DECIMAL(19, 4);
    DECLARE totalAmountBeforeDiscount DECIMAL(19, 4);
    DECLARE finalAmount DECIMAL(19, 4);
    SELECT BILL_ID INTO lastBillId
    FROM
    (SELECT BILL_ID,
            ROWNUM AS RN
      FROM BILLING_DETAILS
     ) s
    WHERE
    RN = (SELECT
            MAX(ROWNUM)
          FROM BILLING_DETAILS
         );
    SET newBillId = CONCAT('BL',IFNULL(TO_CHAR(TO_NUMBER(SUBSTR(lastBillId, 3)) + 1), ''));

    select CALCULATE_LATE_FEE_AND_TAX(
        NEW.ACT_RET_DT_TIME,
        NEW.RET_DT_TIME,
        NEW.REG_NUM,
        NEW.AMOUNT,
        totalLateFee,
        totalTax
    ) into @a;

    SET totalAmountBeforeDiscount = NEW.AMOUNT + totalLateFee + totalTax;

    select CALCULATE_DISCOUNT_AMOUNT(
        NEW.DL_NUM,
        totalAmountBeforeDiscount,
        NEW.DISCOUNT_CODE,
        discountAmt
    ) into @a;

    sET finalAmount = totalAmountBeforeDiscount - discountAmt;

    INSERT INTO
    BILLING_DETAILS (
        BILL_ID,
        BILL_DATE,
        BILL_STATUS,
        DISCOUNT_AMOUNT,
        TOTAL_AMOUNT,
        TAX_AMOUNT,
        BOOKING_ID,
        TOTAL_LATE_FEE
    )
    VALUES
    (
        newBillId,
        str_to_date(sysdate(), '%Y-%m-%d'),
        'P',
        discountAmt,
        finalAmount,
        totalTax,
        NEW.BOOKING_ID,
        totalLateFee
    );

   end;
end if;
END $$

DELIMITER ;
</code>```

BTW to_char is oracle not mysql and is supect sysdate is too.

Body:
ERROR STATEMENT:

CALCULATE_LATE_FEE_AND_TAX(:NEW.ACT_RET_DT_TIME, :NEW.RET_DT_TIME,
:NEW.REG_NUM,:NEW.AMOUNT, totalLateFee, totalTax)

THE WHOLE CODE IS:

CREATE TRIGGER GENERATE_BILLING
AFTER
UPDATE
    ON BOOKING_DETAILS FOR EACH ROW BEGIN IF (
        IFNULL(TO_CHAR(NEW.ACT_RET_DT_TIME), 'NULL') <> 'NULL'
        AND NEW.BOOKING_STATUS = 'R'
    ) THEN BEGIN DECLARE lastBillId VARCHAR(45);DECLARE newBillId VARCHAR(45);DECLARE discountAmt DECIMAL(19, 4);DECLARE totalLateFee VARCHAR(4000);DECLARE totalTax DECIMAL(19, 4);DECLARE totalAmountBeforeDiscount DECIMAL(19, 4);DECLARE finalAmount DECIMAL(19, 4);
SELECT
    BILL_ID INTO lastBillId
FROM
    (
        SELECT
            BILL_ID,
            ROWNUM AS RN
        FROM
            BILLING_DETAILS
    )
WHERE
    RN = (
        SELECT
            MAX(ROWNUM)
        FROM
            BILLING_DETAILS
    );
SET
    newBillId = CONCAT(
        'BL',
        IFNULL(TO_CHAR(TO_NUMBER(SUBSTR(lastBillId, 3)) + 1), '')
    );CALCULATE_LATE_FEE_AND_TAX(
        NEW.ACT_RET_DT_TIME,
        NEW.RET_DT_TIME,
        NEW.REG_NUM,
        NEW.AMOUNT,
        totalLateFee,
        totalTax
    );
SET
    totalAmountBeforeDiscount = NEW.AMOUNT + totalLateFee + totalTax;CALCULATE_DISCOUNT_AMOUNT(
        NEW.DL_NUM,
        totalAmountBeforeDiscount,
        NEW.DISCOUNT_CODE,
        discountAmt
    );
SET
    finalAmount = totalAmountBeforeDiscount - discountAmt;
INSERT INTO
    BILLING_DETAILS (
        BILL_ID,
        BILL_DATE,
        BILL_STATUS,
        DISCOUNT_AMOUNT,
        TOTAL_AMOUNT,
        TAX_AMOUNT,
        BOOKING_ID,
        TOTAL_LATE_FEE
    )
VALUES
    (
        newBillId,
        str_to_date(SYSDATE(), '%Y-%m-%d'),
        'P',
        discountAmt,
        finalAmount,
        totalTax,
        NEW.BOOKING_ID,
        totalLateFee
    );
END;

Body:
You have a number of errors including the function invocation and the missing end and missing end if;

I have no idea what your trigger is supposed to do but this synataxes.

DROP TRIGGER IF EXISTS T;
DELIMITER $$

CREATE TRIGGER T AFTER UPDATE ON BOOKING_DETAILS
FOR EACH ROW
BEGIN
IF(IFNULL(TO_CHAR(NEW.ACT_RET_DT_TIME), 'NULL') <> 'NULL' AND NEW.BOOKING_STATUS = 'R') THEN
 BEGIN
    DECLARE lastBillId VARCHAR(45);
    DECLARE newBillId VARCHAR(45);
    DECLARE discountAmt DECIMAL(19, 4);
    DECLARE totalLateFee VARCHAR(4000);
    DECLARE totalTax DECIMAL(19, 4);
    DECLARE totalAmountBeforeDiscount DECIMAL(19, 4);
    DECLARE finalAmount DECIMAL(19, 4);
    SELECT BILL_ID INTO lastBillId
    FROM
    (SELECT BILL_ID,
            ROWNUM AS RN
      FROM BILLING_DETAILS
     ) s
    WHERE
    RN = (SELECT
            MAX(ROWNUM)
          FROM BILLING_DETAILS
         );
    SET newBillId = CONCAT('BL',IFNULL(TO_CHAR(TO_NUMBER(SUBSTR(lastBillId, 3)) + 1), ''));

    select CALCULATE_LATE_FEE_AND_TAX(
        NEW.ACT_RET_DT_TIME,
        NEW.RET_DT_TIME,
        NEW.REG_NUM,
        NEW.AMOUNT,
        totalLateFee,
        totalTax
    ) into @a;

    SET totalAmountBeforeDiscount = NEW.AMOUNT + totalLateFee + totalTax;

    select CALCULATE_DISCOUNT_AMOUNT(
        NEW.DL_NUM,
        totalAmountBeforeDiscount,
        NEW.DISCOUNT_CODE,
        discountAmt
    ) into @a;

    sET finalAmount = totalAmountBeforeDiscount - discountAmt;

    INSERT INTO
    BILLING_DETAILS (
        BILL_ID,
        BILL_DATE,
        BILL_STATUS,
        DISCOUNT_AMOUNT,
        TOTAL_AMOUNT,
        TAX_AMOUNT,
        BOOKING_ID,
        TOTAL_LATE_FEE
    )
    VALUES
    (
        newBillId,
        str_to_date(sysdate(), '%Y-%m-%d'),
        'P',
        discountAmt,
        finalAmount,
        totalTax,
        NEW.BOOKING_ID,
        totalLateFee
    );

   end;
end if;
END $$

DELIMITER ;

BTW to_char is oracle not mysql and is supect sysdate is too.


问:
NOT NULL constraint failed: dashboard_profile.user_id
I'm trying to save the last IP of User to the Profile module in Django but I get always NOT NULL constraint failed I know that last_ip should be set tonull=True and I run this commands:py .\manage.py makemigrations and py .\manage.py migrate. if you have any suggestions to save IP to the user that will be helpful for me.

Thanks in advance.

```<code>#models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(blank=True, max_length=150)
    last_ip = models.GenericIPAddressField(null=True, blank=True)
    avatar = ContentTypeRestrictedFileField(max_upload_size=10485760, null=True, verbose_name="",default='default.jpg', blank= True, content_types=['image/png', 'image/jpeg'])

    def __str__(self):
        return self.user.username
</code>```
```<code>#forms.py

class UpdateUserForm(forms.ModelForm):
    username = forms.CharField(max_length=150, required=True)
    first_name = forms.CharField(max_length=150, required=False)
    last_name = forms.CharField(max_length=150, required=False)
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ['username','first_name','last_name','email']

class UpdateAvatarBio(forms.ModelForm):
    avatar = forms.ImageField()
    bio = forms.CharField()
    class Meta:
        model = Profile
        fields = ['avatar', 'last_ip', 'bio']
</code>```
```<code>#views.py
def ip_client(request):
    return (
        x_forwarded_for.split(',')[0]
        if (x_forwarded_for := request.META.get('HTTP_X_FORWARDED_FOR'))
        else request.META.get('REMOTE_ADDR')
    )
def profile(request):
    ip = ip_client(request)
    model = Profile(last_ip=ip)
    model.save() # Traceback suppose here is the issue
    if request.method == 'POST':
    ...
    ...
    return render(request, 'profile.html', {'user_form': user_form, 'profile_form': profile_form})
</code>```

答:
You didn't add the user to Profile before saving it

```<code>def profile(request):
    ip = ip_client(request)
    model = Profile(last_ip=ip)
    moddl.user=request.user      #Add this
    model.save() # Traceback suppose here is the issue
    if request.method == 'POST':
         ...
         ...
   return render(request, 'profile.html', {'user_form': user_form, 'profile_form': profile_form})
</code>```

Edit:
Since the user is OneToOne (which means it is a the primary key), so Your code shall be like this

```<code>def profile(request):
    ip = ip_client(request)
    profile = Profile.objects.get(user=request.user)
    profile.last_ip = ip
    profile.save()
    if request.method == 'POST':
         ...
         ...
   return render(request, 'profile.html', {'user_form': user_form, 'profile_form': profile_form})
</code>```

Body:
I'm trying to save the last IP of User to the Profile module in Django but I get always NOT NULL constraint failed I know that last_ip should be set tonull=True and I run this commands:py .\manage.py makemigrations and py .\manage.py migrate. if you have any suggestions to save IP to the user that will be helpful for me.

Thanks in advance.

#models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(blank=True, max_length=150)
    last_ip = models.GenericIPAddressField(null=True, blank=True)
    avatar = ContentTypeRestrictedFileField(max_upload_size=10485760, null=True, verbose_name="",default='default.jpg', blank= True, content_types=['image/png', 'image/jpeg'])

    def __str__(self):
        return self.user.username

#forms.py

class UpdateUserForm(forms.ModelForm):
    username = forms.CharField(max_length=150, required=True)
    first_name = forms.CharField(max_length=150, required=False)
    last_name = forms.CharField(max_length=150, required=False)
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ['username','first_name','last_name','email']

class UpdateAvatarBio(forms.ModelForm):
    avatar = forms.ImageField()
    bio = forms.CharField()
    class Meta:
        model = Profile
        fields = ['avatar', 'last_ip', 'bio']

#views.py
def ip_client(request):
    return (
        x_forwarded_for.split(',')[0]
        if (x_forwarded_for := request.META.get('HTTP_X_FORWARDED_FOR'))
        else request.META.get('REMOTE_ADDR')
    )
def profile(request):
    ip = ip_client(request)
    model = Profile(last_ip=ip)
    model.save() # Traceback suppose here is the issue
    if request.method == 'POST':
    ...
    ...
    return render(request, 'profile.html', {'user_form': user_form, 'profile_form': profile_form})

Body:
You didn't add the user to Profile before saving it

def profile(request):
    ip = ip_client(request)
    model = Profile(last_ip=ip)
    moddl.user=request.user      #Add this
    model.save() # Traceback suppose here is the issue
    if request.method == 'POST':
         ...
         ...
   return render(request, 'profile.html', {'user_form': user_form, 'profile_form': profile_form})

Edit:
Since the user is OneToOne (which means it is a the primary key), so Your code shall be like this

def profile(request):
    ip = ip_client(request)
    profile = Profile.objects.get(user=request.user)
    profile.last_ip = ip
    profile.save()
    if request.method == 'POST':
         ...
         ...
   return render(request, 'profile.html', {'user_form': user_form, 'profile_form': profile_form})


问:
How to select the right-clicked TreeView node in PopupMenu.OnPopup event-handler?
In a 32-bit VCL Application in Windows 10 in Delphi 11 Alexandria, I have a TreeView (TTreeView descendant), where MultiSelect = False and PopupMenu = PopupMenu1, so when I right-click a node in the TreeView, then PopupMenu1 is invoked.

In the PopupMenu1.OnPopup event-handler, I need the right-clicked node to be programmatically selected. How can I do that?

Example: In the following screenshot, the first node is preselected. When I right-click the last node to invoke the popup menu, then the last node gets VISUALLY selected TOO (although MultiSelect = False!):

However, when I try to detect the selected node in the PopupMenu1.OnPopup event-handler:

```<code>procedure TformMain.PopupMenu1Popup(Sender: TObject);
begin
  CodeSite.Send(MyTreeView.Selected.Text', MyTreeView.Selected.Text);
end;
</code>```

... then CodeSite reports still the FIRST node as selected!

So how can I set the right-clicked node in the PopupMenu1.OnPopup event-handler to be selected?

(Please note that the TreeView's OnMouseDown event-handler gets executed AFTER the PopupMenu1.OnPopup event-handler)

Obviously, the TPopupMenu class lacks an OnBeforePopup event!

答:
The simplest solution I know of is to use the OnContextPopup event:

procedure TForm1.TreeView1ContextPopup(Sender: TObject; MousePos: TPoint;
  var Handled: Boolean);
begin
  var TreeNode := TreeView1.GetNodeAt(MousePos.X, MousePos.Y);
  if Assigned(TreeNode) then
    TreeNode.Selected := True;
end;
```

Body:
In a 32-bit VCL Application in Windows 10 in Delphi 11 Alexandria, I have a TreeView (TTreeView descendant), where MultiSelect = False and PopupMenu = PopupMenu1, so when I right-click a node in the TreeView, then PopupMenu1 is invoked.

In the PopupMenu1.OnPopup event-handler, I need the right-clicked node to be programmatically selected. How can I do that?

Example: In the following screenshot, the first node is preselected. When I right-click the last node to invoke the popup menu, then the last node gets VISUALLY selected TOO (although MultiSelect = False!):

However, when I try to detect the selected node in the PopupMenu1.OnPopup event-handler:

procedure TformMain.PopupMenu1Popup(Sender: TObject);
begin
  CodeSite.Send(MyTreeView.Selected.Text', MyTreeView.Selected.Text);
end;

... then CodeSite reports still the FIRST node as selected!

So how can I set the right-clicked node in the PopupMenu1.OnPopup event-handler to be selected?

(Please note that the TreeView's OnMouseDown event-handler gets executed AFTER the PopupMenu1.OnPopup event-handler)

Obviously, the TPopupMenu class lacks an OnBeforePopup event!


问:
Is there an R equivalent of the pythonic "if __name__ == "__main__":     main()"?
The objective is to have two simple ways to source some code, say func.R, containing a function. Calling R CMD BATCH func.R initializes the function and evaluates is. Within a session, issuing source("func.R") simply initializes the function.
Any idea?

答:
It's a lot of work, but I finally got it (and posted at Rosetta Code).

This example exports a function called meaningOfLife. When the script is run by itself, it runs main. When imported by another R file, it does not run main.

```<code>#!/usr/bin/Rscript

meaningOfLife <- function() {
    42
}

main <- function(program, args) {
    cat("Main: The meaning of life is", meaningOfLife(), "\n")
}

getProgram <- function(args) {
    sub("--file=", "", args[grep("--file=", args)])
}

args <- commandArgs(trailingOnly = FALSE)
program <- getProgram(args)

if (length(program) > 0 && length(grep("scriptedmain", program)) > 0) {
    main(program, args)
    q("no")
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It's a lot of work, but I finally got it (and posted at Rosetta Code).

This example exports a function called meaningOfLife. When the script is run by itself, it runs main. When imported by another R file, it does not run main.

#!/usr/bin/Rscript

meaningOfLife <- function() {
    42
}

main <- function(program, args) {
    cat("Main: The meaning of life is", meaningOfLife(), "\n")
}

getProgram <- function(args) {
    sub("--file=", "", args[grep("--file=", args)])
}

args <- commandArgs(trailingOnly = FALSE)
program <- getProgram(args)

if (length(program) > 0 && length(grep("scriptedmain", program)) > 0) {
    main(program, args)
    q("no")
}


问:
Clone div and delete div
I don't understand why all Functions are not working. Normally if you click on the button "+ Loc de munca" needs to appear input and then if you click further on the "+ Loc de munca" need to clone all input. Also if you click on the "Sterge" need everything to delete. Here is the code:

var itm = document.getElementById("myList4").getElementsByTagName("div")[0];

function appearafter2() {
  document.getElementById("buttonappear2").style.display = "block";
  document.getElementById("button2").style.display = "block";
  document.getElementById("hinzufuegen2").style.display = "none";
}

function myFunction2() {
  var itm = document.getElementById("myList4").getElementsByTagName("div")[0];
  var cln = itm.cloneNode(true);
  document.getElementById("myList3").appendChild(cln);
}

function deleteFunction2() {
  var list3 = document.getElementById("myList3");
  var divs = Array.from(list3.getElementsByTagName("div"));

  // If the number of divs is 4, it means we're removing the last
  // cloned div, hide the delete button.
  if (divs.length === 4) {
    document.getElementById("button2").style.display = "none";
  }

  var lastDivToDelete2 = divs[divs.length - 1];

  list3.removeChild(lastDivToDelete2);
}

function allFunction2() {
  myFunction2();
  appearafter2();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#button2 {
  display: none;
}

#buttonappear2 {
  display: none;
}

.input-data2 {
  width: 49%;
}
.label-data2 {
  width: 50%;
}
#myList3 {
  display: none;
}
#label-job-input-inline {
  display: inlin-block;
}
.label-job-input {
  display: block;
}</code>```

  + Loc de munca

Șterge

      Numele firmei
      <select size="1" type="text" id="job-input-1" /><option value="scoala_generala">școala generală</option>
  <option value="scoala">școală profesională</option>
  <option value="lic">liceu</option>
  <option value="fac">facultate</option></select>
      Postul ocupat

      <input size="1" type="text" id="job-input-3" />

      din datapână la data

      <input type="number" style="width: 48%" />
      <input type="number" style="width: 50%; margin-left: 6px" />

  + Loc de munca

```

Hello, I don't understand why all Functions are not working. Normally if you click on the button "+ Loc de munca" needs to appear input and then if you click further on the "+ Loc de munca" need to clone all input. Also if you click on the "Sterge" need everything to delete. Here is the code:

答:
Updated the answer, check if this is what you are trying to achieve.

function myFunction2() {
            var cln = '
'+
            '
'+
            'Numele firmei'+
            '<select size="1" type="text" id="job-input-1" />
';

            document.getElementById("myList3").innerHTML+=cln;
            document.getElementById("buttonappear2").classList.remove('hide');
            document.getElementById("button2").classList.remove('hide');
            document.getElementById("hinzufuegen2").classList.add('hide');
        }

        function deleteFunction2() {
            var divs = Array.from(document.querySelectorAll(".list-item"));
            if(divs.length>0){
                var lastDivToDelete2 = divs[divs.length - 1];
                document.getElementById("myList3").removeChild(lastDivToDelete2);
            }
            if(divs.length==1){
                document.getElementById("buttonappear2").classList.add('hide');
            document.getElementById("button2").classList.add('hide');
            document.getElementById("hinzufuegen2").classList.remove('hide');
            }
        }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide{
      display: none;
    }
    .input-data2 {
      width: 49%;
    }
    .label-data2 {
      width: 50%;
    }
    #label-job-input-inline {
      display: inlin-block;
    }
    .label-job-input {
      display: block;
    }</code>```

+ Loc de munca

Șterge

    școala generală școală profesională liceu facultate
    Postul ocupat
    <form>
        <input size="1" type="text" id="job-input-3" />

        din data
        până la data

        <input type="number" style="width: 48%;" />
        <input type="number" style="width: 50%; margin-left: 6px;" />
    </form>

+ Loc de munca
```

Title: Clone div and delete div

Body:
I don't understand why all Functions are not working. Normally if you click on the button "+ Loc de munca" needs to appear input and then if you click further on the "+ Loc de munca" need to clone all input. Also if you click on the "Sterge" need everything to delete. Here is the code:

var itm = document.getElementById("myList4").getElementsByTagName("div")[0];

function appearafter2() {
  document.getElementById("buttonappear2").style.display = "block";
  document.getElementById("button2").style.display = "block";
  document.getElementById("hinzufuegen2").style.display = "none";
}

function myFunction2() {
  var itm = document.getElementById("myList4").getElementsByTagName("div")[0];
  var cln = itm.cloneNode(true);
  document.getElementById("myList3").appendChild(cln);
}

function deleteFunction2() {
  var list3 = document.getElementById("myList3");
  var divs = Array.from(list3.getElementsByTagName("div"));

  // If the number of divs is 4, it means we're removing the last
  // cloned div, hide the delete button.
  if (divs.length === 4) {
    document.getElementById("button2").style.display = "none";
  }

  var lastDivToDelete2 = divs[divs.length - 1];

  list3.removeChild(lastDivToDelete2);
}

function allFunction2() {
  myFunction2();
  appearafter2();
}

#button2 {
  display: none;
}

#buttonappear2 {
  display: none;
}

.input-data2 {
  width: 49%;
}
.label-data2 {
  width: 50%;
}
#myList3 {
  display: none;
}
#label-job-input-inline {
  display: inlin-block;
}
.label-job-input {
  display: block;
}

  + Loc de munca

Șterge

      Numele firmei
      <select size="1" type="text" id="job-input-1" /><option value="scoala_generala">școala generală</option>
  <option value="scoala">școală profesională</option>
  <option value="lic">liceu</option>
  <option value="fac">facultate</option></select>
      Postul ocupat

      <input size="1" type="text" id="job-input-3" />

      din datapână la data

      <input type="number" style="width: 48%" />
      <input type="number" style="width: 50%; margin-left: 6px" />

  + Loc de munca

Hello, I don't understand why all Functions are not working. Normally if you click on the button "+ Loc de munca" needs to appear input and then if you click further on the "+ Loc de munca" need to clone all input. Also if you click on the "Sterge" need everything to delete. Here is the code:

Body:
Updated the answer, check if this is what you are trying to achieve.

function myFunction2() {
            var cln = '<div class="list-item">'+
            '<div id="addingNewJob">'+
            '<label class="label-job-input" for="job-input-1">Numele firmei</label>'+
            '<select size="1" type="text" id="job-input-1" /></div>';

            document.getElementById("myList3").innerHTML+=cln;
            document.getElementById("buttonappear2").classList.remove('hide');
            document.getElementById("button2").classList.remove('hide');
            document.getElementById("hinzufuegen2").classList.add('hide');
        }

        function deleteFunction2() {
            var divs = Array.from(document.querySelectorAll(".list-item"));
            if(divs.length>0){
                var lastDivToDelete2 = divs[divs.length - 1];
                document.getElementById("myList3").removeChild(lastDivToDelete2);
            }
            if(divs.length==1){
                document.getElementById("buttonappear2").classList.add('hide');
            document.getElementById("button2").classList.add('hide');
            document.getElementById("hinzufuegen2").classList.remove('hide');
            }
        }

.hide{
      display: none;
    }
    .input-data2 {
      width: 49%;
    }
    .label-data2 {
      width: 50%;
    }
    #label-job-input-inline {
      display: inlin-block;
    }
    .label-job-input {
      display: block;
    }

<div id="hinzufuegen2" onclick="myFunction2()">+ Loc de munca</div>
    <div id="myList3">
        <div id="button2" class="hide" onclick="deleteFunction2()">Șterge</div>
    </div>
    școala generală școală profesională liceu facultate
    <label class="label-job-input" for="job-input-2">Postul ocupat</label>
    <form>
        <input size="1" type="text" id="job-input-3" />
        <br />
        <label class="label-data2" for="job-input-3">din data</label>
        <label class="label-data2" for="job-input-4">până la data</label>
        <br />
        <input type="number" style="width: 48%;" />
        <input type="number" style="width: 50%; margin-left: 6px;" />
    </form>
    <div onclick="myFunction2()" class="hide" id="buttonappear2">+ Loc de munca</div>


问:
How to show XAML views and their C# files in UML class diagrams?
I have a bunch of XAML Views (.xaml files) and their corresponding C# (.cs files) in a package.

How would I show them in a UML class diagram?

答:
Each View class consists of one .xaml and a .cs file (in fact you can see that the .cs file class definition starts public partial class ).

Therefore, if your package contains 6 Views then you will have 6 classes to show on your UML class diagram.

It is popular practice to structure WPF applications using Model-View-ViewModel pattern.

In this situation you'll have at least 4 files for one UI page.

For example, PageOneView consists of PageOneView.xaml and PageOneView.cs that uses PageOneViewModel (PageOneViewModel.cs) as its data context (it provides a data binding and manipulation source) and PageOneModel (PageOneModel.cs) would be the data.

If, however, you then want to show your program structure and relationships on a class diagram, then you'd have only 3 classes with relational links (as a View references the ViewModel which in turn references the Model).

In reality the ViewModel may reference multiple Models or classes that act as a data source such as multiple database, data table access.


问:
Can I modify add form field, to have select list from data got by external API?
I want to extend one field from add form, to be able to choose option from select list got by external API. Let me explain the question.
I've got model like this:

```<code>class ContactGroup(Model):
    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique=True, nullable=False)
    my_field_id = Column(Integer, nullable=False)

    def __repr__(self):
        return self.name
</code>```

When I want to add new entity, by default form created by app-builder, I have to specify my_field_id "by hand". So my question is, can I extend my_field_id to instead of specifying integer I will have a select list with data returned by external API.
Api is providing data as a json, ex.:

```<code>{
  data: [
    {
      id: 1,
      name: "My field"
    }
    ...
  ]
}
</code>```

Or is it too complicated for default app-builder forms and I have to rewrite add form completely?

Thanks!

答:
I know that's late answer but, if anyone will ever wants to do something similar, then SelectField is an answer. You can specify select options in init method like this:

```<code>class ContactGroup(Model):
    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique=True, nullable=False)
    my_field_id = SelectField(
        "Legal entity",
        widget=Select2Widget(),
        description="Select a legal entity",
        validators=[validators.Optional()],
        coerce=int,
    )

    def my_field_id_query():
        # get data here...

    def __init__:
        super().__init__(*args, **kwargs)
        self.my_field_id.choices = [(choice["id"], choice["name"]) for choice in my_field_id_query()]

</code>```

More detailed explanation here:

https://github.com/dpgaspar/Flask-AppBuilder/issues/1717

Body:
I want to extend one field from add form, to be able to choose option from select list got by external API. Let me explain the question.
I've got model like this:

class ContactGroup(Model):
    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique=True, nullable=False)
    my_field_id = Column(Integer, nullable=False)

    def __repr__(self):
        return self.name

When I want to add new entity, by default form created by app-builder, I have to specify my_field_id "by hand". So my question is, can I extend my_field_id to instead of specifying integer I will have a select list with data returned by external API.
Api is providing data as a json, ex.:

{
  data: [
    {
      id: 1,
      name: "My field"
    }
    ...
  ]
}

Or is it too complicated for default app-builder forms and I have to rewrite add form completely?

Thanks!

Body:
I know that's late answer but, if anyone will ever wants to do something similar, then SelectField is an answer. You can specify select options in init method like this:

class ContactGroup(Model):
    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique=True, nullable=False)
    my_field_id = SelectField(
        "Legal entity",
        widget=Select2Widget(),
        description="Select a legal entity",
        validators=[validators.Optional()],
        coerce=int,
    )

    def my_field_id_query():
        # get data here...

    def __init__:
        super().__init__(*args, **kwargs)
        self.my_field_id.choices = [(choice["id"], choice["name"]) for choice in my_field_id_query()]

More detailed explanation here:

https://github.com/dpgaspar/Flask-AppBuilder/issues/1717


问:
Control .fadeOut() with jQuery
I have the following jquery code:

```<code><script type="text/javascript">
$(function(){
    $('.gallery-slider li:gt(0)').hide();
    setInterval(function(){
      $('.gallery-slider li:first-child').fadeOut("slow")
         .next('.gallery-slider li').fadeIn(1000)
         .end().appendTo('.gallery-slider');},
      2000);
});
</script>
</code>```

The .fadeIn seems to be working, however the .fadeOut does not seem to be properly accepting the speed parameter. What do I need to change such that it will properly work? Thank you.

答:
The problem is the fade functions don't block..

You can pass a function to fadeout so that it runs after its complete, e.g.

```<code>$('.blarg').fadeOut(100, function() {
  $('.blarg).fadeIn();
});
</code>```

Would wait until its totally faded out before it tries to fade back in.

Title: Control .fadeOut() with jQuery

Body:
I have the following jquery code:

The .fadeIn seems to be working, however the .fadeOut does not seem to be properly accepting the speed parameter. What do I need to change such that it will properly work? Thank you.

Body:
The problem is the fade functions don't block..

You can pass a function to fadeout so that it runs after its complete, e.g.

$('.blarg').fadeOut(100, function() {
  $('.blarg).fadeIn();
});

Would wait until its totally faded out before it tries to fade back in.


问:
EOF: command not found in Jenkins Pipeline
I'm trying to launch Datadog agent in Jenkins pipeline, but I'm getting below errors:

line 7: warning: here-document at line 2 delimited by end-of-file (wanted `EOF').
EOF: Command not found Error.

```<code>    stage('Install Datadog agent'){
        when {
            environment(name: "DATADOG_REQ", value: "enable")
            }
        steps {
            script {
            echo "Installing Datadog Agent"

            sh '''#!/bin/bash
                ssh -o ConnectTimeout=30 -t  ABC@1234 /bin/bash  << EOF || error_exit "creating based folder failed for $service_name"
                sudo chmod u+x ./${JOB_NAME}/enableDatadogAgent.sh
                sudo chown jenkins:jenkins ./${JOB_NAME}/enableDatadogAgent.sh
                echo ${DATADOG_REQ} ${JOB_NAME}
                ./${JOB_NAME}/enableDatadogAgent.sh ${DATADOG_REQ}
                EOF'''
                }

            }
        }
</code>```

Any help would be very helpful.

答:
I changed the << EOF with <<- _EOF_, and now it's working.</p>
```<code>            script {
            echo "Installing Datadog Agent"

            sh '''#!/bin/bash
                ssh -o ConnectTimeout=30 -t  ABC@1234 /bin/bash  <<- _EOF_ || error_exit "Failed to execute while doing SSH"
                    sudo chmod u+x ./${JOB_NAME}/enableDatadogAgent.sh
                    sudo chown jenkins:jenkins ./${JOB_NAME}/enableDatadogAgent.sh
                    echo ${DATADOG_REQ} ${JOB_NAME}
                    ./${JOB_NAME}/enableDatadogAgent.sh ${DATADOG_REQ}
                    _EOF_'''

                }
</code>```

Body:
I'm trying to launch Datadog agent in Jenkins pipeline, but I'm getting below errors:

line 7: warning: here-document at line 2 delimited by end-of-file (wanted `EOF').
EOF: Command not found Error.

    stage('Install Datadog agent'){
        when {
            environment(name: "DATADOG_REQ", value: "enable")
            }
        steps {
            script {
            echo "Installing Datadog Agent"

            sh '''#!/bin/bash
                ssh -o ConnectTimeout=30 -t  ABC@1234 /bin/bash  << EOF || error_exit "creating based folder failed for $service_name"
                sudo chmod u+x ./${JOB_NAME}/enableDatadogAgent.sh
                sudo chown jenkins:jenkins ./${JOB_NAME}/enableDatadogAgent.sh
                echo ${DATADOG_REQ} ${JOB_NAME}
                ./${JOB_NAME}/enableDatadogAgent.sh ${DATADOG_REQ}
                EOF'''
                }

            }
        }

Any help would be very helpful.

Body:
I changed the << EOF with <<- _EOF_, and now it's working.

            script {
            echo "Installing Datadog Agent"

            sh '''#!/bin/bash
                ssh -o ConnectTimeout=30 -t  ABC@1234 /bin/bash  <<- _EOF_ || error_exit "Failed to execute while doing SSH"
                    sudo chmod u+x ./${JOB_NAME}/enableDatadogAgent.sh
                    sudo chown jenkins:jenkins ./${JOB_NAME}/enableDatadogAgent.sh
                    echo ${DATADOG_REQ} ${JOB_NAME}
                    ./${JOB_NAME}/enableDatadogAgent.sh ${DATADOG_REQ}
                    _EOF_'''

                }


问:
How can I open a connection to "Coinex" websocket using "WebSocketSharp" in C#
I'm currently working om my very own trade bot and I want to stream realtime cryptocurrency price from coinex.com using websocket (documentation is here: "https://github.com/coinexcom/coinex_exchange_api/wiki").
I start with a windows form project in Visual Studio and add websocketsharp Nuget package to make a connection using this two lines of code:

```<code>            WebSocket ws = new WebSocket("wss://socket.coinex.com/");
            ws.Connect();
</code>```

but connection is not stablished and I can't continue working on other parts of my program.
after a week searching and googling I have no success. I appreciate any help to solve this problem.

答: I find the problem. The Coinex.com domain restricted (Blocked) here (In IRAN) and I should use Proxy to bypass restriction. But here there is another problem: How can I set Proxy for websocketsharp? there is a "Setproxy" function in "websocketsharp" but do not work.</p>

Body:
I'm currently working om my very own trade bot and I want to stream realtime cryptocurrency price from coinex.com using websocket (documentation is here: "https://github.com/coinexcom/coinex_exchange_api/wiki").
I start with a windows form project in Visual Studio and add websocketsharp Nuget package to make a connection using this two lines of code:

            WebSocket ws = new WebSocket("wss://socket.coinex.com/");
            ws.Connect();

but connection is not stablished and I can't continue working on other parts of my program.
after a week searching and googling I have no success. I appreciate any help to solve this problem.


问:
Check if file is in (sub)directory
I would like to check whether an existing file is in a specific directory or a subdirectory  of that.

I have two File objects.

```<code>File dir;
File file;
</code>```

Both are guaranteed to exist. Let's assume

```<code>dir  = /tmp/dir
file = /tmp/dir/subdir1/subdir2/file.txt
</code>```

I want this check to return true

For now i am doing the check this way:

```<code>String canonicalDir = dir.getCanonicalPath() + File.separator;
boolean subdir = file.getCanonicalPath().startsWith(canonicalDir);
</code>```

This seems to work with my limited tests, but i am unsure whether this might make problems on some operating systems. I also do not like that getCanonicalPath() can throw an IOException which i have to handle.

Is there a better way? Possibly in some library?

Thanks

答:
Since Java 7+ you can just do this:

file.toPath().startsWith(dir.toPath());
```

Title: Check if file is in (sub)directory

Body:
I would like to check whether an existing file is in a specific directory or a subdirectory  of that.

I have two File objects.

File dir;
File file;

Both are guaranteed to exist. Let's assume

dir  = /tmp/dir
file = /tmp/dir/subdir1/subdir2/file.txt

I want this check to return true

For now i am doing the check this way:

String canonicalDir = dir.getCanonicalPath() + File.separator;
boolean subdir = file.getCanonicalPath().startsWith(canonicalDir);

This seems to work with my limited tests, but i am unsure whether this might make problems on some operating systems. I also do not like that getCanonicalPath() can throw an IOException which i have to handle.

Is there a better way? Possibly in some library?

Thanks


问:
Indices of the permutation for sorted list
Given an array, I would like to get an array holding the indices of the permutation that would result in the array being sorted. An example should make it clear:
Input array:

```<code>[10, 50, 40, 20, 30]
</code>```

should produce the following output:

```<code>[0, 3, 4, 2, 1]
</code>```

because if I first take the 0th, then the 3rd, then the 4th, then the 2nd and then the 1st element of the list, I would get [10, 20, 30, 40, 50], which would be the sorted array.

Of course I could just code it in Python from scratch, but I wonder if there is a function for this in Python already.

答:
```<code>a = [10, 50, 40, 20, 30]
ix = [a.index(v) for v in sorted(a)]
</code>```

To my knowledge, there is no function for this. Just this half liner.

Body:
Given an array, I would like to get an array holding the indices of the permutation that would result in the array being sorted. An example should make it clear:
Input array:

[10, 50, 40, 20, 30]

should produce the following output:

[0, 3, 4, 2, 1]

because if I first take the 0th, then the 3rd, then the 4th, then the 2nd and then the 1st element of the list, I would get [10, 20, 30, 40, 50], which would be the sorted array.

Of course I could just code it in Python from scratch, but I wonder if there is a function for this in Python already.

Body:
a = [10, 50, 40, 20, 30]
ix = [a.index(v) for v in sorted(a)]

To my knowledge, there is no function for this. Just this half liner.


问:
update with exists in oracle
I have this query :

```<code>update rexcms e
   set e.cocnd=(select r.cocnd
                  from rexcms r
                 where NVL(r.marche,'*')=NVL(e.marche,'*')
                   and r.cocrd= e.cocrd
                   and r.cocol=e.cocol
                   and r.cocol='CHBIL'
                   and r.marche='CBOT')
 where e.cocol ='CDVHB' ;
</code>```

how can use EXISTS to optimize it

答:
You update the table from rows of the same table. With where e.cocol = 'CDVHB' you only update CDVHB rows. With r.cocol = e.cocol you only update them with data from CDVHB rows. With r.cocol = 'CHBIL' you say that these rows must be CHBIL rows. But a row cannot be a CDVHB and a CHBIL row at the same time, because a row's cocol can only be one or the other.

Your query can hence be reduced to:

```<code>update rexcms set cocnd = null where cocol = 'CDVHB';
</code>```

and there is no need for further optimization.

Title: update with exists in oracle

Body:
I have this query :

update rexcms e
   set e.cocnd=(select r.cocnd
                  from rexcms r
                 where NVL(r.marche,'*')=NVL(e.marche,'*')
                   and r.cocrd= e.cocrd
                   and r.cocol=e.cocol
                   and r.cocol='CHBIL'
                   and r.marche='CBOT')
 where e.cocol ='CDVHB' ;

how can use EXISTS to optimize it

Body:
You update the table from rows of the same table. With where e.cocol = 'CDVHB' you only update CDVHB rows. With r.cocol = e.cocol you only update them with data from CDVHB rows. With r.cocol = 'CHBIL' you say that these rows must be CHBIL rows. But a row cannot be a CDVHB and a CHBIL row at the same time, because a row's cocol can only be one or the other.

Your query can hence be reduced to:

update rexcms set cocnd = null where cocol = 'CDVHB';

and there is no need for further optimization.


问:
Modern Command-Line Programming a la Bloomberg Terminal
I want build a financial analysis tool that will feature screen after screen of diverse, dynamic options. The screens will change based on the input from the previous screens. Any single screen can have hundreds of options, most of which will be listed in lists. I think creating my application using a regular gui style will be difficult and slow.

I'd like to build my software in a command-line like environment. I think the closest thing to what I'm going for is a Bloomberg terminal.

Are there any tools, toolkits, environments, etc that I can use to build my app on a totally blank slate that I can constantly change? I need to be able to draw charts and would love as much flexibility in graphics as possible. The folks at Bloomberg somehow do this. Can anyone give me some tips?

I have considered using a browser-based approach but I would much prefer something more native.

If it matters I'd most like to code in Java and/or jRuby.

Thanks!

Please note that regardless of the merits of the approach (per your view), I have a valid technical question.

答:
Well if you want to draw graphics you'll have to eventually pick up some basic graphics libraries to draw charts.  I'd suggest using JFreeCharts because it's an API to build the charting without drawing line by line which you'll never want to do.

For console input you can use Console in Java6.  That's better than using System.in, System.out.

http://download.oracle.com/javase/6/docs/api/java/io/Console.html

As for not building a GUI you could build a command line operation in Swing so that you can script it, but support more complex editing that's not possible with straight command line processing.  I actually started to build a framework for building command line tools that run inside a swing window so you can get nicer editing, but I haven't open sourced it yet.

If you're adamant about not using a UI toolkit like Swing then you can use BufferedImage:

http://download.oracle.com/javase/6/docs/api/java/awt/image/BufferedImage.html

To draw any graphics you want, but you'll basically be learning Java2D, and rendering graphics pixel by pixel into a BufferedImage and save that to a file instead of the screen.  I think you'll find this route very difficult to build results out of it, but you can literally render anything you want.


问:
Fetch table value using Accessor In Laravel 8 for image
My model name is 'data' and the field name is 'image'.

In the Model when I try to fetch the URL of the image it shows this error Undefined property: App\Models\Data::$image using $this->image;.

But when I try to fetch name using $this->name It's working fine.

I also attached the screenshot of DB for better understanding.

Note: I add use Storage; In the model.

Please help me for solving the issue.

Controller

Model

答:
Before starting to learn querying in laravel, tidy up your code and adjust it to the standard syntax first so you don't make it difficult for yourself.

accept model data in a variable

for example i get latest row

```<code>$mydata = \App\Models\Data::orderBy('id','DESC')->first();
</code>```

if you want to get your data, you can do this

```<code>$mydata->name;
$mydata->image;
</code>```

if still not working, please add a screenshot of your model.

[comment answer]

```<code>public function getImageAttribute ($id) {
     return Data::where('id',$id)->first()->image;
}
</code>```

Body:
Before starting to learn querying in laravel, tidy up your code and adjust it to the standard syntax first so you don't make it difficult for yourself.

accept model data in a variable

for example i get latest row

$mydata = \App\Models\Data::orderBy('id','DESC')->first();

if you want to get your data, you can do this

$mydata->name;
$mydata->image;

if still not working, please add a screenshot of your model.

[comment answer]

public function getImageAttribute ($id) {
     return Data::where('id',$id)->first()->image;
}


问:
Escaping the separator in str_getcsv
str_getcsv("test\\.a.b", ".", "'", "\\");

I would expect the above to equal ["test.a", "b"], however it equals ["test\", "a", "b"]. Am I misunderstanding the purpose or usage of the $escape argument? I want to escape the separator such that the result is the former array.

答:
You could use the "enclosure" char to enclose a separator char:

```<code>var_dump(str_getcsv("'test.a'.b", ".", "'", "\\"));
</code>```

Output:

```<code>array(2) {
  [0]=>
  string(6) "test.a"
  [1]=>
  string(1) "b"
}
</code>```

Title: Escaping the separator in str_getcsv

Body:
You could use the "enclosure" char to enclose a separator char:

var_dump(str_getcsv("'test.a'.b", ".", "'", "\\"));

Output:

array(2) {
  [0]=>
  string(6) "test.a"
  [1]=>
  string(1) "b"
}


问:
Resctricting access to only 1 ip address and console connection
I havent found an answer to this situation, and I'd like to have an answer before trying it and be stuck !

I would like to restrict connection to my EC2 instance to SSH from one IP address. Also I wonder if connecting to this instance within the console (Amazon website) would be prohibited ?
In other words, suppose I usually connect to this instance through a proxy or a VPN. Would I be able to connect to this instance, change parameters, etc. through the amazon website from any place ? In case the proxy or VPN breaks down ?
This may seems a silly question, but I'm not a specialist and I wouldn't like to be stuck outside :)

答:
You can restrict SSH access to an Amazon EC2 instance by creating a Security Group that only permits Inbound SSH (port 22) access from a specific IP address.

The Security Group only limits access to the instance itself. Any activity in the EC2 management console (eg stopping and starting an instance) is not impacted by Security Group settings.

You cannot "connect to an instance from the Amazon EC2 console", but the console does have the ability to launch EC2 Instance Connect, which is a web-based SSH. However, it cannot be restricted to one IP address.


问:
pip error while installing azure cli extension behind proxy
could someone help me please:

I am using Azure cli behind proxy and I have fiddler running.
I am running following commands and setup to login into my azure account,

```<code>SET ADAL_PYTHON_NO_SSL_VERIFY=1
SET AZURE_CLI_DISABLE_CONNECTION_VERIFICATION=1
az login --tenant <company domain>
</code>```

It works well and gives me the list of subscriptions associated with my account.But,
I need to install Azure-devops extension and when i run:

```<code>az extension add --name azure-devops
</code>```

I am getting error: cli.azure.cli.core.util : An error occurred. Pip failed with status code 1.

looking into fiddler it says:
407 proxy authentication  error while connecting to on premise nexus.
My pip config:

```<code>[list]
format=columns
[global]
disable-pip-version-check = true
trusted-host = nexusurl
index = https://[username]:[userpassword]@<nexusurl>
index-url = https://[username]:[userpassword]@<nexusurl>
</code>```

i couldnt figure out what i am missing.

答:
Had the same issue on Windows 10 with WSL2 ubuntu

Solved it by setting the proxy as an environment variable in powershell.

```<code>$Env:HTTP_PROXY = "http://proxy.corporate.com:1234/"
$Env:HTTPS_PROXY = "http://proxy.corporate.com:1234/"
</code>```

Verify if setting was successful by viewing all env variables:

```<code>dir env:
</code>```

Body:
could someone help me please:

I am using Azure cli behind proxy and I have fiddler running.
I am running following commands and setup to login into my azure account,

SET ADAL_PYTHON_NO_SSL_VERIFY=1
SET AZURE_CLI_DISABLE_CONNECTION_VERIFICATION=1
az login --tenant <company domain>

It works well and gives me the list of subscriptions associated with my account.But,
I need to install Azure-devops extension and when i run:

az extension add --name azure-devops

I am getting error: cli.azure.cli.core.util : An error occurred. Pip failed with status code 1.

looking into fiddler it says:
407 proxy authentication  error while connecting to on premise nexus.
My pip config:

[list]
format=columns
[global]
disable-pip-version-check = true
trusted-host = nexusurl
index = https://[username]:[userpassword]@<nexusurl>
index-url = https://[username]:[userpassword]@<nexusurl>

i couldnt figure out what i am missing.

Body:
Had the same issue on Windows 10 with WSL2 ubuntu

Solved it by setting the proxy as an environment variable in powershell.

$Env:HTTP_PROXY = "http://proxy.corporate.com:1234/"
$Env:HTTPS_PROXY = "http://proxy.corporate.com:1234/"

Verify if setting was successful by viewing all env variables:

dir env:


问:
How Can I Make My "Fake ESM" Next 12 Project Use Native ESM?
I had a perfectly working Next.js version 11 site, which used Babel/webpack to get modern "ES Module" syntax: the only require/CommonJS syntax in my whole app was in next.config.js and babel.config.js.

I updated it to Next 12 and it worked great, so I figured I'd try to get rid of those remaining requires, and make my project fully ESM, by adding "type": "module" to my package.json.

That gave me an error about how next.config.js had to use ESM syntax, so I updated it to ESM syntax ... but now I get an error about how Next is (evidently?) using Common JS to import the babel.config.js?

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module:
/home/me/project/client/babel.config.js require() of ES modules is not
supported. require() of /home/me/project/client/babel.config.js from
/home/me/project/client/node_modules/next/dist/build/babel/loader/get-config.js
is an ES module file as it is a .js file whose nearest parent
package.json contains "type": "module" which defines all .js files in
that package scope as ES modules. Instead rename babel.config.js to
end in .cjs, change the requiring code to use import(), or remove
"type": "module" from /home/me/project/client/package.json.

Since I'm not in control of Next I don't know how to fix this (and shouldn't Next 12 be importing with ESM by default?)  Also my syntax in babel.config.js doesn't seem to even matter: whether I use ESM or Common JS, I get that same error.

Any help would be greatly appreciated.

答:
You're importing Next.js itself as an ES Module which is not supported yet.

See: https://github.com/vercel/next.js/discussions/27876#discussioncomment-1163394


问:
Cannot find the answer after my research, help me with mysql
The Error is:

Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ':rafli_namaUser, :rafli_username, :rafli_password)' at line 2 in C:\xampp\htdocs\rafli_kasir\rafli_register.php:16 Stack trace: #0 C:\xampp\htdocs\rafli_kasir\rafli_register.php(16): mysqli->prepare('INSERT INTO raf...') #1 {main} thrown in C:\xampp\htdocs\rafli_kasir\rafli_register.php on line 16

cannot find any solution after research, this is my code:

```<code><?php
require_once("rafli_koneksi.php");
if(isset($_POST['rafli_register'])){
    $rafli_namaUser = filter_input(INPUT_POST, 'rafli_namaUser', FILTER_SANITIZE_STRING);
    $rafli_username = filter_input(INPUT_POST, 'rafli_username', FILTER_SANITIZE_STRING);
    $rafli_password = password_hash($_POST["rafli_password"], PASSWORD_DEFAULT);
    $sql = "INSERT INTO rafli_user (rafli_namaUser, rafli_username, rafli_password)
            VALUES (:rafli_namaUser, :rafli_username, :rafli_password)";
    $stmt = $rafli_conn->prepare($sql);
    $params = array(
        ":rafli_namaUser" => $rafli_namaUser,
        ":rafli_username" => $rafli_username,
        ":rafli_password" => $rafli_password
    );
    $saved = $stmt->execute($params);
    if($saved) header("Location: rafli_login.php");
}
?>
</code>```

rafli_koneksi.php

```<code><?php

$rafli_host = "localhost";
$rafli_username = "root";
$rafli_password = "";
$rafli_database = "rafli_kasir";
$rafli_conn = new mysqli( $rafli_host, $rafli_username, $rafli_password, $rafli_database );
    echo 'Gagal terhubung ke database';
} else {
    // Koneksi berhasil
}
</code>```

?>

答:
Did you forget to define $rafli_conn in this piece of code?

bool means Boolean, i.e. true or false.

You set $stmt = $rafli_conn->prepare($sql); and later it says that you cannot call ->execute() on a bool — so there is a high likelihood that $stmt is returning false.

Can you print_r($stmt) and test what its value is? Once you have that working, you should be fine.

Body:
The Error is:

Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ':rafli_namaUser, :rafli_username, :rafli_password)' at line 2 in C:\xampp\htdocs\rafli_kasir\rafli_register.php:16 Stack trace: #0 C:\xampp\htdocs\rafli_kasir\rafli_register.php(16): mysqli->prepare('INSERT INTO raf...') #1 {main} thrown in C:\xampp\htdocs\rafli_kasir\rafli_register.php on line 16

cannot find any solution after research, this is my code:

<?php
require_once("rafli_koneksi.php");
if(isset($_POST['rafli_register'])){
    $rafli_namaUser = filter_input(INPUT_POST, 'rafli_namaUser', FILTER_SANITIZE_STRING);
    $rafli_username = filter_input(INPUT_POST, 'rafli_username', FILTER_SANITIZE_STRING);
    $rafli_password = password_hash($_POST["rafli_password"], PASSWORD_DEFAULT);
    $sql = "INSERT INTO rafli_user (rafli_namaUser, rafli_username, rafli_password)
            VALUES (:rafli_namaUser, :rafli_username, :rafli_password)";
    $stmt = $rafli_conn->prepare($sql);
    $params = array(
        ":rafli_namaUser" => $rafli_namaUser,
        ":rafli_username" => $rafli_username,
        ":rafli_password" => $rafli_password
    );
    $saved = $stmt->execute($params);
    if($saved) header("Location: rafli_login.php");
}
?>

rafli_koneksi.php

<?php

$rafli_host = "localhost";
$rafli_username = "root";
$rafli_password = "";
$rafli_database = "rafli_kasir";
$rafli_conn = new mysqli( $rafli_host, $rafli_username, $rafli_password, $rafli_database );
    echo 'Gagal terhubung ke database';
} else {
    // Koneksi berhasil
}

?>