text:
Q: Any good way for getting a single instance instead of using Singleton (in C#) I used to use singleton get a single instance, but it was disclaimed by others because of some disadvantage in testing. What's the disadvantage?
Is there any alternative good way for getting a global instance?

So is it OK for me to create only one singleton class Global in application as global hub? so that I can put any other class's single instances in Global.Instance.

A: Ok, why singletons are bad you can read here: What is so bad about singletons?
Specifically for testing: A typical singleton pattern looks like this
class MyClass
{
    private static MyClass m_Instance = new MyClass();
    public static MyClass Instance
    {
        get { return m_Instance; }
    }
}

Now imagine you have to run a whole bunch of tests all involving the MyClass.Instance. This class carries around a state and you usually need to have to have a way to reset it between tests so that each test can start with a clean initial state. Now you can add a Reset() method but that means you add code to your class just for the purpose of being able to test it which is not desirable.
What to use instead: Well, the singleton in itself is not really the bad thing. The problem it leads to is that it makes it easy to write code like this:
class SomeClass
{
    public void SomeMethod()
    {
        ...
        MyClass.Instance.DoSomething();
    }
}

Now you have created an implicit dependency on the singleton instance you cannot easily break. One approach which solves this problem is via dependency injection (which was already mentioned):
class SomeClass
{
    public SomeClass(MyClass myClass)
    {
        m_MyClass = myClass;
    }

    public void SomeMethod()
    {
        ...
        m_MyClass.DoSomething();
    }
}

and you can do:
var someClass = new SomeClass(MyClass.Instance);

in your program and
var someClass = new SomeClass(new MyClass());

for testing.
So singletons are not that bad and sometimes the right tool for the right job, however you need to be careful of how you use them.

A: Testability is the main difficulty as I can see, to address that to some extent, we have unity containers.
Check Unity container http://unity.codeplex.com/

A: i dont see any issues with testability and singletons. also i dont see how DI can replace them.

A: Consider using the what is called "ambient context" pattern instead. This example is taken from Mark Seeman's excellent Dependency Injection in .NET book. This pattern gives you the ease of use of a singleton, and also testability. The important point here is the existence of what is called a good "default" (i.e. DefaultTimeProvider shown in the example). Another thing to consider is not to abuse this pattern, in most cases you can inject the different dependencies into the constructor of the class. This pattern should only be used for concerns that cross cut throughout the whole application.
public abstract class TimeProvider
{
    private static TimeProvider current;
    static TimeProvider()
    {
        TimeProvider.current = new DefaultTimeProvider();
    }
    public static TimeProvider Current
    {
        get { return TimeProvider.current; }

        set
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            TimeProvider.current = value;
        }
    }
    public abstract DateTime UtcNow { get; }
    public static void ResetToDefault()
    {
        TimeProvider.current = new DefaultTimeProvider();
    }
}


text:
Q: How to sort a multidimensional character array alphabetically Swift I am trying to sort a [[Character]] array that has random characters put in to it so that it is all alphabetical. ex output for right now:
["H", "P", "C"]
["F", "K", "V"]
["J", "Y", "B"]

I need it to be like this
["A", "B", "C"]
["D", "E", "F"]
["G", "H", "I"]

Any Ideas?

A: Please check :
let input = [["H", "P", "C"], ["F", "K", "V"], ["J", "Y", "B"], ["A", "L"]]
var sortedArray = input.flatMap({ $0 }).sorted()

var finalArray:[[String]]=[]
var subArray:[String]=[]
for i in 0..<sortedArray.count {
    subArray.append(sortedArray[i])
    if subArray.count == 3 || i == sortedArray.count-1 {
        finalArray.append(subArray)
        subArray = []
    }
}

print(finalArray)
// Output : [["A", "B", "C"], ["F", "H", "J"], ["K", "L", "P"], ["V", "Y"]]

A: func flattenArray(nestedArray: [[Character]]) -> [[Character]]{

var myFlattendArray = [Character]()
var sortedArray = [[Character]]()

for element in nestedArray{
    if element is [Character]{
        for char in element{
            myFlattendArray.append(char)
        }
    }
}
myFlattendArray = myFlattendArray.sorted(by: {$0 < $1})
var arrayForArray = [Character]()
for i in 0..<myFlattendArray.count{
   if((i % nestedArray.count == 0 && i != 0)){
        sortedArray.append(arrayForArray)
        arrayForArray.removeAll()
   }else if i == myFlattendArray.count - 1{
        arrayForArray.append(myFlattendArray[i])
        sortedArray.append(arrayForArray)
        arrayForArray.removeAll()
   }
   arrayForArray.append(myFlattendArray[i])

}
   return sortedArray
}

A: You can use flatMap to flatten your array, sort it and then you can group using this extension from this answer as follow:
extension Array {
    func group(of n: IndexDistance) -> Array<Array> {
        return stride(from: 0, to: count, by: n)
            .map { Array(self[$0..<Swift.min($0+n, count)]) }
    }
}

let arr = [["H", "P", "C"],
           ["F", "K", "V"],
           ["J", "Y", "B"]]

let sorted = arr.flatMap{$0}.sorted().group(of: 3)
sorted  // [["B", "C", "F"], ["H", "J", "K"], ["P", "V", "Y"]]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java Inheritance and Polymorphism Program I am new to Java and have most likely made a stupid mistake on my code.  In particular, I am having problems with the main arguments, asking for and saving scanner objects to link to the other subclasses.  I believe that the Person, Student, Employee, Faculty, and Staff portions are correct but I cannot figure out the Driver portion. Below is the homework problem.  Thank you in advance for any help or advice!
HOMEWORK PROBLEM:
Design a class named  Person and its two subclasses, Student and Employee. Make Faculty and Staff subclasses of Employee.
A Person object  has a name , address, phone number, and email address (all Strings ).
A Student has a class  status (freshman, sophomore, junior, or senior). Define the status as a final String  variable .
An Employee has an office number , salary (both ints ), and a date hired. Use the MyDate class  defined below to create an object  for date hired:
class  MyDate{
private  String  date; //date in the form mm/dd/yy

public MyDate(String  date){
this.date = date;
}

public String  getDate(){
return date;
}
}

A Faculty object  has office hours and a rank (both Strings ), while a Staff object  has a title (as a String ).
For the Student, Faculty, and Staff classes, create toString methods  that store  information about the object  (in the format shown in the examples below).
Test your classes in a Driver class  (within the same file) that asks the user what type  of object  they'd to create as well as what information they'd like it to have.
The program  then uses the object 's toString method  to print information about that object .
Sample Run #1
Enter
1)To create a student
2)To create an employee:  1
Enter  name :  Walter D. Graham
Enter address:  4737 Stadium Drive Whitinsville, MA 01588
Enter phone number:  508-266-2108
Enter email:  walterdgraham@university.edu
Enter student's status:  Junior
Student: Walter D. Graham
Status: Junior
Address: 4737 Stadium Drive Whitinsville, MA 01588
Phone Number: 508-266-2108
Email Address: walterdgraham@university. edu
Sample Run #2
Enter
1)To create a student
2)To create an employee:  2
Enter  name :  Kimberly D. Davis
Enter address:  795 University Hill Road Decatur, IL 62522
Enter phone number:  217-519-6747
Enter email:  kimdavis@school.edu
Enter
1)To create a faculty member
2)To create a staff member:  1
Enter office number:  724
Enter salary:  84101
Enter date hired (mm/ dd/ yy):  06/12/92
Enter office hours:  5-7pm, Mon-Thu
Enter rank:  Adjunct Professor
Faculty: Kimberly D. Davis
Rank: Adjunct Professor
Salary: $84101
Date Hired: 06/12/92
Office Hours: 5-7pm, Mon-Thu
Office: 724
Address: 795 University Hill Road Decatur, IL 62522
Phone Number: 217-519-6747
Email: kimdavis@school. edu
DRIVER PORTION THAT I WROTE:
package person;
import java.util.Scanner;
public class Driver {
//Testing

public static void main(String[] args) {

int studentOrEmployee;
int facultyOrStaff;

Scanner input = new Scanner(System.in);

System.out.println("Enter");
System.out.println("1)To create a student:");
System.out.print("2)To create and employee: ");
studentOrEmployee= input.nextInt();

System.out.print("\n Enter name: ");
Person name = input.next();
System.out.print("\n Enter address: ");
Person address = input.nextString();
System.out.print("\n Enter phone number: ");
Person phone = input.nextString();
System.out.print("\n Enter email ");
Person email = input.nextString();

if (studentOrEmployee==1) {
System.out.print("\n Enter student's status: ");
Person classStanding = input.nextString();
System.out.println(student.toString() + "\n");
}

else if ( studentOrEmployee==2) {

facultyOrStaff= input.nextInt();
if (facultyOrStaff==1) {
System.out.print("\nEnter office number: ");
Person office = input.nextInt();
System.out.print("\nEnter salary");
Person salary = input.nextInt();
System.out.print("\nEnter date hired: ");
Person dateHired = input.next();
System.out.print("\nEnter office hours: ");
Person hours = input.nextString();
System.out.print("\nEnter rank: ");
Person rank = input.nextString();
System.out.println(faculty.toString() + "\n");
}
else if (facultyOrStaff==2) {
System.out.print("\nEnter office number: ");
System.out.print("\nEnter office title: ");
Person title = input.nextString();
System.out.println(staff.toString() + "\n");
}
}
Person person = new Person(name,address, phone, email);
Person student = new Student(name, classStanding, address, phone, email);
Person employee = new Employee(name, address, phone, email, office, salary, dateHired);
Person faculty = new Faculty(name, rank, salary, dateHired, hours, address, phone, email, office);
Person staff = new Staff(name, title, address, phone, email, office, salary, dateHired);
}
}

A: check your declaration. If you wanted to save a String you need to declare your variable as a String.
System.out.print("\n Enter name: ");
String name = input.next();
System.out.print("\n Enter address: ");
String address = input.nextString();
System.out.print("\n Enter phone number: ");
String phone = input.nextString();
System.out.print("\n Enter email ");
String email = input.nextString();
....


text:
Q: JS AddEventListener in loop (for all checkboxes) I wanted to add event listener to all checkboxes on my page.
<input type="checkbox" name="sel[]" id="1" value="1">
<input type="checkbox" name="sel[]" id="2" value="2">
<input type="checkbox" name="sel[]" id="3" value="3">
<input type="checkbox" name="sel[]" id="4" value="4">
<input type="checkbox" name="sel[]" id="5" value="5">
<input type="checkbox" name="sel[]" id="6" value="6">
<!--  .....  -->

<script>
var arr =  document.getElementsByName("sel[]");

var copy = [];

for (i = 0; i < arr.length; i++)
    copy[i] = arr[i].id;

var checkboxes = [];
var data;

