问:
How to read from txt file line and print arrays of strings and integers
I am reading from a text file a specific line defined by a user input with if(nameLine.contains(inputFileName)){ I am trying to print an array of names and array of numbers from that line. Could anyone help me out with how to do so? Do I have to create 2 different methods or can I do it all in main? I only know how to work with one Array in one code with while loop, but I am not sure how to have it all combined. Thank you for your help!

My code is not finished, but this is how it looks so far

```<code>public static void main(String[] args) throws IOException {

    Scanner in = new Scanner(System.in);
    System.out.print("Enter the State name: ");
    String inputFileName = in.next();
    String names = "pplnames17.txt";

    List<String> namearr = new ArrayList<String>();

    File namesFile = new File(names);
    Scanner stateSearch = new Scanner (namesFile);

    //print title
    String line0 = Files.readAllLines(Paths.get("pplnames17.txt")).get(0);
    System.out.printf("%s in %s", line0, inputFileName);

    while(stateSearch.hasNextLine()){
        String nameLine = stateSearch.nextLine();
        if(nameLine.contains(inputFileName)){
            System.out.printf("\n%s",nameLine);
        }
    }
</code>```

This is a partial of my Array code for String, which I had it after a while loop

```<code>    while(stateSearch.hasNextLine()){
    namearr.add(stateSearch.nextLine());
}
String[] arr = namearr.toArray(new String [0]);
System.out.println(arr);
</code>```

答:
Whilst this isn't the greatest solution, here is a potential solution that you could build upon/tidy up.

Basically, read in your file, loop through each line, if the line contains the user input, split each string on that line, check if text or numeric, and add to the relevant array.

```<code>public static void main(String[] args) throws FileNotFoundException {
        List<String> nameArr = new ArrayList<>();
        List<Double> intArr = new ArrayList<>();
        System.out.print("Enter the State name: ");
        Scanner in = new Scanner(System.in);
        String inputFileName = in.next();

        Scanner sc = new Scanner(new File("pplnames17.txt"));

        while (sc.hasNextLine()) {
            String nameLine = sc.nextLine();
            if (nameLine.contains(inputFileName)) {
                String[] inputs = nameLine.split(" ");
                for (String input : inputs) {
                    if (isNumeric(input)) {
                        intArr.add(Double.parseDouble(input));
                    } else {
                        nameArr.add(input);
                    }
                }
            }
        }
        if (!nameArr.isEmpty()) {
            System.out.println(nameArr);
        } else {
            System.out.println("No names found");
        }
        if (!intArr.isEmpty()) {
            System.out.println(intArr);
        } else {
            System.out.println("No numbers found");
        }
    }

    public static boolean isNumeric(String str) {
        try {
            double d = Double.parseDouble(str);
        } catch (NumberFormatException e) {
            return false;
        }
        return true;
    }
</code>```

I tested it and my text file was like this:

abc def ghi 12 55 jkl mno pqr

joe jack mary 1 2 james 4

paul jim kim bob 45 othername

bill yu will gill 455 Paulo

User input of mary gave an output of:

[joe, jack, mary, james]

[1.0, 2.0, 4.0]

Body:
I am reading from a text file a specific line defined by a user input with if(nameLine.contains(inputFileName)){ I am trying to print an array of names and array of numbers from that line. Could anyone help me out with how to do so? Do I have to create 2 different methods or can I do it all in main? I only know how to work with one Array in one code with while loop, but I am not sure how to have it all combined. Thank you for your help!

My code is not finished, but this is how it looks so far

public static void main(String[] args) throws IOException {

    Scanner in = new Scanner(System.in);
    System.out.print("Enter the State name: ");
    String inputFileName = in.next();
    String names = "pplnames17.txt";

    List<String> namearr = new ArrayList<String>();

    File namesFile = new File(names);
    Scanner stateSearch = new Scanner (namesFile);

    //print title
    String line0 = Files.readAllLines(Paths.get("pplnames17.txt")).get(0);
    System.out.printf("%s in %s", line0, inputFileName);

    while(stateSearch.hasNextLine()){
        String nameLine = stateSearch.nextLine();
        if(nameLine.contains(inputFileName)){
            System.out.printf("\n%s",nameLine);
        }
    }

This is a partial of my Array code for String, which I had it after a while loop

    while(stateSearch.hasNextLine()){
    namearr.add(stateSearch.nextLine());
}
String[] arr = namearr.toArray(new String [0]);
System.out.println(arr);

Body:
Whilst this isn't the greatest solution, here is a potential solution that you could build upon/tidy up.

Basically, read in your file, loop through each line, if the line contains the user input, split each string on that line, check if text or numeric, and add to the relevant array.

public static void main(String[] args) throws FileNotFoundException {
        List<String> nameArr = new ArrayList<>();
        List<Double> intArr = new ArrayList<>();
        System.out.print("Enter the State name: ");
        Scanner in = new Scanner(System.in);
        String inputFileName = in.next();

        Scanner sc = new Scanner(new File("pplnames17.txt"));

        while (sc.hasNextLine()) {
            String nameLine = sc.nextLine();
            if (nameLine.contains(inputFileName)) {
                String[] inputs = nameLine.split(" ");
                for (String input : inputs) {
                    if (isNumeric(input)) {
                        intArr.add(Double.parseDouble(input));
                    } else {
                        nameArr.add(input);
                    }
                }
            }
        }
        if (!nameArr.isEmpty()) {
            System.out.println(nameArr);
        } else {
            System.out.println("No names found");
        }
        if (!intArr.isEmpty()) {
            System.out.println(intArr);
        } else {
            System.out.println("No numbers found");
        }
    }

    public static boolean isNumeric(String str) {
        try {
            double d = Double.parseDouble(str);
        } catch (NumberFormatException e) {
            return false;
        }
        return true;
    }

I tested it and my text file was like this:

abc def ghi 12 55 jkl mno pqr

joe jack mary 1 2 james 4

paul jim kim bob 45 othername

bill yu will gill 455 Paulo

User input of mary gave an output of:

[joe, jack, mary, james]

[1.0, 2.0, 4.0]


来源: stackexchange

问:
Getting the key with max value in a portion of a python dictionary
I have a python dictionary, its keys are datetime.datetime objects, such as:

```<code>a = {datetime(2018,1,1):1, datetime(2018,1,2):2, datetime(2018,1,3):3, ...}
</code>```

I would like to get the key (date) with max value in a portion of this dictionary, such as between dates 2018-03-27 and 2018-04-17.

What is the mosy pythonic way of achieving this?

答:
You can constrain the keys to that range of date using a generator expression and then take the one with the maximum value by passing the key as a.get:

```<code>date = max((k for k in a if datetime(2018, 03, 27) <= k <= datetime(2018, 04, 17)),
            key=a.get)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a python dictionary, its keys are datetime.datetime objects, such as:

a = {datetime(2018,1,1):1, datetime(2018,1,2):2, datetime(2018,1,3):3, ...}

I would like to get the key (date) with max value in a portion of this dictionary, such as between dates 2018-03-27 and 2018-04-17.

What is the mosy pythonic way of achieving this?

Body:
You can constrain the keys to that range of date using a generator expression and then take the one with the maximum value by passing the key as a.get:

date = max((k for k in a if datetime(2018, 03, 27) <= k <= datetime(2018, 04, 17)),
            key=a.get)


问:
How to find a value if we have 2 same columns in 2 different tables?
As you can see on the photo. I have 2 tables(A and B). KlantId is common in 2 tables. What I want to achieve is, if I provide the Email then I can get the reservatieNummer.

答:
```<code>select b.reservatieID
from tablea as a
inner join tableb as b on a.KlantId = b.KlantId
where a.email="whatever"
</code>```

and you specify the email in the where condition

Body:
select b.reservatieID
from tablea as a
inner join tableb as b on a.KlantId = b.KlantId
where a.email="whatever"

and you specify the email in the where condition


问:
How to filter a sequence and retain evaluated pred values?
This is a scenario I encountered many times, yet didn't find an idiomatic approach for it...

Suppose one would like to use a self-defined self-pred function to filter a seq. This self-pred function returns nil for unwanted elements, and useful information for wanted elements. It is desirable to keep the evaluated self-pred values for these wanted elements.

My general solution is:

```<code>;; self-pred is a pred function which returns valuable info
;; in general, they are unique and can be used as key
(let [new-seq (filter self-pred aseq)]
   (zipmap (map self-pred new-seq) new-seq))
</code>```

Basically, it is to call self-pred twice on all wanted elements. I feel it is so ugly...

Wonder if there is any better ways. Much appreciated for any input!

答:
i use this kind of snippet:

```<code>(keep #(some->> % self-pred (vector %)) data)
</code>```

like this:

```<code>user> (keep #(some->> % rseq (vector %)) [[1 2] [] [3 4]])
;;=> ([[1 2] (2 1)] [[3 4] (4 3)])
</code>```

or if you like more verbose result:

```<code>user> (keep #(some->> % rseq (hash-map :data % :result)) [[1 2] [] [3 4]])
;;=> ({:result (2 1), :data [1 2]} {:result (4 3), :data [3 4]})
</code>```

Body:
This is a scenario I encountered many times, yet didn't find an idiomatic approach for it...

Suppose one would like to use a self-defined self-pred function to filter a seq. This self-pred function returns nil for unwanted elements, and useful information for wanted elements. It is desirable to keep the evaluated self-pred values for these wanted elements.

My general solution is:

;; self-pred is a pred function which returns valuable info
;; in general, they are unique and can be used as key
(let [new-seq (filter self-pred aseq)]
   (zipmap (map self-pred new-seq) new-seq))

Basically, it is to call self-pred twice on all wanted elements. I feel it is so ugly...

Wonder if there is any better ways. Much appreciated for any input!

Body:
i use this kind of snippet:

(keep #(some->> % self-pred (vector %)) data)

like this:

user> (keep #(some->> % rseq (vector %)) [[1 2] [] [3 4]])
;;=> ([[1 2] (2 1)] [[3 4] (4 3)])

or if you like more verbose result:

user> (keep #(some->> % rseq (hash-map :data % :result)) [[1 2] [] [3 4]])
;;=> ({:result (2 1), :data [1 2]} {:result (4 3), :data [3 4]})


问:
How to replace $ currency with Rp (Rupiah) format in Javascript
**I have a code below, i want to change/replace currency format from ($) with (Rp.) in js. I have tired with this, anybody can help me?</p>

```<code>function update_total() {
  var total = 0;
  $('.price').each(function(i){
    price = $(this).html().replace("$","");
    if (!isNaN(price)) total += Number(price);
  });

  total = roundNumber(total,2);

  $('#subtotal').html("$"+total);
  $('#total').html("$"+total);

  update_balance();
}

function update_balance() {
  var due = $("#total").html().replace("$","") - $("#paid").val().replace("$","");
  due = roundNumber(due,2);

  $('.due').html("$"+due);
}

function update_price() {
  var row = $(this).parents('.item-row');
  var price = row.find('.cost').val().replace("$","") * row.find('.qty').val();
  price = roundNumber(price,2);
  isNaN(price) ? row.find('.price').html("N/A") : row.find('.price').html("$"+price);

  update_total();
}
</code>```

答:
If its only html you want to replace you can use</p>

```<code>replace('$','Rp')
</code>```

Body:
**I have a code below, i want to change/replace currency format from ($) with (Rp.) in js. I have tired with this, anybody can help me?

function update_total() {
  var total = 0;
  $('.price').each(function(i){
    price = $(this).html().replace("$","");
    if (!isNaN(price)) total += Number(price);
  });

  total = roundNumber(total,2);

  $('#subtotal').html("$"+total);
  $('#total').html("$"+total);

  update_balance();
}

function update_balance() {
  var due = $("#total").html().replace("$","") - $("#paid").val().replace("$","");
  due = roundNumber(due,2);

  $('.due').html("$"+due);
}

function update_price() {
  var row = $(this).parents('.item-row');
  var price = row.find('.cost').val().replace("$","") * row.find('.qty').val();
  price = roundNumber(price,2);
  isNaN(price) ? row.find('.price').html("N/A") : row.find('.price').html("$"+price);

  update_total();
}

Body:
If its only html you want to replace you can use

replace('$','&#x52;&#x70;')


问:
How do I print an IFrame from javascript in Safari/Chrome
Can someone please help me out with printing the contents of an IFrame via a javascript call in Safari/Chrome.

This works in firefox:

```<code>$('#' + id)[0].focus();
$('#' + id)[0].contentWindow.print();
</code>```

this works in IE:

```<code>window.frames[id].focus();
window.frames[id].print();
</code>```

But I can't get anything to work in Safari/Chrome.

Thanks

Andrew

答:
Put a print function in the iframe and call it from the parent.

iframe:

```<code>function printMe() {
  window.print()
}
</code>```

parent:

```<code>document.frame1.printMe()
</code>```

OwnerDisplayName: Andrew Bullock

ContentLicense: CC BY-SA 2.5

Body:
Can someone please help me out with printing the contents of an IFrame via a javascript call in Safari/Chrome.

This works in firefox:

$('#' + id)[0].focus();
$('#' + id)[0].contentWindow.print();

this works in IE:

window.frames[id].focus();
window.frames[id].print();

But I can't get anything to work in Safari/Chrome.

Thanks

Andrew

Body:
Put a print function in the iframe and call it from the parent.

iframe:

function printMe() {
  window.print()
}

parent:

document.frame1.printMe()

OwnerDisplayName: Diodeus


问:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException when trying to execute Javascript
I am trying to execute Javascript function called "returnAllLinkTexts()" on the DOM html page loaded via my Java application. Below line is executed by a Swing Buton.

```<code>myscript = browser.executeJavascript("returnAllLinkTexts()").toString(); //Line 407
</code>```

Once in a while I get the following exception. The Java application does not terminate or crash.

```<code>Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException com.demo.Main$BigButtonListener.actionPerformed(Main.java:407)
</code>```

I have tried the following to keep retrying about 20 times but it doesn't even reach this point. Exception is raised immediately @ 407.

```<code>int st = 0;
while (myscript == null){
 myscript = browser.executeJavascript("gogo()").toString();                              if (myscript != null) break;
 if (shit == 20) break;
 sht++;
}
</code>```

UPDATE:

This is the Javascript function returnAllLinkTexts();

```<code>function returnAllLinkTexts(){
var mydata = new Array();

$('a', document).each(function() {
    mydata.push($(this).text());
});

return mydata;
}
</code>```

答: Don't unconditionally call toString() on a return value which may be  null.  Always check first for null!</p>

Body:
I am trying to execute Javascript function called "returnAllLinkTexts()" on the DOM html page loaded via my Java application. Below line is executed by a Swing Buton.

myscript = browser.executeJavascript("returnAllLinkTexts()").toString(); //Line 407

Once in a while I get the following exception. The Java application does not terminate or crash.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException com.demo.Main$BigButtonListener.actionPerformed(Main.java:407)

I have tried the following to keep retrying about 20 times but it doesn't even reach this point. Exception is raised immediately @ 407.

int st = 0;
while (myscript == null){
 myscript = browser.executeJavascript("gogo()").toString();                              if (myscript != null) break;
 if (shit == 20) break;
 sht++;
}

UPDATE:

This is the Javascript function returnAllLinkTexts();

function returnAllLinkTexts(){
var mydata = new Array();

$('a', document).each(function() {
    mydata.push($(this).text());
});

return mydata;
}


问:
Using Vault to encrypt remote Terraform state stored in Consul
As of today, managing secrets such as cloud provider access keys and ids is an open problem in the Terraform project (see github issue ). Whenever, we run terraform plan or terraform apply, these secrets are stored in plain text in the terraform state file. There are numerous third party redaction and encryption scripts such as terrahelp.

My question: Consul is a native backend for storing remote terraform state. Is it possible to use Vault to encrypt state files stored in Consul? I have tried searching through the Terraform backend documentation, but was not able to find any configuration flags that would allow Consul to use Vault to encrypt the state file.

答:
As much as I would like that feature, sadly I don't think that this is possible at the moment. If you want your whole statefile encrypted, then you would need to choose another backend that supports this out of the box, like s3 with bucket encryption enabled.

It would also be nice if there is an official way to hook into the statefile read/store procedure to incorporate vault encryption (or any other custom requirements) by yourself, but afaik this is also not possible.

Small site note: terraform plan does not write anything to the statefile. It is a read-only operation, as otherwise it couldn't be considered safe to use.


问:
Using Revit API draw dimension from gridline to sleeve (Speciality equipment)
Source Code  Using Revit API when we apply Dimension from Grid line to Sleeve (Specialty equipment) that time  Revit returns an error message .from error message if i click "Cancel" option deletes the dimensions  and if i click the "remove reference" button that time some dimension are deleted.

答: Create a dimension that works manually through the user interface first, then use RevitLookup to analyse its properties and find out what exact references it has picked up. In general, if a feature is not available in the Revit product manually through the user interface, then the Revit API will not provide it either.</p>


问:
MySQL Select User id based on multiple AND conditions on same table
I want to select a userid from a single table based on multiple and condition.

```<code>UserID   FieldID  Value
-----------------------------------
1        51         Yes
1        6          Dog
2        6          Cat
1        68         TX
1        69         78701
2        68         LA
</code>```

What I'm trying to get in simple words:

if user search for texas or 78701,
Select userId where (68 = TX OR 69=78701) AND (51=yes) AND (6=Dog)

This should return user id 1.

This is what I tried, but returns null.

```<code>SELECT user_id FROM `metadata`
WHERE ( (`field_id` = '68' AND value LIKE '%TX%')
   OR (`field_id` = '69' AND value LIKE '%78701%') )
   AND `field_id` = '51' AND value = 'Yes'
   AND `field_id` = '6' AND value = 'Dog'
</code>```

答:
Your table structure resembles attribute+value modelling, which essentially splits up the columns of a row into individual pairs, and has the side effect of very weak typing.

As you've noted, this can also make things tricky to query, since you have to reason over multiple rows in order to make sense of the original data model.

One approach could be to take an opinion of a 'primary' criterion, and then apply additional criteria by reasoning over the shredded data, joined back by user id:

```<code>SELECT DISTINCT m.user_id
FROM `metadata` m
WHERE ((`field_id` = '68' AND value LIKE '%TX%')
       OR (`field_id` = '69' AND value LIKE '%78701%'))
 AND EXISTS
 (SELECT 1
    FROM `metadata` m2
    WHERE m2.user_id = m.user_id AND m2.field_id = '51' AND m2.value = 'Yes')
AND EXISTS
  (SELECT 1
     FROM `metadata` m3
     WHERE m3.user_id = m.user_id AND m3.field_id = '6' AND m3.value = 'Dog');
</code>```

However, IMO, it may be better to attempt to remodel the table like so (and ideally choose better descriptions for the attributes as columns):

```<code>UserID   Field51  Field6 Field68  Field69
----------------------------------------
1        Yes      Dog     TX      78701
2        No       Cat     LA      NULL
</code>```

This will make things much easier to query.

Body:
I want to select a userid from a single table based on multiple and condition.

UserID   FieldID  Value
-----------------------------------
1        51         Yes
1        6          Dog
2        6          Cat
1        68         TX
1        69         78701
2        68         LA

What I'm trying to get in simple words:

if user search for texas or 78701,
Select userId where (68 = TX OR 69=78701) AND (51=yes) AND (6=Dog)

This should return user id 1.

This is what I tried, but returns null.

SELECT user_id FROM `metadata`
WHERE ( (`field_id` = '68' AND value LIKE '%TX%')
   OR (`field_id` = '69' AND value LIKE '%78701%') )
   AND `field_id` = '51' AND value = 'Yes'
   AND `field_id` = '6' AND value = 'Dog'

Body:
Your table structure resembles attribute+value modelling, which essentially splits up the columns of a row into individual pairs, and has the side effect of very weak typing.

As you've noted, this can also make things tricky to query, since you have to reason over multiple rows in order to make sense of the original data model.

One approach could be to take an opinion of a 'primary' criterion, and then apply additional criteria by reasoning over the shredded data, joined back by user id:

SELECT DISTINCT m.user_id
FROM `metadata` m
WHERE ((`field_id` = '68' AND value LIKE '%TX%')
       OR (`field_id` = '69' AND value LIKE '%78701%'))
 AND EXISTS
 (SELECT 1
    FROM `metadata` m2
    WHERE m2.user_id = m.user_id AND m2.field_id = '51' AND m2.value = 'Yes')
AND EXISTS
  (SELECT 1
     FROM `metadata` m3
     WHERE m3.user_id = m.user_id AND m3.field_id = '6' AND m3.value = 'Dog');

However, IMO, it may be better to attempt to remodel the table like so (and ideally choose better descriptions for the attributes as columns):

UserID   Field51  Field6 Field68  Field69
----------------------------------------
1        Yes      Dog     TX      78701
2        No       Cat     LA      NULL

This will make things much easier to query.


问:
Timeout in Production but not in Local Rails
I am developing a Rails application.

In a view, I made a form which action is sent to a controller in AJAX by using remote: true

```<code><%= form_tag({controller: "my_controller", action: "my_method"}, {remote: true}) do %>
</code>```

Every thing works fine, but the controller can take a while to compute de result (sometimes more than 100 seconds).

The problem I am facing is that in local environment it works fine, but in production environment, I am getting ERROR 504 GATEWAY_TIMEOUT

Is there a way to make it work in production ?

答:
This is likely due to your load balancer (possibly apache or nginx) in front of your rails server timing out the response because it's taking so long!  I'm most familiar w/ Nginx so I'll walk you through the fix there.

If you set the response timeouts to 10 minutes (600 seconds) in nginx.conf:

```<code>proxy_connect_timeout       600;
proxy_send_timeout          600;
proxy_read_timeout          600;
send_timeout                600;
</code>```

Then restart nginx with service nginx reload you should not see the 504s anymore :)

Body:
I am developing a Rails application.

In a view, I made a form which action is sent to a controller in AJAX by using remote: true

<%= form_tag({controller: "my_controller", action: "my_method"}, {remote: true}) do %>

Every thing works fine, but the controller can take a while to compute de result (sometimes more than 100 seconds).

The problem I am facing is that in local environment it works fine, but in production environment, I am getting ERROR 504 GATEWAY_TIMEOUT

Is there a way to make it work in production ?

Body:
This is likely due to your load balancer (possibly apache or nginx) in front of your rails server timing out the response because it's taking so long!  I'm most familiar w/ Nginx so I'll walk you through the fix there.

If you set the response timeouts to 10 minutes (600 seconds) in nginx.conf:

proxy_connect_timeout       600;
proxy_send_timeout          600;
proxy_read_timeout          600;
send_timeout                600;

Then restart nginx with service nginx reload you should not see the 504s anymore :)


问:
Filter out console messages in Chrome Dev Tools
I have a list of 4 console log messages that appear every 2 seconds in my Dev Tools console. I'd like to filter them out but using the filtering DSL that I use for the Network tab doesn't seem to work

My messages are:

[service]: failed to connect to service

OPTIONS http://127.0.0.1:8888/service net::ERR_CONNECTION_REFUSED

What type of filter should I use to make them disappear??? I tried using rexeg, something like [^service] but it didn't seem to work...

答:
With the latest version of Chrome (^62) it finally seems to work.

I can use -[service] and it properly filters out the messages.


问:
Selecting arrays with specific element values
This is driving me nuts, I've been trying to figure out how to do this one thing for hours now.

What I want to do is select all array items that have a specific value. This is easiest to explain by example:

I have an array, called media[]. It holds ALL of the media in my media gallery. It has two properties of note: path and gallery, or media[x][0] and media[x][1].

I want to select all media objects that belong in a certain gallery, and then add them to that gallery. That's where I'm struggling and it's driving me mad.

Here are my fumbled attempts at trying to do this... this is some seriously messy code (and mostly pointless), I'm just providing it so you can get a sense of how clueless I am about this. Please note that NONE of the code I have right now actually tries to do anything; everything I've done so far ends up as a broken for or while loop that either does nothing or crashes Chrome.

```<code>// this function is meant to return an array of all media items
// that belong in a certain gallery... didn't get that far because
// the loops tripped me up
function getTheMedia (galNum) {
    var output = [];
    for (var i = 0; i < media.length; ++i) {
        // I tried using an if statement here to check if the
        // media[i][1] == galNum, and if so, add it to the output
        // but that didn't work
        output.push(media[i]);
    }
    return output;
}

// this function was actually my first attempt but I kept running into
// the same issue as above
function fillGal () {
    /*
    var output = [];
    for (var i = 0; i < Gallery.length; ++i) {
        output.push(Gallery[i]);
    }
    */
    var output = [];
    var i = 0;
    while (i < media.length) {
        output.push(i);
        i++;
    }
    console.log(output);
}
</code>```

Seeing as I'm kind of burnt out and frustrating with running in circles (...loops? aha...), all I'm really looking for is a way to select only those specific array items as specified above. Everything else (adding them to the Gallery, etc) I can figure out myself.

Otherwise I'm just going to have to go back to the old way: define separate media[]arrays for each "gallery" (mediaThisGallery, mediaThatGallery, etc), and then combine them all at the end to get "allMedia". Only reason I don't want to do that is because I want to be able to change which gallery a media item belongs to... this HAS to be possible, right?

Thanks in advance! Sorry for the scatter-brainedness. I also apologize if the title is a bit off.

EDIT:

```<code>var media = [];

media[0] = ['0.png', 0, 'index'];
media[1] = ['0.png', 0];

media[2] = ['new/316.png', 1, "316"];
media[3] = ['new/kitties.jpg', 1, "D'aww kitties!!"];
media[4] = ['new/home.jpg', 1, "\"I'm Going Home\""];
media[5] = ['new/3.mp4', 1, "Crucible Carnage"];
media[6] = ['new/942.jpg', 1, "this is straight for testing purposes like omg long ass title lol"];
media[7] = ['new/boom.mp4', 1, "Maximum Efficiency"];
media[8] = ['new/42.jpg', 1, "Moo"];

// this is only included as a quick fix so my working code doesn't break
// as my "production" code is using multiple arrays; Media is used
// to store only the selected array (current Gallery)
// in other words, ignore this
var Media = [];
Media = media;

var Gallery = [];
Gallery[0] = [mediaRoot, "index", media ];
Gallery[1] = [mediaRoot, "new", Media ];
</code>```

It's pretty arbitrary atm.

Note that the main reason I'm converting from multiple arrays to a single array is that eventually, I plan to expand this app and I thought it made more sense to store ALL media in a single "database".

答:
Why not define your galleries and gallery-entries in JS-notation like:

```<code>var galleries = [
  {
    id: 1,
    name: "new",
    medias: [
      {
        img: "new/316.png",
        name: 316
      },
      {
        img: "new/home.png",
        name: "Going Home"
      }
    ]
  },
  {
    id: 2,
    name: "index",
    medias: []
  }
]
</code>```

That way you would be able to visualize the data-structure which in turn would make it easier for you to traverse, add and remove elements.

Body:
This is driving me nuts, I've been trying to figure out how to do this one thing for hours now.

What I want to do is select all array items that have a specific value. This is easiest to explain by example:

I have an array, called media[]. It holds ALL of the media in my media gallery. It has two properties of note: path and gallery, or media[x][0] and media[x][1].

I want to select all media objects that belong in a certain gallery, and then add them to that gallery. That's where I'm struggling and it's driving me mad.

Here are my fumbled attempts at trying to do this... this is some seriously messy code (and mostly pointless), I'm just providing it so you can get a sense of how clueless I am about this. Please note that NONE of the code I have right now actually tries to do anything; everything I've done so far ends up as a broken for or while loop that either does nothing or crashes Chrome.

// this function is meant to return an array of all media items
// that belong in a certain gallery... didn't get that far because
// the loops tripped me up
function getTheMedia (galNum) {
    var output = [];
    for (var i = 0; i < media.length; ++i) {
        // I tried using an if statement here to check if the
        // media[i][1] == galNum, and if so, add it to the output
        // but that didn't work
        output.push(media[i]);
    }
    return output;
}

// this function was actually my first attempt but I kept running into
// the same issue as above
function fillGal () {
    /*
    var output = [];
    for (var i = 0; i < Gallery.length; ++i) {
        output.push(Gallery[i]);
    }
    */
    var output = [];
    var i = 0;
    while (i < media.length) {
        output.push(i);
        i++;
    }
    console.log(output);
}

Seeing as I'm kind of burnt out and frustrating with running in circles (...loops? aha...), all I'm really looking for is a way to select only those specific array items as specified above. Everything else (adding them to the Gallery, etc) I can figure out myself.

Otherwise I'm just going to have to go back to the old way: define separate media[]arrays for each "gallery" (mediaThisGallery, mediaThatGallery, etc), and then combine them all at the end to get "allMedia". Only reason I don't want to do that is because I want to be able to change which gallery a media item belongs to... this HAS to be possible, right?

Thanks in advance! Sorry for the scatter-brainedness. I also apologize if the title is a bit off.

EDIT:

var media = [];

media[0] = ['0.png', 0, 'index'];
media[1] = ['0.png', 0];

media[2] = ['new/316.png', 1, "316"];
media[3] = ['new/kitties.jpg', 1, "D'aww kitties!!"];
media[4] = ['new/home.jpg', 1, "\"I'm Going Home\""];
media[5] = ['new/3.mp4', 1, "Crucible Carnage"];
media[6] = ['new/942.jpg', 1, "this is straight for testing purposes like omg long ass title lol"];
media[7] = ['new/boom.mp4', 1, "Maximum Efficiency"];
media[8] = ['new/42.jpg', 1, "Moo"];

// this is only included as a quick fix so my working code doesn't break
// as my "production" code is using multiple arrays; Media is used
// to store only the selected array (current Gallery)
// in other words, ignore this
var Media = [];
Media = media;

var Gallery = [];
Gallery[0] = [mediaRoot, "index", media ];
Gallery[1] = [mediaRoot, "new", Media ];

It's pretty arbitrary atm.

Note that the main reason I'm converting from multiple arrays to a single array is that eventually, I plan to expand this app and I thought it made more sense to store ALL media in a single "database".

Body:
Why not define your galleries and gallery-entries in JS-notation like:

var galleries = [
  {
    id: 1,
    name: "new",
    medias: [
      {
        img: "new/316.png",
        name: 316
      },
      {
        img: "new/home.png",
        name: "Going Home"
      }
    ]
  },
  {
    id: 2,
    name: "index",
    medias: []
  }
]

That way you would be able to visualize the data-structure which in turn would make it easier for you to traverse, add and remove elements.


问:
save string to a date field in sql server
I have the following string that I need to save to a sql server database column that has a date datatype.

'2017-05-25T00:00:00'

Can I use cast within a insert script to save this value and is this the best way?

答:
You can use any of the following options.</p>

```<code>insert into myTable
values (CAST('2017-05-25T00:00:00' as datetime))

insert into myTable
values (Convert(varchar(30),'2017-05-25T00:00:00',102))
</code>```

Body:
You can use any of the following options.

insert into myTable
values (CAST('2017-05-25T00:00:00' as datetime))

insert into myTable
values (Convert(varchar(30),'2017-05-25T00:00:00',102))


问:
Tealium integration
I am looking at my project page load improvement and I do see both utag.js and utag.sync.js loaded.

Does utag and utag.sync.js both javascript files needed for tealium
  integration.

If both are needed then why ? what is the purpose, difference between these two js?

Thanks,
Sri

答:
utag.js and utag.sync.js are there for slightly different reasons. Essentially, utag.js will be needed as this is the main JavaScript file that Tealium generates. It's generally responsible for looking after your Data Layer, evaluating load rules, running extensions, loading/executing your tags, etc. All that sweet, sweet Tealium iQ functionality comes from there.

With all this in mind, the utag.js file is pretty big. So, in order to not slow down the page load, Tealium recommends that you load utag.js asynchronously in the  (see here).

However, there are a few situations where your vendor code needs to be run at the very beginning of the page load. Examples of this include any A/B testing tags (Optimizely, Adobe Target, etc.) or occasionally some content-changing tags require being loaded early in order to flickering.

For these situations, Tealium provides utag.sync.js—that's a separate file from utag.js that you can load synchronously in the . You can then paste the code from any of these tags that require very early loading, in order to be sure that they will be loaded in time. You can read more about how to use utag.sync.js here.

But yes, long story short: utag.js is the main Tealium JS file, responsible for the main functionality. utag.sync.js is then an additional file used for certain situations/bits of code that wouldn't work as required if implemented in utag.js.

Title: Tealium integration

Body:
utag.js and utag.sync.js are there for slightly different reasons. Essentially, utag.js will be needed as this is the main JavaScript file that Tealium generates. It's generally responsible for looking after your Data Layer, evaluating load rules, running extensions, loading/executing your tags, etc. All that sweet, sweet Tealium iQ functionality comes from there.

With all this in mind, the utag.js file is pretty big. So, in order to not slow down the page load, Tealium recommends that you load utag.js asynchronously in the <body> (see here).

However, there are a few situations where your vendor code needs to be run at the very beginning of the page load. Examples of this include any A/B testing tags (Optimizely, Adobe Target, etc.) or occasionally some content-changing tags require being loaded early in order to flickering.

For these situations, Tealium provides utag.sync.js—that's a separate file from utag.js that you can load synchronously in the <head>. You can then paste the code from any of these tags that require very early loading, in order to be sure that they will be loaded in time. You can read more about how to use utag.sync.js here.

But yes, long story short: utag.js is the main Tealium JS file, responsible for the main functionality. utag.sync.js is then an additional file used for certain situations/bits of code that wouldn't work as required if implemented in utag.js.


问:
iphone / Objective C - Comparing doubles not working
I think I'm going insane.
"counter" and "interval" are both doubles. This is happening on accelerometer:didAccelerate at an interval of (.01) . "counter" should eventually increment to "interval". For some reason i cant get this "if" to ring true.

Am I overlooking something?

```<code>double interval = .5;
 if( counter == interval ){ //should eventually be .50000 == .50000
  NSLog( @"Hit!" );
  [self playSound];
  counter = 0;
 }else{
  counter += .01;
 }
NSLog( @"%f, %f, %d",counter,interval,(counter == interval) );
</code>```

答:
In your else block, you are not adding 0.01 to counter, because that is not a representable double-precision value.  You are actually adding the value:

```<code>0.01000000000000000020816681711721685132943093776702880859375
</code>```

Unsurprisingly, when you repeatedly add this value to itself, you never get 0.5 exactly.

Two options: the better is to replace the if condition with (counter >= interval).  Alternatively, you could use a small power of two for the increment instead of something that cannot be represented, like 0.0078125.

Body:
I think I'm going insane.
"counter" and "interval" are both doubles. This is happening on accelerometer:didAccelerate at an interval of (.01) . "counter" should eventually increment to "interval". For some reason i cant get this "if" to ring true.

Am I overlooking something?

double interval = .5;
 if( counter == interval ){ //should eventually be .50000 == .50000
  NSLog( @"Hit!" );
  [self playSound];
  counter = 0;
 }else{
  counter += .01;
 }
NSLog( @"%f, %f, %d",counter,interval,(counter == interval) );

Body:
In your else block, you are not adding 0.01 to counter, because that is not a representable double-precision value.  You are actually adding the value:

0.01000000000000000020816681711721685132943093776702880859375

Unsurprisingly, when you repeatedly add this value to itself, you never get 0.5 exactly.

Two options: the better is to replace the if condition with (counter >= interval).  Alternatively, you could use a small power of two for the increment instead of something that cannot be represented, like 0.0078125.


问:
Can we use document.getElementById() dynamically
I am trying to print an html page using window.print. Where as the html page is getting updated for each rest API call. so can i print continuously for each rest API call???

```<code>    var myPrintContent = document.getElementById("data-box");
    var myPrintWindow = window.open('','Print-Window');
    var popupWindow = window.open('','Print-Window');
    popupWindow.document.write('<TITLE></TITLE>\n');
    popupWindow.document.write('<URL></URL>\n');
    popupWindow.document.write('<script>\n');
    popupWindow.document.write('function print_win(){\n');
    popupWindow.document.write('\nwindow.print();\n');
    popupWindow.document.write('}\n');
    popupWindow.document.write('<\/script>\n');
    popupWindow.document.write('</HEAD>\n');
    popupWindow.document.write('<BODY onload="print_win()" >\n');
    popupWindow.document.write(myPrintContent.innerHTML)
    popupWindow.document.write('</BODY>\n');
    popupWindow.document.write('</HTML>\n');
    popupWindow.document.close();
</code>```

This is what i am doing. so content of data-box.innerhtml is different for different employees. So on each time i call print one page i will get. But for the next employee if i am again calling the print function the called employee details is only getting printed. So what i want is if i gave different id s for different employees, how can i get all the ids dynamically. so that once i call print i can get all the data s of all employee printed.

答:
```<code>window.print();
</code>```

as can be read atw3school is a method to print the current window. It has nothing to with document.getElementById() method.
If your are interested in printing your page, simple print the window. That's it.

But if you want to use document.getElementById() for some other purposes, you can pass variable (the dynamic id) of element in consideration.
here is how you do it

```<code>var myId = "my-element-id";
var myContent = document.getElementById(myId).innerHTML;
</code>```

Better post any code for better help.

Body:
I am trying to print an html page using window.print. Where as the html page is getting updated for each rest API call. so can i print continuously for each rest API call???

    var myPrintContent = document.getElementById("data-box");
    var myPrintWindow = window.open('','Print-Window');
    var popupWindow = window.open('','Print-Window');
    popupWindow.document.write('<TITLE></TITLE>\n');
    popupWindow.document.write('<URL></URL>\n');
    popupWindow.document.write('

Body:
window.print();

as can be read atw3school is a method to print the current window. It has nothing to with document.getElementById() method.
If your are interested in printing your page, simple print the window. That's it.

But if you want to use document.getElementById() for some other purposes, you can pass variable (the dynamic id) of element in consideration.
here is how you do it

var myId = "my-element-id";
var myContent = document.getElementById(myId).innerHTML;

Better post any code for better help.


问:
Creating a custom JSON string from a PHP array
I have a PHP array which outputs as follows:

```<code>Array ( [0] => email@email.com [1] => email@email.com [2] => email@email.com [3] => email@email.com [4] => email@email.com [5] => email@email.com )
</code>```

This array houses a list of email addresses, which I need to output as a custom JSON string, which matches the following:

```<code>{ "email@email.com": {"id":1}, "email@email.com": {"id": 2}, "email@email.com": {"id": 3}, "email@email.com": {"id": 4}, "email@email.com": {"id": 5}, "email@email.com": {"id": 6} }
</code>```

Is anyone able to point me in the right direction? I have tried using json_encode, without success.

答:
Just flip the array </p>

```<code>$arr = Array ( 'email1@email.com', 'email2@email.com', 'email3@email.com');

$json = [];
foreach ($arr as $k =>$v) {
    $json[$v]['id'] = $k+1;
}

echo json_encode($json); // {"email1@email.com":{"id":1},"email2@email.com":{"id":2},"email3@email.com":{"id":3}}
</code>```

Body:
I have a PHP array which outputs as follows:

Array ( [0] => email@email.com [1] => email@email.com [2] => email@email.com [3] => email@email.com [4] => email@email.com [5] => email@email.com )

This array houses a list of email addresses, which I need to output as a custom JSON string, which matches the following:

{ "email@email.com": {"id":1}, "email@email.com": {"id": 2}, "email@email.com": {"id": 3}, "email@email.com": {"id": 4}, "email@email.com": {"id": 5}, "email@email.com": {"id": 6} }

Is anyone able to point me in the right direction? I have tried using json_encode, without success.

Body:
Just flip the array

$arr = Array ( 'email1@email.com', 'email2@email.com', 'email3@email.com');

$json = [];
foreach ($arr as $k =>$v) {
    $json[$v]['id'] = $k+1;
}

echo json_encode($json); // {"email1@email.com":{"id":1},"email2@email.com":{"id":2},"email3@email.com":{"id":3}}


问:
Send +1 Day on JQuery DatePicker
I want to emit the day after the selected day.

```<code>$('#toDate').datepicker({
        inline: true,
        altField: '#x',
        dateFormat: "dd-mm-yy", //day
        altFormat: "yy-mm-dd", //year
        monthNames: ["Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"],
        dayNamesMin: ["Pa", "Pt", "Sl", "Ça", "Pe", "Cu", "Ct"],
        firstDay: 1,
        numberOfMonths: 1,
        onSelect: function(dateText, inst) {
          socket.emit('sockettoDate', $('#x').val());
        }
      });
</code>```

If '2017-11-16' selected, I want to emit '2017-11-17'. Is there any way to do that?

答:
Following code should work for you:</p>

```<code>$('#toDate').datepicker({
    inline: true,
    altField: '#x',
    dateFormat: "dd-mm-yy", //day
    altFormat: "yy-mm-dd", //year
    monthNames: ["Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"],
    dayNamesMin: ["Pa", "Pt", "Sl", "Ça", "Pe", "Cu", "Ct"],
    firstDay: 1,
    numberOfMonths: 1,
    onSelect: function(dateText, inst) {
        var dateup = ('0' + (parseInt(inst.selectedDay) + 1)).slice(-2);
        var monthup = ('0' + (parseInt(inst.selectedMonth) + 1)).slice(-2);
        var newdate = inst.selectedYear+'-'+monthup+'-'+dateup;
        socket.emit('sockettoDate', newdate);
    }
});
</code>```

Title: Send +1 Day on JQuery DatePicker

Body:
I want to emit the day after the selected day.

$('#toDate').datepicker({
        inline: true,
        altField: '#x',
        dateFormat: "dd-mm-yy", //day
        altFormat: "yy-mm-dd", //year
        monthNames: ["Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"],
        dayNamesMin: ["Pa", "Pt", "Sl", "Ça", "Pe", "Cu", "Ct"],
        firstDay: 1,
        numberOfMonths: 1,
        onSelect: function(dateText, inst) {
          socket.emit('sockettoDate', $('#x').val());
        }
      });

If '2017-11-16' selected, I want to emit '2017-11-17'. Is there any way to do that?

Body:
Following code should work for you:

$('#toDate').datepicker({
    inline: true,
    altField: '#x',
    dateFormat: "dd-mm-yy", //day
    altFormat: "yy-mm-dd", //year
    monthNames: ["Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"],
    dayNamesMin: ["Pa", "Pt", "Sl", "Ça", "Pe", "Cu", "Ct"],
    firstDay: 1,
    numberOfMonths: 1,
    onSelect: function(dateText, inst) {
        var dateup = ('0' + (parseInt(inst.selectedDay) + 1)).slice(-2);
        var monthup = ('0' + (parseInt(inst.selectedMonth) + 1)).slice(-2);
        var newdate = inst.selectedYear+'-'+monthup+'-'+dateup;
        socket.emit('sockettoDate', newdate);
    }
});


问:
Looping through JSON object in Swift
I got this JSON object which I sent from my server to my Swift application.

```<code>{
  "625289": {
    "id": 1,
    "subject": "Hello World"
  },
  "625277": {
    "id": 2,
    "subject":"Bye World!"
  }
}
</code>```

So i tried to get the subject for each result ("625289" and "625277") by doing as below in my Swift class:

```<code>struct Resultat : Decodable   {
  let subject: String
}

var result = [Resultat]()
let urlll = URL(string:"http://localhost:8888/api/pouet.php")

URLSession.shared.dataTask(with: urlll!) { (data, response, error) in
  do {
    print("coucoulol")
    //print(response)

    self.result = try JSONDecoder().decode([Resultat].self, from: data!)

    print(self.result)

    for eachTicket in self.result {
      print(eachTicket.subject)
    }
  } catch {
    print("error"+error.localizedDescription)
  }
}.resume()
</code>```

However, when I tried to execute the code, it says "The data couldn’t be read because it isn’t in the correct format." From what I understand, the loop for in the code is suffice to get the values in the arrays or maybe I'm wrong. Any help is appreciated, thanks.

答:
You can try using SwiftyJSON below

$0.0 = Key

$0.1 = value

```<code>let data = JSON(result)
data.dictionaryValue.forEach({
     print($0.1)
})
</code>```

Title: Looping through JSON object in Swift

Body:
I got this JSON object which I sent from my server to my Swift application.

{
  "625289": {
    "id": 1,
    "subject": "Hello World"
  },
  "625277": {
    "id": 2,
    "subject":"Bye World!"
  }
}

So i tried to get the subject for each result ("625289" and "625277") by doing as below in my Swift class:

struct Resultat : Decodable   {
  let subject: String
}

var result = [Resultat]()
let urlll = URL(string:"http://localhost:8888/api/pouet.php")

URLSession.shared.dataTask(with: urlll!) { (data, response, error) in
  do {
    print("coucoulol")
    //print(response)

    self.result = try JSONDecoder().decode([Resultat].self, from: data!)

    print(self.result)

    for eachTicket in self.result {
      print(eachTicket.subject)
    }
  } catch {
    print("error"+error.localizedDescription)
  }
}.resume()

However, when I tried to execute the code, it says "The data couldn’t be read because it isn’t in the correct format." From what I understand, the loop for in the code is suffice to get the values in the arrays or maybe I'm wrong. Any help is appreciated, thanks.

Body:
You can try using SwiftyJSON below

$0.0 = Key

$0.1 = value

let data = JSON(result)
data.dictionaryValue.forEach({
     print($0.1)
})


问:
Display an image in a Fusiontable, which is stored in Google Drive
I uploaded some images to a public folder in my Google Drive and would like to display them in a Fusiontable. I defined a column "link" as "Four line image" and store a link to the image there in the following format (provided by @Mori)

https://drive.google.com/uc?id=FILE-ID

example: https://drive.google.com/uc?id=0B6qZJQj7B-4ERS1KZ3p2SE9IbkU

I also tried the following format (provided by @niutech)

http://googledrive.com/host/<folderID>/<filename>

Unfortunately the result looks like this (screenshot 1)

Only after right click onto the image placeholder and selecting "View image", the image is displayed in a separate window. Now going back to the fusiontable the image appears correctly, see screenshot 2:

What could be the solution to this problem? I would like to see all images without need to right click first. Btw, I'm using Firefox.

EDIT: I now set the Fusiontable to "visible to anybody with link" and tested with Google Chrome and Opera. There it works fine. Firefox still does not work. Seems to be a browser issue...

答:
You almost had the correct answer. You have to change your picture's URL from the one for viewing the picture, to a direct URL for download.

See https://www.labnol.org/internet/direct-links-for-google-drive/28356/ for details.

I managed to do this in a calculated column (I use google form to gather info, then google spreadsheet and than synchronized fusion table). I changed the URL with spreadsheet formula:

```<code>=CONCAT("https://drive.google.com/uc?export=download&id=",right(left('URL',(len('URL')-17)),len('URL')-49))
</code>```

Where 'URL' is the URL for viewing your picture in the browser.

Hope it helps anyone else!

Body:
You almost had the correct answer. You have to change your picture's URL from the one for viewing the picture, to a direct URL for download.

See https://www.labnol.org/internet/direct-links-for-google-drive/28356/ for details.

I managed to do this in a calculated column (I use google form to gather info, then google spreadsheet and than synchronized fusion table). I changed the URL with spreadsheet formula:

=CONCAT("https://drive.google.com/uc?export=download&id=",right(left('URL',(len('URL')-17)),len('URL')-49))

Where 'URL' is the URL for viewing your picture in the browser.

Hope it helps anyone else!


问:
Exception When Deserializing an ISO Date in JSON
I am trying to deserialize an API response to a class object. But I get the error:

DateTime content 2017-11-15T10: 00: 00 does not start with \ / Date (and not ending) \ /, which is required for JSON.

My Code:

```<code>client.BaseAddress = new Uri(APP_URL);

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(APPLICATIONJSON));

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<HttpConference>));

HttpResponseMessage response = client.GetAsync(GET_ALL_CONFERNECES).Result;

response.EnsureSuccessStatusCode();

System.IO.Stream svar = response.Content.ReadAsStreamAsync().Result;

List<HttpConference> model = (List<HttpConference>)serializer.ReadObject(svar);
</code>```

In the database I am using datetime.

The Json response:

```<code>[
{
    "ID": 1,
    "Namn": "Conference Microsoft",
    "StartDatum": "2017-11-15T10:00:00",
    "SlutDatum": "2017-11-15T12:00:00",
    "KonferensID": null
},
{
    "ID": 2,
    "Namn": "föreläsning",
    "StartDatum": null,
    "SlutDatum": null,
    "KonferensID": null
}
]
</code>```

this is the errormessage thrown by the code:

'svar.WriteTimeout' threw an exception of type 'System.InvalidOperationException'

I get an error at the ReadAsStreamAsync:

```<code>EDIT
</code>```

ReadTimeout = 'reply.ReadTimeout' threw an exception of type 'System.InvalidOperationException'

found this article that talks about this problem. But I didn't know how to implement it in my code. Any ideas?

答:
Since you agree to use JSON.NET here is a solution with it:

Try it online

```<code>public static void Main()
{
    // I use the json direclty instead of the httpClient for the example
    var json = @"[
    {
    ""ID"": 1,
    ""Namn"": ""Conference Microsoft"",
    ""StartDatum"": ""2017-11-15T10:00:00"",
    ""SlutDatum"": ""2017-11-15T12:00:00"",
    ""KonferensID"": null
    },
    {
    ""ID"": 2,
    ""Namn"": ""föreläsning"",
    ""StartDatum"": null,
    ""SlutDatum"": null,
    ""KonferensID"": null
    }
    ]";

    // See the official doc there: https://www.newtonsoft.com/json
    var conferences = JsonConvert.DeserializeObject<List<Conference>>(json);
    Console.WriteLine(conferences[0].StartDatum);
}

// this class was generated with http://json2csharp.com/
public class Conference
{
    public int ID { get; set; }
    public string Namn { get; set; }
    public DateTime? StartDatum { get; set; }
    public DateTime? SlutDatum { get; set; }
    public object KonferensID { get; set; } // we cant know the type here. An int maybe?
}
</code>```

Output

```<code> 11/15/2017 10:00:00 AM
</code>```

Outside of the deserialization problem, you should use async/await instead of Result.

Body:
I am trying to deserialize an API response to a class object. But I get the error:

DateTime content 2017-11-15T10: 00: 00 does not start with \ / Date (and not ending) \ /, which is required for JSON.

My Code:

client.BaseAddress = new Uri(APP_URL);

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(APPLICATIONJSON));

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<HttpConference>));

HttpResponseMessage response = client.GetAsync(GET_ALL_CONFERNECES).Result;

response.EnsureSuccessStatusCode();

System.IO.Stream svar = response.Content.ReadAsStreamAsync().Result;

List<HttpConference> model = (List<HttpConference>)serializer.ReadObject(svar);

In the database I am using datetime.

The Json response:

[
{
    "ID": 1,
    "Namn": "Conference Microsoft",
    "StartDatum": "2017-11-15T10:00:00",
    "SlutDatum": "2017-11-15T12:00:00",
    "KonferensID": null
},
{
    "ID": 2,
    "Namn": "föreläsning",
    "StartDatum": null,
    "SlutDatum": null,
    "KonferensID": null
}
]

this is the errormessage thrown by the code:

'svar.WriteTimeout' threw an exception of type 'System.InvalidOperationException'

I get an error at the ReadAsStreamAsync:

EDIT

ReadTimeout = 'reply.ReadTimeout' threw an exception of type 'System.InvalidOperationException'

found this article that talks about this problem. But I didn't know how to implement it in my code. Any ideas?

Body:
Since you agree to use JSON.NET here is a solution with it:

Try it online

public static void Main()
{
    // I use the json direclty instead of the httpClient for the example
    var json = @"[
    {
    ""ID"": 1,
    ""Namn"": ""Conference Microsoft"",
    ""StartDatum"": ""2017-11-15T10:00:00"",
    ""SlutDatum"": ""2017-11-15T12:00:00"",
    ""KonferensID"": null
    },
    {
    ""ID"": 2,
    ""Namn"": ""föreläsning"",
    ""StartDatum"": null,
    ""SlutDatum"": null,
    ""KonferensID"": null
    }
    ]";

    // See the official doc there: https://www.newtonsoft.com/json
    var conferences = JsonConvert.DeserializeObject<List<Conference>>(json);
    Console.WriteLine(conferences[0].StartDatum);
}

// this class was generated with http://json2csharp.com/
public class Conference
{
    public int ID { get; set; }
    public string Namn { get; set; }
    public DateTime? StartDatum { get; set; }
    public DateTime? SlutDatum { get; set; }
    public object KonferensID { get; set; } // we cant know the type here. An int maybe?
}

Output

 11/15/2017 10:00:00 AM

Outside of the deserialization problem, you should use async/await instead of Result.


问:
Work-around for enclosing instance ineligible for garbage collection
The enclosing instance here isn't eligible for garbage collection as long as the enclosed instance is alive, right?

```<code>interface Foo<T> {
    T compute();

    default Foo<T> memoize() {
        return new Foo<>() {
            T result = null;

            boolean cached = false;

            @Override
            public T compute() {
                if (!cached) {
                    result = Foo.this.compute();
                    cached = true;
                }
                return result;
            }
        };
    }
}
</code>```

Does this solve that problem?

```<code>interface Foo<T> {
    T compute();

    default Foo<T> memoize() {
        return Foo.memoize(this);
    }

    private static <T> Foo<T> memoize(Foo<T> original) {
        class Bar implements Foo<T> {
            T result = null;

            Foo<T> foo;

            Bar(Foo<T> original) {
                foo = original;
            }

            @Override
            public T compute() {
                if (foo != null) {
                    result = foo.compute();
                    foo = null;
                }
                return result;
            }
        }
        return new Bar(original);
    }
}
</code>```

答:
No, why would it?

The Bar instance inside the memoize() function has a field that holds the Foo object. Whether you hold it via scoping or via implicit field assignment is irrelevant to garbage collection.

If you want to keep a reference to an object that can be garbage collected, use WeakReference/SoftReference.

Body:
The enclosing instance here isn't eligible for garbage collection as long as the enclosed instance is alive, right?

interface Foo<T> {
    T compute();

    default Foo<T> memoize() {
        return new Foo<>() {
            T result = null;

            boolean cached = false;

            @Override
            public T compute() {
                if (!cached) {
                    result = Foo.this.compute();
                    cached = true;
                }
                return result;
            }
        };
    }
}

Does this solve that problem?

interface Foo<T> {
    T compute();

    default Foo<T> memoize() {
        return Foo.memoize(this);
    }

    private static <T> Foo<T> memoize(Foo<T> original) {
        class Bar implements Foo<T> {
            T result = null;

            Foo<T> foo;

            Bar(Foo<T> original) {
                foo = original;
            }

            @Override
            public T compute() {
                if (foo != null) {
                    result = foo.compute();
                    foo = null;
                }
                return result;
            }
        }
        return new Bar(original);
    }
}


问:
Script to execute chmod continuously
I am working on Solaris servers. I am using an ADMIN user which has all the accesses while other colleagues are using a different user with limited access.
When others want to access the logs I have to manually give chmod 755 on the log folders and when a new file is generated I have to do chmod again.

Is there a way to write a script to run chmod continuously every 2 mins on some folders?

答:
What you need is a cron job.

To setup a cron task, run this command as your ADMIN user:

```<code>crontab -e
</code>```

It will open a text editor for you to enter a new job. Write the following line inside the text editor, replace [file1 file2 ... fileN] with the files you want to chmod, then save. It should run your chmod command every 2 minutes.

```<code>*/2 * * * * chmod 755 [file1 file2 ... fileN]
</code>```

This first solution doesn't work on every system! I don't really know about Solaris but if you have a problem with the first format, here is a workaround that will run you command every hour at the minute 0, the minute 2, the minute 4, and so on, until the minute 58:

```<code>0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,3 6,38,40,42,44,46,48,49,50,52,54,56,58 * * * * chmod 755 [file1 file2 ... fileN]
</code>```

You can check that your job was saved correctly with the command crontab -l that lists your cron tasks.

I invite you to read some documentation on cron so that you can understand the format used by crontab. Here is a good link

Title: Script to execute chmod continuously

Body:
What you need is a cron job.

To setup a cron task, run this command as your ADMIN user:

crontab -e

It will open a text editor for you to enter a new job. Write the following line inside the text editor, replace [file1 file2 ... fileN] with the files you want to chmod, then save. It should run your chmod command every 2 minutes.

*/2 * * * * chmod 755 [file1 file2 ... fileN]

This first solution doesn't work on every system! I don't really know about Solaris but if you have a problem with the first format, here is a workaround that will run you command every hour at the minute 0, the minute 2, the minute 4, and so on, until the minute 58:

0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,3 6,38,40,42,44,46,48,49,50,52,54,56,58 * * * * chmod 755 [file1 file2 ... fileN]

You can check that your job was saved correctly with the command crontab -l that lists your cron tasks.

I invite you to read some documentation on cron so that you can understand the format used by crontab. Here is a good link


答:
You should start by modifying your array.
As far as I've understood, the email address should become the key, the original key should be increased by one and be set as a value for an "id".

Please notice that since the email is being set as a key, if you'd have duplicated email address - the last one would overwrite the first occurrence.

```<code>$emails = array(
 0 => 'email1@email.com', //key => email
 1 => 'email2@email.com',
 2 => 'email3@email.com'
);

$new_emails = array();
foreach($emails as $key => $email){
 $new_emails[ $email ]['id'] = $key+1;
}

var_dump($new_emails);

/*
Output:
array(3) {
  ["email@email.com"]=>
  array(1) {
    ["id"]=>
    int(1)
  }
  ["email2@email.com"]=>
  array(1) {
    ["id"]=>
    int(2)
  }
  ["email3@email.com"]=>
  array(1) {
    ["id"]=>
    int(3)
  }
}
*/

echo json_encode($new_emails);

/*
Output:
{"email@email.com":{"id":1},"email2@email.com":{"id":2},"email3@email.com":{"id":3}}
*/
</code>```

Title: Creating a custom JSON string from a PHP array

Body:
You should start by modifying your array.
As far as I've understood, the email address should become the key, the original key should be increased by one and be set as a value for an "id".

Please notice that since the email is being set as a key, if you'd have duplicated email address - the last one would overwrite the first occurrence.

$emails = array(
 0 => 'email1@email.com', //key => email
 1 => 'email2@email.com',
 2 => 'email3@email.com'
);

$new_emails = array();
foreach($emails as $key => $email){
 $new_emails[ $email ]['id'] = $key+1;
}

var_dump($new_emails);

/*
Output:
array(3) {
  ["email@email.com"]=>
  array(1) {
    ["id"]=>
    int(1)
  }
  ["email2@email.com"]=>
  array(1) {
    ["id"]=>
    int(2)
  }
  ["email3@email.com"]=>
  array(1) {
    ["id"]=>
    int(3)
  }
}
*/

echo json_encode($new_emails);

/*
Output:
{"email@email.com":{"id":1},"email2@email.com":{"id":2},"email3@email.com":{"id":3}}
*/


问:
DRF Serializer Relations / JSON API Framework
*Update 1: Attempts with corresponding errors now shown in serializer code

*Update 2: I've narrowed the issue to a conflict with the JSON Api framework I'm using

I'm fairly new to Python and Django and I'm struggling quite a bit with relations. I'm able to create the relations in the database however I've been unable to serialize the models together for a response object, despite trying every method in the documentation which seems very straightforward. My goal is to return both models from an APIView on login and if this code doesn't error I get a response with just the user model. The errors vary based on the different techniques and are similar to what other users get when having trouble with relations, however their fixes haven't solved my problem.

I'm wondering if there's something obvious I'm not doing right. I'm happy to share more code but I'm really at a loss as to how to proceed.

Fyi: My models are in different apps which is why the fk reference is users.User

Models:

```<code>class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=50, unique=True)
    password = models.CharField(max_length=100)
    name = models.CharField(max_length=50)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    has_business = models.BooleanField(default=False)

    objects = UserManager()
    USERNAME_FIELD = 'email'

    REQUIRED_FIELDS = ['password']

    def get_full_name(self):
        return self.name

    def get_short_name(self):
        return self.name

    def __str__(self):
        return self.email

class Business(models.Model):
    name = models.CharField(max_length=50, unique=True)
    address = models.CharField(max_length=100)
    phone = models.CharField(max_length=20)
    description = models.CharField(max_length=500)
    user = models.ForeignKey(
        'users.User',
        related_name='business',
        unique=False,
        on_delete=models.CASCADE
        )
    has_driver = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
</code>```

Serializer:

```<code>class UserSerializer(serializers.ModelSerializer):

    token = srs.SerializerMethodField()

biz = BusinessSerializer(many=True, read_only=True,
source='business.id')
error: just returns user model

biz = BusinessSerializer(read_only=True, many=True, source='business')
error: ForeignKey' object has no attribute

biz = serializers.RelatedField(many=True, read_only=True)
error: 'User' object has no attribute 'biz'

biz = serializers.ReadOnlyField(source='businesses.id')
error: RelatedManager object at 0x7fed496fe208> is not JSON
serializable

biz = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
error:'User' object has no attribute 'biz'

    class Meta:
        model = models.User
        fields = ('id', 'email', 'password', 'name', 'token', 'has_business', 'biz')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):

        user = models.User(
                email = validated_data['email'],
                name = validated_data['name'],
                phone = validated_data['phone'],
                location = validated_data['location'],
            )
        user.set_password(validated_data['password'])
        user.save()

        return user
