text:
Q: Load JQuery file dynamically and execute it I have to load JQuery script dynamically beacause the script is sometimes charged and sometimes it doesn't. After that, I have to execute a JQuery function. I have tried but it doesn't work. Can you help me? This is my code:
<script>
    var script   = document.createElement("script");`
    script.type  = "text/javascript";
    script.src   = "http://code.jquery.com/jquery-1.7.1.min.js";
    script.text  = "alert('voila!');"
    document.body.appendChild(script);
    $(document).ready(function() {
    getNumRecommendations("http://localhost:8080/elAbogado/","3974");});
</script>

A: Try this:
function loadScript(url, callback)
{
    // adding the script tag to the head as suggested before
   var head = document.getElementsByTagName('head')[0];
   var script = document.createElement('script');
   script.type = 'text/javascript';
   script.src = url;

   // then bind the event to the callback function
   // there are several events for cross browser compatibility
   script.onreadystatechange = callback;
   script.onload = callback;

   // fire the loading
   head.appendChild(script);
}

And then just: loadScript("http://code.jquery.com/jquery-1.7.1.min.js", myCode);
Source: How do I include a JavaScript file in another JavaScript file?


text:
Q: Replace multiple newlines with just 2 newlines using unix utilities I have tried to look for the correct way to implement this, reading from stdin and printing to stdout. I know that I can use squeeze (-s) to delete multiple lines of the same type, but I want to leave two newlines in the place of many, not just one. I have looked into using uniq as well, but am unsure of how to. I know that fold can also be used, but I cannot find any information on the fold version I want, fold (1p).
So, if I have the text as input:
    A B C D

    B C D E

I would want the output to instead be
    A B C D

    B C D E

A: You can use awk like this:
awk 'BEGIN{RS="";ORS="\n\n"}1' file

RS is the input record separator, ORS is the output record separator.
From the awk manual:

If RS is null, then records are separated by sequences consisting of a newline plus one or more blank lines

That means that the above command splits the input text by two or more blank lines and concatenates them again with exactly two newlines.

A: Following awk may help you on same.
awk -v lines=$(wc -l < Input_file) 'FNR!=lines && NF{print $0 ORS ORS;next} NF' Input_file

OR
awk -v lines=$(wc -l < Input_file) 'FNR!=lines && NF{$0=$0 ORS ORS} NF' Input_file

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sorting an array of array in PHP Request your help on sorting an array of array in PHP as below, tried all these function ksort, usort, arsort, krsort nothing seem to be working, any help would be much appreciated.
Original Array
Array
(
    [serv1-DB] => Array
        (
            [2019-11-22] => 0
            [2019-11-23] => 0
            [2019-11-24] => 0
            [2019-11-25] => 1
            [2019-11-26] => 3
            [2019-11-27] => 3
            [2019-11-28] => 3
            [2019-11-29] => 3
        )

    [ser2-DB] => Array
        (
            [2019-11-25] => 0
            [2019-11-24] => 0
            [2019-11-22] => 0
            [2019-11-23] => 0
            [2019-11-26] => 3
            [2019-11-27] => 3
            [2019-11-28] => 3
            [2019-11-29] => 3
        )

Output Required
Array
(
    [serv1-DB] => Array
        (
            [2019-11-29] => 3
            [2019-11-28] => 3
            [2019-11-27] => 3
            [2019-11-26] => 3
            [2019-11-25] => 1
            [2019-11-24] => 0
            [2019-11-23] => 0
            [2019-11-22] => 0

        )

    [ser2-DB] => Array
        (
            [2019-11-29] => 3
            [2019-11-28] => 3
            [2019-11-27] => 3
            [2019-11-26] => 3
            [2019-11-25] => 0
            [2019-11-24] => 0
            [2019-11-23] => 0
            [2019-11-22] => 0

        )

A: You want to sort the sub arrays, so you need to loop over each of them (in write mode) and sort the keys in reverse order using krsort:
foreach ($array as &$subArray) {
  krsort($subArray);
}

Demo: https://3v4l.org/g8pBu

A: You have to sort reversely on the arrays like this:
// The arrays
$arrays = array(
    "serv1-DB" => array(
        "2019-11-22" => 0,
        "2019-11-23" => 0,
        "2019-11-24" => 0,
        "2019-11-25" => 1,
        "2019-11-26" => 3,
        "2019-11-27" => 3,
        "2019-11-28" => 3,
        "2019-11-29" => 3
    ),
    "ser2-DB" => array(
        "2019-11-25" => 0,
        "2019-11-24" => 0,
        "2019-11-22" => 0,
        "2019-11-23" => 0,
        "2019-11-26" => 3,
        "2019-11-27" => 3,
        "2019-11-28" => 3,
        "2019-11-29" => 3
    )
);

// The sorting part
foreach($arrays AS $k => $array) {
    krsort($array);
    $arrays[$k] = $array;
}


text:
Q: How to programatically enable System Restore monitoring for a drive? I found a code that enables System Restore monitoring, but it's for C# and I need to convert it to Delphi. Here's the code:
ManagementScope scope = new ManagementScope("\\\\localhost\\root\\default");
ManagementPath path = new ManagementPath("SystemRestore");
ObjectGetOptions options = new ObjectGetOptions();
ManagementClass process = new ManagementClass(scope, path, options);
ManagementBaseObject inParams = process.GetMethodParameters("Enable");
inParams["WaitTillEnabled"] = true;
inParams["Drive"] = osDrive;
ManagementBaseObject outParams = process.InvokeMethod("Enable", inParams, null);

Could anyone help me to convert the above code to Delphi ?

A: The following function returns True if the System Restore monitoring of a specified drive has been enabled, False otherwise. As the input ADrive parameter specify the full drive path to be monitored. When this parameter is the system drive, or an empty string, all drives will be monitored. This function does not wait for monitoring to be enabled completely before it returns. Instead, it returns immediately after starting the System Restore service and filter driver:
function EnableSystemRestore(const ADrive: string): Boolean;
var
  WbemObject: OleVariant;
  WbemService: OleVariant;
  WbemLocator: OleVariant;
begin;
  Result := False;
  try
    WbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
    WbemService := WbemLocator.ConnectServer('localhost', 'root\DEFAULT');
    WbemObject := WbemService.Get('SystemRestore');
    Result := WbemObject.Enable(ADrive) = S_OK;
  except
    on E: EOleException do
      ShowMessage(Format('EOleException %s %x', [E.Message, E.ErrorCode]));
    on E: Exception do
      ShowMessage(E.Classname + ':' + E.Message);
  end;
end;

And the usage:
procedure TForm1.Button1Click(Sender: TObject);
begin;
  if not EnableSystemRestore('D:\') then
    ShowMessage('Failed!')
  else
    ShowMessage('Succeeded!');
end;


text:
Q: Persisting data on android studio Is it possible to persist the state of a page in android studio? For example, I have a click counter and I want to persist the value of the counter so that I can restore it when I re-open the app. Currently, the counter value disappears after closing the app.

A: use SharedPreferences
More info: http://developer.android.com/reference/android/content/SharedPreferences.html

A: This may help you when saving values.
Android saving data


text:
Q: create an instance of class on stack I'm a beginner in C#, just some questions, lets say we have a class 'Person',
I know when we do like:
Person p = new Person();

we create a p object on the heap, and p will be garbage collected.
so my questions are:
Q1- If I want to create an instance of class on stack by avoiding the 'new' keyword, should I do like(I know by declaring Person as Struct will do the same job,but I just want the class to behave in the same way):
Person p = Person();

Q2- when I just do:
Person p;

was the default constructor invoked? or default constructor was not invoked, just a piece of stack memory is allocated?

A: Q1:
Attempting to initialize an object without usage of the new keyword will result in a compile-time error. So, the answer is no.
Q2:
No constructor is invoked when you fail to initialize an object. Space is allocated and set to NULL. So in this case, p would be treated as NULL.
Additional Info
You can make Person a struct. Structs are treated as value types in C#, so they will be allocated on the Stack. However, if you have members inside your struct that are reference types, they will still be allocated on the Heap.
When you allocate space for an object, you are able to reference it within its scope. Even though the memory referenced is located on the heap, the reference itself is located on the stack. So, once the GC realizes that no reference is pointing to a chunk of memory on the heap, it's freed up.
I do not believe it's possible to allocate space for a reference type on the Stack in C#. If you want to achieve this, try working with an unmanaged runtime.


text:
Q: How to perform Group by Average opreation using DAX in power BI? I have a sample dataset as below in power BI.

I want to first group by DeliveryMonth and sum the column Item and then group by Period and take average of column Item. If I directly use average in aggregation it is getting average of whole column. instead I just want average of filtered grouped data by category. my desired output should be as shown below.

Current Average aggregation shows this in power bi.

I have tried creating DAX measure using different formulas but did not quite get it. Is there anyway I can get this working? I would really appreciate any help on this. Thanks.

A: I have replicated your model, the following calculation should work.
In essence, is grouping the values using SUMMARIZE under the desired granularity.
I couldn't match the number 4391.7, I don't know if that's an error.
Calculation: Measure
Avg. Item Sum =
    AVERAGEX(
        SUMMARIZE('Table','Table'[Category],'Table'[DeliveryMonth],'Table'[Period]),
        CALCULATE(sum('Table'[Item]))
        )

Output

Category
Period
Avg. Item Sum

A
Sum20
1497.23

B
Sum20
525.1

A
Fal20
1473.1

B
Fal20
440.9

A
Win20
1102.2

B
Win20
1116.3

A
Spr21
780.3

B
Spr21
567.1

For future reference, the original table as markdown

Category
DeliveryMonth
Item
Period

A
06 January 2020
963.9
Sum20

A
06 January 2020
500
Sum20

A
06 January 2020
100
Sum20

A
07 January 2020
963.9
Sum20

A
07 January 2020
400
Sum20

A
07 January 2020
200
Sum20

A
08 January 2020
963.9
Sum20

A
08 January 2020
100
Sum20

A
08 January 2020
300
Sum20

A
09 January 2020
1473.1
Fal20

A
10 January 2020
1473.1
Fal20

A
11 January 2020
1473.1
Fal20

A
12 January 2020
1102.2
Win20

A
01 January 2021
1102.2
Win20

A
02 January 2021
1102.2
Win20

A
03 January 2021
780.3
Spr21

A
04 January 2021
780.3
Spr21

A
05 January 2021
780.3
Spr21

B
06 January 2020
525.1
Sum20

B
07 January 2020
525.1
Sum20

B
08 January 2020
525.1
Sum20

B
09 January 2020
440.9
Fal20

B
10 January 2020
440.9
Fal20

B
11 January 2020
440.9
Fal20

B
12 January 2020
1116.3
Win20

B
01 January 2021
1116.3
Win20

B
02 January 2021
1116.3
Win20

B
03 January 2021
567.1
Spr21


text:
Q: javascript Error - for loop I wrote a this simple code in js.
    var n=10;
    for (i=1;i=n;i++){
    console.log('avinsyh');
     }

But the loop executes greater than 2000 and crashing the browser.Why this is happening so?
Note: If I  Execute this:
 var n=10;
    for (i=1;i<n;i++){
    console.log('avinsyh');
     }

Then the javascritpt outputs the correct results

A: It's the assignment in the comparison part of the for loop, which makes an infinite loop. i becomes always n and evaluates to true.
for (i = 1; i = n; i++){
//          ^^^^^

var n = 10,
    i;

for (i = 1; i <= n; i++){
    document.write('i: ' + i + '<br>');
}

A: in your first  for loop , i=n will set i equal to the value of n and thus return a truthy value(as n is not 0) and you get a infinite loop.

A: In your for loop you are assinging the value i = n which is always true and hence results in infinite loop.

The condition expression is evaluated. If the value of condition is
  true, the loop statements execute. If the value of condition is false,
  the for loop terminates. If the condition expression is omitted
  entirely, the condition is assumed to be true.

In your second case you are comparing the value of i on each iteration and hence you are getting the expected result.
The basic syntax of for loop is:
for ([initialExpression]; [condition]; [incrementExpression])
 statement

So in your first case you are not providing the [condition] rather it is an assignment.


text:
Q: Node voltage equation with weird solutions I recently had an exam with the following multiple choice problem:

Consider the circuit below:

The node voltage equation for node A is which of the following?:

*

*\$ \frac{V_A-kV_a}{R_1}+ \frac{V_A-V_3}{R_2} + \frac{V_A-V_B}{R_6} = 0 \$

*\$ \frac{V_A+kV_A}{R_1} + \frac{V_A-V_3}{R_2} + \frac{V_A-V_B}{R_6} = 0 \$

*\$ \frac{V_A-kV_A}{R_1} + \frac{V_A+V_3}{R_2} + \frac{V_A+V_B}{R_6} = 0 \$

*\$ \frac{V_A+kV_A}{R_1} + \frac{V_A+V_3}{R_2} + \frac{V_A+V_B}{R_6} = 0 \$

*\$ \frac{2V_A}{R_1} + \frac{V_A+V_3}{R_2} + \frac{V_A+V_B}{R_6} = 0\$

*\$ \frac{V_A-V_3}{R_2} + \frac{V_A-V_B}{R_6} = 0\$

My attempt
This is how I would make the node voltage equation for node A:
\$ \frac{V_A}{R_1} + \frac{V_A-V_3}{R_2} + \frac{V_A-V_B}{R_6} + ki_1 = 0 \$
But as you can see, it doesn't match any of the options above and I can't figure out how I'm supposed to reach on of those solutions.
Can somebody help me out?

A: A tricky case.
V3=(I1-I2)R3. Va=-(I1)R1. With these you can fade the controlled current source from your equation.


text:
Q: Сохранение позиции Player в 2d раннере юнити c# В игре, меню паузы реализовано через отдельную сцену (я знаю что я идиот), но на поздней стадии уже не хочется переделывать все сначала. Так вот, мне надо чтобы позиция игрока сохранилась при переходе с меню паузы на саму игру. Сейчас позиция сохраняется только при выходе из игры
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class SaveXYZ : MonoBehaviour

{
public Scene Scene;
void Start()
{
if (PlayerPrefs.HasKey("PosX") && PlayerPrefs.HasKey("PosY") && PlayerPrefs.HasKey("PosZ"))
{
transform.position = new Vector3(PlayerPrefs.GetFloat("PosX"), PlayerPrefs.GetFloat("PosY"), PlayerPrefs.GetFloat("PosZ"));
}
}

private void OnApplicationQuit()
{
PlayerPrefs.SetFloat("PosX", transform.position.x);
PlayerPrefs.SetFloat("PosY", transform.position.y);
PlayerPrefs.SetFloat("PosZ", transform.position.z);
}

}


text:
Q: Firefox 3.6 update breaks selenium I'm unable to run any selenium tests since I updated Firefox to 3.6. Is it happening just to me or is it everybody?
Error message I get is: Could not start Selenium session: Failed to start browser session
This is in Windows Xp.

A: Ok. Found the problem. My Netbeans was using version 1.0.1 which did not support 3.6.
This fixed it: http://geekswithblogs.net/thomasweller/archive/2010/02/14/making-selenium-1.0.1-work-with-firefox-3.6.aspx

A: You can also try the extension "Nightly Test Tool" before a extension officially supports a new released version.

A: Selenium 1.0.3 was updated to work with Firefox 3.6 so suggest updating your version instead of going in and hacking the jar file.
You can get the latest version from http://code.google.com/p/selenium/downloads/list


text:
Q: Convert Numpy Array with float to integer I have a numpy array:
array([ 6., 13., 10.,  9.,  5.,  4.,  4.,  4.,  3.,  5.,  4., 20.,  6.,
       14.,  8.,  6.,  3.,  3.,  3.,  2.,  2.,  5.,  6., 11., 11., 11.,
        9.,  3.,  3.,  3.,  2.,  3.,  2.,  3.,  6., 11., 15., 12.,  5.,
        3.,  3.,  5.,  2.,  2.,  2.,  2.,  3.,  4.,  7.,  2.,  8.,  2.,
        3.,  2.,  1.,  3.,  1.,  1.,  5.,  5.,  4.,  2.,  5.,  2.,  3.,
        2.,  2.,  2.,  1.,  2.,  4., 11.,  5.,  4.,  3.,  4.,  3.,  3.,
        3.,  4.,  3.,  4.,  2.,  6.,  6.,  3.,  3.,  2.,  3.,  4.,  2.,
        3.,  2.,  4.,  2.,  5.,  4.,  3.,  2.,  2.,  3.,  2.,  2.,  2.,
        2.,  3.,  3.], dtype=float32)

...but I want to make it contain integers instead of floats. Can you help me to solve this?

A: You can Numpy's built in method, astype:
a = np.ones((3,3))
print(a.dtype) #defaults to float64

a = a.astype(int) #changes to int

A: import numpy as np

arr = np.array([6., 13., 10., 9., 5., 4., 4., 4., 3., 5., 4., 20., 6.,1])
int_arr = arr.astype(np.int64)


text:
Q: Passing parameter to javascript onclick without using HTML I can't figure this out. I'm trying to create an onclick handler purely in Javascript.
What I plan to do here is inside this DIV, have a collection of items that I can click on. For now, these items will be numbers from 0 to 9 inclusive. When a number is clicked on, a system message consisting solely of that number should pop-up on the screen. I narrowed my problem down to just the onclick handler definition.
If I use this format:
    item[n].onclick=function(n){
       handler(n);
    }

The handler will fire only when click a number which is correct, but the message that appears is something about mouse event.
If I use this format:
    item[n].onclick=function(){
       handler(n);
    }

The handler will pass a value of -1 which in turn is printed as a message. I think it means "false".
How do I modify this:
    item[n].onclick=function(){
       handler(n);
    }

so that 'n' being used as the handler parameter is the same as the number I click on the screen?
My code is the following:

function handler(n){
    alert(n);
}

collections=document.getElementById('Itemset');
for(n=0;n<10;n++){
    item[n]=document.createElement('DIV');
    item[n].innerHTML=n;
    collections.appendChild(item[n]);
    item[n].onclick=function(n){
       handler(n);
    }
}

What I'm effectively trying to do if you want to understand it HTML wise is this:

0

1

2

3

4

5

6

7

8

9

Except that I don't want to write out onclick="handler(n);" a million times.
Any advice? and feel free to point to another resource that has the answer I need if there is one.
UPDATE
I'm looking for something compatible with older browsers as well. I'm going to have to not go for the bind function because according to mozilla docs, it works for IE 9+. I'm looking for something that works for IE 7+ as well as other browsers. I might have to go for event listeners if there is no other alternative.

A: You have a closure issue here (see JavaScript closure inside loops – simple practical example), a simple solution is to use bind to use the current value of n to be a parameter of the handler function
item[n].onclick=handler.bind(item[n],n);

A: U can use  addEventListener and ID for find clicked element...
 document.getElementById("Itemset").addEventListener("click", function(e) {
        // e.target is the clicked element!
        // If it was a list item
        var value_data = parseInt(e.target.textContent);
        if(e.target && value_data > -1) {
            alert("Malai test:: "+value_data);
                        //handler(value_data);
        }
    });

https://jsfiddle.net/malai/tydfx0az/

A: I found my answer here: https://bytes.com/topic/javascript/answers/652914-how-pass-parameter-using-dom-onclick-function-event
Instead of:
item[n].onclick=function(n){
   handler(n);
}

I have to do:
item[n].onclick=new Function('handler('+n+')');

Funny thing is, the word function needs to be capitalized when making a new instance. It's awkward I have to go this route but it works in IE 7+

A: One alternative is :
function handler(){
    alert(this.id);
}
function myFunction() {

    var item=[];

    collections=document.getElementById('Itemset');
    for(n=0;n<10;n++){
        item[n]=document.createElement('DIV');
        item[n].innerHTML=n;
        item[n].setAttribute("id","itemset"+n);
        collections.appendChild(item[n]);
        item[n].onclick=handler;
    }
}

Insert dynamic ids  to the elements and when you click on any element retrieve its id using this.id and do whatever you want to do with that value.
That's all.
Hope this helps.


text:
Q: Why don't the spacesuits have a maneuvering unit? The spacesuit in the Passengers movie that are used to move outside the ship are attached to the hull with magnetic soles and only a single safety rope.
Shouldn't they have a maneuvering unit (like MMU) installed in case the rope breaks?

A: The important thing to note here is that like all of the other passenger amenities on board the Avalon, the spacesuits and 'EVA experience' are little more than a fairground ride.

Computer Voice: We hope you decide to join us again... for another thrilling experience!

We already know from the attempts to break into the crew quarters that our futuristic ship has meta-materials that are essentially unbreakable and we see when Jim leaves the ship that the tether snakes out of the wall and automatically attaches itself to him, giving him the illusion of control while the ship still retains 100% safety.

In short, the EVA is an experience that's intended for someone with zero space-flight knowledge. Providing the passenger with an MMU would simply give them the ability to kill themselves with their first uncontrolled flight into a bulkhead.


text:
Q: C# Socket connection doesn't work I'm Trying to create a code to send a TCP message to a server.
When I use AutoIT Script Language with this code:
Example()

Func Example()

Local $ConnectedSocket, $szData

Local $szIPADDRESS = "10.200.0.104"

Local $nPORT = 1040

; Start The TCP Services

TCPStartup()

; Initialize a variable to represent a connection

$ConnectedSocket = -1

;Attempt to connect to SERVER at its IP and PORT 1040

$ConnectedSocket = TCPConnect($szIPADDRESS, $nPORT)

; If there is an error... show it

If @error Then
MsgBox(4112, "Error", "TCPConnect failed with WSA error: " & @error)

Else

$szData="0x0021601FA10706052B0C00815ABE14281206072B0C00821D8148A007A0050303000800000DA20B0201013006020200D30500"

TCPSend($ConnectedSocket, $szData)

EndIf

EndFunc;==>Example

Works fine but I need to write the same code in C#. I try to do this:
private static byte[] MessageToByteArray(string message, Encoding encoding)
        {
            var byteCount = encoding.GetByteCount(message);
            if (byteCount > byte.MaxValue)
                throw new ArgumentException("Message size is greater than 255 bytes in the provided encoding");
            var byteArray = new byte[byteCount + 1];
            byteArray[0] = (byte)byteCount;
            encoding.GetBytes(message, 0, message.Length, byteArray, 1);
            return byteArray;
        }

        public static void Main(string[] args)
        {
            const string message = "0x0021601FA10706052B0C00815ABE14281206072B0C00821D8148A007A0050303000800000DA20B0201013006020200D30500";
            var byteArray = MessageToByteArray(message, Encoding.ASCII);

            Socket m_socClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

            System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("10.200.0.104");
            System.Net.IPEndPoint remoteEP = new IPEndPoint(ipAdd, 1040);
            m_socClient.Connect(remoteEP);

            try
            {

                m_socClient.Send(byteArray);
            }
            catch (SocketException se)
            {
                Console.WriteLine(se.Message.ToString());
            }

        }

But this code doesn't work. The server shows when he receives the command. With C# code, the server shows that have connected but the command doesn't execute.

A: Are you sure you have to prefix the length?
byteArray[0] = (byte)byteCount;
encoding.GetBytes(message, 0, message.Length, byteArray, 1);

Often you have a null-terminated string:
encoding.GetBytes(message, 0, message.Length, byteArray, 0);
byteArray[byteArray.Length - 1] = (byte)'\0';


text:
Q: How to get a running sum on HTML table? I searching a solution for give the running sun to a editable html table, like a spreadsheet:

A: Hi here is a basic example of what you want using :

*

*The HTML content editable property.

*A css class to append a focusout event to the table cell.

*A simple loop to sum all values when one value changes.

$('#tbodyTest >tr').on('focusout', 'td.editable', (e) => {
  let target = $(e.target),
    parent_row = $(e.target).closest('tr'),
    previous_row = parent_row.prev();
  setTimeout(() => {
    if (!isNaN(target.text())) {
  $('#tbodyTest').children('tr').each((i,e)=>{
      $(e).find('td').last().text(Number($(e).find('td:eq(2)').text()) +Number($(e).prev().find('td').last().text()))
    })
    }else{
      target.text("0");
  parent_row.find('td').last().text("0");
  $('#tbodyTest').children('tr').each((i,e)=>{
  $(e).find('td').last().text(Number($(e).find('td:eq(2)').text()) +Number($(e).prev().find('td').last().text()))
})
    }
  })
})
.editable {
  background-color: red;
}

    date
    desc
    cost
    running sum

      01-01-2019
      a
      1000
      1000

      01-02-2019
      a

      01-03-2019
      a

      01-04-2019
      a

Keep in mind that this is a basic example and you will probably add more stuff according to your needs since your ask is simple as well.
Hope it helps

A: Anyone still looking to this.

$('tr').each(function(index, el) {
  if (index == 0) {
    $(this).find('.running-balance').text($(this).find('.amount').text());
  } else {
    var prevRow = $(this).prev();
    var prevBalance = Number(prevRow.find('.running-balance').text());
    var currentAmount = Number($(this).find('.amount').text());
    var newBalance = prevBalance + currentAmount;
    $(this).find('.running-balance').text(newBalance.toFixed(2));
  }
});
td,
th {
  border: 1px solid;
}

      Description
      Amount
      Running Balance

      a
      100

      b
      150

      c
      125

      d
      205

      e
      50


text:
Q: Accessing the content of a parsed JSON text I am reading an http request containing JSON and parsing it like this:
res = JSON.parse(httpRequest.responseText)

The result of my request is:
{"node":[{"id":"10","name":"a_name"}], "childs":[{"id":"11"}]}

How can I access to the attribute childs in javascript?

A: You can access the attributes like it:
res.childs[0].id;

this will give the output:
11

Similarly you can access other attributes.

A: The resulting JSON is accessible as a regular JavaScript object (that's one of the cool things about JSON) and you can access them as you would a regular JavaScript object.
For example:
var res = JSON.parse('{"node":[{"id":"10","name":"a_name"}], "childs":[{"id":"11"}]}');
console.log(res.childs);


text:
Q: How to make gVim transparent on Ubuntu 10.10? I have a .gvimrc file that works fine on OS X 10.6, but won't work on Ubuntu. It contains a line that reads set transparency=15, and when i run gVim it reports:
Error detected while processing /home/user/.gvimrc:
line   25:
E518: Unknown option: transparency=15

Any ideas to make gVim transparent by default?
Chers!
The whole .gvimrc file for completion:
" Turn on line numbers
set number

" Change colorscheme
colorscheme ir_black

" Turns on the tab bar always
set showtabline=2

" Number of horizontal lines on the screen
set lines=60

" GUI Option to remove the Toolbar (T)
set guioptions-=T

" Sets the percent transparency
set transparency=15

A: I'm afraid the transparency feature is only in MacVim. I just grepped the source code for Vim 7.3 (the latest stable version) and I couldn't find any trace of a transparency option.
One possible solution is to do it via Compiz; look for the module that enables transparent windows: from there you should be able to set up a special rule for Gvim windows.

A: Another option would be to skip gvim and just run regular vim inside, e.g., gnome-terminal or some other terminal emulator that supports transparency. (I use guake.) Gvim doesn't offer much over regular vim.

A: sudo apt-get install  xcompmgr devilspie transset-df
mkdir -p ~/.devilspie
cd ~/.devilspie
touch opacity.ds
vim opacitiy.ds

Change the file contents to:
( if ( contains ( window_class ) "Gvim" ) ( begin ( spawn_async (str
"transset-df -i " (window_xid) " 0.85" )) ) )

You may add devilspie /home/username/.devilspie/opacity in startup apps.

A: Inside your .gvimrc
autocmd GuiEnter * silent exec "!transset -a 0.80"
Possible variants: transset might be transset-df, 0.80 is the opacity (from 0 - 1).

A: transparency-windows-vim and the vimtweak plugins it worked for me.
paste these in your .vimrc and place the .dll files in the same directory ass the gvim.

Plug 'mattn/transparency-windows-vim'

Plug 'mattn/vimtweak'


text:
Q: Inline Block Display Issue I am creating a dashboard and in the dashboard I got two boxes that I wanted have in the same level at the top. I am using the display "inline-block" to group them in boxes; however, the result is different instead the bottom part is in the same level but the top is not. See screenshot below:
https://www.mediafire.com/convkey/8e14/xdh672yojc8owe86g.jpg
I set the height of each box to "auto". You can see on the screenshot that the first box is not aligned equally to the second box, is there a way to have the two boxes in the same level or aligned equally at the top? I tried using table-cell display but it has compatibility issue on other browsers such as IE. Thanks

A: Use the verical-align: top; CSS property on the element which contains your inline-block elements. ;)


text:
Q: Error while mounting host directory in Nexus Docker I am using the following command to run my container
docker run -d -p 9001:8081 --name nexus -v /Users/user.name/dockerVolume/nexus:/nexus-data sonatype/nexus3

Container starts and fail immediately. with the following logs

mkdir: cannot create directory '../sonatype-work/nexus3/log':
  Permission denied
mkdir: cannot create directory
  '../sonatype-work/nexus3/tmp': Permission denied
Java HotSpot(TM)
  64-Bit Server VM warning: Cannot open file
  ../sonatype-work/nexus3/log/jvm.log due to No such file or directory

I was following this link to set it up
I have given said permission to nexus directory.
I also tried the following SO link but that didn't help me either.
I was still getting the same error.
Docker Version 17.12.0-ce-mac47 (21805)
[EDIT]
I did made changes to the ownership of my nexus folder on my host
sudo chown -R 200 ~/dockerVolume/nexus

A: In my ubuntu server I had to perform:
chown -R 200:200 path/to/directory

Not only 200, but 200:200

A: If you have this problem trying to run Nexus3 inside of Kubernetes cluster, you should set UID with initContainers. Just add it to your spec:
initContainers:
- name: volume-mount-hack
  image: busybox
  command: ["sh", "-c", "chown -R 200:200 /nexus-data"]
  volumeMounts:
  - name: <your nexus pvc volume name>
    mountPath: /nexus-data

A: That Dockerfile is available, in the repo sonatype/docker-nexus3.
And mounting a volume is documented as:

Mount a host directory as the volume.
This is not portable, as it relies on the directory existing with correct permissions on the host. However it can be useful in certain situations where this volume needs to be assigned to certain specific underlying storage.

$ mkdir /some/dir/nexus-data && chown -R 200 /some/dir/nexus-data
$ docker run -d -p 8081:8081 --name nexus -v /some/dir/nexus-data:/nexus-data sonatype/nexus3

So don't forget to do, before your docker run:
chown -R 200 /Users/user.name/dockerVolume/nexus


text:
Q: What is the difference between a logistic regression and log binomial regression? I understand that the outcomes have different meanings such as in epidemiology but what is the difference between the two models? I am new to statistics and will greatly appreciate an easy to understand answer and preferably with an example.

A: Both models are binomial generalized linear models (GLMs). The "binomial" part of that phrase means that we think the outcome $Y_i$ for each observation $i$ is generated as the result of a single weighted coin flip, 0 or 1, governed by the parameter $p_i$, which is equal to the probability of getting a 1 (i.e., $p_i = P(Y_i=1)$).
Where the models differ is in the form of the relationship between the predictors $X_i$ and $p_i$. In logistic regression, the relationship is
specified as $$
p_i=\text{expit}(X_i \beta)=\frac{1}{1+\exp(-X_i\beta)}
$$
or, equivalently,$$
\text{logit}(p_i)=\frac{p_i}{1-p_i}=X_i\beta
$$
In log-binomial regression, the relationship is specified as $$
p_i=\exp(X_i \beta)
$$
or, equivalently,
$$
\log(p_i)=X_i \beta
$$
The coefficients $\beta$ are interpreted differently between the two models. For both, it makes sense to exponentiate them. In logistic regression, $\exp(\beta_k)$ is the odds ratio corresponding to a 1-unit change in $X_k$, holding all other variables in the model constant. In log-binomial regression, $\exp(\beta_k)$ is the risk ratio corresponding to a 1-unit change in $X_k$, holding all other variables in the model constant.
Logistic regression always produces estimates of $p_i$ that are between 0 and 1. This is not true for log-binomial regression; when a model is not saturated, it is generally possible, given a set of estimated coefficients, to compute an estimate of $p_i$ that is greater than 1 (but it will always be positive). There can be numerical problems when using log-binomial regression for this reason (i.e., the model can be hard for computer programs to fit). Which model fits your data better is an empirical question, but logistic regression will almost always perform better unless there are very few 1s.
For saturated models, the two models will fit exactly the same and produce the same predicted probabilities. The log-binomial model is therefore most useful when you have a saturated model and you want to interpret a coefficient as a risk ratio, e.g., when the only predictor in your model is treatment status in a randomized trial.
See here and here for more discussions of these models.

A: They are both GLMs, and they both take the variance of the response to have a mean-variance relationship as p(1-p) with p = probability of response. The difference regards the transformation of the expected response in the GLMs. The logistic regression models the logit transformation of the p whereas log binomial models the log of the p. The exponentiated (non-intercept) coefficients for logistic regression model are interpretted as odds ratios whereas for log-binomial they are relative risk ratios. Logistic regression is valid in outcome dependent sampling like case control studies. Log-binomial models risk overfitting response probabilities to values greater than 1. They give approximately equal estimation and inference when the probaibility of response is very low.


text:
Q: Accordion Menu in Asp.net Mvc4 I am using a template for my project. I have an accordion menu in this template, but it is not ready to use(not slidingup or down). How can I make it slideup and down on click ? Here are my codes and a screenshot from my menu. I am giving the html source code too.
Menu

              @foreach (var kategori in Model.kategoriler)
              {

 @kategori.KategoriAd

                  @foreach (var altkat in kategori.AltKategoriler)
                  {

 @altkat.AltKategoriAd

                  }

              }

Source Code:

 Kalemler

 Jel Kalemler

 Boya Kalemleri

 Kurşun Kalemler

 Dolma Kalemler

 Tükenmez Kalemler

 Fosfoslu Kalemler

 Pilot  Kalemler

 Defterler

 Orta Boy Defterler

 Küçük Boy Defterler

 Büyük Boy Defterler

 Okul Defterleri

 Günlük ve Ajandalar

 Seyahat Defterleri

 Tarif Defterleri

 Baskılar

 Kalpli Baskı

 Vintage Baskı

 Saatli Baskı

 Kalem Kutuları

 Çıtçıtlı Meyveli Kalem Kutusu

 Deri Çiçekli Kalem Kutusu

 Aksesuarlar

 Paper Doll Bozuk Para Cüzdanı

 Çizgili Bozuk Deri Para Cüzdanı

 Hesap Makinesi

 Hesap Makinesi

 Dekorasyon

 Minyatür Banklar

 Müzik Kutuları

 Kapı Süsleri

 Bantlar

 Aynalar

 Metal Kutular

 Mini Metal Kutular

 Çiçekli Metal Kutular

 Ivır Zıvırlar

 Mandallar

A: I solved the problem, here is my solution.
 $(document).ready(function () {  var panels = $('#main > li > ul').hide();
            $('#main > li > span').click(function () {
                var $this = $(this);
                panels.slideUp();
                $('#main > li > span').not($this).removeClass('subDropdown minus');
                $('#main > li > span').not($this).addClass('subDropdown plus');
                $this.next().toggle();
                $this.toggleClass('subDropdown plus').toggleClass('subDropdown minus');

                return false;
  });});


text:
Q: Query SQL Server Database from native iOS Application I am working on an in-house, iOS app that will need read-only access to a SQL Server with multiple databases. I know the stock answer here is "write some web services", but I'd like a solution that is self-contained. Is there any way to directly connect to a SQL Server database from an iOS application? I'm thinking something like a basic ODBC connection.
I've seen a lot of users asking this question, but very few answers other than "write a web service." Is that really the only way?

A: A web service is indeed the only way, but Red Gate's written one you can reuse:
http://www.mobilefoo.com/iSqlServerSDK.html
http://labs.red-gate.com/Tools/Details/iSqlSDK
It's not officially released yet, just in beta, so keep in mind that features & prices may change.

A: Actually the easiest way is to create a MVC 3 or 4 asp.net web application. call the web methods. You don't need any API to pay for.
I use SBJson to serialize domain object and then send the objects as serialized jSOn to MVC 3. It's super easy to do. I even send images with base64, so it's .net compatible.
See my blog post with sample code:
http://nickturner.wordpress.com/2012/10/09/107/

A: So, after much searching and trial and error, unfortunately the best (only?) way I've found is indeed using Web Services.
Fortunately, Linq to SQL makes the WCF-creation-side incredibly easy. Once I got someone at work to walk me through setting up a Windows web server and adding the web service (and buying access to an online web server), the Windows side was up and ready to go.
I'm still working through all of the syntax stuff on the SOAP interaction side, but keeping my different methods somewhat similar in structure allows me to tinker a little until it works. By this time, I think I've gotten it to work pretty well.
So, both answers I got back were (disappointingly) correct. The only way to interact is through a Web Service. Even the 3rd party solutions they mentioned were really just convenient wrappers around the same type of technology. As it turns out, I'd rather have finer control over the process.
One word of advice: Get a real, external web server. I tried doing this on a non-Server Windows VM on my iMac/MacBook Pro, and it was like pulling teeth! Once I actually got access to an external, full, stand-alone web server, the process was much more streamlined and easy. Do yourself a favor and take that headache out of the equation!

A: There was a SQL ISAPI extension as part of SQLXML, but I think it has been deprecated: http://msdn.microsoft.com/en-us/library/aa226559%28v=SQL.80%29.aspx
This was effectively a pre-built, and relatively open, web service - so I'm not sure this counts as a direct connection.
You could also check out http://odbcrouter.com/Main


text:
Q: Extend React forwardRef component with methods I want to create an extended component with some additional functions added.
Let's say I have an ExtendedButton component which has a button that is forwardRef:ed, but which also has a doubleClick method. I know this is a silly example, but something like this:
const ExtendedButton = forwardRef<HTMLButtonElement, React.HTMLAttributes<HTMLButtonElement>>((props, ref) => {
  const btnRef = useRef<HTMLButtonElement>(null);
  useImperativeHandle(ref, () => btnRef?.current as HTMLButtonElement);

  const doubleClick = () => {
    btnRef.current?.click();
    btnRef.current?.click();
  };

  return <button {...props} ref={btnRef}></button>;
});

I want to be able to get the doubleClick method, as well as all the methods on the button, from a consumer component like this:
export const Consumer = () => {
  const ref = useRef<HTMLButtonElement>(null);

  ref.current.doubleClick();
  ref.current.click();

  return <ExtendedButton ref={ref}></ExtendedButton>;
};

I feel I should probably remove the forwardRef so the ref is pointing to ExtendedButton instead of button, but how can I get the button methods then?
Thanks!

A: useImperativeHandle should expose all the methods you want to access:
type ExtendedButtonType = HTMLButtonElement & { doubleClick: () => void }
const ExtendedButton = forwardRef<ExtendedButtonType, React.HTMLAttributes<HTMLButtonElement>>(
  (props, ref) => {
    const btnRef = useRef<HTMLButtonElement>(null)
    const doubleClick = (): void => {
      btnRef.current?.click()
      btnRef.current?.click()
    }
    useImperativeHandle(
      ref,
      () =>
        ({
          ...btnRef.current,
          doubleClick,
        } as ExtendedButtonType),
    )

    return <button {...props} ref={btnRef} />
  },
)

export const Consumer: FC = () => {
  const ref = useRef<ExtendedButtonType>(null)

  ref.current?.doubleClick()
  ref.current?.click()

  return <ExtendedButton ref={ref} />
}

A: add the method inside the useImperativeHandle
  const ExtendedButton = forwardRef<HTMLButtonElement, React.HTMLAttributes<HTMLButtonElement>>((props, ref) => {
      const btnRef = useRef<HTMLButtonElement>( );

      useImperativeHandle(ref, () => ({

        ...btnRef.current,
        doubleClick: () => {
          btnRef.current?.click();
          btnRef.current?.click();
         };
      }));

      return <button {...props} ref={btnRef}></button>;
    });


text:
Q: Using base64_encode when using PHP's crypt() function I have a quick question for you guys:
I am tinkering with PHP (I am relatively inexperienced), and am interested in developing a secure password hashing system for use on my site. Through other articles and questions on SO, I have surmised that I should be using PHP's crypt() function for an implementation of BSD's bcrypt hashing algorithm.
My question to you pertains to the fact that, when I feed the function an initialization vector or password, inputs that are not base64 seem to return a "0" as the hash. Here is what I have implemented to work around this issue:
$salt = base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM));

and
$password = base64_encode($password);

Is there a danger of collisions or otherwise decreased security when I change the encodings like this?
My idea was that I would like to allow users to use any range of characters for their passwords (I will enforce a good password policy) without having to worry about my hash function returning an empty hash.
Is there a more simple or elegant way to do this? Should I perhaps be using a hash function that doesn't restrict my salt and password as much?
Thanks in advance for any help you can give me.

A: Encoding it under base64 does not increase the chance of collision as it is simply a 1-to-1 translation. It does not reduce the password haystack whatsoever.

A: For hashing in php, I suggest using the hash function. It takes an algorithm to use, so you can throw it through sha or anything else.
As for collisions, I wouldn't worry about them, it's highly unlikely that you will get impacted by collisions.


text:
Q: CMake how to find linked absolute path for *.lib files I have a CMake project which is runnable, with part of the code
target_link_libraries(exec PRIVATE d3d11.lib dwmapi.lib d3dcompiler.lib)

How do I know which *.lib (from where) is used?
Is it possible to print the path?
Thanks
Try to find the path to CMake link library, specifically *.lib files.


text:
Q: Handling QSqlTableModel data on startup I have an application of which I want data from an SQLite database to be parsed directly on startup.
When starting the application, I'm calling a member function of my QSqlTableModel instance called create():
mymodel.cpp
MyModel::MyModel(QObject* parent) : QSqlTableModel(parent)
{
}

// ...

void MyModel::create()
{
    // SQL specific
    createTable();

    setTable(myTableName);
    setSort(2, Qt::DescendingOrder);
    setEditStrategy(QSqlTableModel::OnManualSubmit);

    // config specific
    addUserEntry();

    emit myModelChanged();
};

I have a controller which provides MyModel for QML:
mycontroller.h
class MyController : public QObject
{
    Q_OBJECT
    Q_PROPERTY(MyModel* myModel READ myModel CONSTANT)

    MyModel* myModel() { return _myModel; }

    // ...

private:
    QSqlDatabase _database;
    MyModel* _myModel { nullptr };
};

mycontroller.cpp
MyController::MyController(QObject* parent) : QObject(parent)
{
    _database = QSqlDatabase::database();
    // ...
    _myModel = new MyModel(this, _database);
}

void MyController::start()
{
    _myModel->create();
    // ...
}

The controller class is being registered for QML in my main.cpp:
main.cpp
int main(int argc, char* argv[])
{
    // ...

    qmlRegisterType<MyController>("my.application.app", 1, 0, "MyController");

    // ...
    _myController->start();

and instantiated in main.qml:
main.qml
ApplicationWindow {
    // ...

    MyController {
        id: myController
        objectName: "myController"

        onMyModelChanged: {
            if (myModel.someValue.length > 0) {
                Config.someValue = myModel.someValue;
            }

            if (myModel.otherValue.length > 0) {
                Config.otherValue = myModel.otherValue;
            }
        }
    }

    // ...

Now, what I want is for my QSqlTableModel to retain data from the SQL table directly after calling the create function so the table model will be refreshed and accessible in QML.
E.g., I want Config.someValue and Config.otherValue in QML to be set directly after starting the application.
How do I tell the QSqlTableModel to refresh and push data to QML even if no data was changed before?
What I can see is when calling QSqlTableModel::data(index(0, 0), 2).toString(), the information is already there, however the table model is not being refreshed in QML but the values requested (i.e. myModel.someValue and myModel.otherValue are shown as undefined. How do I achieve this?


text:
Q: Spring Batch nor run reader and writer function after initilazation I have a spring batch running that run the read() function at the beginning end never again. I also have JobExecutionListenerSupport which has beforeJob and afterJob It runs this method but does not run the read and writer function.
Batch Configuration
@Configuration
@EnableBatchProcessing
public class BatchConfiguration {

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Bean
    public ListItemReader<Blog> reader() {
        System.out.println("reader");
        return new ListItemReader<Blog>(new ArrayList<Blog>());
    }

    @Bean
    public JdbcBatchItemWriter<Blog> writer(DataSource dataSource) {
        return new JdbcBatchItemWriterBuilder<Blog>()
                .itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<Blog>())
                .sql("INSERT INTO blog (param, blog_url, blog_title) VALUES (:identity.param,:identity.url, :blogTitle)")
                .dataSource(dataSource).build();
    }

    @Bean
    public Job importCrawlingBatch(JobCompletionNotificationListener listener, Step step1) {
        return jobBuilderFactory.get("importCrawlingBatch").incrementer(new RunIdIncrementer()).listener(listener)
                .flow(step1).end().build();
    }

    @Bean
    public Step step1(JdbcBatchItemWriter<Blog> writer)

        return stepBuilderFactory.get("step1")
                .<Blog, Blog>chunk(10)
                .reader(reader())
                .writer(writer)
                .faultTolerant()
                .skip(DuplicateKeyException.class).skipPolicy(new ItemSkipPolicy())
                .allowStartIfComplete(true).build();
    }
}

How I run multiple times
@Component
@AllArgsConstructor
@EnableScheduling
public class ScheduledJobConfiguration {
    private final JobLauncher jobLauncher;

    private final Job ourJob;

    @Scheduled(cron = "0 */1 * * * *")
    public void startBatchJob() throws Exception {
        JobParameters jobParameters = new JobParametersBuilder().addString("time", new Date().toString())
                .toJobParameters();

        jobLauncher.run(ourJob, jobParameters);
    }

}

And my JobExecutionListenerSupport
@Component
public class JobCompletionNotificationListener extends JobExecutionListenerSupport {

    @Override
    public void beforeJob(JobExecution jobExecution) {
        super.beforeJob(jobExecution);

        System.out.println(">>> CRAWLING STARTED <<<");
    }

    @Override
    public void afterJob(JobExecution jobExecution) {
        if (jobExecution.getStatus() == BatchStatus.COMPLETED) {
            System.out.println(">>> CRAWLING FINISHED <<<");
        }
    }

}

The console log:
 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.4.4)

23:46:02 INFO  c.b.a.Application:55 - Starting Application using Java 15 on katesel with PID 6081 (/home/atesel/Projects/PostgreSQLBlogCrawling/Workspace/blogcrawling/target/classes started by atesel in /home/atesel/Projects/PostgreSQLBlogCrawling/Workspace/blogcrawling)
23:46:02 INFO  c.b.a.Application:662 - No active profile set, falling back to default profiles: default
23:46:03 INFO  o.s.d.r.c.RepositoryConfigurationDelegate:128 - Bootstrapping Spring Data JPA repositories in DEFAULT mode.
23:46:03 INFO  o.s.d.r.c.RepositoryConfigurationDelegate:188 - Finished Spring Data repository scanning in 31 ms. Found 2 JPA repository interfaces.
23:46:03 INFO  o.s.b.w.e.t.TomcatWebServer:108 - Tomcat initialized with port(s): 8080 (http)
23:46:03 INFO  o.a.c.c.StandardService:173 - Starting service [Tomcat]
23:46:03 INFO  o.a.c.c.StandardEngine:173 - Starting Servlet engine: [Apache Tomcat/9.0.44]
23:46:03 INFO  o.a.c.c.C.[.[.[/]:173 - Initializing Spring embedded WebApplicationContext
23:46:03 INFO  o.s.b.w.s.c.ServletWebServerApplicationContext:289 - Root WebApplicationContext: initialization completed in 1074 ms
23:46:03 INFO  c.z.h.HikariDataSource:110 - HikariPool-1 - Starting...
23:46:04 INFO  c.z.h.HikariDataSource:123 - HikariPool-1 - Start completed.
23:46:04 INFO  o.h.j.i.u.LogHelper:31 - HHH000204: Processing PersistenceUnitInfo [name: default]
23:46:04 INFO  o.h.Version:44 - HHH000412: Hibernate ORM core version 5.4.29.Final
23:46:04 INFO  o.h.a.c.Version:56 - HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
23:46:04 INFO  o.h.d.Dialect:175 - HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL10Dialect
23:46:04 INFO  o.h.e.t.j.p.i.JtaPlatformInitiator:52 - HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
23:46:04 INFO  o.s.o.j.LocalContainerEntityManagerFactoryBean:437 - Initialized JPA EntityManagerFactory for persistence unit 'default'
Writer
step 1
Reader
23:46:04 INFO  o.s.s.c.ThreadPoolTaskScheduler:181 - Initializing ExecutorService
23:46:04 INFO  o.s.s.c.ThreadPoolTaskScheduler:181 - Initializing ExecutorService 'poolScheduler'
23:46:04 WARN  o.s.b.a.o.j.JpaBaseConfiguration$JpaWebConfiguration:221 - spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
23:46:05 INFO  o.s.s.c.ThreadPoolTaskExecutor:181 - Initializing ExecutorService 'applicationTaskExecutor'
23:46:05 WARN  o.s.b.a.b.JpaBatchConfigurer:57 - JPA does not support custom isolation levels, so locks may not be taken when launching Jobs
23:46:05 INFO  o.s.b.c.r.s.JobRepositoryFactoryBean:185 - No database type set, using meta data indicating: POSTGRES
23:46:05 INFO  o.s.b.c.l.s.SimpleJobLauncher:215 - No TaskExecutor has been set, defaulting to synchronous executor.
23:46:05 INFO  o.s.b.w.e.t.TomcatWebServer:220 - Tomcat started on port(s): 8080 (http) with context path ''
23:46:05 INFO  o.s.s.c.ThreadPoolTaskScheduler:181 - Initializing ExecutorService
Hibernate:
    select
        cronconfig0_.id as id1_1_0_,
        cronconfig0_.cron_exp as cron_exp2_1_0_
    from
        cron_conf cronconfig0_
    where
        cronconfig0_.id=?
23:46:05 INFO  c.b.a.Application:61 - Started Application in 3.271 seconds (JVM running for 3.512)
Hibernate:
    select
        cronconfig0_.id as id1_1_0_,
        cronconfig0_.cron_exp as cron_exp2_1_0_
    from
        cron_conf cronconfig0_
    where
        cronconfig0_.id=?
23:47:00 INFO  o.s.b.c.l.s.SimpleJobLauncher:146 - Job: [FlowJob: [name=importCrawlingBatch]] launched with the following parameters: [{time=Wed Mar 09 23:47:00 TRT 2022}]
>>> BATCH CRAWLING STARTED <<<
23:47:00 INFO  o.s.b.c.j.SimpleStepHandler:149 - Executing step: [step1]
23:47:00 INFO  o.s.b.c.s.AbstractStep:273 - Step: [step1] executed in 16ms
>>> BATCH  CRAWLING FINISHED <<<

As it can be seen from the run the read and write functions are not called. They only called once an it is during initialization and never again.

A: It was because I didn't add the @StepScop attribute for reader and writer functions. If you want to learn more what happens when you add  @StepScop
@Configuration
@EnableBatchProcessing
public class BatchConfiguration {

@Autowired
public JobBuilderFactory jobBuilderFactory;

@Autowired
public StepBuilderFactory stepBuilderFactory;

@Bean
@StepScope
public ListItemReader<Blog> reader() {
    System.out.println("reader");
    return new ListItemReader<Blog>(new ArrayList<Blog>());
}

@Bean
@StepScope
public JdbcBatchItemWriter<Blog> writer(DataSource dataSource) {
    return new JdbcBatchItemWriterBuilder<Blog>()
            .itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<Blog>())
            .sql("INSERT INTO blog (param, blog_url, blog_title) VALUES (:identity.param,:identity.url, :blogTitle)")
            .dataSource(dataSource).build();
}

@Bean
public Job importCrawlingBatch(JobCompletionNotificationListener listener, Step step1) {
    return jobBuilderFactory.get("importCrawlingBatch").incrementer(new RunIdIncrementer()).listener(listener)
            .flow(step1).end().build();
}

@Bean
public Step step1(JdbcBatchItemWriter<Blog> writer)

    return stepBuilderFactory.get("step1")
            .<Blog, Blog>chunk(10)
            .reader(reader())
            .writer(writer)
            .faultTolerant()
            .skip(DuplicateKeyException.class).skipPolicy(new ItemSkipPolicy())
            .allowStartIfComplete(true).build();
   }
}


text:
Q: Generating a jQuery UI progress bar I'm using a 3rd party service to process images and they provide a handy jQuery plugin. The plugin can output feedback on the upload transfer, and I would like to display this as a nice jQuery progress bar from the jQuery UI.
Here is the example they give, which currently just shows the transfer status as text:
$('#MyForm').transloadit({
  modal: false,
  onProgress: function(bytesReceived, bytesExpected) {
    // render your own progress bar!
    $('#progress')
      .text((bytesReceived / bytesExpected * 100).toFixed(2)+'%');
  },
  onError: function(assembly) {
    alert(assembly.error+': '+assembly.message);
  }
});

A: In order to update the Progess Bar value, use this:
$("#progress").progressbar("value", ((bytesReceived / bytesExpected) * 100));

For more info see the docs.

A: $('#progress').progressbar("option", "value", bytesReceived / bytesExpected * 100);


text:
Q: Wierd terminal display glitch in c, Ubuntu When I run the first code it with "\n" at the end of every print statement it gives me the expected output which is in case of num == 35
The generated sequence:
35
106
53
160...

code to generate collatz sequence:
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>

int main(int argc, char* argv[])
{
    int fd[2], fd1[2], num = atoi(argv[1]), id = getpid();

    printf("\nRecieved number: %d\n", num);

    if(num > 0)
    {
        printf("The generated sequence: \n");

        while(num > 1)
        {
            pipe(fd);
            pipe(fd1);

            if(fork()) //parent process
            {
                printf("%d \n", num);
                int n;
                close(fd[0]); //closing read end..
                close(fd1[1]); //closing write end..

                write(fd[1], &num, sizeof(num));
                wait(NULL);
                read(fd1[0], &n, sizeof(n));

                num = n;

                close(fd[1]);
                close(fd1[0]);

                if(num == 1) {
                    printf("1\n");
                    exit(0);
                }
            }

            else    //child process
            {
                int n;
                close(fd[1]); //closing write end..
                close(fd1[0]); //closing read end..

                read(fd[0], &n, sizeof(n));

                if(n%2 == 0)
                    n /= 2;

                else
                    n = 3*n+1;

                write(fd1[1], &n, sizeof(n));

                close(fd1[1]);
                close(fd[0]);
                exit(0);
            }
        }
    }

    else {
        printf("\nERROR: number should be positive!!\n");
        exit(1);
    }

    return 0;
}

...But the problem is if I change the printing line
printf("%d \n", num);

to
printf("%d, ", num);

my output will have repetitions i.e.
it will print:
with n=35
sequence: 35 sequence: 35, 106 sequence: 35, 106, 53 sequence: 35, 106, 53, 160...

Although printing on new line fixes the repetition problem, I don't want to print every number of sequence on new line.

A: Without a newline character, the output remains in the program's buffer. When the program forks, the buffer is duplicated along with the rest of the program. Eventually, both the parent and the child write more output, including what was in the buffer. So the output appears multiple times.
You can eliminate this duplication of the buffer contents by flushing the buffer forking. Put fflush(stdout); immediately before if (fork()). Flushing the buffer (which is inside the executing process) writes its contents to the stream (which is outside the executing process) and empties it.


text:
Q: Mongodb config file empty. How can I fix it? I am having problem with Mongodb regarding authentication, and was hoping to fix it by editing the config file. The first time I was able to edit it and it contained text. I then uninstalled Mongo and reinstalled it, and it is empty now. The command line I use is:
nano /etc/mongo.conf

I reinstalled it a couple more times, still can't figure it out. How can I fix it?

A: If you use nano /somepath/somefile it creates a new file if somefile not exists. Then you should look at /etc/init/ and not /etcit's probably your find the config file inside the first directory!


text:
Q: How/when does iOS determine safeAreaLayoutguides and layoutMargins? While working on a custom UINavigationController transition, I noticed something interesting: I create a copy of a UIView in my fromController, and add it to the transitionContext to do an animation, but it has a different value for safeLayoutGuides/Insets than the original in the the fromController. It has similar margins, though, differing only by the amount of the safeAreaInsets:
if let fromController = transitionContext.viewController(forKey: .from) as? WTPTransformingHeaderController
{
    // Make a copy of the from header
    let header_FromCopy = fromController.view_Header.copy() as! WTPTransformingHeaderView

    // fromController.view_Header.safeAreaLayoutInsets = UIEdgeInsets(top: 20.0, left: 0.0, bottom: 0.0, right: 0.0)
    // fromController.view_Header.layoutMargins = UIEdgeInsets(top: 48.0, left: 8.0, bottom: 8.0, right: 8.0)

    // header_FromCopy.safeAreaLayoutInsets = .zero
    // header_FromCopy.layoutMargins = UIEdgeInsets(top: 28.0, left: 8.0, bottom: 8.0, right: 8.0)
}

Exactly how does UIView set these properties? At what point in the view's lifecycle? I'm guessing it is determined by the view hierarchy somehow, but I cannot find specifics.


text:
Q: SQL deadlocking..in single user mode now Couple of databases produced an error this morning whilst running in Single User Mode.  Due to the following error I am unable to do anything :(
Msg 1205, Level 13, State 68, Line 1
Transaction (Process ID 62) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

I receive that error when trying the following (using the Master Database as a Sys Admin):
ALTER DATABASE dbname
SET MULTI_USER;
GO

For the sake of it I have tried Restarting the SQL Server, I have tried killing any processes and I have even tried resetting the single user myself:
ALTER DATABASE dbname
SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO

The job which was running was designed to copy the database and put it in single user mode immediately to try and make it faster.
Anyway I can remove the locks?

A: Ok,  I will answer my own.
I had to use the following:
sp_who

which displayed details of the current connected users and sessions, I then remembered about Activity Monitor which shows the same sort of stuff...Anyway that led me away from my desk to some bugger who had maintained connections to the database against my wishes...
Anyway once I had shut the PC down (by unplugging it...deserved it) I could then run the SQL to amend it into MULTI_USER mode (using system admin user):
USE Master
GO

ALTER DATABASE dbname
SET MULTI_USER;
GO

FYI for those who care, this can be used to immediately set the DB to SINGLE_USER:
ALTER DATABASE dbname
SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO

Further details, if you know the process id you can use kill pid:
kill 62

Bare in mind SSMS creates a process for your user as well, in my case this was being rejected due to another.
EDIT:  As Per Bobby's recommendations we can use:
sp_Who2

This can show us which process is blocked by the other process.

A: Had the same problem.  This worked for me:
set deadlock_priority high; -- could also try "10" instead of "high" (5)
alter database dbname set multi_user; -- can also add "with rollback immediate"

From ideas/explanation:
http://myadventuresincoding.wordpress.com/2014/03/06...
http://www.sqlservercentral.com/blogs/pearlknows/2014/04/07/...

A: tanks a lot.
SET DEADLOCK_PRIORITY HIGH ---- could also try "10" instead of "high" (5)
GO
ALTER DATABASE  SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
ALTER DATABASE  SET MULTI_USER
GO

A: When related system processes are at dead block scenario.
SPID 15 & SPID 29 - both are background SysProcesses.
This helps in such cases:
--------- START OF CMDs--------
SET DEADLOCK_PRIORITY HIGH ---- could also try "10" instead of "high" (5)
GO
ALTER DATABASE <dbname> SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
ALTER DATABASE <dbname> SET MULTI_USER
GO
-------------------------- END OF CMDs ------------------

Blocking Case with an User DB RESTORE process putting DB in Single_User


text:
Q: Easiest way to display a 3d model in Angular 4.0? I'm new to development and I'm making my own portfolio website to display some models and some products I've worked on in my career. The 3-d models are fairly simple and I can export them in pretty much any format (obj, stl, gltf etc..). I'm building the project in Angular and it's almost done so I would very much like to stick with it, with that in mind does anyone have any fairly simple suggestions to display 3-d models? I have had a look into threeJS but without clear working examples in angular im struggling to get it working. I did stumble upon the npm module "angular-stl-model-viewer" but once I've successfully installed it into an angular project directory via npm, and then try to import it in to app.module.ts I get errors. I think this may be due to the module being quite old.
Error below.
Build at: 2022-04-14T18:30:38.090Z - Hash: 81dc5d17ac2a0515 - Time: 7538ms
Error: node_modules/three/src/renderers/WebGLRenderer.d.ts:35:31 - error TS2304: Cannot find name 'OffscreenCanvas'.
35  canvas?: HTMLCanvasElement | OffscreenCanvas;
~~~~~~~~~~~~~~~
× Failed to compile.
Any help would be great thanks!


text:
Q: DocuSign and Office 365 SharePoint Online via REST API I will have the documents uploaded to our SharePoint Online library and from there I want to send document for signature of the customer and track the status. I don't want to get into DocuSign templates or any other thing as we will have multiple documents for multiple customers and using SharePoint Online as repository and DocuSign as just for signing tool.

A: Depending on the specifics of your use case, it's possible that the "DocuSign for SharePoint" connector might give you the functionality you require (without any need for development work on your part).  See https://www.docusign.com/partner/docusign-for-sharepoint-online for information about the (free) connector.
If the connector doesn't meet your needs, then you should be able to develop a custom integration between your SharePoint Online library and DocuSign -- provided that SharePoint Online has an API by which you can access the documents, create/update objects (to track DocuSign status), etc.  The DocuSign API can be used to integrate DocuSign with any other system, as long as that system provides a way for you to programmatically access its contents (i.e., an API).
From the DocuSign side of things, the DocuSign Developer Center (https://www.docusign.com/developer-center) is a good starting point for understanding the API.  Additionally, you'll want to become very familiar with the REST API Guide (https://08d1d92f490618f41c65-8fb00e97ac499a7066a18ce9c66b019b.ssl.cf2.rackcdn.com/REST_API_Guide_v2.pdf).  I'd suggest that you review these resources as starting point, and post more specific API questions here on SO if/when they arise.


text:
Q: will_paginate with endless Scrolling | Rails4 THIS IS THE SOLUTION
So i'm using will_paginate / Bootstrap Will Paginate with Endless Scrolling.
To get the Pagination working:
1.) In my Controller i updated my index action with
@clips = Clip.order("created_at desc").page(params[:page]).per_page(20)

2.) Edit my index view:
<%= will_paginate @clips%>

DONE
Pagination works just fine.
To Add Endless scrolling i did the same steps as in my previous Rails 3 App.
1.) Edit my clips.js.coffee

jQuery ->
$('#clips-masonry').imagesLoaded ->
    $('#clips-masonry').masonry itemSelector: ".clips-masonry" # Thats my Masonry

if $('.pagination').length # Thats for the Endless Scrolling
    $(window).scroll ->
        url = $('.pagination .next_page a').attr('href')
        if url && $(window).scrollTop() > $(document).height() - $(window).height() - 50
            # What to do at the bottom of the page
            $('.pagination').text("Fetching more Clips...")
            $.getScript(url)
        $(window).scroll()

2.) Create an index.js.erb with:
$boxes = $('<%= j render(@clips) %>')

$('#clips-masonry').append( $boxes ).imagesLoaded( function(){
  $('#clips-masonry').masonry( 'reload');
});
<% if @clips.next_page %>
  $('.pagination').replaceWith('<%= j will_paginate(@clips) %>');
<% else %>
  $('.pagination').remove();
<% end %>

3.) Added format.js to my Controller index action
def index
    @clips = Clip.order("created_at desc").page(params[:page]).per_page(12)
    respond_to do |format|
        format.html
        format.js
    end
end

4.) My _clip.html.erb is wrapped with the div

A: Ok, i got it working with my Updated Question, everyone who stumbles upon this problem, This is the solution.

A: Incase someone prefers to use JS/JQUERY:
$(window).scroll(function() {

  var url;

  // Checks if products are currently being loaded
  if (window.pagination_loading) {
    return;
  }

  // Grabs the URL from the "next page" button
  url = $('.pagination .next_page').attr('href')

  // Chckes if you're n height from the bottom
  if (url && $(window).scrollTop() > $(document).height() - $(window).height() - 50) {

    // Variable to know that you are currently loading products
    window.pagination_loading = true;

    // Text while loading
    $('.pagination').text('');

    // Run the script
    return $.getScript(url).always(function() {
      return window.pagination_loading = false;
    });

  }
});

Index.js.erb:
$products = $('<%= j render(@products) %>')

$('#productsContainer').append( $products );

<% if @products.next_page %>
  $('.pagination').replaceWith('<%= j will_paginate(@products) %>');
<% else %>
  $('.pagination').remove();
<% end %>

index.html.erb

    <%= will_paginate @products %>

Controller:
  respond_to do |format|
    format.html
    format.js
  end


text:
Q: Continuity and Joint Continuity (further thought) A follow up question of the cited question bellow.
Consider a function $f(x, y):\mathbb{R}\times\mathbb{R}\rightarrow\mathbb{R}$ is continuous in each argument. If we have continuous function $y(x):\mathbb{R}\rightarrow\mathbb{R}$, is $g(x)\equiv f(x,y(x))$ continuous?
In the former question, the joint continuity fails with a counter example. In the example the basic idea is to construct a path along which the function is not continuous, yet if we set $y(x)$ fixed, there is only one path to be verified. So is there maybe some conditions under which $f(x,y(x)$ is continuous?
@MISC {98831,
    TITLE = {Continuity and Joint Continuity},
    AUTHOR = {user12586 (https://math.stackexchange.com/users/12586/user12586)},
    HOWPUBLISHED = {Mathematics Stack Exchange},
    NOTE = {URL:Continuity and Joint Continuity (version: 2012-01-13)},
    EPRINT = {Continuity and Joint Continuity},
    URL = {Continuity and Joint Continuity}
}


text:
Q: How to speed up program that finds the shortest path between two wikipedia articles I recently coded a program that finds the shortest path between two wikipedia articles. The problem is getting ALL the links from a page and putting them into a graph is taking a long time. Finding the path is the easy part.
Basicly what I'm doing is this:
startingPage = 'Lisbon'
target = 'Adolf Hitler'
graph = nx.DiGraph()
graph.add_node(startingPage)
found = pages.import_page(graph, startingPage)

while found != True:
    for node in list(graph):
        if graph.out_degree(node) == 0:
            found = pages.import_page(graph, node)
        if found == True:
            break;

And my import_page function is this one:
def import_page(graph, starting, target):
    general_str = 'https://en.wikipedia.org/w/api.php?action=query&prop=links&pllimit=max&format=json&titles='
    data_str = general_str + starting
    encoded_data_str = data_str.encode('utf-8') #Sanitize input
    response = url.urlopen(encoded_data_str)
    data = json.loads(response.read())
    pageId = data['query']['pages'].keys()
    print starting
    if data['query']['pages'].keys()[0] == '-1': #Check if the page doesn't exist in Wikipedia
        return False
    elif data['query']['pages'][pageId[0]].keys()[2] != 'links': #Check if the page has no links in it
        return False

    for jsonObject in data['query']['pages'][pageId[0]]['links']:

        graph.add_node(jsonObject['title'])
        graph.add_edge(starting, jsonObject['title'])

        if jsonObject['title'] == target:
            return True

    while data.keys()[0] != 'batchcomplete':

        continueId = data['continue']['plcontinue']
        continue_str = data_str + '&plcontinue=' + continueId
        encoded_continue_str = continue_str.encode('utf-8') #Sanitize input
        response = url.urlopen(encoded_continue_str)
        data = json.loads(response.read())

        for jsonObject in data['query']['pages'][pageId[0]]['links']:
            graph.add_node(jsonObject['title'])
            graph.add_edge(starting, jsonObject['title'])
            if jsonObject['title'] == target:
                return True

    return False

The problem is for any distance bigger than 2/3 links it is a taking an immense amount of time. Any ideas on how I can speed it up?

A: Finding the shortest path with certainty is practically impossible with a simple algorithm and a web API. If the shortest path has N steps, you need to walk every possible path with length N-1 or less to be sure. With millions of articles and dozens to hundreds of links from each, that's unfeasible unless you are really lucky and the shortest path is just 1-2 links. If it's say 10 steps away, you'd have to make billions of requests, which would take years.
If you just want to find a reasonably short path most of the time, you can try something like an A* search algorithm with a good heuristic. For example, you could hypothesize some sort of small-world property and try to identify topic hubs which are close to other topic hubs and also to all articles in that topic. Or you can score candidates on being on the same topic, or in the same historic period as the target.

A: I used an approach as @Tgr point out, exploiting a small world.
If you use a weighted network, you can limit the search to a subgraph sufficiently large to encompass relevant hubs, and small enough to be handled in a web RESTful API.
You may want to check out iGraph module rather networkx, for less memory footprint.
With the approach I suggested to you I have been able to obtain shortest paths connecting up to 5 queried wikipedia articles, with a memory footprint of up to 100MB of sub-graph created in real time. A shortest path between two topics takes less than 1s.
I would be happy to share a link to my project, which actually compute a weighted knowledge networks for the wikipedia to allow search for connections between multiple topics - would it break SO policy or could be useful for the OP and discussion over his question?
EDIT

Thank you @Tgr for debriefing on the policy.
Nifty.works is a prototype platform to search for connections between inter-disciplinary fields.
The knowledge graph is a subset of Wikidata paired with English Wikipedia.
As an example for the OP, this example shows shortest paths queried between five Wikipedia articles: subgraph for connections between articles: "Shortest Path Problem", "A star search", "networkx", "knowledge graph" and "semantic network"
I computed the knowledge graph of Wikipedia as a weighted network.
The network has small-world properties.
A query for connections (paths) in between of articles is made by delimiting a portion of the knowledge graph (a sub-graph).
With this approach it is possible to serve a graph search fast enough to provide insights in knowledge discovery, even on small server machines.
Here you find examples of gamification of shortest paths between two articles of English Wikipedia, each pair has a distance bigger than 3 links - that is, they are not first neighbours: e.g. "Machine Learning" and "Life" -here a json of the queried subgraph).
You might even want to add parameters to adjust the size of your weighted sub-graph, so to obtain different results.
As an example, see the differences between:

*

*machine learning - life: query of shortest paths on weighted
subgraph of the knowledge graph of English Wikipedia (small-world network) (1)

*machine learning - life: query of shortest paths on weighted
subgraph of the knowledge graph of English Wikipedia (small-world network) (2)
Finally, also look at this question: https://stackoverflow.com/a/16030045/305883


text:
Q: How can I prove by induction that this is a closed form of the Fibonacci sequence? How can I prove by induction that this is a closed form of the Fibonacci sequence?
$$F_n=\frac1{\sqrt5}\left(\frac{1+\sqrt5}2\right)^{n+1}-\frac1{\sqrt5}\left(\frac{1-\sqrt5}2\right)^{n+1}$$
I've never seen before the $n+1$ exponent

A: How to write a proof by induction.
Step 1: Show that it is true in the base case
$F(0) = \frac{1}{\sqrt5}\phi - \frac{1}{\sqrt5}\phi'$
where $\phi = \dfrac{1+\sqrt5}{2}$ and $\phi' = \dfrac{1-\sqrt5}{2}$
Step 2:
State the inductive hypothesis: "Assume that $F(k) = \frac{1}{\sqrt5}\phi^{k+1} - \frac{1}{\sqrt5}\phi'^{k+1}$ for all $k < n$"
Step 3:
show that $F(n) = F(n-1) + F(n-2) = \frac{1}{\sqrt5}\phi^{n+1} - \frac{1}{\sqrt5}\phi'^{n+1}$
You get to use your hypothesis, i.e. $F(n-1) = \frac{1}{\sqrt5}\phi^n - \frac{1}{\sqrt5}\phi'^n$ and $F(n-2) =$ ...  to help you.
Regarding the exponents, treat them like you would treat any other exponent.
$(x)(x^n) = x^{n+1}$  They follow their algebraic rules, and just stick to the rules.

A: First of all, I think you have a mistake, I'm pretty sure the exponent is $n$ and not $n+1$.
Second of all, here's a hint:
Let's write: $\frac{1}{\sqrt{5}} (\frac{1+\sqrt{5}}{2})=\phi_1$
and $\frac{1}{\sqrt{5}} (\frac{1-\sqrt{5}}{2})=\phi_2$
Note that $\phi_1$ and $\phi_2$ are the solutions to the following equation:
$x^2-x-1$
And therefore $\phi_1^2-\phi_1-1=0$
So we get that $\phi_1+1=\phi_1^2$
And in the same way $\phi_2+1=\phi_2^2$
Now try to do the induction by using this somewhere along the way.


text:
Q: Reference current RoleProvider instance? When inside an ASP.NET page, module or handler with an HttpContext present, how do I get a reference to the current RoleProvider instance?
It's the provider used for authorization when the IPrincipal.IsInRole(..) method is called. By default, or from configuration, my provider seems to be a SqlRoleProvider instance by an error given when I'm running the app.
I want to inspect the type of provider at runtime to provide feedback on which one is actually being used.

A: The static Roles class has a Provider property on it which you can use to reference the current provider.
Roles.Provider

and if you are using a custom RoleProvider, you can cast it in order to access custom functionality.
((MyCustomRoleProvider)Roles.Provider).AllYourRoleAreBelongToUs();


text:
Q: Original Domain Names VS Generic Ones ? (seo) We've currently a debate here about original domain names versus generic domain names in term of seo efficiency.
We mean by generic domain names, domains like :
- buy-hifi.com
- game-news.com
- easy-meet.com

We mean by original domain names, domains like :
- hifihot.com
- gamesmaniac.com
- lovein.com

What is your opinion ? (actually it's more a poll than a actual question but developments are welcome)

A: I remember reading an article about AccuWeather being offered the chance to buy weather.com.  They passed on it because it didn't reflect their image, The Weather Channel snatched it afterwards, and AccuWeather ended up regretting their decision.  While a generic name won't sing your brand, and a brand is important, it's hard to say which is better.  I couldn't imagine generic domain names for companies like Apple, Microsoft, IBM, etc., so I suppose it depends.  What a lousy answer.  How about this: both.  Why not have both name types and offer redirection?


text:
Q: Debmirror error I followed the guide for setting up debmirror from https://help.ubuntu.com/community/Debmirror . I changed the files to go to an external drive and set it to download Focal and Hirsute. Debmirror completes without errors but I get an error when I try to point a computer to it but get an error when I try apt-get update.
Error message:
The repository 'http://192.168.1.42/ubuntu hirsute Release' does not have a Release file.Updating from such a repository can't be done securely, and is therefore disabled by default.See apt-secure(8) manpage for repository creation and user configuration details.
Where am I going wrong?

Files download to here
/mnt/USBHDD/mirrors/ubuntu_repository
├── dists
│   ├── focal
│   ├── focal-security
│   ├── focal-updates
│   ├── hirsute
│   ├── hirsute-security
│   └── hirsute-updates
├── pool
│   ├── main
│   ├── multiverse
│   ├── restricted
│   └── universe
└── project
    └── trace

For Apache I symlinked to /var/www/ubuntu
Tree looks the same as above.
Here is my sh script
#!/bin/bash

# Arch=         -a      # Architecture. For Ubuntu can be i386, powerpc or amd64.
# sparc, only starts in dapper, it is only the later models of sparc.
# For multiple  architecture, use ",". like "i386,amd64"

arch=amd64,i386

# Minimum Ubuntu system requires main, restricted
# Section=      -s      # Section (One of the following - main/restricted/universe/multiverse).
# You can add extra file with $Section/debian-installer. ex: main/debian-installer,universe/debian-installer,multiverse/debian-installer,restricted/debian-installer

section=main,restricted,universe,multiverse

# Release=      -d      # Release of the system (, focal ), and the -updates and -security ( -backports can be added if desired)
# List of updated releases in: https://wiki.ubuntu.com/Releases
# List of sort codenames used: http://archive.ubuntu.com/ubuntu/dists/

release=focal,focal-security,focal-updates,hirsute,hirsute-security,hirsute-updates

# Server=       -h      # Server name, minus the protocol and the path at the end
# CHANGE "*" to equal the mirror you want to create your mirror from. au. in Australia  ca. in Canada.
# This can be found in your own /etc/apt/sources.list file, assuming you have Ubuntu installed.

server=archive.ubuntu.com

# Dir=          -r      # Path from the main server, so http://my.web.server/$dir, Server dependant

inPath=/ubuntu

# Proto=        --method=       # Protocol to use for transfer (http, ftp, hftp, rsync)
# Choose one - http is most usual the service, and the service must be available on the server you point at.
# For some "rsync" may be faster.

proto=rsync

# Outpath=              # Directory to store the mirror in
# Make this a full path to where you want to mirror the material.

outPath=/mnt/USBHDD/mirrors/ubuntu_repository

# The --nosource option only downloads debs and not deb-src's
# The --progress option shows files as they are downloaded
# --source \ in the place of --no-source \ if you want sources also.
# --nocleanup  Do not clean up the local mirror after mirroring is complete. Use this option to keep older repository

# Start script

debmirror       -a $arch \
                --no-source \
                --check-gpg \
                --checksums \
                -s $section \
                -h $server \
                -d $release \
                -r $inPath \

A: After much web surfing I found the answer to my question.
The problem was with Apache's default location.
Guide has it listed as /var/www/ubuntu
Should be /var/www/html/ubuntu
After making that change my mirror is working.
Missing piece to the puzzle was located at:
Created apt-mirror but cannot browse to it from localhost/ubuntu
Props to Arronical


text:
Q: Security, cryptography: Stupid Challenge - Response protocol? Ok guys just a small game:
I have some specifications for a project. At some point they ask for the following to encrypt a password over the net, saying that it is a challenge response protocol:

CLIENT ----------------------------- SERVER

(1)ask for challenge -------------->

(2)    <---------------------------- send SHA1 taken from the time
                                       (this is the challenge)
(3) make SHA1 xor PASSWORD --------> if it's equal to SHA1 xor stored password

(4)    <---------------------------- Grant access

For those who don't know it SHA stands for Secure Hashing Algorithm, a standard algorithm for cryptography.
I hope it's clear. Question is: If I sniff packets 2 and 3 (the "challenge" and the "challenge xor password", I do have the actual password just with another xor between them both!?!? There is other way to implement this kind of protocol??

A: You would be able to reverse engineer the password.  You want to send the SHA of the password, not the password itself.  Rolling your own security protocols is almost never a good idea.  Can you not use SSL or something equivalent?
http://en.wikipedia.org/wiki/Cryptographic_nonce

A: How about the following:

*

*Server sends a random challenge

*Client sends SHA1 checksum of (challenge+password)

*Servers compares against SHA1 checksum of (challenge+stored password)

A: That's a pretty horrible protocol.  If this is something someone wants you to implement, refuse to.  There are existing, vetted protocols for this type of thing.  If this is a game where you point out all the flaws - okay.

*

*Anyone who hears steps 2 & 3 knows the password

*Anyone who hears step 3 and notes the time can brute-force the password if he has any idea of the precision of the time on the server

*I can pretend to be a server (arp poisoning, dns rediction, etc), and get your password, never completing step 4 and feigning a timeout

*Vulnerable to Man in the Middle Attacks because there's no shared secret between client/server or certificates on the server

*Relies on the server storing the SHA1(time) and waiting for a response, so I can overload the server with requests for challenges and never reply.

And I'm definetly missing some more.

A: You are right -- if you capture the challenge and (challenge XOR password) then extracting the password is easy.
You need to use proper encryption in step 3, not XOR.  Encrypt the challenge with the password.
To make an attacker's life harder you could add random data to what you encrypt to: e.g. encrypt paddingCHALLENGEpadding.  The server doesn't care what the padding is, it knows where to look for the challenge, but it means an attacker won't know what the whole plaintext is.

A: As the other's have pointed out, you are correct.  Also keep in mind that someone could intercept communication (3) and potentially resend it while the real user is experiencing network issues (eg: a DDOS), the impostor would then be logged in and often that is sufficient to change the password (that is, many systems don't require that you supply a password inorder to change it once you are logged in).
You may want to consider HMAC (keyed-Hash Message Authentication Code).  I've blogged about it in detail here: http://blog.ciscavate.org/2007/09/creating-a-secure-webauth-system-part-1-hmac.html and I'll give a quick summary below.
HMAC is a method of ensuring that a message was generated by someone with access to a shared secret. HMAC makes use of some sort of one-way hashing function (like MD5 or SHA-1) to encrypt the secret along with a message. This generates a short digest of 16-20 bytes that acts as a fingerprint of the message+secret combination. When the digest is sent along with the message, the receiver (our server) can re-generate the hash with the same HMAC calculation and compare the locally generated digest with the digest that came along with the message. Remember: the server has the secret too, so it has enough information to confirm the digest.  (This only considers the problem of verifying the origin of a message, but you can use the same approach to encrypt the entire message, if you use a different secret, say a set of public keys.)

A: The way I would do this is the following:

*

*Challenge the server.

*Server responds with it's public key
(for, say RSA encryption) digitally
signed.

*Client verifies PK, and encrypts
password with the key, then
digitally signs the encrypted
password.

*Server verifies signing and decrypts
the password to store/check it.
The digital signing is important here as it acts as the beginning of preventing man in the middle attacks.

A: As others have pointed out, yes, this is a poor challenge response algorithm.
You probably want to check out Digest Authentication, as used by HTTP. In fact, if your protocol is over HTTP, you can skip writing your own and just use or implement this.

A: public key encryption? Use the server's public key to encrypt the password.

A: Although it is never a good solution to roll out your own cryptographic protocol, and it is something I would not suggest....
To overcome the problem that you are facing...
F - A function which takes in the password and a pseudorandom monotonically increasing value and returns a number. For e.g. Hash(Hash(Password) ^ Timestamp)

*

*Server : Ask for Challenge, Send (Timestamp). Remember Last Timestamp Sent.

*Client, Send Response (Send F(Password, Timestamp) and Timestamp)

*Server: Check Client by using Hash(Password) and Timestamp sent by the client (> Timestamp sent in Challenge).

*If Client is correct, grant access.

*Ensure present timestamp is greater than all client sent timestamps before next challenge to prevent replay attacks.

Kind regards,
Ashish Sharma

A: I believe the Diffie-hellman is a well-known and solid key exchange protocol?


text: Q: Show Client Source Without Allowing Them to Copy It I have a client that I need to show source code to for his project, but I don't want him to be able to download or copy it easily until I allow him to. Is there a way to upload the code to github or some other place and then have it show up in image format?


text:
Q: AVAudioEngine warning: "deprecated Carbon Component Manager for hosting Audio Units" I'm writing my first audio app for Mac, which loads an external audio unit and uses it to play sound through an instance of AVAudioEngine, and I've been seeing this warning:

WARNING:  140: This application, or a library it uses, is using the
  deprecated Carbon Component Manager for hosting Audio Units. Support
  for this will be removed in a future release. Also, this makes the
  host incompatible with version 3 audio units. Please transition to the
  API's in AudioComponent.h.

I've already transitioned from using AVAudioUnitComponents to AudioComponents (now accessed via this api) which I expected would solve this issue, but I'm still seeing this warning when I call start() on my engine.
Any ideas what's going wrong here? As far as I can tell, I'm no longer using deprecated APIs. Is it possible that AVAudioEngine is using deprecated APIs under the hood?
Here's a snippet from the code I'm working with. I'm calling selectInstrument with a description I've retrieved using the AudioComponents API.
public func selectInstrument(withDescription description: AudioComponentDescription, callback: @escaping SelectInstrumentCallback) {
    AVAudioUnit.instantiate(with: description, options: []) { avAudioUnit, error in
        guard let unit = avAudioUnit else {
            callback(nil)
            return
        }

        self.disconnectCurrent()
        self.connect(unit: unit)

        unit.auAudioUnit.requestViewController { viewController in
            callback(viewController)
        }
    }
}

private func disconnectCurrent() {
    guard let current = currentInstrument else { return }
    self.engine.disconnectNodeInput(engine.mainMixerNode)
    self.engine.detach(current)
    self.currentInstrument = nil
    self.engine.stop()
}

private func connect(unit: AVAudioUnit) {
    let hardwareFormat = self.engine.outputNode.outputFormat(forBus: 0)
    self.engine.connect(self.engine.mainMixerNode, to: self.engine.outputNode, format: hardwareFormat)
    self.engine.attach(unit)
    do {
        try ExceptionCatcher.catchException {
            let stereoFormat = AVAudioFormat(standardFormatWithSampleRate: hardwareFormat.sampleRate, channels: 2)
            self.engine.connect(unit, to: self.engine.mainMixerNode, format: stereoFormat)
        }
    } catch {
        let monoFormat = AVAudioFormat(standardFormatWithSampleRate: hardwareFormat.sampleRate, channels: 1)
        self.engine.connect(unit, to: self.engine.mainMixerNode, format: monoFormat)
    }

    unit.auAudioUnit.contextName = "Running in AU host demo app"
    self.currentInstrument = unit

    do {
        // Carbon Component Manager warning issued here:
        try self.engine.start()
    } catch {
        print("Failed to start engine")
    }
}

Thanks for your help!


text:
Q: Deactivate the link of lookup-fields (2010) On our solution (SP Foundation) we multiple lists with quite some lookup fields. Some of the lookup fields are user fields who link to the user info list, and we don't want that to happen.

Of course, we can limit the access of the (user info) list itself, but it's not a nice solution when the user clicks on the lookup field, and lands on a access denied page.
The question is:
Is it possible to remove the link from the lookupfield? If yes, how?

A: Your best bet would be to remove that field/column from the Public view and all other views where you dont want to see it.
If you still want to see the value, create a calculated column which extracts the value from the lookup column and displays that. use the =TEXT calculated column
Hope this helps.

A: The previous answer is really not a solution it is just workaround. You best bet is not to remove field or create some calculated field o just use what SharePoint can give to you.
First you should create xsl in mapped folder \14\TEMPLATE\LAYOUTS\XSL for example UsersInfoViewStyles.xsl and add content like in image bellow changing field internal name to you lookup field:

Second step is to change XslLink to your created xsl file of view defined in schema.xml file like in image bellow:

This will take off links from you lookup field in view. I hope this helps someone in the future.

A: I used jQuery to remove the links by selecting all anchor tags pointing to the look up list (check the href for each of the look up values and they should all start pointing to some list and have an "ID=" at the end). I then unwrapped it from the tags to just return the text. Here is the code line for my list, but you will of course need to change it to the one your look ups are pointing towards:
$(document).ready(function()
{
     $('a[href*="https://mytest.com/sites/MySite/_layouts/listform.aspx?PageType=4&ListId={DERGERG23THE-CH2E-4Y24-9F9C-434E63RT462RER}&ID="]').contents().unwrap();
});


text:
Q: Simplifying a circuit with an empty wire (that may or may not be in parallel) Determine the value of the resistance R in the circuit shown below, given that Req = 9 ohms.

I called the top-left, top-right and middle-right nodes a, c and b respectively, and did a delta-Y transformation on the 24-ohm, 4-ohm and R resistor. I got that R3 and the 8-ohm resistor are in series, but now I'm completely stuck on trying to figure out how the empty wire in the middle of the circuit gets simplified.
If my understanding of parallel is correct then I think the wire is in parallel with the 30-ohm resistor because both ends connect to each other, so the equivalent resistance would be 0 and I could cancel out the 30-ohm resistor completely. But if that's true, then by the same reasoning wouldn't the wire also ultimately short everything above it including R? And if it's not in parallel with the 30-ohm resistor, how can I simplify anything?

A: your reasoning is correct that the 39 ohm resistor parallell with the wire can be replaced with just the wire.  but there are no other parts that only
parallel the wire.  To elimitate a resistor entirely both ends must be connected to the same node.
from here-on in the solution can  be found by making series and parallel combinations.
I re-drew the circuit without the 30 ohm

simulate this circuit – Schematic created using CircuitLab
every path from A passes through a resistor...
it looks like the next simplification is to combine the 8 and the 24,  and then combine that with the 4 and then that with the 12... etc.

A: Consider this T-shirt showing the crucial part of your circuit:

You can cancel the resistor only if there is some way of going from one end of the resistor to the other end through some wires, without going through any other resistor.
This is obviously true for the 30 Ω resistor.
However, none of the resistors above (or any combination of those resistors) has a wire parallel in this way.
Once you have eliminated the 30 Ω resistor, you can find sufficient series/parallel combinations to simplify, as shown by Jasen's answer.


text:
Q: Выбор изображения из галереи MVVMCross В axml описана кнопка, по клику на кнопку, нужно открыть галерею и передать в ViewModel путь к выбранному изображению.
Реализация в рамках MVVMCross, нужен именно путь, так как он будет сохранятся в бд.

A: В первую очередь необходимо создать обьект, после взаимодействия с которым будет вызван метод CreateImageIntent();
private void CreateImageIntent()
    {
        var imageIntent = new Intent();
        imageIntent.SetType("image/*");
        imageIntent.SetAction(Intent.ActionGetContent);
        StartActivityForResult(Intent.CreateChooser(imageIntent , "Select photo") , 0);
    }

После выбора изображения и закрытия Активити галереи будет вызван метод
protected override void OnActivityResult(int requestCode , Android.App.Result resultCode , Intent data)
    {
        base.OnActivityResult(requestCode , resultCode , data);
        if (resultCode == Android.App.Result.Ok)
        {
            Android.Net.Uri uri = data.Data;
            imgPath.ImageUrl = uri.Path;
            ImgPathHolder.ImgPathString = GetRealPathFromURI(uri);

        }
    }

А метод GetRealPathFromURI(); - вернет нам путь, который можно забиндить к ImageView
private string GetRealPathFromURI(Android.Net.Uri contentURI)
    {
        ICursor cursor = ContentResolver.Query(contentURI , null , null , null , null);
        cursor.MoveToFirst();
        string path = cursor.GetString(cursor.GetColumnIndex(MediaStore.Files.FileColumns.Data));
        cursor.Close();

        return path;
    }