text:
Q: Insert data from VB net into Postgresql I'm trying to input data from my vb into PostgreSQL
the source is another database on Ms Access
im using this code for connection
Public Function LoadAcces_tblpibconr() As DataTable 'ganti ini sesuai nama table
    Dim Table As DataTable = New DataTable()
    Command.Connection = conn.OpenConnection()
    Command.CommandText = "select * from tblpibconr"
    Command.CommandType = CommandType.Text
    ReadRows = Command.ExecuteReader()
    Table.Load(ReadRows)
    ReadRows.Close()
    conn.CloseConexion()
    Return Table
End Function

'=====================================TABLE POSTGRESQL========================='
Public Function LoadNpgsql_tblpibconr() As DataTable
    Dim Table As DataTable = New DataTable()
    Cmd.Connection = connNpgsql.OpenConnection()
    Cmd.CommandText = "select * from tblpibconr"
    Cmd.CommandType = CommandType.Text
    ReadRows1 = Cmd.ExecuteReader()
    Table.Load(ReadRows1)
    ReadRows1.Close()
    connNpgsql.CloseConexion()
    Return Table
End Function

I'm using this function for filtering the data
I'll compare the data first and take the data without a match and stored it into postgresql
Public Function CekData_tblpibconr(ByVal car As String, ByVal reskd As String, ByVal contno As String) As Boolean
    Dim Table As DataTable = New DataTable()

    Cmd.Connection = connNpgsql.OpenConnection()
    If Cmd.Parameters.Count > 0 Then
        Cmd.Parameters.Clear()
    End If
    Cmd.Parameters.AddWithValue("@car", car)
    Cmd.Parameters.AddWithValue("@reskd", reskd)
    Cmd.Parameters.AddWithValue("@contno", contno)
    Cmd.CommandText = <sql>select * from tblpibconr where car=@car and reskd=@reskd and contno=@contno</sql>.Value
    Cmd.CommandType = CommandType.Text

    ReadRows1 = Cmd.ExecuteReader() 'ERROR System.InvalidOperationException: 'Parameter '@car' must have its value set'

    Table.Load(ReadRows1)
    ReadRows1.Close()
    If Table.Rows.Count > 0 Then
        Return False
    Else
        Return True
    End If
    Cmd.Parameters.Clear()
    connNpgsql.CloseConexion()
End Function

Sub bandingkan_data_tblpibconr()
    For i = 0 To DGV1.Rows.Count - 1
        Dim validasi = query.CekData_tblpibconr(DGV1.Rows(i).Cells(0).Value, DGV1.Rows(i).Cells(1).Value, DGV1.Rows(i).Cells(2).Value) 'cek data dari access ke postgresql
        If validasi = True Then 'jika data di access tidaj ada
            'inser data
            Dim a As String
            If IsDBNull(DGV1.Rows(i).Cells(4).Value.ToString()) Then
                a = "0"
            Else
                a = DGV1.Rows(i).Cells(4).Value.ToString()
            End If
            DGV1.Rows(i).DefaultCellStyle.BackColor = Color.MistyRose
            Dim Insertdata = query.insertNpgsql_tblpibconr(DGV1.Rows(i).Cells(0).Value.ToString(), DGV1.Rows(i).Cells(1).Value.ToString(), DGV1.Rows(i).Cells(2).Value.ToString() _
                              , DGV1.Rows(i).Cells(3).Value.ToString(), a)
            If Insertdata = True Then
                ' MsgBox("Masuk")
            Else
                MsgBox("Data Gagal DIMASUKAN")
            End If
        End If

    Next i
    LoadNpgsql_tblpibconr()
    MsgBox("Selesai")
End Sub

Public Function insertNpgsql_tblpibconr(ByVal car As String, ByVal reskd As String, ByVal contno As String, ByVal contukur As String, ByVal conttipe As String) As Boolean

    Cmd.Connection = connNpgsql.OpenConnection()
    If Cmd.Parameters.Count = 0 Then
        Cmd.Parameters.Clear()

    End If
    Try
        Cmd.CommandText = "insert into tblpibconr(car,reskd,contno,contukur,conttipe) values(@car,@reskd,@contno,@contukur,@conttipe)"
        Cmd.CommandType = CommandType.Text
        Cmd.Parameters.AddWithValue("@car", car)
        Cmd.Parameters.AddWithValue("@reskd", reskd)
        Cmd.Parameters.AddWithValue("@contno", contno)
        Cmd.Parameters.AddWithValue("@contukur", contukur)
        Cmd.Parameters.AddWithValue("@conttipe", conttipe)
        Cmd.ExecuteNonQuery()
        str = "insert into tblpibconr(car,reskd,contno,contukur,conttipe) values(@car , @reskd , @contno, @contukur, @conttipe)"
        Return True
    Catch ex As Exception
        MsgBox(ex.Message)
        Return False
    End Try

    connNpgsql.CloseConexion()
End Function

this is the error that I get

System.InvalidOperationException: 'Parameter '@car' must have its
value set'

ITS Refer to ReadRows1 = Cmd.ExecuteReader() on function cekdata_tblpibconr and Dim validasi = query.CekData_tblpibconr(DGV1.Rows(i).Cells(0).Value, DGV1.Rows(i).Cells(1).Value, DGV1.Rows(i).Cells(2).Value) on sub bandingkan_data_tblpibconr
but this error appear after the data successfully inserted to my Postgresql

A: Before running the Function where the error occurred, I have checked if we really have a value for car.
This method demonstrates what I mean by keeping your database objects local. The connection and command are created locally in a Using block. They will be closed and disposed even it there is an error.
You can pass the connection string directly to the constructor of the connection. Likewise, pass the command text and the connection to the constructor of the command. The default CommandType is CommandType.Text so it is not necessary to explicitly set that property.
Open the connection at the last possible moment directly before the command is executed.
Public Function CekData_tblpibconr(ByVal car As String, ByVal reskd As String, ByVal contno As String) As Boolean
    If String.IsNullOrEmpty(car) Then
        MessageBox.Show("Car has no value")
        Return True '??
    End If
    Dim Table As DataTable = New DataTable()
    Using cn As New NpgsqlConnection(ConStr),
            cmd As New NpgsqlCommand("select * from tblpibconr where car=@car and reskd=@reskd and contno=@contno;", cn)
        cmd.Parameters.Add("@car", NpgsqlDbType.Varchar).Value = car
        cmd.Parameters.Add("@reskd", NpgsqlDbType.Varchar).Value = reskd
        cmd.Parameters.Add("@contno", NpgsqlDbType.Varchar).Value = contno
        cn.Open()
        Table.Load(cmd.ExecuteReader)
    End Using
    If Table.Rows.Count > 0 Then
        Return False
    Else
        Return True
    End If
End Function


text:
Q: Windbg help -> how can I read the code at this callstack? I have a dump of a windows service i made. The exception is that my code can't move a file (for some reason). Now, in my code there's a number of places where i move files around the filesystem. So, using Windbg, i'm trying to see the code where the exception occurs.
here's my !clrstack dump..
0:016> !clrstack -p
OS Thread Id: 0xdf8 (16)
Child-SP         RetAddr          Call Site
0000000019edea70 0000064278a15e4f System.IO.__Error.WinIOError(Int32, System.String)
PARAMETERS:
    errorCode = <no data>
    maybeFullPath = <no data>

0000000019edead0 0000064280181ce5 System.IO.File.Move(System.String, System.String)
PARAMETERS:
    sourceFileName = <no data>
    destFileName = <no data>

0000000019edeb50 0000064280196532 MyClass.Foo.DoSomeStuffInHere(System.String)
PARAMETERS:
    this = 0x0000000000c30aa8
    filePathAndName = 0x0000000000d1aad0

now, this helps a lot...
0:016> !do 0x0000000000d1aad0
Name: System.String
MethodTable: 00000642784365e8
EEClass: 000006427803e4f0
Size: 88(0x58) bytes
(C:\WINDOWS\assembly\GAC_64\mscorlib\2.0.0.0__b77a5c561934e089\mscorlib.dll)
String: C:\BlahBlahFolder\FooFolder\4469.jpg
Fields:
-snipped-

So i've figured out the file which failed to be moved. kewl. But i just want to see the code in this method MyClass.Foo.DoSomeStuffInHere(System.String) which calls File.Move(..).  That method has lots of File.Move .. so i could put try / catches / debug / trace information .. but i'm hoping to be more efficient by using Windbg to help find this problem.
Any thoughts?

A: You cannot get the exact line of code, unless the application was deployed in debug mode.  And if that were the case, I believe it would be showing them in the !clrstack call.

A:
This is a difficult problem and may require stepping outside of one's comfort zone of managed only debugging.

What you want to do is map the IL for the function MyClass.Foo.DoSomeStuffInHere to the dissassembly of that function.  My example below is x86 however x64 can follow the same steps.
This is referenced way down deep in the following link.
Debugging Unexpected Process Termination
Example text from the whitepaper:
In the managed stack, Debugging.Unexpected.btnSTA_Click ...
Look at the code in the Debugging.Unexpected.btnSTA_Click event.
private void btnSTA_Click(object sender, System.EventArgs e)
{
   DebuggingCOMLib.STAClass staobj =  new DebuggingCOMLib.STAClass();
   staobj.RaiseError(1,5);
   Label1.Text += "STA Call Completed sucessfully";
}

If the source code is not available, you can examine the assembly by supplying the instruction pointer for the call-stack frame to the !u command. The instruction pointer can be retrieved from the !clrstack: output.
0096f970  03a00e06 [DEFAULT] [hasThis] Void
Debugging.Unexpected.btnSTA_Click(Object,Class System.EventArgs)