</code>```

View:

```<code>class LoginUser(APIView):
    permission_classes = (permissions.AllowAny,)
    resource_name = 'users'

    def post(self, request):
        email = request.POST.get('email', False)
        password = request.POST.get('password', False)

        if(email and password):

            lu = UserAuth()
            authenticated_user = lu.auth(email=email, password=password)

            if authenticated_user is not None:
                if authenticated_user.is_active:

                    serializer = serializers.UserSerializer(authenticated_user, context={'request': request})
                    return Response(serializer.data, status=status.HTTP_200_OK)
</code>```

答:
Turns out I was using a beta version (pip install djangorestframework-jsonapi==2.0.0-beta.1) of the JSON API Framework and it wasn't handling relations very well. I picked the beta because it was the one the documentation lists which is kind of odd. You have to dig a bit for the more stable versions. I'm embarrassed to say how long that took me to figure out.

Here's the stable version as of this day: pip install djangorestframework-jsonapi==2.2.0

Body:
*Update 1: Attempts with corresponding errors now shown in serializer code

*Update 2: I've narrowed the issue to a conflict with the JSON Api framework I'm using

I'm fairly new to Python and Django and I'm struggling quite a bit with relations. I'm able to create the relations in the database however I've been unable to serialize the models together for a response object, despite trying every method in the documentation which seems very straightforward. My goal is to return both models from an APIView on login and if this code doesn't error I get a response with just the user model. The errors vary based on the different techniques and are similar to what other users get when having trouble with relations, however their fixes haven't solved my problem.

I'm wondering if there's something obvious I'm not doing right. I'm happy to share more code but I'm really at a loss as to how to proceed.

Fyi: My models are in different apps which is why the fk reference is users.User

Models:

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=50, unique=True)
    password = models.CharField(max_length=100)
    name = models.CharField(max_length=50)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    has_business = models.BooleanField(default=False)

    objects = UserManager()
    USERNAME_FIELD = 'email'

    REQUIRED_FIELDS = ['password']

    def get_full_name(self):
        return self.name

    def get_short_name(self):
        return self.name

    def __str__(self):
        return self.email

class Business(models.Model):
    name = models.CharField(max_length=50, unique=True)
    address = models.CharField(max_length=100)
    phone = models.CharField(max_length=20)
    description = models.CharField(max_length=500)
    user = models.ForeignKey(
        'users.User',
        related_name='business',
        unique=False,
        on_delete=models.CASCADE
        )
    has_driver = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)

Serializer:

class UserSerializer(serializers.ModelSerializer):

    token = srs.SerializerMethodField()

biz = BusinessSerializer(many=True, read_only=True,
source='business.id')
error: just returns user model

biz = BusinessSerializer(read_only=True, many=True, source='business')
error: ForeignKey' object has no attribute

biz = serializers.RelatedField(many=True, read_only=True)
error: 'User' object has no attribute 'biz'

biz = serializers.ReadOnlyField(source='businesses.id')
error: RelatedManager object at 0x7fed496fe208> is not JSON
serializable

biz = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
error:'User' object has no attribute 'biz'

    class Meta:
        model = models.User
        fields = ('id', 'email', 'password', 'name', 'token', 'has_business', 'biz')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):

        user = models.User(
                email = validated_data['email'],
                name = validated_data['name'],
                phone = validated_data['phone'],
                location = validated_data['location'],
            )
        user.set_password(validated_data['password'])
        user.save()

        return user

View:

class LoginUser(APIView):
    permission_classes = (permissions.AllowAny,)
    resource_name = 'users'

    def post(self, request):
        email = request.POST.get('email', False)
        password = request.POST.get('password', False)

        if(email and password):

            lu = UserAuth()
            authenticated_user = lu.auth(email=email, password=password)

            if authenticated_user is not None:
                if authenticated_user.is_active:

                    serializer = serializers.UserSerializer(authenticated_user, context={'request': request})
                    return Response(serializer.data, status=status.HTTP_200_OK)


答:
Don't ever compare doubles or floats with equality - they might look the same at the number of significant figures your are examining but the computer sees more.

For this purpose, the Foundation Framework provides "epsilon" values for different types such as "float" and "double". If the distance between two numbers is smaller than epsilon, you can assume these two numbers are equal.

In your case, you would use it as follow:

```<code>- (BOOL)firstDouble:(double)first isEqualTo:(double)second {
    if(fabs(first - second) < DBL_EPSILON)
        return YES;
    else
        return NO;
}
</code>```

Or in Swift 4:

```<code>func doublesAreEqual(first: Double, second: Double) -> Bool {
    if fabs(first - second) < .ulpOfOne {
        return true
    }
    return false
}
</code>```

Two very useful links:

What Every Computer Scientist Should Know About Floating-Point Arithmetic

Interesting discussion of Unit in Last Place (ULP) and usage in Swift

Friday Q&A 2011-01-04: Practical Floating Point

Title: iphone / Objective C - Comparing doubles not working

Body:
I think I'm going insane.
"counter" and "interval" are both doubles. This is happening on accelerometer:didAccelerate at an interval of (.01) . "counter" should eventually increment to "interval". For some reason i cant get this "if" to ring true.

Am I overlooking something?

double interval = .5;
 if( counter == interval ){ //should eventually be .50000 == .50000
  NSLog( @"Hit!" );
  [self playSound];
  counter = 0;
 }else{
  counter += .01;
 }
NSLog( @"%f, %f, %d",counter,interval,(counter == interval) );

Body:
Don't ever compare doubles or floats with equality - they might look the same at the number of significant figures your are examining but the computer sees more.

For this purpose, the Foundation Framework provides "epsilon" values for different types such as "float" and "double". If the distance between two numbers is smaller than epsilon, you can assume these two numbers are equal.

In your case, you would use it as follow:

- (BOOL)firstDouble:(double)first isEqualTo:(double)second {
    if(fabs(first - second) < DBL_EPSILON)
        return YES;
    else
        return NO;
}

Or in Swift 4:

func doublesAreEqual(first: Double, second: Double) -> Bool {
    if fabs(first - second) < .ulpOfOne {
        return true
    }
    return false
}

Two very useful links:

What Every Computer Scientist Should Know About Floating-Point Arithmetic

Interesting discussion of Unit in Last Place (ULP) and usage in Swift

Friday Q&A 2011-01-04: Practical Floating Point

ContentLicense: CC BY-SA 4.0


问:
Edge extension requesting JSON doesn't work
I'm working on an Edge extension, and I need to request JSON from an external website. The following example works fine on stackoverflow.com, but fails on steamcommunity.com/id/ where I need it.

Here are the files I have:

jQuery (from local file)

manifest.json:

```<code>{
  "author": "me",
  "name": "Get JSON",
  "description": "get json",
  "version": "0.1",
  "manifest_version": 2,
  "content_scripts": [
    {
      "matches": [
        "*://steamcommunity.com/id/*",
        "*://stackoverflow.com/*"
      ],
      "js": ["jquery.min.js", "myscript.js"]
    }
  ]
}
</code>```

myscript.js:

```<code>var url = 'https://raw.githubusercontent.com/bahamas10/css-color-names/master/css-color-names.json';

