text:
Q: Trimming TikZ grid I have the following picture:

obtained from:
\begin{tikzpicture}
\draw (0,0) grid (4,4);
\draw[invmidarrow=0.5]
(0,0) to[out=110,in=250] (0,2)
(0,2) to[out=70,in=190] (1,4)
(1,4) to[out=10,in=170] (3,4)
(3,4) to[out=-10,in=180] (4,4)
(4,4) to[out=0.in=45] (4,3)
(4,3) to[out=225,in=135] (4,2)
(4,2) to[out=-45,in=190] (4,1)
(4,1) to[out=-10,in=-10] (3,0)
(3,0) to[out=190,in=290] (0,0);
\end{tikzpicture}

with the following key definition:
\tikzset{invmidarrow/.style={postaction=decorate,decoration={markings,mark={at position #1 with {\arrow{latex reversed}}}}}}

and using the decorations.markings library. I would like to know if there are easy ways to:

*

*Trim and extend the grid so that it only fills the curve;

*Add arrows to the grid so that all (or some of) the squares have counterclockwise arrows;

*Add arrow tips every x*(curve length) to the curve, x being a fraction I can choose.

The picture is in Physics notes, where the teacher derived conservativity of the electric field from the nullity of its curl, and is illustrating the process by which we do so, turning the line integral into a sum of line integrals which are then turned into surface integrals of the curl over the single squares, which are imagined to become smaller and smaller.
MWE:
\documentclass[a4paper]{report}
\usepackage{tikz}
\usetikzlibrary{decorations.markings}
\tikzset{invmidarrow/.style={postaction=decorate,decoration={markings,mark={at position #1 with {\arrow{latex reversed}}}}}}

\begin{document}

\begin{tikzpicture}
\draw (0,0) grid (4,4);
\draw[invmidarrow=0.5]
(0,0) to[out=110,in=250] (0,2)
(0,2) to[out=70,in=190] (1,4)
(1,4) to[out=10,in=170] (3,4)
(3,4) to[out=-10,in=180] (4,4)
(4,4) to[out=0.in=45] (4,3)
(4,3) to[out=225,in=135] (4,2)
(4,2) to[out=-45,in=190] (4,1)
(4,1) to[out=-10,in=-10] (3,0)
(3,0) to[out=190,in=290] (0,0);
\end{tikzpicture}
\end{document}

A: Do you want something like this?

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{decorations.markings}
\tikzset{invmidarrow/.style={postaction=decorate,decoration={markings,mark={between positions 0 and 1 step #1
with {\arrow{latex reversed}}}}}}
\begin{document}
\begin{tikzpicture}
\begin{scope}
\draw [clip]
(0,0) to[out=110,in=250]
(0,2) to[out=70,in=190]
(1,4) to[out=10,in=170]
(3,4) to[out=-10,in=180]
(4,4) to[out=0.in=45]
(4,3) to[out=225,in=135]
(4,2) to[out=-45,in=190]
(4,1) to[out=-10,in=-10]
(3,0) to[out=190,in=290] (0,0);
\draw (-1,-1) grid (5,5);
\end{scope}
\draw [thick,invmidarrow=10mm]
(0,0) to[out=110,in=250]
(0,2) to[out=70,in=190]
(1,4) to[out=10,in=170]
(3,4) to[out=-10,in=180]
(4,4) to[out=0.in=45]
(4,3) to[out=225,in=135]
(4,2) to[out=-45,in=190]
(4,1) to[out=-10,in=-10]
(3,0) to[out=190,in=290] (0,0);
\draw[red,invmidarrow=5mm] (1,1) rectangle (3,3);
\end{tikzpicture}
\end{document}

Edit
Putting
\draw[red,invmidarrow=10mm] (1.5,1) -- (1,1) -- (1,3) -- (3,3) -- (3,1) -- cycle;

instead of
\draw[red,invmidarrow=5mm] (1,1) rectangle (3,3);

we get

and we avoid markings on the vertices.


text:
Q: Location of iPhone backup Where does iTunes backup (location) iPhone data on Mac Snow Leopard.
Cannot fine MobileSync\backup in ~/Library/Application Support/

A: Looks like previous iTunes versions (probably with Snow Leopard) backups were in
Users/Name/iTunes/Mobile Backups.
Now there stored users/name/library/application support/mobilesync/backup.
I would assume the older Users/Name/iTunes/Mobile Backups could be deleted if you see
backups also in users/name/library/application support/mobilesync/backup.

A: You can find iPhone back up /Users/<ComputerName>/Library/iTunes/Mobile Backups

A: The confusion may be in the fact that there are more than one Library folders that contain Application Support folders.  The path you want is the /Library/Application Support/ that are contained within your User folder then your home folder (named with your username).
Users/____/Library/Application Support/MobileSync\backup

A: OSX 10.6.8 and iTunes 11 in August 2013, open itunes, go to preferences, navigate to the devices tab and right click on the backup you want to "Show in Finder" voila!
for me it's users > [username] > library > Application Support > Mobilesync
like it's been for years now.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Numerical methods for systems of differential equations There are many methods to solve ordinary differential equations, but what about systems of ODEs?
So far I've seen only two methods mentioned in this context:
Euler's and Runge-Kutta 4th order. Both of them calculate new $y_{i,n+1}$ based only on set of $y_{*,n}$ from the previous iteration.
So are there other numerical methods to solve (possibly non-linear) systems of differential equations?

A: All Runge-Kutta methods, all multi-step methods can be easily extended to vector-valued problems, that is systems of ODE. Some of the order conditions for Runge-Kutta systems collapse for scalar equations, which means that the order for vector ODE may be smaller than for scalar ODE. Methods with that defect are usually not considered, you can find one famous instance, an order 5 method, in the original paper of Kutta.


text:
Q: Filter an item and show x number of oldest records for that item Friends,
I tried to do some patchwork to resolve my task however not successful (no background in programming). So any help would be appreciated.
Background:
Excel spreadsheet with multiple item IDs, one item can have multiple rows associated with it (Unit Number 1 to N). Each row (Unit number) has a date association (repeating or same). For example:
I've 2000 units of item number 10110014 spanning from 04/22/2022 to 07/07/2022. Also, I've another 500 units of item 10112767 spanning from 05/01 to 7/7. It is a live sheet and data will get added daily.
Task:
I want to generate a list of unit numbers based on 2 input parameters - Item ID and number of units:

*

*filter and return the oldest records (based on number of units parameter for the corresponding Item ID)

*copy these records in a new sheet

*delete the returned records from the original sheet.

Let me know how can i achieve this.

A: Copy First n Rows from a Filtered Range

*

*The code needs to be copied to the sheet module of the worksheet whose screenshot is posted in the question, e.g. Sheet1, not into a standard module e.g. Module1.

*There is nothing to run, the code runs automatically.

*Carefully adjust the values in the constants section.

*The rows might be copied only after changing the value in B2 that is if the value in B1 is valid and there are enough items (units).

*You could 'decorate' some of the Exit Sub lines (except the last) with an appropriate message box or Debug.Print line to not wonder why nothing is happening.

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    ' Define constants.

    ' Source
    Const sIdCellAddress As String = "B1"
    Const sUnitsCellAddress As String = "B2"
    Const sFirstCellAddress As String = "A4"
    Const sIdColumn As Long = 1
    ' Destination
    Const dName As String = "Sheet2"
    Const dFirstCellAddress As String = "A2"

    ' Turn off any existing filters.

    If Me.FilterMode Then Me.ShowAllData

    ' Validate the inputs.

    Dim iCell As Range: Set iCell = Me.Range(sIdCellAddress)
    Dim uCell As Range: Set uCell = Me.Range(sUnitsCellAddress)

    Dim irg As Range

    ' Check if the id cell was changed (will not trigger the copy).
    Set irg = Intersect(iCell, Target)
    If Not irg Is Nothing Then
        Application.EnableEvents = False ' to not re-trigger when clearing
            uCell.ClearContents
        Application.EnableEvents = True
        Exit Sub ' the id cell was changed
    End If

    ' Status: the id cell was not changed!

    ' Check if the units cell was changed (may trigger the copy).
    Set irg = Intersect(uCell, Target)
    If irg Is Nothing Then Exit Sub ' units cell was not changed

    ' Status: the units cell was changed!

    ' Check if the id cell is not blank.
    Dim iString As String: iString = CStr(iCell.Value)
    If Len(iString) = 0 Then Exit Sub ' id cell is blank

    ' Validate the units cell.
    Dim uValue As Variant: uValue = uCell.Value
    If VarType(uValue) <> vbDouble Then Exit Sub ' is not a number
    If uValue <> Int(uValue) Then Exit Sub ' is not a whole number
    If uValue < 1 Then Exit Sub ' is zero or negative

    ' Reference the filtered range ('iscvrg').

    ' Reference the source range.
    Dim srg As Range: Set srg = Me.Range(sFirstCellAddress).CurrentRegion

    ' Reference the id data column range (no headers).
    Dim iscrg As Range
    Set iscrg = srg.Columns(sIdColumn).Resize(srg.Rows.Count - 1).Offset(1)

    ' Count the existing items.
    Dim iCount As Long: iCount = Application.CountIf(iscrg, iString)
    If iCount = 0 Then Exit Sub ' no items
    If iCount < uValue Then Exit Sub ' not enough items

    ' Filter the source range.
    srg.AutoFilter sIdColumn, iString

    ' Reference the visible cells of the id data column range.
    Dim iscvrg As Range: Set iscvrg = iscrg.SpecialCells(xlCellTypeVisible)

    ' Remove the filter.
    Me.AutoFilterMode = False

    ' Combine the first n ('uValue') cells into the source union range ('surg').

    Dim isCell As Range
    Dim surg As Range
    Dim n As Long

    For Each isCell In iscvrg.Cells
        n = n + 1
        If surg Is Nothing Then
            Set surg = isCell
        Else
            Set surg = Union(surg, isCell)
        End If
        If n = uValue Then Exit For
    Next isCell

    ' Reference the destination first cell ('dfCell').

    Dim dws As Worksheet: Set dws = Me.Parent.Worksheets(dName)
    Dim difCell As Range: Set difCell = dws.Range(dFirstCellAddress)

    Dim dlCell As Range
    Set dlCell = difCell.EntireRow.Resize(dws.Rows.Count - difCell.Row + 1) _
        .Find("*", , xlFormulas, , xlByRows, xlPrevious)

    Dim dfCell As Range

    If dlCell Is Nothing Then
        Set dfCell = difCell
    Else
        Set dfCell = difCell.Offset(dlCell.Row - difCell.Row + 1)
    End If

    ' Copy and delete.

    With Intersect(surg.EntireRow, srg)
        .Copy dfCell
        Application.EnableEvents = False ' to not re-trigger when deleting
            .Delete xlShiftUp
        Application.EnableEvents = True
    End With

End Sub


text:
Q: Converting compressed data in array of bytes to string Suppose I have an Array[Byte] called cmp. val cmp = Array[Byte](120, -100).
Now, new String(cmp) gives x�, and (new String(cmp)).getBytes gives Array(120, -17, -65, -67) which isn't equal to the original Array[Byte](120, -100). This byte of -100 was part of an Array[Byte] obtained by compressing some string using Zlib.
Note: These operations were done in Scala's repl.

A: When you've got arbitrary binary data, never ever try to convert it to a string as if it's actually text data which has been encoded into binary data using a normal encoding such as UTF-8. (Even when you do have text data, always specify the encoding when calling the String constructor or getBytes().) Otherwise it's like trying to load an mp3 into an image editor and complaining when it doesn't look like a proper picture...
Basically, you should probably use base64 for this. There are plenty of base64 encoders around; I like this public domain one as it has a pretty sensible interface. Alternatively, you could use hex - that will be more readable if you want to be able to easily understand the original binary content from the text representation manually, but will take more space (2 characters for each original 1 byte, vs base64's 4 characters for each original 3 bytes).

A: More like Java, but java.io.ByteArrayInputStream, java.util.zip.InflaterInputStream and java.io.DataInputStream can be used.
import java.io._

val bis = new ByteArrayInputStream(cmp)
val zis = new InflaterInputStream(bis)
val dis = new DataInputStream(zis)
val str = dis.readUTF()

To go backwards,
val bos = new ByteArrayOutputStream()
val zos = new InflaterOutputStream(bos)
val dos = new DataOutputStream(zos)
dos.writeUTF(str)
val cmp = bos.toArray


text:
Q: Is there only one counter example in $K_5$ for $R(3,3)$? Title says it all. And the one that I know is below. (image from wikipedia)

My question is: Is there only one counter example in $K_5$ for $R(3,3)$ where $K_5$ is a complete graph of 5 points and $R(s,t)$ is Ramsey number.

A: Yes, try it yourself. If you start out with one node connected to 3 or 4 edges of the same colour, you will find it impossible to complete the graph.
Hence every node must be connected to two red and two blue edges. Starting with this, and keeping this rule for every node, you are forced to end up with the coloring of $K_5$ you've shown. You'll notice you will have a choice for one edge, but both will lead to either the coloring you've shown or one that looks different, but is in fact isomorphic to the one you've shown (two nodes have just moved around).

A: Another way to think about it: How many graphs $G$ are there on 5 vertices such that both $G$ and $\overline{G}$ are triangle free?
$C_5\cong\overline{C_5}$ is the only answer.

A: This coloring has the property that

each vertex is incident to exactly two red edges and two blue edges. (Property $X$)

Any $R(3,3)$ coloring of $K_5$ must have this property.  For suppose we had an $R(3,3)$ coloring of $K_5$ that did not have property $X$.  Then there is some vertex $v$ with at least three edges of the same color, say red.  These three edges are also incident to vertices $u_1, u_2, u_3$.  Each edge $u_i-u_j$ must be blue, or else $v, u_i, u_j$ would be vertices of a red triangle.  But then $u_1, u_2, u_3$ are vertices a blue triangle.  So any $R(3,3)$ coloring must have property $X$.
Now consider the subgraph consisting of just the red edges.  Every vertex in this subgraph has degree 2.  It is an easy theorem that such a graph is a union of disjoint cycles.   In this case, there can't more than one cycle because that would require at least 6 vertices and we have only 5.  So the red edges must form a single cycle of length 5.  We can then arrange the vertices so that this cycle is the outer pentagon, as you did, and then the blue edges must be the inner pentagram, also a cycle of length 5.


text:
Q: Tivoli workload scheduler - background job I have the following problem about running a job in background, this is a backup job, I know TWS tells you not to run a job in background but in my scenario I have no other option but to run it in background, this is because I have a lot of scripts and used to run manually but now needs to automate and schedule with tws.
The idea I have is to create a job that validates the backup background job and waits until the background job is finished, only then it will continue its normal flow.
Any idea how to do it? or maybe TWS has an option to do this.
Thanks.

A: basically TWS uses the $TWS_HOME/jobmanrc file as a wrapper to launch the script defined in a job, redirect script logs to TWS stdlist and handles the return code to manage dependencies with other jobs/schedules.
you can have a look at that jobmanrc file, it's pretty simple to read.
that said, if your background job is not launched using TWS, no chance to have it's return code managed by TWS. you can create a technical job running a script every n minutes to monitor your background job with an exit code >0 until it is running ( ps aux|grep  && exit 1 ) and put a success dependency on your following schedules, but it's dirty.


text:
Q: Legends with multiple rows in Matlab How to create a legend with multiple rows or fit a legend within the plotting area. Following is my code and output plot
figure;
col = jet(numel(node_id_without_duplicates));
%legend('Node ');

for i=1:numel(node_id_without_duplicates)
    specific_node = node_id_without_duplicates(i);
    legendInfo{i} = ['Node ', num2str(specific_node)];
    MTBF_Specific_Node; //This is the call of an another tool created by me and not included in this example.
end
legend(legendInfo);

A: You can use gridLegend on FEX. It uses undocumented hidden axes property ScribeLegendListeners, for details please see "Multi-column (grid) legend" on Undocumented MATLAB.
I totally agree with gnovice: the plot is overloaded, rethink it to be more helpful and informative. However, if you want readers to understand nothing and say "Wow, it seems to be a hard task" the plot is just correct.


text:
Q: Redirecting old php pages on IIS 7.5 Apologies if this has already been covered. It seems redirecting/rewriting URLs is easy, hosting PHP is easy, but redirecting PHP on IIS is a bit of a pain. Basically I am trying on a IIS server to redirect requests for any php page to default.aspx
I believe the main problem is that out-of-the-box IIS doesn't want to serve PHP.
Steps that I covered so far include

*

*Writing a rewrite rule that does a regex match on any php file and pass it to default.aspx

*Adding *.php to the handlers and using the same one defined for *.aspx

*Restarting the server

*Hitting head against brick wall

I don't want to have to install FastCGI or equivalent just to do this - I just want to be able to handle any php pages that used to reside on the domain and point them at default.aspx
Any suggestions/advice welcome!

A: Have you tried the web.config.txt this is like .htaccess on an APACHE server. I don't know what your trying to rewrite, but here is a simple template to get you started.
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Redirect to WWW" stopProcessing="true">
          <match url=".*" />
          <conditions>
            <add input="{HTTP_HOST}" pattern="^carlosag.net$" />
          </conditions>
          <action type="Redirect" url="http://www.carlosag.net/{R:0}" redirectType="Permanent" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

A: The basic PHP redirection function used for this purpose is header, you can check it in the manual.
http://php.net/manual/en/function.header.php
Basically is:
header('Location: http://iis.default.com/home.aspx');


text:
Q: Laravel - Trying to update data in controller data in view with button click I normally use Laravel for pure API backend calls only, however, recently I require the need to build some simple front end views for my app.
Normally working with AngularJS for anything front end, I thought Laravel and blade would be similar, but I seem to be struggling with (what I thought) was basic functionality.
My use case is this:
I have some tabled data displayed on a view ($data).  Also on my view I have a start date ($startDate) and an end date ($endDate), all of which I pass in from the controller using the ->with() statement.  I am assuming this is the best way?
return View::make( 'reports' )->with( ['data' =>$data, 'startDate' => $startDate, 'endDate' => $endDate] );

I am trying to achieve the functionality of clicking on a back button or a forward button and having both the $startDate and $endDate shift forward or back a week and returning a new set of $data.
Is there a simple way of achieving this?


text:
Q: jQuery - Adding classes to elements inside array with delay I have an array that contains some elements from my page.
Now I need a function that literates through the array and adds a class bold to each element. The problem is that once the class is added, some time has to pass. Then bold has to be removed and needs to be applied to the next element, resulting in a "wave" motion.
I've tried to do it like this:
$.each(tdArr, function(i, v) {
  v.addClass("bold");
  setTimeout(function(){
    v.removeClass("bold");
  }, 900)
})

The problem with that code is that bold is added to all elements at once and gets removed 900 ms later, again from all elements at the same time.
What do I have to do to add a delay between the separate actions?

A: I think you need to approach this slightly differently, as setTimout returns straight away it wont stop the next element being set as bold.
You could do it with a method like this:
function bold(i){
    if(i>0){
        $tdArr.eq(i-1).removeClass('bold');
    }
    if(i == $tdArr.length){
        return;
    }
    $tdArr.eq(i).addClass('bold')

    setTimeout(function() { bold(i+1) },900);
}

And then to call it you'd just need to call bold(0):
Live example: http://jsfiddle.net/rJGjZ/

A: Try this:
$.each(tdArr, function(index, element) {
  var $elem = $(element);
  $elem.addClass("bold");
  setTimeout(function(){
    $elem.removeClass("bold");
  }, 900)
})

The second param is not a jQuery element and you need convert him

A: Increase the delay as you iterate the array, and make sure to wrap your element in jQuery if it's not already wrapped. If it's a collection of jQuery elements, then use each to iterate.
var delay = 900

$els.each(function(){
  var $this = $(this)
  setTimeout(function(){
    $els.removeClass('bold')
    $this.addClass('bold')
  }, delay+=900)
})

Otherwise, I would use for and wrap the element in jQuery.
for (var i=0, l=arr.length, d, prev; i<l; i++; d+=900) {
  prev = arr[i-1]
  setTimeout(function(){
    if (prev) $(prev).removeClass('bold')
    $(arr[i]).addClass('bold')
  }, d)
}

A: Would something like this work for you ?
function Bold(element) {
  $(element).addClass("bold"); // we bold the current tdArr
  setTimeout(function(){
    var nextSibling = $(element).next("td") // (if the tdArr are "td" tags) we find the next td brother of this one
    if (!!nextSibling) Bold(nextSibling); // if there is a brother, repeat the function on him after 900ms
  }, 900)
}

Bold(myfirsttd);


text:
Q: Uncaught Error: Call to undefined method stdClass::update() even though the method is definitely defined I'm getting

Uncaught Error: Call to undefined method stdClass::update()in
  /Applications/XAMPP/xamppfiles/htdocs/gallery/admin/includes/content.php:14
  Stack trace: #0
  /Applications/XAMPP/xamppfiles/htdocs/gallery/admin/index.php(11):
  require_once() #1 {main} thrown in
  /Applications/XAMPP/xamppfiles/htdocs/gallery/admin/includes/content.php
  on line 14.

However, the method update() is defined. Here is the user class:
class User {
    public $username;
    public $password;
    public $first_name;
    public $last_name;

    public static function find_query($query) {
        global $db;

        $obj_arr = NULL;

        if($db -> query($query) -> num_rows != 1) {
            $users = $db -> query($query);

            while($user = $users -> fetch_object()) {
                $obj_arr[] = $user;
            }

            return $obj_arr;
        } else {
            return $db -> query($query) -> fetch_object();
        }
    }

    public static function find_all() {
        return self::find_query("SELECT * FROM users");
    }

    public static function get_user_byId($id) {
        return self::find_query("SELECT * FROM users WHERE id=$id LIMIT 1");
    }

    public static function verify_user($username, $password) {
        global $db;

        $username = $db -> escape_string($username);
        $password = $db -> escape_string($password);

        $q = "SELECT * FROM users WHERE username='$username' AND password='$password' LIMIT 1";

        return self::find_query($q);
    }

    public function create() {
        global $db;

        $username = $db -> escape_string($this -> username);
        $password = $db -> escape_string($this -> password);
        $first_name = $db -> escape_string($this -> first_name);
        $last_name = $db -> escape_string($this -> last_name);

        $q = "INSERT INTO users (username, password, first_name, last_name) ";
        $q .= "VALUES ('$username', '$password', '$first_name', '$last_name')";

        if($db -> query($q)) {
            $this -> id = $db -> insert_id();

            return true;
        } else {
            return false;
        }
    }

    public function update() {
        global $db;

        $id = (int) $id;

        $username = $db -> escape_string($this -> username);
        $password = $db -> escape_string($this -> password);
        $first_name = $db -> escape_string($this -> first_name);
        $last_name = $db -> escape_string($this -> last_name);

        $q = "UPDATE users SET username='$username', password='$password', first_name='$first_name', last_name='$last_name' ";
        $q .= "WHERE id=$id";

        //return (mysqli_affected_rows($db -> db) == 1) ? true:false;
        return ($db -> db -> affected_rows == 1) ? true:false;
    }
}

I have called update like so:
$user = User::get_user_byId(4);
$user -> password = 'newpass';
$user -> update();

The other methods work fine, just update(). Is this an instantiation problem perhaps? I'm so sorry if this is a stupid question. I have looked on here for answers but can't find anything relevant enough to solve the problem. Thanks.

A: You should use:
return $db -> query($query) -> fetch_object("User");

fetch_object() by default returns a Standard Class (stdClass) object. That's why you're getting a Call to undefined method stdClass::update(). You can provide the desired Class name by passing its name in the first argument of the function.

A:
User::get_user_byId

gives you not an instance of the class User. So $user don't have any methods of Class User.
You have to make an instance of the Class User like

$user = new User();

an than you can use the Methods like

$user->update();


text:
Q: Checking the time difference between two php DateTime objects I am checking a difference between two timestamps returned from a database. Here is the code I'm using for this:
$startDate = new \DateTime($last14[$item]->started);
$endDate = new \DateTime($last14[$item]->finished);
$interval = $startDate->diff($endDate);

This returns the DateInterval object and it is correct.
Now the problem is I need to count all occurrences of the difference being over 13 hours. 13 hours dead is OK but 13 hours and 1 minutes needs counting. I have created a messy nested if lump:
if ($interval->h > 12) {
    if ($interval->i > 0) {
        $count++;
    } else {
        if ($interval->h > 13) {
            $count++;
        }
    }
}

This appears to work but I was wondering if there is a better (cleaner) method of doing this. I have considered converting the time difference to minutes and just doing:
if ($minutes > $minutesIn13Hours) {
    $count++;
}

but that's another conversion step.
Any other ideas?

A: if ($interval->h * 60 + $interval->i > 13*60) {
    $count++;
}

A: You will have less conditions to check if you do something like this:
if ( ($interval->h * 100) + $interval->i > 1300 ) {
            $count++;
}

A: I suppose the most clean, most readable and hopefully faster way of doing what you ask is this:
if (($interval->h > 12 && $interval->i > 0) || $interval->h > 13) {
  $count++;
}

Though, I suppose it will not be much faster than your first solution (if it is faster...).
P.S.: Probably @RST solution will be a even little faster, but, since you ask for a cleaner solution, this is for sure more clear...

A: Or simply add 13 hours to start date then compare to end date.
if($endDate > $startDate->add(new DateInterval('PT13H'))) {
    $count++; // got it
}

More clean, readable, reliable, and safer. Probably better (in speed) than diff, btw.


text:
Q: How to make webkit SessionStore to work with database? I would like to create a python class to work with SessionStore class of WebKit server to save session data to database, are there somebody know how to do it? Thanks in advance.
YH

A: One way to do this would involve using class inheritance .
class SessionStoreDb(Webkit.SessionStore):
    def storeSession_db(self, session):
        #use this method to store session data in your database

This will create a new class SessionStoreDb which 'inherits' all the methods of Webkit.SessionStore and adds a new method storeSessoin_db.


text:
Q: Confused about Big O notation I have two questions:
public static void method1(int[] a, int[] b) {
   int sum1 = 0, sum2 = 0;

   for(int i = 0; i < a.length; i++) {
      sum1 += a[i];
   }

   for(int i = 0; i < b.length; i++) {
      sum2 += b[i];
   }
}

Question 1: Is this in O(n)? Does it matter how many loops (not nested loops) are in method1?
Question 2: What if there is a
Arrays.sort(a);

inside the method1, what function is it?

A:
Question 1: Is this in O(n)?

That's correct (here, n denotes the length of each of the two arrays).

Does it matter how many loops (not nested loops) are in method1?

It doesn't, as long as the number of loops is fixed, and the number of iterations in each loop is linear in n. More formally, if C is some constant, C*n is O(n).

Question 2: What if there is a Arrays.sort(a);

Sorting is usually O(n logn), and this is what Arrays.sort(int[]) does on average. The documentation is vague about the worst-case performance:

This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.

This clearly stops short of guaranteeing O(n logn) in the worst case. Reading between the lines suggests that it's probably O(n^2).
It is interesting to note that in JDK7, Arrays.sort(Object[]) uses a different algorithm to the one used by Arrays.sort(int[]). The former is an adaptation of TimSort, and should therefore guarantee O(n logn) worst-case performance. Unfortunately, the documentation again stop short of spelling this out.

A: *

*a. It's O(n) where n = length of input (total)
b. Yes it matters how many loops are there: if it's a constant number of loops k then it's O(k*n) which is usually considered as O(n) but if k >= n it's something that should be taken into account

*Arrays.sort(a); is implemented using merge sort which is running in O(n log n) both in average and worst case (not like NPE said!).
Update for MrSmith42:
From http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html:
the algorithm used by sort(Object[]) does not have to be a MergeSort, but it does have to be stable.)
And also:
Implementation note: The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.


text:
Q: nothing published to artifactory using gradle artifactory plugin I followed the solution given here: upload artifact to artifactory using gradle, but it is not working for me.
Here is my code:
apply plugin: 'artifactory'
apply plugin: 'maven-publish'

/* Specify the repositories to be used for downloading artifacts */
repositories {
    maven {
        url = "${artifactory_contextUrl}/repo"
    }
}
/* Define the repository (in artifactory) where artifactoryPublish task should publish */
artifactory {
    contextUrl = "${artifactory_contextUrl}"
    publish {
        repository {
            repoKey = "${artifactory_repoKey}"
            username = "${artifactory_user}"
            password = "${artifactory_password}"
        }
    }

    defaults {
        publications ('integTestPublish')
    }

}
publishing {
    publications {
        integTestPublish(MavenPublication) {
            setArtifactId(project.name + '-' + integTestJar.appendix)
            artifact integTestJar.archivePath
        }
    }
}

The error is:
> Could not find method defaults() for arguments [build_3a14r6bjhcvi883gaucf1jd8f0$_run_closure1_closure5_closure9@71bc1581] on root project 'samples'.

GAV used for artifactory plugin is:
classpath group: 'org.jfrog.buildinfo', name: 'build-info-extractor-gradle', version: '2.1.0'

What is wrong here ? can someone point me to DSL/API doc of artifactory plugin version 2.1.0
My gradle version is 1.11

A: As explained in the user guide, artifactory plugin of version 2.X is intended to work with maven plugin, not maven-publish plugin. For working with publications please use artifactory-publish plugin of version 2.X, or, preferably, use version 3.0 of com.jfrog.artifactory plugin. It is intended to work with maven-publish publications and compatible both with Gradle 1 and Gradle 2.
This answer contains a fully working example.


text:
Q: Error when compiling Caffe on OSX 10.12.1 I followed the instruction here and the file compilation is fine. But when it gets into the linker stage, I got the following error:
AR -o .build_release/lib/libcaffe.a
LD -o .build_release/lib/libcaffe.so.1.0.0-rc3
clang: warning: argument unused during compilation: '-pthread'
ld: library not found for -lopencv_core
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [.build_release/lib/libcaffe.so.1.0.0-rc3] Error 1

I searched online but found nothing about this issue
Can anyone help me out?
I installed opencv3 in addition to opencv using brew install --HEAD opencv3
You can find my Makefile.config in this post.
Thanks in advance!


text:
Q: Wordpress returning double values for get_author I took over a Wordpress site and noticed a weird bug. Despite echoing a single get_author() on posts, the pages are displaying doubles for the author (i.e., AuthorAuthor).
Any idea why this may happen?

A: The function may display the content already so echoing it will produce the name twice. Remove the echo, or use get_the_author().


text:
Q: How to get "double.class" by a "Double" Object description:

*

*I need use getMethod, it requires the parameterTypes.

*The origin method requires double (a primitive type, not Double), and I can't change origin method.

*I can't just input double.class in parameterTypes, because the s maybe diffierent types, such as Integer(not int).

*The method parameter in Foo.java are always and only primitive types.

code:
test.java
    public static void main( String args[] )
    {
        Object obj = new Foo();
        Object s = 1.2;
        String type = "Double";
        try {
            Method method = obj.getClass().getMethod("return" + type, s.getClass());// got NoSuchMethodException here, because it requires `double` not Double
            System.out.println(method.invoke(obj,s));
        } catch (NoSuchMethodException | IllegalAccessException |InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
Foo.java //(I can't change/add code/delete in this part)
public class Foo {
    public double returnDouble(double type){
        return type;
    }
    public int returnInt(int type){
        return type;
    }
}

what I have tried:

*

*Use Map

    public static void main( String args[] )
    {
        Object obj = new Foo();
//        Object s = 1;
//        String type = "Int";
        Object s = 1.2;
        String type = "Double";
        Map<String, Class> methodClassMap = new HashMap<String, Class>() {{
            put("Double",double.class);
            put("Integer",int.class);
        }};
        try {
            Method method = obj.getClass().getMethod("return" + type, methodClassMap.get(s.getClass().getSimpleName()));
            System.out.println(method.invoke(obj,s));
        } catch (NoSuchMethodException | IllegalAccessException |InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

*

*It worked, but I have to list all possible type of value the s.

question:

*

*Any better solution than using Map? Maybe use generic?

A: When you know beforehand that the target method always uses a primitive types, you can use the unwrap() method of MethodType of the java.lang.invoke package.
Object obj = new Foo();
Object s = 1.2;
String type = "Double";
try {
    MethodType mt = MethodType.methodType(s.getClass(), s.getClass()).unwrap();
    Method method = obj.getClass().getMethod("return" + type, mt.parameterArray());
    System.out.println(method.invoke(obj, s));
} catch(ReflectiveOperationException e) {
    e.printStackTrace();
}

Alternatively, when you're already using the method type of the java.lang.invoke package, you can also use a method handle to perform the invocation.
Object obj = new Foo();
Object s = 1.2;
String type = "Double";
try {
    MethodType mt = MethodType.methodType(s.getClass(), s.getClass()).unwrap();
    MethodHandle mh = MethodHandles.lookup().bind(obj, "return" + type, mt);
    System.out.println(mh.invoke(s));
} catch(Throwable e) {
    e.printStackTrace();
}

But note that unlike Reflection, the return type has to be correctly specified for the lookup. I'm assuming the same return type as the parameter type, like in your example.


text:
Q: Kleene $\models^{x_1 x_2 ... x_n}$ Mathematical Logic by Kleene page 107

As I understand for one variable $\forall x.A(x)$ it means that instead of considering all possible logical functions for $A(x)$ we need to choose only the function $I(x)=true$ for all values of $x$.
$A_1,...,A_m\models^{x_1...x_q}B \equiv \forall {x_1,...,x_q}.A_1,...\forall {x_1,...,x_q}.A_m \models B$ - if I got it right.
I see no difference between $\forall{x,y}.A(x,y)$ and $\forall{x}.A(x,y)$ because logical function $I(x,y)$ for $\forall{x}.A(x,y)$ always $true$ regardless of $y$ and the same holds for $\forall{x,y}.A(x,y)$
I can't get the difference between $A_1,...,A_m\models^{x_1...x_q}B$ and $A_1,...,A_m\models^{x_1...x_qx_{q+1}...x_r}B$


text:
Q: Can't change the name of the legend I have a dataset like these

Region
Greenspace
Bluespace

North
30
5

South
50
10

West
15
2

East
10
1

data <- data.frame (  stringsAsFactors = FALSE,
  Region = c("North", "South", "West", "East"),
  Greenspace = c(30,50,15,10),
  Bluespace = c(5,10,2,1)
)

I want to create a histogram showing the regions in the x-axis and percentage in the yaxis. I used that code
data %>% pivot_longer(cols = Greenspace:Bluespace) %>% ggplot(aes(x = Region, y = value, fill = name)) + geom_col(position = 'dodge') + ggtitle("Contrast between 4 different region areas for Greenspace and Bluespace") + xlab("Region") + ylab("percentage")+ scale_fill_manual(values=c("blue", "dark green"))

Now the problem is instead of name i want space in the legend. I change fill into name but got error message could not find space.
But the problem is i don't want name, I want space
Has anyone an idea how to fix it. I appreciate every help :)

A: That's what labs is for. You can assign names to the different aesthetics, which will then be shown as the title of this aesthetic:
library(tidyverse)
data %>%
  pivot_longer(cols = Greenspace:Bluespace) %>%
  ggplot(aes(x = Region, y = value, fill = name)) +
  geom_col(position = 'dodge') +
  ggtitle("Contrast between 4 different region areas for Greenspace and Bluespace") +
  scale_fill_manual(values = c(Bluespace = "blue",
                               Greenspace = "dark green")) +
  labs(x = "Region", y = "percentage", fill = "space")

Created on 2022-08-23 by the reprex package (v2.0.1)
I think this becomes clear when looking at the x and y aesthetic, which you labeled using the special functions xlab and ylab. If you put this within labs the axis titles change. As a side note, you can remove the title of an aesthetic by setting, for example, labs(fill = NULL) or labs(fill = "").


text:
Q: PyСharm. Cannot run Black Formatter as external tool. Access denied Black formatter setup as External Tool. When I run External Tool->Black I get an error message:
Cannot run program "c:\users\kakal\appdata\local\packages\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\localcache\local-packages\python39\site-packages\black" (in directory "C:\my_python_projects\Geo"): CreateProcess error=5, Access denied
but if i run from Administrator command line everything is ok.
Does anybody know, how to fix it?

*

*PyCharm 2022.1.1 (Professional Edition)

*Black Formatter 22.3.0

*Windows 10 Pro 21H2


text:
Q: Use SceneKit to render an CVOpenGLTextureRef I am using AVCaptureSession, and outputting a CVOpenGLTextureRef at 60fps, which I need to display using SceneKit.
I'm fairly sure I should be using the SCNProgramDelegate method bindValueForSymbol: but can't quite figure out the mechanism to bind the texture ref. The examples I have seen use a GLKTextureInfo object, and bind its name property with the call to glBindTexture().
What is the equivalent mechanism to do this with an CVOpenGLTextureRef?

A: A relatively easy solution may be to use AVCaptureVideoPreviewLayer. You can set it directly as the contents of the diffuse material of the geometry you want to display the frames on, and you get the benefits of all the optimisation work that Apple have (probably) done for this. AVFoundation and SceneKit will handle all the details for you.
If you are doing work on the CPU to the incoming buffer, there's also the lower level AVSampleBufferDisplayLayer class, which lets you pass CMSampleBufferRef objects, which you can build from a CVPixelBufferRef. It's a bit more difficult to feed and care for, but not impossible.


text:
Q: Prevent app from being launched at boot if manually launched by user I've set my application to be launched at system startup and it does so. The problem is that it takes about ~30 seconds between the homescreen showing up and my app to be launched. This may be a problem if the user doesn't wait.
My idea is to prevent the app from being re-launched when the system broadcasts the message IF it is already running.
So, basically, I'm looking for either solution:

*

*Decrease wait time between system start and app start AND / OR;

*Prevent app from being launched when the message is received if it is already running.

The first topic is something I want to achieve regardless, but I don't control when android will fire the message. If I could achieve both, it would be great, but I'd settle for the second option.

I don't think it's necessary to show this, but I've set everything in the Manifest (i.e BOOT_COMPLETED) and this is my code, where MyNamedActivity is my main activity (working code):
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED) && AppController.getUsuarioLogado() == null) {
        Intent i = new Intent(context, MyNamedActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
}

Note: Removing addFlags line causes the app to cash.


text:
Q: How to loop through a nested array and retrieve values I have the following array:
 my_tst = [
    [
        {
            "name": "shield",
            "version": "8.6.3"

        },
        {
            "name": "bosh-dns",
            "version": "1.17.0"
        },
        {
            "name": "nessus_agent",
            "version": "1.0.24"
        },
        {
            "name": "node-exporter",
            "version": "4.2.0"
        },
        {
            "name": "syslog",
            "version": "11.6.1"
        }
    ],
    [
        {
            "name": "shield",
            "version": "8.6.3"
        },
        {
            "name": "bosh-dns",
            "version": "1.16.0"
        },
        {
            "name": "nessus_agent",
            "version": "1.0.24"
        },
        {
            "name": "node-exporter",
            "version": "4.2.0"
        },
        {
            "name": "syslog",
            "version": "11.6.1"
        }
    ]
]

I am trying to loop through the array and output only the values of name.
I used this loop:
my_tst["name"].each do |run|
    p run
end

The loop is returning an Error:
TypeError: no implicit conversion of String into Integer

How do I output all values in the nested array?

A: You're trying to use [] in an array, which is meant to be used passing a numeric parameter in order to access its elements by their index. You're passing a string, which is the way you get values from hashes, and there's the problem.
You have an array of arrays containing hashes (with an interesting indentation), so in that case you need to first iterate the "main" array, to be able to get the hashes over each array.
This is one way you can achieve that:
my_tst.each_with_object([]) do |e, arr|
  e.each { |f| arr << f[:name] }
end
# ["shield", "bosh-dns", "nessus_agent", "node-exporter", "syslog", "shield", "bosh-dns", "nessus_agent", "node-exporter", "syslog"]

Or:
data.flat_map do |e|
  e.map { |f| f[:name] }
end

Anyway, there's going to be a nested iteration.


text:
Q: Input Validation for a String in C I'm trying to make a loop that does not stop until the user inputs a string. For ex. if the user inputs a number or a letter it will say Invalid input until the user enters a string.
But for some strange reason, when I run my code and I input a string, the program continues to loop the block of code. Here's the output
#include <stdio.h>

int main() {
    char name[100];
    char letter[100];

  lt:
    printf("\033[0;33m");
    printf("\nEnter your Name:\ni.e. Miguel\n");
    printf("\033[0m");
    scanf("%s", name);
    if (name != letter) {
       printf("\033[0;31m");
       printf("Invalid input");
       printf("\033[0m");
       goto lt;
    }
    return0;
}

I've tried the goto function to loop the code but seems like that isn't working.

A: Uninitialized variables:
char letter[100];

letter is used uninitialized in your code. It's contents are indeterminate. Variables declared with automatic storage aren't implicitly initialised to 0.
Comparing strings:
if (name != letter)

This only compares the pointer addresses (and I believe it invokes undefined behavior), not the contents of the what those pointers point to.
The C standard library provides a function strcmp that compares two strings.
Note: It's declared in string.h.
Buffer overflow vulnerability:
scanf("%s", name);

is similar to using gets (in terms of limiting input). scanf will happily continue to read from stdin until it sees a whitespace, ignore everything to the right hand side of the whitespace, (which leads to more problems down the road) and potentially overflow the buffer.
You could use a field width to limit input:
scanf("%99s", name);

Or even better, use fgets.
fgets(name, sizeof(name), stdin);

It will read at most n - 1 characters and null-terminate the string.
Side-note: fgets will store the \n character in the buffer, which might not be what you want. Here's one way to remove it¹:
name[strcspn(name, "\n\r")] = '\0';

scanf returns the number of successful conversions:
Ignoring the return value of scanf gainsays the 6th commandment of  Henry Spencer's "The Ten Commandments for C Programmers":

If a function be advertised to return an error code in the event of
difficulties, thou shalt check for that code, yea, even though the
checks triple the size of thy code and produce aches in thy typing
fingers, for if thou thinkest ``it cannot happen to me'', the gods
shall surely punish thee for thy arrogance.

if (scanf("%99s", name) != 1) {
   handle the error here..
}

Using goto:
While that is a legal use, it's discouraged. goto should not be used for such purposes.
Instead, as @SimonGoater suggested, use a while loop.

if the user inputs a number or a letter it will say Invalid input
until the user enters a string.

So the requirements are:

*

*Names should be greater than 1 character.

*Names shouldn't have any numbers in them. (But my friends have names with numbers, and even special characters. :-( )

Note:

*

*You can't have a string with one char, unless that char is a null-byte.

Possible Solutions:

*

*As strlen doesn't include the null-terminator, we can use it to calculate the length of the string, and if it equals 1, handle the error accordingly.

*Iterate through the buffer character by character, and if you find a number or a special character, handle the error accordingly.
[1] You might want to give this a read for more:
https://codereview.stackexchange.com/q/67608

A: #include <stdio.h>
#include<conio.h>
#include<string.h>
int main(){
char name[100];
char letter[100]="amir";

lt:
printf("\033[0;33m");
printf("\nEnter your Name:\ni.e. Miguel\n");
printf("\033[0m \n");
scanf("%s",name);
if(strcmp(name, letter) != 0){
   printf("\033[0;31m");
   printf("Invalid input");
   printf("\033[0m");
   goto lt;
 }
return 0;
}


text:
Q: Change name column 'created_at' and 'updated_at' in user table in Laravel 8 Hello I'm new in code and I try to change the name columun of created_at and updated_at in User table.
I see other tuto and he write in model :
Change name of Laravel's created_at and updated_at
const CREATED_AT = 'post_date';
const UPDATED_AT = 'post_modified';

But for me in User model I write :
class User extends Authenticatable
{
    use Uuid;
    use HasApiTokens,HasFactory, Notifiable;

    const CREATED_AT = 'registered_on';
    const UPDATED_AT = 'modify_on';
}

But when I try the migration the column 'created_at' is here and no the 'registered_on'.
Any ideas ?

A: you have just changed the model's column name.
you have to change the migrations too:
remove the ->timestamps() and add the registered_on & modify_on column, like below:
$table->timestamp('registered_on');
$table->timestamp('modify_on');

Note: to remove function is timestamps() with s
Then run:
php artisan migrate:refresh

to rebuild all of the tables


text:
Q: nested form has many through rails4 I'm not getting the expected results, the Skills are not getting saved. I want to allow each person to have say a primary skill ONLY 1.
DB
  # Table name: people
  #
  #  id          :integer          not null, primary key
  #  first_name  :string(255)
  #  last_name   :string(255)
  #  headline    :string(255)
  #  description :string(255)
  #  user_id     :integer
  #  created_at  :datetime
  #  updated_at  :datetime
  #

  # == Schema Information
  #
  # Table name: skills
  #
  #  id          :integer          not null, primary key
  #  title       :string(255)
  #  description :text
  #  created_at  :datetime
  #  updated_at  :datetime
  #

  # == Schema Information
  #
  # Table name: entity_skills
  #
  #  id          :integer          not null, primary key
  #  skill_id    :integer
  #  person_id   :integer
  #  created_at  :datetime
  #  updated_at  :datetime
  #

Models
class Person < ActiveRecord::Base
  has_many :entity_skills
  has_many :skills, through: :entity_skills, foreign_key: "person_id"
  accepts_nested_attributes_for :skills
end

class Skill < ActiveRecord::Base
 has_many :entity_skills
 has_many :people, through: :entity_skills, foreign_key: "person_id"
end

class EntitySkill < ActiveRecord::Base
  belongs_to :person
  belongs_to :skill
end

Controller
def new
  @person = Person.new
  @all_skills = Skill.all
  @entity_skills = @person.skills.build

end

def edit
  @all_skills = Skill.all

  @entity_skills = @person.entity_skills.build
end

def create
  @person = Person.new(person_params)

  respond_to do |format|
    if @person.save
      format.html { redirect_to @person, notice: 'Person was successfully created.' }
      format.json { render action: 'show', status: :created, location: @person }
    else
      format.html { render action: 'new' }
      format.json { render json: @person.errors, status: :unprocessable_entity }
    end
  end
end

 def person_params
  params.require(:person).permit(:first_name, :last_name, :headline, :description, :user_id, :employer_id, skills_attributes: [:id])
end

Form
<%= form_for(@person) do |f| %>
  ....
  ....

Skills

    <%= f.fields_for @entity_skills do |es| %>
        <%= es.label "All Skills" %>
        <%= collection_select(:skills, :id, @all_skills, :id, :title) %>
    <% end %>

    <%= f.submit %>

<% end %>

Nothing is being saved for the skills,  Can someone explain what is going on?

A: DB
  # == Schema Information
  #
  # Table name: entity_skills
  #
  #  id          :integer          not null, primary key
  #  skill_id    :integer
  #  person_id   :integer
  #  created_at  :datetime
  #  updated_at  :datetime
  #  position    :integer
  #

Controller
  def new
    @person = Person.new
    @all_skills = Skill.all
    5.times {@person.entity_skills.build}
  end

  def create
    @person = Person.new(person_params)
    respond_to do |format|
      if @person.save

        format.html { redirect_to @person, notice: 'Person was successfully created.' }
        format.json { render action: 'show', status: :created, location: @person }
      else
        format.html { render action: 'new' }
        format.json { render json: @person.errors, status: :unprocessable_entity }
      end
    end
  end

    def person_params
       params.require(:person).permit(:first_name, :last_name, :headline, :description, :user_id, :employer_id,  :entity_skills_attributes  => [:skill_id, :position, :person_id, :id])
    end

Form

Skills

  <% i=0 %>
  <%= f.fields_for :entity_skills do |builder| %>
    <% i+=1 %>
    <%= render 'shared/skills_fields', :f => builder, :i=> i %>
  <% end %>

shared/skills_fields

   <%= f.label "All Skills" %>

   <%= f.collection_select(:skill_id, Skill.all, :id, :title) %>
     <%= f.hidden_field :position, :value=>i %>
     <%= f.hidden_field :person_id, :value=>@person.id %>

I had a few things funky, params were accepted but not assigned correctly to the form, also made mistake of using :skills in the permitted params instead of :entity_skills_attributes  => [:skill_id, :position]
To work with updates all I had to do was
 def edit
   @entity_skills=  @person.entity_skills
 end

I will use the position to reorder skills in case anyone wonders ;-)
Finally solved

A: You cant save a has_many through without constructing the join records.
Perhaps checkout this tutorial by Dave Shepard which runs through the things you need to do with a full example.


text:
Q: How to use Intent in kotlin fragment
As you see Intent is red and I can't make it fix any idea?

A: make use of requireContext() instead of this inside fragments
val intent = Intent (requireContext(), foo::class.java)

A: You are using it in Fragment,so use context instead of this
context?.let{ nonNullContext ->
val intent = Intent(nonNullContext, splash2::class.java)
}


text:
Q: Structure of visualforce page using standard controller, extension and wrapper of data? I am creating a component to add to a contact record that shows aggregated note data from two different sources.
Page
<apex:page id="AggergatedNotes"
    standardController="Contact"
    extensions="AggregatedNotesController"
    sideBar="false"
    showHeader="false"
    tabStyle="Contact">
    <c:AggergatedNotes notes="{!wrapper}" />
</apex:page>

Controller
public with sharing class AggregatedNotesController {
    private Case theCase;
    private Contact theContact {get; set;}
    public List<Wrapper> wrappers {get; set;}

    public AggregatedNotesController (ApexPages.StandardController stdController) {
        List<String> Contacts = new List<String>();
        List<Wrapper> wrappers = new List<Wrapper>();

        if (ApexPages.currentPage().getParameters().get('id').startsWith('003') ) {
            this.theContact = (Contact) stdController.getRecord();
            this.parentId = theContact.Id;
            Contacts = Utilities.GetExternalContacts(theContact.Id, 'Ent');
        } else {
            stdController.addFields(new List<String> {'Contact.Id'});
            this.theCase = (Case) stdController.getRecord();
            this.parentId = theCase.Contact.Id;
            Contacts = Utilities.GetExternalContacts(theCase.Contact.Id, 'Ent');
        }
        if (Contacts.size() > 0) {
            List<Event__x> events = [
                SELECT
                OwnerId__r.Name__c,
                OwnerId__r.Id,
                Description__c
                FROM
                Event__x
                WHERE
                WhoId__c IN :Contacts
                ORDER BY EndDateTime__c DESC
            ];

            List<Task__x> tasks = [
                SELECT
                OwnerId__r.Name__c,
                OwnerId__r.Id,
                Description__c
                FROM
                Task__x
                WHERE
                WhoId__c IN :Contacts
                ORDER BY ActivityDate__c DESC
            ];

            for (Event__x ev: events) {
                wrappers.add(new Wrapper(ev) );
            }
            for (Task__x ta: tasks) {
                wrappers.add(new Wrapper(ta) );
            }
        }
    }
    public class Wrapper {
        public Event__x evt {get; set;}
        public Task__x tsk {get; set;}
        public String comments {get; set;}
        public String ownerId {get; set;}
        public String ownerName {get; set;}

        public Wrapper(Task__x t) {
            tsk = t;
            comments = tsk.Description__c;
            ownerId = tsk.OwnerId__r.Id;
            ownerName = tsk.OwnerId__r.Name__c;
        }

        public Wrapper(Event__x e) {
            evt = e;
            comments = evt.Description__c;
            ownerId = evt.OwnerId__r.Id;
            ownerName = evt.OwnerId__r.Name__c;
        }
    }
}

Component
<apex:component id="AggregatedNotes" controller="AggregatedNotesComponentController">
    <apex:attribute name="notes" type="Wrapper" description="The Aggergated Notes List" assignTo="{!wrappers}"/>
   ... Will render table here ...
</apex:component>

Component Controller
public with sharing class AggregatedNotesComponentController {
    // Not sure how to get the wrapper data here
}

From what I understand, I need to use the standard controller and then extend my apex class.
Since I am using the two different sources of data, I believe I need to use a wrapper to combine them for my visualforce page.
My main issue is that I don't know now how to pass the data from the page to the component so that I can render it.
Within the component where I assign it to an attribute, it also requires a type (<apex:attribute name="notes" type="...") and I wasn't able to get Wrapper to work. Unsure what other type this would be.
I'm sure I am way off on this, but hoping to get some feedback on how to approach this structure.


text:
Q: CLOCKS_PER_SEC Not Matching Results From std::clock() I'm using the following short program to test std::clock():
#include <ctime>
#include <iostream>

int main()
{
    std::clock_t Begin = std::clock();

    int Dummy;
    std::cin >> Dummy;

    std::clock_t End = std::clock();

    std::cout << "CLOCKS_PER_SEC: " << CLOCKS_PER_SEC << "\n";
    std::cout << "Begin: " << Begin << "\n";
    std::cout << "End: " << End << "\n";
    std::cout << "Difference: " << (End - Begin) << std::endl;
}

However, after waiting several seconds to input the "dummy" value, I get the following output:
CLOCKS_PER_SEC: 1000000
Begin: 13504
End: 13604
Difference: 100

This obviously doesn't make much sense.  No matter how long I wait, the difference is always somewhere around 100.
What am I missing?  Is there some header I forgot to include?
I'm using Xcode with GCC 4.2.

A: clock() counts CPU time, so it's not adding any time if it's sitting around waiting for input.


text:
Q: Prove: If $G$ has an element of order $k$ and an element of order $m$, the order of $G$ is a multiple of lcm(k,m). Prove: If $G$ has an element of order $k$ and an element of order $m$, the order of $G$ is a multiple of lcm(k,m).
This is the same as asking to show if $k\mid n$ and $m\mid n$ then $q \mid n$. Where $n$ is the order of $G$ and $q$ is the lcm(k,m). I can't show this. Any help

A: Let $g_1$ be the subgroup of order $k$ and $g_2$ be the subgroup of order $m$. By Lagrange's theorem $|G|$ is a multiple of both $k$ and $m$ since $|\langle g_1 \rangle|=k$ and $|\langle g_2 \rangle|=m$.
Thus $|G|$ is a common multiple of $k$ and $m$ and therefore is divisible by the least common multiple of $k$ and $m$.


text:
Q: validar formulários em função de select Estou trabalhando com html5 e preciso validar um campo do meu formulário em função de outro.
Tenho um campo <select> chamado Tipo de Documento, com três opções possíveis (BI,Dire,passaporte) e um outro campo Numero do Documento. Preciso que quando uma opção que for selecionada no <select> (por exemplo passaporte), o preenchimento do campo Numero de Documento aceite apenas caracteres de passaporte e torna-se obrigatório.

A:
Existem muitas formas de se fazer, utilizei jQuery e jQueryMask que é
  um plugin que formata os inputs conforme a regra que
  definimos, tbm podia ser feito com regular expression.

$('#divCampo').hide();

  $(document).ready(function(){
 $('#sel').on('change', function(){
   var sel = $('[name="sel"]').val();
   var select = $('#sel :selected').text();
   var esvaziaCampo = $('#campo').val('');

  if (sel == '0') {
   $('#divCampo').hide();
  }
  else if (sel == '1') {
   $('#divCampo').show();
   $('#campo').mask('000-000');
   $('#texto').text(select);
  }
  else if (sel == '2') {
   $('#divCampo').show();
   $('#campo').mask('000-000-000');
     $('#texto').text(select);
  }
  else if (sel == '3') {
   $('#divCampo').show();
   $('#campo').mask('(000) 0000-00000');
   $('#texto').text(select);
  }

 });
})

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<form action="https://www.google.com">

  Tipo de documento
  <select class="form-control" name="sel" id="sel">
   <option value="0"></option>
   <option value="1">BI</option>
   <option value="2">Dire</option>
   <option value="3">Passaporte</option>
  </select>

             Preencha o campo
      <input class="form-control" type="text" id="campo" required>

      <input type="submit" class="btn btn-primary" id="btn" value="Enviar">

</form>


text:
Q: Always on python script with Upstart. Python used for serial communication First of All, I want to wish you a Merry Christmas.
I have a two problem with Upstart.
1) I need to keep a python script always on in a Linux ubuntu distro.
The script is responsable to communicate with serial port /tty/ACM0 and is essential in my application.
At boot time, Upstart launch the script (I can see this using "service myscript status"), but it don't work. If I manually type
service myscript stop
service myscript start

it work properly.
2) Sometimes happens that the device is connected but not recognized by linux.
In that case, the script fails and upstart respawn it (and it is correct), but I would like to wait some seconds before the respawn, instead also the new process will die and there will be a lot of overhead (using top, python take 98% of CPU in this case).
The problem should be software, because the devices is always connected when the system is on.
Here my config file /etc/init/myscript.conf
description "...."
 author "...."

start on runlevel [2345]
stop on runlevel [!2345]

respawn limit unlimited

exec python /smartwarmth/bin/Seriale.py

Thank you very much for your support.


text:
Q: NSDate gurus: my calculation method fails to produce consistent dates. Why? I created a method to find the third Friday of every month.
When I run it from Eastern time zone, all is well.
When I run it from Central, the dates are off.
My method:
-(NSDate*) getSaturdayAfterThirdFriday:(NSDate*)date {
    NSDate* resultDate = nil;

    if( date != nil ) {

        NSDateFormatter *df = [[NSDateFormatter alloc] init];

        // start at the 1st of the month
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

        NSTimeZone *zone = [NSTimeZone timeZoneWithName:@"EST"];
        [calendar setTimeZone:zone];
        NSDateComponents *comp = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date];
        [comp setDay:1];
        date= [calendar dateFromComponents:comp];
        [calendar release];

        // count number of 'fri' (including today)
        BOOL foundFlag = NO;
        NSString* dateString = nil;
        NSInteger count = 0;

        [df setDateFormat:@"EEE"];

        while (foundFlag == NO) {
            dateString = [df stringFromDate:date];
            if( [dateString caseInsensitiveCompare:@"fri"] == 0 ) {
                count++;
                NSLog(@"Found Friday: %@", [date description]);
            }
            if( count >= 3 ) foundFlag = YES;
            else date = [NSDate dateWithTimeInterval:86400 sinceDate:date];
        }

        // get the next day (Saturday)
        resultDate = [NSDate dateWithTimeInterval:86400 sinceDate:date];

        [df release];
    }

    return resultDate;
}

The date that is passed is created with this method:
-(NSDate*) getDateForEasternTime:(NSDate*)date {
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSTimeZone *zone = [NSTimeZone timeZoneWithName:@"EST"];
    [calendar setTimeZone:zone];
    NSDateComponents *comp = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date];
    date = [calendar dateFromComponents:comp];
    [calendar release];
    NSLog(@"getDateForEasternTime: %@", [date description]);
    return date;
}

I need to calculate dates based on Eastern Time only.
Here's my log output for Eastern time zone:
getDateForEasternTime: 2010-11-14 05:00:00 GMT

Found Friday: 2010-11-05 05:00:00 GMT

Found Friday: 2010-11-12 05:00:00 GMT

Found Friday: 2010-11-19 05:00:00 GMT

And for Central Time:
getDateForEasternTime: 2010-11-14 05:00:00 GMT

Found Friday: 2010-11-05 05:00:00 GMT

Found Friday: 2010-11-13 05:00:00 GMT

Found Friday: 2010-11-20 05:00:00 GMT

What's even more strange is that if I go further West in time zones, there is the discrepancy.  If I go East in time zones there is none.
Any NSDate guru's can help with this?
Edit:
When I refer to changing the time zone, I'm talking about changing the time zone on the device itself.  The line:
NSTimeZone *zone = [NSTimeZone timeZoneWithName:@"EST"];

Remains unchanged.

A: All your code is unnecessary. Using the weekday and weekdayOrdinal properties of NSDateComponents you can directly query a NSCalendar for the 3rd Friday of a month:
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setWeekday:6];        // 1 = Sunday ... 7 = Saturday
[components setWeekdayOrdinal:3]; // 3rd Friday
[components setMonth:11];
[components setYear:2010];
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSDate *date = [currentCalendar dateFromComponents:components];

Also, there is almost the same example for this in the Developer Documentation.


text:
Q: Building geoprocessing service using ArcGIS ModelBuilder? Using ArcGIS 10.4 for Desktop, I am trying to build a model to be published as a service. this model should take shapefile and table as inputs and run "Join Field" tool on them then i am using "feature class to feature class" tool to save that shapefile as a featureclass in a db.
so far the service output is:
Job Status: esriJobSucceeded
Results:
None
attached the screenshot from my model
the model works fine on arcmap and i can see the feature class created in the default db. i was expecting to do the same when i run as a service, when i checked the default db on the server, couldn't find the output
i m wondering why it didn't save anything in the db ? am i missing a step ?

A: It is a while since I have done this but it looks to me like your model may not have specified an output parameter.
If you compare your model to one in the Help page titled  A quick tour of authoring and sharing geoprocessing services you will see that the latter has two input and one output parameters while yours only has a single input parameter.


text:
Q: How to get keystrokes in a bash terminal on MacOS? How to get keystrokes in a bash terminal on MacOS?
I found the code here (author:Chris Redford):
enter link description here
How to add ESC key to exit loop? Thank you for your help
Modified code:
#!/bin/bash

ESC=$'\033'
# distinguish between enter and space
IFS=''

while true; do
    read -rsn1 a
    # is the first character ESC?
    if [[ $ESC == $a ]]; then
        read -rsn2 b
    fi

    input=$a$b
    unset b

    case $input in
        $ESC[A) echo UP ;;
        $ESC[B) echo DOWN ;;
        $ESC[C) echo RIGHT ;;
        $ESC[D) echo LEFT ;;

        $ESC) break ;; ### This line does not work ###

        '') echo ENTER ;;
        q) break ;;
    esac
done


text:
Q: how to set table row height to fixed value for all tables Report contains 4 tables. All rows should have same height.
I tried anwer from
set table row height
by using
    .table td, .table th {
        height: 63px;
    }

Howewer if left table second rows has more lines, this is ignored. I also tried to use !important and set tr height, but its height is still ignored.
How to fix this ?
Bootstrap 3 and jquery are used.

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1" />

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

            Kuupäev
            Märkused

            Viimane
            hind

            22.04.2016
            Arve 22.04.2016,Tellimus 161813 22.04.2016

            29.03.2016
            Tellimus 161413 28.03.2016

              kuupaev

              märkused

              5B2

              91in1

              AutoGreaseWhite

              BERBrake30L

              BERceramic

              BERhermeetik

              BERhss19osa

              BERklaasilapp

              BERviimlapp

              BERõlilapid50tk

              BRNsoftLapp

              Etch16ml

              Heebel

              HSS6.0

              HSS8.0

              HST12S

              HSTClear12mm

              KD-400

              KENTseep3L

              Laadija

              LiimGel

              LiimVedel

              NAPFC

              Piliiatslamp

              PlazTex

              PPDG

              PSG-Skang

              PTFE+

              SDL

              ShowrGlaz

              SOS

              Speedy500

              SRA

              SRP

              SWG3

              TyreDress

              USBjuhe

              Veljepuhasti

            Viimane hind
            20,05000
            8,50000
            5,70000
            60,00000
            5,00000
            8,35000
            30,00000
            1,60000
            1,40000
            25,00000
            2,30000
            4,50000
            2,55000
            5,60000
            6,70000
            9,31000
            11,00000
            4,30000
            18,00000
            4,50000
            8,00000
            7,50000
            0,00000
            0,00000
            9,85000
            9,30000
            16,50000
            9,15000
            0,00000
            21,35000
            7,20000
            11,70000
            8,50000
            0,00000
            5,70000
            7,55000
            1,50000
            19,00000

            22.04.2016 0:00.00
            Arve 22.04.2016,Tellimus 161813 22.04.2016

            6,0000

            29.03.2016 0:00.00
            Tellimus 161413 28.03.2016

            1,0000
            4,0000

            1,0000

            1,0000

            3,0000

            28.03.2016 0:00.00
            Arve 29.03.2016

            1,0000
            4,0000

            1,0000

            1,0000

            3,0000

A: Add div to every tds and put content inside the div to achieve this...
.table td, .table th, .table tr,.table div{
    height: 63px !important;
}

A: .table td, .table th, .table tr {
    height: 72px;
    white-space: normal;
    word-break: break-all !important;
    word-wrap: break-word !important;
}

Please try it.Add the properties and adjust the height.
Or
.table td, .table th, .table tr {
    height: 72px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}


text:
Q: Strange (almost) anonymous instance In the Scala Reference page on Using Clauses there is code like this:
trait Ord[T]:    // From the previous page
  def compare(x: T, y: T): Int
  extension (x: T) def < (y: T) = compare(x, y) < 0
  extension (x: T) def > (y: T) = compare(x, y) > 0

def descending[T](using asc: Ord[T]): Ord[T] = new Ord[T]:
    def compare(x: T, y: T) = asc.compare(y, x)

I've not seen anything like the new Ord[T]: ... before.  It is almost like an anonymous class but using a : instead of braces.  Is it the same thing?  I've just not seen this construct before.


text:
Q: How to remove the inner units in a compound list in Python? x = [['a','b'],['c','d','g'],['e','f','h','i','j'].......['zzy','xxx']]

If I got a compound list like this (a large list) in Python, how can I elegantly remove only, say, the element 'c' without removing the whole element ['c','d','g'] together?
Obviously merely list.remove() doesn't work for this, and implementing a for loop works
for i in x:
    for j in i:
        if j == 'c':
           i = i.remove(j)

but is computationally expensive since it's a very long list...
thank you

A: You can find the "smallest" element using min (provide a custom key function if you want to change the definition of smallest).
An O(n) solution (where n is the total number of elements in all the lists) can be to rebuild each list by omitting the smallest element:
x = [['a','b'],['b','b'],['c','c']]

smallest = min(min(l) for l in x)

x = [[e for e in l if e != smallest] for l in x]
print(x)
# [['b'], ['b', 'b'], ['c', 'c']]

A: The only improvement I could find to your code is:
x = [['a','b'],['c','d','g'],['e','f','h','i','j'],['zzy','xxx']]

def remove(compound_list, elem):
    for lst in compound_list:
        for ix, item in enumerate(lst):
            if item == elem:
                del lst[ix]
remove(x, 'c')

It is slow O(n^2) but it is faster that first solution which counting i.remove(j) it's O(n^3)


text:
Q: Is there a way to put Java objects in a POST request from a JSP? I have a JSP page that renders, and calls a Web service to load some initial data. The user fills out some form information, and then submits it to the server, which could possibly return the same JSP page for further processing (and another submit). The initial data never changes, but it is an object representation, so I'm trying to figure out how to maintain it between each POST so I'm not always calling the service. Is a session variable the only way to do this? Any help is appreciated. Thanks!

A:
Is a session variable the only way to do this?

Not the only but maybe the best. I don't see any point in sending back and forward the object since is is not needed in the client side. Plus it may be tampered with.
The alternative is to serialize  your object using Base64 encoding ( so it is text/plain ) and stored as a hidden value.
But, again, things that should go in the server, should remain in the server.
From the lessons learn on the blog entry: Why Isn't My Encryption.. Encrypting?

If it doesn't have to be sent to the client, then don't! Secrets sent to the client can potentially be tampered with and compromised in various ways that aren't easy to see or even predict. In our case, we can store login state on the server and avoid transmitting any of that state to the client altogether.

A: I would stuff it in the session variable at login time - storing data in the client is intrinsicly insecure.  If you do not expire your sessions but create them so they can be serialized to storage instead and use a web container supporting that, you never have to reload them.
If that is not interesting then create a cache around the web service so the results are kept there, and expired after some inactivity.  That will require active cleaning up though.

A: Session is the way to go. Do you really need to send it over the wire each time? Think of JSON if there is the real purpose, but otherwise use session and store it on server side.

A: Depending on how the web service is set up, you could perhaps interpose a caching layer between you and it.  For example, if it's a REST web service (or at least one that properly allows GET responses to be cached), then you can keep on fetching stuff from it, but nearly all your requests will get answered from your local HTTP cache.
If you decide on serialization, you can use XML, JSON, or another approach, eg Google's Protocol Buffers.  With highly automated serialization libraries like XStream you can even automate the mappings for JavaBeans.

A: Serialize it. http://java.sun.com/javase/6/docs/technotes/guides/serialization/index.html


text:
Q: change paragraph font size back and fourth on all paragraphs how can i make this code work on all paragraphs on a website, this is just an example code. i want it the change all paragraphs font sizes up and down with the click of the button. right now its only changing the first paragraph
<button type="button" onclick="change_font_size();">Change font size</button>

 this is some text

 this is also some text

A: Change ids to classes. Use querySelectorAll instead of getElementById and use forEach to go through every element. You don't need variable font_is_large and you can replace it with p.style.fontSize !== "150%".

function change_font_size( )
{
  paragraphs = document.querySelectorAll('.p');
  paragraphs.forEach((p) => {
     if (p.style.fontSize !== "150%") {
       p.style.fontSize = "150%" ;
     }
     else {
        p.style.fontSize = "100%" ;
      }
  })
}
<button type="button" onclick="change_font_size();">Change font size</button>

 this is some text

 this is also some text


text:
Q: High Level Language on an STM32 Are languages like eLua and Micro Python feasible for production level use on an embedded micro like an STM32?
There doesn't seem too be much information outside of their sites. Not looking to do real time stuff in these languages directly, but perhaps linking them into existing lower level C modules could speed up testing and application level development. So I was curious if anyone has had much experience with these in the real world.

A: Ada is certainly feasible. See these articles for example:
http://www.embeddedrelated.com/showarticle/617.php
http://electronicdesign.com/blog/running-ada-2012-cortex-m4
Some resources discussed here and available on github including the Ravenscar (real-time tasking designed with reliability in mind) RTS.


text:
Q: How can I use jQuery to get an HtmlTableRow (which starts life invisible/hidden) to display? I am creating some html elements via server-side (C#) code. Since this is a jQuery forum, I won't show that code, but it adds a column caption row and a first row of "textboxes" that are visible; then, I add two more rows of textboxes that start off invisible. I additionally (no pun intended) have a button (with the caption "+") that should make the first invisible row visible on the first click, and the second invisible row visible on the second click. I'm trying to accomplish that with this jQuery:
$(document).on("click", '[id$=btnAddFoapalRow]', function (e) {
    if ($('[id$=foapalrow3]').not(":visible")) {
        console.log('reached the foapalrow3 not visible branch');
        //        $('[id$=foapalrow3]').slideDown(); <= neither this nor the below works
        $('[id$=foapalrow3]').attr("visibility", "visible");
    }
    else if ($('[id$=foapalrow4]').not(":visible")) {
        console.log('reached the foapalrow4 not visible branch');
        $('[id$=foapalrow4]').slideDown();
    }
});

I do see the "reached the foapalrow3 not visible branch'" log msg in the console, but neither the slideDown() nor the "visibility=visible" code does a durned thing (pardon my 1800s backwoods dialect).
What do I need to do to visiblize foaplarow3 (and 4, as appropriate)?
Here's the code-behind/server-side (C#):
foapalrow3 = new HtmlTableRow();
foapalrow3.ID = "foapalrow3";

var cellColIndex2 = new HtmlTableCell();
cellColIndex2.Width = CELL_WIDTH;
foapalrow3.Cells.Add(cellColIndex2);
var cellColFund2 = new HtmlTableCell();
cellColFund2.Width = CELL_WIDTH;
foapalrow3.Cells.Add(cellColFund2);
var cellColOrg2 = new HtmlTableCell();
cellColOrg2.Width = CELL_WIDTH;
foapalrow3.Cells.Add(cellColOrg2);
var cellColAccount2 = new HtmlTableCell();
cellColAccount2.Width = CELL_WIDTH;
foapalrow3.Cells.Add(cellColAccount2);
var cellColActivity2 = new HtmlTableCell();
cellColActivity2.Width = CELL_WIDTH;
foapalrow3.Cells.Add(cellColActivity2);
var cellColAmount2 = new HtmlTableCell();
cellColAmount2.Width = CELL_WIDTH;
foapalrow3.Cells.Add(cellColAmount2);

boxIndex2 = new TextBox()
{
    CssClass = "dplatypus-webform-field-input",
    Width = TEXTBOX_WIDTH
};
cellColIndex2.Controls.Add(boxIndex2);
boxFund2 = new TextBox()
{
    CssClass = "dplatypus-webform-field-input",
    Width = TEXTBOX_WIDTH
};
cellColFund2.Controls.Add(boxFund2);
boxOrganization2 = new TextBox()
{
    CssClass = "dplatypus-webform-field-input",
    Width = TEXTBOX_WIDTH
};
cellColOrg2.Controls.Add(boxOrganization2);
boxAccount2 = new TextBox()
{
    CssClass = "dplatypus-webform-field-input",
    Width = TEXTBOX_WIDTH
};
cellColAccount2.Controls.Add(boxAccount2);
boxActivity2 = new TextBox()
{
    CssClass = "dplatypus-webform-field-input",
    Width = TEXTBOX_WIDTH
};
cellColActivity2.Controls.Add(boxActivity2);
boxAmount2 = new TextBox()
{
    CssClass = "dplatypus-webform-field-input",
    Width = TEXTBOX_WIDTH
};
cellColAmount2.Controls.Add(boxAmount2);
foapalHTMLTable.Rows.Add(foapalrow3);
foapalrow3.Visible = false;

The code for foapalrow4 is the same as the above for foapalrow3, except for the obvious differences. So, basically, all I need to happen on the clicking of the "+" button is to set:
foapalrow3.Visible = false;

...but via jQuery. And this is what it looks like:

UPDATE
I looked at the generated HTML for the page, and was surprised by a couple of things: one, the jQuery appears in there twice (it's duplicated) - why?
Second, and perhaps more significantly, there is no "foapalrow3" anywhere in the source, although that is the ID I give the HtmlTableRow. No wonder it's not being responded to, if it isn't aware of the existence of an element whose ID ends with "foapalrow3". The button's ID is there:

Section 5: FOAPAL / Payment Amount Information

<button id="ctl00_ctl24_g_5f3fedca_19f7_4bc3_b84e_efbef0c48a33_ctl00_btnAddFoapalRow" type="button" OnClientClick="return false;">+</button>

...and thus its click event is handled, but why isn't the ID for the HtmlTableRow not recorded, and what do I have to do so that it is?
UPDATE 2
Here is the HTML for "Section 5" which is where the rows should appear:
Explain Payment: <textarea name="ctl00$ctl24$g_5f3fedca_19f7_4bc3_b84e_efbef0c48a33$ctl00$explainPaymentTextBox" rows="2" cols="20" id="ctl00_ctl24_g_5f3fedca_19f7_4bc3_b84e_efbef0c48a33_ctl00_explainPaymentTextBox" class="finaff-webform-field-input" style="width:660px;display:inline-block;"></textarea>

Section 5: FOAPAL / Payment Amount Information

<button id="ctl00_ctl24_g_5f3fedca_19f7_4bc3_b84e_efbef0c48a33_ctl00_btnAddFoapalRow" type="button" OnClientClick="return false;">+</button>

        Index
        Fund
        Organization
        Account
        Activity
        Amount

        <input name="ctl00$ctl24$g_5f3fedca_19f7_4bc3_b84e_efbef0c48a33$ctl00$ctl130" type="text" class="finaff-webform-field-input" style="width:88px;" />
        <input name="ctl00$ctl24$g_5f3fedca_19f7_4bc3_b84e_efbef0c48a33$ctl00$ctl132" type="text" class="finaff-webform-field-input" style="width:88px;" />
        <input name="ctl00$ctl24$g_5f3fedca_19f7_4bc3_b84e_efbef0c48a33$ctl00$ctl134" type="text" class="finaff-webform-field-input" style="width:88px;" />
        <input name="ctl00$ctl24$g_5f3fedca_19f7_4bc3_b84e_efbef0c48a33$ctl00$ctl136" type="text" class="finaff-webform-field-input" style="width:88px;" />
        <input name="ctl00$ctl24$g_5f3fedca_19f7_4bc3_b84e_efbef0c48a33$ctl00$ctl138" type="text" class="finaff-webform-field-input" style="width:88px;" />
        <input name="ctl00$ctl24$g_5f3fedca_19f7_4bc3_b84e_efbef0c48a33$ctl00$ctl140" type="text" class="finaff-webform-field-input" style="width:88px;" />

It seems to me that the creation of the HtmlTableRow is not being fully "translated" to the generated html for some reason.
UPDATE 3
I tried adding IDs to the Textboxes, too, like so:
boxIndex2 = new TextBox()
{
    CssClass = "finaff-webform-field-input",
    Width = TEXTBOX_WIDTH,
    ID = "boxIndex2foapalrow3"
};
cellColIndex2.Controls.Add(boxIndex2);

...but searching the generated HTML ("View Source") for "boxIndex2foapalrow3" turns up not even a turnip.
I can understand why the "right" elements need to ID'd for this to work, but why do the IDs not even show up in the generated HTML?
What we've got here (in addition to the everlasting failure to communicate) is TextBoxes added to HtmlTableCells, which are added to HtmlTableRows, which are added to an HtmlTable. It is the HtmlTableRow that I'm setting invisible in the C# code-behind:
foapalrow3.Visible = false;

...but it seems like setting it back to visible is a conundrum wrapped in an enigma wrapped in a mystery, etc.
Maybe the cells need IDs too, like:
cellColAmount2.ID = "cellAmount2foapalrow3";

?
UPDATE 4
I reckon it should have been obvious - when the elements are not visible, they are not rendered on the page, and thus they are not found in the "View Source" and thus they are not found when searching for an ID that ends with "foapalrow3".
So I still don't know how to do what I want, but I know why my present (now former, actually) approach hung fire.
Perhaps rather than making them invisible, I'll have to give them a height the equivalent of the combined IQ of the members of the Flat Earth Society (0).
UPDATE 5
I tried using height to get it to work, by changing the HtmlTableRow's Height val to zilch in the code-behind:
foapalrow3.Height = "0";

...but that did not work, either, because setting the height to zero did nothing - the row displays at full/normal height...
UPDATE 6
Riffing on David Waters' answer, I tried this:
Code-behind:
foapalrow3.Attributes.Add("display", "none");
foapalHTMLTable.Rows.Add(foapalrow3);
//foapalrow3.Visible = false;

jQuery:
$(document).on("click", '[id$=btnAddFoapalRow]', function (e) {
    if ($('[id$=foapalrow3]').not(":visible")) {
        console.log('reached the foapalrow3 not visible branch');
        $('[id$=foapalrow3]').attr("display", "table-row");
    }
    else if ($('[id$=foapalrow4]').not(":visible")) {
        console.log('reached the foapalrow4 not visible branch');
        $('[id$=foapalrow4]').slideDown();
    }
});

...but no go. The HtmlTableRow is still visible from the git-go.
UPDATE 7
I added this to the code-behind:
foapalrow3.Attributes["class"] = "hiddenTableRow";
foapalHTMLTable.Rows.Add(foapalrow3);

...and this to the script file:

...but foapalrow3 is still visible from the git-go; yet, clicking the button does add the next (third blank row, which is foapalrow4) so, we're on the right track, but something is still phunky in funky town.

A: *

*Remove foapalrow3.Visible = false; from the server side code, as this will prevent html being generated for this row

*Add a class or style to foapalrow3 applying the CSS property display:none;

*On you button click either remove the class from foapalrow3 or if you choose to use a style attribute change display to display:table-row;
e.g.
CSS
.hiddenTableRow {
   display:none;
}

.Net
// foapalrow3.Visible = false;
// Edit - CssClass is not present on HtmlTableRow
// foapalrow3.CssClass = "hiddenTableRow";
foapalrow3.Attributes["class"] = "hiddenTableRow";

Javascript
$("[Css Selector To find the Row]").removeClass("hiddenTableRow");


text:
Q: How to parent a Ray Casted transform? I have the RaycastHit hitInfo; variable, and I want the object hit by the ray cast to get parented by the main gameObject, which is the origin of the ray.
hitInfo.collider.gameObject.name.parent = gameObject; doesn't seem to work though.

A: Try with Transform.parent gameObject.transform.parent.

A: The parent is a transform object. If the raycast is successful do the following:
hit.collider.gameObject.transform.parent = transform;

The gameObject that executed the ray will be the parent of the object hit with ray.


text:
Q: Is it possible to write a JS library that works both as es6 module and a plain script tag? Normally when you import a script in a traditional way, you do something like:
<script src="https://jsdeliver.com/packagename"></script>

And when you import a ES module, you do:
<script>
import { method } from "https://jsdeliver.com/packagename"
...
</script>

I was wondering if there's a way to write a JS library once, so that it will automatically load in both ways. If you import, it would load as ES module, and if you include it as <script src> it loads as traditional script.

A: Yes and No.
You can write an ESM module that can be loaded both from other ESM modules with import and can be loaded from a <script> tag.  To do that, however, you must use the type="module" attribute in the script tag as in:
<script type="module" src="https://jsdeliver.com/packagename"></script>

This tells the browser that this is a Javascript module script, not the older fashioned plain browser script.

You cannot have a script that is both a module and a traditional browser script because an ESM module script like you show has exports and you can't have those in a traditional, plain browser script.
So, you have to make the script an ESM script and then use the proper modifier in the <script> tag so the browser will load the ESM script properly.

Note, the situation you show would not be very common because this line of code:
import { method } from "https://jsdeliver.com/packagename"

implies that a primary purpose of this module is to deliver exported functions, but loading that via a <script> tag would not be delivering those exports.  So, the script would have to have two somewhat different purposes when loaded the two different ways. Doable, but perhaps not really how you should do things.  Perhaps you would instead, put the common, shared code into its own ESM module that can be shared and then let the top level module serve the different purposes that a <script> tag would vs. a script that you were importing methods from.


text:
Q: Post json data getting csrf token missing or invalid Would appreciate if someone can help me find the problem. I know there are a lot of solutions regarding this specific problem. Have been stuck here for a quite a long time now.
My code
Views
class HolidayList(ListCreateAPIView):
    queryset = Holiday.objects.all()
    serializer_class = HolidaySerializer
    permission_classes = [IsAdminUser, IsAuthenticated]
    authentication_classes = [SessionAuthentication,BasicAuthentication]

url
url(r'^$', HolidayList.as_view(), name='holiday-list-api'),

Getting this error
{"detail":"CSRF Failed: CSRF token missing or incorrect."}

my rest framework configuration
REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'base.csrf_exempt.CsrfExemptSessionAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
        'rest_framework.permissions.IsAdminUser',
    ),
}

Tried to use CsrfExempt but no luck. What am i missing here ?
from rest_framework.authentication import SessionAuthentication

class CsrfExemptSessionAuthentication(SessionAuthentication):
   def enforce_csrf(self, request):
     return

A: Had the same problem and solved with the following jquery snippet
<script>
    $(document).ready(function(){
        $.ajaxSetup({headers: {"X-CSRFToken": getCookie("csrftoken")}});
    });

    function getCookie(name) {
        function escape(s) { return s.replace(/([.*+?\^${}()|\[\]\/\\])/g, '\\$1'); };
        var match = document.cookie.match(RegExp('(?:^|;\\s*)' + escape(name) + '=([^;]*)'));
        return match ? match[1] : null;
    }
</script>

csrf_token is stored in the cookie called "csrftoken" and you need to pass it to the request header. In your case to your POST request header.
hope it will help.


text:
Q: Thread safety when updating data bound objects from non UI thread (WPF/Silverlight) This may be seen as a duplicate of Thread safety, lists, binding and WPF, but I post it anyway since I'm not fully happy with the accepted response, and I might be able to express what I suspect is the same question more exactly.
Any operations related to UI in WPF/Silverlight must be performed on the UI, including INotifyPropertyChanged and INotifyCollectionChanged, but - when data binding to an object (single object or collection), will the framework only read the values of the data bound object synchronously in the event handler, or could it come back any time and query the object?
What I want to do is have a worker thread updating a data bound object (often), periodically raising a CollectionChanged event if the collection is dirty to trigger a UI update. If I can know that the framework will only read the values in the collection in the event handler, a simple lock in the code raising the event to lock the collection would be enough, but if not, I will have to perform a deep copy of the collection.
So 1) can the framework read my collection even outside of the event handler and 2) if it can, is there a better way of updating something on a worker thread and publish it to the UI other than performing a deep copy?