To disassemble this function, type !u 03a00e06.
    0:010> !u 03a00e06
    Normal JIT generated code
    [DEFAULT] [hasThis] Void Debugging.Unexpected.btnSTA_Click(Object,Class
    System.EventArgs)
    Begin 03a00de0, size 54
   <snip>
    03a00e18 8b15a89c1702     mov     edx,[02179ca8] ("STA Call Completed
    sucessfully")
    03a00e1e e83d3590ff       call    03304360 (System.String.Concat)
    <snip>
    03a00e2f 5e               pop     esi
    03a00e30 5f               pop     edi
    03a00e31 c20400           ret     0x4

Ok, now what?
Scan your own !u output for a line like
call    03304360 (System.IO.File.Move)

Also, you can run !ip2md 03a00e06 to get the MethodDesc and then run !dumpil  to examine the IL code if that is easier.
You could count the number of calls to System.IO.File.Move in the !u output and then count down the same number in the IL.  Then you can use .NET Reflector to Disassemble the method and map the C# to IL and compare the result.
Lot's of steps, but it would get you to the same result :-)
Thanks,
Aaron

redpajama_set_name: RedPajamaStackExchange


text:
Q: Have you ever told your friend Peter that you wanted/want to go to the US for further education? You have been wanting to go to the US for further education. Your parents ask you:

Have you ever told your friend Peter that you wanted to go to the US for further education?

Have you ever told your friend Peter that you want to go to the US for further education?

Which is correct, wanted or want?

A:
Have you ever told your friend Peter that you wanted to go to the US
for further education?
Have you ever told your friend Peter that you want to go to the US for
further education?

Both sentences are acceptable and common.  The first is probably the default way to say it, but the second makes clear that the "wanting" is still true in the present.  The first one does not make that claim, but leaves it open to context.  If, for example, the person was lying about wanting to go and or has changed their mind, the first sentence must be used.

Have you ever felt you were different from others? Here it's not
"are". Why? Is "are" fine?

In this sentence, using "were" clearly indicates that the speaker does not take a position on the truth of whether the person has ever really been different or not and refers to at least one occasion that could have happened any time in the past up to and including the present.  It is the same as saying: "Have you ever felt different from others?"  The difference may have been true in the past, but might not be true now.
Using "are" refers to present time and strongly implies that the difference being referenced would persist now or at least could still manifest itself at any time.  The reference to the present can also mean that the speaker asserts that there is a difference in the present and is just asking whether the addressee has ever felt this fact.

A:
Have you ever told your friend Peter that you want to go to the US for further education?

This one. Because Present Perfect is present so there's no need to change "want" to "wanted" (a post form).


text:
Q: How to verify network bandwidth issue in web application I am maintainign a ASP.NET app. Some of users action are pretty slow; one of my colleagues claim it is caused by network bandwidth as some used dll will connect over to internet to get data.
How could I verify it's really due to network issue? Any tools can peer the network connection during the process?
Thanks.

A: I would implement tracing - enable remote tracing on the server
<configuration>
  <system.web>
    <trace enabled="true" requestLimit="40" localOnly="false"/>
  </system.web>
</configuration>

and then modify the code that calls the DLL in question, include this code before and after call:
Trace.Write("Calling dll " + DateTime.Now.ToString());

and after
Trace.Write("Finished calling dll " + DateTime.Now.ToString());

then hit the page that's slow, and after that go to http://yourserver/Trace.axd and look at the last aspx request

A: If you think the "network issue" is on the server side then you could just use TaskManager andswitch to the network tab to see the bandwidth utilization. If the utilization is close to the bandwidth you have at your server's end then you'll know for sure.
The same can be done if you suspect the user doesn't have enough bandwidth.
FYI: If you are making additional internet calls (either from the client or the server) there will be additional network latency that you'll get (for each call). That doesn't indicate a bandwidth issue but just that there are additional network latency issues to deal with.


text:
Q: CLIPS интерпретатор: сохранение истории команд $ clips
         CLIPS (V6.24 06/15/06)
CLIPS> asdf
asdf
CLIPS> ^[[A   <----- здесь была нажата стрелка вверх

Можно ли при нажатии стрелки вверх отображать предыдущие записи как в обычном терминале Linux?


text:
Q: Sort an integer without using an array on C I need to sort the digits of a multiple digit integer (eg. 587328) without using an array on C.
I've tried to make it but it doesn't work and I'm not really sure why because there's apparently no errors.
int main(){
    int n, dig, temp;
    printf("\nPlease ingress a number: ");
    scanf("%d", &n);
    for (dig=0; dig<9; dig++){
        for(temp=n; temp>10; temp/=10){
            if(temp%10==dig){
                printf("%d", dig);
                printf("\n");
            }
        }
    }
    return 0;
}

A: I need to sort an integer (A number tbh) without using an array on C
Method 1:
I suppose there are other, more elegant methods but the following method does follow the constraint of not using arrays or any kind of purposefully created contiguous blocks of memory to store elements, only individually created variables.
Without the use of an array, or any other form contiguous memory it becomes increasingly messy to assign, organize and sort a collection of individual values. (See case 10: below for illustration)  The larger the collection, the messier the task becomes.  The following method(s) is limited to <=10 digits.
The following method (limited to 10 digits) uses a combination of the following:

*

*pre-defined set of 10 int variables

*switch() within a for() loop to separate and store digits

*Simple sorting network and a SWAP macro in a switch()
Output of following:
6539345654
sorted
3344555669

        int a = -1;
        int b = -1;
        int c = -1;
        int d = -1;
        int e = -1;
        int f = -1;
        int g = -1;
        int h = -1;
        int i = -1;
        int j = -1;

        int tmp;
        long long num = 4565439356;//input value for illustration

    int main(void)
    {
        char buf[11] = {0};
        sprintf(buf, "%lld", num);
        int len = strlen(buf);

        //separate and store digits
        //for(int x=0; num; num /= 10, ++x)//reads digits from LSD to MSD
        for(int x=9; num; num /= 10, --x)//reads digits from MSD to LSD

        {
            switch(x)  {
                case 0:
                    a = num%10;
                    break;
                case 1:
                    b = num%10;
                    break;
                case 2:
                    c = num%10;
                    break;
                case 3:
                    d = num%10;
                    break;
                case 4:
                    e = num%10;
                    break;
                case 5:
                    f = num%10;
                    break;
                case 6:
                    g = num%10;
                    break;
                case 7:
                    h = num%10;
                    break;
                case 8:
                    i = num%10;
                    break;
                case 9:
                    j = num%10;
                    break;
            }
        }
        //sort appropriate number of digits
         switch(len)  {
            case 1:
                a;
                break;
            case 2:
                printf("%d%d\n", a,b);
                SORT(a,b);
                printf("sorted\n%d%d\n", a,b);
                break;
            case 3:
                printf("%d%d%d\n", a,b,c);
                SORT(a,b);
                SORT(a,c);
                SORT(b,c);
                printf("sorted:\n%d%d%d\n", a,b,c);
                break;
            case 4:
                printf("%d%d%d%d\n", a,b,c,d);
                SORT(a,b);
                SORT(a,c);
                SORT(a,d);
                SORT(b,c);
                SORT(b,d);
                SORT(c,d);
                printf("sorted:\n%d%d%d%d\n", a,b,c,d);
                break;
            case 5:
                printf("%d%d%d%d%d\n", a,b,c,d,e);
                SORT(a,b);
                SORT(a,c);
                SORT(a,d);
                SORT(a,e);
                SORT(b,c);
                SORT(b,d);
                SORT(b,e);
                SORT(c,d);
                SORT(c,e);
                SORT(d,e);
                printf("sorted:\n%d%d%d%d%d\n", a,b,c,d,e);
                break;
            case 6:
                printf("%d%d%d%d%d%d\n", a,b,c,d,e,f);
                SORT(a,b);
                SORT(a,c);
                SORT(a,d);
                SORT(a,e);
                SORT(a,f);
                SORT(b,c);
                SORT(b,d);
                SORT(b,e);
                SORT(b,f);
                SORT(c,d);
                SORT(c,e);
                SORT(c,f);
                SORT(d,e);
                SORT(d,f);
                SORT(e,f);
                printf("sorted:\n%d%d%d%d%d%d\n", a,b,c,d,e,f);

                break;
            case 7:
                //and so on
                break;
            case 8:
                i = num%10;
                //and so on
            case 9:
                //and so on
                break;
            case 10:
                printf("%d%d%d%d%d%d%d%d%d%d\n", a,b,c,d,e,f,g,h,i,j);
                SORT(a,b);
                SORT(a,c);
                SORT(a,d);
                SORT(a,e);
                SORT(a,f);
                SORT(a,g);
                SORT(a,h);
                SORT(a,i);
                SORT(a,j);
                SORT(b,c);
                SORT(b,d);
                SORT(b,e);
                SORT(b,f);
                SORT(b,g);
                SORT(b,h);
                SORT(b,i);
                SORT(b,j);
                SORT(c,d);
                SORT(c,e);
                SORT(c,f);
                SORT(c,g);
                SORT(c,h);
                SORT(c,i);
                SORT(c,j);
                SORT(d,e);
                SORT(d,f);
                SORT(d,g);
                SORT(d,h);
                SORT(d,i);
                SORT(d,j);
                SORT(e,f);
                SORT(e,g);
                SORT(e,h);
                SORT(e,i);
                SORT(e,j);
                SORT(f,g);
                SORT(f,h);
                SORT(f,i);
                SORT(f,j);
                SORT(g,h);
                SORT(g,i);
                SORT(g,j);
                SORT(h,i);
                SORT(h,j);
                SORT(i,j);
                printf("sorted\n%d%d%d%d%d%d%d%d%d%d\n", a,b,c,d,e,f,g,h,i,j);
                break;
        }
        return 0;
    }

***EDIT - alternate method***

Some words about the _array_ thing...
Not all `C` variables expressed using array _notation_, are arrays. eg. this:

    char *a = malloc(10*sizeof(*a));

creates a memory location in heap memory comprised of `10` contiguous `char`
sized locations, and the areas of memory of `a` can be expressed as

    a[0], ... a[9]

But `a` is not a _C array_, it is a pointer. The declaration:

    char a[10];

_is_ a C array, and with the exception of where it is stored (on the stack), does the same.

More on C arrays:

[Arrays ref 1](https://www.tutorialspoint.com/cprogramming/c_arrays.htm)
[Arrays ref 2](https://www.cs.nmsu.edu/~rth/cs/cs271/notes/Pointers.html)
[Arrays ref 3](https://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1069897882&id=1073086407)

The following uses pointers, not C Arrays.

***Method 2***

Output of following:

    345654
    sorted:
    344556

Example code:

    char *digits = "456543";
    void main(void)
    {

        int len = strlen(digits);
        int num = atoi(digits);
        char *elements = calloc(len, sizeof(*elements));
        if(elements)
        {
            for(int i=0; num; num /= 10, ++i)
            {
                *(elements +i) =(char)(num%10);
            }
        }
        for(int i = 0;i<len;i++)
        {
            printf("%d", *(elements + i));
        }
        printf("\nsorted\n");
        char *sorted = sort(elements, len);
        for(int i = 0;i<len;i++)
        {
            printf("%d", (char)(*(sorted + i)));
        }
        free(elements);

    }

    char * sort( char *numbers, int count )
    {
        int i, j;

        char temp;
        do{
            j = 0;
            for (i = 0;i<count-1;i++){
                    if (*(numbers+i) > *(numbers+i+1)){//this was numbers[k], which was an error
                        j = 1;
                        temp = *(numbers+i);
                        *(numbers+i) = *(numbers+i+1);
                        *(numbers+i+1) = temp;
                    }
                }
        } while (j == 1);
        return numbers;
    }


text: Q: How to make JSP project live on Internet? I have made a project in eclipse in HTML and JSP . I want to make it online or live . I have tried hostinger.in , 000webhost.com and also wordpress.com . But no one is supporting to host JSP pages . I don't want to purchase any domain name as it is just made for fun and my knowledge .


text:
Q: if statement - short circuit evaluation vs readability Sometimes, an if statement can be rather complicated or long, so for the sake of readability it is better to extract complicated calls before the if.
e.g. this:
if (SomeComplicatedFunctionCall() || OtherComplicatedFunctionCall())
{
    // do stuff
}

into this
bool b1 = SomeComplicatedFunctionCall();
bool b2 = OtherComplicatedFunctionCall();

if (b1 || b2)
{
    //do stuff
}

(provided example is not that bad, it's just for illustration... imagine other calls with multiple arguments, etc.)
But with this extraction I lost the short circuit evaluation (SCE).

*

*Do I really lose SCE every time? Is there some scenario where the compiler is allowed to "optimize it" and still provide SCE?

*Are there ways of keeping the improved readability of the second snippet without losing SCE?

A:
1) Do I really lose SCE every time? Is compiler is some scenario
  allowed to "optimize it" and still provide SCE?

No you don't, but it's applied differently:
if (SomeComplicatedFunctionCall() || OtherComplicatedFunctionCall())
{
    // do stuff
}

Here, the compiler won't even run OtherComplicatedFunctionCall() if SomeComplicatedFunctionCall() returns true.
bool b1 = SomeComplicatedFunctionCall();
bool b2 = OtherComplicatedFunctionCall();

if (b1 || b2)
{
    //do stuff
}

Here, both functions will run because they have to be stored into b1 and b2. Ff b1 == true then b2 won't be evaluated (SCE). But OtherComplicatedFunctionCall() has been run already.
If b2 is used nowhere else the compiler might be smart enough to inline the function call inside the if if the function has no observable side-effects.

2) What is the best practice in such situation? Is it only possibility
  (when I want SCE) to have all I need directly inside if and "just
  format it to be as readable as possible" ?

That depends.
Do you need OtherComplicatedFunctionCall() to run because of side-effects or the performance hit of the function is minimal then you should use the second approach for readability. Otherwise, stick to SCE through the first approach.

A: Another possibility that short circuits and has the conditions in one place:
bool (* conditions [])()= {&a, &b, ...}; // list of conditions
bool conditionsHold = true;
for(int i= 0; i < sizeOf(conditions); i ++){
     if (!conditions[i]()){;
         conditionsHold = false;
         break;
     }
}
//conditionsHold is true if all conditions were met, otherwise false

You could put the loop into a function and let the function accept a list of conditions and output a boolean value.

A: Very strange: you are talking about readability when nobody mentions the usage of comment within the code:
if (somecomplicated_function() || // let me explain what this function does
    someother_function())         // this function does something else
...

In top of that, I always preceed my functions with some comments, about the function itself, about its input and output, and sometimes I put an example, as you can see here:
/*---------------------------*/
/*! interpolates between values
* @param[in] X_axis : contains X-values
* @param[in] Y_axis : contains Y-values
* @param[in] value  : X-value, input to the interpolation process
* @return[out]      : the interpolated value
* @example          : interpolate([2,0],[3,2],2.4) -> 0.8
*/
int interpolate(std::vector<int>& X_axis, std::vector<int>& Y_axis, int value)

Obviously the formatting to use for your comments may depend on your development environment (Visual studio, JavaDoc under Eclipse, ...)
As far as SCE is concerned, I assume by this you mean the following:
bool b1;
b1 = somecomplicated_function(); // let me explain what this function does
bool b2 = false;
if (!b1) {                       // SCE : if first function call is already true,
                                 // no need to spend resources executing second function.
  b2 = someother_function();     // this function does something else
}

if (b1 || b2) {
...
}

A: I tend to break down conditions onto multiple lines, i.e.:
if( SomeComplicatedFunctionCall()
 || OtherComplicatedFunctionCall()
  ) {

Even when dealing with multiple operators (&&) you just need to advance indention with each pair of brackets. SCE still kicks in - no need to use variables. Writing code this way made it much more readible to me for years already. More complex example:
if( one()
 ||( two()> 1337
  &&( three()== 'foo'
   || four()
    )
   )
 || five()!= 3.1415
  ) {

A: If you have long chains of conditions and what to keep some of the short-circuiting, then you could use temporary variables to combine multiple conditions. Taking your example it would be possible to do e.g.
bool b = SomeComplicatedFunctionCall() || OtherComplicatedFunctionCall();
if (b && some_other_expression) { ... }

If you have a C++11 capable compiler you could use lambda expressions to combine expressions into functions, similar to the above:
auto e = []()
{
    return SomeComplicatedFunctionCall() || OtherComplicatedFunctionCall();
};

if (e() && some_other_expression) { ... }

A: 1) Yes, you no longer have SCE. Otherwise, you would have that
bool b1 = SomeComplicatedFunctionCall();
bool b2 = OtherComplicatedFunctionCall();

works one way or the other depending if there is an if statement later. Way too complex.
2) This is opinion based, but for reasonably complex expressions you can do:
if (SomeComplicatedFunctionCall()
    || OtherComplicatedFunctionCall()) {

If it ways too complex, the obvious solution is to create a function that evaluates the expression and call it.

A: You can also use:
bool b = someComplicatedStuff();
b = b || otherComplicatedStuff(); // it has to be: b = b || ...;  b |= ...; is bitwise OR and SCE is not working then

and SCE will work.
But it's not much more readable than for example:
if (
    someComplicatedStuff()
    ||
    otherComplicatedStuff()
   )

A:
1) Do I really lose SCE every time? Is compiler is some scenario allowed to "optimize it" and still provide SCE?

I don't think such optimization is allowed; especially OtherComplicatedFunctionCall() might have some side effects.

2) What is the best practice in such situation? Is it only possibility (when I want SCE) to have all I need directly inside if and "just format it to be as readable as possible" ?

I prefer to refactor it into one function or one variable with a descriptive name; which will preserve both short circuit evaluation and readability:
bool getSomeResult() {
    return SomeComplicatedFunctionCall() || OtherComplicatedFunctionCall();
}

...

if (getSomeResult())
{
    //do stuff
}

And as we implement getSomeResult() based on SomeComplicatedFunctionCall() and OtherComplicatedFunctionCall(), we could decompose them recursively if they're still complicated.

A: One natural solution would look like this:
bool b1 = SomeCondition();
bool b2 = b1 || SomeOtherCondition();
bool b3 = b2 || SomeThirdCondition();
// any other condition
bool bn = bn_1 || SomeFinalCondition();

if (bn)
{
  // do stuff
}

This has the benefits of being easy to understand, being applicable to all cases and having short circuit behaviour.

This was my initial solution: A good pattern in method calls and for-loop bodies is the following:
if (!SomeComplicatedFunctionCall())
   return; // or continue

if (!SomeOtherComplicatedFunctionCall())
   return; // or continue

// do stuff

One gets the same nice performance benefits of shortcircuit evaluation, but the code looks more readable.

A: Readability is necessary if you work in a company and your code will be read by someone else. If you write a program for yourself, it is up to you if you want to sacrifice performance for the sake of comprehensible code.


text:
Q: Expanding a divergence term I am trying to prove the following as a part of a larger derivation:
$$\nabla^\sigma.(\gamma^{wn}I^\sigma)=\nabla^\sigma\gamma^{wn}-N\gamma^{wn}(\nabla^\sigma.N)$$
Where,
$N$ is the unit vector normal to the interface
$\gamma^{wn}$ is a scalar
surface divergence operator, $\nabla^\sigma=\nabla-NN.\nabla$
projected surficial identity tensor, $I^\sigma=I-NN$
Here is my attempt:
$$\nabla^\sigma.(\gamma^{wn}I^\sigma)=\gamma^{wn}\nabla^\sigma.I^\sigma+I^\sigma.\nabla^\sigma\gamma^{wn}$$
$$\nabla^\sigma.(\gamma^{wn}I^\sigma)=(I-NN).\nabla^\sigma\gamma^{wn}+\gamma^{wn}\nabla^\sigma.(I-NN)$$
$$\nabla^\sigma.(\gamma^{wn}I^\sigma)=I.\nabla^\sigma\gamma^{wn}-NN.\nabla^\sigma\gamma^{wn}+\gamma^{wn}(\nabla^\sigma.I-\nabla^\sigma.NN)$$
$$\nabla^\sigma.(\gamma^{wn}I^\sigma)=\nabla^\sigma\gamma^{wn}-(N.\nabla\gamma^{wn})N-\gamma^{wn}\nabla^\sigma.NN$$
$$\nabla^\sigma.(\gamma^{wn}I^\sigma)=\nabla^\sigma\gamma^{wn}-(N.\nabla\gamma^{wn})N-\gamma^{wn}(\nabla.N)N-\gamma^{wn}(N.\nabla{N})$$
So terms 1 and 3 are what I needed, but I got two more terms. I am not sure if I did this correctly and what I have missed.
Appreciate any help!


text:
Q: Auto populating calendars in excel I have a list of project IDs with start and end dates listed by the numbered day and month. (EX august =8, 1st =1) I have a calendar on another sheet with the month and day numbers in their own cells. I want the project ID to populate in the cell where the month and day numbers on the two sheets match.
Example = if A1 + A2 on Sheet1 Match A1 & A2 on Sheet2, Populate The Project ID here.
Can someone help me figure out the easiest way to do this?

A: If you have a data like this (in Sheet 1 for this example):

You can use this array formula (don't forget to press Ctrl+Shift+Enter) to populate the ID when the day and month number match:
=INDEX(Sheet1!$A$1:$A$6,MAX((A2=Sheet1!$B$2:$B$6)*(B2=Sheet1!$C$2:$C$6)*ROW(Sheet1!$B$2:$B$6)))

The brackets at the beginning and end of the formula is because it's an array formula.
I let you an example here: https://docs.google.com/spreadsheets/d/1xVmoZ8cGURuwnYF8AsLkozWUIxc5nPmt/edit?usp=sharing&ouid=109997475435544900987&rtpof=true&sd=true


text:
Q: Compare two excel columns which the most frequently occur in specific date I would like to compare between few columns, what where the top 5 most popular products in year 2015.
I have this kind of data flow to work with:
Client | Product | Date of buy
------------------------------
client1 | A | 15.06.2015
client3 | A | 04.12.2015
client5 | F | 15.06.2015
client9 | G | 15.01.2015
client2 | G | 15.01.2015
client1 | R | 05.07.2015
client3 | G | 15.06.2015
client1 | F | 05.07.2015
client3 | F | 15.06.2016
Results - which products client bought the most with (in same date) the top 5 products communities of them. E.g..

 1. Product A + Product H 222 times
 2. Product A + Product E 77 times
 3. Product B + Product O 70 times
 4. etc
 5. ...

Greetz,

A: Making the assumption:

*

*you can use helper columns.

*Your Columns up above are A, B and C.

*You have two header rows and data starts in row 3.

*Your dates are stored in an excel date format and not string values.

In E2 I generated a list of unique product items using the following formula:
=INDEX($B$3:$B$11,MATCH(0,INDEX(COUNTIF($E$2:E2,$B$3:$B$11),0,0),0))

I copied it down to match the number of rows in the initial list.  It starts spitting #N/A when all the unique items in the list have been listed.  If you want to avoid this you could put the formula inside of:
=IFERROR(insert formula,"")

Now in column F I did a count based on your criteria of each item and within the year 2015. I used a multiple count if function called COUNTIFS:
=COUNTIFS($C$3:$C$11,"<"&DATE(2016,1,1),
          $C$3:$C$11,">"&DATE(2014,12,31),
          $B$3:$B$11,E3)

I just reformatted that for easier reading.  You will have to edit that slightly if you want to copy and paste.  If you don't like seeing 0 when there is no product in the adjacent column you could wrap the equation in:
=IF(E3="","",  insert formula  )

I then skipped a column and sorted the list of counted items from largest to smallest and had it return the numbers in sequence.  I only went down two rows, but you could technically do the whole list.  The large function does this and the formula in H3 looks like:
=LARGE($F$3:$F$11,ROWS($1:1))

I then went back 1 column and put the product name that corresponds to the count, and then took the next name in the list when products had equal count.  I put that in column F as normally when I read I want to read the product name first then read the quantity. If you want it the other way around just swap the columns.  The formula in G1 is:
=INDEX($E$3:$E$11,MATCH(H3,$F$3:$F$11,0)+COUNTIF($H$3:$H3,H3)-1)

Copy E3 and F3 down as far as you need.  Copy G3 and H3 down one row and you will have top two.  down two rows and you have top three etc.
This is how it looks...The dates are displayed according to my computers date format.


text:
Q: Xcode after compiling program shows only lldb, but no answers, how to change it?     #include <iostream>
    #include <math.h>
    #include <cstdlib>
    #include <cmath>
    #include <stdlib.h>
    #include <iomanip>
    using namespace std;
    int main () {

    double x=0.2,skait,vard1,vard2,E;

    cout<<"Results"<<endl;
    for (int i=1; i<=10; i++)
    {
        E=exp(x+2);
        skait=log((2*x*x)+(3*E));
        vard1=abs(sin(2*x)-(8*x*x*x));
        vard2=sin(x*x);
        cout<<(skait/(vard1+vard2))<<endl;
        x=x+0.08;
    }
    return 0;

So this was my lab project, but after compiling the code i get (lldb) message and nothing else.
How to view the answer or change the preferences so that i'd never see that error again?
(http://imgur.com/ZCCwptW) - The error


text:
Q: Google Cloud Identity: Group Managers cannot delete group members I am listed as MANAGER in a group that I am managing on a Google Cloud Platform organisation via the IAM Groups interface on https://console.cloud.google.com/iam-admin/groups.
But they delete icon is greyed out, and displaying a message:

You need the following permissions to be granted by a group administrator for this action:
Required permission(s): cloudidentity.memberships.remoMemberRole

The message links to a documentation, that has no helpful information nor mentions the problem described in the message.
AFAIK, as a manager of a group, one should be able to add and remove members.
Can you help me fix or explain this issue?

A: This issue got resolved. It was an UI bug and got fixed by the Cloud Console team. I can no longer reproduce it.


text:
Q: matrix addition from an array r I have an array with 272 matrices, each one is 2 by 2. I now want to sum these matrices up using matrix addition. So I want the return to be a single 2 by 2 matrix.  Here are some code I have used.
 y <- as.matrix(faithful)
 B <- matrix(c(0,0,0,0),nrow = 2)

 sigma <- function(n = 272,u_new) {
     vec = replicate(272,B)

     for (i in 1:n) {

w <- (y-u_new)[i,]
x <- ptilde1[i]*(w%*%t(w))
vec[,,i][1,1] <- x[1,1]
vec[,,i][1,2] <- x[1,2]
vec[,,i][2,1] <- x[2,1]
vec[,,i][2,2] <- x[2,2]}

  vec
  }

Here vec is the array with 272 matrices. Thank you in advance.

A: Here is code which loops a number of times (272) and adds a matrix to the same list.
B <- matrix(c(0,0,0,0),nrow = 2)
list <- list(B)
for (i in 2:272) {
    list[[i]] <- B
}

To add them all together, you can use the Reduce() function:
sum <- Reduce('+', list)
> sum
     [,1] [,2]
[1,]    0    0
[2,]    0    0

This is a contrived example because all the matrices are the zero matrix.  I will leave it to you as a homework assignment to use the matrices you actually want to sum together.


text:
Q: Laravel Service Provider Still Registering In If Statement I'm having a few issues with registering a Laravel service provider. In the sense that the service provider is always gets registered, even when it shouldn't.
I'm using composer require laravel/telescope --dev and looking at their docs. You can do an if statement within AppServiceProvider.php to allow this to register on occasion, in this sense I want only to register if the app has debug enabled.
I created the method.
protected function hasDebug()
{
   return config('app.debug');
}

This returned whether or not debug is set within the env. I then have the following if statement within my register method.
public function register()
{
    if ($this->hasDebug()) {
        $this->app->register(TelescopeServiceProvider::class);
    }
}

However, even when I have not enabled debugging (I can see this by doing dd($this-hasDebug()) it will return false. Everything to do with Telescope is being provided. I can still access routes, whereas realistically I do not want to be able to access anything to do with Telescope.
Can someone point out where I'm going wrong?

A: For anyone else who is having this issue, this is how to correct it.
The issue was to do with auto discovery within composer. It was always picking up Telescope therefore always registering it.
Although all of the logic was correct within my AppServiceProvider because it was registering it was basically ignored.
Inside of composer.json, I added this...
"extra": {
    "laravel": {
        "dont-discover": [
            "laravel/telescope"
        ]
    }
},

A: Change "app.debug" to APP_DEBUG.  The config helper pulls the mappings directly from your .env file.


text:
Q: Цикл foreach в переменной Как можно записать следующий код по-другому?
$errors .=

    "
Его ключ =" .

    foreach($_SESSION['cart'] as $key => $value) {
        $_SESSION['cart'][$key];
    } .

    "его наличие = {$_SESSION['auth'][$id]['nalichies']}
";

Сейчас выходит ошибка syntax error unexpected t-foreach.
Возможно надо записать по-другому?
[cart] => Array
    (
        [1] => Array
            (
                [qty] => 2
                [name] => Название 1
                [price] => 999
                [img] => 1.jpg
                [nalichies] => 2
            )

        [3] => Array
            (
                [qty] => 3
                [name] => Название 2
                [price] => 750
                [img] => no_image.jpg
                [nalichies] => 53
            )

    )

Вот сам код выполнения:
$errors = ''; // флаг проверки пустых полей
$name = trim($_POST['name_zakaz']);

if(empty($name)) $errors .= '
Не указано ФИО
';

//ТАК РАБОТАЕТ (то, что нужно). Но, если реализовать на данных основанных из корзины - так не правильно, т.к. $vnal можно подделать.  Поэтому хочется брать данные из сессии корзины, как показано на 2-ом for
for ($i = 0; $i < count ($_POST['na']);$i++ ) {
    $id = $_POST["na"][$i]; // уникальный id товара
    $vnal = $_POST["nas"][$i]; // имеющееся количество товара
    $kolvo = $_POST["nass"][$i]; // количество введенное заказчиком
    if ($kolvo > $vnal) { //если заказчик ввел кол-во товаров больше числа доступных товаров
        $errors .= "
Товара с id = {$id} в кол-ве {$kolvo} шт. нет в наличии!
";
    }
}
//ТАК НЕ РАБОТАЕТ.
for ($i = 0; $i < count ($_POST['na']);$i++ ) {
    $id = $_POST["na"][$i]; // уникальный id товара - его, конечно, надо тоже брать из сессии корзины
    $kolvo_tovara_v_korzine = $_POST["nass"][$i]; // количество введенное заказчиком уже брать методом POST

    if ($kolvo_tovara_v_korzine > $_SESSION['cart'][$id]['nalichies']) { //если заказчик ввел кол-во товара больше числа имеющегося наличия
        $errors .= "
Товар с id =" .(foreach($_SESSION['cart'] as $key => $value){$_SESSION['cart'][$key];}). "не может содержаться в количестве: {$kolvo_tovara_v_korzine} шт.
";
    }    //Также хотелось бы
}

if(empty($errors)){
    // выполнение кода
}else{
// если не заполнены обязательные поля и другие возможные ошибки
    $_SESSION['order']['res'] = "
Ошибка оформления заказа:
{$errors}

";
    $_SESSION['order']['name'] = $name;
    return false;
}

A: Было бы круто показать в каком виде хранится информация в глобальном массиве $_SESSION['cart'] и что вы ожидаете увидеть на выходе.
Насколько я понял, вы имели ввиду это...
$errors .= "
Его ключ =";
foreach($_SESSION['cart'] as $key => $value) {
    $errors .= $value; // Если нужен только ключ, то вместо $value подставьте $key
}
$errors .= "его наличие = {$_SESSION['auth'][$id]['nalichies']}
";

A: Попробуйте формировать $_POST['nass'] так:
<imput type="number" name="nass[<?=product_id;?>]" value="{customer_entered_qty}" />

Достаньте из $_post nass:
$post_nass = $_POST['nass'];

И добавлять сверку session_qty и customer_entered_qty:
foreach($session as $sess_k => $sess_v){

    foreach($post_nass as $post_k => $post_v){

       $post_v = strip_tags(htmlspecialchars(mysql_real_escape_string(abs((int)$post_v))));

       if($post_k == $sess_v['name'] && $post_v > $sess_k['nalichies']){
           $errors .= "
нельзя купить " . $sess_k['qty'] . "ед. " . $sess_k['name'] . " - в наличии: " . $sess_k['nalichies'] . "
";
       }

    }

}

Для идентификации единицы товара лучше всё же использовать id а не name.


text:
Q: Is there a way to use Lombok's @builder with a limited set of attributes in the constructor? I'm working on a project which uses the Builder pattern. But this team uses Builder constructor arguments for the "required" attributes, and the builder "setters" for the optional stuff.
Here is an example where name is required and age is optional.
Person person = Person.Builder("Bob Belcher").age(23).build();

When I apply @Builder, is there anyway I can instruct Lombok to add specified attributes in the builder's constructor?

A: I would suggest an overloaded static method builder taking the required arguments and returning the builder object. Thus lombok won't be generating a builder method since we have already defined it.
@Builder
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class Person {
    // fields....
    public static PersonBuilder builder(String name) {
        return new PersonBuilder().name(name);
    }

}

The private access level could enforce that the object be created using only the of method.
For the requirement of "builder setters for the optional stuff", such that you cannot invoke name() on the builder object, you may try to override the builder methods for the required arguments to make it private. Refer here. (Also related use case)
@Builder
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class Person {
    // fields....
    public static PersonBuilder builder(String name) {
        return new PersonBuilder().name(name);
    }

    public static class PersonBuilder  {
        private PersonBuilder name(String name) {
            this.name = name;
            return this;
        }
    }
}

// invoke as
Person.builder("my name").age(23).build();


text:
Q: Jquery PopUp in asp.net gridview Please provide me code to how to open jquery popup by clicking on asp.net gridview row to show each row's data in the popup

A: http://www.encodedna.com/2013/03/gridview-row-mouseover.htm
https://web.archive.org/web/20211020202824/https://www.4guysfromrolla.com/articles/070407-1.aspx
and some technical details on
Display details on moving mouse over a row in gridview?


text:
Q: Check fields in GraphQLObjectType with typescript I use graphql-js to do my schema and i can't detect error types on compilation with typescript :
ie :
export type CustomFieldsType = {
  id: number;
};

export default {
  type: new GraphQLNonNull(
    new GraphQLObjectType({
      name: 'DescriptionFields',
      fields: {
        id: {
          description: 'custom description for id',
          type: new GraphQLNonNull(GraphQLID),
        },
        ...
      },
    }),
  ),
  args: {
   ...
  },
  resolve: () =>...
};

Is there any way to apply my custom CustomFieldsType on my GraphQLObjectType ?


text:
Q: netDxf package - System.IO.FileNotFoundException: 'Could not load file or assembly 'System.Drawing.Common I am attempting to run the code sample listed on the README for the netDXF project: https://github.com/haplokuon/netDxf, but the code throws the following exception on the line DxfDocument dxf = new DxfDocument();:
System.IO.FileNotFoundException: 'Could not load file or assembly 'System.Drawing.Common, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot find the file specified.'

Steps I followed:
1. I installed Visual Studio 2019 and created a new project with a "target Framework" value of ".NET core 3.0" and an "Output Type" of "Console application".
2. I have installed the netDXF package by right-clicking my project and selecting "Manage NuGet Packages", and installing netDxf from there.
3. I ran the code, saw the exception, and gathered the following stack trace from the .netDxf library:
    netDxf.dll!netDxf.Tables.TextStyle.TextStyle(string name, string font, bool checkName)  Unknown
    netDxf.dll!netDxf.Tables.TextStyle.TextStyle(string name, string font)  Unknown
    netDxf.dll!netDxf.Tables.TextStyle.Default.get()    Unknown
    netDxf.dll!netDxf.DxfDocument.AddDefaultObjects()   Unknown
    netDxf.dll!netDxf.DxfDocument.DxfDocument(netDxf.Header.HeaderVariables drawingVariables, bool createDefaultObjects, System.Collections.Generic.IEnumerable<string> supportFolders) Unknown
    netDxf.dll!netDxf.DxfDocument.DxfDocument(netDxf.Header.HeaderVariables drawingVariables)   Unknown
    netDxf.dll!netDxf.DxfDocument.DxfDocument() Unknown
>   Mason.dll!Mason.Program.Main() Line 15  C#

Here is the full code snippet that I am attempting to run (Program.cs):
using netDxf;
using netDxf.Entities;
using netDxf.Header;

namespace Mason
{
    class Program
    {
        public static void Main()
        {
            // your dxf file name
            string file = "sample.dxf";

            // by default it will create an AutoCad2000 DXF version
            DxfDocument dxf = new DxfDocument();
            // an entity
            Line entity = new Line(new Vector2(5, 5), new Vector2(10, 5));
            // add your entities here
            dxf.AddEntity(entity);
            // save to file
            dxf.Save(file);

            // this check is optional but recommended before loading a DXF file
            bool isBinary;
            DxfVersion dxfVersion = DxfDocument.CheckDxfFileVersion(file, out isBinary);
            // netDxf is only compatible with AutoCad2000 and higher DXF version
            if (dxfVersion < DxfVersion.AutoCad2000) return;
            // load file
            DxfDocument loaded = DxfDocument.Load(file);
        }
    }
}


text:
Q: Associated Delete in CakePHP 2.5.4 I have 2 entities in the database Element and Section.
1 section has 0-N elements so in the element table I have a foreign key
CONSTRAINT `elements_sections` FOREIGN KEY (`section_id`) REFERENCES `sections` (`id`) ON UPDATE CASCADE ON DELETE CASCADE

Element Model .php has this:
public $belongsTo = array(
        'Section' => array(
            'className' => 'Section',
            'foreignKey' => 'section_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );

In the Section model I have:
public $hasMany = array(
    'Element' => array(
        'className' => 'Element',
        'foreignKey' => 'section_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    )
);

All this code looks good, however, when I delete an element of the section with ID=X, if there's an element (in any other section) with ID=X that element is deleted too. This is the code I am using in my whole aplication but only fails here. $this->data is the Element object.
$this->Element->delete($this->data)

A detailed example:
Section 20 -> Element 400
Section 3 -> Element 20
If I delete the element 400, the Element 20 is deleted too.
I guess that I am missing a configuration parameter or some.
Thanks in advance.

A: For somebody that can face the same problem this could help:
Model::delete() can delete multiple records.
[
    'id' => 1,
    'category_id' => 3,
    'price' => 10000,
]

Will generate
DELETE FROM elements WHERE id IN (1, 3, 10000).


text:
Q: Obtain html element by custom attribute I'm trying to get an element by a custom attribute, the element I want is right below
<div id="ember4714" data-test-field-name="Opportunity name">

I want to get the element by the data-test-field-name attribute when its value equals "Opportunity name", I have to do that because the id always changes value in the panel I'm working on.
How can I get this element by this attribute?

A: You can use the CSS attribute selector:
document.querySelector('[data-test-field-name="Opportunity name"]')


text:
Q: How to call api vs parameters cancellationToken xamarin forms I am building an operation that calls api with the cancellationToken parameter. cancel () from event A, when the party B is calling, the api will be caught, but I want this exception to be arrested on the api side. ..... help, it took me 4 days but it didn't work out
api server
public async Task<Actionresult> getText(CancellationToken token){ string s= "";try{for(int i=0;i<10;i++)
       {
           a += " number "+i;
           await Task.Delay(1000,token);
         }
 }catch(Excaption ex){
     return badrequest("canceled")
 }

}
client xamaarin app
CancellationTokenSource cts = new CancellationTokenSource();

private async commandEventA()
{
    cts.Cancel();
}

private async commandEventB()
{
    var token =cts.Token();
    string txtkq ="";
    var client = new RestClient("urlwebb");
    RestRequest request = new RestRequest("");
    try{
        var a = await
            client.ExcuteTaskAsync(request,token);
    }catch(TaskCancellationException ex){}
}


text:
Q: get all post and comments on single html templates I am quite new to django. So forgive me if any stupid content mentioned over here and please guide me.
I want to display the all post and related comments in to crave.html template. I tried that but am not able to do that. How can i use the ajax request over there?
models.py
class crave_data(models.Model):
    person = models.ForeignKey(User)
    post=models.TextField(blank = True,null = True)
    date= models.DateTimeField(auto_now_add=True, blank=True)

 class comments(models.Model):

    crave=models.ForeignKey(crave_data, blank = True,null = True)
    reply=models.CharField(max_length=1000, blank = True,null = True)

    date= models.DateTimeField(auto_now_add=True, blank=True)

i want to display the all possts and related comments on the crave.html page. And after submitting the craveit should get display on the same page. And there should be option for reply. Like normal post comment structure.
Here is my views.py
@login_required
def crave_edit(request, id=None):
    instance = get_object_or_404(crave_data, pk=id) if id else None
    crave_made = None
    if instance and instance.person != request.user:
        raise PermissionDenied()

    if request.method=="POST":
        form=CraveDataForm(request.POST, request.FILES, instance=instance)

        if form.is_valid():
            crave_made = form.save(commit=False)
            crave_made.person = request.user
            crave_made.save()

       else:
        form=CraveDataForm(instance=instance)

    return render(request, "crave/crave.html", {'form' : form,'crave_made':crave_made})

@login_required
def crave_view(request, id):
    #what id is this? this is crave_data id
    crave = get_object_or_404(crave_data, pk=id)
    print crave
    check = comments.objects.filter(crave=crave.id)
    if request.method=="POST":
        form=CraveReplyForm(request.POST, request.FILES)
        if form.is_valid():
            reply = form.save(commit=False)
            reply.person=request.user
            reply.crave = crave
            reply.save()
    else:
        form=CraveReplyForm()

    return render(request, "crave/comment.html", {'crave': crave, 'form' : form, 'check':check})

My urls.py
urlpatterns = patterns('crave.views',
                       url(r'^$', 'crave_edit'),
                       url(r'^(?P<id>.*)/$', 'crave_edit'),
                       url(r'^reply_get/(?P<id>.*)$', 'crave_view'),

     )

crave.html
<form action="" method="post" style="font-size:150%">{% csrf_token %}
Query

                {{ form.post }}
  <input type="submit" value="Submit" style="background-color:#53760D;color:#D0F18F;width:30% ;align:center;margin:0 auto;" />
</form>

comment.html
<form class="horizontal-form" role="form" action="/crave/reply_get/{{crave.id}}" method="post"  style="padding: 10px;">
           {% csrf_token %}

                        {{ form.reply.label_tag }} {{ form.reply }}

                    <input type="submit" class="btn btn-success" value="reply" />
    </form>
  {{crave}}
{% for pf in check%}
                  {{pf.reply}}

            {% endfor %}

Rt now post and comment are on different templates. I want to use ajax request to get all post and comment on crave.html page.
Please help me out. Thanks in advance.


text:
Q: Get error when install Oracle JDK 8 on Ubuntu 18.04 I am trying install Oracle Java 8 on Ubuntu 18.04 LTS.
$ java --version

Command 'java' not found, but can be installed with:

sudo apt install default-jre
sudo apt install openjdk-11-jre-headless
sudo apt install openjdk-8-jre-headless

According tutorial i added ppa:
sudo add-apt-repository ppa:webupd8team/java

and after that i updated my os:
$ sudo torsocks apt-get update
Hit:1 http://ppa.launchpad.net/webupd8team/java/ubuntu bionic InRelease
Ign:2 http://dl.google.com/linux/chrome/deb stable InRelease
Hit:3 http://us.archive.ubuntu.com/ubuntu bionic InRelease
Hit:4 http://dl.google.com/linux/chrome/deb stable Release
Hit:6 http://us.archive.ubuntu.com/ubuntu bionic-updates InRelease
Hit:7 http://us.archive.ubuntu.com/ubuntu bionic-backports InRelease
Hit:8 http://us.archive.ubuntu.com/ubuntu bionic-security InRelease
Reading package lists... Done

and then I ran:
sudo apt-get install oracle-java8-installer

But I got :
$ sudo torsocks apt-get install oracle-java8-installer
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package oracle-java8-installer is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'oracle-java8-installer' has no installation candidate

I found this solution but it is not working and I got same error

A: The WebUpd8 Team's PPA for that repository has been discontinued, per the PPA's page itself.
To quote the PPA specifically, this is in regards to changes in the License Agreement, and that you must physically manually download the latest Java 8 versions because they make you sign into an Oracle Account (which is free) to even gain access to downloads.  This is explicitly stated in the PPA description, quoted here as of April 22, 2019:

The Oracle JDK License has changed for releases starting April 16,
  2019.
The new Oracle Technology Network License Agreement for Oracle Java SE
  is substantially different from prior Oracle JDK licenses. The new
  license permits certain uses, such as personal use and development
  use, at no cost -- but other uses authorized under prior Oracle JDK
  licenses may no longer be available. Please review the terms carefully
  before downloading and using this product. An FAQ is available here:
  https://www.oracle.com/technetwork/java/javase/overview/oracle-jdk-faqs.html
Oracle Java downloads now require logging in to an Oracle account to
  download Java updates, like the latest Oracle Java 8u211 / Java SE
  8u212. Because of this I cannot update the PPA with the latest Java
  (and the old links were broken by Oracle).
For this reason, THIS PPA IS DISCONTINUED (unless I find some way
  around this limitation).

A: I look up to the webupd8 site and it seems that the ppa was discontinued.

Oracle Java downloads now require logging in to an Oracle account to download Java updates, like the latest Oracle Java 8u211 / Java SE 8u212. Because of this I cannot update the PPA with the latest Java (and the old links were broken by Oracle).
For this reason, THIS PPA IS DISCONTINUED (unless I find some way
  around this limitation).
  http://www.webupd8.org/2012/09/install-oracle-java-8-in-ubuntu-via-ppa.html

How to install it then?
You can create account on Oracle to download Java from their site (they are free for personal use), then follow this instruction → How can I install Sun/Oracle's proprietary Java JDK 6/7/8 or JRE?.


text:
Q: How to generate combination of N elements with limited supply of 2 each without explicit nested loops If N is fixed,like N = 3, then it is easy, i can use nested loops of depth 3.
e.g.
from i in Enumerable.Range(0, 2)
from j in Enumerable.Range(0, 2)
from k in Enumerable.Range(0, 2)
select new int[] { i, j, k };

what if N is a variable?

A: What you need is some sort of array 'multiplyer'. Something like this:
private static IEnumerable<int[]> Multiply(IEnumerable<int[]> input,
    IEnumerable<int> multiplyers)
{
    foreach (var array in input)
    {
        foreach (var multiplyer in multiplyers)
        {
            yield return array.Concat(new int[] { multiplyer })
                .ToArray();
        }
    }
}

You can use this method as follows to get the same result as your example above:
int n = 3;

var multiplyers = Enumerable.Range(0, 2);

IEnumerable<int[]> results =
    from m in multiplyers select new int[] { m };

while (n-- > 1)
{
    results = Multiply(results, multiplyers);
}

Now n is variable.


text:
Q: How to destroy the imageflow jquery plugin instance? has anyone worked with imageflow jquery plugin? Do you know how to destroy an instance? When I remove with jquery the structure that this plugin creates, the events of the plugin continue to be triggered. Any idea or tip how to do this? Thanks

A: Have you tried simply unbinding the events associated with the object:
theObject.unbind()

Also, check out this SO question - it looks similar, and may help


text:
Q: Проблема с прозрачным текстом при иммитации обводки с помощью псевдоэлементов Мне трудно поверить, что не существует стандартного и простого (и независимого от браузера) способа поместить эффект обводки вокруг текста с помощью CSS.
Есть -webkit-text-stroke, но по какой-то странной причине, обводка сосредоточена вокруг границы текста, а не за ее пределами. Как показано здесь.
Я пытаюсь реализовать обходной путь, основанный на этой идее, который помещает заштрихованный текст в псевдоэлемент за исходным незаштрихованным текстом. Я продемонстрировал это в этом jsfiddle со следующим кодом:

var jQueryAttr = function(selector, attr, setterFunction) {
  document.querySelectorAll(selector).forEach((el, i) => {
    el.setAttribute(attr, setterFunction.call(el, i, attr));
  });
};

jQueryAttr('.myclass', 'data-myclass', function(index, attr) {
  return this.innerHTML;
});
body {
  background: none;
}

.basic {
  color: rgba(186, 218, 85, 1);
  font: 2.5em Georgia, serif;
}

.myclass {
  position: relative;
  background: transparent;
  z-index: 0;
}

.myclass::before {
  content: attr(data-myclass);
  position: absolute;
  -webkit-text-stroke: 0.2em rgba(0, 0, 0, 1);
  z-index: -1;
}

.anotherclass {
  -webkit-text-stroke: 0.2em rgba(0, 0, 0, 1);
}

Text without any stroke

Text with outer stroke

Without the trick applied

Это работает нормально, за исключением того, что если сам текст имеет некоторую прозрачность, то вы видите темный штрих под ним, как показано в этом варианте.
Как вы можете видеть, черный цвет от обведенного элемента просачивается в текст (в верхней строке).
Так есть ли еще один хитрый способ решить эту проблему?
Я предполагаю, что возможно добавить еще один псевдоэлемент между слоем с обводкой и слоем без обводки. С чистым белым текстом или с тем, чтобы соответствовать фону. Но я хотел бы применить эту технику в контексте, где я не не знаю цвет фона заранее, например, где это накладывается на произвольное выбранное пользователем изображение. По этой причине, в приведенном выше примере я установил значение фона body.

A: SVG решение
Самым простым и с лучшей поддержкой браузеров может быть SVG.
Вы можете настроить примерно то же самое, что вы сделали с :: before, с той разницей, что версия с обводным фоном может иметь маску, которая позволит видеть только внешнюю линию.  Оттуда вы можете просто добавить копию того же текста поверх, и вы сможете применить непрозрачность, как вы хотите, как для обводки и заливки:

body{
  background-image:url(https://picsum.photos/800/800?image=1051);
  background-size:cover;
  background-position:center;
  font-family: sans-serif;

}
svg {
  font-size: 40px;
  font-weight: bold;
}
.textStroke {
  stroke: black;
  stroke-width: 12px;
  stroke-linejoin: round;
}
.visibleText {
  fill: rgba(186, 218, 85, 1);
  transition: fill-opacity .5s linear;
}
.visibleText:hover {
  fill-opacity: 0;
}
<svg width="350">
  <defs>

    <text x="10" y="55" id="txt">Text with outline</text>
    <mask id="mymask">

      <rect x="0" y="0" width="450" height="70" fill="#FFF"></rect>
      <use xlink:href="#txt" fill="#000"/>
    </mask>
  </defs>

  <use xlink:href="#txt" mask="url(#mymask)" class="textStroke"/>

  <use xlink:href="#txt" class="visibleText"/>
</svg>

Источник ответа: @Kaiido

A: *

*Вот идея, где вы можете применить mix-blend-modeё в сочетании с
text-shadow, чтобы приблизить это. Самое сложное - отрегулировать
тень на тот случай, если вы хотите широкую строку обводки:

.text > span {
  font-family:sans-serif;
  font-size:60px;
  font-weight: bold;
  color:#fff; /*use white*/
  /*create the stroke around text*/
  text-shadow:
    2px 0  0px #000,
    0 2px 0px #000,
    2px 2px 0px #000,
    -2px 0 0px #000,
    0 -2px 0px #000,
    -2px -2px 0px #000,
    -2px 2px 0px #000,
    2px -2px 0px #000;
  mix-blend-mode: darken; /*everything is more dark than white so we always see the background */
}
.text {
  display:inline-block;
  padding:20px;
  background:linear-gradient(to right,red, blue);
}

Some text here

*

*Использование CSS-переменной, вероятно, облегчит настройку:

.text > span {
  font-family:sans-serif;
  font-size:60px;
  font-weight: bold;
  color:#fff; /*use white*/
  /*create the stroke around text*/
  text-shadow:
    var(--s,2px) 0  var(--c,0) #000,
    0 var(--s,2px) var(--c,0) #000,
    var(--s,2px) var(--s,2px) var(--c,0) #000,
    calc(-1*var(--s,2px)) 0 var(--c,0) #000,
    0 calc(-1*var(--s,2px)) var(--c,0) #000,
    calc(-1*var(--s,2px)) calc(-1*var(--s,2px)) var(--c,0) #000,
    calc(-1*var(--s,2px)) var(--s,2px) var(--c,0) #000,
    var(--s,2px) calc(-1*var(--s,2px)) var(--c,0) #000;
  mix-blend-mode: darken; /*everything is more dark than white so we always see the background */
}
.text {
  display:inline-block;
  padding:20px;
  background:linear-gradient(to right,red, blue);
  background-size:cover;
  background-position:center;
}

Some text here

Some text here

Some text here

*

*Если вам нужен прозрачный цвет для текста, вы можете продублировать
его, используя псевдоэлемент:

.text > span {
  font-family:sans-serif;
  font-size:60px;
  font-weight: bold;
  position:relative;
  display:inline-block;
}
.text > span::before,
.text > span::after {
  content:attr(data-text);
}
.text > span::before {
  color:#fff; /*use white*/
  /*create the stroke around text*/
  text-shadow:
    var(--s,2px) 0  var(--c,0) #000,
    0 var(--s,2px) var(--c,0) #000,
    var(--s,2px) var(--s,2px) var(--c,0) #000,
    calc(-1*var(--s,2px)) 0 var(--c,0) #000,
    0 calc(-1*var(--s,2px)) var(--c,0) #000,
    calc(-1*var(--s,2px)) calc(-1*var(--s,2px)) var(--c,0) #000,
    calc(-1*var(--s,2px)) var(--s,2px) var(--c,0) #000,
    var(--s,2px) calc(-1*var(--s,2px)) var(--c,0) #000;
  mix-blend-mode: darken; /*everything is more dark than white so we always see the background */
}
.text > span::after {
  position:absolute;
  top:0;
  left:0;
  color:rgba(0,255,0,0.4);
}
.text {
  display:inline-block;
  padding:20px;
  background:linear-gradient(to right,red, blue);
  background-size:cover;
  background-position:center;
}

Источник ответа: @Temani Afif

A: Решение с помощью SVG фильтров
Для получения обводки вокруг текста, можно использовать комбинированный SVG фильтр, состоящий из последовательно применяемых фильтров: feMorphology, feComposite и feColorMatrix.
Решение универсальное, его можно использовать для любых графических объектов.
Пример использования

body{
  background-image:url(https://picsum.photos/800/800?image=1061);
  background-size:cover;
  font-family: serif;

}
<svg  viewBox="0 0 350 350" >
  <defs>
    <filter id="groupborder" filterUnits="userSpaceOnUse"
            x="-20%" y="-20%" width="300" height="300">
      <feMorphology operator="dilate" in="SourceAlpha"
                    radius="5" result="e1" />
      <feMorphology operator="dilate" in="SourceAlpha"
                    radius="2" result="e2" />
      <feComposite in="e1" in2="e2" operator="xor"
                   result="outline"/>
      <feColorMatrix type="matrix" in="outline"
                     values="0 0 0 0 0.1
                             0 0 0 0 0.2
                             0 0 0 0 0.2
                             0 0 0 1 0" result="outline2"/>
      <feComposite in="outline2" in2="SourceGraphic"
                   operator="over" result="output"/>
    </filter>
  </defs>
  <g id="group" filter="url(#groupborder)">
    <text x="10" y="100"  stroke-width="1" fill="#1D3A56"  font-family="serif" font-size="30" font-weight="700" > Text with outline </text>
  </g>
</svg>


text:
Q: Find $\lim\limits_{x \to +\infty}\frac{f(x)}{x}.$ Suppose $f(x)$ be a periodical function defined over $\mathbb{R}$, bounded nearby $x=0$ and satisfy $\lim\limits_{x \to +\infty}[2f(x)-f(2x)]=0.$ Find $\lim\limits_{x \to +\infty}\dfrac{f(x)}{x}.$
Let $T$ be a positive period of $f(x)$. Then $2f(x)-f(2x)=2f(x+nT)-f[2(x+nT)]$, where $n=1,2,\cdots.$ Hence $\lim\limits_{n \to \infty}[2f(x)-f(2x)]=\lim\limits_{n \to \infty}\left[2f(x+nT)-f(2(x+nT))\right]=0,$ which implies $2f(x)=f(2x)$ holding for any $x\in \mathbb{R}$. Further, $f(x)=\dfrac{1}{2}f(2x)=\cdots=\dfrac{1}{2^n}f(2^nx).$ How to go on?

A: You have most of what you need:  you have deduced for all $x$
$$ f(x) = 2^{-n} f(2^n x). $$
Replace $x$ with $2^{-n}x$ and you obtain for any $x \in [0,T]$,
$$ f(x) = 2^n f(2^{-n}x ). $$
Now use the boundedness of $f$ in the neighbourhood of $x=0$.  There exists $b > 0 $ and $\delta >0$ such that $|f(x)| \leqslant b $ whenever $|x| < \delta$.  Because $f$ is periodic, we can find a fixed integer $n$ such that $0 \leqslant 2^{-n} x  < \delta$ for all $x \in [0,T]$: simply choose $n > \log (T / \delta) / \log 2$.  Then, for every $x \in [0,T]$
$$
|f(x)| = |2^n f(2^{-n}x)| \leqslant 2^n b$$
and by periodicity, it follows $f(x)$ is bounded by $2^nb$ for all $x$.  Then
$$ \left\lvert \frac{f(x)}{x} \right\rvert \leq \frac{ 2^nb}{|x|} \to 0 \quad\text{as}\quad  x \to \infty.$$


text:
Q: Move SVG element without Jquery UI I am trying to make svg element dragable with JQuery(no UI) I have found this code
jsfiddle. I wanted to create something like jsfddle2. I gues that I cant use it on svg elements like that. Any ideas how to make it ?
function endMove() {
    $(this).removeClass('movable');
}
function startMove() {
    $('.movable').on('mousemove', function(event) {
        var thisX = event.pageX - $(this).width() / 2,
            thisY = event.pageY - $(this).height() / 2;

        $('.movable').offset({
            left: thisX,
            top: thisY
        });
    });
}
$(document).ready(function() {
    $("#testedCircle").on('mousedown', function() {
        $(this).addClass('movable');
        startMove();
    }).on('mouseup', function() {
        $(this).removeClass('movable');
        endMove();
    });

});

A: Just make a container for you svg tag. here is the example

 <svg width="100" height="100" id="testedCircle">
  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
 </svg>

A: Just Enclose your SVG element with an outer div and use draggable functionality on that outer div instead of svg element. You have to ensure that outer div is having width in px equal to the SVG element is having. I have just added border to see the placement of outer div. Below I have placed complete Code:
HTML

    <svg width="100" height="100">
      <circle id="testedCircle" cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
    </svg>

Javascript
function endMove() {
    $(this).removeClass('movable');
}
function startMove() {
    $('.movable').on('mousemove', function(event) {
        var thisX = event.pageX - $(this).width() / 2,
            thisY = event.pageY - $(this).height() / 2;

        $('.movable').offset({
            left: thisX,
            top: thisY
        });
    });
}
$(document).ready(function() {
    $("#containerDiv").on('mousedown', function() {
        $(this).addClass('movable');
        startMove();
    }).on('mouseup', function() {
        $(this).removeClass('movable');
        endMove();
    });

});


text:
Q: Can a fluid approach the speed of light according to the equation of continuity? We all are well aware with the equation of continuity (I guess) which is given by:
$$A_1V_1= A_2V_2$$
Where $A_1$ and $A_2$ are any two cross sections of a pipe and $V_1$ and $V_2$ are the speeds of the fluid passing through those cross sections.

Suppose $A_1$ is $1\ m^2$ and $V_1$ is $2\ m/s$ and $A_2$ is $10^{-7}\ m^2$. This will mean that $V_2$ will be $2×10^{7}\ m/s$ which is much closer to the speed of light.
But my teacher just said it is not possible. He didn't give a reason.

Is he saying this because density of the liquid will change (given mass increases and length contracts with higher speed)?
Why can't we use this equation to push fluids to a higher speed?
If there is a limit on the maximum speed we can get to with this equation, what is it?
For simplicity of calculations, you may take water.

A: That simplified form of continuity equation assumes that the fluid is incompressible. That is only a valid assumption at low Mach numbers. I think a typical "rule of thumb" is that a Mach number less than 0.3 is required for the assumption to hold. So for the continuity equation to hold in that form requires a speed which is much less than the speed of sound which in turn is much less than the speed of light. You cannot use the continuity equation to achieve supersonic flow, let alone relativistic flow.
Note, that is not to say that supersonic flow is impossible, but rather that it is not possible simply by application of that form of the continuity equation. You need a form that accounts for compressibility. Superluminal flow is fundamentally impossible as no massive particle can reach c with finite energy.

A: You can check your hypothesis by closing the mouth of a pipe (from which water is flowing out) to different degrees. You will find that the flow velocity increases initially as the outlet area is decreased, reaches a maximum and then falls off to zero as you proceed to completely close the outlet. This is because, when the outlet area is very small, viscous forces and surface tension effects become dominant and retard the flow velocity.

A: One must look at all relevant equations when discussing what's possible or what's doable.  In this case, you must look also at the momentum equation, which is Newton's Law, and when you do, you see that the pressure required for high Mach number in fluids becomes impossible to achieve in practice.
In talking about incompressible flow, from a fundamental point of view, it's not possible to achieve even Mach 1 in an "incompressible" fluid.  The criterion by which a fluid can be considered incompressible is that the Mach number squared be much less than unity.  That means the Mach number itself should be less than about 0.3, and above that, the fluid is compressible; i.e. changes in it's density become important. Thus, one can argue that it's impossible for an incompressible fluid to have a velocity close to the speed of sound in that fluid, simply because it must experience compressibility for Mach number above about 0.3.
Also, when you go through the numbers, you will find that it takes very large pressures to accelerate say, water to high Mach number.  It's thus pure fantasy to even imagine speeds approaching the speed of light.

A: That is one version of the continuity equation for sure. But that is not the most general one. As a matter of fact, that condition can be deduced from the incompressibility of a fluid as in a limit of the Navier-Stokes equation:
$$\rho(\partial_t + v \cdot \nabla)v + \nabla p = 0,$$
where $\rho$ is the density, $p$ is the pressure and $v$ is the velocity field in the fluid, assumed to satisfy $\nabla\cdot v = 0$. But even if you take everything under consideration in this description, the formalism will allow for fluids to have a speed higher than the speed of light.
The reason for this is that even the Navier-Stokes equation is a limit of its relativistic counterpart, the conservation of the stress-energy tensor:
$$\nabla^\mu T_{\mu\nu} = 0.$$
And from this equation, it is easy to show that your fluid will not propagate faster than light under the assumption that your $T_{\mu\nu}$ is physical.

A: One thing not pointed out in the above answers is that if a fluid was truly "incompressible", it would violate special relativity.  This is because the speed of sound in a fluid can be derived from its equation of state $\rho(P,T)$ which gives the density as a function of the pressure and temperature.  Specifically, we have
$$
\frac{1}{v^2} = \left( \frac{\partial \rho}{\partial P} \right)_s,
$$
where $v$ is the speed of sound in the material and the derivative is taken while holding entropy constant. If $\rho$ were really & truly "incompressible", then it would be constant with respect to $P$, and the above derivative would vanish.  Thus, $v^2 \to \infty$, which is faster than light.[citation needed]
The resolution to this is that "incompressible" doesn't literally mean incompressible.  It just means "the range of pressures we're looking at is so small that the compression of the fluid is negligible."

A: I recieved a lot of great answers.
But I came up with an idea this morning (which I would like to share) which I would like to share (actually I need to know whether this kind of reasoning is right or not).

When Sir Isaac Newton was trying to estimate the speed of sound, he assumed that the process of transmission is isothermal stating that the molecules get enough time to be in thermal equilibrium with the surrounding. But with this he got a different (more specifically:   smaller) value for the speed of transmission.
But then came Laplace and he corrected Newton by saying that the process is too fast to be isothermal and thus the process is definitely adiabatic.

\Rightarrow So if we take the above paragraph in consideration, we can similarly come to an estimate (not a certain reason though).
If the speed of water is something like $150-200$ $m/sec$ , the molecules have some time to interact with its surrounding and so the pressure inside the tube doesn't drop much. But as it approaches the speed of sound or any higher speed, the molecules have very less time to interact and the pressure on the walls of the tube decreases to a great extent and thus this situation becomes similar to that of an imploding can.

We can't even exceed the speed of sound with this equation. So thinking to reach the speed of light with this equation is completely stupid .


text:
Q: Get value from Javascript to Input type Hidden I am just trying to add code in this javascript to get values of slide to input type="hidden", but i can't get value into input type="hidden", what do I do wrong? Anyway, thanks for your help!
This is javascript code:
// <![CDATA[
var hWidth, bWidth;

function setBgPos(v) {
    var off = v * hWidth;
    var pos = -bWidth + (v * bWidth);
    $('slider').setStyle({backgroundPosition: Math.round(pos - off) + 'px'});
}

function setSlideOutput(v) {
    $('percent').innerHTML = Math.round(v * 100) + '%';
}

Event.observe(window, 'load', function() {
    hWidth = $('slider-handle').getWidth();
    bWidth = $('slider-bar').getWidth();
    var slide = new Control.Slider('slider-handle', 'slider-bar', {
        sliderValue: 0.25,
        onSlide:
            function(v) {
                setBgPos(v);
                setSlideOutput(v);
                $('percentage').value = Math.round(v * 100) + '%';
            },
        onChange:
            function(v) {
                setBgPos(v);
                setSlideOutput(v);
                $('percentage').value = Math.round(v * 100) + '%';
            }
    });
    setBgPos(slide.value);
    setSlideOutput(slide.value);
});
// ]]>

Html:
    <!DOCTYPE html>

    <input type="hidden" id="percentage" name="percentage" value="0" />

A: you should use $('#percentage') instead of $('percentage')

A: Try using  $('#percentage')[0].value
What you need is DOM element, not jquery object.
Or, alternatively, use $('#percentage').val('')

A: UPDATE: Solved to add setvalue, this did help me: http://www.ruby-forum.com/topic/143329 . Thanks for all the tips guys and more thanks for Geek Num 88!


text:
Q: How to restart audio in React Component using Hooks I'm trying make a soundboard using React. I've pulled some code from other stack overflow answers but what I can't get to work is to have the audio restart when triggered again during playback. Instead it just continues to play to the end.
Here is my current code:
import React, { useState, useEffect } from 'react'
import styled from 'styled-components'

const Button = (props) => {

    const useAudio = url => {
        const [audio] = useState(new Audio(url));
        const [playing, setPlaying] = useState(false);

        const toggleSound = () => setPlaying(!playing);

        useEffect(() => {
                playing ? audio.play() : audio.pause();
            },
            [playing]
        );

        useEffect(() => {
            audio.addEventListener('ended', () => setPlaying(false));
            return () => {
                audio.removeEventListener('ended', () => setPlaying(false));
            };
        }, []);

        return [playing, toggleSound];
    };

    useEffect(() => {
        function handleClick(e) {
            if(e.key === props.trigger){
                toggleSound();
            }
        }

        window.addEventListener('keydown', handleClick);

        return () => {
            window.removeEventListener('keydown', handleClick);
        };
    }, []);

    const [playing, toggleSound] = useAudio(`./sounds/${props.audio}`);

    return (
        <ButtonWrapper playing={playing} onClick={toggleSound}>
            {props.children} - {props.trigger.toUpperCase()}
        </ButtonWrapper>
    )
}

export default Button;

const ButtonWrapper = styled.button`
    background: ${props => props.playing ? 'red' : 'white'};
    border: none;
    font-size: 20px;
`

A: Did you try to use .load() method?
The reference says that .load() reloads the element https://www.w3schools.com/tags/av_met_load.asp


text:
Q: How to delete the matching pattern from given occurrence I'm trying to delete matching patterns, starting from the second occurrence, using sed or awk. The input file contains the information below:
abc
def
abc
ghi
jkl
abc
xyz
abc

I want to the delete the pattern abc from the second instance. The output should be as below:
abc
def
ghi
jkl
xyz

A: Neat sed solution:
sed '/abc/{2,$d}' test.txt
abc
def
ghi
jkl
xyz

A: $ awk '$0=="abc"{c[$0]++} c[$0]<2; ' file
abc
def
ghi
jkl
xyz

Just change the "2" to "3" or whatever number you want to keep the first N occurrences instead of just the first 1.

A: One way using awk:
$ awk 'f&&$0==p{next}$0==p{f=1}1' p="abc" file
abc
def
ghi
jkl
xyz

Just set p to pattern that you only want the first instance of printing:

A: Taken from : unix.com
Using awk '!x[$0]++' will remove duplicate lines. x is a array and it's initialized to 0.the index of x is $0,if $0 is first time meet,then plus 1 to the value of x[$0],x[$0] now is 1.As ++ here is "suffix ++",0 is returned and then be added.So !x[$0] is true,the $0 is printed by default.if $0 appears more than once,! x[$0] will be false so won't print $0.


text:
Q: como hacer un Update a partir de 3 o 4 columnas con valores distintos en cada columna Hola a todos espero me puedan ayudar... estoy tratando de generar una consulta la cual tiene las siguientes columnas empresa ARTICULO, SUBCUENTA, ALMACEN las cuales me estableceran una zona de 6 zonas en total si hago la consulta estableciendo el almacen, el articulo, la subcuenta me da una zona la pregunta es como hacer un update que me indentifique de varios articulos, varias empresas, subcuentas y almacenes para que me quite los nulos y me establezca las zonas respectivamente asi como en la siguiente imagen, comparto el query
select * from ArtAlm where almacen='99'
--and empresa='GD3'
and articulo='03110' and subcuenta='c3'

...
espero me puedan ayudar, estare al pendiente de sus comentarios.  saludos!!
comparto dos consultas en las que asi extraigo las zonas
select * from ArtAlm where almacen='99'
and articulo='07151' and subcuenta='c3' and almacen='99'  ----esta es zona2
select * from ArtAlm where almacen='99'
and articulo='00038' and subcuenta=''    ---- esta es zona 3

A: Para poder actualizar los registros que contienen un valor NULL en el campo Localizacion a partir del valor que tienen el resto de valores de la tabla con los mismos datos de Articulo, Subalmacen y Almacen se puede hacer una unión de tablas como sigue:
UPDATE ArtAlm
SET ArtAlm.Localizacion = destino.Localizacion
From ArtAlm
LEFT JOIN ArtAlm destino
ON ArtAlm.almacen = destino.almacen
    AND ArtAlm.empresa = destino.empresa
    AND ArtAlm.articulo = destino.articulo
    AND ArtAlm.subcuenta = destino.subcuenta
    AND destino.Localizacion IS NOT NULL
WHERE ArtAlm.Localizacion IS NULL

La explicación es la siguiente:

*

*Buscamos todos los elementos cuyo campo Localizacion sea nulo.

*Realizamos una unión de la tabla ArtAlm consigo misma en la que los campos coincidan pero que el campo Localizacion esté definido (no sea NULL).

*Realizamos la asignación del valor de Localizacion en el registro en el que vale NULL del obtenido del otro registro similar pero que no es nulo.


text:
Q: no entiendo la respuesta que obtengo en la terminal en la terminal de VScode estoy colocando "git add -A" para guardar los cambios porque voy a subirlo a github, pero la respuesta que me da luego de ejecutarlo es "fatal: not a git repository (or any of the parent directories)"
sabrán porque me da esa respuesta?, tienen idea de que estaré haciendo mal?

A: eso es porque no has inicializado el git en ese directorio... coloca primero git init
para inicializarlo, esto creará el directorio oculto .git


text:
Q: Handle iPhone calling from external device (e.g. a car) How does a car's system handle calls from an iPhone? The device is plugged through into the car's system using the dock connector at the bottom of the iPhone. Now when a call comes through the car intercepts it and you can press a button (usually on the steering wheel) to answer and then speak through the inbuilt microphones of the car and listen through the speakers in the car. All of this is done through connecting the device into a dock.... how does this work?
P.S: Is it possible to initiate calls from an outside system as well?
P.P.S: All of this is done without an App being installed on the iPhone itself though...

A: Any bluetooth devices that implement HFP or HSP bluetooth profiles will be able to receive the call from iPhone.To display the info( Caller ID or Contact name) on the car kit, the device has to implement PBAP or MAP bluetooth profiles.No App is required on iPhone.


text:
Q: How to check if mysql_query returned anything or not
Possible Duplicate:
mysql_fetch_array() expects parameter 1 to be resource, boolean given in select

So I am trying to check if the following query returns any result or not
  $numUsersSameRatingQuery="SELECT * `user ratings` WHERE  category='$category' AND categoryId='$categoryId' AND  `userAromaRating`>0 ";

  $result=mysql_query($numUsersSameRatingQuery);

   $numResults=mysql_num_rows($result);

  if($numResults==0)
  {
   // do the INSERT INTO
  }
  else
  {
   //do the UPDATE SET
  }

However, the above returns the following error and the if($numResults) is executed anyway each time. In other words, I can never get the else block to run.
Here is the error
 Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\boozeDb\profileThis.php on line 141

Helps are appreciated.

A: You could use is_resource to make sure that it's a resource. You could alternatively use an if statement to make sure that FALSE wasn't returned.
To display the error, use mysql_error.
Example:
<?php

// From http://ca2.php.net/manual/en/function.mysql-query.php

$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
    trigger_error('Invalid query: ' . mysql_error());
}

A: mysql_query() either returns a statement handle (query succeeded) or a boolean FALSE (query failed). Your code does not check for error conditions and blindly assumes success. Modify the code to look like this:
$result=mysql_query($numUsersSameRatingQuery) or trigger_error(mysql_error());
                                             ^^^^^^^^^^^^^^^^^^^^^^--- add this

Given your sample query, you're missing the FROM keyword, and should probably be:
SELECT * FROM `user ratings`
        ^^^^^^

I would STRONGLY urge you to NOT use fieldnames that contain spaces. They're nothing but trouble.

A: Just like everyone else has commented, an if statement or an "or die()" could help not generating that error again, while the error probably comes from the missing "FROM" in your query.
I just felt the need to comment the fact that you're now making TWO queries to prevent some or all columns in the table from being duplicates: a SELECT and an INSERT. This could be done in ONE query and would speed up your code:
INSERT ..(what you want to insert).. ON DUPLICATE KEY UPDATE ..(what to update if it already exists)..
for more info here's MySQLs manual page about it.


text:
Q: Code Sign Using Electron-Builder on Windows I'm having trouble getting code-signing to work on Windows.  I have the following in package.json:
"distwin": "ionic-app-scripts build && set CSC_LINK=C:\\Data\\Development\\Projects\\DocsOnTapV2\\build\\dotv2codesign.pfx && set CSC_KEY_PASSWORD=NotTelling && build"

But when I run this I always get the following error:
Error: C:\Data\Development\Projects\DocsOnTapV2\build\dotv2codesign.pfx  doesn't exist
    at C:\Data\Development\Projects\DocsOnTapV2\node_modules\electron-builder\src\codeSign.ts:45:11
    at next (native)
    at runCallback (timers.js:651:20)
    at tryOnImmediate (timers.js:624:5)
    at processImmediate [as _immediateCallback] (timers.js:596:5)
From previous event:
    at downloadCertificate (C:\Data\Development\Projects\DocsOnTapV2\node_modules\electron-builder\out\codeSign.js:49:21)
    at Lazy.WinPackager.cscInfo.Lazy (C:\Data\Development\Projects\DocsOnTapV2\node_modules\electron-builder\src\winPackager.ts:42:9)
    at Lazy.get value [as value] (C:\Data\Development\Projects\DocsOnTapV2\node_modules\electron-builder-util\src\util.ts:248:24)
    at C:\Data\Development\Projects\DocsOnTapV2\node_modules\electron-builder\src\winPackager.ts:168:32
    at next (native)

It is telling me that the 'pfx' file does not exist.  But it does!  I've tried all sorts of variations for the CSC_LINK variable with no success. What do I need to do to enable electron-builder to find the 'pfx' file?


text:
Q: Novels Have Parts x Chapters x Subchapters? Sections? I searched for this one and didn't quite got what I needed. I've found that Books have chapters, and then there are mentions of sections, but none seem to be mentioning this in novels, more like academic books.
In Stephen King books I've read, there's always a chapter, then a 1 with a short text, then a 2, short text, and so on, until the chapter ends, another one starts, and it's the same thing.
Are those 1, 2, 3 etc. called Sections? Subchapters?
On the same note, why there is no indentation at the beggining of the first paragraph after those? Is the 1 considered to be the actual begining of the first paragraph or something?
(Sometimes there are Parts, then Chapters, then whatever the other one is called)

A: In most cases, novels are divided into chapters and there are no other divisions. A chapter can have only a number, or it might also have a title, as in the case you have presented.
When the word part is used, it typically refers to groups of chapters, and a novel will have only a few parts.
I think I have never seen the word section used within a novel itself, but it is frequently used by people who discuss novels in the way you have described—to identify the parts into which a chapter has been divided. Sections are not always numbered, but they can be. In some cases, they also have a title or a label of some kind.
It is common for the first line of a chapter or a section not to be indented. The choice is usually made by the person who designs the appearance of the book. It is not an editorial decision and follows no standard rule.


text:
Q: Class inheritance best practices in terms of properties and sql related methods #region Properties
public int ID
{
    get;
    set;
}
public string Name
{
    get;
    set;
}
public string MetaTitle
{
    get;
    set;
}
public string MetaDescription
{
    get;
    set;
}
public virtual int WebsiteID
{
    get;
    set;
}
public DateTime TimeStamp
{
    get;
    set;
}
#endregion Properties

#region Methods
public void Insert()
{
    string sqlString = "INSERT INTO Pages ([name], [value], [meta_title], [meta_description], [website_id]) " +
        "VALUES (@Name, @Image, @Description, @MetaTitle, @MetaDescription, @WebsiteID);";
    SqlConnection sqlConnection =
        new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    using (SqlCommand sqlCommand = new SqlCommand(sqlString, sqlConnection))
    {
        sqlCommand.Parameters.AddWithValue("@Name", this.Name);
        sqlCommand.Parameters.AddWithValue("@Image", this.Image);
        sqlCommand.Parameters.AddWithValue("@Description", this.Description);
        sqlCommand.Parameters.AddWithValue("@MetaTitle", this.MetaTitle);
        sqlCommand.Parameters.AddWithValue("@MetaDescription", this.MetaDescription);
        sqlCommand.Parameters.AddWithValue("@WebsiteID", this.WebsiteID);
        try
        {
            sqlConnection.Open();
            sqlCommand.ExecuteNonQuery();
            sqlConnection.Close();
            sqlConnection.Dispose();
        }
        catch (SqlException e)
        {
        }
    }
}

Two questions:
I have another class called Section which will derive from the class above called Page. However, Section will not have a WebsiteID but will have a PageID instead. They're both integers but how do I go about changing the property name is the derived class.
The second thing is, should I override the Insert() method to use another sqlString? If not, what is the best way of implementing such requirements?
Thanks in advance.

A: I have another class called Section which will derive from the class
above called Page. However, Section will not have a WebsiteID but will
have a PageID instead. They're both integers but how do I go about
changing the property name is the derived class.
The mistake is that your page contains section object so you don't have to derive Section from Page: Page must have a collection of section
class Page
{
     private Section[] sections;
     public Section[] Sections {get;set;}
}

A: I think your inheritance might be a bit off. A "section" is NOT a "page", or is it?
Why not have a base class, called Content or something like that, with the properties:
public int ID { get; set; }
public string Name { get; set; }
public string MetaTitle { get; set; }
public string MetaDescription { get; set; }
public DateTime TimeStamp { get; set; }

And have Page extend it adding the WebsiteID and Section adding the PageID.
But I would also recommend separating the entity model from the data access. Using something like Entity Framework or NHibernate to handle persistence for you would save you from having to write that code manually.
That way you could have a more connected model, where Section actually references a Page entity, and not handle IDs manually. Also Page could contain Sections in the same manner (like a List<Section>), and you'd possibly have a cleaner model.


text:
Q: .NET Binary XML How does .NET's Binary XML work?
There's some documentation on it at http://msdn.microsoft.com/en-us/library/cc219210.aspx, but it doesn't say how to make it. There isn't even an example of the output. I'm guessing anything related to binary xml would be in System.Xml, but I can't find anything.
Also, my searches for binary xml have led me to XmlDictionaryWriter, which apparently can write "binary XML format", but it doesn't even exist in System.Xml!
My goal is to possibly serialize my data in binary xml (right now I'm using XmlSerializer, which writes standard, human-readable xml).
Can anyone give me an example of how to serialize to binary xml or even just write binary xml?

A: XmlDictionaryWriter is in System.Runtime.Serialization which you need to add as a reference first.


text:
Q: AngularJS factory return no data first time, but after called interval method it does Im trying to make a AngularJS factory that provides my app with a list of businesses. But i cant seem to get the variable the first time this is run. But after interval is run, i get the variable.
I get this on the first run on the controller in the page:

angular.js:12783 Error: [$injector:undef] Provider 'businessList' must return a value from $get factory method

But I think my solution is faulty, any how? Can anyone point me in the right direction here? For example is using rootScope here a good idea?
What I want is a globally accessible list of businesses in my app, that is collected on start of visit, and updates itself with a timer. So i dont have to all the time call for induvidial requests from the laravel backend, when i can just find it in that list.. is my idea.
Factory:
myApp.factory('businessList', ['$interval', '$http', '$rootScope',
    function($interval, $http, $rootScope) {
      function bedriftliste() {
        $http.get('get/allebedrifter')
            .then(function(result) {
                bedrifter = result.data;
                $rootScope.bedrifter = bedrifter;
            });
        return $rootScope.bedrifter;
    }
    var bedrifter = bedriftliste();
    // start periodic checking
    $interval(bedriftliste, 5000);
    return bedrifter;
}
]);

Controller
myApp.controller('bsC', ['$rootScope', '$scope', 'businessList',
                    function($rootScope, $scope, businessList) {
    $scope.allebedrifter = businessList;
}]);`

A: I solved this by just doing a http.get if object was null.
        if (!$rootScope.allebedrifter) {
        $http.get('get/bedrift/' + $scope.tslug)
            .then(function(result) {
                bedriften = result.data;
                $scope.bedriften = bedriften;
       });

Seems to work fine like this

A: Although I am late in pointing out but that doesn't seem to be a proper solution to this problem. You need to make these changes in factory:
myApp.factory('businessList', ['$interval', '$http', '$rootScope',
function($interval, $http, $rootScope) {
  function bedriftliste() {
    return $http.get('get/allebedrifter');
}

}
]);
and in the controller you'll do something like this:
myApp.controller('bsC', ['$rootScope', '$scope', 'businessList', function($rootScope, $scope, businessList) {
                    function TestFunction(){
     businessList.bedriftliste().then(function successCallback(response) {
        $scope.allebedrifter = response.data;
//it will invoke 5 seconds after you receive the response from your factory method, I didn't test it but it will solve your problem
        $interval(TestFunction, 5000);
    }, function errorCallback(response) {
    });
}

}]);