$.getJSON(url, function(data) {
  console.log(data);
});
</code>```

As I've said, this example works fine on Stackoverflow, but fails on Steam.

This is the error I receive on the Steam website:

```<code>CSP14312: Resource violated directive 'connect-src 'self' http://steamcommunity.com https://steamcommunity.com https://api.steampowered.com/ http://localhost:27060 http://store.steampowered.com/ https://store.steampowered.com/' in Content-Security-Policy: https://raw.githubusercontent.com/bahamas10/css-color-names/master/css-color-names.json. Resource will be blocked.
</code>```

EDIT: I should also add, that this exact example works fine when using a Chrome extension in Google Chrome.

Any help is appreciated.

答:
Microsoft Edge, differently from Chrome and Firefox, doesn't ignore the website CSP rules for extensions.

See https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/11320214/ for an open issue.

The only viable workaround I know, which I also tested myself, is to change the CSP response headers on the fly by using browser.webRequest.onHeadersReceived, which luckily is well supported in Edge.

NOTE: this code was adapted from this great article, which also explains the problem in more detail: https://transitory.technology/browser-extensions-and-csp-headers/

The code adds your extension to the allowed urls for each CSP header and directive, it should be executed in the background page, which should be set as persistent.

Make sure to add the webRequest and webRequestBlocking permissions to your manifest.json.

```<code>const cspHeaderNames = [
  'content-security-policy',
  'content-security-policy-report-only',
  'x-webkit-csp'
];

