text:
Q: USB webcam and available formats I have an ELP usb camera. The available formats are:
$ v4l2-ctl --list-formats-ext -d /dev/video1
ioctl: VIDIOC_ENUM_FMT
Type: Video Capture

[0]: 'MJPG' (Motion-JPEG, compressed)
    Size: Discrete 1920x1080
        Interval: Discrete 0.033s (30.000 fps)
    Size: Discrete 1280x720
        Interval: Discrete 0.017s (60.000 fps)
    Size: Discrete 1024x768
        Interval: Discrete 0.033s (30.000 fps)
    Size: Discrete 640x480
        Interval: Discrete 0.008s (120.101 fps)
    Size: Discrete 800x600
        Interval: Discrete 0.017s (60.000 fps)
    Size: Discrete 1280x1024
        Interval: Discrete 0.033s (30.000 fps)
    Size: Discrete 320x240
        Interval: Discrete 0.008s (120.101 fps)
[1]: 'YUYV' (YUYV 4:2:2)
    Size: Discrete 1920x1080
        Interval: Discrete 0.167s (6.000 fps)
    Size: Discrete 1280x720
        Interval: Discrete 0.111s (9.000 fps)
    Size: Discrete 1024x768
        Interval: Discrete 0.167s (6.000 fps)
    Size: Discrete 640x480
        Interval: Discrete 0.033s (30.000 fps)
    Size: Discrete 800x600
        Interval: Discrete 0.050s (20.000 fps)
    Size: Discrete 1280x1024
        Interval: Discrete 0.167s (6.000 fps)
    Size: Discrete 320x240
        Interval: Discrete 0.033s (30.000 fps)

Suppose I would like to use MJPG 1280x720 @ 20fps, or even something strange like 1280x720 @ 18fps.
This answer says:

Only the listed formats are supported by v4l2, anything else would need to be coded by the user, and RGBs are very seldom provided, despite virtually all CCDs working in Bayer RGGB [...]

What's the way to set custom resolution and framerate?
Even more silly question, is there a way to control shutter time with these USB cameras?
EDIT:
I'm working with Python. OpenCV cannot access the camera at all, while it works with Webcamoid software.

A: I would just change the frequency that you sample from the camera to the frame rate you desire.
If we look at the MJPEG:

Size: Discrete 1280x720
Interval: Discrete 0.017s (60.000 fps)

Just read from that stream 20 times a second (essentially just getting every 3rd frame), or 18 times a second (getting every third/fourth frame).
IN HTML you'd do this with the getUserMedia:
set your variables of width, height and framerate:
var constraints = { audio: {sampleRate: audiobitrate,
                            echoCancellation: true},
    video:{
        width: { min: 100, ideal: width, max: 1920 },
        height: { min: 100, ideal: height, max: 1080 },
        frameRate: {ideal: framerate}
    }
};
console.log(constraints);
navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {

// do your thing... }

This code is pulled from a livestream app I built (line 273): https://github.com/dougsillars/browserLiveStream/blob/master/public/index.html


text:
Q: How to insert/update with sysdate in hibernate? i am using hibernate. db is oracle. my requirement is i need to insert/update a entity with sysdate but not new Date(). please help me how to achieve this?
Thanks!

A: You can use current_timestamp() HQL function to achieve that.

A: After a long R&D, at last I found the solution for inserting/ updating with database SYSDATE (not application server Date) using hibernate in date column. Hope it will help you, please find the solution for the above
1) add extra property in mapping.hbm.xml file like below
property name="systemDate" formula="(select sysdate from dual)"

2) add setters and getters for the 'systemDate' property in POJO class
private Date systemDate;

public Date getSystemDate() {
    return this.systemDate;
}

public void setSystemDate(Date systemDate) {
    this.systemDate = systemDate;
}

3) In your DAO, before inserting or updating the date column, fetch the systemDate property and save the session with that value.
POJOclass Obj = new

// the below line returns the database system date,because we had given the formula for this property in mapping.xml file

Date systemDate= POJOclassObj.getSystemDate();

and add the above Date to your columns. It will insert Database sysdate.

A: The first (accepted) answer actually doesn't meet the requirement, as it will use new Date() under the covers. The OP's solution works, but it's a bit cumbersome. When the row is created, sysdate can be specified as the column default. For updates, most DBA's seem to define a before trigger that updates the column value. The trigger is beneficial because it prevents circumvention of the requirement.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to select just rows that contains integers and decimals in sql oracle? I want to select just integers and decimal ones from my procedure. In this case 192 and 193.0. What I have tried is regexp_like(columnName, '^[[:digit:]]*$') but it just appears 192 (integer ones).
Thank you in advance.

A: How about TRANSLATE?
SQL> with test (col) as
  2    (select 'Negativo' from dual union all
  3     select '192'      from dual union all
  4     select '193.3'    from dual union all
  5     select '20.a4'    from dual
  6    )
  7  select col
  8  from test
  9  where translate(col, '0123456789.', 'a') is null;

COL
--------
192
193.3

SQL>

A: I would recommend a function like this:
CREATE OR REPLACE FUNCTION IsNumeric(Expression IN VARCHAR2) RETURN INTEGER IS
   val NUMBER;
BEGIN
    val := TO_NUMBER(Expression);
    RETURN 1;
EXCEPTION
    WHEN VALUE_ERROR OR INVALID_NUMBER THEN
        RETURN 0;
END IsNumeric;

A: Try
regexp_like(columnName, '^[[:digit:]]*(\.[[:digit:]]+)?$')

That allows an optional point followed by at least one digit to follow the first sequence of digits.

A: If you're on 12.2 or above, you can use the default <value> on conversion error clause to return a default value when the str can't be converted to a number.
e.g.:
select 'abc' str, to_number('abc' default null on conversion error) str_num
from   dual;

str str_num
--- -------
abc

See this dbfiddle for a demo.


text:
Q: gtest - Report index variable for loop with EXPECT_EQ I am using gtest but I am new to gtest.  I would like to do compares of values within two std::vectors of complex data structures.  I want to do something like this:
ASSERT_EQ(a.size(), b.size());

for (int x = 0; x < a.size(); x++) {
  EXPECT_EQ(
    sqrt(pow(a.real[x], 2) + pow(a.imag[x], 2)),
    sqrt(pow(b.real[x], 2) + pow(b.imag[x], 2)));
}

This is great in that for mismatches it reports the values that were compared, e.g. 5 != 7, but it does not report the index variable "x".  Is there some way I can easily output the index variable when mismatch is detected?

