text:
Q: Removing elements from LinkedHashMap and ListBuffer of ListBuffer, used as vertex attributes into a graph structure I have built a graph in Scala using the GraphX API. In my graph, each vertex has a LinkedHashMap[Int, ListBuffer[ListBuffer[Int]]] as attribute: every couple (key, value) of the LinkedHashMap represents:

*

*key: id of a node - as Int

*value: all the possible paths to reach the node - every path is a ListBuffer[Int], so i have a ListBuffer of ListBuffer[Int]
(I've used Pregel to create the LinkedHashMaps).
So, I want to implement the case of removing a node from the graph. What I have to do is:

*

*removing, in each LinkedHashMap, the element with the key == id_of_the_node

*removing, in each ListBuffer[ListBuffer[Int]], the lists (paths) which contain the deleted node (the path will not exist anymore).

Suppose I have the following nodes (I will omit the others):
node 1: (1,Map(5 -> ListBuffer(ListBuffer(1, 3, 5), ListBuffer(1, 4, 5)), 6 -> ListBuffer(ListBuffer(1, 3, 6)), 3 -> ListBuffer(ListBuffer(1, 3)), 4 -> ListBuffer(ListBuffer(1, 4)), 1 -> ListBuffer(ListBuffer(1))))
node 2: (2,Map(5 -> ListBuffer(ListBuffer(2, 1, 3, 5), ListBuffer(2, 1, 4, 5)), 6 -> ListBuffer(ListBuffer(2, 1, 3, 6)), 3 -> ListBuffer(ListBuffer(2, 1, 3)), 4 -> ListBuffer(ListBuffer(2, 1, 4)), 1 -> ListBuffer(ListBuffer(2, 1)), 2 -> ListBuffer(ListBuffer(2))))
node 3: (3,Map(5 -> ListBuffer(ListBuffer(3, 5)), 6 -> ListBuffer(ListBuffer(3, 6)), 3 -> ListBuffer(ListBuffer(3))))
And suppose I want to delete node 3 from myGraph. Then, the nodes' attributes should become:
node 1: (1, Map(5 -> ListBuffer(ListBuffer(1, 4, 5)), 4 -> ListBuffer(ListBuffer(1, 4)), 1 -> ListBuffer(ListBuffer(1))))
node 2: (2, Map(5 -> ListBuffer(ListBuffer(2, 1, 4, 5)), 4 -> ListBuffer(ListBuffer(2, 1, 4)), 1 -> ListBuffer(ListBuffer(2, 1)), 2 -> ListBuffer(ListBuffer(2))))
node 3: (-1, LinkedHashMap[ListBuffer[ListBuffer[]]]()) - I don't know how to assign an empty LinkedHashMap[ListBuffer[ListBuffer[Int]]].
I've defined the following method:
def del(nodeToDelete: Int, vertexMap: collection.mutable.LinkedHashMap[Int,ListBuffer[ListBuffer[Int]]]): collection.mutable.LinkedHashMap[Int,ListBuffer[ListBuffer[Int]]] = {
      vertexMap.keySet.foreach{ k =>
        if(k == nodeToDelete) vertexMap.remove(k)
      }
      vertexMap
    }

But it's just for the point 1 mentioned above (removing the element with the key == id_of_the_node). Plus, if I call it on the vertices of myGraph as follows, it doesn't give me the wanted result.
myGraph.vertices.map(vertex => vertex._2).map(myMap => del(3,myMap))

How to write the method properly (implementing both point 1 and 2)? And how to use it on myGraph.vertices? In pseudocode:
foreach key k of vertexMap
 if(k == nodeToDelete) vertexMap.remove(k)
 foreach ListBuffer l1
  foreach ListBuffer l2
  if (l2.contains(nodeTodelete)) remove the list
 if(l1 is empty) vertexMap.remove(k)

Also, is LinkedHashMap the data structure with the best time complexity for the remove method?

A: Since I don't have the GraphX Api, I used your code for some, I hope tightly related, definition, like this:
val node1 = (1, Map(5 -> ListBuffer(ListBuffer(1, 4, 5)), 4 -> ListBuffer(ListBuffer(1, 4)), 1 -> ListBuffer(ListBuffer(1))))

and so on for node2 and 3, which worked in the REPL by just importing ListBuffer. Then I can remove by filtering:
node1._2.map (_._2.filter (! _.contains (3))).filter (_.size > 0)
/*
res34: scala.collection.immutable.Iterable[scala.collection.mutable.ListBuffer[scala.collection.mutable.ListBuffer[Int]]] =
List(ListBuffer(ListBuffer(1, 4, 5)),
  ListBuffer(ListBuffer(1)), ListBuffer(ListBuffer(1, 4)))
*/
scala> node2._2.map (_._2.filter (! _.contains (3))).filter (_.size > 0)
    /*
    res35: scala.collection.immutable.Iterable[scala.collection.mutable.ListBuffer[scala.collection.mutable.ListBuffer[Int]]] =
 List(
  ListBuffer(ListBuffer(2, 1, 4, 5)), ListBuffer(ListBuffer(2, 1)),
  ListBuffer(ListBuffer(2)), ListBuffer(ListBuffer(2, 1, 4)))
    */

node3._2.map (lbouter => lbouter._2.filter (lbinner=> ! lbinner.contains (3))).filter (_.size > 0)
res36: scala.collection.immutable.Iterable[scala.collection.mutable.ListBuffer[scala.collection.mutable.ListBuffer[Int]]] = List()

lbouter and lbinner stand for the inner and outer ListBuffers.
Update: Executable example with delete function:
import collection.mutable._

def delnode (x: Int, vertexMap: Map [Int, ListBuffer [ListBuffer [Int]]]) = {
    vertexMap.values.map (_.filter (! _.contains (x))).filter (_.size > 0)
}

val anode = (Map (5 -> ListBuffer (ListBuffer (1, 3, 5), ListBuffer (1, 4, 5)), 6 -> ListBuffer(ListBuffer (1, 3, 6)), 3 -> ListBuffer(ListBuffer (1, 3)), 4 -> ListBuffer(ListBuffer (1, 4)), 1 -> ListBuffer (ListBuffer(1))))
val bnode = (Map (5 -> ListBuffer (ListBuffer (2, 1, 3, 5), ListBuffer (2, 1, 4, 5)), 1 -> ListBuffer(ListBuffer (2, 1)), 6 -> ListBuffer(ListBuffer (2, 1, 3, 6)), 2 -> ListBuffer(ListBuffer (2)), 3 -> ListBuffer(ListBuffer (2, 1, 3)), 4 -> ListBuffer(ListBuffer (2, 1, 4))))
val cnode = (Map (5 -> ListBuffer (ListBuffer (3, 5)), 6 -> ListBuffer(ListBuffer (3, 6)), 3 -> ListBuffer(ListBuffer (3))))

delnode (3, bnode)
/*
res9:  Iterable[scala.collection.mutable.ListBuffer[scala.collection.mutable.ListBuffer[Int]]] =
List(
ListBuffer(ListBuffer(2)), ListBuffer(ListBuffer(2, 1, 4, 5)),
ListBuffer(ListBuffer(2, 1, 4)), ListBuffer(ListBuffer(2, 1)))

For multiple nodes, map over them and remove empty results:
    List (anode, bnode, cnode).map (n => delnode (3, n)).filter (_.size > 0)
res12: List[Iterable[scala.collection.mutable.ListBuffer[scala.collection.mutable.ListBuffer[Int]]]] = List(List(ListBuffer(ListBuffer(1, 4, 5)), ListBuffer(ListBuffer(1, 4)), ListBuffer(ListBuffer(1))), List(ListBuffer(ListBuffer(2)), ListBuffer(ListBuffer(2, 1, 4, 5)), ListBuffer(ListBuffer(2, 1, 4)), ListBuffer(ListBuffer(2, 1))))


text:
Q: Add an empty Column in between while selecting columns in a Dataframe (Spark) I am trying to add an empty column in between two columns in a dataframe select statement.
Using the withColumn function, I'm able to append only as an end column, but I need the empty column in the middle (3rd column & 6th column) as shown below.
val product1 = product.select("_c1","_c2"," ","_c4", "_c5", "_c5", " ", "c6")

I tried using withColumn in the middle of the select statement as shown below which gives the error:
val product1 = product.select("_c1","_c2",product.withColumn("NewCol",lit(None).cast("string")),"_c4", "_c5", "_c5", " ", "c6")

>error: overloaded method value select with alternatives:
  (col: String,cols: String*)org.apache.spark.sql.DataFrame <and>
  (cols: org.apache.spark.sql.Column*)org.apache.spark.sql.DataFrame
 cannot be applied to (String, String, String, String, String, String, String, String, org.apache.spark.sql.DataFrame, String)

Please let me know if any suggestions. Thanks

A: For selecting columns in dataframes, it is possible to use either strings (column names) or the columns (of Column type) as input. From the documentation:

def select(col: String, cols: String*): DataFrame
Selects a set of columns.

def select(cols: Column*): DataFrame
Selects a set of column based expressions.

However, these can not be mixed. In this case, use the select with Column type. To get the column of a specific name, use the col function or $ (after importing spark implicits).
val spark = SparkSession()....
import spark.implicits._

val product1 = product.select($"_c1", $"_c2", lit(" ").as("newCol1"), $"_c4", $"_c5", $"_c5", lit(" ").as("newCol2"), $"c6")

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to identify entities which have repeated values in sequence using MySQL? I have a table:
 UNIT_ID | YEAR | MONTH |  VAR
---------+------+-------+------
    1    | 2015 |   1   |   0
    1    | 2015 |   2   |   0
    1    | 2015 |   3   |   0
    2    | 2015 |   1   |  10
    2    | 2015 |   2   |  10
    2    | 2015 |   3   |  10
    1    | 2015 |   4   |   5
    1    | 2015 |   5   |   5
    1    | 2015 |   6   |   5
    2    | 2015 |   4   |  10
    2    | 2015 |   5   |   3
    2    | 2015 |   6   |   3
    3    | 2016 |   1   |   3
    3    | 2016 |   2   |   3
    3    | 2016 |   3   |   3
    3    | 2016 |   4   |   3
    2    | 2016 |   6   |   0
    2    | 2016 |   7   |   0
    2    | 2016 |   8   |   0

I want to know which units have a sequence bigger than 3 zeros or bigger than 4 values repeated. Grouped by year. So, my result table would be like this:
1 | 2015 | true
2 | 2015 | true
2 | 2016 | true

I have found this solution but unfortunately I could not adapt to my case. I need also that the query is in MySQL.

A: You could just join them 4 times. Last join is a left join to allow the case for 3 0's.
select a.unit_id, a.year, 'true'
from tbl a
join tbl b on a.unit_id = b.unit_id and a.year = b.year and a.month+1 = b.month and a.var = b.var
join tbl c on b.unit_id = c.unit_id and b.year = c.year and b.month+1 = c.month and b.var = c.var
left join tbl d on c.unit_id = d.unit_id and c.year = d.year and c.month+1 = d.month and c.var = d.var
where a.var = 0 or d.var is not null;

Faster and more generic solution. It scans the table only once, and uses user defined variables (@pu for previous unit_id, @py for previous year, etc) to remember the previous row:
select distinct unit_id, year
from (
  select unit_id, `year`, `month`, `var`,
    if(unit_id=@pu and `year`=@py and `month`=@pm+1 and `var`=@pv, @i:=@i+1, @i:=1)*
    if(@pu:=unit_id,1,1)*if(@py:=`year`,1,1)*if(@pm:=`month`,1,1)*if(@pv:=`var`,1,1) as c
  from table1 a
  join (select @pu:=null, @py:=null, @pm:=null, @pv:=null, @i:=1) b
  order by unit_id, `year`, `month`, `var`) a
group by unit_id, `year`, `var`
having (`var` = 0 and max(c) >= 3) or (`var` != 0 and max(c) >= 4);

fiddle


text:
Q: How to deploy pom.xml as SNAPSHOT with maven? I have a pom.xml and i want to use it as the parent pom.xml of my project.
and want to make the name for the pom.xml which was uploaded on Nexus like ABC-root-pom-2.0.0-SNAPSHOT.pom
so could anyone tell me what the command is using maven ?
Thanks

A: Do not worry about what name the pom will have on the repository manager. The Maven repository format dictates that.
To get a Maven project with pom packaging deployed you have to do the normal steps of adding the distributionManagment to the pom and the credentials to the settings.xml. Then you run
mvn clean deploy

and thats it. Your other project can then reference it. An example for such a pom project is my progressive-organization-pom.


text:
Q: Filter column of lists in pandas dataframe So I want to filter a column of lists which should only contain specific items.
This my original table:

id
code

1
[Hes3086, Hes3440, Hes3220]

2
[Hes3440, Nee8900]

3
[Hes1337, Hes3440]

4
[Nee8900, Hes3440]

5
[Hes1337, Nee8900]

6
[Hes3220, Nee8900]

7
[Hes3220, Nee8900, Hes3440]

I want the rows which only have specific items in the lists: Hes3440, Nee8900, Hes3220
Which should generate the following output:

id
code

2
[Hes3440, Nee8900]

4
[Nee8900, Hes3440]

6
[Hes3220, Nee8900]

7
[Hes3220, Nee8900, Hes3440]

I am able to filter the dataset by making sure that at least one of the desired items is in each row, but this is not what I want.
Would appreciate any help!
thanks,
M

A: Use issubset in boolean indexing with Series.map:
L = ['Hes3440','Nee8900','Hes3220']

df = df[df.code.map(lambda x: set(x).issubset(L))]
print (df)
   id                         code
1   2           [Hes3440, Nee8900]
3   4           [Nee8900, Hes3440]
5   6           [Hes3220, Nee8900]
6   7  [Hes3220, Nee8900, Hes3440]

List comprehension alternative:
df = df[[set(x).issubset(L) for x in df.code]]


text:
Q: How do I stop getting errors when importing cdns? This is my code. Why do I get these errors? Have been trying a thousand ways and keep getting nowhere.
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.4/gsap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.4/Observer.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.4/ScrollTrigger.min.js"></script>
    <script src= "https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.4/ScrollToPlugin.min.js"></script>
    <script async src="https://unpkg.com/es-module-shims@1.3.6/dist/es-module-shims.js"></script>

    <script type="importmap">
      {
        "imports": {
          "three": "https://unpkg.com/three@<version>/build/three.module.js",
          "three/addons/": "https://unpkg.com/three@<version>/examples/jsm/",
            "gsap": "https://unpkg.com/browse/gsap@<version>/src/gsap-core.js",
            "gsap/": "https://unpkg.com/browse/gsap@<version>/src/",
        }
      }
    </script>
    <script type="module" src="/main.js"></script>

import * as THREE from "three";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
import { EffectComposer } from "three/addons/postprocessing/EffectComposer.js";
import { RenderPass } from "three/addons/postprocessing/RenderPass.js";
import { gsap } from "gsap";
import { Observer } from "gsap/Observer";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import { ScrollToPlugin } from "gsap/ScrollToPlugin"
import state from "https://gramophone-frezy.s3.eu-central-1.amazonaws.com/bestR.json";
import * as core from '@theatre/core.js'

GET https://unpkg.com/three@%3Cversion%3E/examples/jsm/loaders/GLTFLoader.js net::ERR_ABORTED 404
main.js:3          GET https://unpkg.com/three@%3Cversion%3E/build/three.module.js net::ERR_ABORTED 404
main.js:10          GET https://unpkg.com/browse/gsap@%3Cversion%3E/src/ScrollToPlugin net::ERR_ABORTED 404
main.js:6          GET https://unpkg.com/three@%3Cversion%3E/examples/jsm/postprocessing/RenderPass.js net::ERR_ABORTED 404
main.js:7          GET https://unpkg.com/browse/gsap@%3Cversion%3E/src/gsap-core.js net::ERR_ABORTED 404
main.js:5          GET https://unpkg.com/three@%3Cversion%3E/examples/jsm/postprocessing/EffectComposer.js net::ERR_ABORTED 404
main.js:12          GET https://unpkg.com/browse/theatre@%3Cversion%3E/core.js net::ERR_ABORTED 404
main.js:9          GET https://unpkg.com/browse/gsap@%3Cversion%3E/src/ScrollTrigger net::ERR_ABORTED 404
main.js:8          GET https://unpkg.com/browse/gsap@%3Cversion%3E/src/Observer net::ERR_ABORTED 404
I also get these errors
sound.png:1 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "image/png". Strict MIME type checking is enforced for module scripts per HTML spec.
sound2.png:1 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "image/png". Strict MIME type checking is enforced for module scripts per HTML spec.
bestR.json:1 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "application/json". Strict MIME type checking is enforced for module scripts per HTML spec.
When I import them as
import soundImg from 'https://gramophone-frezy.s3.eu-central-1.amazonaws.com/sound.png';
import soundImg2 from 'https://gramophone-frezy.s3.eu-central-1.amazonaws.com/sound2.png';

and
import soundImg from './images/sound.png';
import soundImg2 from './images/sound2.png';
import state from "./scene/bestR.json";

I would very much appreciate the help as I am completely out of ideas.
To add some context, I am trying to upload the website to Hostinger from a Vite project. Hosting locally worked without the cdns, but didn't on hostinger so I tried with cdns and got this far.


text:
Q: How to get date as input from user using scanner? I'm writing a registration activity and I wanted to let users enter the registration date for storing the record but the problem is how do I get the date as input from user using scanner? Did this but it somehow says there's an error sorry I'm still new to java.
System.out.println(" Enter in  following format : dd-mm-yyyy");

String regDate=s.nextLine();

SimpleDateFormat format=new SimpleDateFormat("dd-mm-yyyy");

Date regDate=format.parse(date);

A: Here is a really small example with proper exception handling:
public class DateInputTest implements Closeable {

    private static final String DATE_FORMAT = "yyyy-MM-dd";

    private final Scanner scanner;

    public DateInputTest() {
    this.scanner = new Scanner(System.in);
    }

    public LocalDate getDateInput() {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT);
    String line = scanner.nextLine();
    try {
        return LocalDate.parse(line, formatter);
    } catch (Exception e) {
        System.err.println("Invalid date value:: " + line);
    }
    return null;
    }

    @Override
    public void close() throws IOException {
    scanner.close();
    }

    public static void main(String... args) {
        DateInputTest test = new DateInputTest();
        System.out.print("Please input a date [pattern yyyy-MM-dd]: ");
    Optional.ofNullable(test.getDateInput()).ifPresent(System.out::println);
    }

}

A: You can't have two variables with the same name. Also, date isn't defined anywhere.
Last line should be like this:
Date date = format.parse(regDate);

A: You can do it like this:
import java.text.SimpleDateFormat;
import java.util.*;

class Main {
  public static void main(String[] args) throws Exception {
    System.out.println("dd-mm-yyyy");
    Scanner scanner = new Scanner(System.in);
    String date = scanner.nextLine();
    Date date1=new SimpleDateFormat("dd-MM-yyyy").parse(date);
    System.out.println(date1);
  }
}


text:
Q: Placing Lock Icon on WooCommmerce "Place Order" Checkout Button (WordPress 'ignoring' Changes...) Trying to do something I thought would be relatively simple.
Here is the default woocommerce "Place order" button
<button type="submit" class="button alt" name="woocommerce_checkout_place_order" id="place_order" value="Place order" data-value="Place order">Place order</button>
and Font Awesome has this lock icon
All I am trying to do is add this icon within the button, as such:
... data-value="Place order"> Place order</button>

Things I have tried:
1.
Overriding the payment.php template in my child theme: child-theme/woocommerce/checkout/payment.php.
changed line 52 --
<?php echo apply_filters( 'woocommerce_order_button_html', '<button type="submit" class="button alt" name="woocommerce_checkout_place_order" id="place_order" value="' . esc_attr( $order_button_text ) . '" data-value="' . esc_attr( $order_button_text ) . '"> ' . esc_html( $order_button_text ) . '</button>' ); // @codingStandardsIgnoreLine ?>

(just simply added the  before Place order)
So I go to checkout, confirm it is loading my template in my child theme -- and look at the button.
No change.
<button type="submit" class="button alt" name="woocommerce_checkout_place_order" id="place_order" value="Place order" data-value="Place order">Place order</button>

*via functions
add_filter( 'woocommerce_order_button_html', 'misha_custom_button_html' );

 function misha_custom_button_html( $button_html ) {
     echo '
';
     var_dump(html_entity_decode($button_html));
     echo '
';
  return $button_html;
 }

Same thing -- I go back to checkout.
Right above the checkout button I see my var_dump
'<button type="submit" class="button alt" name="woocommerce_checkout_place_order" id="place_order" value="Place order" data-value="Place order"> Place order</button>' (length=190)

So it literally shows the correct HTML in the var_dump, but right below it, is the button,
<button type="submit" class="button alt" name="woocommerce_checkout_place_order" id="place_order" value="Place order" data-value="Place order">Place order</button>
No change.
I've also tried changing it directly in the function, but for some reason it is not rendering the correct output for the icon! Meaning ignoring the icon html all together.
I can change the text of the button, add stuff before or after it... but for some reason I cannot add this icon html within it.
Very weird, I do not understand it.
Why is this button being so stubborn and how can I add the font awesome icon to the button?

A: I guess I can just do this with CSS pseudo elements
#place_order::before {
    content: "\f023";
    font-family: FontAwesome;
}

and shows the icon before.


text:
Q: Upload an image to webserver using HTML POST I'm trying to make a screen capturing program which uploads it straight to one of the servers after. Unfortunately everything I tried either gave me errors or didn't work out at all.
Private Sub Form1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseUp
    Form2.Hide()
    Me.Hide()
    Dim bounds As Form2
    Dim screenshot As System.Drawing.Bitmap
    Dim graph As Graphics
    bounds = Form2
    screenshot = New System.Drawing.Bitmap(bounds.Width, bounds.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb)
    graph = Graphics.FromImage(screenshot)
    graph.CopyFromScreen(Form2.Bounds.X, Form2.Bounds.Y, 0, 0, bounds.Size, CopyPixelOperation.SourceCopy)
    Form2.BackgroundImage = screenshot
    Using sendto As New Net.WebClient
        Dim param As New Specialized.NameValueCollection
        param.Add("userfile", screenshot)
        Dim response_bytes = sendto.UploadValues("http://www.directimg.eu/index.php", "POST", param)
        Dim response_body = (New Text.UTF8Encoding).GetString(response_bytes)
    End Using
    Me.Close()
End Sub

This is my current code, unfortunately it doesn't work because "screenshot" needs to be a string.
I hope I can be helped out!
Thanks.

A: To send images in POST data you convert them to a Base64 string. But first you must get the image bytes. Here is an example, I have modified as necessary because I do not have your forms but you should be able to follow it:
Imports System.Drawing
Imports System.IO

Module Module1

Sub Main()
    Dim screenshot As System.Drawing.Bitmap
    Dim graph As Graphics

    screenshot = New System.Drawing.Bitmap(400, 400, System.Drawing.Imaging.PixelFormat.Format32bppRgb)
    graph = Graphics.FromImage(screenshot)

    graph.CopyFromScreen(20, 500, 0, 0, New Size(400, 400), CopyPixelOperation.SourceCopy)

    Dim ms As MemoryStream = New MemoryStream()
    screenshot.Save(ms, System.Drawing.Imaging.ImageFormat.Png)

    'screenshot.Save("c:\deleteme\screenshot.png")

    Dim imgBytes As Byte() = ms.ToArray()
    Dim imgStr As String = System.Convert.ToBase64String(imgBytes)

    Using sendto As New Net.WebClient
        Dim param As New Specialized.NameValueCollection
        param.Add("userfile", imgStr)
        Dim response_bytes = sendto.UploadValues("http://www.directimg.eu/index.php", "POST", param)
        Dim response_body = (New System.Text.UTF8Encoding).GetString(response_bytes)
    End Using

End Sub

End Module


text:
Q: Include directives not importing I've been having this problem multiple times throughout a program I'm currently working on where gcc doesn't recognize a function or file type that I import from a library even though the include directive is clearly at the top of the program with all the others. To get around this I've just been finding similar libraries and using functions from those, but for what I'm trying to do right now none of the libraries I have found are working. Here is my list of directives:
#include "oscar.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <libgen.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <time.h>
#include <utime.h>
#include <malloc.h>

I'm currently trying to change the access and modification times in a file. I've tried using utime(), utimes(), futimens() and several other variations and all of them are having the same problem. GCC isn't recognizing many of the functions or file types. For example, I'm trying to use futimens():
futimens(m_file_desc, times);

but gcc gives the following error
warning: implicit declaration of function 'futimens'

A: You probably need to need to specify the feature test macros.
From the man page:
futimens():
Since glibc 2.10:
_XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
Before glibc 2.10:
_GNU_SOURCE

So, depending on your glibc version, you need to either define _GNU_SOURCE or _XOPEN_SOURCE, or _POSIX_C_SOURCE with appropriate values.


text:
Q: Crystal reports dynamic logo(image) i am using visual studio 2010 and trying to add a dynamic image into the crystal report, i dont want to use dataset, how could i assign a URL to the image, and just change the image with the same name (ex: c:\logo.jpg different image than the existing one but the same name) and the report read it.
thanks for your replies

A: Before doing anything make new parameter (string) which will be presenting your URL of your image.
Then insert picture in your Crystal Report (1)(choose some default picture, blank or whatever picture). Next right click on picture and Format Graphics (2). Go to section Picture (3) and write down formula for URL.
Picture of step 1, 2 and 3.

Simple and easy
Hope it helps


text:
Q: Webservices help We have a web service running on the server. We want to use the service in local machine. Could some one kindly give all the steps to get the methods availble in the client.
We have created web methods in the server. And trying to access the same thing on the client. I can literally access those methods using the refernce variable of the server. but when I try to run it , it comes up with run time exception unable to connect to remote server.
I have added the web reference to my client class. What else I am missing. Do I need to do any kind of registration of service with client  from command prompt.
I am assuming the client is unable to connect to server because the server is not running when I try to access the methods.
Any one with guidance will be helpful.
Thank you
Hari Gillala
I have added web refernce to this below client class using http://ipaddressofwerver/decisionclass/decisionclass.svc
The code:
try
    {
        DecisionClass ds = new  DecisionClass();

             string s = ds.Url;
        Label1.Text = s;
        string [] a = ds.GetList();
        foreach (string i in a)
        {
            Response.Write(i);

        }

    }
    catch (Exception Ex)
    {
        Response.Write(Ex.Message);
    }

A:
I am assuming the client is unable to connect to server because the server is not running when I try to access the methods.

If it's not running, it won't generate a WSDL either. However, it may have been running while you created the web reference, and then stopped.
Here are some things you can try to track down the problem:

*

*Open the web service's URL, as specified in the web reference, in a regular web browser. This should bring up the web service's documentation page, and if you're running locally and haven't changed the web service's web.config, you can even call some simple methods using the provided test forms

*See if you can access the web service with SoapUI or a similar tool.

Also, make sure you're running the web service in IIS, not in the Visual Studio development server - IIS will keep running when you close the project or even Visual Studio, but the development server might not.


text:
Q: Nexus Docker-Registry behind NGINX returns 502 on docker login My admin and I are frustrated because we can't figure out how to set up the docker-registry part of nexus correctly.
We've setup the "docker-hosted"-Repository in Nexus.
Below you can find the nginx config:
server {
    listen   *:443;
    server_name  server.local;

    # allow large uploads of files
    client_max_body_size 50G;

    # optimize downloading files larger than 1G
    #proxy_max_temp_file_size 2G;

    ssl on;
    ssl_certificate      snakeoil.crt
    ssl_certificate_key  snakeoil.key

    location / {
      # Use IPv4 upstream address instead of DNS name to avoid attempts by nginx to use IPv6 DNS lookup
      proxy_pass http://127.0.0.1:8081/;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto "https";
    }

    location /v1/ {
       proxy_set_header Host $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header X-Forwarded-Proto "https";
       proxy_pass http://172.17.0.1:5000;
    }
}

When hitting login we only get:
Error response from daemon: login attempt to https://someToplevelURL.com/v2/ failed with status: 502 Bad Gateway

Another thing is, why is it forcing us to /v2 even if we toggle the "Use v1" button in nexus?


text:
Q: Matrix multiplication with Python I have a numerical analysis assignment and I need to find some coefficients by multiplying matrices. We were given an example in Mathcad, but now we have to do it in another programming language so I chose Python.
The problem is, that I get different results by multiplying matrices in respective environments. Here's the function in Python:
    from numpy import *
def matrica(C, n):
N = len(C) - 1
m = N - n
A = [[0] * (N + 1) for i in range(N+1)]
A[0][0] = 1
for i in range(0, n + 1):
    A[i][i] = 1
for j in range(1, m + 1):
    for i in range(0, N + 1):
        if i + j <= N:
            A[i+j][n+j] = A[i+j][n+j] - C[i]/2
        A[int(abs(i - j))][n+j] = A[int(abs(i - j))][n+j] - C[i]/2
M = matrix(A)
x = matrix([[x] for x in C])
return [float(y) for y in M.I * x]

As you can see I am using numpy library. This function is consistent with its analog in Mathcad until return statement, the part where matrices are multiplied, to be more specific. One more observation: this function returns correct matrix if N = 1.

A: I'm not sure I understand exactly what your code do.  Could you explain a little more, like what math stuff you're actually computing.  But if you want a plain regular product and if you use a numpy.matrix, why don't you use the already written matrix product?
a = numpy.matrix(...)
b = numpy.matrix(...)
p = a * b #matrix product


text:
Q: What is StringIO() used for in this script? I just started using Django and Python and I'm trying to build a photo app. This script is generating thumbnails and I'd like to do that myself. Unfortunately I don't understand what StringIO() is doing. The Python Docs aren't very helpful to me in that case.
Can someone please explain to me what StringIO() does in this particular case?
From http://djangosnippets.org/snippets/1172/:
def save(self):
    from PIL import Image
    #Original photo
    imgFile = Image.open(self.image.path)

    #Convert to RGB
    if imgFile.mode not in ('L', 'RGB'):
        imgFile = imgFile.convert('RGB')

    #Save a thumbnail for each of the given dimensions
    #The IMAGE_SIZES looks like:
    #IMAGE_SIZES = { 'image_web'      : (300, 348),
    #                'image_large'    : (600, 450),
    #                'image_thumb'    : (200, 200) }
    #each of which corresponds to an ImageField of the same name
    for field_name, size in self.IMAGE_SIZES.iteritems():
        field = getattr(self, field_name)
        working = imgFile.copy()
        working.thumbnail(size, Image.ANTIALIAS)
        fp = StringIO()
        working.save(fp, "JPEG", quality=95)
        cf = ContentFile(fp.getvalue())
        field.save(name=self.image.name, content=cf, save=False);

    #Save instance of Photo
    super(Photo, self).save()

A: StringIO is a class which can be used as a file-like object. You can use it exactly as you would a regular file, except instead of the data being written to disk, it will be written to a buffer ( a string buffer ) in memory.
In this script it looks like the image is first saved to a StringIO memory buffer, and after that the value of the string is retrieved and passed to the constructor for ContentFile to create a new instance of ContentFile, which is then passed to the field save function.
I would presume that the reason the script is using StringIO is that the constructor for ContentFile takes in a string, and writting to and then reading a StringIO file is the easiest way to get the image contents represented as a string.
As a side note, I would like to suggest that you look at Django's ImageFile field type, it has been more than enough for my image related needs, and is more clear than going through StringIO and ContentFiles.

A: StringIO provides the ability to read and write to a string just like one would write to a file.  This could make the coding more convenient, easier, or both.
It also lets you edit strings, unlike regular python strings.


text:
Q: How can I capture the stdout/stderr from exec instead of popen? I want to create a Python program that takes in another Python file as an argument, executes it and processes the the stdout/stderr while still returning stdout/stderr to the calling processes. Basically, these two should be equivalent from the end user's point of view (though the first is doing some extra processing the user doesn't see)
python passthrough.py some_example.py

vs
python some_example.py

I've seen examples of how to do this using popen and pipes, but for other reasons I can't do this in a subprocess; it needs to use the same interprete, so I need to use exec. Is it still possible to do this? To be more clear, I want passthrough.py to behave like this:
def process_output(text):
    pass
def process_err(text):
    pass

file_to_run = sys.argv[1]
sys.stdout = sys.stdout && process_output  # pipe stdout to sys.stdout AND some func
sys.stderr = sys.stderr && process_err # pipe stderr to sys.stdout AND some func
execfile(file_to_run) # Would actually use exec so it works with 3.x as well


text:
Q: Countdown timer stopping at random points I have an application that requires multiple countdown timers to run (some simultaneously). They also update UI elements with the time remaining on the countdown. I have tried using DispatcherTimer for it's easy way to interact with UI elements. However, over a 300 second countdown, it becomes out of sync with real time (because of the heavy UI updating) to the point that I get 30 seconds left on the timer when it should be 0.
I then tried switching to a System.Threading.Timer (code below). Now, the timer is spot-on and in sync with real life time. However, the Timer stops ticking after a random number of ticks (between 3 seconds and 60 seconds). I suspect it's either the garbage collector kicking in,  or the Invoke (used for updating the UI) but don't really have the knowledge to continue down this path. Can anybody give me any insight as to why the timer randomly stops ?
private int counter = 500;
private void btnTopBlue_Click(object sender, RoutedEventArgs e)
{
    btnTopBlue.Content = counter.ToString();
    Timer dt = new Timer(topBlue_Tick, null, 1000, 1000);
}
private void topBlue_Tick(object sender)
{
     if (counter > 0)
     {
         counter--;
         Dispatcher.BeginInvoke(() => btnTopBlue.Content = counter.ToString());
     }
     else
         ((Timer)sender).Dispose();
 }

A: Don't count.  Compare current time to the start time of the timer, and do the math.  That way, even if you miss a half second here and a half second there, you'll still be spot on time.
Consider this code:
    private static DateTime EndTime { get; set; }

    private void Button_Click(object sender, RoutedEventArgs e)
    {

        DispatcherTimer dt = new DispatcherTimer();
        dt.Interval = TimeSpan.FromSeconds(.1);

        dt.Tick += (s, evt) =>
                       {
                           var remaining = EndTime - DateTime.Now;

                           timeRemaining.Text = string.Format("{0:0.0}", remaining.TotalSeconds);

                           if(remaining.TotalSeconds <= 0)
                           {
                               dt.Stop();
                           }
                       };

        EndTime = DateTime.Now + TimeSpan.FromSeconds(30);
        dt.Start();

    }

A: This happened to me for a service I was writing.  The timer would eventually stop, and debugging the process found that the threads had been garbage collected.  It was suggested to me that setting the .IsBackground = true property would fix this.  I ended up doing something different, so I didn't get a chance to try this.  It may help you though.


text:
Q: How do I display the last variable update while single stepping in gdb If a C program is something like:
void main ()
{
    int a, b, c;
    a = 1;
    b = a + 1;
    c = b + 1;
}

while running gdb, and single stepping:
How do I display the variable that got updated by that single step?  Of course this is a highly simplified example, the idea being trace the execution.   Something like:
(gdb) step
         a=1
(gdb) step
         b=2
(gdb) step
         c=3

Thanks

A: gdb has an option that causes it to display 6 panels.
The upper right panel displays locals or registers.
(gdb) step
      a=1

With this display, the line a=1 is the next line to be executed.

How do I display the variable that got updated by that single step?

In the 6 panel display, the variable a is displayed, (and since you did not initialize it, any value might show prior to the step) and when you step, the 'a' value is updated.
In emacs, the command is (setq gdb-many-windows t), and I am confident the gdb manual can identify the command line equivalent.
--- might be related to "layout regs"

A: This cannot be done automaticly, imagine a line where you step that loks like this:
int a = someFunction(b++, c--);

a, b, and c change (along with any number of global or static variables affected by someFunction). How would GDB know what to print? You can use the print command to show a variables value.

A: The closest thing that gdb has to this is setting a watch for a variable.  GDB will break every time a watched variable is changed.  GDB: Watch a variable in a given scope for example


text:
Q: Triple integral - relation to volume I had to calculate the triple integral $J$ of the function $$F(x,y,z) = z$$ over the body $Q \subseteq \mathbb{R}^3$ defined via the inequality
$x^2 + y^2 + z^2 - 2Rz \le 0$,
where $R > 0$ is a constant.
$$J = \iiint_{Q} z \,dx \,dy \,dz$$
This body is the closed ball of radius $R$
centered at the point $M = (0,0,R)$, right?
This is an exercise in using spherical coordinates.
So I figured out that in spherical coordinates this body can be defines as follows:
$\theta \in [0, \pi/2]$
$\phi \in [0, 2\pi]$
$\rho \le 2R\cos\theta$
Here $\theta$ is the inclination (or polar angle) and $\phi$ is the azimuthal angle.
OK... So I calculated $J\ $ by using spherical coordinates and I got this answer.
$$\frac{4\pi R^4}{3}$$
Is my answer correct?
Then I noticed that this is actually the volume of the body multiplied by $R$.
My question is what is the intuition behind this?
There must be a reason why this integral is exactly the volume of the ball multiplied by $R$.

A: Maybe the symmetry would help our understanding. The ball is symmetric in the plane $z=R$. We separate the ball into upper half $Q_+$ and lower $Q_-$. Also we can pair $(x,y,z)\in Q_-$ with $(x,y,2R-z)\in Q_+$ and vice versa. Then, the function $z$ sums up to a constant $2R$. Therefore,
$$J=\int_{Q_+}z+\int_{Q_-}z=\int_{Q_-}2R,$$
that is, $2R$ times the volume of a half-ball.
Note that the computation above is justified with the change of variables formula.

A: Let's introduce a transformation $z^\prime = z - R$ so that the sphere has origin as its centre in the $(x, y, z^\prime)$ coordinates. We then have
\begin{equation}
J = \iiint z dx dy dz = \iiint (z^\prime + R) dx dy dz^\prime.
\end{equation}
One can use the usual spherical polar coordinates in the $(x, y z^\prime)$ system to conclude that
\begin{equation}
\iiint z^\prime dx dy dz^\prime = 0
\end{equation}
and
\begin{equation}
\iiint R dx dy dz^\prime = R \iiint dx dy dz^\prime = R \times \frac{4\pi R^3}{3}.
\end{equation}
Therefore, we have
\begin{equation}
J = \frac{4\pi R^4}{3}.
\end{equation}
Perhaps, this might give you an insight into the origin of the factor $R$. You may also want to note that the dimension of the integrand $J$ is the fourth power of length, which is reflected in the expression of $J$.

A: A physics point of view helps here. The center of mass of an object or system with density $\rho(\vec r)$ has its center of mass at
$$ \bar r = \frac{\iiint \vec r \rho(\vec r)\, dV }{\iiint \rho(\vec r)\, dV } $$
If we use this sphere and say it has density $1$, the center of mass is
$$ \bar r = \frac{\iiint_Q(x \hat \imath + y \hat \jmath + z \hat k)\, dx\, dy\, dz}{\iiint_Q dx\, dy\, dz} $$
The denominator is simply the volume of the sphere, $\frac{4}{3} \pi R^3$. Since $Q$ is symmetric in $x$ and $y$, the numerator's $\hat \imath$ and $\hat \jmath$ components come out to zero. The fact the numerator equals $\frac{4}{3} \pi R^4 \hat k$ tells us the sphere's center of mass is $(0,0,R)$. Of course, that's the center of the sphere.
For a strictly mathematical argument inspired by all this, we can note that
$$ \iiint_Q (z-R)\, dx\, dy\, dz = 0 $$
by symmetry, so
$$ \iiint_Q z\, dx\, dy\, dz = R \iiint_Q dx\, dy\, dz $$


text:
Q: snprintf function not declared? I'm trying to use the snprintf function which based on the manual I've read is apart of the <stdio.h> header however I'm getting an error that it's been implicitly declared. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct users {
    char* user_id;
};
    typedef struct users users_t;

int save_user_detail(user_t);

int main() {
    users_t users;
    save_user_detail(users);
    return 0;
}

int save_user_detail(users_t users)
{

    printf("Type the filename = ");
    scanf("%s", users.user_id);
    char* extension = ".txt";
    char fileSpec[strlen(users.user_id)+strlen(extension)+1];
    FILE *file;
    snprintf(fileSpec, sizeof(fileSpec), "%s%s", users.user_id, extension);
    file = fopen(fileSpec, "w");
    if(file==NULL)
    {
        printf("Error: can't open file.\n");
        return 1;
    }
    else
    {
        printf("File written successfully.\n");
        fprintf(file, "WORKS!\r\n");
    }
    fclose(file);
    return 0;
 }

A: You seem to be using gcc, but this compiler does not necessarily use the glibc, which is compliant with the C Standard and supports snprintf.
On the Windows architecture, you may be using the Microsoft C library, which in older versions did not have snprintf or renamed it as _snprintf.
Here are 2 ways you can try a work around your problem:

*

*try using _snprintf instead of snprintf.

*define snprintf manually after including <stdio.h> as
int snprintf(char *buf, size_t size, const char *fmt, ...);

The compiler should stop complaining about the missing prototype and if the runtime library does have a symbol for snprintf with a matching calling convention, it will link to it and the program should behave as expected.


text:
Q: When do you use 'nom de plume' vs. 'pen name' vs. 'pseudonym'? Dictionaries usually treat nom de plume as synonymous with 'pen name' or 'pseudonym'.  Example from Merriam Webster's dictionary:

Definition of nom de plume: a name that a writer uses instead of his or her real name : PSEUDONYM, PEN NAME

In what context would you use one rather than the other?  Is it a matter of regional preferences (ex. one is more prevalent in Britain and the other in America)?

A: I would suggest you write under a pen name rather than a nom de plume. The French don't say nom de plume: they say Nom de guerre. Nom de plume was made up by English-speakers 150 years ago. As H.W.Fowler said (and Etymonline mentions) it is "ridiculous for English writers to use a French phrase that does not come from France."
As Stuart F said, pseudonym is more general. You can write, or do anything you like, under a pseudonym.

A: A pseudonym is any time you are using a name other than your own.
A pen name is when an author publishes under a different name.
A nom de plume is when a pretentious author publishes under a different name.
Generally a pseudonym has the intention of concealing who the real person is. With a pen name or nom de plume it may be for purposes other than concealment.

A: I recommend: when in doubt use the most common one...

Ngram


text:
Q: PhpStorm to connect to remote MariaDB server with SSH tunnel I have a remote server on AWS Lightsail hosting a MariaDB instance.
I have to keep the MariaDB server without SSL. I would like to connect to the database using PhpStorm and SSH tunneling with my default SSH connection to the machine.
When I am on the machine via SSH, I can log into the MariaDB server with sudo mysql -h localhost -u ... -p, but from PhpStorm I get kicked off as it seems the sudo is not performed.
How can I get this to work?
I successfully tested the SSH tunneling connection. The login procedure to the MariaDB server does not work.


text:
Q: Javascript scope/binding issue with function params of a function defined within another function my problem is the following:
I have a code like this.
    (function(){
        var someVar = "some Value";
        someDOMnode.onclick = function(e){
            somePredefinedFunction( [{id: someVar}] );
        }
    })();

Now when the DOM node is clicked it won't have "some Value" as param but "someVar" (the name of the variable).
What I want is, as you may see, to have "some Value" passed to the function.
How do I solve this?


text:
Q: How to log out user after closing browser ASP.NET MVC I log in using PasswordSignInAsync function like
var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.Remember, shouldLockout: false);
And field model.Remember (isPersistent) is false.
And in my Startup class, I have some code like
app.UseCookieAuthentication(new CookieAuthenticationOptions{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });

What I would like to achieve is not only logging out the user after 30 minutes, but also after closing the browser.

A: Did u try clear cookie when window.unload from client side?
Maybe this resolve your problem.


text:
Q: Why is my go handler not producing valid FormData? I'm tinkering around trying to get a server written in go to respond to a "mime/multipart" form with a "mime/multipart" form.
With the code below, I'm getting Uncaught (in promise) TypeError: Could not parse content as FormData.
My go looks like this:
package main

import (
    "log"
    "mime/multipart"
    "net/http"
)

func handler(resp http.ResponseWriter, req *http.Request) {
    req.ParseMultipartForm(2097152)
    mw := multipart.NewWriter(resp)
    mw.WriteField("name", req.FormValue("user_name"))
    mw.WriteField("email", req.FormValue("user_email"))
    mw.WriteField("message", req.FormValue("user_message"))
    resp.Header().Set("Content-Type", mw.FormDataContentType())
    mw.Close()
}

func main() {
    http.HandleFunc("/", handler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

My browser code looks like this:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>Your first HTML form</title>
        <link rel="stylesheet" href="form.css">

<form name="theForm" method="post">

    Name:
    <input type="text" id="name" name="user_name">

    E-mail:
    <input type="email" id="mail" name="user_email">

    Message:
    <textarea id="msg" name="user_message"></textarea>

    <button type="submit">Send your message</button>

</form>

If I change the JavaScript to .then(response => response.text), I get what looks like the right response, so not sure if there's a missing CRLF at the end or what?

A: You have to move resp.Header().Set("Content-Type", mw.FormDataContentType()) to above the first write. Like so:
func handler(resp http.ResponseWriter, req *http.Request) {
    req.ParseMultipartForm(2097152)
    mw := multipart.NewWriter(resp)
    resp.Header().Set("Content-Type", mw.FormDataContentType())
    mw.WriteField("name", req.FormValue("user_name"))
    mw.WriteField("email", req.FormValue("user_email"))
    mw.WriteField("message", req.FormValue("user_message"))
    mw.Close()
}

HTTP headers can't be modified after the first write to the ResponseWriter. If no Content-Type is set at that point it defaults to Content-Type: text/plain; charset=utf-8 which the browser can't parse since it needs the boundary which is given in the Content-Type header


text:
Q: PHP image if else CSS I'm wondering how I could echo an image depending on a css style?
To be more clear: My navigation is transparent, if I scroll down the navigation sticks to the top of the screen but gets a white background.
My logo can be used in gray and white. When transparent its hard to read in gray, so I use the white version.
When the navigation becomes white, the white logo isn't visible so I want it to change to the gray logo.
Is there a way to change an image with an if / else?
Something like if navigation is white echo graylogo, else echo whitelogo
Thanks a lot!

A: if I was you, i'd put the 2 images in my code, then, you'd simply have to do show the logo depending on the class. Example:

Then the css:
.nav.white .white-img{
   display: none;
}
.nav.black .black-img{
   display: none;
}

Then, using PHP when you create your page, you could set the right class to your nav element, or using javascript if it's event driven. (user click, user scroll or etc)


text:
Q: How to create linux account with useradd without creating mail spool Summary
Can I create a new user without creating mail spool and without modification of /etc/default/useradd ?
Explaination
I want to create a user that has a home directory and skeletion, but I don't want the useradd script to add a mail spool file to the unix system.
My /etc/default/useradd file states that
CREATE_MAIL_SPOOL=yes

but I don't want to modify the default behaviour.
For now I'm using
useradd nomailuser
rm /var/spool/mail/nomailuser

Also I know about -d but it seems that I can't find an option for not creating a mail spool.
I'm thinking about is there an option to use custom /etc/default/useradd file.

A: man useradd
   -K, --key KEY=VALUE
       Overrides /etc/login.defs defaults (UID_MIN, UID_MAX, UMASK, PASS_MAX_DAYS and others).

       Example: -K PASS_MAX_DAYS=-1 can be used when creating system account to turn off password ageing, even though
       system account has no password at all. Multiple -K options can be specified, e.g.: -K UID_MIN=100 -K UID_MAX=499

So, try this:
# useradd -K MAIL_DIR=/dev/null nomailuser

A warning would appear (Creating mailbox file: Not a directory), but you can ignore.

A: I'm setting up a Docker image with Alpine and shadow package and got the same error.
To avoid this "Creating mailbox file: No such file or directory" error I had to add the following inline replacement before trying to add user:
RUN sed -i 's/^CREATE_MAIL_SPOOL=yes/CREATE_MAIL_SPOOL=no/' /etc/default/useradd

This is a Dockerfile directive. If you are struggling with an already running host, just edit the /etc/default/useradd file and change the setting accordingly. This change would prevent any other user creation from getting its mailbox created.
It that is not the desired behavior, you can just create the /var/mail folder with
[ -d /var/mail ] || mkdir /var/mail

Or in the Dockerfile:
RUN mkdir /var/mail

Hope this helped.

A: Oddly enough, the answer is no. I just read the sourcecode and there is no option for this, though there is a workaround (sort of): maildirs don't get created for system accounts.
So you can do useradd -r -m. You'll have to specify a UID/GID manually as well though, as they're picked from different ranges.


text:
Q: How to parse json objects inside json array in c#? I have a json file which has either of the following formats:

*

*Sample 1:

{
  "MyOrders": [
    {
      "order": "my order1",
      "url": "tt"
    }
  ]
}

Sample 2:
{
  "MyOrders": [
    [
      {
        "order": "my order 1",
        "url": "ddfdfd"
      },
      {
        "order": "order 2",
        "url": "asdfwe"
      }
     ],
     [
      {
        "order": "my order 3",
        "url": "ertrt"
      },
      {
        "order": "my order 4",
        "url": "werwe"
      }
    ]
  ]
}

I have the following code:
InputItems root = JsonConvert.DeserializeObject<InputItems>(myJsonText);

And I have the following classes:
public class InputItems
    {
            [JsonProperty("MyOrders")]
            public List<Order> objects { get; set; }

    }

    public class Order
    {

        [JsonProperty("order")]
        public string order{ get; set; }

        [JsonProperty("url")]
        public string url { get; set; }

}

But it works just for the first case. How can I improve it to also cover the second sample format?
Thanks in advance.

A: I've written a converter that should help you:
public class SingleArrayOrNestedConverter<TItemType> : JsonConverter<List<TItemType>>
{
    public override List<TItemType> ReadJson(JsonReader reader, Type objectType, List<TItemType> existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        // Read the object as JSON
        var token = JToken.ReadFrom(reader);
        if (token is JObject) // it's just a lone object, so wrap it in a list and return it
        {
            return new List<TItemType>() { token.ToObject<TItemType>(serializer) };
        }
        else if (token is JArray arrayOfObjects) // it's an array of objects, so let's loop through
        {
            var result = new List<TItemType>();
            foreach (var item in arrayOfObjects)
            {
                if (item is JObject) // the nested item is an object, so let's add it to the list
                {
                    result.Add(item.ToObject<TItemType>(serializer));
                }
                else if (item is JArray nestedArrayOfObjects) // the nested item is an array, so let's loop through it
                {
                    foreach (var nestedItem in nestedArrayOfObjects)
                    {
                        // this will throw an exception if nestedItem doesn't represent an object
                        result.Add(nestedItem.ToObject<TItemType>(serializer));
                    }
                }
            }
            return result;
        }
        return null;
    }

    // we can't use this code for serializing so make sure JSON.NET doesn't try
    public override bool CanWrite => false;

    public override void WriteJson(JsonWriter writer, List<TItemType> value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

This will work with the following JSON samples.
Sample 1:
{
    "MyOrders": [{
            "order": "my order1",
            "url": "tt"
        }
    ]
}

Sample 2:
{
    "MyOrders": [
        [{
                "order": "my order1",
                "url": "tt"
            }
        ]]
}

Sample 3:
{
    "MyOrders": {
        "order": "my order1",
        "url": "tt"
    }
}

Sample 4:
{
    "MyOrders": [
        [{
                "order": "my order1",
                "url": "tt"
            }
        ], {
            "order": "my order1",
            "url": "tt"
        }
    ]
}

To apply it to your code, you'll need to use the JsonConverterAttribute:
[JsonConverter(typeof(SingleArrayOrNestedConverter<Order>))]

Which looks like this:
public class InputItems
{
    [JsonProperty("MyOrders")]
    [JsonConverter(typeof(SingleArrayOrNestedConverter<Order>))]
    public List<Order> objects { get; set; }
}


text:
Q: Is there a numpy function for sorting according to a vector with indices? I want to sort a numpy vector according to another numpy vector with indices.
import numpy as np
my_vector = np.array([9. 6. 21. 17. 12.])
my_indices = np.array([1. 4. 2. 0. 3.])

what_i_want = np.array([17. 9. 21. 12. 6.])

Is there a function for this? Something like reverse argsort

A: It can be done in O(n) using advanced assignment:
my_vector = np.array([9., 6., 21., 17., 12.])
my_indices = np.array([1., 4., 2., 0., 3.])
my_result = np.empty_like(my_vector)
my_result[my_indices.astype(int)] = my_vector
my_result
# array([17.,  9., 21., 12.,  6.])

Timings on a larger example:
from timeit import timeit

a = np.random.random(1000000)
b = np.random.permutation(1000000).astype(float)

def fargsort():
    return(a[b.argsort()])

def fassign():
    c = np.empty_like(a)
    c[b.astype(int)] = a
    return c

np.all(fargsort() == fassign())
# True
timeit(fargsort,number=10)
# 1.2764090860000579
timeit(fassign,number=10)
# 0.17262099700747058

A: Use argsort as follows:
import numpy as np
my_vector = np.array([9., 6., 21., 17., 12.])
my_indices = np.array([1., 4., 2., 0., 3.])

print(my_vector[my_indices.argsort()])

Output:

[17.  9. 21. 12.  6.]

A: You can try this:
import numpy as np
my_vector = np.array([9., 6., 21., 17., 12.])
my_indices = np.array([1., 4., 2., 0., 3.])

res_sorted = [x for _,x in sorted(zip(my_indices,my_vector))]
print(res_sorted)

output:
[17.0, 9.0, 21.0, 12.0, 6.0]


text:
Q: Working with bytes in Python using SHA-256 So I want to use SHA-256 for a specific problem: Calculate digest from a bytearray, then concatenate the resulting digest to another block of bytes ( a 1024 byte block for this problem ) and calculate the digest for the concatenated values.
For example:
Here are my two byte blocks:
from hashlib import sha256
rawhex4 = b'\x44'*773
rawhex3 = b'\x33'*1024

h = sha256()
h.update(rawhex4)
aux = h.digest()

This hexdigest is: d8f8a9eadd284c4dbd94af448fefb24940251e75ca2943df31f7cfbb6a4f97ed
then I want to concatenate this 32 byte digest to my next block and hash it but I am not getting the correct answer. I do the following:
h.update(rawhex3 + aux)

I know for fact that hashing rawhex3 + hash(rawhex4) will give me this digest:
26949e3320c315f179e2dfc95a4158dcf9a9f6ebf3dfc69252cd83ad274eeafa
What could I be missing? I am pretty new to Python

A: Try this:
from hashlib import sha256
rawhex4 = b'\x44'*773
rawhex3 = b'\x33'*1024

h1 = sha256()
h1.update(rawhex4)
aux = h1.digest()

h2 = sha256()
h2.update(rawhex3 + aux)
print h2.hexdigest()

A: You are reusing the hash object which already contains bits from rawhex4.
If you create a new one, you'll get your 26..fa result.


text:
Q: Boot from DVD takes too long It takes over 15 minutes to boot from two DVD's that I burned from two different downloads  - DeskTop - from the Ubuntu web site using InfraRecorder. Then when I use the mouse to try to start something there is a time lag making any progress impossible. I get virtually no response from clicks of the mouse. Can you help me fix this? I was able to use Bodhi Linux on a live USB with no problems. I would be very grateful for a fix. I am using the 32 bit Ubuntu.

A: Maybe it's just basic thing like the DVD read is too slow or something.
I suggest to use USB Flash Drive.it's much faster than DVD.
but maybe Ubuntu on USB is also still a little bit slow


text:
Q: Meaning of 'as you may say' Here is the example, which is from 'Baker's blue-jay yarn' by Mark Twain.
I think the sentence means '(bad words) you might say in everyday life', but I'm not sure.
"He just had strength enough to crawl up onto the comb and lean his back agin the chimbly, and then he collected his impressions and begun to free his mind. I see in a second that what I had mistook for profanity in the mines was only just the rudiments, as you may say."

A: As you may say qualifies the narrator's use of rudiments, and means that this expression is in some way rhetorical or exaggerated. Similar expressions are:

... only just the rudiments, so to speak.
  ... only just the rudiments, in a manner of speaking.
  ... only what you might call the rudiments.
  ... only just the rudiments, as it were.
  ... only kinda sorta the rudiments.


text:
Q: Change the background color of a div in angular I would like to change the bg colour of div when clicked on that particular div.
The div is placed in a slider panel. For example, if I click Home, the slider gets hidden and the home panel opens up. Again when I open the slider, the bg colour should be retained to say that I am in Home panel. I tried using ng-style and ng-class, but it doesnt work.

A: Your ng-style syntax is wrong.
It should be
ng-style="{'background-color':'blue'}"

Please, note that ng-class take a css class not individual properties

CSS
.bgColor{
  background-color:blue;
}

There are many different ways to declare ng-class. Take a look here.
This useful SO post talks about different ways to conditionally applying css in AngularJS.

A: ng-style="{'background-color':'#CCCCCC'}">

Reference


text:
Q: Как прочитать файл с райширением .ebc (ebcdic) через python? Возникла такая проблема, есть файл в формате .ebc (ebcdic), его размер более 10 Гб. Не получается прочитать с помощью python. При попытке конвертировать через utf-8 и прочее, выдает ошибку.

A: ebcdic - это специальный двоичный формат.
Поэтому просто декодировать в строку не получится, стандартная реализация Python ничего не знает о таком формате сообщений.
Быстрое гугление подсказывает библиотеку https://pypi.org/project/ebcdic/, скорее всего, она должна помочь.


text:
Q: How to communicate to one particular ESP8266 in a network of multiple ESP8266, where every module is running a server instance listening on port 80 I am quite new to IoT, but I am building a system where I have multiple IoT devices in a home connected to internet using ESP8266 module. But I do not have a particular gateway in any home. I am relying on WiFi router. To convey any message to the device, from internet, I need to identify the particular device.
I am using DDNS for the home router's IP. But how can I send requests coming from the server to all the devices connected.
I have this code in my ESP8266 modules.
ESP 1:
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

MDNSResponder mdns;
ESP8266WebServer server(80);

void setup(){
server.on("/esp_unique_01/", [](){
    server.send(200, "text/html", webPage);
  });
  server.on("/esp_unique_01/socket1On", [](){
    server.send(200, "text/html", webPage);
    digitalWrite(gpio0_pin, HIGH);
    delay(1000);
  });
  server.on("/esp_unique_01/socket1Off", [](){
    server.send(200, "text/html", webPage);
    digitalWrite(gpio0_pin, LOW);
    delay(1000);
  });
}

ESP 2:
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

MDNSResponder mdns;
ESP8266WebServer server(80);

void setup(){
server.on("/esp_unique_01/", [](){
    server.send(200, "text/html", webPage);
  });
  server.on("/esp_unique_02/socket1On", [](){
    server.send(200, "text/html", webPage);
    digitalWrite(gpio0_pin, HIGH);
    delay(1000);
  });
  server.on("/esp_unique_02/socket1Off", [](){
    server.send(200, "text/html", webPage);
    digitalWrite(gpio0_pin, LOW);
    delay(1000);
  });
}

Both of these ESP modules are having a dynamic IP. Any lead would be highly appreciated.

A: a mixture from the example of MDNS :
  char hostString[16] = {0};
  sprintf(hostString, "ESP_%06X", ESP.getChipId());
  if (!MDNS.begin(hostString)) {
    Serial.println("Error setting up MDNS responder!");
  }
  Serial.println("mDNS responder started");

  // Start TCP (HTTP) server
  server.begin();
  Serial.println("TCP server started");

  // Add service to MDNS-SD
  MDNS.addService("http", "tcp", 80);

So you gonna have http service description for node1.  Run second node's web server on a different port and define it.

A: The solution is to assign static IP addresses to your ESP8266 modules and to use different ports to access them from internet. Here is the code to assign a static address to ESP8266:
IPAddress ip(192,168,1,xx);               // desired static IP address
IPAddress gateway(192,168,1,yy);          // IP address of the router
IPAddress subnet(255,255,255,0);

WiFi.begin(ssid, password);
WiFi.config(ip, gateway, subnet);

while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
}

Now that you know local IP addresses of your ESP8266 devices you can choose ports to be forwarded to your ESPs. For example you can choose ports 8266, 8267, 8268, 8269, ... or any other above 1024 and then set the port forwarding in your router settings so port 8266 will be forwarded to the IP address of your first ESP and port 80, port 8267 will be forwarded to the IP address of your second ESP and port 80 etc.
Afterwards you can access your ESPs from internet using URLs looking like http://xx.xx.xx.xx:8266, http://xx.xx.xx.xx:8267, http://xx.xx.xx.xx:8268, http://xx.xx.xx.xx:8269, ...
Since you are already using dynamic DNS service to access your ESP8266 when there are no other ESPs in your local network, that means you can just add :8266, :8267, :8268, :8269, ... to the URL you are already using. In other words, if the URL consisting of what you have chosen + the part generated by your dynamic DNS service is http://myhome.something.com then you will now use http://myhome.something.com:8266, http://myhome.something.com:8267 etc.


text:
Q: How to check if radio button is selected or not using Selenium WebDriver?

Mi Dirección 1

Predeterminada

<input id="17390233" class="default_shipping_address" type="radio" name="address" checked="true">
Seleccionar como tarjeta predeterminada

this is the HTML code
If radio button selected is true then print the class span value?
please help me..

A: In Java, this would do it:
if(driver.findElement(By.id("17390233")).isSelected()){
    System.out.println(driver.findElement(By.xpath("//input[@id='17390233']/following-sibling::span[1]")).getText());
}

If the radio button is selected, then the text will show. If you want to use the text somewhere, I suggest you put it in a string instead:
String spanText = driver.findElement(By.xpath("//input[@id='17390233']/following-sibling::span[1]")).getText();

Hope this answers your question.
EDIT: Here is an update of other ways to try.
If the className default_shipping_address is unique (e.g. not used anywhere else on the page), you may try locating the element by className:
if(driver.findElement(By.className("default_shipping_address")).isSelected()){
    System.out.println(driver.findElement(By.xpath("//input[@class='default_shipping_address']/following-sibling::span[1]")).getText());
}

If that class is not unique, maybe the DIV's className selectCard_left is?
if(driver.findElement(By.className("selectCard_left"))){
    System.out.println(driver.findElement(By.xpath("//div[@class='selectCard_left']/span[1]")).getText());
}

If none of the classNames are unique, a complete xpath expression is required. If you still are unable to get that text, I refer to reading up on how to use xpath: http://www.w3schools.com/XPath/xpath_syntax.asp
I hope that you find this information useful.


text:
Q: Morgan logger logs not everything to file I use Morgan and Express to provide REST APIs for my website. I implementet the morgan-logger this way in my main.js:
app.use(morgan('dev')); //logger
app.use(morgan('dev', {stream: fs.createWriteStream('./access.log', {flags:
'a'})}));

Now it logs me every call to an API in my access.log file like this:
::ffff:10.60.101.165 - - [26/Feb/2019:08:19:57 +0000] "POST /api/api1
HTTP/1.1" 200 -
::ffff:10.60.101.165 - - [26/Feb/2019:08:19:58 +0000] "POST /api/api2
HTTP/1.1" 200 -
::ffff:10.60.101.165 - - [26/Feb/2019:08:19:58 +0000] "POST /api/api3
HTTP/1.1" 200 -

Thats fine, but when I write own log messages like console.log("error in file A"), it is printed in the console but not in my access.log file. How can I write manually to it inside my API file?

A: We use morgan logger for API logging. If you want to log anything then you can use winston logger library. Its pretty easy to use. I have already answered that here - Log4js javascript create daily log file
Also you can use pm2 to host your service. After that whenever you log anything on console, pm2 will write them in a file.

A: To log everything use common instead of dev.
app.use(morgan('common')); //logger
app.use(morgan('common', {stream: fs.createWriteStream('./access.log', {flags:
'a'})}));


text:
Q: Suppose a $3\times{5}$ matrix $A$ has three pivot columns, what is the dimension of the Null space? The question is as follow: " Suppose a $3\times{5}$ matrix $A$ has three pivot columns, what is the dimension of the Null space? "
I think the answer have to be $2$ .
There are $3$ pivot columns so that means that there are $2$ columns left with free variables.
The answer of the questions is apperantly 5. I dont know why and i am wondering if the answer is wrong and mine is correct. They say that the Dim of the Nulspace is in R5 because the vectors are in R5
Can someone tell me what is correct?
Thank you.

A: The dimension of the nullspace is $2$. You are right, and the given answer is wrong.
The nullspace is a subspace of $\Bbb R^5$, and as such the elements of said nullspace is most naturally described using $5\times 1$ column vectors. However, that doesn't mean the space has dimension $5$.


text:
Q: How to Hide UITableView? When pressing a button in my view controller it shows a UIView which has UISearchBar and UISearchDisplayController and UITableView in it(changes the view's hidden property to NO).
When I select a row in the table view I set the view's property to hidden=YES, but it doesn't hide the tableView. What can be the problem?
I implemented the UITableViewDelegate protocol and I receive  tableView:didSelectRowAtIndexPath: message(I set the view's hidden=YES  there).
Please note that when I call view's hidden=YES from searchBarCancelButtonClicked: it hides successfully.
I think that UISearchDisplayController is causing the problem.
Some code:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.searchView.hidden = YES; // hide successfully the tableView.
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath   *)indexPath
{
    self.searchView.hidden = YES; //doesn't hide the tableView.
}

EDIT: Found the problem, see my answer below. In short I added [self.searchDisplayController setActive:NO];

A: Found the problem - I needed to add [self.searchDisplayController setActive:NO]; and now it works.
Code:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.searchDisplayController setActive:NO]; //Added line of code.
    self.searchView.hidden = YES; // Now it works!
}

A: Try this:
 tableview.hidden = YES;

A: [self.yourview setHidden:Yes];
if the tableview is inside the view it should also hide


text:
Q: How do I stop my componentDidMount from getting called twice? how do I stop my componentDidMount from getting called twice?
Following is my code:
class BarSearchFormComponent extends Component {
  constructor(props) {
    super(props);
    this.searchInput = React.createRef();
    this.onChange = this.onChange.bind(this);
    this.onKeyDown = this.onKeyDown.bind(this);
    this.state = { keywords: null, inputValue: '' };
  }

  componentDidMount() {
    const value = queryString.parse(window.location.search);
    const { keywords } = value;
    this.setState({ inputValue: keywords });
  }

  onKeyDown(e) {
    if (e.keyCode === KEY_CODE_ENTER) {
      this.props.onSubmit({ keywords: this.state.keywords })
      if (this.searchInput.current) {
        this.searchInput.current.blur();
      }
    }
  }
  onChange(keywords) {
    this.setState({ keywords: keywords }, () => {
      this.setState({ inputValue: this.state.keywords });
    });
  }

  render() {
    const { right } = this.props;
    return (
      <FinalForm

I am trying to display the searched keyword in my bar search component.


text:
Q: What does & = in C& operator=(const C&) & = default; do? A few questions on SO use a particular syntax for declaring default assignment operators.
Rule-of-Three becomes Rule-of-Five with C++11?
class C {
  C(const C&) = default;
  C(C&&) = default;
  C& operator=(const C&) & = default;
  C& operator=(C&&) & = default;
  virtual ~C() { }
};

I'm confused by the & = used for the assignment operators. After a quick test, default assignment operator declarations seem to compile and give the expected behavior with or without the additional ampersand.
I don't see the & = syntax on cppreference.

A: The & there is a ref qualifier.
In that particular case it makes it so that the instance of C you want to assign to must be a non-const lvalue.


text:
Q: Genarating Random Move right left up down Suppose that we have a 4 faces die. The person toss the die and if it land on:
1) the person will move to the right
2) the persone will move to the left
3) the person will move upward
4) the person will move downward
The process will repeat again by tossing the coin and move from the last position and so on for n more times.
How can I generate this random simulation.
test[n_] := Accumulate[RandomChoice[{{-1, 0}, {1, 0}, {0, 1}, {0, -1}}, n]]

How can i show the last point that it is plot if I use this function
ListLinePlot[test[10]]?

A: You might implement your random walk something like this.
walk[n_] :=
  Prepend[
    Accumulate[RandomChoice[{{-1, 0}, {1, 0}, {0, 1}, {0, -1}}, n]],
    {0, 0}]

trial[n_] :=
  Module[{path, start, end},
    path = walk[n];
    start = First @ path;
    end = Last @ path;
    ListLinePlot[path,
      Epilog -> {PointSize[Large], Point[start], Red, Point[end]},
      AspectRatio -> Automatic]]

SeedRandom[3]; trial[25]


text:
Q: Is SSE floating-point arithmetic reproducible? The x87 FPU is notable for using an internal 80-bit precision mode, which often leads to unexpected and unreproducible results across compilers and machines. In my search for reproducible floating-point math on .NET, I discovered that both major implementations of .NET (Microsoft's and Mono) emit SSE instructions rather than x87 in 64-bit mode.
SSE(2) uses strictly 32-bit registers for 32-bit floats, and strictly 64-bit registers for 64-bit floats. Denormals can optionally be flushed to zero by setting the appropriate control word.
It would therefore appear that SSE does not suffer from the precision-related issues of x87, and that the only variable is the denormal behavior, which can be controlled.
Leaving aside the matter of transcendental functions (which are not natively provided by SSE unlike x87), does using SSE guarantee reproducible results across machines and compilers? Could compiler optimizations, for instance, translate into different results? I found some conflicting opinions:

If you have SSE2, use it and live happily ever after. SSE2 supports
  both 32b and 64b operations and the intermediate results are of the
  size of the operands.
   - Yossi Kreinin, http://www.yosefk.com/blog/consistency-how-to-defeat-the-purpose-of-ieee-floating-point.html

...

The SSE2 instructions (...) are fully IEEE754-1985 compliant, and they
  permit better reproducibility (thanks to the static rounding
  precision) and portability with other platforms. Muller et aliis,
  Handbook of Floating-Point Arithmetic - p.107

however:

Also, you can't use SSE or SSE2 for floating point, because it's too
  under-specified to be deterministic. - John Watte
http://www.gamedev.net/topic/499435-floating-point-determinism/#entry4259411

A: As Stephen noted, results produced by a given piece of SSE assembly code will be reproducible; you feed the same code the same input and you get the same output at the end.  (That is, John Watte's quote is flat-out wrong.)
You threw the word "compilers" in there, though.  That's a different ball game entirely.  Many compilers are still quite bad at preserving the correctness of floating-point code.  (The ATLAS errata page makes mention that clang "fails to produce correct code for some operations.")  If you use special functions in your code, you're also, to some extent, at the mercy of whoever implemented your math library.

A: SSE is fully specified*.  Muller is an expert in floating point arithmetic; who are you going to trust, him or some guy on a gamedev forum?
(*) there are actually a few exceptions for non-IEEE-754 operations like rsqrtss, where Intel never fully specified the behavior, but that doesn't effect the IEEE-754 basic operations, and more importantly their behavior can't actually change at this point because it would break binary compatibility for too many things, so they're as good as specified.


text:
Q: JUnit test crashes in setUp I'm testing two activities: the first one completes its tests and finishes, but the first test in the second one crashes with the following error:
Test failed to run to completion. Reason: 'Instrumentation run failed due to 'java.lang.NullPointerException''. Check device logcat for details

I figured the line activity = getActivity(); in the test class gives a null and thus crashes the test. Here's the relevant part of the test class. Why does this happen, and how do I fix it?
public ResultActivityTest() {
    super(ResultActivity.class);
}

@Override
protected void setUp() throws Exception {
    super.setUp();

    activity = getActivity();
    displayoperands = (TextView) activity.findViewById(R.id.result_textview);
    resultdisplay = (TextView) activity.findViewById(R.id.textView2);
    canvas = (SurfaceView) activity.findViewById(R.id.surfaceview);
    layoutRoot = (RelativeLayout) activity.findViewById(R.id.rellay);
    back = (Button) activity.findViewById(R.id.back_button);

    activity.setImag1(2.0);
    activity.setImag2(2.0);
    activity.setReal1(2.0);
    activity.setReal2(2.0);
    activity.setOperation("A");
}

A: I figured it out after a bit of tampering with the activity and some trial and error. The problem was, the activity's onCreate demanded a bundle with variables from the calling activity. This being null, kept crashing the activity that the test tried to start without passing any variables. The solution is to initialise the required variables with a (dummy/default) value that works with the activity.


text:
Q: Does it make any difference to analyse change from baseline (observational study) or post-hoc contrast post vs. baseline? I have an observational, non-randomized longitudinal study with 3 time point + baseline (t0 ... t3). Analysing solely the post-values in such trials is meaningless. I want to analyze the change from baseline, as the typical activity in medical studies.
I'm wondering, whether it makes any difference to model the change scores (Time_x - baseline) and obtain the differences (T3-T0, T2-T0, T1-T0) vs. modelling the post values itself and then test the appropriate contrasts after that: T3 vs T0, T2 vs T0, T1 vs T0?
For me, the outcome must be the Dunnett contrast: all vs. baseline, that's all. So this suggests to model post-values and then use appropriate contrasts, rather than modelling change scores - because how to adjust using the Dunnett, right?
Scenario 1:
Model: post_response ~ covariates
Dunnett: post_t3 vs t0, post_t2 vs. t0, post_t1 vs. t0 + Dunnett adjustment based on the multivariate t distribution.
Scenario 2:
Model: change_from_baseline ~ covariates
Dunnett: have no idea how?
But how to use Dunnett when I analyze change score?! To employ Dunnett I need the post-analysis (adjusted for baseline), so the answer seems clear.
I only wonder if the two approaches make any difference for modelling itself?


text:
Q: How do I bind the tmux prefix key to C-'? I'd like to set my tmux prefix key to Ctrl-apostrophe, but when I use set-option prefix "C-'" or set-option prefix C-"'", tmux complains that "unknown key: C-'". Similarly for ` and :. Is there a way to bind these keys?

A: Most terminal emulators only generate special output for a restricted set keys when used in combination with the Control modifier key. The apostrophe key is one of the keys that does not generate any special output sequence (it ether does nothing or just outputs a regular apostrophe).
See Wikipedia's "ASCII control characters" and "How control characters map to keyboards".
You can check to see if your terminal emulator generates any output for Control-', by typing it into cat -v, or at a shell prompt (in most common shells) after typing a Control-V.
If it does generate some special output (not just '), then you might be able to bind it in tmux if the control code/sequence is known to tmux. The list of keys names that tmux recognizes is in its manpage under the "Key Bindings" section. tmux will only recognize special keys if the terminfo entry for your TERM outside of tmux defines them (see man terminfo for the "capability" names and infocmp for the ones your TERM defines); if needed, you can extend your system's terminfo entry just for tmux with its terminal-overrides configuration variable (or recompile your own custom entry with tic).
If it does not generate any special output then you would have to somehow reconfigure it to do so (if that is possible); you might have it generate the same code as ^], or the sequence for "F20" (if it is defined in your TERM's entry when outside tmux).


text:
Q: Evaluating an infinite sum involving possibly hypergeometric terms I was considering the following infinite sum
$$ A(n) = \sum_{k=2}^{\infty}\left[\frac{(-1)^{k+n-1}}{k^n}(0k -1)(k-1)(2k-1)...((n-1)k-1) \right] $$
Some cases:
$$ A(1) = \sum_{k=2}^{\infty}\left[\frac{(-1)^{k+1}}{k} \right]= -\frac{1}{2} + \frac{1}{3} - \frac{1}{4} ... = \ln(2) - 1 $$
A trickier sum to evaluate is: $A(2)$. This resolves to:
$$ A(2) = \sum_{k=2}^{\infty}\left[\frac{(-1)^{k+2}}{k^2} (k-1)\right] = \frac{1}{4} - \frac{2}{9} + \frac{3}{16} ... $$
Some jugglery is required but if we consider
$$ 1 - x + x^2 -x^3 ... = \frac{1}{1+x}$$
And integrate
$$ \ln(1+x) = x - \frac{1}{2}x^2 + \frac{1}{3}x^3 + ... $$
Divide by x and integrate
$$ \int_{0}^{1} \frac{\ln(1+x)}{x} dx   = x - \frac{1}{4}x^2 + \frac{1}{9} x^3 ... $$
Now multiply by (-1), divide by x and differentiate
$$ - \left( \frac{1}{x} \int_{0}^{1} \frac{\ln(1+x)}{x} dx \right)' = \frac{1}{4} - \frac{2}{9} x + \frac{3}{16} x^2 ... $$
Meaning
$$ \left( \frac{1}{x^2} \int_{0}^{1} \frac{\ln(1+x)}{x} dx  - \frac{1}{x}  \frac{\ln(1+x)}{x} \right)_{@x = 1} = \frac{1}{4} - \frac{2}{9} + \frac{3}{16} ...  $$
Through very mysterious techniques of the omniscient Wolfram Alpha this evaluates to
$$ \frac{\pi^2}{12} - \ln(2) = \frac{1}{4} - \frac{2}{9} + \frac{3}{16} ...  $$
So now this is totally in the deep end, but I have a suspicion the sum I have given can somehow be related to the riemann zeta function, in some good quality closed form. It's a wild guess but the $\ln(2)$ and now the $\pi^2$ hint me that's a good idea.
How to show this?

In case it's helpful
I tried to bash this with Sister Celine's method. By writing as
$$ A(n) = \sum_{k=2}^{\infty}\left[\frac{(-1)^{k+n-1}}{k^n}(0k -1)(k-1)(2k-1)...((n-1)k-1) \right] = \sum_{k=2}[ M(n,k) ]  $$
And tried to find a recurrence for $M$ but unfortunately after consider $a_0(n) M(n,k) + a_1(n) M(n+1,k) + a_2(n) M(n-1,k) $ it became clear I'm going to need some more terms (possibly a lot more) before I can find a closed recurrence. Unfortunately my maple package has expired (I did send them an email to renew!) so I couldn't throw the might of Shalosh B. Ekhad in the Zeilberger package to close it up.
I suspect though that this would be ample for those techniques.

A: This is not an answer but it is too long for a comment.
Interested by the post, I first wrote (from definition) $$A_n=\sum _{k=2}^{\infty } \frac{(-1)^{k+n} }{k}\left(\frac{k-1}{k}\right)_{n-1}$$ where appears the Pochhammer symbol.
Then, "playing" with a CAS, I obtained the following terms $$A_1=-1+\log (2)$$ $$A_2=\frac{\pi ^2}{12}-\log (2)$$ $$A_3=\frac{3 \zeta (3)}{4}-\frac{\pi ^2}{4}+2 \log (2)$$ $$A_4=-\frac{9 \zeta (3)}{2}+\frac{11 \pi ^2}{12}+\frac{7 \pi ^4}{720}-6 \log (2)$$ $$A_5=\frac{105 \zeta (3)}{4}+\frac{15 \zeta (5)}{16}-\frac{25 \pi ^2}{6}-\frac{7 \pi
   ^4}{72}+24 \log (2)$$ $$A_6=-\frac{675 \zeta (3)}{4}-\frac{225 \zeta (5)}{16}+\frac{137 \pi ^2}{6}+\frac{119
   \pi ^4}{144}+\frac{31 \pi ^6}{30240}-120 \log (2)$$ $$A_7=1218 \zeta (3)+\frac{2625 \zeta (5)}{16}+\frac{63 \zeta (7)}{64}-147 \pi
   ^2-\frac{343 \pi ^4}{48}-\frac{31 \pi ^6}{1440}+720 \log (2)$$
As you suspect, beside the $(-1)^{n-1}(n-1)!\log(2)$ term, $A_n$ is a linear combination of $\zeta(.)$ functions $$A_n=(-1)^{n-1}(n-1)!\log(2)+\sum_{i=2}^{n}a_i\, \zeta(i)$$
At this point, may I confess that I am totally stuck ?
Edit
Just for clarity, defining $$B_n=A_n-(-1)^{n-1}(n-1)!\log(2)$$ and back to only $\zeta(.)$ functions, we would have $$B_2=\frac 12 \zeta(2)$$ $$B_3=-\frac 32 \zeta(2)+\frac 34 \zeta(3)$$ $$B_4=\frac{11 }{2}\zeta(2)-\frac{9 }{2}\zeta (3)+\frac{7 }{8}\zeta(4)$$ $$B_5=-25 \zeta(2)+\frac{105 }{4}\zeta (3)-\frac{35 }{4}\zeta(4)+\frac{15 }{16}\zeta (5)$$ $$B_6=137 \zeta(2)-\frac{675
   }{4}\zeta (3)+\frac{595 }{8}\zeta(4)-\frac{225 }{16}\zeta (5)+\frac{31 }{32}\zeta(6)$$ $$B_7=-882 \zeta(2)+1218 \zeta (3)-\frac{5145 }{8}\zeta(4)+\frac{2625 }{16}\zeta (5)-\frac{651 }{32}\zeta(6)+\frac{63 }{64}\zeta
   (7)$$

A: I do not know if what follows is of some help, but:
Note that $\prod_{j=0}^{n-1}(jk-1)=P_n(k)$, is a polynomial in $k$. Put $P_n(x)=a_0+a_1x+\cdots a_{n-1}x^{n-1}$, then your sum is
$$A(n)=(-1)^{n-1}\sum_{j=0}^{n-1}a_j(\sum_{k\geq 2}\frac{(-1)^k}{k^{n-j}})$$
and $\sum_{k\geq 1}\frac{(-1)^k}{k^{s}}=\eta(s)=(1-2^{1-s})\zeta(s)$
See https://en.wikipedia.org/wiki/Riemann_zeta_function#Generalizations, ( in "the functional equation" part)
The case $j=n-1$ gives you the $\log(2)$ term, up to a constant due to the $k\geq 2$.

A: The trick should be to rewrite (for $n>0$)
\begin{align}
A(n) &= \sum_{k=2}^{\infty}\frac{(-1)^{k+n-1}}{k^n}(0k -1)(k-1)(2k-1)...((n-1)k-1)\\
&= \sum_{k=2}^{\infty}(-1)^{k-1}\left(\frac 1k\right)\left(\frac 1k-1\right)...\left(\frac 1k-(n-1)\right)\\
&= \sum_{k=2}^{\infty}(-1)^{k-1}\left(\frac 1k\right)_n\\
\end{align}
where $(x)_n$ is the Pochhammer symbol ("falling factorial") and a generating function for the signed Stirling numbers of the first kind (the term $\,i=0\,$ is omitted since $\;s(n,0)=0\,$ for $n>0$) :
$$(x)_n=\sum_{i=1}^n s(n,i)\,x^i$$
this gives (for $\,\eta\,$ the Dirichlet eta function or "alternating zeta function") :
\begin{align}
A(n) &= \sum_{k=2}^{\infty}(-1)^{k-1}\sum_{i=1}^n s(n,i)\,\frac 1{k^i}\\
&= \sum_{i=1}^n s(n,i)\,\sum_{k=2}^{\infty}(-1)^{k-1} \frac 1{k^i}\\
&= \sum_{i=1}^n s(n,i)\,(\eta(i)-1)\quad\text{but}\quad  \sum_{i=1}^n s(n,i)=0\quad\text{for}\;n>1\\
&= \sum_{i=1}^n s(n,i)\,\eta(i)\quad\text{for}\;n>1\quad\text{and}\quad s(1,1)(\eta(1)-1)\quad\text{for}\;n=1\\
\\
A(n)&= \begin{cases}s(n,1)\,\log(2)+\sum_{i=2}^n s(n,i)\left(1-2^{1-i}\right)\zeta(i),&n>1\\
\log(2)-1,&n=1\\
\end{cases}
\end{align}
Since $\;s(n,1)=(-1)^{n-1}(n-1)!\;$ these expressions are in perfect agreement with the table exposed by Claude Leibovici.


text:
Q: datepickerdialog theme_holo_light not displayed correctly in Samsung J7 Core I use java code to display datepickerdialog with a theme THEME_HOLO_LIGHT.
My compiled SDK version is 27. The theme is displayed perfectly in an oppo device (Nougat 7.0). However, in samsung J7 Core, the output is a different THEME.
Sample output of THEME_HOLO_LIGHT
The result of an output in Samsung is THEME_DEVICE_DEFAULT_DARK.
I want the THEME_HOLO_LIGHT to display. Please help.
datePickerDialog = new DatePickerDialog(this,AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
            USERBIRTHDATE = dateFormat.format(new Date(year - 1900, month, dayOfMonth));
            dateTxt.setText(USERBIRTHDATE);
            flag = true;
        }
    }, 1997, 0, 01);

A: Instead of AlertDialog.THEME_HOLO_LIGHT write android.R.style.Theme_Holo_Light.
If this doesn't work, replace it with this:
datePickerDialog = new DatePickerDialog(this,new ContextThemeWrapper(this, android.R.style.Theme_Holo_Light), new DatePickerDialog.OnDateSetListener() {..}


text:
Q: How to display dataframe table in telegram bot using python I am doing stock market price bot project using python.
So I want to display the top gainers and top losers list after user clicks the button top gainers or losers.
So I am using pandas dataframe for display the tables using scraping the gainers url.In pycharm and jupyter notebook it is printing the tables.
But after I tried to print it on telegram bot using
import telegram
import pandas as pd
url = 'https://www.moneycontrol.com/markets/global-indices/'
response = requests.get(url)
print(response)
market = pd.read_html(url)
new_market = market[0]
new_market2 = new_market[['Name','Current Value','%Change']]
update.message.reply_text(new_market2.to_markdown())

it is not giving me in dataframe table format. How to display this new_market dataframe on telegram bot in proper format.

A: I've just found a great tool for that need, it is called tabulate.
It prints tabular data and works with DataFrame.
from tabulate import tabulate
import pandas as pd

df = pd.DataFrame({'col_two' : [0.0001, 1e-005 , 1e-006, 1e-007],
                   'column_3' : ['ABCD', 'ABCD', 'long string', 'ABCD']})

print(tabulate(df, headers='keys', tablefmt='psql'))

+----+-----------+-------------+
|    |   col_two | column_3    |
|----+-----------+-------------|
|  0 |    0.0001 | ABCD        |
|  1 |    1e-05  | ABCD        |
|  2 |    1e-06  | long string |
|  3 |    1e-07  | ABCD        |

 bot.send_message(chat_ids, f'<pre>{table}</pre>', parse_mode=ParseMode.HTML)


text:
Q: Loop over list items, except for the last two items (python) I want to for loop over a list of 14 items except for the last two items.
Does anybody know if there is a function or command in python which accomplishes this?

A: Python lists support slicing like this:
for i in your_list[:-2]

A: random_list = [1, 2, 3, 4, 5, 6]

for element in random_list[:-2]:
     print(element)

[Out] :
1 2 3 4

A: optionally
items = [] # your 14 item long list here
for i in range(len(items)-2):
    print(items[i])


text:
Q: validate form and print to a table I need to validate a form in javascript by printing the error message next to the input box. When I do that, the validation only flashes on the screen and does stay on the screen. I also having the same problem when I print the table from javascript, it only flashes on the screen and does not stay on. I can not find any syntax error, but I know I am missing something.
Thank you in advance.
Avi
<!DOCTYPE html>

    <title>TODO supply a title</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <form name="theForm" action="FormAndTable.html" method="post">
        First Name: <input type="text" id="fname">

        Last Name: <input type="text" id="lname">

        Date of Birth: <input type="text" id="dob">

        <input type="submit" value="Save" onclick="validateForm()">
    </form>

A:
Use type="button", type="submit" will submit the form and it will reload the page.

Try this:

function validateForm() {
  var x = document.getElementById('fname').value;

  if (x === null || x === "") {
    document.getElementById('error1').innerHTML = "Invalid Entry";
  } else
    tableCreate();
}

function tableCreate() {
  var N = document.getElementById('fname').value;
  var L = document.getElementById('lname').value;
  var D = document.getElementById('dob').value;

  var ar = [N, L, D];
  console.log(ar);
  document.write('
');
  document.write('
');
  document.write('First Name	');
  document.write('Last Name	');
  document.write('Date of Birth	');
  document.write('
');

  for (var i = 1; i < ar.length; i++) {
    document.write('
' + ar[i] + '
');
  }

  document.write('
');
}
<form name="theForm" action="FormAndTable.html" method="post">
  First Name:
  <input type="text" id="fname">

Last Name:
  <input type="text" id="lname">

Date of Birth:
  <input type="text" id="dob">

  <input type="button" value="Save" onclick="validateForm()">
</form>


text:
Q: Error while using TryFrom for String in Rust I am trying to implement TryFrom for converting a string to a slice with the help of the following code shown below.
impl<const N: usize> TryFrom<String> for [u8; N] {
    type Error = &'static str;

    fn try_from(value: String) -> Result<[u8; N], Self::Error> {
        let val = value.as_bytes()[..];
        Ok(val)
    }
}

I am getting a compilation error when I call
let a = String::try_from("a".to_string())

impl<const N: usize> TryFrom<String> for [u8; N] {
    | ^^^^^^^^^^^^^^^^^^^^^---------------^^^^^-------
    | |                    |                   |
    | |                    |                   this is not defined in the current crate because arrays are always foreign
    | |                    `std::string::String` is not defined in the current crate
    | impl doesn't use only types from inside the current crate

A: You are not allowed to implement traits on external types because of the orphan rule.
See Implementing a Trait on a Type:

But we can't implement external traits on external types. For example,
we can't implement the Display trait on Vec within our aggregator
crate, because Display and Vec are both defined in the standard
library and aren't local to our aggregator crate. This restriction is
part of a property called coherence, and more specifically the orphan
rule, so named because the parent type is not present. This rule
ensures that other people's code can't break your code and vice versa.
Without the rule, two crates could implement the same trait for the
same type, and Rust wouldn't know which implementation to use.