// @see https://developer.mozilla.org/en-US/docs/Web/Security/CSP/CSP_policy_directives
const cspSources = [
  'connect-src',
  'default-src',
  'font-src',
  'frame-src',
  'img-src',
  'media-src',
  'object-src',
  'script-src',
  'style-src',
  'child-src',
  'form-action',
];

const url = browser.extension.getURL("").slice(0, -1); // (remove trailing "/")

browser.webRequest.onHeadersReceived.addListener(details => {
  details.responseHeaders.forEach(header => {
    const isCspHeader = cspHeaderNames.indexOf(header.name.toLowerCase()) >= 0;
    if (isCspHeader) {
      let newValue = header.value;
      cspSources.forEach(source => {
        newValue = newValue.replace(source, source + ' ' + url);
      });
      header.value = newValue;
    }
  });
  return {
    responseHeaders: details.responseHeaders
  };
}, {
  urls: ['<all_urls>'],
  types: ['main_frame', "sub_frame"],
}, ["blocking", "responseHeaders"]);
</code>```

Body:
I'm working on an Edge extension, and I need to request JSON from an external website. The following example works fine on stackoverflow.com, but fails on steamcommunity.com/id/ where I need it.

Here are the files I have:

jQuery (from local file)

manifest.json:

{
  "author": "me",
  "name": "Get JSON",
  "description": "get json",
  "version": "0.1",
  "manifest_version": 2,
  "content_scripts": [
    {
      "matches": [
        "*://steamcommunity.com/id/*",
        "*://stackoverflow.com/*"
      ],
      "js": ["jquery.min.js", "myscript.js"]
    }
  ]
}

myscript.js:

var url = 'https://raw.githubusercontent.com/bahamas10/css-color-names/master/css-color-names.json';

$.getJSON(url, function(data) {
  console.log(data);
});

As I've said, this example works fine on Stackoverflow, but fails on Steam.

This is the error I receive on the Steam website:

CSP14312: Resource violated directive 'connect-src 'self' http://steamcommunity.com https://steamcommunity.com https://api.steampowered.com/ http://localhost:27060 http://store.steampowered.com/ https://store.steampowered.com/' in Content-Security-Policy: https://raw.githubusercontent.com/bahamas10/css-color-names/master/css-color-names.json. Resource will be blocked.

EDIT: I should also add, that this exact example works fine when using a Chrome extension in Google Chrome.

Any help is appreciated.

Body:
Microsoft Edge, differently from Chrome and Firefox, doesn't ignore the website CSP rules for extensions.

See https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/11320214/ for an open issue.

The only viable workaround I know, which I also tested myself, is to change the CSP response headers on the fly by using browser.webRequest.onHeadersReceived, which luckily is well supported in Edge.

NOTE: this code was adapted from this great article, which also explains the problem in more detail: https://transitory.technology/browser-extensions-and-csp-headers/

The code adds your extension to the allowed urls for each CSP header and directive, it should be executed in the background page, which should be set as persistent.

Make sure to add the webRequest and webRequestBlocking permissions to your manifest.json.

const cspHeaderNames = [
  'content-security-policy',
  'content-security-policy-report-only',
  'x-webkit-csp'
];

// @see https://developer.mozilla.org/en-US/docs/Web/Security/CSP/CSP_policy_directives
const cspSources = [
  'connect-src',
  'default-src',
  'font-src',
  'frame-src',
  'img-src',
  'media-src',
  'object-src',
  'script-src',
  'style-src',
  'child-src',
  'form-action',
];

const url = browser.extension.getURL("").slice(0, -1); // (remove trailing "/")

browser.webRequest.onHeadersReceived.addListener(details => {
  details.responseHeaders.forEach(header => {
    const isCspHeader = cspHeaderNames.indexOf(header.name.toLowerCase()) >= 0;
    if (isCspHeader) {
      let newValue = header.value;
      cspSources.forEach(source => {
        newValue = newValue.replace(source, source + ' ' + url);
      });
      header.value = newValue;
    }
  });
  return {
    responseHeaders: details.responseHeaders
  };
}, {
  urls: ['<all_urls>'],
  types: ['main_frame', "sub_frame"],
}, ["blocking", "responseHeaders"]);


问:
I want access span for hide & show purpose with class name & id name which will start with?
I want to access a span with a specific class and id (the id will start with specific pattern)

```<code><span id='asd111' class="demo"></span>
<span id='asd122' class="demo"></span>
<span id='asd133' class="demo"></span>
<span id='asd144' class="demo"></span>
</code>```

Now I want to hide/show above spans using single jQuery statement. How can do this? All span id start with common asd1 pattern.

Please give me idea as soon as possible.

*i have just given example in this code.. those spans are coming dynamically in my code in different nested divs, so i want hide those with those id pattern & class name???

答:
Here is an example of doing this with JQuery.

$('#test').on('click', function(){
  $('span[id^="asd1"].demo').hide();
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">Click Me</div>

<span id='asd111' class="demo">1</span>
<span id='asd122' class="demo">2</span>
<span id='asd133' class="demo">3</span>
<span id='asd144' class="demo">4</span>
<span id='asd133' class="test">5</span>
<span id='asd144' class="test">6</span></code>```