A: You can´t guarantee that something will only read your structure in the event handler since the databinding could be refreshed if any other window controls causes a refresh on the hiearchy so locking the structure isn't what I would do.
As mentioned in the post you´ve found the way to do this is to make sure that the event is posted to the GUI-thread in a safe manner using the dispatcher like below:
public void DoWork(object sender, DoWorkEventArgs e)
{
    // Update GUI
    Dispatcher.BeginInvoke(new Action(MyPostMethod), DispatcherPriority.Normal);
}

public void MyPostMethod()
{
    // Here you´d post whatever data to the gui
}

I usually use the Action and Action<T> constructs to not having to create new delegates for every to-gui posting.


text:
Q: Compilation fails with texlive 2020 When trying to compile the following MWE using pdflatex:
\documentclass{article}
\begin{document}
 Test Test
\end{document}

I get the following error message:
jbroedel@t450s:~/Dropbox/LatexTest$ pdflatex test.tex
This is pdfTeX, Version 3.14159265-2.6-1.40.21 (TeX Live 2020/Debian) (preloaded format=pdflatex)
 restricted \write18 enabled.
entering extended mode
(./test.tex
LaTeX2e <2020-02-02> patch level 5
L3 programming layer <2020-06-18>
(/usr/share/texlive/texmf-dist/tex/latex/base/article.cls
Document Class: article 2019/12/20 v1.4l Standard LaTeX document class
(/usr/share/texlive/texmf-dist/tex/latex/base/size10.clo))

! LaTeX Error: File `l3backend-pdfmode.def' not found.

Type X to quit or <RETURN> to proceed,
or enter new name. (Default extension: def)

Enter file name:

The file l3backend-pdfmode.def is not present. I am using the Debian packages of TexLive, which does now by default use some parts of l3backend:
ii  texlive-base   2020.20200925-1 all          TeX Live: Essential programs and files

Did somebody experience a similar problem? If this turns out not to be my fault, I will file a bug report, however, would be happy for a workaround solution.

A: Now pdflatex from TexLive runs flawless with the Debian TexLive packages.
The problem was the (not systemwide) folder ~/texlive2020 containing an old .fmt file. Following the usual latex strategy, this would be used preferrably over the newly generated systemwide format files from installing a new TeXLive version. Why this version of pdflatex.fmt in a subfolder of my home folder has not been found by kpsewhich (see comments on my question) is not clear to me, but can for sure be explained.
Punchline: the old installation was not completely removed for all users, and interfered with the new (and fresh) installation.


text:
Q: jQuery: find a last child that has specific class If I have deep nested unordered list and I have a reference to the root node, is there a built in way to find a last child of "li" type that has specific css class? For example if I have a tree view branch 5 levels deep, and branch is expanded down to thrid level, levels 1,2,3 will have a class "collapsable". Now I want to find a last "li" in this case on level 3 that has this class.

A: Not too hard:
$("li.someclass", rootOfList).last()

searches rootOfList for the last li with class someclass


text:
Q: Using MapProxy in QGIS I'm trying to print a layout in QGIS that contain the WMS cartography of IGM, but each time I try there's a different hole in the result.
I discovered that MapProxy can do the trick, downloading the cache before the printing.
So, I ask you how to use MapProxy in QGIS to obtain the result and/or if there is a better way to solve.

A: You set up Mapproxy and expose the wms function as a cache for IGM. To make sure you dont get any holes I suggest that you create the complete cache by seeding it first. The documentation at the website is quite clear on how.
After that you can consume the wms-service just as any other wms in QGis