for (j = 0; j < arr.length; j++)
{
    checkboxes[j] = document.getElementById(copy[j]);
    checkboxes[j].addEventListener('change', (event) => {
    if (event.target.checked)
    {
        data = j;
        $.post("/php/ses.php", {data:data});
    }
    else
    {
        data = (-1)*j;
        $.post("/php/ses.php", {data:data});
    }
 });
</script>

It works for every checkbox, but always sends 6 if any checkbox is checked (or -6 when unchecked). I wanted to: 1 and -1 for first chceckbox, 2 and -2 for second etc, not 6/-6 for every.

A: As far as you use JQuery this code may be more preferable
var checkboxes =  $('[name="sel[]"]');

//listen all checkboxes change event
checkboxes.on('change', function(){
    var id = this.value; // id equals j in your code
    $.post("/php/ses.php", { data: this.checked ? id: -id }); // send data id if checked and -id if not checked
});

A: You could use checkboxes data value for your data instead of keeping a separate instance of it.

var arr =  document.getElementsByName("sel[]");
for (j = 0; j < arr.length; j++){
    arr[j].addEventListener('change', (event) => {
    if (event.target.checked) {
        //$.post("/php/ses.php", {data:data});
        console.log({data: parseInt(event.target.value)});
    }else {
        //$.post("/php/ses.php", {data:data});
        console.log({data: -parseInt(event.target.value)});
    }
 });
 }
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
</head>
<body>
<input type="checkbox" name="sel[]" id="1" value="1">
<input type="checkbox" name="sel[]" id="2" value="2">
<input type="checkbox" name="sel[]" id="3" value="3">
<input type="checkbox" name="sel[]" id="4" value="4">
<input type="checkbox" name="sel[]" id="5" value="5">
<input type="checkbox" name="sel[]" id="6" value="6">
</body>
</html>

The reason your code ends up with 6 is that your data is a global variable and gets updated after each loop, and it ends up with 6 at the end, there is no local data for event listener for each item on arr.
Please check this to learn more about it JavaScript closure inside loops – simple practical example

A: While the answer by Prokhor Orlov is correct I want to explain what is wrong in OP. At the moment when event handler fires the for loop iterator is already ran out of the loop and has its max value. This error is very common in beginners and the question was asked 100+ times. The solution is also well known, use closure in the loop. Something like this.
for (i = 0; i < arr.length; i++) {
(function(j){
  checkboxes[j] = document.getElementById(copy[j]);
  checkboxes[j].addEventListener('change', (event) => {
    if (event.target.checked) {
      data = j;
      $.post("/php/ses.php", {
        data: data
      });
    } else {
      data = (-1) * j;
      $.post("/php/ses.php", {
        data: data
      });
    }
  });
})(i);
}

Disclaimer: This is not recommended code in this case


text:
Q: How to extract a dataframe which is within a list in r, using a condition? I have a list which has dataframes of various dimensions. I want to extract those dataframes who rows greater than 30
I tried :
DR<-sapply(list, function(x) subset(list,nrow(list$'x')=30))

But it is showing error.
Please help!

A: Assuming your list is called list_df, we can use Filter
Filter(function(x) nrow(x) == 30, list_df)

Or sapply
list_df[sapply(list_df, nrow) == 30]

We can also use purrr::keep
purrr::keep(list_df, ~nrow(.) == 30)


text:
Q: Is it possible in Grafana using a source data table with a JSON field, to get an attribute from that field? We configure Grafana to use a table input data source, it works very well with the fields already defined (like time, status, values, etc.).
But now a new field has been added to the table that is a serialized JSON object, returned from a process we can not modify.
We need to use a value (timestamp) that is a property of this serialized object in that table string field.
One serialized field value example is this:
{"timestamp":"2020-02-23T18:25:44.012Z","status":"fail","errors":[{"timestamp":"2020-02-23T18:25:43.511Z","message":"invalid key: key is shorter than minimum 16 bytes"},{"timestamp":"2020-02-23T18:25:43.851Z","message":"unauthorized: authorization not possible"}]}

The pretty print is:
{
  "timestamp": "2020-02-23T18:25:44.012Z",
  "status": "fail",
  "errors": [
    {
      "timestamp": "2020-02-23T18:25:43.511Z",
      "message": "invalid key: key is shorter than minimum 16 bytes"
    },
    {
      "timestamp": "2020-02-23T18:25:43.851Z",
      "message": "unauthorized: authorization not possible"
    }
  ]
}

Is there any way to use a value like: field.timestamp or field.errors[0].timestamp ?
Is there a Plugin that allows it ?, or is not possible at all ?

A: Use PostgreSQL JSON column select in your Grafana query, e.g.:
SELECT
  field->'timestamp',
...


text:
Q: Is 'mathematics formulas' correct? I'm reading a book in which I spotted a mistake, I think. The full part of the sentence reads:

In mathematics formulas you can use \{ and \} for { and }, […]

Shouldn't this be "mathematical formulas"?

A: I believe the book you are reading is The TeXbook by Donald E. Knuth. Considering the name of the author, I believe that this is intentional rather than a typo.
In this book, you can find numerous places where he writes mathematical formula (and of course, mathematical formulas). However, also in the book are terms such as mathematics printing, mathematics mode, and mathematics typing.
So, in my humble opinion, the author uses the term mathematics formulas in this specific place (and it is the only place in the book that you will find this term) to emphasize the sense of typesetting. (I haven't seen anyone write mathematical formulas with \{ and \} in any book anyway.) In other words, he wants to remind the reader of the typesetting of mathematical formulas in the context of TeX, not mathematical formulas in general.


text:
Q: Annotate returning null on non-existent values and I want to convert this to null into empty string I have two models , Customer and Purchase. I want to return the last store that the customer purchased from and order on this.
I can successfully show this list, showing last store the Customer purchased from, and being able to order on store name, using the following models, query/subquery.
# models
class Customer(models.Model):

    name = models.CharField(max_length=30)

class Purchase(models.Model):

    store = models.CharField(max_length=30)
    amount = models.DecimalField(decimal_places=2,max_digits=6)
    customerID = models.ForeignKey(Customer, on_delete=models.CASCADE,
                                   related_name='purchases')
    order_date = models.DateField()

#viewset

#subquery
purchase_qs = Purchase.objects.filter(customerID=OuterRef("pk")).order_by("-order_date")

queryset = Customer.objects.all().annotate(last_purchase=Subquery(purchase_qs.values('store')[:1]))

ordering_fields = ['last_purchase']

My Current Output for Customers who have zero Purchases is.
"last_purchase":null
I want to have
"last_purchase":""

A: ForeignKey fields automatically append _id to the name of the model field, so you'd need to use customerId_id to reference the ForeignKey.  Clearly this isn't what you want, so I'd recommend renaming the field to customer instead, also I think this is why your query is blank.
With that being said, you don't really need Subquery or OuterRef for this. Instead you can use the reverse relation of your Customer model, along with Max:
from django.db.models import Max

Customer.objects.select_related('Purchase').annotate(
    last_purchase = Max('purchases__order_date')
)

Lastly, the null key is False by default so no need to say null=False, and it doesn't make sense to have blank=True but null=False.  See this question for an excellent explanation about what the differences between null and blank are.
Update
The Coalesce function seems to be perfect for this scenario:
from django.db.models import Max, Coalesce, Value

Customer.objects.select_related('Purchase').annotate(
    last_purchase = Coalesce(Max('purchases__order_date', Value(''))
)


text:
Q: Delta lake and ADLS Gen2 transactions We are running a Delta lake on ADLS Gen2 with plenty of tables and Spark jobs. The Spark jobs are running in Databricks and we mounted the ADLS containers into DBFS (abfss://delta@<our-adls-account>.dfs.core.windows.net/silver). There's one container for each "tier", so bronze, silver, gold.
This setup has been stable for some months now, but last week, we've seen a sudden increase in transactions within our storage account, particularly in the ListFilesystemDir operations:

We've added some smaller jobs that read and write some data in that time frame, but turning them off did not reduce the amount of transactions back to the old level.
Two questions regarding this:

*

*Is there some sort of documentation that explains which operation on a Delta table causes which kind of ADLS transactions?

*Is it possible to find out which container/directory/Spark job/... causes this amount of transactions, without turning off the Spark jobs one by one?

A: If you go into logs from your data lake (if you have log analytics enabled) you can view the exact timestamp, caller and target of the spike. Take that data and go into your databricks cluster and navigate to Spark UI. In there you should be able to see timestamps and jobs. There you can find what notebook is causing it.


text:
Q: HITS centrality I want the centrality measure of a particular vertex in my graph, and for Closeness, Betweenness and Degree centralities I have been using :
Pick[bc, VertexList[graph1], 1 ]

However, for HITSCentrality, the result is in two lists, and I'm not sure how to pick out the two values for a single node.
Something like this isn't working...
Pick[bc, VertexList[graph1], {1,1} ]

A: For HITSCentrality you could try
Pick[Transpose[HITSCentrality[graph1]], VertexList[graph1], 1]


text:
Q: convert bash pipeline into a function with parameter I have a pipeline I use to preview csv files:
cat file_name.csv | sed -e 's/,,/, ,/g' | column -t -s ","| less -s
But i want to create an alias viewcsv that will allow to just replace the filename.
I tried viewcsv="cat $1 | sed -e 's/,,/, ,/g' | column -t -s ","| less -s" but that didn't work.  Googling turned up that I need to convert this pipeline to a function?  How can i convert this to a function so that viewcsv file_name.csv will return same output as cat file_name.csv | sed -e 's/,,/, ,/g' | column -t -s ","| less -s does?

A: Function syntax looks like this:
viewcsv() {
    sed -e 's/,,/, ,/g' "$1" | column -t -s ","| less -s
}

Notice that I have replaced cat "$1" | sed with sed "$1".
csvkit has a CSV previewer, by the way:
$ csvlook <<< $'a,b,c\n10,20,30'
|  a |  b |  c |
| -- | -- | -- |
| 10 | 20 | 30 |


text:
Q: Use Tshark to view json data When I use tshark to decode capfile like this
 tshark -V -r test.cap  -Y 'http>0'

I got
...
JavaScript Object Notation: application/json
    Object
        Member Key: "ret"
            Number value: 99
        Member Key: "message"
            String value:test

Question is how I can get json data like that use tshark
...
{"ret":99,"message":"test"}

A: tshark -r test.cap  -Y 'http>0' -T json

tshark -r test.cap  -Y 'http>0' -T json -x # to also include the raw packet data

A: Had similar problem.
Failed to solved it with wireshark/tshark options only.
Below is my workaround for extracting raw json and xml from cap files.
# 1. convert to pdml with DISABLED json and xml dissectors
tshark -r "wireshark.cap" -2 -R "http" --disable-protocol json --disable-protocol xml -V -T pdml > "wireshark.cap.pdml.xml"

# 2. get hex encoded raw data from media.type pdml element
# 3. perform hex decode

I used groovy script for steps 2 and 3
import groovy.xml.*

...

def String hexDecode(String s) {
    if ( null == s || 0 == s.length() ) {
            return null
    }
    def res = ""
    for (int i = 0; i < s?.length(); i += 2) {
            res += (Character)((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16))
    }
    return res
}

...

def xmlFile = new File("wireshark.cap.pdml.xml")
def pdml  = new XmlParser().parseText( xmlFile.text )
pdml.packet.each{ packet->
    def media = packet.proto.find{ "media"==it.@name }
    def hex  = media?.field.find{"media.type"==it.@name }?.@value
    def raw = hexDecode(hex)
}

A: I'm not quite sure what "how I can get json data like that use tshark" means.  The JavaScript info you saw when you ran tshark looks like that because tshark parses application/json bodies as JSON and displays the JSON information in pretty output like you see.  If you don't want it to do that, you'd need to disable the JSON protocol/dissector; unfortunately I don't believe there is a way to disable protocols in tshark, but there is in wireshark (go to menu Analyze->Enabled Protocols and uncheck the JSON one).


text:
Q: Voltage supply for an IC circuit I'm currently working on setting up a logic circuit using ICs (SN74LS08N, HD74LS04P and CD4075BCN) and LEDs. I looked at their datasheets and I found that the maximum voltage supply to the ICs is 5.25V.
Which type of battery should I use as the source?
I currently found 2 solutions on the internet, one is getting a 9V battery with LM7805 voltage regulator IC and the other one is connecting 3 AAA batteries in series.
Which one is better for my circuit?

A: Since you have planned to use battery as a power source with Logic gates, it is better to use low quiescent current regulators than 7805. Because 7805 is old one. There are new and upgraded regulators for low quiescent current applications.
With that in mind, you can use MCP1702 series regulator for your project. The main objective here is you are using battery. So, the current consumption from the battery should be less in order to extend the life of battery whether it is 9V or AAA batteries.
So, I suggest this IC for you. The delivering current of MCP1702 is more than enough for Logic gates ICs. More info you can found in it's data sheet.
Circuit is so simple as you might have seen in 7805 circuit.
Data sheet : https://www.microchip.com/wwwproducts/en/en028178

A: I sometimes use 4 NiMH AA or AAA cells in series for approximately 5V.  Freshly charged they can exceed the 5.25V, but not usually by much and under load they drop a little further.  Their nominal voltage is only 1.2 volts each but fresh off a charger they can read around 1.4V.  They will drop down from that pretty rapidly under load (eg. a flashlight).  For a little security you could always put a 1n4002 type rectifier in series to drop the voltage by a bit, but I've never bothered.  They don't hold that high voltage for very long and settle into the region of their nominal voltage pretty quickly for the long haul.
The nice thing about NiMH is they have a pretty flat discharge curve, meaning that your circuit will stay in the operating voltage region for longer before the battery is too exhausted to power the circuit, compared to using 3 alcaline cells, which lose voltage even faster owing to their steeper discharge curve.

A: Just use a 9 volt battery and a 7805 regulator.

*

*You can get a 7805 from wherever you got your logic ICs.  Other regulators aren't as commonly available, and other regulators aren't as forgiving as the 7805 (it isn't picky about the surrounding circuit and is pretty rugged electrically.)

*9 volt batteries can't deliver enough current to burn things out if you wire something wrong.

*It is easy to tell when to replace the battery - when the 7805 output drops below 5V.

Simple and reliable is best if you are just beginning.
I mean, consider what happens if your circuit doesn't work.
If you are using one of the "better" regulators, then they can oscillate if the circuit (input and output capacitance) is wrong.  The output voltage will be wrong (and vary thousands of times a second.) How will you find that as a beginner?
If you use a stack of 1.5V batteries, how will you be sure that you didn't get more than 5V long enough to damage something?

*

*Only power the circuit when you are using it (saves battery power.)

*Use a new battery when you go to demonstrate it to your instructor.

*Buy a bunch of 100 nanofarad capacitors when you buy your 7805.  Place one 100nF capacitor across the power supply pins of every IC in the circuit - right at the IC.  Everytime a digital IC switches states, it draws a spurt of current.  That can cause the voltage at the IC to dip, which can cause the IC to misbehave.  The capacitors make up for the little spurts and keep the voltage steady - your circuit will be more reliable.  These are known as "decoupling capacitors."

*If your circuit doesn't work, you can touch the ICs with your finger.  If any IC is noticeably warmer than the others, then you can start looking for wiring problems around that IC. A 9 volt battery can deliver enough current to make things get warm, but not enough to burn your finger (or go bang.)  The AA 1.5V cells can easily deliver enough current to burn a finger or worse.

*Build your 5V regulator circuit by itself first, and make sure it delivers 5V before you attach any of your logic ICs to it.

The other answers give good advice in general, but you are a student just starting out.  Simple and reliable are more important than any other considerations - for now.
As you go further into electronic things, you can look into more sophisticated regulators or other batteries.
For now, do what always works and has a very low chance of going wrong - you aren't yet equipped to deal with problems.

A: You could use a USB power supply (or cell phone charger - same thing) as a 5 volt power supply - saves buying batteries.


text:
Q: How to get second column value of invoked row in table? In below context menu example .. how to get value of second column that invoked it?
Refer Link
tried with $(this).find('td:second').text() but it didnt work. :P
How to do this?

A: No need to write such this long code here. Just assign a class name to each <tr> like row then add click event listener like this:
$(".row").click(function () {
  var txt = $(this).children().eq(1).text();
  alert(txt);
});

jsfiddle

A: You can get your row or invoked row then use cells proberty to access second column
$(".row").click(function () {
  var colText = $(this).cells[1].textContent;
  // or-> var colText = row.cells[1].textContent;
});


text:
Q: LC4VF, Summer 2016: The $Lightning.use function works in Developer Org but gets 500 Error in Sandbox How do I eliminate or work around a 500 error preventing me from using Lightning components on a VisualForce page in a sandbox? Identical code works in a dev org but fails in a sandbox.
Note: In the sandbox I used, the "My Domain" feature is in a "Ready for Testing but Hidden from Users" state, whereas in the dev org I used, the "My Domain" feature is in a fully deployed state.
Only mentioning My Domain for good measure, since this document says:

Finally, you don't need to enable My Domain to use Lightning
  components in the following contexts.

*

*Lightning components with Communities in Community Builder

*Lightning Components for Visualforce

Copious details below.
Inputs
Sample code taken verbatim from Lightning Components Developer Guide.
lcvfTest.app
<aura:application access="GLOBAL" extends="ltng:outApp">
    <aura:dependency resource="ui:button"/>
</aura:application>

lcvfTest.vfp
<apex:page >
    <apex:includeLightning />

    <div id="lightning" />

    <script>
        $Lightning.use("c:lcvfTest", function() {
          $Lightning.createComponent("ui:button",
          { label : "Press Me!" },
          "lightning",
          function(cmp) {
            // do some stuff
          });
        });
    </script>
</apex:page>

Results
Dev org succeeded but Sandbox failed.
Dev Org
Renders a button, just as described in the documentation.
Sandbox Org
No Button is rendered. The browser's debug console reveals a request which fails with a 500 error.
(Note: In the following output, hash-like values in the "loaded" object were replaced with fictitious ones, since I do not know whether the hashes contain private information. Custom domain values are also fictitious. The "fwid" values are not fictitious.)
The URL of the request which triggered a 500 error was:
https://my-custom-domain--my-sandbox-name.cs2.my.salesforce.com/l/%7B%22mode%22%3A%22PROD%22%2C%22app%22%3A%22c%3AlcvfTest%22%2C%22fwuid%22%3A%22HARM87fxppWmsEY_Ve9awQ%22%2C%22loaded%22%3A%7B%22APPLICATION%40markup%3A%2F%2Fc%3AlcvfTest%22%3A%22N7gJLRFbk4dlneywPZJt2f%22%7D%2C%22requestedLocales%22%3A%5B%22en_US%22%2C%22en%22%5D%2C%22ls%22%3A%22YN%22%7D/inline.js

Opening this URL in its own browser tab yields the following content (indentation added by me):
aura.error(
{
    "exceptionEvent":true,
    "event": {
        "descriptor":"markup://aura:clientOutOfSync",
        "eventDef": {
            "s":1,
            "v": {
                "descriptor":"markup://aura:clientOutOfSync",
                "type":"APPLICATION",
                "superDef": {
                    "s":2,
                    "v": {
                        "descriptor":"markup://aura:applicationEvent",
                        "type":"APPLICATION",
                        "xs":"G",
                        "attributes":{}
                    }
                },
                "attributes":{}
            }
        }
    },
    "defaultHandler":"function() {$A.clientService.setOutdated()}"
});

The large URL-encoded portion of the URL above decodes to this (indentation added by me):
{
    "mode":"PROD",
    "app":"c:lcvfTest",
    "fwuid":"HARM87fxppWmsEY_Ve9awQ",
    "loaded":
    {
        "APPLICATION@markup://c:lcvfTest":"N7gJLRFbk4dlneywPZJt2f"
    },
    "requestedLocales":["en_US","en"],
    "ls":"YN"
}

Environments Tested
Attempted some additional setups other than those above. Here is a full list of environments tested (including the above), with results:

*

*Failed: A Sandbox (on cs2) for a Summer 2016 Enterprise org, created
before June 11. My Domain in a Testing phase of deployment.

*Failed: Another Sandbox (on cs44) for org #1, created on July 19. My Domain in a testing phase of deployment.

*Succeeded: A Developer Edition org. My Domain fully deployed.

*Succeeded: Another Developer Edition org. My Domain fully deployed.

*Succeeded: A sandbox for an Unlimited Edition org, unrelated to org #1 and created before June 11. My Domain fully deployed.

Possible Stack Trace
While I do not know how to access a server-side exception log for the Aura framework, I have attempted to piece together a stack trace by manually inspecting the Aura source code from github. The result of my attempt is as follows:

*

*AuraResourceServlet.doGet: Line 124

*TemplateResource.write: Line 68

*TemplateResource.internalWrite: Line 87

*DefinitionServiceImpl.updateLoaded: Line 209


text:
Q: python json search from multiple URLs i have tow urls or json file and both have the same ID looks this.
file1
{
    {
    "code": 200,
    "students": [
        {
            "student": "John, Doe",
            "Total Marks": "79%",
            "math": 55,
            "Sience": 56

        },
        {
            "student": "Jame, George",

            "Total Marks": "99%",
            "math": 55,
            "Sience": 56
        }
    ]
}

file2
{
     {
    "code": 200,
    "students": [
        {
            "student": "John, Bill",
            "Total Marks": "69%",
            "math": 58,
            "Sience": 46

        },
        {
            "student": "Joe, Ham",

            "Total Marks": "49%",
            "math": 25,
            "Sience": 26
        }
    ]
}

i want to search for student name on both json from URL to get the marks.
for example i want to Search for John i should get both John Doe and Bill

A: Your JSON is invalid. You can use JSONLint to validate your JSON, and fix any errors.
Your JSON should look like the below after validating:
{
    "code": 200,
    "students": [
        {
            "student": "John",
            "Total Marks": "79%",
            "math": 55,
            "Sience": 56

        },
        {
            "student": "Jame",
            "Total Marks": "99%",
            "math": 55,
            "Sience": 56
        }
    ]
}

As you can see the JSON was missing a couple of " quotes and had extra , commas trailing in each object, which will cause errors when deserializing your JSON to an object. For demonstration purposes, I will show how to read JSON from a file called data.json.
First we can make a function that goes through a JSON array and finds a student based on a given name:
def get_student(data, name):
    for item in data:
        if item["student"] == name:
            return item

We can also have it return a list of names using a list comprehension:
def get_student(data, name):
    return [item for item in data if item["student"] == name]

Then we can open the JSON file with a with context manager and deserialize the JSON with json.load. We can then call get_student() on the students JSON array:
from json import load
from json import JSONDecodeError

with open("C:\\data.json") as json_file:
    try:
        data = load(json_file)
        print(get_student(data["students"], 'John'))
    except JSONDecodeError as ex:
        print(ex)

Which returns the following student object:
{'student': 'John', 'Total Marks': '79%', 'math': 55, 'Sience': 56}

If no student was found, get_student() will simply return None. I also used try..except to catch and print any errors with the JSON deserialization, which will trigger a json.JSONDecodeError exception if the JSON file is invalid.
Update from Question
For making the above work with multiple JSON files(Just 2 in this case, as updated in your question), you can try out the below code. It adds extra logic to split the names by "," and compare the first names. To make sure names like John and john are considered equal, we can make both first names lowercase with .lower(). Additionally, It is better design to make first names and last names separate fields however.
from json import load
from json import JSONDecodeError

def get_student_by_firstname(data, first_name):
    for item in data:
        try:
            firstname, _ = map(str.strip, item["student"].split(","))
        except ValueError:
            firstname = item["student"].strip()

        if firstname.lower() == first_name.lower():
            return item

files = [
    "C:\\data1.json",
    "C:\\data2.json"
]

for path in files:
    with open(path) as json_file:
        try:
            json_data = load(json_file)
            print(get_student_by_firstname(json_data["students"], first_name="John"))
        except JSONDecodeError as ex:
            print(ex)

Output:
{'student': 'John, Doe', 'Total Marks': '79%', 'math': 55, 'Sience': 56}
{'student': 'John, Bill', 'Total Marks': '69%', 'math': 58, 'Sience': 46}


text:
Q: Set RelativeLayout backgroundColor using java code I have
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/mainRelativeLayout">

and I'm trying to setup the background using java code (I don't want to do it in xml) using this code in onCreate method:
View view = (View)findViewById(R.id.mainRelativeLayout);
        view.setBackgroundColor(0xFF000000);

or this code:
View view = (View)findViewById(R.id.mainRelativeLayout);
        view.setBackgroundColor(android.R.color.white);

However, it fails at first line when it tries to find the id. Where's the problem? Thanks
start of my onCreate() code:
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getPrefs();
        if (themePreference) {
            setTheme(android.R.style.Theme_Light_NoTitleBar);
        }else{
            setTheme(android.R.style.Theme_Black_NoTitleBar);
        }
        setContentView(R.layout.main);
        /*View view = (View)findViewById(R.id.mainRelativeLayout);
        view.setBackgroundColor(0xFF000000);*/

        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

        this.submitBtn = (Button) this.findViewById(R.id.submitBtn);
        this.cleanBtn = (Button) this.findViewById(R.id.clear_txt_Input);
        this.inputQ = (EditText) this.findViewById(R.id.inputQ);
        ...

stack trace:
myApp [Android Application]
    DalvikVM[localhost:8610]
        Thread [<1> main] (Suspended (exception RuntimeException))
            ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 1768
            ActivityThread.handleLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 1784
            ActivityThread.access$1500(ActivityThread, ActivityThread$ActivityClientRecord, Intent) line: 123
            ActivityThread$H.handleMessage(Message) line: 939
            ActivityThread$H(Handler).dispatchMessage(Message) line: 99
            Looper.loop() line: 130
            ActivityThread.main(String[]) line: 3835
            Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
            Method.invoke(Object, Object...) line: 507
            ZygoteInit$MethodAndArgsCaller.run() line: 847
            ZygoteInit.main(String[]) line: 605
            NativeStart.main(String[]) line: not available [native method]
        Thread [<8> Binder Thread #2] (Running)
        Thread [<7> Binder Thread #1] (Running)

A: Were you able to run your app successfully without changing the background color?  Because I was able to run a simplified version of your code without any errors.  I think your error might be elsewhere.
Have you tried using Project > Clean to clean and rebuild your project?
Here is the test code I used.
The Activity:
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    View view = findViewById(R.id.mainLayout);
    view.setBackgroundColor(0xFFEE3333);
}

And the XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/mainLayout">

    <Button
    android:id="@+id/button"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Stack Overflow"/>

</RelativeLayout>


text:
Q: Conflict between Bfrtip (buttons) and number dropdown Here is my code for a datatables implementation:
<script type="text/javascript" src="../js/jquery-3.1.1.min.js" ></script>
<script type="text/javascript" src="../js/jquery-ui.js" ></script>
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.4.2/css/buttons.dataTables.min.css" type="text/css" media="all">
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.4.2/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/1.4.2/js/buttons.flash.min.js"></script>
<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/vfs_fonts.js"></script>
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/1.4.2/js/buttons.html5.min.js"></script>

var table = $('#TransactionsTable').DataTable( {
    dom: 'Bfrtip',
    buttons: [
        'copy',
        'csv',
        'excel'
    ],
    "order": [[6, "desc"]],
    "columnDefs": [
       {
          "visible": false,
            "targets": [8]
       }
    ]
} );

I have a problem with the line "dom: 'Bfrtip',". If I include it, the buttons show, but the dropdown that allows you to select number of entries (e.g. show 10, 25, 50, 100 entries) disappears. If I remove that line the dropdown comes back but the buttons don't show. Why do I need to choose? How can I have both?

A: use dom: 'Blfrtip'. Note that there is an 'L' after B

A: Use dom: 'Blfrtip', to make the "per page" selector appear.
Notice I've included l there, it stands for length changing input control.
See the docs for more info.


text:
Q: Setup wordpress as subpath but in different root Main site: example.com in /var/www/example.com.
Wordpress blog: example.com/blog in /var/www/blog.
Can't make it work.
server {
    listen 80;

    server_name example.com;

    root /var/www/example.com;

    # Add index.php to the list if you are using PHP
    index Index.html index.html index.htm index.nginx-debian.html;

    location ~* \.(ico|jpg|jpeg|png|gif|swf|css|json|txt|sd|html)$ {
            try_files $uri =404;
            access_log off;
            expires 1d;
    }

    location ~* \.(js)$ {
        gzip_static on;
        gunzip on;
        try_files $uri =404;
        access_log off;
        expires 1d;
    }

    location /blog {
        alias  /var/www/blog/;
        #try_files $uri $uri/ /index.php?q=$request_uri;
        try_files $uri $uri/ @blog;

        location ~ \.php$ {
            fastcgi_split_path_info ^(.*\.php)(.*)$;
            try_files $uri =404;
            include       /etc/nginx/fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param PATH_INFO $fastcgi_path_info;
            fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
            fastcgi_pass unix:/run/php/php7.4-fpm.sock;
            #fastcgi_index index.php;

             #include the fastcgi_param setting
            include fastcgi_params;
        }
    }

    location @blog {
            rewrite ^/blog(.*) /blog/index.php?q=$1;
    }
}

For http://example.com/blog got 403 Forbidden. Looks like alias doesn't work with try_files.
But even http://example.com/blog/index.php doesn't work. Got File not found. .


text:
Q: Sending json file through Http Post curl I have been working with Jenkins, and now Im stuck when I try to make an HTTP Post using curl, I am sending a json file, to a file in my page who is waiting for it, and then do some functions, the code I am using is the following:
curl -X POST -k -i -H "Accept: application/json" -w "%{body}" -w "%{http_code}" -d "@/var/lib/jenkins/workspace/myFolder/session.json" http://mypage.com/myFolder/newfile.php
But apparently Im not sending correctly the data of the file, the newfile.php has something like this:
echo $_REQUEST['sessionId'];
But always get an error when I try to echo the index sessionId, I mean my file "newfile.php" is not getting anything from my jenkins curl, can you help me out?
Thanks in advance!!

A: The JSON that you send is in the request body.  The keys/values will not be available in the $_REQUEST array, hence why you are getting the error.  You will need to access the request body in order to get the sessionId property.
$requestBody = file_get_contents('php://input');
$session = json_decode($requestBody);
$sesionId = $session["sessionId"];
echo "Session ID: $sessionId";

The file_get_contents('php://input') returns the body of the POST request.
Make sure to also add the appropriate Content-Type header to your post request:
curl -X POST -k -i -H "Accept: application/json" -H "Content-Type: application/json" -w "%{body}" -w "%{http_code}" -d "@/var/lib/jenkins/workspace/myFolder/session.json" http://mypage.com/myFolder/newfile.php`


text:
Q: Copy text from host to Vbox How to copy text from windows7-host to linux CentOS7 in virtualbox without using VboxAdditions and shared folders?Is it really possible just using keyboard and mouse?

A: AFAIK with out installing VboxAdditions  , no you cant unless you have taken remote access(internally) via SSH so you can access via Putty or other SSH tools to access.


text:
Q: Execution flow in MVC I am trying to learn MVC in detail, and I am wondering what's the exact functional flow internally, in the sense of which functions (important functions) are called and what they do when the application starts and what functions are called apart from the controller actions that we write in our application as we proceed.

A: Check out Redgates's free "The ASP.NET MVC Request Handling Pipeline" poster for execution flow
and Steven Sanderson's MCV book for details.

A: Here are the detailed steps:

*

*Request comes into ASP.NET

*ASP.NET Routing finds the route match by calling RouteCollection.GetRouteData

*This in turn calls RouteBase.GetRouteData on each route until it finds a match

*The IRouteHandler for the matching route has its GetHttpHandler method called

*The MvcHandler runs (ProcessRequest is called)

*The MVC controller factory locates and creates the controller in CreateController

*The ControllerActionInvoker determines which action to run in InvokeAction

*The AuthorizationFilter stage executes (this includes the authorization method on the controller itself)

*The ActionExecuting stage executes

*The requested action method is executed

*The ActionExecuted stage executes

*If there is a result object then the ResultExecuting stage executes

*If the result wasn't cancelled then the ActionResult's ExecuteResult method is executed

*The ResultExecuted stage executes

*If an error occured then the Exception stage executes

I would also like to refer you to the MVC Snake Diagram that I use in many presentations on ASP.NET MVC. Here's the full image:
The blog post I linked to describes some of the concepts used in ASP.NET MVC regarding how data flows through the application.


text:
Q: How to add custom field or attribute to customer's address and API and save it in magento2? I have created my custom field and attribute, using following code and it is reflected in db.
$attributesInfo = [
            'state' => [
                'label' => 'State',
                'type' => 'static',
                'input' => 'text',
                'position' => 140,
                'visible' => true,
                'required' => false,
            ],
        ];

        $columns = [
                    'state' => [
                        'type' => Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                        'nullable' => false,
                        'LENGTH' =>255,
                        'comment' => 'State',
                    ],
                ];

        foreach ($attributesInfo as $attributeCode => $attributeParams) {
            $customerSetup->addAttribute('customer_address', $attributeCode, $attributeParams);
        }

        $tableNames=['customer_address_entity','quote_address','sales_order_address'];

          // Declare data

        $connection = $setup->getConnection();
        foreach ($tableNames as $tableName) {
            foreach ($columns as $name => $definition) {
                $connection->addColumn($tableName, $name, $definition);
            }
        }

and i created my fieldset.xml
<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:DataObject/etc/fieldset.xsd">
    <scope id="global">
        <fieldset id="customer_address">
            <field name="state">
                <aspect name="create" />
                <aspect name="update" />
                <aspect name="to_quote_address" />
            </field>
        </fieldset>
        <fieldset id="sales_convert_order_address">
            <field name="state">
                <aspect name="to_quote_address" />
            </field>
        </fieldset>
        <fieldset id="sales_convert_quote_address">
            <field name="state">
                <aspect name="to_order_address" />
                <aspect name="to_customer_address" />
            </field>

        </fieldset>
        <fieldset id="sales_copy_order_billing_address">
            <field name="state">
                <aspect name="to_order" />
            </field>
        </fieldset>
        <fieldset id="order_address">
            <field name="state">
                <aspect name="to_customer_address" />
            </field>
        </fieldset>
    </scope>
</config>

and then i edited edit.phtml file and added my custom field state
but after i clicked save address  the data is not saving in db , do i need to do any thing extra to save the data in db ?

A: For Magento 2.2
In the case of customer address, saving extension attributes is a little bit different as explained in the documentation of Magento for Product entities. http://devdocs.magento.com/guides/v2.2/extension-dev-guide/extension_attributes/adding-attributes.html
The following steps needs to be done:

*

*Create an etc/extension_attributes.xml and define the attribute for the Magento\Customer\Api\Data\AddressInterface

*Create a etc/fieldset.xml file if you wish that your custom attributes will be copied from the checkout shipping address fieldset into the customer address fieldset. This is extra, you don't need it if you don't use the information for the checkout or other areas.

*Create an UpgradeData.php script to create the attribute

*Create an UpgradeSchema.php if you want to set your attribute as a static. Important here is that the attribute is not a system one, otherwise it won't be recognized internally as a custom attribute and won't be saved.

*Then you need to overwrite and update edit.phtml template for the address form

You don't need at all a plugin in this case.
Here are some sample code for the different files explained before
extension_attributes.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
    <extension_attributes for="Magento\Customer\Api\Data\AddressInterface">
        <attribute code="my_attribute" type="string"/>
    </extension_attributes>
</config>

fieldset.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:DataObject/etc/fieldset.xsd">
    <scope id="global">
        <fieldset id="customer_address">
            <field name="my_attribute">
                <aspect name="to_quote_address" />
            </field>
        </fieldset>
    </scope>
</config>

UpgradeData.php Create the attribute
<?php
namespace MyNamespace\Modulename\Setup;

use Magento\Customer\Model\Customer;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;

/**
 * Class InstallSchema
 */
class UpgradeData implements UpgradeDataInterface
{
    /**
     * @var \Magento\Customer\Setup\CustomerSetupFactory
     */
    protected $customerSetupFactory;

    /**
     * UpgradeData constructor.
     *
     * @param \Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory
     */
    public function __construct(CustomerSetupFactory $customerSetupFactory)
    {
        $this->customerSetupFactory = $customerSetupFactory;
    }

    /**
     * @param ModuleDataSetupInterface $setup
     * @param \Magento\Framework\Setup\ModuleContextInterface $context
     */
    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();

        /* @var $customerSetup \Magento\Customer\Setup\CustomerSetup */
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

        if (version_compare($context->getVersion(), '1.0.3', '<')) {

            $attributesInfo = [
                Data::ATTR_PREFIX . 'my_attribute'  => [
                    'label'    => 'My Attribute',
                    'type'     => 'varchar', // can be static too
                    'input'    => 'text',
                    'position' => 81,
                    'visible'  => true,
                    'required' => false,
                    'system'   => 0, // Important otherwise attribute is not seen as custom attribute
                ],
            ];

            foreach ($attributesInfo as $attributeCode => $attributeParams) {
                $customerSetup->addAttribute('customer_address', $attributeCode, $attributeParams);
            }

            foreach ($attributesInfo as $attributeCode => $attributeParams) {

                $attribute = $customerSetup->getEavConfig()->getAttribute('customer_address', $attributeCode);
                $attribute->setData(
                    'used_in_forms',
                    ['adminhtml_customer_address', 'customer_address_edit', 'customer_register_address']
                );
                $attribute->save();
            }
        }

        $setup->endSetup();
    }
}
?>

UpgradeSchema.php if case you use want a static attribute, update the DB table of customer address
<?php
namespace MyNamespace\Modulename\Setup;

use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

/**
 * Upgrade the Quote module DB scheme
 */
class UpgradeSchema implements UpgradeSchemaInterface
{
    /**
     * @var string
     */
    private static $connectionName = 'checkout';

    /**
     * {@inheritdoc}
     */
    public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();

        $setup->getConnection(self::$connectionName)->addColumn(
            $setup->getTable('customer_address', self::$connectionName),
            'my_attribute',
            [
                'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                'length' => 255,
                'comment' => 'My attribute'
            ]
        );

        $setup->endSetup();
    }
}
?>

view/frontend/layout/customer_address_form.xml to insert your own edit.phtml form
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<update handle="customer_account"/>

    <referenceBlock name="customer_address_edit">
        <action method="setTemplate">
            <argument name="template" xsi:type="string">MyNamespace_Modulename::address/edit.phtml</argument>
        </action>
    </referenceBlock>

</page>

view/frontend/templates/address/edit.phtml Template of the address form to improve
...

        <?= $block->escapeHtml(__('My Attribute')) ?>

            <input type="text"
                   name="my_attribute"
                   id="my_attribute"
                   value="<?= $block->escapeHtmlAttr($block->getAddress()->getCustomAttribute('my_attribute')->getValue()) ?>" />

...

A: create the attribute as shown below in community version , if its EE then magento2 default provide add attribute for custom and customer address from admin side and also you can use below code to create custom customer attribute pragmatically in magento2
   $attributesInfo = [
        'state' => [
            'label' => 'State',
            'type' => 'static',
            'input' => 'text',
            'position' => 160,
            'visible' => true,
            'system'=>0,
            'is_user_defined' => 1,
            'required' => false,
        ],
    ];

    foreach ($attributesInfo as $attributeCode => $attributeParams) {
        $customerSetup->addAttribute('customer_address', $attributeCode, $attributeParams);
        $customerSetup->getEavConfig()->getAttribute('customer_address', $attributeCode)
            ->setData('used_in_forms', ['customer_address_edit','customer_register_address','adminhtml_customer_address'])
            ->save();
    }


text:
Q: Boost ASIO streambuf I am confused about the input sequence and output sequence in boost asio::streambuf classes.
According to the code examples (for sending data) in the documentation it seems that the buffer representing the input sequence is used for writting to socket and the one representing the output sequence is used for reading.
Example -
boost::asio::streambuf b;
std::ostream os(&b);
os << "Hello, World!\n";
// try sending some data in input sequence
size_t n = sock.send(b.data());
b.consume(n); // sent data is removed from input sequence

Now, is there a nomenclature problem?

A:
"Everything is relative"
Albert Einstein

The documentation says:

Characters written to the output sequence of a basic_streambuf object are appended to the input sequence of the same object.

From the point of view of the streambuf it will read from its output sequence and write into its input sequence which might seem kind of inverted, but you can think of the streambuf as a pipe for things to make sense.
From the user (anything that uses the streambuf, including sockets) point of view now, you will write into the ouput sequence of the streambuf and read from its input sequence which seems more natural.
So yeah the same way left and right are inverted depending on what you're facing, inputs and outputs are inverted depending from which side you look at it.

"Don't believe every quote you read on the internet, because I totally didn't say that"
Albert Einstein

A: The nomenclature for boost::asio::streambuf is similar to that of which is defined in the C++ standard, and used across various classes in the standard template library, wherein data is written to an output stream and data is read from an input stream.  For example, one could use std::cout.put() to write to the output stream, and std::cin.get() to read from the input stream.
When manually controlling the streambuf input and output sequences, the general lifecycle of data is as follows:

*

*Buffers get allocated with prepare() for the output sequence.

*After data has been written into the output sequence's buffers, the data will be commit()ed.  This committed data is removed from the output sequence and appended to the input sequence from which it can be read.

*Data is read from the input sequence's buffers obtained via data().

*Once data has been read, it can then be removed from the input sequence by consume().

When using Boost.Asio operations that operate on streambuf or stream objects that use a streambuf, such as std::ostream, the underlying input and output sequences will be properly managed.  If a buffer is provided to an operation instead, such as passing passing prepare() to a read operation or data() to a write operation, then one must explicitly handle the commit() and consume().
Here is an annotated version of the example code which writes directly from an streambuf to a socket:
// The input and output sequence are empty.
boost::asio::streambuf b;
std::ostream os(&b);

// prepare() and write to the output sequence, then commit the written
// data to the input sequence.  The output sequence is empty and
// input sequence contains "Hello, World!\n".
os << "Hello, World!\n";

// Read from the input sequence, writing to the socket.  The input and
// output sequences remain unchanged.
size_t n = sock.send(b.data());

// Remove 'n' bytes from the input sequence. If the send operation sent
// the entire buffer, then the input sequence would be empty.
b.consume(n);

And here is the annotated example for reading from a socket directly into an streambuf.  The annotations assume that the word "hello" has been received, but not yet read, on the socket:
boost::asio::streambuf b;

// prepare() 512 bytes for the output sequence.  The input sequence
// is empty.
auto bufs = b.prepare(512);

// Read from the socket, writing into the output sequence.  The
// input sequence is empty and the output sequence contains "hello".
size_t n = sock.receive(bufs);

// Remove 'n' (5) bytes from output sequence appending them to the
// input sequence.  The input sequence contains "hello" and the
// output sequence has 507 bytes.
b.commit(n);

// The input and output sequence remain unchanged.
std::istream is(&b);
std::string s;

// Read from the input sequence and consume the read data.  The string
// 's' contains "hello".  The input sequence is empty, the output
// sequence remains unchanged.
is >> s;

Note how in the above examples, the steam objects handled committed and consuming the streambuf's output and input sequences.  However, when the buffers themselves were used (i.e. data() and prepare()), the code needed to explicitly handle commits and consumes.


text:
Q: Is it ok to omit "the" in front of plural nouns? What is the difference between

*

*The problems with the current education systems

Vs.

*The problems with current education systems

Is the second one grammatical?


text:
Q: Error using lapply to pass dataframe variable through custom function I have a function that was suggested by a user as an aswer to my previous question:
word_string <- function(x) {
  inds <- seq_len(nchar(x))
  start = inds[-length(inds)]
  stop = inds[-1]
  substring(x, start, stop)
}

The function works as expected and breaks down a given word into component parts as per my sepcifications:
 word_string('microwave')
[1] "mi" "ic" "cr" "ro" "ow" "wa" "av" "ve"

What I now want to be able to do is have the function applied to all rows of a specified columnin a dataframe.
Here's dataframe for purposes of illustration:
word <- c("House", "Motorcar", "Boat", "Dog", "Tree", "Drink")
some_value <- c("2","100","16","999", "65","1000000")
my_df <- data.frame(word, some_value, stringsAsFactors = FALSE )
my_df
      word some_value
1    House          2
2 Motorcar        100
3     Boat         16
4      Dog        999
5     Tree         65
6    Drink    1000000

Now, if I use lapply to work the function on my dataframe, not only do I get incorrect results but also an error message.
 lapply(my_df['word'], word_string)
$word
[1] "Ho" "ot" "at" ""   "Tr" "ri"

Warning message:
In seq_len(nchar(x)) : first element used of 'length.out' argument

So you can see that the function is being applied, but it's being applied such that it's evaluating each row partially.
The desired output would be something like:
[1] "ho" "ou" "us" "se
[2] "mo" "ot" "to" "or" "rc" "ca" "ar"
[3] "bo" "oa" "at"
[4] "do" "og"
[5] "tr" "re" "ee"
[6] "dr" "ri" "in" "nk"

Any guidance greatly appreciated.

A: The reason is that [ is still a data.frame with one column (if we don't use ,) and so here the unit is a single column.
str(my_df['word'])
'data.frame':   6 obs. of  1 variable:
# $ word: chr  "House" "Motorcar" "Boat" "Dog" ...

The lapply loops over that single column instead of each of the elements in that column.
W need either $ or [[
lapply(my_df[['word']], word_string)
#[[1]]
#[1] "Ho" "ou" "us" "se"

#[[2]]
#[1] "Mo" "ot" "to" "or" "rc" "ca" "ar"

#[[3]]
#[1] "Bo" "oa" "at"

#[[4]]
#[1] "Do" "og"

#[[5]]
#[1] "Tr" "re" "ee"

#[[6]]
#[1] "Dr" "ri" "in" "nk"


text:
Q: How create a kudu table in cloudera quickstart VM I have been trying to create a kudu table in impala using the cloudera quickstart VM following this example
https://kudu.apache.org/docs/quickstart.html
    CREATE TABLE sfmta
PRIMARY KEY (report_time, vehicle_tag)
PARTITION BY HASH(report_time) PARTITIONS 8
STORED AS KUDU
AS SELECT
  UNIX_TIMESTAMP(report_time,  'MM/dd/yyyy HH:mm:ss') AS report_time,
  vehicle_tag,
  longitude,
  latitude,
  speed,
  heading
FROM sfmta_raw;

getting the following error:
ERROR: AnalysisException: Table property 'kudu.master_addresses' is required when the impalad startup flag -kudu_master_hosts is not used. The VM used is cloudera-quickstart-vm-5.13.0-0-virtualbox. Thanks in advance for your help

A: From the documentation

If the -kudu_master_hosts configuration property is not set, you can
  still associate the appropriate value for each table by specifying a
  TBLPROPERTIES('kudu.master_addresses') clause in the CREATE TABLE
  statement or changing the TBLPROPERTIES('kudu.master_addresses') value
  with an ALTER TABLE statement.

So your table creation should looks like
 CREATE TABLE sfmta
PRIMARY KEY (report_time, vehicle_tag)
PARTITION BY HASH(report_time) PARTITIONS 8
STORED AS KUDU
TBLPROPERTIES ('kudu.master_addresses'='localhost:7051')
AS SELECT
  UNIX_TIMESTAMP(report_time,  'MM/dd/yyyy HH:mm:ss') AS report_time,
  vehicle_tag,
  longitude,
  latitude,
  speed,
  heading
FROM sfmta_raw;

7051 is the default port for kudu master.


text:
Q: Impossibility of making an "If and only if statement" stronger? Is it impossible to prove a stronger version of an "if an only if" result?
It seems to me that the answer would be "no" because to strengthen "$A$ iff $B$" I would need to either weaken $A$ or $B$. Suppose I weaken $A$ (so $A$ no longer holds but some condition implied by $A$ holds). Then $B$ cannot hold since $A$ is necessary for $B$ (i.e. $B\implies A$, so $\text{not } A\implies\text{not }B$).
So basically, if there is an "if and only if" result, in order to improve upon it would both $A$ and $B$ need to be weakened?
Thanks

A: You're right: just working with the left or right side cannot result in a stronger statement.  However, something like:
$$(A \leftrightarrow B) \land C$$
is a stronger claim than
$$A \leftrightarrow B$$

A: If you weaken both $A$ and $B$ you simply get something that is neither stronger nor weaker than the original. For example,

I take a red umbrella to work if and only if it rains on a Tuesday

neither implies nor is implied by

I take an umbrella to work if and only if it rains on a weekday

(both A and B have been weakened).
The only way I can think of to make a stronger statement than $A\Longleftrightarrow B$ is to add something to it, for example finding a third condition $C$ such that $A$, $B$ and $C$ are all equivalent.

A: In practice, the way to "strenghten" an equivalence is often the following: Suppose we proved
$$
A \iff B.
$$
Now it's often the case that this equivalence is a 'corollary' of a more general result that we later discover. I.e. there are statements $A^-, B^-$ for which we can prove
$$
A^- \iff B^-
$$
and for which we (usually for trivial reasons) have
$$
A \wedge B^-  \implies B \text{ and } B \wedge A^- \implies A.
$$
In this case the proof of $A^- \iff B^-$ can be viewed as a strengthening of the previous result that $A \iff B$.
The way this usually goes is that $A,B$ are 'global' statements and $A^-, B^-$ are 'localized' version of this. (This came up recently in a discussion about strong cardinals but I don't think that going into details will be very helpful to this thread.)


text:
Q: How to modifiy path for JDK for NeurophStudio I tried do install NeurophStudio on Win 10, but when i try to run it i got this message

I installed this program on my hard drive, but my windows is installed on my SSD.
How can i change --jdkhome destination on NeurophStudio, because i didnt install any NetBeans?
What do i need to run to enter that --jdkhome instrunction, and how to I enter my path like C:\bla\bla\jdk12 or C:/bla/bla/jdk12
UPDATE:
I tried installing it on my SSD, but same result as before.
When i run javac --version in cmd, i get this:

I have java jkd path in JAVA_HOME aswell:

A: In windows try this: (Works for some people)
First install latest version

https://www.oracle.com/java/technologies/javase-downloads.html

Find the instalation Neuroph Studio folder and when look for a neurophstudio\etc\neurophstudio.conf file.
Open it with e.g notepad++ and search this property#jdkhome="/usr/local/java/jdk1.8.0_20"
Update it for your actual path like this jdkhome="C:\Program Files\Java\jdk-15.0.1" and remove #.
Save and exit.
If this solution remove initial error messege box, but program after launch quit immediately probably you didn't update your JDK (latest version).

A: It says it can't find the JDK, but it's actually looking for the JRE. Install that, and you should be good.


text:
Q: how to write the AsyncTask in JSON parser for my code? I am developing a login application using MySQL database. I am using JSONParser from the database package to connect to the local mysql database I am getting the following error please some one help me. I googled for this error but what I got is to use the AsyncTask but I don't know where to use and how to use and what is the Mainthread also.
Please some one edit my code and explain or post relevant codes...
"android.os.NetworkonMainThreadException" is the error when I running the application from 4.2 genymotion emulator...
package com.android.database;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}``

A: Network Operations must be done in background.
You can use AsyncTask to accomplish this.

A: You are performing network operation on the UI thread and you can't do it. Consider using AsyncTask to do this kind operations, or an external library like this, which allows you to make Http request asynchronously in a very simple way.

A: I'm not sure if I understand your question correctly, and I would like to rather add a comment but am not allowed (too low rep) so here goes:
This class JSONParser i'm assuming is the "Activity" you are talking about. This is not an activity though, but a class, so you could rather create a new object of this class and use it from your calling activity:
JSONParser json = new JSONParser();
json.getJSONFromUrl(url,params);

Thing is, doing this parsing will take time and on the main UI thread this will probably pause the thread and might even let the app crash if the thread takes longer than 5 seconds to respond. This means you should use AsyncTask to run this JSONParser methods. A good place to start with learning AsyncTask is Vogella. He has some great tutorials on his site.
You will probably use doInBackground to run your getJSONFromUrl method and then update your UI thread from the onPostExecute method. So basically: Use AsyncTask


text:
Q: Test against actual value of input type="number" I am creating a form for a mobile web app with input boxes asking for number input, so I'm using input type="number" for the validation and it's working well. I am also changing behavior based on the input in the box. I need to hide a div until the user enters text in the box. When they delete all text from the box, then hide the div again. This is easy to do - detect keyup on the input and if its value is an empty string or not. The problem comes when the user enters text that's not a valid number (possible, at least with iOS keyboard). The value of the input box is an empty string when the entered text is not a valid number, unfortunately. So my code is hiding the div when I do still need it to be visible, because it thinks the input box has no value in it.
How can I get the actual value stored in a number input type so I can test against it? (I need to keep it a number input type so the proper keyboard appears.) Thanks!
Here's my snippet of code:
$('input.deletable').keyup(function() {
     console.log($(document.activeElement).val()); //returns empty string if input is "?)&" for example
     if ($(document.activeElement).val() != '')
          $('#myDiv').css('display', 'block');
     else
          $('#myDiv').css('display', 'none');
});

A: I think that "document.activeElement" isnt the best way to get the current input value. You can verify the input validity as well.
$('input.deletable').keyup(function() {
     var $this = $(this);
     if ($this.val() != '' && this.checkValidity())
          $('#myDiv').css('display', 'block');
     else
          $('#myDiv').css('display', 'none');
});


text:
Q: Play framework 2.1.3 function that will render scala template with given parameters I need a method in my controller to call the appropriate template, from the parameters that it received, in this manner:
public static Result renderTemplate(String folder, String template) {
    return ok(
        views.html.<<FOLDER_GOES_HERE>>.<<TEMPLATE_NAME_GOES_HERE>>.render(Users.createForm)
    );
}

if this possible? I would have done it with reflection, but for some reason I can't list the fields of view and view.html.
Can someone tell me why and explain what should I do to accomplish this?
Thank you

A: If you go that way you may loose type safety and the possebility to catch some error on on compile time instead of runtime.
But is still possible:
final Class<?> clazz = Class.forName("views.html." + folder + "." + template);
//assumed you have a String parameter for your template
java.lang.reflect.Method render = clazz.getDeclaredMethod("render", String.class);
play.api.templates.Html html = (play.api.templates.Html) render.invoke(null, "hi");
return ok(html);

Another way that does no include the overhead of reflection is to make an index of the templates at build time with SBT and source generators. You can walk through the views folder and then create a map from folder/template name and the invokations.
The map is in a generated class and looks like this:
map.put("folderx.templatey", views.html.folderx.templatey);//no reflection!

So at least SBT warns you at build time if the template does not exist.


text:
Q: Sitecore : login content editor as visitor Setting:
We have a Sitecore extranet/intranet.
We have 100-ish user who need to access the intranet.
We have 10 content editor licenses.
I would like to login a user ( with the "sitecore/Sitecore Client User" role ) into the intranet.
However this user should simply get his/her read rights for the intranet and not be seen as a content editor ( the Sitecore Client User role automaticly makes the user a content editor )
If i use Sitecore.Security.Authentication.AuthenticationManager.Login(user, false); will sitecore automaticly see this user as a content editor and thus use up one of the licenses ?

A: The best way to do this would be to setup your site to have a separate domain for the delivery. Then create your own login page for the site that uses the ASP.Net membership API to log the user in. It will use the domain specified in the site settings. These users will not count against the content editor licences, but you are still able to add security to the items to give the users read access to the content.
This article https://www.markstiles.net/Blog/2011/12/26/setting-up-a-sitecore-extranet.aspx is an older one, but the principles still apply. You can also look at http://sdn.sitecore.net/upload/sitecore6/sc61keywords/security_api_cookbook_usletter.pdf
Note that this will not log them into the content editor or the desktop. If you need the users to be able to log into the content editor, that is a valid use of a licence, your only option there would be to get more licences.


text: Q: nesting ConnectionStrings.xxx.config In Visual Studio 2015 IDE, I have several ConnectionStrings.versionX.config files nested under the main ConnectionStrings.config.  I created some new ones but they are not nested as others.  I also created several configurations using the Configuration Manger.  In the Solution Explorer when I right click the web.conifg the context menu contains an "add config transformation" option. However, the context menu on the right click of ConnectionStrings.config doesn't have that option. Am I missing something?  Thanks.


text:
Q: How to build this SearchQuery in SharePoint 2013 Search Result Webpart? My search query:
Path:{Site.URL} EventDateOWSDATE:{Today+4} OR EndDateOWSDate:{Today+4}

Does only return the events with an Enddate of Today+4.
But I want it, to show me "all the Events of Today+4 or all the Events that End on Today+4".
How do I have to build the query correctly?

A: Try Path:{Site.URL} EventDateOWSDATE:{Today+4} -OR EndDateOWSDate:{Today+4}


text:
Q: Apache Commons Compress unable to add hard link in tar I have a set of files in which there are some hard links pointing to some of the files.
For Example:
/tmp/test/file1
/tmp/test/file1_Link

The file1 is a file with size 1 MB.
file1_Link is a hard link pointing to file1
When I use the unix tar command to tar these both files , the resulting archive has a size of 1 MB (mytar.tar)
tar -cvf ../mytar.tar .
-rw-r--r--  1 bsarraf  189060905   1.0M Feb 11 22:06 mytar.tar
-rw-r--r--  1 bsarraf  189060905   2.0M Feb 11 22:10 files.tar

However when I use the apache commons compress and add all the files in the tar file, I get a tar with size 2 MB (files.tar).
This means in the tar the same file was added twice.
How can I add the hard link file in the tar as a hard link of the other file?

A: For others who might have the same issue, I was able to solve the issue with the following approach:
1. Identify if the file is a hard link, there are various ways to do this.
2. Once hardlinks are identified, use the following method to add the hardline file in the tar
private void addLinkFileToTar(TarArchiveOutputStream tar, File linkFile, File file, String base)
        throws IOException {
    String entryName = base + linkFile.getName();
    TarArchiveEntry tarEntry = new TarArchiveEntry(entryName, TarConstants.LF_LINK);
    tarEntry.setLinkName(base+file.getName());
    tar.putArchiveEntry(tarEntry);
    tar.closeArchiveEntry();
}

here linkFile is the hard Link file and file is the target File.


text:
Q: Reading data from Simulink into Python over UDP I want to send data from a Simulink model (running in real time) to a Python script (also running in real time.  I am using Simulink's built-in "UDP Send" block, which works, but I don't know how to decode the data I'm getting.  This is what my python script looks like:
import sys, struct
from socket import *

SIZE = 1024      # packet size

hostName = gethostbyname('0.0.0.0')

mySocket  = socket( AF_INET, SOCK_DGRAM )
mySocket.bind((hostName,5002))

repeat = True
while repeat:
    (data,addr) = mySocket.recvfrom(SIZE)
    data = struct.unpack('d',data)
    print data

I've suspected that the data stream should be something like a double, but while it's giving me numbers they aren't meaningful:

*

*If simulink sends a constant "1", I get an output of "3.16e-322"

*If Simulink sends a constant "2", I get an output of "3.038e-319"
Any ideas?

A: Turns out my network was reversing the packet bits.  The solution was to read it in as bit-reversed:
data = struct.unpack('!d',data)

I have no clue why this happens over some networks and not others.  Can someone comment on a way to tell if I need to use bit-reversal?

A: The problem occurs when the sender and receiver has different byte order.
See sys.byteorder.
Best practice should be to always convert to network order when sending and convert again when receiving.


text:
Q: Toggle markers - Google API V3 - Heatmap I've made one map based on this nice topic: Toggle Markers in Google Maps. It is a heatpmap with pins indicating places.
I cannot, however, toggle the pins i've added and keep the heatmap layer.
I've only added some of the pins (and heatmap data points) here, in order to keep it short, and once I add them all it gets very hard to visualize the heatmap itself - that's why I need a button to toggle them.
I searched a lot on stackoverflow, but I'm a beginner on coding and running out of time.
CODE
    <!DOCTYPE html>

    <meta charset="utf-8">
    <title>Sao Paulo</title>

      <button onclick="toggleHeatmap()">Toggle Heatmap</button>
      <button onclick="changeGradient()">Change gradient</button>
      <button onclick="changeRadius()">Change radius</button>
      <button onclick="changeOpacity()">Change opacity</button>

strong text
Any help would be much appreciated. Thanks so much!

A: To toggle the markers independently of the heatmap.  You need to create another function to toggle them, and remove the code that toggles them in toggleHeatmap:
function toggleMarkers() {
    if (markers[0].getMap() != null) {
        var arg = null;
    } else {
        var arg = map;
    }
    for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(arg);
    }
}

function toggleHeatmap() {

    if (heatmap.getMap() != null) {
        heatmap.setMap(null);
    } else {
        heatmap.setMap(map);
    }
}

As Dr.Molle indicated, markers needs to be global.
working jsfiddle
working code snippet:

// Adding Data Points
var map, pointarray, heatmap;
var markers = [];

function initialize() {
  var mapOptions = {
    zoom: 11,
    center: new google.maps.LatLng(-23.5934217, -46.6627102),
    mapTypeId: google.maps.MapTypeId.SATELLITE
  };

  map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);

  var pointArray = new google.maps.MVCArray(taxiData);

  heatmap = new google.maps.visualization.HeatmapLayer({
    data: pointArray
  });

  heatmap.setMap(map);

  var locations = [
    ['1', -23.664681, -46.664681],
    ['2', -23.565873, -46.565873],
    ['3', -23.651898, -46.651898],
    ['4', -23.383921, -46.383921],
    ['5', -23.550021, -46.550021],
    ['6', -23.687124, -46.687124],
    ['7', -23.638630, -46.638630],
    ['8', -23.379916, -46.379916],
    ['9', -23.575142, -46.575142],
    ['10', -23.651898, -46.651898]

  ];

  var infowindow = new google.maps.InfoWindow();

  var iconBase = '';
  var marker, i;
  for (i = 0; i < locations.length; i++) {
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(locations[i][1], locations[i][2]),
      map: map,
      icon: iconBase + ''
    });

    markers.push(marker);

    google.maps.event.addListener(marker, 'click', (function(marker, i) {
      return function() {
        infowindow.setContent(locations[i][0]);
        infowindow.open(map, marker);
      };
    })(marker, i));
  }

  function AutoCenter() {
    //  Create a new viewpoint bound
    var bounds = new google.maps.LatLngBounds();
    //  Go through each...
    $.each(markers, function(index, marker) {
      bounds.extend(marker.position);
    });
    //  Fit these bounds to the map
    map.fitBounds(bounds);
  }
  AutoCenter();

}

function toggleMarkers() {
  if (markers[0].getMap() != null) {
    var arg = null;
  } else {
    var arg = map;
  }
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(arg);
  }
}

function toggleHeatmap() {

  if (heatmap.getMap() != null) {
    heatmap.setMap(null);
  } else {
    heatmap.setMap(map);
  }
}

function changeGradient() {
  var gradient = [
    'rgba(0, 255, 255, 0)',
    'rgba(0, 255, 255, 1)',
    'rgba(0, 191, 255, 1)',
    'rgba(0, 127, 255, 1)',
    'rgba(0, 63, 255, 1)',
    'rgba(0, 0, 255, 1)',
    'rgba(0, 0, 223, 1)',
    'rgba(0, 0, 191, 1)',
    'rgba(0, 0, 159, 1)',
    'rgba(0, 0, 127, 1)',
    'rgba(63, 0, 91, 1)',
    'rgba(127, 0, 63, 1)',
    'rgba(191, 0, 31, 1)',
    'rgba(255, 0, 0, 1)'
  ];

  heatmap.set('gradient', heatmap.get('gradient') ? null : gradient);
}

function changeRadius() {
  heatmap.set('radius', heatmap.get('radius') ? null : 35);
}

function changeOpacity() {
  heatmap.set('opacity', heatmap.get('opacity') ? null : 0.2);
}

google.maps.event.addDomListener(window, 'load', initialize);
var taxiData = [new google.maps.LatLng(-23.672783, -46.664681),
  new google.maps.LatLng(-23.672783, -46.664681),
  new google.maps.LatLng(-23.672783, -46.664681),
  new google.maps.LatLng(-23.672783, -46.664681),
  new google.maps.LatLng(-23.672783, -46.664681),
  new google.maps.LatLng(-23.532816, -46.565873),
  new google.maps.LatLng(-23.532816, -46.565873),
  new google.maps.LatLng(-23.532816, -46.565873),
  new google.maps.LatLng(-23.532816, -46.565873),
  new google.maps.LatLng(-23.532816, -46.565873),
  new google.maps.LatLng(-23.532816, -46.565873),
  new google.maps.LatLng(-23.532816, -46.565873),
  new google.maps.LatLng(-23.532816, -46.565873),
  new google.maps.LatLng(-23.532816, -46.565873),
  new google.maps.LatLng(-23.531575, -46.651898),
  new google.maps.LatLng(-23.531575, -46.651898),
  new google.maps.LatLng(-23.526200, -46.550021),
  new google.maps.LatLng(-23.714602, -46.687124),
  new google.maps.LatLng(-23.714602, -46.687124),
  new google.maps.LatLng(-23.714602, -46.687124),
  new google.maps.LatLng(-23.714602, -46.687124),
  new google.maps.LatLng(-23.714602, -46.687124),
  new google.maps.LatLng(-23.599363, -46.539564),
  new google.maps.LatLng(-23.599363, -46.539564),
  new google.maps.LatLng(-23.599363, -46.539564),
  new google.maps.LatLng(-23.648271, -46.748602),
  new google.maps.LatLng(-23.648271, -46.748602),
  new google.maps.LatLng(-23.648271, -46.748602),
  new google.maps.LatLng(-23.648271, -46.748602),
  new google.maps.LatLng(-23.743565, -46.704938),
  new google.maps.LatLng(-23.753251, -46.670598),
  new google.maps.LatLng(-23.753251, -46.670598),
  new google.maps.LatLng(-23.753251, -46.670598),
  new google.maps.LatLng(-23.538945, -46.454974),
  new google.maps.LatLng(-23.538945, -46.454974),
  new google.maps.LatLng(-23.538945, -46.454974),
  new google.maps.LatLng(-23.538945, -46.454974),
  new google.maps.LatLng(-23.538945, -46.454974),
  new google.maps.LatLng(-23.502081, -46.449464),
  new google.maps.LatLng(-23.502081, -46.449464),
  new google.maps.LatLng(-23.502852, -46.631123),
  new google.maps.LatLng(-23.502852, -46.631123),
  new google.maps.LatLng(-23.550412, -46.597303),
  new google.maps.LatLng(-23.550412, -46.597303),
  new google.maps.LatLng(-23.550412, -46.597303),
  new google.maps.LatLng(-23.616210, -46.495470),
  new google.maps.LatLng(-23.616210, -46.495470),
  new google.maps.LatLng(-23.476226, -46.703023),
  new google.maps.LatLng(-23.530669, -46.444300),
  new google.maps.LatLng(-23.492830, -46.600559),
  new google.maps.LatLng(-23.492830, -46.600559),
  new google.maps.LatLng(-23.492830, -46.600559),
  new google.maps.LatLng(-23.722254, -46.704621),
  new google.maps.LatLng(-23.594344, -46.751259),
  new google.maps.LatLng(-23.594344, -46.751259),
  new google.maps.LatLng(-23.594344, -46.751259),
  new google.maps.LatLng(-23.594344, -46.751259),
  new google.maps.LatLng(-23.526226, -46.417361),
  new google.maps.LatLng(-23.526226, -46.417361),
  new google.maps.LatLng(-23.526226, -46.417361),
  new google.maps.LatLng(-23.521684, -46.561784),
  new google.maps.LatLng(-23.521684, -46.561784),
  new google.maps.LatLng(-23.521684, -46.561784),
  new google.maps.LatLng(-23.521684, -46.561784),
  new google.maps.LatLng(-23.521684, -46.561784),
  new google.maps.LatLng(-23.499804, -46.516773),
  new google.maps.LatLng(-23.646948, -46.701438),
  new google.maps.LatLng(-23.523667, -46.700788),
  new google.maps.LatLng(-23.529025, -46.529134),
  new google.maps.LatLng(-23.529025, -46.529134),
  new google.maps.LatLng(-23.529025, -46.529134),
  new google.maps.LatLng(-23.548776, -46.560548),
  new google.maps.LatLng(-23.548776, -46.560548),
  new google.maps.LatLng(-23.548776, -46.560548),
  new google.maps.LatLng(-23.501684, -46.493347),
  new google.maps.LatLng(-23.501684, -46.493347),
  new google.maps.LatLng(-23.652993, -46.645012)
];
html,
body,
#map-canvas {
  height: 100%;
  margin: 0px;
  padding: 0px
}
#panel {
  position: absolute;
  top: 5px;
  left: 50%;
  margin-left: -180px;
  z-index: 5;
  background-color: #fff;
  padding: 5px;
  border: 1px solid #999;
}

  <button onclick="toggleHeatmap()">Toggle Heatmap</button>
  <button onclick="toggleMarkers()">Toggle Markers</button>
  <button onclick="changeGradient()">Change gradient</button>
  <button onclick="changeRadius()">Change radius</button>
  <button onclick="changeOpacity()">Change opacity</button>

A: *

*the function AutoCenter uses some kind of library(maybe jQuery), but you didn't load this library anywhere.
You may either load jQuery or(preferable, because that's the only part that uses jQuery), replace this part:
//  Go through each...
$.each(markers, function (index, marker) {
  bounds.extend(marker.position);
});

by...
//  Go through each...
for (var i = 0; i < markers.length; i++) {
  bounds.extend(markers[i].position)
}

*the markers-array must be global accessible(currently it's only accessible inside initialize)
replace this part:
 var markers = new Array();

by....
window.markers = new Array();

To be able to toggle markers and heatmap independently you'll need 2 functions
function toggleHeatmap() {
  heatMap.setMap((heatMap.getMap()===null)?map:null);
}

function toggleMarkers() {
 if(markers.length){
   var m=(markers[0].getMap()===null)?map:null;
   for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(m);
   }
 }
}


text:
Q: async/await / assignments from function returns Currently having a simple funtion :
async function getItem(id) {
  const item = await ... doing a bunch of time consuming stuff
  return item;
}

Coming from synchronous languages, and still understanding async/awaits from the surface; i'd expected the following to return the resolved item :
const item = getItem('items-8');
console.log(item); // Just getting a promise

The question is a bit 'cosmetic', but as async/await kind of solves callbacks, i'd be looking to get further and even avoid thenables things.
Is it possible to get such one-liner variable assignment with async/awaits ? What would be the syntax/code structure ?

A: async..await is syntactic sugar for ES6 promises, it allows to write asynchronous code in synchrounous-like manner. The code that uses promises cannot be synchronous, because promises are asynchronous.
In order to be written in synchronous manner, the code that uses getItem should reside in async function, too. If it is top-level and doesn't reside in another function (like application initialization code), it can reside in async IIFE.
It's either
getItem('items-8').then(item => {
  ...
});

Or
// inside `async` function
const item = await getItem('items-8');
...


text:
Q: Import cell id to a formula I have to calculate the standard deviation up to a particular cell in Excel. The value of the first cell is known to me. I also have found the cell id of the second cell, up to which I require the standard deviation, using the ADDRESS function and saved it in another cell.
How can I import that cell id into the formula for standard deviation?
This the formula I have already tried:
=STDEVP(C2:(INDEX(C88,1,1)))

where INDEX(C88,1,1) is used to get last cell id that I stored in cell C88.

A: Please try:
=STDEV(INDIRECT("C2:"&C8))

A: Is the reason that you have to look for the "2nd" cell is that you have a table that can increase in size? If so, I suggest changing your range into a table. Excel makes this quite easy with "Format as Table" on the "Home" ribbon.
If you do this, your formula will look as pretty as this:
=STDEV.P(Table1[Column1])

In addition, it resizes by itself. There is no need for hocus pocus.
A table can have a "Totals" row and it allow you to pick the function to use (yes, that includes STDEV).


text:
Q: indentation error in file comparison function I'm trying to compare line in two file and do something with it . but i'm getting error on indentation and i'm not sure why there is error .
i will appreciate for any pointer .
[root@localhost ~]# python commit.py
File "commit.py", line 85
done = True
^

IndentationError: unexpected indent
Code that has error:
 75 def compareline():
 76  done = False
 77  for filename in newfilenamelist:
 78   if done:
 79    break
 80   with open(filename) as line:
 81    for list in opendifffilelist:
 82     if not list:
 83      print "List is empty"
 84      done = True
 85     for line in filename:
 86      if list == line :
 87       opendifffilelist.remove(list)
 88       outfile.append(outfile)
 89       break

A: At a first glance your indentation seems correct. This kind of error is often due to mixing tabs and spaces in the source code.
From PEP 8:

Spaces are the preferred indentation method.
Tabs should be used solely to remain consistent with code that is
  already indented with tabs.
Python 3 disallows mixing the use of tabs and spaces for indentation.
Python 2 code indented with a mixture of tabs and spaces should be
  converted to using spaces exclusively.
When invoking the Python 2 command line interpreter with the -t
  option, it issues warnings about code that illegally mixes tabs and
  spaces. When using -tt these warnings become errors. These options are
  highly recommended!

The section just above it is about indentation in general.

A: Try this formatting. Your error was likely due to mixing tabs and spaces.
def compareline():
    done = False
    for filename in newfilenamelist:
        if done:
            break
        with open(filename) as line:
            for list in opendifffilelist:
                if not list:
                    print "List is empty"
                    done = True
            for line in filename:
                if list == line :
                    opendifffilelist.remove(list)
                    outfile.append(outfile)
                    break


text:
Q: Javascript function to load a DIV after the entire page is loaded I want to load the DIV "image" only after the entire page is loaded.
What JS code do I need?

    CONTENT

I will call the function with :
$(document).ready(function()

A: Just put the request call inside ready function :
$(document).ready(function(){ //after the entire page is loaded.
   // load the DIV "image"
   $.get('url', function(data) {
        $('.image').html(data);
   });
});

Hope this helps.

A:

$(window).load(function() {
  $('.image').fadeIn();
});

        CONTENT