Body:
I want to access a span with a specific class and id (the id will start with specific pattern)

Now I want to hide/show above spans using single jQuery statement. How can do this? All span id start with common asd1 pattern.

Please give me idea as soon as possible.

*i have just given example in this code.. those spans are coming dynamically in my code in different nested divs, so i want hide those with those id pattern & class name???

Body:
Here is an example of doing this with JQuery.

$('#test').on('click', function(){
  $('span[id^="asd1"].demo').hide();
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">Click Me</div>

<span id='asd111' class="demo">1</span>
<span id='asd122' class="demo">2</span>
<span id='asd133' class="demo">3</span>
<span id='asd144' class="demo">4</span>
<span id='asd133' class="test">5</span>
<span id='asd144' class="test">6</span>


问:
Web scraping with R, solution with Jsonlite seems flaky
I maintain small scrips to extract financial data from websites. One of them retrieves the dutch natural gas grid balance. However, I keep getting problems with it as it works for a while, then get an error message and finally find a work around. Anyway, it seems that I am using a rather flaky method to do it. Could anyone guide me to a better direction (package) of getting this done?
Below I add the code (which again stopped working)

```<code>library(curl)
library(bitops)
url <- "https://www.gasunietransportservices.nl/en/shippers/balancing-regime/sbs-and-pos/graphactualjson/MWh"
h <- new_handle(copypostfields ="moo=moomooo")
handle_setheaders(h, "Content-Type" = "text/moo", "Cache-Control" = "no-cache", "User-Agent" = "A cow")
req <- curl_fetch_memory(url, handle=h)
x <- rawToChar(req$content)
library(jsonlite)
json_data <- fromJSON(x)

data <- json_data[,c(1,4)]
n=tail(data,1)
</code>```

Many thanks

答:
You can use rvest for this (but there could be better approaches too)

```<code>library(rvest)

json_data <- read_html('https://www.gasunietransportservices.nl/en/shippers/balancing-regime/sbs-and-pos/graphactualjson/MWh') %>%
             html_text() %>%
             jsonlite::fromJSON(.)

data <- json_data[,c(1,4)]
n=tail(data,1)
n
</code>```

Output:

```<code>> n
           sbsdatetime position
37 2017-11-16 12:00:00       -9
</code>```

Slightly elegant solution if the dataframe isn't required:

```<code>library(rvest)
library(dplyr)
read_html('https://www.gasunietransportservices.nl/en/shippers/balancing-regime/sbs-and-pos/graphactualjson/MWh') %>%
  html_text() %>%
  jsonlite::fromJSON(.)  %>%
  select(1:4) %>%
  tail(n=1)
</code>```

Body:
I maintain small scrips to extract financial data from websites. One of them retrieves the dutch natural gas grid balance. However, I keep getting problems with it as it works for a while, then get an error message and finally find a work around. Anyway, it seems that I am using a rather flaky method to do it. Could anyone guide me to a better direction (package) of getting this done?
Below I add the code (which again stopped working)

library(curl)
library(bitops)
url <- "https://www.gasunietransportservices.nl/en/shippers/balancing-regime/sbs-and-pos/graphactualjson/MWh"
h <- new_handle(copypostfields ="moo=moomooo")
handle_setheaders(h, "Content-Type" = "text/moo", "Cache-Control" = "no-cache", "User-Agent" = "A cow")
req <- curl_fetch_memory(url, handle=h)
x <- rawToChar(req$content)
library(jsonlite)
json_data <- fromJSON(x)

data <- json_data[,c(1,4)]
n=tail(data,1)

Many thanks

Body:
You can use rvest for this (but there could be better approaches too)

library(rvest)

json_data <- read_html('https://www.gasunietransportservices.nl/en/shippers/balancing-regime/sbs-and-pos/graphactualjson/MWh') %>%
             html_text() %>%
             jsonlite::fromJSON(.)

data <- json_data[,c(1,4)]
n=tail(data,1)
n

Output:

> n
           sbsdatetime position
37 2017-11-16 12:00:00       -9

Slightly elegant solution if the dataframe isn't required:

library(rvest)
library(dplyr)
read_html('https://www.gasunietransportservices.nl/en/shippers/balancing-regime/sbs-and-pos/graphactualjson/MWh') %>%
  html_text() %>%
  jsonlite::fromJSON(.)  %>%
  select(1:4) %>%
  tail(n=1)


答:
Update your example code. If you expect to receive JSON code of object that has more then one 'attribute' with same name 'email@email.com' the answer is: it's not possible!

Because in JSON:

```<code>{ "email@email.com": {"id":1}, "email@email.com": {"id": 2}, "email@email.com": {"id": 3}, "email@email.com": {"id": 4}, "email@email.com": {"id": 5}, "email@email.com": {"id": 6} }
</code>```

is equal to (using Chrome's JavaScript):

```<code>{"email@email.com":{"id":6}}
</code>```

Body:
I have a PHP array which outputs as follows:

Array ( [0] => email@email.com [1] => email@email.com [2] => email@email.com [3] => email@email.com [4] => email@email.com [5] => email@email.com )

This array houses a list of email addresses, which I need to output as a custom JSON string, which matches the following:

{ "email@email.com": {"id":1}, "email@email.com": {"id": 2}, "email@email.com": {"id": 3}, "email@email.com": {"id": 4}, "email@email.com": {"id": 5}, "email@email.com": {"id": 6} }

Is anyone able to point me in the right direction? I have tried using json_encode, without success.

Body:
Update your example code. If you expect to receive JSON code of object that has more then one 'attribute' with same name 'email@email.com' the answer is: it's not possible!

Because in JSON:

{ "email@email.com": {"id":1}, "email@email.com": {"id": 2}, "email@email.com": {"id": 3}, "email@email.com": {"id": 4}, "email@email.com": {"id": 5}, "email@email.com": {"id": 6} }

is equal to (using Chrome's JavaScript):

{"email@email.com":{"id":6}}