A: SCOPED_TRACE (https://github.com/google/googletest/blob/main/docs/advanced.md#adding-traces-to-assertions) can be used, like:
for (int x = 0; x < a.size(); x++) {
  SCOPED_TRACE("x = " + std::to_string(x));
  EXPECT_EQ(
  ...

It's especially useful when there are more than one check:
for (int x = 0; x < a.size(); x++) {
  SCOPED_TRACE("x = " + std::to_string(x));
  EXPECT_EQ(...
  EXPECT_EQ(...

A: From https://github.com/google/googletest/blob/main/docs/primer.md:

To provide a custom failure message, simply stream it into the macro using the << operator, or a sequence of such operators.

So if you wanted to output what your index is for the expect equal, you would do something like:
EXPECT_EQ(
  sqrt(pow(a.real[x], 2) + pow(a.imag[x], 2)),
  sqrt(pow(b.real[x], 2) + pow(b.imag[x], 2))) << "x is : " << x << std::endl;


text:
Q: Node-Red to InfluxDB Cloud HTTPError: 405 I have a problem setting up my connection between my raspberry pi and influxDB cloud.
The raspberry pi serves as MQTT broker (using mosquitto). I subscribed to the topic (temperature, humidity (..)) and now want to store this data in my InfluxDB Cloud.
I wanted to use node-red for this.
I successfully get the MQTT messages looking like that with the MQTT in node:
{"topic":"esp/dht/temperature","payload":22.1,"qos":0,"retain":false,"_msgid":"e7133e911452b1e4"}

Now I just want to store the plain object in my influxDB without changing the object (for now). Therefore I put in a influxDB out node.
I configured it like that:

*

*URL: https://westeurope-1.azure.cloud2.influxdata.com/orgs/9999999999999

*Token: My All Access token generated in influxDB Cloud UI

*Organization: uibk

*Bucket: test

*measurement: temperature

This throws an HTTPError 405:
HttpError: 405 Method Not Allowed :
<title>405 Not Allowed</title>

405 Not Allowed

nginx/1.22.1

What is the problem here?
edit:
screenshots of influxdb out node


text:
Q: What quality measures can be used to evaluate a density-based clustering algorithm? I have a weighted undirected graph, where weight is the similarity and range from 0 to 1.
I applied a density-based clustering method and get some clusters, with overlapping nodes (node can belong to more than one cluster), and with noise or outlier nodes ( node don't belong to any cluster).
Now, are there quality measures that works fine with this clustering result?
For example, one of measures I think about is Modularity Q, but I don't sure if it suitable for my graph or not.
Also if other measures such as internal density, node betweeness, converge and entropy can be used here ?
Thank in advance.

A: There was one recently proposed:

*

*Moulavi, D., Jaskowiak, P. A., Campello, R. J. G. B., Zimek, A., & Sander, J. (2014). Density-based clustering validation. In Proceedings of the 14th SIAM International Conference on Data Mining (SDM), Philadelphia, PA.

Havn't read it in details yet, or tried it.


text:
Q: Repeating variable in query string I am experiencing a strange issue with javascript and firefox 10.0.11. I have tested with IE and am unable to replicate the issue.
I have a link which goes to a page that shows some information about an object. I have added additional features to this page using javascript. If javascript is enabled, the anchor link will be redirected to a javascript function instead.
Comment

function CommentSubmit(id) {
    $("#DynForm").append("<input type='hidden' name='id' value='" + id + "' />");
    $("#DynForm").attr("action", "/Comment/Index");
    $("#DynForm").submit();
    return false;
};

As you can see, the javascript inserts a hidden input tag with the key value. The javascript-free version works fine, but i experience some issues with the javascript. When clicking the Comment button for any item the first time, it works fines. If I hit back then click any Comment link, the page shows up as if I clicked the first link again. Upon inspection, I noticed that the url parameters get 'stacked' for each subsequent 'Back' and 'Click'
/Comment?id=1
/Comment?id=1&id=2
/Comment?id=1&id=2&id=3

If I navigate to the page again (without going back), the first link will work again then start this strange behavior. Looking at the page source after clicking a few links, I see no new hidden fields that would add these additional parameters. Is this a known issue? How can I further debug this and fix it?

A: This isn't a bug, it's a feature :)
Your browser is caching the page, so when you go back you're not refreshing it, you're returning to it as it was, i.e., with the hidden input field.
All you need to do is remove that field before you append it again.
function CommentSubmit(id) {
    $("input[name=id]").remove();
    $("#DynForm").append("<input type='hidden' name='id' value='" + id + "' />");
    $("#DynForm").attr("action", "/Comment/Index");
    $("#DynForm").submit();
    return false;
};


text:
Q: My excel file is in Germany(German) format and would like to change to English(UK) format I have tried multiple codes such as this

Sub DateFixer()
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False
        For Each r In Selection
            v = r.Text
            r.Clear
            r.NumberFormat = "dd/mm/yyyy hh:mm:ss"
            r.Value = DateSerial(Mid(v, 7, 4), Mid(v, 4, 2), Left(v, 2)) + TimeSerial(Mid(v, 12, 2), Mid(v, 15, 2), Right(v, 2))
        Next r
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True
End Sub

and this
Application.ActiveWorkbook.Worksheets("data").Range("A1:A3").NumberFormat = "dd/mm/yyyy hh:mm:ss am/pm
"

and this
Sub changeformat()

    Dim lastrow As Long
    lastrow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
    'MsgBox lastrow
    For i = 2 To lastrow
        Cells(i, 2).NumberFormat = ("dd/mm/yyyy hh:mm:ss am/pm")
    Next i

End Sub

But it still did not change my DateTime to 9/12/20 09:28:00 am. May i know what did i do wrongly?

A: You can do it splitting each part and forcing them into dates. Then sum up and then change format:

Sub changeformat()

Dim lastrow As Long
Dim i As Long

lastrow = Cells(Rows.Count, 1).End(xlUp).Row

For i = 2 To lastrow
    Cells(i, 1).Value = CDate(Replace(Split(Cells(i, 1), " ")(0), ".", "/")) + CDate(Split(Cells(i, 1), " ")(1))
    Cells(i, 1).NumberFormat = ("dd/mm/yyyy hh:mm:ss am/pm")
Next i

End Sub

After executing code I get:

Notice the value 9.12.20 09:27:60 can't be converted because 09:27:60 is not a valid time. Seconds always go from 00 to 59, not from 1 to 60. So actually 09:27:60 should be 09:28:00
I'm afraid you'll need to code an exception for this cases.

A: As shown by the fact that, when in General format, the cell is still displaying a date/time string, the date/time stamps are Text strings and not "real" Excel dates (which are stored as days and fractions of a day).
First we have to convert the string to a "real" date.  Then one can use the .NumberFormat property to display it in a cell however we want.
Fortunately, the format seems fixed so we can split on the dot/space and colon to get the different date/time parts.
The code below assumes

*

*all the dates are text strings

*the number format codes for dates are mdy and for time hms
As written, the results will be written in the adjacent column. To change it in place, see the comments in the code.
Option Explicit
Sub dateFixer()
    Dim vSrc As Variant, vRes As Variant
    Dim rSrc As Range, rRes As Range
    Dim V, W, X, I As Long

With ActiveSheet
    Set rSrc = .Range(.Cells(2, 1), .Cells(.Rows.Count, 1).End(xlUp))

    'set rRes = rSrc to overwrite original
    Set rRes = rSrc.Offset(rowoffset:=0, columnoffset:=1)
End With

'read into vba array for speedy processing
vSrc = rSrc

'Dim output array
ReDim vRes(1 To UBound(vSrc, 1), 1 To UBound(vSrc, 2))

'process the string dates
For I = 1 To UBound(vSrc, 1)
    V = Split(vSrc(I, 1), ".") '0=day, 1 = month
    W = Split(V(2), " ")  ' 0=year
    X = Split(W(1), ":")   ' 0,1,2 = hr:min:sec

    vRes(I, 1) = DateSerial(W(0), V(1), V(0)) + TimeSerial(X(0), X(1), X(2))
Next I

'Write the results back to the worksheet
Application.ScreenUpdating = False
With rRes
    .EntireColumn.Clear
    .Value = vRes
    .NumberFormat = "dd/mm/yy hh:mm:ss"
End With

End Sub


text:
Q: Is PHP Azure going to get PHP 5.5 or 5.6? I have been running a PHP web service on Azure VMs because of an older problem with the Azure PHP Powershell scripts, which has since been fixed. However, it seems that the PHP cloud services only support up to PHP 5.4 which is useless for loads of new features and specifically, in my case, the latest Amazon SDK. I want to change back because cloud services are much better supported by MS and are slightly cheaper than VMs.
I can't find where this PHP Azure project is actively maintained and whether there are any plans for 5.5 or 5.6 support or whether there is a way to get this to work on cloud services as opposed to VMs?

A: The current Web App Application Settings let you choose the follow PHP Versions:

*

*5.4

*5.5

*5.6

Maybe you are using a old service. Try the new "Web App".


text:
Q: How to paste data from Excel into cxGrid I have a Delphi application using DevExpress cxGrid (which is connected to database).
I require to be able to copy-paste data from Excel into the grid.
Is this possible? If so, how to do it, which additional components do i need?

A: Check the format with Clipboard.HasFormat(CF_TEXT).
Extract the text with Clipboard.AsText.
Split into rows with StringList.Text := Clipboard.AsText.  Each item in the string list is now a row from the clipboard.
Split each row into individual cells using a Split function:
function Split(const s: string; Separator: char): TStringDynArray;
var
  i, ItemIndex: Integer;
  len: Integer;
  SeparatorCount: Integer;
  Start: Integer;
begin
  len := Length(s);
  if len=0 then begin
    Result := nil;
    exit;
  end;

  SeparatorCount := 0;
  for i := 1 to len do begin
    if s[i]=Separator then begin
      inc(SeparatorCount);
    end;
  end;

  SetLength(Result, SeparatorCount+1);
  ItemIndex := 0;
  Start := 1;
  for i := 1 to len do begin
    if s[i]=Separator then begin
      Result[ItemIndex] := Copy(s, Start, i-Start);
      inc(ItemIndex);
      Start := i+1;
    end;
  end;
  Result[ItemIndex] := Copy(s, Start, len-Start+1);
end;

A: You can check the content of the clipboard after you copy content from the Excel app. and then on CTRL+V shortcut you parse the content of the clipboard and set data to their respective cells.


text:
Q: Does python support enumerated types? Is there a way to have C++ like enumerated types like in Python? For example, in C++ I can do:
enum Foo {
    bar,
    foobar,
    blah
};

and use these as global constants. Is there a similar thing in Python?

A: From the Docs:
Enumerations are created using the class syntax, which makes them easy to read and write. An alternative creation method is described in Functional API. To define an enumeration, subclass Enum as follows:
>>>
>>> from enum import Enum
>>> class Color(Enum):
...     red = 1
...     green = 2
...     blue = 3

A: Python3.4+ supports various types of enumerations in the enum module.  Obviously it's not quite the same as an enumerated type in C or C++, but it serves the same purpose.  If you're stuck in an older version of python, there's a 3rd party backport available on pypi.
Basic usage would look like:
class Foo(enum.Enum):
    bar = 1
    foobar = 2
    blah = 3


text:
Q: How to open a saved Google Onhub diagnostic report? I have a saved Google Onhub diagnostic report. With Notepad I can't see the whole file, because it's encrypted. A Hex-Editor won't open it neither.
Can someone tell me if there is a program to open it correctly?
Thank you!

A: It's a protobuf encoded file, containing an archive of files and other data entries.
There's a Go project on github that decodes it, and even if you don't run their Go code, you can use the protobuf schema that's available in that repository to decode the report in whichever environment you choose using the protobuf bindings available in the official website


text:
Q: Displaying a div layer over a frameset? i have two framesets like below
<FRAMESET ROWS="*, 0">
   <FRAME SRC="index.php" FRAMEBORDER=0 id="contentfrm" name="contentfrm">
   <FRAME SRC="music.php" FRAMEBORDER=0 id="musicfrm" name="musicfrm" NORESIZE SCROLLING="no" >
  </noframes>
</FRAMESET><noframes></noframes>

My first frame is website with full screen,second frame have some music player,
so when user clicking on first frame link i need to add some loading animation for full page,
i can track the click event of the first frame site within second frame.
but i don't know how to append some contents to html of page for 4-5 seconds (html of the current page not the frame ).
can anyone tell me how to cover the page(append some html to page for little time) for 5-6 second when i click on first frameset link thank you

A: you can use delay on jquery - but if you want to allow users to cancel loading frame two you should use this code:
$('#contentfrm').click(function(){
   $('.animationgif').show();
   time = setTimeout(function() {
        $('.animationgif').hide();
        $('#musicfrm').show();
    },500);
});
$('.cancel').click(function(){
   $('.animationgif').hide();
   clearTimeout(time);
});


text:
Q: Does jqGrid or jQuery have the functionality of caching DOM changes inside a string For example, if we have select/option/dropdown box in html. 1) is faster than 2) in jQuery if we have an array size of 5000.
1) make a string first:
var str = '';
for (var i = 0; i<an_array.length; i++) {
  str +='<option value="' + an_array[i] + '">' + an_array[i] + '</option>';
}
jQuery("#my_select").append(str);

2) append every time:
for (var i = 0; i<an_array.length; i++) {
  jQuery("#my_select").append(
    jQuery('<option></option>').val(an_array[i]).html(an_array[i])
  );
}

My question is: does jQuery or jqGrid have such kind of function that makes a cache string first and then post everything on html when done? Or are we already using this way in jqGrid? The reason I am asking this question is that seems jqGrid is really slow when I have more than 500 columns. This is just like in C. You can either auto flush to a file every time you do fprintf, or you can manually flush it when you are done.
Thanks in advance.

A: I've seen it said several times in the jQuery documentation that cached objects should always be used when re-iterating the same DOM content multiple times because it takes more processing power to walk the DOM each time.
I would code your solution thus:-
HTML
<select id="my_select"/>

JavaScript/jQuery
//an array to use for demonstration
var arr = ["one", "two", "three", "four", "five"];

var $frag = $();
$.each(arr, function () {
    $frag = $frag.add($("<option/>").val(this).text(this));
});
$("#my_select").append($frag);

Note the line var $frag = $();. The $() creates an empty jQuery object, and I have prefixed the variable name $frag with a $ simply to remind myself that it's a jQuery object rather than a text string.
Hope that answers your question satisfactorily.
Best regards,
Alan


text:
Q: Firebase Auth/unauthorized domain. Domain is not authorized ---What should i do..? I am trying to run this sample firebase project, but I keep getting this error in the browser console.
message: "Error: auth/unauthorized-domain"


text:
Q: selecting each week of kendo calendar Hi Is there any way to get first day and last day of each week of Kendo Calendar? Like below?

A: You can do it using jQuery as:
// Create calendar
var cal = $("#cal").kendoCalendar({}).data("kendoCalendar");

// Print first and last date on each row
$("tbody > tr", cal._table).each(function(idx, elem) {
    console.log($("td:first", elem).text(), $("td:last", elem).text());
})

What I do is get the table that represents the calendar cal._table and the iterate on each row of the body of the table.
Then I extract the text of the first and last cell of the row.
Running example here : http://jsfiddle.net/OnaBai/W9VFB/


text:
Q: Ajax/PDO return lastInsertId not working I would like to use the lastInsertId on the success event. The request work fine I can insert a new element but nothing return.
function.js
function add_elem(i)
{
var mydata ="e1="+0+"&e2="+0+"&e3="+100+"&e4="+100+"&e5="+i+"&addelem=1";
$.ajax({
    url:"edit.php",
    type:'POST',
    data: mydata,
    success: function(f) {
        alert(f);
    },
    error: function() {
        alert('error try again');
    }
});

edit.php
<?php include"inc/config.php";
$positionx=$_POST['e1'];
$positiony=$_POST['e2'];
$lar=$_POST['e3'];
$haut=$_POST['e4'];
$typ=$_POST['e5'];
if(isset($_POST['addelem']))
{
    $req_add=$bdd->prepare('insert into elem (element_position_x,element_position_y,element_width,element_height,element_type)
                            values(:posx,:posy,:width,:height,:type)');
    $req_add->execute(array(
        'posx' =>$positionx,
        'posy' =>$positiony,
        'width' =>$lar,
        'height' =>$haut,
        'type' =>$typ
        )
    );
return $bdd->lastInsertId();
} ?>

Did I miss something ?
Edit:
Solved by changing :
return $bdd->lastInsertId();
to :
echo $bdd->lastInsertId();
Thank to Michael Berkowski.

A: If you get result from:
$bdd->lastInsertId();

Try use dataType param in your ajax request (dataType: "JSON")
 $.ajax({
     url:"edit.php",
     type:'POST',
     dataType: "json"
     data: mydata,
     success: function(f) {
         alert(f);
     },
     error: function() {
         alert('error try again');
     }

And at server side when you get result you should encode to json and echo backward to browser. For example:
  $req_add->execute(array(
       'posx' =>$positionx,
       'posy' =>$positiony,
       'width' =>$lar,
       'height' =>$haut,
       'type' =>$typ
    ));
  $result = $bdd->lastInsertId();
  echo json_encode($result);

A: Server side, you can use JSON to format output of your request:
$req_add->execute(array(
   'posx' =>$positionx,
   'posy' =>$positiony,
   'width' =>$lar,
   'height' =>$haut,
   'type' =>$typ
));
$result = array('id'=>$bdd->lastInsertId());

header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');

echo json_encode($result);
exit;

And client side, you can use dataContent property in jquery ajax to handle results :
$.ajax({
    url:"edit.php",
    type:'POST',
    dataType: "json"
    data: mydata,
    success: function(data,txt,xhr) {
        var myNewId = data.id;
    },
    error: function() {
        alert('error try again');
    }


text:
Q: Image is not uploaded through android app with PHP 8 in a new linux server In a shared host Linux server,
I have a PHP code which uploads an image on the server
On the other side I have an Android application which sends http post request to upload the image
Everything is working fine
Now I've purchased a Linux server which is not a shared host
In other word, I have complete control over the server
I've installed Nginx and php 8 (php version on the shared host was 5)
Now

$_FILES

on the server side has nothing in it
In other words, the image is not uploaded at all
To test more I utilized the following codes to see if I ignore the Android application what will happen and everything worked fine:
<!DOCTYPE html>
<html>
<body>

<form action="upload2.php" method="post" enctype="multipart/form-data">
  Select image to upload:
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
  $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
  if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
  } else {
    echo "File is not an image.";
    $uploadOk = 0;
  }
}

// Check if file already exists
if (file_exists($target_file)) {
  echo "Sorry, file already exists.";
  $uploadOk = 0;
}

// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
  echo "Sorry, your file is too large.";
  $uploadOk = 0;
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
  echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
  $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
  echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
  if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
  } else {
    echo "Sorry, there was an error uploading your file.";
  }
}
?>

So I feel Android request is not truly processed here while it was ok in the shared host
Following you could see the main part of the Android application too:
 public static String ServiceCall_TextCommand(String mFileName, String mFileDestination, String mFileData) {

        Log.e("asa", "proprotttwwww 13 ");
        int serverResponseCode = 0;
        //String fileName = sourceFileUri;
        String fileName = mFileName;
        //String fileName = "/storage/emulated/0/DCIM/Screenshots/A5.png";

        //String fileName = "JSONFile.json";

        String upLoadServerUri = null;
        /************* Php script path ****************/
        upLoadServerUri = mFileDestination;

        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        //int bytesRead, bytesAvailable, bufferSize;
        int bufferSize;
        byte[] buffer;
        //int maxBufferSize = 5 * 1024 * 1024;
        //int maxBufferSize = 1024 ;
        /*File sourceFile = new File(sourceFileUri);
        if (!sourceFile.isFile()) {
            Log.e("uploadFile", "Source File not exist :" + sourceFileUri);
            return "0";
        }
        else {*/

        try {
            // open a URL connection to the Servlet
            //FileInputStream fileInputStream = new FileInputStream(json);
            //FileInputStream fileInputStream = new FileInputStream(sourceFile);

            URL url = new URL(upLoadServerUri);

            // Open a HTTP  connection to  the URL
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            //conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;boundary=" + boundary);

            //conn.setRequestProperty("userfile", fileName);
            conn.setRequestProperty("uploaded_file", fileName);
            //conn.setRequestProperty("Content-Length", Integer.toString(fileInputStream.available()));

            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            //dos.writeBytes("Content-Disposition: form-data; name="uploaded_file";filename=""
            //                + fileName + """ + lineEnd);

            //dos.writeBytes("Content-Disposition: form-data; name=uploaded_file;filename="
            //                + fileName + "" + lineEnd);

            //dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
            //        + fileName + "\"" + lineEnd);

            //dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName + "\"" + lineEnd);

            dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\"; filename=\""
                    + fileName + "\"" + lineEnd);

            //int length = fileInputStream.available();
            //Log.e(TAG, "lllllllllllllllllll: "+length);

            dos.writeBytes(lineEnd);

            // create a buffer of  maximum size
            //bytesAvailable = fileInputStream.available();

            //int totalBytes = bytesAvailable;

            //bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bufferSize = mFileData.length();
            //buffer = new byte[bufferSize];
            buffer = mFileData.getBytes(Charset.forName("UTF-8"));
            //buffer = mFileData.getBytes(Charset.forName("ISO-8859-1"));

            // read file and write it into form...
            //bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            //int cnt =0,cnt2;
            //while (bytesRead > 0) {
            //cnt++;
            //publishProgress(""+(int)((cnt*100)/1000));
            dos.write(buffer, 0, bufferSize);
            //bytesAvailable = fileInputStream.available();
            //bufferSize = Math.min(bytesAvailable, maxBufferSize);
            //bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            //cnt++;
            //cnt2 = (cnt*100*maxBufferSize)/totalBytes;
            //Log.e(TAG, "llbytesRead:cnt2 = "+cnt2+"Total ="+totalBytes);
            ////publishProgress(""+cnt2);
            //publishProgress(""+50);

            //}

            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();

            Log.i("BBBuploadFile", "HTTP Response is : "
                    + serverResponseMessage + ": " + serverResponseCode);

            Log.e("sasssssile", "xxxxm File Name : "
                    + mFileName);

            Log.e("sasssssile", "xxxxm File Data : "
                    + mFileData);

            if (serverResponseCode == 200) {

                Log.e(TAG, "Completeeee ");
            }
            else
            {
                return  Constants.ServerResponse_Error_General;
            }

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder total = new StringBuilder();
            String line;
            //Log.d(TAG, "AAe Start ................ " + total.toString().length());

            //long mCounter = 0;

            try
            {
                while ((line = in.readLine()) != null)
                {
//                    mCounter++;
  //                  Log.e(TAG, "AAe mCounter = " +mCounter);
    //                Log.e(TAG, "AAe line = " +line);
                    //Log.e(TAG, "AAe in = " +in);

                    total.append(line).append('\n');
                    //Log.e(TAG, "AAe total = " +total);
      //              Log.e(TAG, "total size = " + total.toString().length());
                }

                /*for (line = in.readLine(); line != null; line = in.readLine()) {
                    mCounter++;
                    //Log.e(TAG, "AAe mCounter = " +mCounter);
                    //Log.e(TAG, "AAe line = " +line);
                    //Log.e(TAG, "AAe in = " +in);

                    total.append(line).append('\n');
                    //Log.e(TAG, "AAe total = " +total);
                    //Log.e(TAG, "total size = " + total.toString().length());
                }*/

            }
            catch (Exception e)
            {
                //Log.e("asa", "proprotttwwww 177777 ");
            }

            //Log.e(TAG, "AAe mCounter2 = " +mCounter);

            //Log.d(TAG, "AAe End ................ " + total.toString().length());

            Log.d(TAG, "AAAServer Response total.toString().length is BB: " + total.toString().length());

            //Log.d(TAG, "AAAServer Response1111 is: " + total.toString() + ": " + serverResponseCode);

            largeLog(TAG,"AAAServer Response1111 is: " + total.toString() + ": " + serverResponseCode);

            //Log.d(TAG, "AAAServer Response is: " + total.toString() + ": " + serverResponseCode);

            //close the streams //
            //fileInputStream.close();
            dos.flush();
            dos.close();

            // Verify Command Response Checksum
            String mServerResponse = total.toString();
            mServerResponse = getStringBetween(mServerResponse,"@#@","#@#");
            Log.e("sds", "Server Response #######between########### Data:"+ mServerResponse);

            if (ValidateChecksum_WithoutCheckRange(mServerResponse) == false)
            {
                Log.e("sds", "Server Response ################## Error: ValidateChecksum");
                return Constants.ServerResponse_Error_General;
            }
            Log.e("sds", "Server Response ################## : ValidateChecksum: TRUE");

            String mCommand_Response_CommandName = SubString(mServerResponse,0,2);
            String mCommand_Send_CommandName     = SubString(mFileData,0,2);
            if (Validate_CommandResponse_CommandName(mCommand_Send_CommandName,mCommand_Response_CommandName) == false)
            {
                Log.e("sds", "Server Response ################## Error: CommandName");
                return Constants.ServerResponse_Error_General;
            }
            Log.e("sds", "Server Response ################## : CommandName: TRUE");

            String mCommand_Response_UserID = SubString(mServerResponse,0,2);
            String mCommand_Send_UserID     = SubString(mFileData,0,2);
            if (Validate_CommandResponse_UserID(mCommand_Send_UserID,mCommand_Response_UserID) == false)
            {
                Log.e("sds", "Server Response ################## Error: UserID");
                return Constants.ServerResponse_Error_General;
            }
            Log.e("sds", "Server Response ################## : UserID: TRUE");

            String mCommand_Response_MagicCode = SubString(mServerResponse,0,2);
            String mCommand_Send_MagicCode     = SubString(mFileData,0,2);
            if (Validate_CommandResponse_MagicCode(mCommand_Send_MagicCode,mCommand_Response_MagicCode) == false)
            {
                Log.e("sds", "Server Response ################## Error: MagicCode");
                return Constants.ServerResponse_Error_General;
            }
            Log.e("sds", "Server Response ################## : MagicCode: TRUE");

            return mServerResponse;

            /*if (ProcessCommandResponse(helper,mCommand_Response_CommandName,mServerResponse) == false)
            {
                Log.e("sds", "Server Response ################## Error: ProcessCommandResponse =>"+mCommand_Response_CommandName);
                return Constants.ServerResponse_Error_ProcessCommandResponse;
            }
            else
            {
                Log.e("sds", "Server Response ################## Success");
                return Constants.ServerResponse_Success;
            }*/

            /*if (total.toString().contains("Move successful") == true )
            {
                Log.e(TAG, "Move To Server successful");
                return "Move To Server successful";
            }
            else if (total.toString().contains("JSONLastFile =") == true)
            {
                String FileNum = getBetweenStrings(total.toString(),"JSONLastFile =","dump end");
                Log.e(TAG, "Dump Ok , FileNum = "+FileNum);

                if (FileNum.length() >= 12) //Phone Number
                {
                    return total.toString();
                }
                else
                {
                    return FileNum;
                }

            }
            else
            {
                Log.e(TAG, "Move To Server Failed");
                return "Move To Server Failed";
            }*/

        } catch (MalformedURLException ex) {

            Log.e("asa", "proprotttwwww 18 ");
            //dialog.dismiss();
            ex.printStackTrace();
            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
            return Constants.ServerResponse_Error_General;
        } catch (Exception e) {

            Log.e("asa", "proprotttwwww 19 ");
            //dialog.dismiss();
            e.printStackTrace();
            Log.e(TAG, "111222Exception: " + e.getMessage());
            return Constants.ServerResponse_Error_General;
        }

        //}
        //dialog.dismiss();
        //return serverResponseCode;
    } // End else block

Another strange point is when I check the

/Var/log/nginx/error.log

I see the following code which indicated this is a get http request not a Post one:
2022/07/21 05:29:41 [error] 1881#1881: *875 FastCGI sent in stderr: "PHP message: PHP Warning:
And
    request: "GET /upload.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php8.1-fpm.sock:", host:

A: Problem Solved!
The problem was just adding www to the url address from Android side
I changed

https://www. example.com/upload2.php

to

https:// example.com/upload2.php

and the problem was solved
The point is in the server administration panel, I had set that every

www. example.com

request would be automatically redirected to

example.com

Now I reversed it and the problem is solved with the following url from Android side:

https://www. example.com/upload2.php


text:
Q: left join table on string like '%table.name%' I am trying to left join products.table and manufacturer.table to implement the manufacturer into the products table
The only problem there is no id linking the tables, so I am trying something like this.
 SELECT [kArtikel]
  ,[cArtNr]
  ,a.[cName]
  ,a.[cBeschreibung]
  ,H.cName
  ,[cKurzBeschreibung]
  ,[cHersteller]
  ,[cHAN]
  FROM [db].[dbo].[tartikel] a
  left join [db].[dbo].[tHersteller] h on a.cName Like '%H.Cname%'
  where cHersteller is null

But with this query I am recieving only H.cName = Null
After 2 min execute with the same number of products, having cHersteller = Null
While searching I only find examples where join is on some id with where clause. But this is not the possible here.

A: You are querying whether a.cName contains the literal H.Cname, which is probably not what you were gunning for. If you want to have  wildcards around H.Cname, you can use the + operator:
SELECT [kArtikel]
  ,[cArtNr]
  ,a.[cName]
  ,a.[cBeschreibung]
  ,H.cName
  ,[cKurzBeschreibung]
  ,[cHersteller]
  ,[cHAN]
FROM [db].[dbo].[tartikel] a
LEFT JOIN [db].[dbo].[tHersteller] h ON a.cName LIKE '%' + H.Cname + '%'
WHERE cHersteller IS NULL


text:
Q: Is it possible to get a list of suggestion comments from a given google file in a google drive account? I have a file in my google drive account that has many suggestions created from users in "Suggesting" mode. Suggestions are comments, but made in suggesting mode. When in "Suggesting" mode the user can not make edits, but can instead make suggestions, and when a suggestion is created it creates a comment such as: Replace the word "Hello" with "Hi".
Google Drive API has a Comments API that will allow me to list all comments created for a file. However, it does not list "suggestion" comments.
https://developers.google.com/drive/v2/reference/comments/list
Is there a way to get a list of suggestion comments for a file, instead of just comments?


text:
Q: NodeJS: What's the most efficient way to read the last X bytes of a very large file (+1GB)? I would like to efficiently read the last X bytes of a very large file using node.js. What's the most efficient way of doing so?
As far as I know the only way of doing this is by creating a read stream and loop until a hit the byte index.
Example:
// lets assume I want the last 10 bytes;
// I would open a stream and loop until I reach the end of the file
// Once I did I would go to the last 10 bytes I kept in memory

let f = fs.createReadStream('file.xpto'); //which is a 1gb file
let data = [];

f.on('data', function(data){
    for (d of data){
        data.push(d)
        data = data.slice(1,11); //keep only 10 elements
    }

})
f.on('end', function(){
    // check data
    console.log('Last test bytes is', data)
})
f.resume();

A: You essentially want to seek to a certain position in the file. There's a way to do that. Please consult this question and the answers:
seek() equivalent in javascript/node.js?
Essentially, determine the starting position (using the file length from its metadata and the number of bytes you're interested in) and use one of the following approaches to read - as stream or via buffers - the portion you're interested in.

Using fs.read

fs.read(fd, buffer, offset, length, position, callback)
position is an argument specifying where to begin reading from in the file.

Using fs.createReadStream
Alternatively, if you want to use the createReadStream function, then specify the start and end options: https://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options

fs.createReadStream(path[, options])
options can include start and end values to read a range of bytes from the file instead of the entire file.

A: Here's the sample code based on Arash Motamedi answer.
This will let you read the last 10 bytes of a very large file in a few ms.
let fs = require('fs');

const _path = 'my-very-large-file.xpto';
const stats = fs.statSync(_path);

let size = stats.size;
let sizeStart = size-10;
let sizeEnd = size;

let options = {
    start: sizeStart,
    end: sizeEnd
}
let stream = fs.createReadStream(_path, options)
stream.on('data',(data)=>{
    console.log({data});
})
stream.resume()

A: For a promised version of the read solution:
import FS from 'fs/promises';

async function getLastXBytesBuffer() {
  const bytesToRead = 1024; // The x bytes you want to read
  const handle = await FS.open(path, 'r');
  const { size } = await handle.stat(path)

  // Calculate the position x bytes from the end
  const position = size - bytesToRead;

  // Get the resulting buffer
  const { buffer } = await handle.read(Buffer.alloc(bytesToRead), 0, bytesToRead, position);

  // Dont forget to close filehandle
  await handle.close()

  return buffer
}


text:
Q: Multiple domains with wildcard certificates on single Apache2 virtual host Is there any good way to use multiple wildcard certificates with single Apache 2 VirtualHost?
I have one IP based VirtualHost which is hosting websites from multiple domains. Each domain has wildcard certificate and I have been trying a way to make as compact as possible configuration file for this kind of situation.
At the moment, I have one VirtualHost for each main domain, but the configuration file is getting quite large when I am adding more domains.

A: You need to follow the general SSL Certificate installation guide for Apache2 Virtual Host, there is no other simple option available.
Make sure to enable the SNI.

A: If you have one IP, you can define multiple VirtualHosts on it. Every VirtualHost has its own certificate and ServerName and that works well together with SNI.
The "problem" is, that there is no configuration option for this kind of problem. This is a "limitation" of mod_ssl configuration options. You could use additional domains in the certificate, in that case you have one vhost per DocRoot.
If the size of the configuration is your problem, then it would be a good advice to use a configuration directory (with include) and put one file per domain or virtualhost in it. That's the way, distributions are managing vhosts. In this case you can easily switch or copy to the configuration you need. In my case (900 domains) this works very well. I've also added variables on the beginning of a domain vhost file that is used inside the configuration for DocRoot, Logfile, ServerName and ServerAliases.


text:
Q: Checking if email address already exists in db I'm trying to error handle a registration aspx/c# page on my application and want to run a check whether the email address that a user has tried to register already exists as the email address is used as a primary key in my database.
I have tried IF NOT EXISTS/IF EXISTS but these dont give the desired effect so was wondering if there was another way around it?
Look forward to your reply,
Scott

A: select count(*) from users where email = @email

(int)executescalar > 0 == dupe

A: First answer certainly works, but a slightly more performant example would be:

select top 1 null from users where email = @email

on large or poorly-indexed tables.


text:
Q: I enable mssql in IIS, but I can't connect sql server. How to fix it I can not connect Sql Server 2012 with mssql extension. Please help me to fix it. I Got this message in error log.

PHP Warning:  PHP Startup: Unable to load dynamic library 'C:\Program
  Files (x86)\PHP\v5.2.17\ext\php_mssql.dll' - The specified module
  could not be found.  in Unknown on line 0

Thanks


text:
Q: "Progressively" loading entities from RESTful API in NgRx I'm building an application using Angular 7 and NgRx, and trying this with the Entity State Adapter.
I want to ask for one or more objects from NgRx by ID, but if it's not in the store, I want to ask for it from the RESTful API, then put it in the NgRx store.
I built the RESTful API and can ask for any number of objects with an array of IDs, and I read about how I can select objects from NgRx using one or more IDs, and I know how to load data into NgRx using effects and reducers.
But, how can I get the system to work so that if I ask for one or more objects by ID, it will return the existing ones from the store if they exist and/or update the store by requesting them from the RESTful API.
There's a lot of data so pre-loading it all is inefficient, but there are mixed uses where I'll need to show a list of many, or show a single one, or show related objects by ID, etc.
For example:
List page wants IDs 0-10 to show in a list. Ask the store for them, store doesn't have them, so it gets them from the API. Now the store has 0-10 and the list displays them.
Details page wants ID 10, the store has it from previous loading the list page (in this case), but it also wants ID 13 and 14 because they're related, so I'm going to ask for 10, 13, and 14. The store has 10 so it displays immediately, but has to request 13 and 14 from the RESTful API and populates the store when they return.
List page shows "page 2", which is IDs 11-20, and 13 and 14 are already in the store, so it just has to go get 11-12 and 15-20 from the API, etc.
Multiplied by thousands, because there's too much data to just load locally all at once.
My bad solution:
My thought about achieving this is have a selector for id[], and that selector returns whichever IDs already exist in the store, and then dispatches an action for the missing IDs so then the effects and reducers do their job. I don't know how to get a selector to dispatch an action (if that's even the right approach).
Alternately, in the component asking for the data, it dispatches the action for whatever data doesn't come back from the selector, but putting that logic in the component isn't a good place for it.
I thought about putting it in a service, which seems rational, but I'm not sure how then to communicate the store/state to the component and the service without having to duplicate a bunch of code, and/or how to pass state updates through the service to the component, and other weird realtime state issues.

A: You could return the missing ID's from the selector (instead of list of found id's return an object containing a list of found entities and array of missing id's if any), and then in the subscription (or tap if you utilise $async pipe) dispatch the action which will fetch the missing id's via Effect.
Something like this:
export const $mySelector = createSelector($someEntitySelector, (entities, props: { ids: string[] }) => {
  const items = [];
  const missingIds = [];

  props.ids.map(id => {
    if (entities[id]) {
       items.push(entities[id]);
    } else {
       missingIds.push(id);
    }

  })

  return {
    items,
    missingIds
  }
});

in the component:
  this.store$.select($mySelector).pipe(
    tap({items, missingIds} => {
       if (missingIds) {
         // dispatch action that will trigger the effect
       }
    })

  )

You would definitely need to handle a case where there is no ID on the server (if the service doesn't find it safest bet is to delete that id so it doesn't call the service again for no reason)


text:
Q: why do we use KeyValuePair keyword instead of Dictionary keyword as the type in foreach loop? am just learning c# and wanted to use the type instead of var in foreach loop while using the dictionary, but it gave me error when i used Dictionary
Dictionary<int, string> names = new Dictionary<int string>();

names[10] = "some test";
names[11] = "another text";

foreach(Dictionary<int,string> name in names)
{
    Console.WriteLine(name);
}

A: Ultimately, the dictionary doesn't contain multiple dictionaries; it contains (semantically, at least): multiple key/value pairs - hence that is what foreach gives you, via multiple KeyValuePair<int, string> values. You can use this without even needing to know about the type:
foreach (var pair in names)
{
    Console.WriteLine(pair.Key);
    Console.WriteLine(pair.Value);
}

(which is identical to foreach (KeyValuePair<int, string> pair in names))
or:
foreach ((var key, var value) in names)
{
    Console.WriteLine(key);
    Console.WriteLine(value);
}

(you can also use var (key, value) or (int key, string name) as the enumerator declaration)


text:
Q: Socket.io - How to prompt for username, and save the username in an array? I have got a basic chatroom which detects when users connect to the server, and leave.
Now I would like to prompt the user to enter a username when he joins the server, how can I do that?
Code is below:
Index.html

Server.js
var io = require('socket.io'),
  connect = require('connect');

var app = connect().use(connect.static('public')).listen(3000);
var game_room = io.listen(app);

game_room.sockets.on('connection', function (socket) {
    socket.emit('entrance', {message: 'Welcome to the chat room!'});
    socket.emit('entrance', {message: 'Your ID is #' + socket.id});

    socket.on('disconnect', function  () {
        game_room.sockets.emit('exit', {message: 'A chatter has disconnected.'});
    });

    socket.on('chat', function  (data) {
        game_room.socket.broadcast.emit('chat', {message: '# ' + data.message});
    });

    socket.broadcast.emit('entrance', {message: 'A new chatter is online.'});
});

A: You can just add this to your server code:
var users = [];

game_room.sockets.on('connection', function (socket) {
    socket.emit('entrance', {message: 'Welcome to the chat room!'});
    socket.emit('entrance', {message: 'Your ID is #' + socket.id});

    socket.on('adduser', function (name) {
       users.push(name);

       // attempt to clean up
       socket.once('disconnect', function () {
         var pos = users.indexOf(name);

         if (pos >= 0)
           users.splice(pos, 1);
       });
    });

    // ...
});

(it won't work if 2 users choose the same name.)

A: server.js
io.on('connection', function(socket){
  socket.on('newuser', function(nick){
   var newUser = nick;
   console.log(newUser + ' connected');
   io.emit('connection2', newUser + ' connected.');
   socket.on('disconnect', function(){
     console.log('user disconnected');
     io.emit('disconnection', newUser + ' disconnected.');
   });
   socket.on('chat message', function(msg){
     io.emit('chat message', msg);
   });
 });

index.html - In the


text:
Q: How can I prevent autosubmitting in FormPage? If I deploy this code:
CloudDeploy[FormPage[{"x" -> <|"Input" -> "Apple"|>}, Identity]]

When I execute the URL the form is automaticaly submitted as in the image below

To prevend auto submitting, as mentioned in this post, I tried:
CloudDeploy[FormPage[{"x" -> <|"Input" -> "Apple", "AutoSubmitting" -> False|>}, Identity]]

...but without success. Any clue?
The real case is a form with some default values that can be changed before the submition.

A: Using @rowsi's hint, in my real world case "Apple" is a variable, so we need Evaluate to solve It:
myVar = "Apple";
CloudDeploy@FormPage[
      {"x" -> <|"Input" -> HoldForm@Evaluate[myVar]|>}
      , Identity
  ]


text:
Q: How to bind data in asp.net c# treeview control I have never used treeview control in asp.net but now I need to bind data to it. My stored procedure from sql server is returning the the values as below. I m using c#
TermID  ParentID  Name
2021    0          A. Geographic locations
3602    2021       Oceania
3604    3602       Australasia
3621    3604       New Zealand
3619    3604       Pacific Islands
3585    3619       Polynesia
3592    3585       Samoa
3594    3592       American Samoa

Each Term has parentID and any TermID with ParentID=0 is the root node. How can we bind this data to treeview. I will appreciate any advise or examples

A: This may be useful :
TreeView control expects a heirarchical data structure like xml/sitemaps, so we cant bind the DataTable to it directly. Use data table Select where ParentID = ID
Please use a recursive method to create child items relevent to current menu item ID, refer to link below for code.
http://www.charith.gunasekara.web-sphere.co.uk/2010/10/how-to-bind-datatable-to-aspnet.html
n below link will help you creating ur own tree view control.
http://www.codeproject.com/KB/tree/DataBoundTreeView.aspx


text:
Q: WCF Configuration Reference Where is the definitive .NET WCF configuration reference documentation?
I need some documentation that lists every configuration option, with helpful descriptions of what each setting actually means.

A: This documentation should help you out a lot.
Windows Communication Foundation Configuration Schema
It lists all the possible configuration settings for Windows Communication Foundation (WCF).
The visualization of all the configuration settings allows for a unique perspective. At the end of the article, there are a few links which if you follow will bring you into expanded discussion and documentation. If you want to just reference any of the settings found in the schema, there will be an article on MSDN expanding on it - just search for it.


text:
Q: Как в gitlab ci log скрыть вводимые команды (echo off)? Сейчас в логах сборок вывод примерно такой (bash):
...
$ echo "Finish recompile objects"
Finish recompile objects
$ echo "BUILD - OK"
BUILD - OK
...

То есть при просмотре выводятся вводимые команды и их результат. Есть ли возможность скрыть команды и оставить только вывод?
...
Finish recompile objects
BUILD - OK
...

В cmd есть режим echo off, вот хотелось бы активировать такой же.
Буду благодарен за любые идеи :)

A: Как правильно направил aleksandr barakin в комментариях, решение заключается в многострочном скрипте с использованием | (literal)
myjob:
  script:
  - |
    # printing the job information
    echo --------------------------
    echo Building ${CI_COMMIT_SHA}
    echo --------------------------

На выводе в логе будет следующий результат:
(...)
$ # printing the job information # collapsed multi-line command
--------------------------
Building 629fcab9e39f8564cb2a0d1a7f104e2312a22288
--------------------------
(...)

В итоге, вводимые команды не отображаются, кроме первой, а вывод от них корректно отображается.
Больше вариантов решения можно увидеть в этом обсуждении - https://gitlab.com/gitlab-org/gitlab-runner/-/issues/4645


text:
Q: Convert Sbyte to integer in c# I can't seem to figure out a way to convert an sbyte back to original integer value.
int k = 148;
sbyte t = (sbyte)k;
int asd = Convert.ToInt32(t);

The value of asd is -108. How can I convert the sbyte back to int to get the original value of 148?
Thanks

A: Assuming you want the result to be in the range 0-255 inclusive, the simplest approach is:
int asd = t & 0xff;

This will promote k to an int, then take just the bottom 8 bits, leaving all the top 24 bits as 0.
However, I'd question why you'd want to use sbyte for this in the first place. It's very very rarely a good idea - one of the design flaws of Java (in my view) was to make byte a signed type. If you want to represent byte values, byte would be more appropriate.

A: As sbyte is in range -128 to 127, ideally your existing method should not return sbyte when the return value can be between 0-255.
But anyway, you can first try converting sbyte into byte and then into int.
I suppose following code should work
int k = 148;
sbyte t = (sbyte)k;
byte b=(byte)t;

Console.WriteLine(b);
Console.WriteLine();

int asd = Convert.ToInt32(b);
Console.WriteLine(asd);

A: An sbyte holds values from -128 to 127 because the first bit represents plus or minus.
Cast your sbyte to byte first, then convert to int.
        int k = 148;
        sbyte t = (sbyte)k;
        int asd = (int)(byte)k;
        Assert.AreEqual(148, asd);


text:
Q: Booktabs table does not show in pdf or doc I get an error when trying to create a pdf that has a booktabs table in it. If I delete the table code, the pdf is created without a problem.
RStudio: Latest version
R: latest version
tinytex: latest version
Below is my Rmd file:
---
title: "table"
author: "Author"
date: "2/13/2021"
output:
  pdf_document:
    latex_engine: xelatex
  html_document:
    df_print: paged
includes:
  in_header: preamble.tex
---

Something here

\begin{table}[h]
    \centering
    \caption{Descriptive Statistics}
    \label{tab:descriptiveStatistics}
    {
        \begin{tabular}{lr}
            \toprule
             & Weight  \\
            \cmidrule[0.4pt]{1-2}
            Valid & 13  \\
            Missing & 0  \\
            Mean & 170.769  \\
            Std. Deviation & 29.255  \\
            Minimum & 140.000  \\
            Maximum & 235.000  \\
            \bottomrule
        \end{tabular}
    }
\end{table}

Below is my preamble.tex file:
\usepackage{booktabs}
\usepackage{makecell}

The error that I get is as follows:
output file: test.knit.md

! Undefined control sequence.
l.81             \toprule

Error: LaTeX failed to compile test.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See test.log for more info.
In addition: Warning message:
In has_crop_tools() :
Tool(s) not installed or not in PATH: pdfcrop, ghostcript
-> As a result, figure cropping will be disabled.
Execution halted

A: Your preamble.tex isn't included because your yaml header is wrong. Should be:
---
title: "table"
author: "Author"
date: "2/13/2021"
output:
  pdf_document:
    latex_engine: xelatex
    includes:
      in_header: preamble.tex
  html_document:
    df_print: paged
---

Then it works.
I would also recommend using kableExtra. It basically produces LaTeX code and saves you a lot of time making tables in my experience. You can set keep_tex: yes (also under pdf_document:) to double-check what is being produced.


text:
Q: Factory Method: Need of Creator hierarchy I am new to design patterns. While going through GOF, one way to implement factory pattern is to create a parallel hierarchy of creators (factories) corresponding to each product. Why do we need this hierarchy? Does it not create unnecessary sub classes?
Can someone please give me an example where we need this kind of implementation.

A: You need this pattern if you do not wish to make your decision about what object you want to create in the context where you use them, but want to postpone it. You can use the factory pattern to postpone the decision to runtime.
Here is an example (a little bit oversimplified, but I hope you get the point):
You want to write a program that is creating NumberObjects, and you want to have either a simple kind of them, or a complex one. But you don't want to hardcode the decision which kind of number object to use in your program, but want to make it depending on the command line arguments for you program.
First, you create 2 classes SimpleNumberObject and ComplexNumberObject, both implementing the class NumberObject that has an abstract method print() and obliges the child classes to implement it. Something like:
public class NumberObject {
    protected int number;
    public NumberObject(int number) {
        this.number = number;
    }
    abstract void print();
}

public class SimpleNumberObject extends NumberObject {
    public SimpleNumberObject(int number) {
        super(number);
    }
    public void print() {
        System.out.println("My number is " + number);
    }
}

public class ComplexNumberObject() extends NumberObject {
    public SimpleNumberObject(int number) {
        super(number);
    }
    public void print() {
        System.out.println("My number is " + number
            + " and I can do a lot more complex stuff");
    }
}

Then you create the abstract class NumberFactory, with the method createNumber() and the child classes SimpleNumberFactory and ComplexNumberFactory, that have to implement this method, where they return the respective NumberObject: SimpleNumberFactory a SimpleNumberObject and ComplexNumberFactory a ComplexNumberObject.
(I will skip the implementation here, if you need it for understanding let me know then I can put it too.)
Then, you design your main class, where you deside in the constructor if it's going to use SimpleNumberObject or ComplexNumberObject.
public class MainClass {

    private NumberFactory numberFactory;

    public MainClass(String arg) {
        if (arg != null && arg.equals("complex") {
            numberFactory = new ComplexNumberFactory();
        } else {
            numberFactory = new SimpleNumberFactory();
        }
    }

    public void printSomeNumber() {
        NumberObject number = numberFactory.createNumber();
        number.print();
    }

    public static void main(String[] args) {
        MainClass mainClass = new MainClass(args[0]);
        mainClass.printSomeNumber();
    }
}

So what happens here is that according to what the command line argument is, it will create either SimpleNumberObjects or ComplexNumberObjects. You didn't specify it in the code, so the compiler can't tell what object will be used, just that it implements NumberObject.
With the Factories, you were giving the responsibility away from MainClass how to create a number. They may use a random generator to produce the integer the NumberObject constructor needs, or some iterative number. Fact is, the main class doesn't need to care, and you decoupled it a bit.
About the postponing of the decision what object to create: it doesn't necessarily have to be the command line argument, but can be a different class, some context information, or something else. Basically, you use this pattern if you want to make the decision somewhere else, and of course if you want to delegate the creation of an object to a factory.
You are right that there is a lot of subclassing going on, which makes this pattern kind of class-heavy. In practice you have to decide whether it pays off to use it or not. If you are going to use a factory for object creation anyway, you have different object subclasses anyway, and it is important for you that you do not make the decision about which subclass to create at a certain point in your program, then you might consider using it.


text:
Q: UITableViewCell animation while scrolling I have a UITableView with custom UITableViewCells in it. These cells can be opened and closed with an animation. When the user scrolls I would like to close the cell. I do this by posting a notification like this:
[[NSNotificationCenter defaultCenter] postNotificationName:@"closeSwipedCell" object:nil];

This will call a method which does my simple animation in my subclass of UITableViewCell. This is working fine but the animation won't happen until the user stops scrolling the UITableView again.
Is it possible to do this animation while scrolling the table view?

A: Here's a great detailed explanation of how to do a swipe to a cell submenu, like the twitter iphone app. I think it's very similar to what your looking for.  It doesn't use notifications to close a cell, it uses the events from the UIScrollViewDelegate as the other commenters have recommended.
iDevRecipes
look for the post on idevrecipes.com called "How does the Twitter iPhone app implement side swiping on a table".
There's good description but also code to download.

A: You should be able to listen to the UIScrollViewDelegate method scrollViewDidScroll: and fire your event then.
Check out the Apple docs on UIScrollViewDelegate.
EDIT: If I was unclear, the UITableViewDelegate conforms to the UISCrollViewDelegate.

A: scrollViewDidScroll: may only be called at the end of the user scrolling. You may want to try firing your notification using the scrollViewWillBeginDragging: delegate method, which will definitely be called at the beginning of the scroll action.
There are also several UIViewAnimationOptions constants (IIRC, UIViewAnimationOptionBeginFromCurrentState is the one I'm thinking of) that affect whether animation will begin during another animation action, such as scrolling (tracking).
You'll need to OR that option with your existing animation options in the options: parameter of your animation method call.


text:
Q: Director sum, isometric let $ E $ be a normed space that can be represented as a direct sum of two vector subspaces: $ E = F + G $. Show that $\frac{ E}{ F}$ is isometric with $ G $
Using the quotient norm since $ F $ is a closed subspace I want to build the bijective mapping between the quotient space and$ G$.
One idea is to take an ismorphism theorem that is an isometry but I have not gotten far.
The other is to directly construct the function but I don't see how to proceed from the definition of quotient norm, maybe it is some extension.
Will you have any comments or suggestions, thanks.

A: Hints:
$(1).\ $ the projection $\pi:E\oplus F\to E$ is linear and has kernel equal to $F$, so the first isomorphism theorem applies to say.....
$(2).\ \pi $  maps the unit ball $B^{E\oplus F}_1(0)$ onto the unit ball $B^{E}_1(0)$, so...


text:
Q: DB2-12 (Z/OS) - Create Alias for Stored Procedure it's possible to define an alias for a stored procedure (sql-native)?
In the documentation, reference is made only to: SEQUENCE and TABLES
1) CREATE PROCEDURE OWXXCOLL.STORED1()
2) CREATE ALIAS DB2C.STORED1 FOR OWXXCOLL.STORED1;
3) CALL DB2C.STORED1();

EDIT 2021-05-14
The original question arises for the following problem (I was hoping to get away with using aliases)
Intro

*

*I have defined a native SP
The OWXXCOLL schema is the same one I also use for tables/index...
(I noticed that the tables also have different aliases)

    CREATE PROCEDURE OWXXCOLL.STORED1(...)
        LANGUAGE SQL
        ISOLATION LEVEL CS
        WLM ENVIRONMENT FOR DEBUG MODE WLMENV1
        ALLOW DEBUG MODE
    BEGIN
       ...
    END@

*I also modified the cobol program (name:PGMSTO1) to call the Stored with the CALL statement (without qualifier)

    EXEC SQL
        CALL STORED1 (...)
    END-EXEC.

The problem
The various table accesses (SELECT) work correctly BUT When I run the PGMSTO1 the call to the Stored ends with sqlcode -440

NO AUTHORIZED PROCEDURE BY THE NAME STORED1 HAVING COMPATIBLE ARGUMENTS WAS FOUND<

The error comes from the fact that it is not using the owner OWXXCOLL but DB2C (DB2C is user who scheduled the jcl/batch)
If I enter the qualifier (OWXXCOLL) the call it's OK.
I don't understand what to check and what configurations are missing.
Thanks

A: The cobol program (PGMSTO1) that calls the stored procedure has the following BIND parameters:
COLLID     NAME    OWNER CREATOR QUALIFIER DYNAMICRULES    PATHSCHEMAS
OWXXCOLL   PGMSTO1 DB2C  DB2C    FPXX       B               "DB2C"

"DB2C"  path is used to resolve unqualified stored procedure
I will need to modify the bind parameter "PATH".
I will try to ask to add my schema as well (OWXXCOLL)
PATH("OWXXCOLL","DB2C")


text:
Q: drawimage to a secified canvas width and height If the source svg is in a responsive environment, how do I use drawImage() to draw a to a given canvas size?
Example: How do I get the svg drawn to a 412.5 x 487.5 canvas, if the original svg is 550 x 650 and it is being viewed on a mobile device (so obviously the svg will be seen smaller than the original size)?
Fiddle
svgToImage(svg2, function(img2){
        ctx2.drawImage(img2, 0, 0);
      });

      function svgToImage(svg2, callback) {
        var nurl = "data:image/svg+xml;utf8," + encodeURIComponent(svg2),
            img2 = new Image;

          img2.onload = function() {
             callback(img2);
          }
          img2.src = nurl;
      }

A: When you SVG has loaded, simply set the canvas size, then draw in the image using the width and height arguments of drawImage.
Note that a bitmap can only take integer values so your canvas has to be either 413x488 or 412x487. If you don't set the canvas size it will default to 300x150 and then stretch to the size you use for style/CSS:
  svgToImage(svg2, function(img2){
      ctx2.canvas.width = 413;               // set canvas size
      ctx2.canvas.height = 488;
      ctx2.drawImage(img2, 0, 0, 413, 488);  // draw SVG/image at same size
  });

Updated fiddle


text:
Q: Wordpress - Loop one row only show 4 result here is my custom code this will list all page from specific parent but now, how to show every row only 4 result, and last row will have class 'last'.
<?php

        //this is custom query for show page from specific parent page in different page

        $child_pages = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_parent = '11' AND post_type = 'page' ORDER BY menu_order", 'OBJECT');
        if ( $child_pages ) : foreach ( $child_pages as $pageChild ) : setup_postdata( $pageChild ); ?>

<a href="<?php echo  get_permalink($pageChild->ID); ?>"><?php echo get_the_post_thumbnail($pageChild->ID, array(222,123)); ?>

            <a href="<?php echo  get_permalink($pageChild->ID); ?>" rel="bookmark" class="property_name" title="<?php echo $pageChild->post_title; ?>">
            <?php echo $pageChild->post_title; ?>

<?php the_advanced_excerpt('length=50&use_words=0&no_custom=1&ellipsis=%26hellip;&exclude_tags=img,p,strong'); ?>

<a href="<?php echo  get_permalink($pageChild->ID); ?>">MORE INFO...

        <?php endforeach; endif; ?>

Thanks.

A: Change this line:
$child_pages = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_parent = '11' AND post_type = 'page' ORDER BY menu_order", 'OBJECT');

To:
$child_pages = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_parent = '11' AND post_type = 'page' ORDER BY menu_order LIMIT 4", 'OBJECT');

And these lines:
if ( $child_pages ) : foreach ( $child_pages as $pageChild ) : setup_postdata( $pageChild ); ?>

To:
$num_child_pages = count($child_pages);
if ( $num_child_pages ) : for ($i = 0; $i < $num_child_pages; $i++):
    $pageChild = $child_pages[$i];
    setup_postdata( $pageChild ); ?>

    <div class="child-thumb_home looping <?php if ($i == $num_child_pages - 1): ?>last<?php endif; ?>">


text:
Q: Angular $http params encoding issue I have an Angular 1.4 service that makes an $http.get() request to the MapQuest API. If I pass my API key as part of the url directly then it works however if I add it as part of the params field then it does not.
Working:
var url = 'http://open.mapquestapi.com/geocoding/v1/address?key=Gmjtd%7Cluub2d08nh%2C2s%3Do5-2u2gh4';

$http.get(url);

// Key actually sent
Gmjtd%7Cluub2d08nh%2C2s%3Do5-2u2gh4

Not working:
var url = 'http://open.mapquestapi.com/geocoding/v1/address';

$http.get(url, {
  params: {
    key: 'Gmjtd%7Cluub2d08nh%2C2s%3Do5-2u2gh4'
  }
});

// Key actually sent
 Gmjtd%257Cluub2d08nh%252C2s%253Do5-su2gh4

Not working either:
var url = 'http://open.mapquestapi.com/geocoding/v1/address';

$http.get(url, {
  params: {
    key: encodeURIComponent('Gmjtd%7Cluub2d08nh%2C2s%3Do5-2u2gh4');
  }
});

// Key actually sent
Gmjtd%25257Cluub2d08nh%25252C2s%25253Do5-2u2gh4

It appears that passing the key in the params field causes it to undergo some kind of encoding process which renders it invalid.
How can I maintain the original key when using the params method?

A: Angular does indeed encode params. You should call decodeURIComponent since the key is already encoded.
$http.get(url, {
  params: {
    key: decodeURIComponent('Gmjtd%7Cluub2d08nh%2C2s%3Do5-2u2gh4');
  }
});


text:
Q: Trying to use libsodium with web worker error TypeError: sodium.crypto_pwhash is not a function I imported sodium.js using importScripts, but when web worker runs it gives error TypeError: sodium.crypto_pwhash is not a function. Console.log sodium.js in worker however prints the sodium object. What am i missing?

A: As explained in this issue, you need to load the browser-sumo version so it includes crypto_pwhash.

const worker_script = `
  self.sodium = {
    onload: function (sodium) {
     postMessage( sodium.crypto_pwhash.toString() );
    }
  };
  importScripts('https://cdn.jsdelivr.net/gh/jedisct1/libsodium.js@master/dist/browsers-sumo/sodium.js');
`;
const worker = new Worker( URL.createObjectURL( new Blob( [ worker_script ], { type: "text/javascript" } ) ) );
worker.onmessage = ({data}) => console.log( data );


text:
Q: Cmake count occurences of words in a file I know this sounds totally weird ... but a new requirement came up and we need to count the occurrences of a specific word in all our C++ files, using CMake (specifically in a platform independent way, not assuming we have any other tools, such as python, perl,)...
Is this even remotely possible? If yes, How?

A: FILE(READ file.cpp contents)
STRING(REGEX MATCHALL needle matches "${contents}")

Now matches will be a list of all the occurrences of needle in file.cpp.
If, like requested in the question title, you also need to count the number of occurrencies, you would then  call:list(LENGTH matches n_matches).


text:
Q: PHP Loop using preg_replace or sprintf to swap MYSQL data with tags inside a string in ##tag## format Say I have a returned array from a database with:
$row = array("percent" => "33%", "name" => "30 Cups", "price" => "$16");

I will also have a returned string of something like:
$string = "Take ##percent## off our newly released ##name## at just ##price## for the set!"

I am trying to find a way to loop through and change the $string to:
Take 33% off our newly released 30 Cups at just $16 for the set!

But, it should also work with a switched up $row and $string. As in $price and ##price## might change to $year and ##year## for a subscription item. I don't mind creating a key/value pair for assigning $year to ##year## or having it know that ##year## is $year via code.
The idea is that somebody else might come and create a string of:
$string = "XMAS is here and we have a ##percent## off deal on ##name##, hurry while supplies are still in stock!"

So the PHP code in the page will never be changed. It will just have something like:
<?= $tagline ?>

I don't need help on querying the DB or anything else other than how to switch out the ##tags## in $string with the data in $row. Any help would be appreciated.
Edit: At this point I would be happy just to be given some ideas on what a system of replacing formatted ##tags## like this would be called so I can try to find an example of it on github.

A: Use str_replace() and array_keys()
<?php

/**
 * replace_tags()
 *
 * @param array $row
 * @param string $string
 * @return string
 */
function replace_tags( $row, $string ) {

    if( is_array( $row ) && !empty( $row) ) {

        $tags = array();
        $keys = array_keys( $row );

        foreach( $keys as $tag ) : $tags[] = '##' . $tag . '##'; endforeach;

        $string = str_replace( $tags, $row, $string );
    }

  return $string;
}

$row = array( "percent" => "33%", "name" => "30 Cups", "price" => "$16" );

$string = "Take off ##percent## our newly released ##name## at just ##price## for the set!";

$tagline = replace_tags( $row, $string );

echo $tagline;

?>


text:
Q: NLog initial send and multiple bulk emailing Background
I have a web application written in asp.net core v2.2. I use NLog as my 3rd party logger which emails me each time there's an application error which works well.
    <targets>

        <target xsi:type="Mail"
                  name="emailnotify"
                  header="An Error has been reported By foo.com (${machinename}) ${newline}  "
                  layout="${longdate} ${level:uppercase=true:padding=5} - ${logger:shortName=true} - ${message} ${exception:format=tostring} ${newline}"
                  html="true"
                  addNewLines="true"
                  replaceNewlineWithBrTagInHtml="true"
                  subject="Error on foo.com (${machinename})"
                  to="foo@foo.com"
                  from="foo@foo.com"
                  secureSocketOption="StartTls"
                  smtpAuthentication="basic"
                  smtpServer="${environment:EmailConfigNlogSMTPServer}"
                  smtpPort="25"
               smtpusername="${environment:EmailConfigNlogSMTPUsername}"
                smtppassword="${environment:EmailConfigNlogSMTPPassword}" />

        <target xsi:type="Null" name="blackhole" />
    </targets>

     <rules>

        <logger name="Microsoft.*" level="Info" writeTo="blackhole" final="true" />

        <logger name="*" minlevel="Error" writeTo="emailnotify" final="true" />
      </rules>

However, there are times when a large amount of emails, in short succession could come in, making me feel like I'm being "spammed", before I've had chance to resolve the issue.

*

*An example could be on rare occasions such as my application's 3rd party search engine being down. At this point every user doing a search on the website would generate an error resulting in a potentially large number of emails.

*Another example is when speculative 404s are occurring either by companies gathering website technology statistics or just plain dodgy requests. i.e. /bitcoin/xxx or /shop/xxx or git/.head/xxx.

Historically, I've used the "filters" feature around some of the 404s I was receiving and have set some up. See example below. However, in bulk format, I want to be notified about all 404s or 500s. I don't feel it's a good idea trying to filter things out that don't seem relevant as you can start missing out on key information such as hacking attempts, SQL injection attacks or application sniffing:
    <filters>
        <when condition="contains('${message}','.php')" action="Ignore" />
        <when condition="contains('${message}','wp-includes')" action="Ignore" />
        <when condition="contains('${message}','wordpress')" action="Ignore" />
        <when condition="contains('${message}','downloader')" action="Ignore" />
      </filters>
    </logger>

Requirement
I want to introduce the following logic into my application logging:

*

*Email notify when the first 500 error of type occurs (i.e error performing search on website, error accessing database) so I know straight away the first time the application has the initial error

*Bulk notify consecutive 500 errors after the initial error so I know when else this error occurred but it won't continue to "spam" me.

*Bulk notify all 404, 405 errors

These bulk emails would notify me after 50 errors or once a day whichever comes first.
Ideally, I would like the format of the bulk email to be:
Bulk email
Subject: 500 errors (13) | 404 errors (2)
Body in a table format:
500 Errors (13)
-----------------------------------------------------
| When                 | Message                    |
-----------------------------------------------------
| 2019-11-13 11:10:29  | Website search engine down |
-----------------------------------------------------
| 2019-11-13 11:10:30  | Website search engine down |
-----------------------------------------------------
| 2019-11-13 11:10:31  | Website search engine down |
-----------------------------------------------------
| 2019-11-13 11:10:32  | Website search engine down |
-----------------------------------------------------
| 2019-11-13 11:10:33  | Website search engine down |
-----------------------------------------------------
| 2019-11-13 11:10:34  | Website search engine down |
-----------------------------------------------------
| 2019-11-13 11:10:35  | Website search engine down |
-----------------------------------------------------
| 2019-11-13 11:11:01  | Login failed for user foo  |
-----------------------------------------------------
| 2019-11-13 11:11:01  | Login failed for user foo  |
-----------------------------------------------------
| 2019-11-13 11:11:01  | Login failed for user foo  |
-----------------------------------------------------
| 2019-11-13 11:11:02  | Login failed for user foo  |
-----------------------------------------------------
| 2019-11-13 11:11:02  | Login failed for user foo  |
-----------------------------------------------------
| 2019-11-13 11:11:02  | Login failed for user foo  |
-----------------------------------------------------

404 Errors (2)
-----------------------------------------------------
| When                 | Message                    |
-----------------------------------------------------
| 2019-11-13 11:10:45  | /bitcoin not found         |
-----------------------------------------------------
| 2019-11-13 11:10:57  | /shop not found            |
-----------------------------------------------------

Alternatively, I'd be happy to have separate bulk emails for the 500s, 404s or 405s.
In the example bulk email above, the application would've informed me straight away with 2 separate emails that there was an issue

*

*With the website search engine being down

*The user not being able to access the SQL database

And then after hitting 50 errors or once a day, send out the bulk email.
Question
Is my requirement possible using just NLog configuration?
I can see how I can carry out bulk notification using NLog's buffer wrapper configuration, although I don't think it's possible to output in the table format I'd ideally like.
      <target xsi:type="BufferingWrapper"
              name="bulkemailnotify"
              bufferSize="50"
              flushTimeout="86400000"
              slidingTimeout="False"
              overflowAction="Flush">
        <target xsi:type="emailnotify" />
      </target>

If not, would it be looking at one of the following?

*

*Extending NLog

*Removing NLog and adding a custom logger
Ideally, I would continue to use NLog and would only look to add a custom logger as a last resort.

A: Lets say that ${aspnet-response-statuscode} is the one returning the HTTP Status Code:
Then we can have following two targets:

*

*Instant mail-target with first error (instant trigger with first event, and waits 5 min before triggering again)

*Bulk mail-target with all errors (triggers after 5 min with all events)

Then you could probably do this:
<targets async="true">
   <target xsi:type="SplitGroup" name="special-mail">
       <target xsi:type="FilteringWrapper" name="filter-mail">
          <filter type="whenRepeated" layout="${aspnet-response-statuscode}" timeoutSeconds="300" action="Ignore" />
          <target xsi:type="Mail" name="instant-mail">
                 Instant Error Report
          </target>
       </target>
       <target xsi:type="BufferingWrapper" name="buffer-mail" flushTimeout="300000">
           <target xsi:type="Mail" name="bulk-mail">
                Bulk Error Report
           </target>
       </target>
   </target>
</targets>
<rules>
    <logger name="Microsoft.*" maxlevel="Info" final="true" />
    <logger name="*" minlevel="Error" writeTo="special-mail" final="true" />
</rules>

Not that skilled with the mail-target-layouts (header + body + footer) and making a good looking html-email. But you can probably steal something from the internet.

A: I've marked @Rolf Kristensen's answer as the answer because he gave me a large chunk of the functionality I asked for.
However, I thought I'd share what my final config looked like in case this can help anyone else.
Ideally, I wanted to use the ${exception:format=HResult} to check for a repeating log in the "whenRepeated" filter but there's a bug which has been fixed in a future release of nlog.
Edit: Updated the WhenRepeated attribute of the <filter> to include ${exception:format=TargetSite} ${exception:format=Type} as per Rolf Kristensen's recommendation.
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="Warn"
      internalLogFile="c:\temp\internal.txt">

  <extensions>
    <add assembly="NLog.MailKit"/>
  </extensions>

  <variable name="exceptiontostring" value="${exception:format=tostring}" />
  <variable name="abbreviatedenvironment" value="${left:inner=${environment:ASPNETCORE_ENVIRONMENT}:length=1}" />
  <variable name="websiteshortname" value="${configsetting:cached=True:name=WebsiteConfig.ShortName}" />

  <variable name="numsecondstobufferkeyerrors" value="10" />

  <variable name="nummillisecondstobufferkeyerrors" value="10000" />

  <variable name="nummillisecondstobuffernonkeyerrors" value="5000" />
  <variable name="borderstyle" value="border: 1px solid #000000;" />

  <targets async="true">

    <target xsi:type="File" name="error" fileName="D:\Dev\dotnet\Core\Logs\Logging2.2\error-log-${shortdate}.log"
                 layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
    <target xsi:type="File" name="info" fileName="D:\Dev\dotnet\Core\Logs\Logging2.2\info-log-${shortdate}.log"
                 layout="${longdate}|${logger}|${uppercase:${level}}|${message}" />
  </targets>

  <targets>

    <default-wrapper xsi:type="AsyncWrapper">
      <wrapper-target xsi:type="RetryingWrapper" retryDelayMilliseconds="6000" retryCount="10" />
    </default-wrapper>

    <default-target-parameters xsi:type="Mail">
      <to>${configsetting:cached=True:name=EmailConfig.SendErrorsTo}</to>
      <from>${configsetting:cached=True:name=EmailConfig.FromAddress}</from>
      <secureSocketOption>StartTls</secureSocketOption>
      <smtpAuthentication>basic</smtpAuthentication>
      <smtpServer>${environment:EmailConfigNlogSMTPServer}</smtpServer>
      <smtpPort>25</smtpPort>
      <smtpusername>${environment:EmailConfigNlogSMTPUsername}</smtpusername>
      <smtppassword>${environment:EmailConfigNlogSMTPPassword}</smtppassword>
      true
      <addNewLines>true</addNewLines>
      <replaceNewlineWithBrTagInHtml>true</replaceNewlineWithBrTagInHtml>
    </default-target-parameters>

    <target xsi:type="SplitGroup" name="key-error-mail">
      <target xsi:type="FilteringWrapper" name="filter-mail">

        <filter type="whenRepeated" layout="${exception:format=TargetSite} ${exception:format=Type}" timeoutSeconds="${numsecondstobufferkeyerrors}" action="Ignore" />

        <target xsi:type="Mail" name="key-error-instant-mail">
          <subject>Error on ${websiteshortname} (${abbreviatedenvironment}) ${newline}</subject>
          <layout>${longdate} ${level:uppercase=true:padding=5} - ${logger:shortName=true} - ${message} ${exceptiontostring} ${newline}</layout>
        </target>
      </target>

      <target xsi:type="BufferingWrapper" name="buffer-key-error-mail" flushTimeout="${nummillisecondstobufferkeyerrors}">

        <target xsi:type="Mail" name="key-error-bulk-mail">
          <subject>Bulk Key Errors on ${websiteshortname} (${abbreviatedenvironment})</subject>
          <layout>
            <strong>${aspnet-response-statuscode} Error ${when:when='${aspnet-request-url}'!='':inner=on ${aspnet-request-url} (${aspnet-mvc-controller} > ${aspnet-mvc-action})}</strong>
            <table width="100%" border="0" cellpadding="2" cellspacing="2" style="border-collapse:collapse; ${borderstyle}">
            <thead>
            <tr style="background-color:#cccccc;">
            <th style="${borderstyle}">Date</th>
            <th style="${borderstyle}">IP Address</th>
            <th style="${borderstyle}">User Agent</th>
            <th style="${borderstyle}">Method</th>
            </tr>
            </thead>
            <tbody>
            <tr>
            <td style="${borderstyle}">${longdate}</td>
            <td style="${borderstyle}">${aspnet-request-ip}</td>
            <td style="${borderstyle}">${aspnet-request-useragent}</td>
            <td style="${borderstyle}">${aspnet-request-method}</td>
            </tr>
            <tr><td colspan="4" style="${borderstyle}">${message}</td></tr>
            <tr><td colspan="4" style="${borderstyle}">${exceptiontostring}</td></tr>
            </tbody></table>
            ${newline}
          </layout>
        </target>
      </target>
    </target>

    <target xsi:type="BufferingWrapper" name="buffer-mail-non-key-error" flushTimeout="${nummillisecondstobuffernonkeyerrors}">
      <target xsi:type="Mail" name="bulk-mail-non-key-error">
        <subject>Bulk Errors on ${websiteshortname} (${abbreviatedenvironment})</subject>
        <layout>
          <strong>${aspnet-response-statuscode} Error ${when:when='${aspnet-request-url}'!='':inner=on ${aspnet-request-url} (${aspnet-mvc-controller} > ${aspnet-mvc-action})}</strong>
          <table width="100%" border="0" cellpadding="2" cellspacing="2" style="border-collapse:collapse; ${borderstyle}">
          <thead>
          <tr style="background-color:#cccccc;">
          <th style="${borderstyle}">Date</th>
          <th style="${borderstyle}">IP Address</th>
          <th style="${borderstyle}">User Agent</th>
          <th style="${borderstyle}">Method</th>
          </tr>
          </thead>
          <tbody>
          <tr>
          <td style="${borderstyle}">${longdate}</td>
          <td style="${borderstyle}">${aspnet-request-ip}</td>
          <td style="${borderstyle}">${aspnet-request-useragent}</td>
          <td style="${borderstyle}">${aspnet-request-method}</td>
          </tr>
          <tr><td colspan="4" style="${borderstyle}">${message}</td></tr>
          </tbody></table>
          ${newline}
        </layout>
      </target>
    </target>

    <target xsi:type="Null" name="blackhole" />

  </targets>

  <rules>

    <logger name="Microsoft.*" level="Info" writeTo="blackhole" final="true" />

    <logger name="*" level="Info" writeTo="info" final="true" />

    <logger name="*" minlevel="Error" writeTo="error" />

    <logger name="*" minlevel="Error" writeTo="key-error-mail">
      <filters defaultAction="Log">
        <when condition="starts-with('${aspnet-response-statuscode}','4')" action="Ignore" />
      </filters>
    </logger>

    <logger name="*" minlevel="Error" writeTo="buffer-mail-non-key-error">
      <filters defaultAction="Log">
        <when condition="not starts-with('${aspnet-response-statuscode}','4')" action="Ignore" />
      </filters>
    </logger>
  </rules>
</nlog>


text:
Q: How to turn an user inputted value into a regexp without messing up with special characters? I'm fiddling around with MongoDB and there is something I stumbled upon. I'd like to make a simple application in which the user can search all documents in a collection, getting the documents of which the key username contains a certain user inputted value.
For implementing "contains" it appears a regular expression can be used. This works fine, but how can I convert user input into a regular expression? The problem is that simply doing ...
new RegExp(value);

... does not work because of special characters (like (, [ etc.). This means the user cannot do a query containing ( this way.
I thought escaping everything would do the job:
new RegExp(value.replace(/./g, function(x) {
    return "\\" + x;
});

... but it doesn't because some escaped characters are also special (e.g. \d), so this way non-special characters become special.
I'm a bit lost how I could turn a user inputted value into a regular expression. Or is there perhaps a better way of doing a query for all documents of which a key contains a certain user inputted value?

A: Implementation:
Based on this source.
var oldText = "[hello, world :) ]";
var sre = new RegExp('(\\' + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'].join('|\\') + ')', 'g');
var newText = oldText.replace(sre, '\\$1'); // "\[hello, world :\) \]"

Further explanation:
sre is a regular expression that is matching all possible special characters and is using parentheses so it can reference matched parts.
Incomplete sre example:
/(\/|\.|\\)/g

This will try to match for any of this characters: "/", "." and "\". Using then
text.replace(sre, '\\$1');

will escape every single matched character in text with "\". So it will replace "." with "\.", etc.


text:
Q: display current user data in MVC In MVC i want to authenticate users,they must not be able to see other user data when logged on. Users must be able to CRUD their own data only. I have created two model:
public class User
{
    public int id { get; set; }
    public string Username { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }

    public List<Product> Products { get; set; }
}

public class Product
{
    public int productId { get; set; }
    public string productName { get; set; }
    public double productPrice { get; set; }

    public User Users { get; set; }
}

And i have product controller, where i want to authenticate users from CRUD other users data.

A: You can make your code to perform CRUD operations on only the products available for logged in user.
Use below scenario for your requirement.
public class User
{
    public int id { get; set; }
    public string Username { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }

    public List<Product> Products {
        get{
            //get all products from database/storage for this user. for ex: I have called a method to get products
            //you can filter products related to this user by sending this user id to database or using code like below
            //Writing this code/logic in controller would be preferable

            return GetAllProducts().Where(p => p.Users.id == this.id).ToList();
        }
        set;
    }
}

A: Agree with Rajesh, I would recommend you use Current User's data and filter Rajesh you showed. Current User's Data may include Id of current logged user. If you use cookies to keep user's session, you can retrieve his Id from cookies in controller or filter attribute: HttpContext.Current.Request.Cookies["auth_cookie"].


text:
Q: Multiple UPDATE, same column, different values, different WHERE conditions I am trying to update a field with different conditions in where.
Actually I have the next instructions:
Update StmHistItm Set SHI_nPayable = @minPayable where SHI_iItemPK = @minrecno
Update StmHistItm Set SHI_nPayable = @maxPayable where SHI_iItemPK = @maxrecno

Is there a way to do this two instruction in just one?

A: You could use a case expression and combine the where clauses:
UPDATE StmHistItm
SET    SHI_nPayable = CASE SHI_iItemPK
                      WHEN @minrecno THEN @minPayable
                      WHEN @maxrecno THEN @maxPayable
                      END
WHERE  SHI_iItemPK IN (@minrecno, @maxrecno)