text:
Q: How to use package restore with packages containing only tools? I use Nuget with enabled Package Restore feature. Thus /packages folder is in ignore list (.hgignore since I use mercurial). That works fine on my CI server (Teamcity).
To be able to run xUnit tests I added xunit.runners package. However this package contains only tools folder and after it has been added no any changes were detected by mercurial (nothing new to commit). Seems like only /packages folder got updated.
How to enable package restore for such packages (containing only tools)?
For now the only solution I found is using regexp syntax in .hgignore:
syntax: regexp
packages/(?!xunit.runner).*

But in this case it just saves all package content in source control.

A: You can try manually add package xunit.runners to your packages.config. This will resolve runner when you will first build your tests or solution.


text:
Q: Array pushes elements already in Array despite !arry.includes I am trying to build an app that requires a directory. Every time I update the component, it pushes the data into the array again creating multiple copies. I tried solving that by adding an !arry.includes, but that does not stop it for adding another occurrence of the data.
 const Directory = () => {
  const [searchResults, setSearchResults] = useState([]);
  const [loading, setLoading] = useState(false);
  const { currentUser } = useContext(AuthContext);

  useEffect(() => {
    setLoading(true);
    const data = async () => {
      const q = query(collection(db, "users"), where("type", "==", "doctor"));
      const querySnapshot = await getDocs(q);
      querySnapshot.forEach((doc) => {
        const data = doc.data();
        if (!searchResults.includes(data)) {
          searchResults.push(data);
        }
      });
      setLoading(false);
    };
    data();
  },[]);
  console.log(searchResults);

A: It appears that you are trying to compare objects here which doesn't work with the array.includes() method.
In javascript
const user1 = {name : "nerd", org: "dev"};
const user2 = {name : "nerd", org: "dev"};
user1 == user2; // is false

You would need to search for something more specific or try Comparing Objects. Either way what your trying to do is tricky and you may need to explore lodash or something to solve it

A: I found an easier way!
 useEffect(() => {
    setLoading(true);
    const data = async () => {
      const q = query(collection(db, "users"), where("type", "==", "doctor"));
      const querySnapshot = await getDocs(q);
      querySnapshot.forEach((doc) => {
        const data = doc.data();
        const notInArray = searchResults.some(u => u.uid === data.uid);
        console.log(notInArray);
        if (notInArray === false) {
          searchResults.push(data)
        }
      });
      setLoading(false);
    };
    return () => {
      data();
    };
  }, []);

redpajama_set_name: RedPajamaStackExchange


text:
Q: XPath/Schematron equivalent of "xsl:value-of" I built a schematron pattern and found an unexpected error.
I tried to compair a string (e.g. "Robinson 1983") to the output of an xsl function.
My function works like this
<xsl:value-of select="surname"/><xsl:text> </xsl:text><xsl:value-of select="year"/>

So, in schematron
test="'Robinson 1983' = ...function-call..."

gave back "false" because the output of the function is a sequence consisting of three text elements.
I was able to fix that using xslt
<xsl:variable name="output"><xsl:value-of select="...function-call..."/></xsl:variable>

and
test="'Robinson 1983' = $output"

gave back "true" as expected.
But I'm wondering: How is this the be solved in "pure" Schematron/XPath?
Is there any equivalent to xsl:value-of? I.e. turning a sequence into a string, getting rid of other content.
I think this is one of the most import things you want to do in XPath, but I didn't find a solution.

A: I tried to recreate your example, but it worked perfectly for me just as you had it coded first.
I suspect that the function using your first select statement:
<xsl:value-of select="surname"/><xsl:text> </xsl:text><xsl:value-of select="year"/>

is returning those combined values as a single string, but your data may actually contain multiple sets of (surname year) strings.
Is is possible that your data contains multiple sets of (surname year) strings?  Maybe your function is inadvertently returning more that one set at a time.


text:
Q: Identify a short horror story about a cursed man with imps crawling under his skin I have a recollection of reading this particular horror story as a young teen (circa 1993?), but cannot now find it. It was written in a style reminiscent of Edgar Allan Poe's. (I have browsed the latter's tales to no avail, however.) Here follows the story as I remember it. Thanks in advance to anyone who can point me in the right direction.
(The setting might be the 19th century.) A man travels (possibly to India or South America) to meet a friend (probably an archaeologist or explorer) who wrote to ask him to come since he has fallen terribly ill. There, the main character finds his friend uncooperative and secretive. The sick man's health fluctuates, and his bouts of illness correlate with large lumps appearing on his skin.
One night, the puzzled protagonist decides to spy on his friend, and sees him cutting open one of his cysts with a knife. An imp-like creature emerges from the wound and addresses the feverish man. I do not remember its exact words; they seemed to imply that the infected fellow had a duty to perform should he wish to be rid of this curse. It left me with the general impression that he had to return an artifact or restore something to its earlier condition, but that this task was impossible, dooming him to a (hopefully short) life of torment borne of his own flesh.
I believe the story ends at this point, or maybe shortly afterwards as the onlooking character reels in horror and flees.

A: This is Lukundoo, by Edward Lucas White
An explorer is cursed with small people that grow out of boils on his skin

Then we three sat about Stone and watched that hideous, gibbering
prodigy grow up out of Stone's flesh, till two horrid, spindling
little black arms disengaged themselves. The infinitesimal nails were
perfect to the barely perceptible moon at the quick, the pink spot on
the palm was horridly natural. These arms gesticulated and the right
plucked toward Stone's blond beard.

He was cursed for some unknown reason:

"Has she forgiven me?" Stone asked in a muffled strangle. "Not while
the moss hangs from the cypresses," the head squeaked. "Not while the
stars shine on Lake Pontchartrain will she forgive."

In many anthologies.


text:
Q: How can I iterate through nested arrays? I have created an array as follows
while (defined ($line = `<STDIN>`))

        {
        chomp ($line);
        push @stack,($line);
        }

each line has two numbers.
15 6
2  8

how do iterate over each item in each line?
i.e. I want to print
15
6
2
8

I understand it's something like
foreach (@{stack}) (@stack){

    print "?????
}

This is where I am stuck.

A: #!/usr/bin/perl

use strict;
use warnings;

while ( my $data = <DATA> ) {
    my @values = split ' ', $data;
    print $_, "\n" for @values;
}

__DATA__
15 6
2  8

Output:

C:\Temp> h
15
6
2
8

Alternatively, if you want to store each line in @stack and print out later:
my @stack = map { [ split ] } grep { chomp; length } <DATA>;

The line above slurps everything coming from the DATA filehandle into a list of lines (because <DATA> happens in list context). The grep chomps each line and filters by length after chomping (to avoid getting any trailing empty lines in the data file -- you can avoid it if there are none). The map then splits each line along spaces, and then creates an anonymous array reference for each line. Finally, such array references are stored in each element of @stack. You might want to use Data::Dumper to look at @stack to understand what's going on.
print join("\n", @$_), "\n" for @stack;

Now, we look over each entry in stack, dereferencing each array in turn, then joining the elements of each array with newlines to print one element per line.
Output:

C:\Temp> h
15
6
2
8

The long way of writing essentially the same thing (with less memory consumption) would be:
my @stack;

while ( my $line = <DATA> ) {
    last unless $line =~ /\S/;
    my @values = split ' ', $line;
    push @stack, \@values;
}

for my $ref ( @stack ) {
    print join("\n", @$ref), "\n";
}

Finally, if you wanted do something other than printing all values, say, sum all the numbers, you should store one value per element of @stack:
use List::Util qw( sum );

my @stack;

while ( my $line = <DATA> ) {
    last unless $line =~ /\S/;
    my @values = split ' ', $line;
    push @stack, @values;
}

printf "The sum is %d\n", sum @stack;

A: See the perldsc documentation. That's the Perl Data Structures Cookbook, which has examples for dealing with arrays of arrays. From what you're doing though, it doesn't look like you need an array of arrays.
For your problem of taking two numbers per line and outputting one number per line, just turn the whitespace into newlines:
 while( <> ) {
     s/\s+/\n/; # turn all whitespace runs into newlines
     print;     # it's ready to print
     }

With Perl 5.10, you can use the new \h character class that matches only horizontal whitespace:
 while( <> ) {
     s/\h+/\n/; # turn all horizontal whitespace runs into newlines
     print;     # it's ready to print
     }

As a Perl one-liner, that's just:
 % perl -pe 's/\h+/\n/' file.txt

A: #!/usr/bin/perl

while ($line = <STDIN>) {
    chomp ($line);
    push @stack, $line;
}

# prints each line
foreach $line (@stack) {
    print "$line\n";
}

# splits each line into items using ' ' as separator
# and prints the items
foreach $line (@stack) {
    @items = split / /, $line;

    foreach $item (@items) {
        print $item . "\n";
    }
}

A: I use 'for' for "C" style loops, and 'foreach' for iterating over lists.

A: #!/usr/bin/perl

use strict;
use warnings;
open IN, "< read.txt" or
    die "Can't read in 'read.txt'!";

my $content = join '', <IN>;

while ($content =~ m`(\d+)`g) {
    print "$1\n";
}


text:
Q: Footer layout slides up with softkeyboard I have a footer layout in my base activity and i extend other activities with base activity. the problem is when soft keyboard open footer slides up with it. i tried
android:windowSoftInputMode="adjustPan"

but it did not help. Any Solution.?

A: set android:windowSoftInputMode="stateHidden|adjustPan" in your manifest.

A: if you are using a scrollview try adding  to the xml
android:isScrollContainer="false"

And try;
android:windowSoftInputMode="adjustNothing"


text:
Q: serialize dictionary with dynamic key I would like to create a django rest framework serializer, in order to serialize this dict:
"series": {
        "real": "Real",
        "forecast": "Forecast",
        "upper_ci": "Upper CI",
        "lower_ci": "Lower CI"
}

The problems is that real, forecast, upper_ci, lower_ci are all dynamic keys, and there might be other different keys.


text:
Q: jQuery ajax loading html / php content from external files I have a mixed html / php in external files and loading that content dynamically:
example file: my_data.php

        <?php esc_html_e('Player height:', AWP_TEXTDOMAIN); ?>

        <input type="number" class="playerHeight">

I am retrieving this content in file with ajax:
php function:
function preview_preset_settings() {

        $result = dirname(__FILE__) . '/includes/preset_config/ . 'my_data.php';

        $content = file_get_contents($result);

        header( "Content-Type: text/html" );

        echo $content;

        exit;

    }

jquery:
$.ajax({
        type: 'POST',
        url: ajax_url,
        data: ajax_data,
    }).done(function(result) {

        activePreset.empty().html(result);

 ....

The problem is when this comes back with ajax and I add this in my div container (activePreset.empty().html(result);), php tags are commented out.
So there is no result of
 <?php esc_html_e('Player height:', AWP_TEXTDOMAIN); ?>

As you can see I need to echo some php in there as well.
If this is not possible to achieve in such way I will have to take a different approach.


text:
Q: How to disable dates in Dynarch calendar I'm using Dynarch calendar in one of my Magento module and i want to disable some specific dates in an array like below.
var array = ["2014-01-14","2014-01-15","2011-01-16"]

I'm currently using this code and this disables all the days except sundays. I tried in many ways with JQuery methods and could not be success.
disableFunc : function(date)
    {
        var y = calendar.date.getFullYear();
        var m = calendar.date.getMonth();
        var d = calendar.date.getDate();

            var day_off_array = dayoff.split(",") ;
            //document.write(day_off_array);
            currentTime = new Date();
            var d1=currentTime.getDate();
            var m1=currentTime.getMonth();
            var y1=currentTime.getFullYear();

        if (date.getDay() != 0) {
         return true; // true says "disable"
         } else {
         return false; // leave other dates enabled
        }

        if(y < y1)
        {
            return true;
        }
        else if(m1 > m && y==y1)
        {
            return true;
        }

    }

Is there a way to achieve this and any helps would be appreciated. Thanks.

A: See examples at http://www.dynarch.com/jscal/#sec8
The above calendar allows selection between 8 April and 25 December 2009.
Here's the code that we used:
Calendar.setup({
  cont: "sample1",
  min: 20090408,
  max: 20091225
});


text:
Q: Nokia imaging SDK editingsession is not found -windows phone Im new to nokia image SDK, I ahve installed the latest version(1.0.272.0 ) for windows phone .Whenever I try to use EditingSession, I get error as

"EditingSession is not found.Are you missing an assembly directive?"

I have included the following namespace
using Nokia.Graphics.Imaging;
using Nokia.InteropServices;

Please help..

A: Image SDK has changed significantly in the RTM version (compared to Beta versions) and in RTM, editing session is gone. With a lot of samples around are still referring to beta code, you can take a look at differences between Beta and RTM versions here (http://developer.nokia.com/Resources/Library/Lumia/#!nokia-imaging-sdk/how-to-upgrade.html) or consult RTM core concepts at Nokia's Imaging SDK site (http://developer.nokia.com/Resources/Library/Lumia/#!nokia-imaging-sdk/core-concepts.html).


text:
Q: Angularjs bad argument ng:areq error I'm getting this error when running my application. This error comes in only one controller. I have done other controllers in the same way but in this particular controller I get this following error.

Argument 'questionAddCtrl' is not a function, got undefined

Controller:
;
(function () {
    'use strict';

    angular.module('app').controller('questionAddCtrl', ['$scope', '$http', function ($scope, $http) {

            $scope.data = {
                question: '',
                ans1: '',
                ans2: '',
                ans3: '',
                ans4: '',
                ans5: '',
                correct_ans: ''
            };

            $scope.submit = function (selectData) {
                console.log("submit pressed");

                var questionAddRequest = {
                    "question": selectData.question,
                    "answerOne": selectData.ans1,
                    "answerTwo": selectData.ans2,
                    "answerThree": selectData.ans3,
                    "answerFour": selectData.ans4,
                    "answerFive": selectData.ans5,
                    "correctAnswer": selectData.correct_ans

                };

                var url = 'http://localhost/AwtCW2012002/api/restApiController/question.json';

                $scope.jsonData = JSON.stringify(questionAddRequest);

                console.log(questionAddRequest);
                console.log();

                $http({
                    method: 'POST',
                    url: url,
                    data: questionAddRequest
                }).then(function (response) {
                    console.log(response);
                    $scope.data = {
                        question: '',
                        ans1: '',
                        ans2: '',
                        ans3: '',
                        ans4: '',
                        ans5: '',
                        correct_ans: ''
                    };
                });
            }
        }]);
})();

Views:

    <form class="form-horizontal" role="form" name='quizAdd' ng-submit="submit(data)">

            Question:

                <input type="text" class="form-control" id="question" ng-model="data.question" placeholder="Enter Question">

            Answer 1:

                <input type="text" class="form-control" name="answer1" ng-model="data.ans1" id="answer1" placeholder="Enter Answer 1">

            Answer 2:

                <input type="text" class="form-control" name="answer2" ng-model="data.ans2" id="answer2" placeholder="Enter Answer 2">

            Answer 3:

                <input type="text" class="form-control" name="answer3" ng-model="data.ans3" id="answer4" placeholder="Enter Answer 3">

            Answer 4:

                <input type="text" class="form-control" name="answer4" id="answer4" ng-model="data.ans4" placeholder="Enter Answer 4">

            Answer 5:

                <input type="text" class="form-control" name="answer5" id="answer5" ng-model="data.ans5" placeholder="Enter Answer 5">

            Select Correct Answer:

                <select class="form-control" ng-model="data.correct_ans" id="sel1">
                    <option>{{data.ans1}}</option>
                    <option>{{data.ans2}}</option>
                    <option>{{data.ans3}}</option>
                    <option>{{data.ans4}}</option>
                    <option>{{data.ans5}}</option>
                </select>

                <button type="submit" class="btn btn-default">Submit</button>

    </form>

A: Try to set the array of dependencies that your module requires, like so:
angular.module('app', []);

instead of
angular.module('app');


text:
Q: How to write a DLL file in C? How do I write a DLL file in C?
I was looking online, but I always get tutorials for C++, not C. I want to write my first DLL file in C. How can I do that? What would a short example be?

A: Let's get you started on your first DLL:

*

*Start Visual Studio .NET.

*Go to menu File -> New -> Project.

*Select Visual C++ Project, and from the Templates, select Win32 Project.

*Give the name to your project. This will be the name of your final DLL file.

*Press OK.

*Select DLL from Application Type (In the Application Settings tab).

*Check Empty Project and press Finish.

You need to attach an empty source file to the blank project:

*

*Start Solution Explorer (if it's not displayed).

*Right click to the Source Files, Add -> Add New Item and then select C++ File and give the name to it.

*Press Open.

In the opened window, enter the following code:
#include <stdio.h>
extern "C"
{
    __declspec(dllexport) void DisplayHelloFromMyDLL()
    {
        printf ("Hello DLL.\n");
    }
}

*

*__declspec(dllexport) is an obligatory prefix which makes DLL functions available from an external application.

*extern "C" (with braces, for scoping) shows that all code within brackets is available from "outside" the file. Although code will compile even without this statement, during runtime, you will get an error. (I leave this as an experiment for you).
Build this application and your DLL file is ready.
Refer to Walkthrough: Creating and Using a Dynamic Link Library for more information on how to do addition and stuff.


text:
Q: obtain and grab single value from getCookie() function I am trying to use the getCookie() function and grab the sessionID's value.
When I call the following function in my code:
let sessionCookie = await this.driver.manage().getCookie(['sessionid']);
console.log(sessionCookie)

I get this response:
 {
  domain: 'xxx.xxxxxx.xxx',
  expiry: 1629398293,
  httpOnly: true,
  name: 'sessionid',
  path: '/',
  secure: true,
  value: 'bte8erv3t3piimsu3cmoqv3wvp16i2jj'
}

How do I get the string of characters from value ?

A: Hi just add 'value' for console.log
let sessionCookie = await this.driver.manage().getCookie(['sessionid']);
console.log(sessionCookie.value)


text:
Q: Error in evaluating the test script when retrieving a string from the response in postman From the below response structure i want to retrieve the id field and save it in the environment variable in postman.
I tried all possible methods to do it but unable to do so.
{
    "childMaxAge": 13,
    "selectedForBooking": [
        {
            "id": "0661be61-d0ae-411009-a96d-64229a",
            "firstName": "Test",
            "gender": {
                "code": "MALE",
                "name": "Male"
            }
   ]
}

i have tried the below and it also doesn't work.
tests["Status code is 201"] = responseCode.code === 201;
var data = JSON.parse(responseBody);
console.log(data);
var custid=JSON.parse(data.selectedForBooking[0].id);
tests ["selectedForBooking"]= postman.setEnvironmentVariable("CustId1", custid);

but it gives error :
There was an error in evaluating the test script:  JSONError: Unexpected token '6' at 1:2 0661be61-d0ae-411009-a96d-64229a ^

A: There is no need to parse response data second time.
Also there is no need to use tests[] if you're not going to assert anything.
tests["Status code is 201"] = responseCode.code === 201;
var data = JSON.parse(responseBody);
console.log(data);
var custid=data.selectedForBooking[0].id;
postman.setEnvironmentVariable("CustId1", custid);

var custid=JSON.parse(data.selectedForBooking[0].id); was trying to make a json object out of 0661be61-d0ae-411009-a96d-64229a which is not a json formated string.

A: Have a look to POSTMAN : parsing a JSON response, how deep can I go into the response?
I used to have a similar problem, I was trying to reach
body.entries[0].attributes.device.type

I managed getting the value by doing
body.entries[0].attributes['device.type']

make sure you use single quotes (I don't know why ...)
Hope this helps
Alexandre

A: Your JSON data itself is wrong, that is why it was showing that error.
It Must be :
{
    "childMaxAge": 13,
    "selectedForBooking": [
        {
            "id": "0661be61-d0ae-411009-a96d-64229a",
            "firstName": "Test",
            "gender": {
                "code": "MALE",
                "name": "Male"
            }
        }
   ]
}

Now u can try this
var custid=data.selectedForBooking[0].id;
It will return the required value


text:
Q: Bootstrap v5.x tooltip remains on page after navigating away from its page I am using Bootstrap v5.x for my application.
In the JavaScript, I have, according to the documentation, enabled tooltips everywhere:
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
    return new bootstrap.Tooltip(tooltipTriggerEl)
})

I am also generating dynamic content, this is a Blazor application, so I have added this to my JavaScript as well:
$('body').tooltip({
    selector: '[data-toggle="tooltip"]'
});

This all works very well for what I am doing, except for one edge case; and that is when I click an element with a tooltip that navigates from the current page. When I do this, the tooltip remains on screen until I perform a Ctrl + F5.

 myMethod(id)">

@code {
    myMethod(int id){
        // navigate to next page ...
    }
}

If I do this multiple times, I am left with multiple tooltips all over my page.
How can I hide the tooltip when I navigate away?


text:
Q: Show that 7 is a quadratic residue for any prime p of the form 28k + 1 and 28k + 3. Interesting number theory question, which I feel should be reasonably straight forward, but I can't seem to crack it.

Show that 7 is a quadratic residue for any prime p of the form 28k + 1 and 28k + 3.

Now, I know that a quadratic residue $a$ (mod m) means that there exists $x$ such that $x^2\equiv a$(modm).
So if 7 is a quadratic residue mod 28k+1 or 28k+3 then $x^2\equiv 7$ (mod 28k+1 or 28k +3).  But I am unsure of how to tackle this problem.
Perhaps, I could go on to say that for the first case, $x^2\equiv 6$ (mod 28k) $\equiv$ 3 (mod 14k)??
Or perhaps I am going about this wrong.
I also know the laws of quadratic reciprocity, so I need to show $(\frac{7}{28k+1})$ =1 and likewise for 28k +3
Help would be greatly appreciated.  Thank you

A: Hint: If $p=28k+1$ then $\frac{7-1}{2}\cdot \frac{p-1}{2}$ is even. If $p=28k+3$ then $\frac{7-1}{2}\cdot\frac{p-1}{2}$ is odd.

A: Using Quadratic Reciprocity Theorem,
$$\left(\frac p7\right)\left(\frac 7p\right)=(-1)^{\frac{3(p-1)}2}$$
Now, if $p\equiv1\pmod4,\left(\frac p7\right)\left(\frac 7p\right)=1\iff \left(\frac 7p\right)=\left(\frac p7\right)$
Now, $(\pm1)^2\equiv1\pmod 7,(\pm2)^2\equiv4,(\pm3)^2\equiv2\implies p$ needs to be $1,2,4\pmod 7$
$p\equiv1\pmod4$ and $p\equiv1\pmod7\implies p\equiv1\pmod {4\cdot7}$
Using CRT, we can show
$p\equiv1\pmod4$ and $p\equiv2\pmod7\implies p\equiv9\pmod {4\cdot7}$
$p\equiv1\pmod4$ and $p\equiv4\pmod7\implies p\equiv25\pmod {4\cdot7}\equiv-3$
Now, if $p\equiv-1\pmod4,\left(\frac p7\right)\left(\frac 7p\right)=-1\iff \left(\frac 7p\right)=-\left(\frac p7\right)$
and $p$ needs to be $3,5,6\pmod 7$
$p\equiv-1\pmod4\equiv3$ and $p\equiv3\pmod7\implies p\equiv3\pmod {4\cdot7}$
$p\equiv-1\pmod4$ and $p\equiv6\pmod7\equiv-1\implies p\equiv-1\pmod {4\cdot7}$
Using CRT, we can show
$p\equiv-1\pmod4$ and $p\equiv5\pmod7\implies p\equiv19\pmod {4\cdot7}\equiv-9$
So, $7$ is a quadratic residue for any prime $p\equiv\pm1,\pm3,\pm9\pmod{28}$


text:
Q: Bigquery LoadJobConfig Delete Source Files After Transfer When creating a Bigquery Data Transfer Service Job Manually through the UI, I can select an option to delete source files after transfer. When I try to use the CLI or the Python Client to create on-demand Data Transfer Service Jobs, I do not see an option to delete the source files after transfer. Do you know if there is another way to do so? Right now, my Source URI is gs://<bucket_path>/*, so it's not trivial to delete the files myself.

A: For me works this snippet (replace YOUR-... with your data):
from google.cloud import bigquery_datatransfer
import os

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "YOUR-CRED-FILE-PATH"

transfer_client = bigquery_datatransfer.DataTransferServiceClient()

destination_project_id = "YOUR-PROJECT-ID"
destination_dataset_id = "YOUR-DATASET-ID"

transfer_config = bigquery_datatransfer.TransferConfig(
    destination_dataset_id=destination_dataset_id,
    display_name="YOUR-TRANSFER-NAME",
    data_source_id="google_cloud_storage",
    params={
        "data_path_template":"gs://PATH-TO-YOUR-DATA/*.csv",
        "destination_table_name_template":"YOUR-TABLE-NAME",
        "file_format":"CSV",
        "skip_leading_rows":"1",
        "delete_source_files": True
    },
)

transfer_config = transfer_client.create_transfer_config(
    parent=transfer_client.common_project_path(destination_project_id),
    transfer_config=transfer_config,
)
print(f"Created transfer config: {transfer_config.name}")

In this example, table YOUR-TABLE-NAME must already exist in BigQuery, otherwise the transfer will crash with error "Not found: Table YOUR-TABLE-NAME".
I used this packages:
google-cloud-bigquery-datatransfer>=3.4.1
google-cloud-bigquery>=2.31.0

Pay attention to the attribute delete_source_files in params. From docs:

*

*Optional param delete_source_files will delete the source files after each successful transfer. (Delete jobs do not retry if the first effort to delete the source files fails.) The default value for the delete_source_files is false.


text:
Q: Get Values from one google sheet enter it onto another sheet with a 4 loop I have to spreadsheets.  I want the program to look at Row A on spreadsheet Ind and see if it is a 1 or 0.  if it is a one on the active sheet "return" I want it to grab the date from Row D in spreadsheet "Ind" and post it onto Spreadhseet "return".  I can't figure this out and I have it working on VBA in excel.
Any help would be greatly appreciated.
function myFunction() {

 X = 5;
 Y = 2;
 Z = 1;
 Count = 4560;
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var source_sheet = ss.getSheetByName("Ind");
 var target_sheet = ss.getSheetByName("Returns");

 while (Z < Count){

   if (source_sheet.getRange("A" & X) = 1) {
      var buydate = source_sheeet.getRange("D" & X).getValues()
      target_sheet.getRange("A" & Y) = buydate
      target_sheet.getRange("B" & Y) = "Buy"
      Y = Y + 1
   } else if (source_sheeet.Range("C" & X) = 2) {
      var selldate = source_sheeet.Range("D" & X).getvalues()
      target_sheet.getRange("A" & Y) = selldate
       target_sheet.getRange("B" & Y) = "Sell"
       Y = Y + 1
   }

    X = X + 1
   Z = Z + 1
  }}

A: This line:
if (source_sheet.getRange("A" & X) = 1) {

Is using an ampersand, and it should be a plus sign.  To concatenate strings in JavaScript, use a plus sign.
Also, source_sheet.getRange() will return a range, not a value, so it's never going to equal 1. You would need to use something like the following:
if (source_sheet.getRange("A" + X.toString()).getValue() === 1) {

And use triple equal signs for an equality check.  JavaScript is constantly attempting to coerce variables into the type that seems correct.  So, it might convert the number in the variable "X" to a string, but you can also use the toString() method.
getValues() returns a two-dimensional array.  Each inner array represent a row.  Each element in the inner array represents a cell in a row.
If you only want to get one value, use getValue() (no "s" on the end) instead of getValues().
var buydate = source_sheet.getRange("D" + X.toString()).getValue();

You are trying to set the value by using an equal sign.  That won't work.  You need to use the setValue() or setValues() method.
target_sheet.getRange("A" + Y.toString()).setValue(buydate);

By not using the var key word in your assignments, the variables automatically become "global" variables.
X = 5;
Y = 2;
Z = 1;

There's no need to make them global variables in this case, I don't think.
var X = 5,
    Y = 2,
    Z = 1;

You can declare multiple variables all at the same time.


text:
Q: dynamically drawing polylines on googlemaps using php/mysql I am new to the googlemaps API. I have written a small app for my mobile phone that periodically updates its location to an SQL databse.
I would like to display this information on a googlemap in my browser. Ideally i'd like to then poll the database periodically and if any new co-ords have arrived, add them to the line.
Best way of describing it is this.
In a quest to get to there, i've started on the documents on google and been modifying them to try and acheive what I want. It doesn't work - and i don't know enough to know why. I would love some advice as to why, and any pointers towards my ultimate goal would be very much welcomed.

       Google Maps AJAX + MySQL/PHP Example

   <script type="text/javascript">
  //<![CDATA[

function load() {
  if (GBrowserIsCompatible()) {
    var map = new GMap2(document.getElementById("map"));
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(47.614495, -122.341861), 13);

    GDownloadUrl("phpsqlajax_genxml.php", function(data) {
      var xml = GXml.parse(data);
      var line = [];
      var markers = xml.documentElement.getElementsByTagName("points");
        for (var i = 0; i < points.length; i++) {
            var point = points.item(i);
            var lat  = point.getAttribute("lat");
            var lng  = point.getAttribute("lng");

            var latlng = new GLatLng(lat, lng);

       line.push(latlng);
       if (point.firstChild) {
         var station = point.firstChild.nodeValue;
         var marker = createMarker(latlng, station);
         map.addOverlay(marker);
       }
     }

     var polyline = new GPolyline(line, "#ff0000", 3, 1);
     map.addOverlay(polyline);
});
}
//]]>

My php file is generating the following XML;
<?xml version="1.0" encoding="UTF-8" ?>
<points>
<point lng="-122.340141" lat="47.608940"/>
<point lng="-122.344391" lat="47.613590"/>
<point lng="-122.356445" lat="47.624561"/>
<point lng="-122.337654" lat="47.606365"/>
<point lng="-122.345673" lat="47.612823"/>
<point lng="-122.340363" lat="47.605961"/>
<point lng="-122.345467" lat="47.613976"/>
<point lng="-122.326584" lat="47.617214"/>
<point lng="-122.342834" lat="47.610126"/>
</points>

I have successfully worked through this; http://code.google.com/apis/maps/articles/phpsqlajax.html before attempting to customise the code.
Any pointers? Where am I go wrong?

A: You seem to be on the right track.
Your php script should accept a timestamp parameter, and should check if new points have been inserted in the database after that timestamp. If yes, it should return a response with the latest entry (or a list of entries after that timestamp, if you want to show a live trail as the vehicle moves).
On the client-side, you may want to initiate an AJAX request to the server-side script, either using normal or long polling, with the timestamp parameter of the last update.
When your AJAX request receives new information from the server, you would simply move your markers on the map. Then initiate a new AJAX request with the updated timestamp paramater.
Pseudocode-ish example using jQuery:
var lastUpdate = '2000/01/01 00:00:00';

function autoUpdate () {
    $.ajax({
       type: "GET",
       url: "phpsqlajax_genxml.php?last_update=" + lastUpdate,
       dataType: 'xml',
       success: function(xmlData) {

          // 1. Check if the xmlData is empty. If not we received
          //    some fresh data.
          // 2. Update lastUpdate from the xmlData with the timestamp from
          //    the server. Don't use JavaScript to update the timestamp,
          //    because the time on the client and on the server will
          //    never be exactly in sync.
          // 3. Move the markers on Google Map.

          // Relaunch the autoUpdate() function in 5 seconds.
          setTimeout(autoUpdate, 5000);
       }
    });
}


text:
Q: Changing gridplot using RadioButtonGroup, Python Bokeh Dears,
I have got three gridplot and was trying to replace the gridplots base on Radio Button selection. for example, if I select 611 then grid1 should be visible and when I select 612 (grid2) should be visible. I have been searching but couldn't get to a solution.  I have tried multiple things but nothing works. please help me guide to how to accomplish that.
kindly find below my code.
grid1 = gridplot([[V1_Traffic, D1_Traffic]])
grid2 = gridplot([[V2_Traffic, D2_Traffic]])
grid3 = gridplot([[V3_Traffic, D3_Traffic]])

def update_plot(attrname, old, new):

    if button_group.labels[0] == '611':
        curdoc().clear()
        curdoc().add_root(lay_out)
        # curdoc().add_root(grid)
        #lay_out = layout([[button_group]])
        show(grid1)

    if button_group.labels[1] == '612':
        curdoc().clear()
        curdoc().add_root(lay_out)
        # curdoc().add_root(grid2)
        #lay_out = layout([[button_group]])
        show(grid3)

    if button_group.labels[2] == '613':
        curdoc().clear()
        curdoc().add_root(lay_out)
        # curdoc().add_root(grid3)
        #lay_out = layout([[button_group]])
        show(grid3)

button_group = RadioButtonGroup(labels=["611", "612", "613"], active=0)
button_group.on_change("active", update_plot)

# create layout and add to curdoc
lay_out = layout([[button_group]])
curdoc().add_root(grid)
curdoc().add_root(lay_out)

Thanks for your time. Best Regards

A: dears,
I have got the solution and got it to work. kindly find below my code.
def update_plot(attrname, old, new):

    if options[button_group.active] == '611':
        curdoc().clear()
        curdoc().add_root(lay_out)
        curdoc().add_root(grid)

    if options[button_group.active] == '612':
        curdoc().clear()
        curdoc().add_root(lay_out)
        curdoc().add_root(p2)

    if options[button_group.active] == '613':
        curdoc().clear()
        curdoc().add_root(lay_out)
        curdoc().add_root(p3)

options = ["611", "612", "613"]
button_group = RadioButtonGroup(labels=options, active=0)
button_group.on_change("active", update_plot)

# create layout and add to curdoc
lay_out = layout([[button_group]])
curdoc().add_root(grid)
curdoc().add_root(lay_out)

Radio buttons are indexed button_group.labels[0] was not working, therefore, modifying it by doing an extra step
options = ["611", "612", "613"]
button_group = RadioButtonGroup(labels=options, active=0)

and by calling it by
if options[button_group.active] == '612'

curdoc().clear() to clear everything is there on the page and replace it with new grid data.
curdoc().add_root(lay_out) to display radio buttons
curdoc().add_root(p3) to display the new grid
I am new to programming. I am not sure if it is a good solution or a bad solution but at the moment it works for me:).
thanks again for your time.
Best Regards


text:
Q: Unable to change eclipse line length or comment line length I've tried changing all of the line wrapping parameters, both increasing and decreasing the maximum line length for source and comments, as well as disabling comment formatting. However, I'm unable to affect the code formatter's line-splitting behavior. No matter what changes I make to the format, line splitting occurs at 120 characters for both comments and source code. I've also tried upgrading eclipse from 3.6 to 3.7.
Any ideas why this is happening?

A: *

*Right-click on your project and go to Properties

*Check if Java Code Style > Formatter > Enable project specific settings is checked

*If so, check the Active profile
My guess is that there was a different Active profile selected than the one you were editing.  Deleting the project and recreating it caused the project to return to the default code style profile, where Enable project specific settings is unchecked.

A: Did you change the lines width from :
Preferences > Java > Code Style > Formatter >> then editing the maximum line width ?


text:
Q: Problem Setting Item Level Permissions Dynamically I am working with SharePoint 2010 feature receivers. On feature activation I am creating multiple web part pages in library "Site Pages". I want to set individual permissions for each page, but I want it to be done as the page is created rather than going to SP and managing the permissions through UI. Could you please help me on setting up the permissions dynamically.
Here my sample code
 private void SetPermissions(SPWeb web, string configurationFileName, string rootTag, string pageName)
{
  try
  {

    SPList list = web.Lists[pagesLibrary];// "Site Pages"
    SPQuery query = new SPQuery();
    var pages = SPHelper.GetConfigurationElements(configurationFileName, rootTag);
    foreach (var pagedef in pages)
    {

      //Get the SPListItemId by querying with item title.
      int pageID = SPHelper.GetListItemIdByTitle(list, pageTitle);
      // Check if page exists in the library.
      if (pageID == 0)
        continue;

      // Get page item by page ID
      query.RowLimit = 1U;
      query.Query = string.Format("<Where><Eq><FieldRef Name='ID' /><Value  Type='Counter'>{0}</Value></Eq></Where>", pageID);
      SPListItemCollection items = list.GetItems(query);
      if (items == null || items.Count < 1)
        continue;
      SPListItem page = items[0];
      if (page == null)
        continue;

      // Check if page has unique permissions. If not then break the inheritance.
      if (!page.HasUniqueRoleAssignments)
        page.BreakRoleInheritance(false,true);

      // Currently assigned roles.
      SPRoleAssignmentCollection currentRoles = page.RoleAssignments;
      // Remove current role assignments of the page.
      for (int i = currentRoles.Count - 1; i >= 0; i--)
      {
        SPRoleAssignment roleAssign = currentRoles[i];
        currentRoles.Remove(i);
      }

      // Read groups and roles from configuration file for each page/report.
      var groups = pagedef.Elements(Groups).Elements();
      foreach (var group in groups)
      {
        string groupName = group.GetAttribute(Name);
        SPRoleType role = (SPRoleType)Enum.Parse(typeof(SPRoleType),group.GetAttribute(Role));
        SPRoleDefinition roleDef = web.RoleDefinitions.GetByType(role);
        // Check if group exists in the site.
        SPGroupCollection siteGroups = web.SiteGroups;
        SPGroup oGroup = siteGroups.TryGet(groupName);
        if (oGroup == null)
          continue;
        SPRoleAssignment roleAssign = new SPRoleAssignment(oGroup);
        roleAssign.RoleDefinitionBindings.Add(roleDef);
        page.RoleAssignments.Add(roleAssign);
      }
    }
  }
  catch (Exception ex)
  {

    throw;
  }
}

This code use to work fine. But now It breaks the inheritance for just 1 item (page) in the list and upon checking the rest of the items (page.HasUniqueRoleAssignments) it always returns true which is not the case.
The above code is written at feature activation.
What I am doing wrong here.
Thanks.

A: Here are the steps:

*

*Break the inheritance
SPListItem targetItem = newWeb.Lists[uniqueListId].GetItemByUniqueId(uniqueItemId);
if (!targetItem.HasUniqueRoleAssignments)
{targetItem.BreakRoleInheritance(true);}

*Specify the target role definition (i.e., Full Controls,Contribute..)
SPRoleDefinition oSPRoleDefinition = newWeb.RoleDefinitions.GetById(selectedPermissionId);

*Create a SPRoleAssingment using SPUser or SPGroup as the parameter
SPRoleAssignment oSPRoleAssignment = new SPRoleAssignment(targetUser);

*Perform the binding
oSPRoleAssignment.RoleDefinitionBindings.Add(oSPRoleDefinition);

*Add the role assignment to the target item.
targetItem.RoleAssignments.Add(oSPRoleAssignment);

If you want to remove any default roleassingment to an item you can use this code:-
 SPRoleAssignmentCollection SPRoleAssColn = TargetItem.RoleAssignments;

 for (int i = SPRoleAssColn.Count - 1; i >= 0; i--)
 {
      SPRoleAssignment roleAssign = SPRoleAssColn[i];
      SPRoleAssColn.Remove(i);
 }

Hope this help.

A: It should work, You are elevating Web Object Right ?
 SPSecurity.RunWithElevatedPrivileges(delegate
        {
            using (SPSite site = properties.Feature.Parent as SPSite)
            {
                SPWeb rootweb = site.RootWeb;
                SetPermissions(rootweb)
            }
        });

I have written a blog post for permission assignment http://sharepoint497.blogspot.com/2012/09/sharepoint-2010-security-using-object.html do check it out, it might help.

A: Tthis is a feature to manage permissions list dynamically, by adding a rule based in column List or user profile service properties:
Permission Management, CodePlex


text:
Q: Safe rule applying remotely using NFT If you have experience, could you please advise how to safely apply firewall rules remotely on Linux using nft?
Particularly on Debian, we used for a long time iptables-apply(8) to safely apply remotely firewall rules to avoid lock out ourselves in case of some mistakes in rules.
As of now, latest Debian release comes with nftables instead of iptables, and official advice is to start using new tool nft.
I known that there is wrapper that converts old style iptables rules on the fly, but everywhere it advised to not mix old style with new one, so we finally decided to switch all rules to a new (sort of pf) style, but we are still humans and don't want to lock ourselves out of remote servers in case of mistake in rules.
So shortly, is there some procedure to do the same as iptables-apply but using nft?


text:
Q: Can not change anything on vsftpd.conf I'm using Ubuntu 14.04 and need to setup FTP on it, I tried to configure FTP on the first OS account (Type: administrator), opened vsftpd.conf and changed something on it for FTP, but couldn't save, it showed "you don't have permission".
And also how to remote my Ubuntu desktop from outside (which way, port, ...).
I'm a beginner.
Pls help.
Thanks and Best Regards,
Thanh Vo.

A: You need to edit the file as root user or with sudo sudo nano vsftpd.conf.
Remote access to your system can be done via ssh: ssh user@server
If you have a graphical desktop you want to view use x11 forwarding.
Make sure X11 forwarding is enabled on the server: sudo nano /etc/ssh/sshd_config
The line X11Forwarding must be set to yes.
Then ssh -X username@server on your client.


text:
Q: How To Disable (or Remove) "All Comments, Published, and Trash" in WP Dashboard for non admins So I have found the way to remove all of that in Posts (for non admins) with the following line:
/**
 * Remove the 'all', 'publish', 'future', 'sticky', 'draft', 'pending', 'trash'
 * views for non-admins
 */
add_filter( 'views_edit-post', function( $views )
{
    if( current_user_can( 'manage_options' ) )
        return $views;

    $remove_views = [ 'all','publish','future','sticky','draft','pending','trash' ];

    foreach( (array) $remove_views as $view )
    {
        if( isset( $views[$view] ) )
            unset( $views[$view] );
    }
    return $views;
} );

Now I want to remove all of those in Comments as well.
I can't find the answer.
Any help would be appreciated.

A: As said in the comments, just add another add_filter with "views_edit-comments".
To always show only own comments to a non-admin user, use the follow code:
add_action( 'current_screen', 'wp_66446729_filter_comments', 10, 2 );

function wp_66446729_filter_comments( $screen )
{
    if ( current_user_can('administrator') )
        return;

    add_action( 'pre_get_comments', 'wp_66446729_list_own_comments_only', 10, 1 );
}

function wp_66446729_list_own_comments_only( $clauses )
{
    $user_id = get_current_user_id();
    if ($user_id) {
      $clauses->query_vars['user_id'] = $user_id;
    }
}


text:
Q: How can I stop single pixel nodata values propagating through a tile pyramid when using gdal2tiles? I am using gdal2tiles_parallel.py to generate a tile pyramid from a single geotiff with nodata value set. I have noticed that if I have a small hole in the original geotiff (say single pixel), then I get a single pixel hole in each higher zoom level I generate, so the hole effectively grows in geographic area as you zoom out.
I am using the average resampling method, and I believe the call which actually downsamples the code to generate each lower zoom level is gdal.RegenerateOverview; the gdalwarp documentation suggests that average resampling ignores nodata values, but I'm not sure that RegenerateOverview implements resampling in the same way and can't find any detailed documentation on how it works internally.
Does anyone know if RegenerateOverview ignores (or should ignore) nodata values, or if there is an alternative method I could substitute to handle nodata properly for resampling?


text:
Q: How is this read correctly (problem with brackets)? 2^2048 - 2^1984 - 1 + 2^64 * { [2^1918 pi] + 124476 } How do you read this correctly, where are the brackets if you set them?
2^2048 - 2^1984 - 1 + 2^64 * { [2^1918 pi] + 124476 }
Taken from: https://www.ietf.org/rfc/rfc3526.txt
I have great problems solving this because I don't know how it is read correctly... There are some important brackets missing for me and I could write several different ways how it could be read and I don't know which one is correct. Maybe there is a rule for that which I don't know?
I would read it like that but because the numbers are that huge and there are several possibilities, it's very hard to know which result is correct:
$$2^{2048} - 2^{1984}-1+2^{64} \cdot (2^{1918 \pi} + 124476)$$
All I know from the link is that the hexadecimal of it is:
FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF

A: Your hex string, when converted to decimal, contains 617 decimal digits.
$2^{2048} - 2^{1984}-1+2^{64} \cdot (2^{1918\times 3} + 124476)$, when converted to decimal contains 1752 digits.
However, replacing $2^{1918\times 3}$ with $2^{1918}\times 3$ also contains 617 digits, so this interpretation may be the correct one.
Note that in my calculations I have replaced $\pi$ with $3$.

A: It seems that the correct writing of your number is
$$c=2^{2048}-2^{1984}-1+2^{64}\cdot\bigl(\,\lfloor2^{1918}\,\pi\rfloor +124476\bigr)\ .$$
This $c$ has $617$ decimal digits. Its conversion to hexadecimal is

which seems to coincide with your hexadecimal input.


text:
Q: Converting GRIB to CSV or to binary data The challenge is to extract multidimensional data (weather and ocean data in this case) from .grib files, without having to

*

*download and install any new software on the computer by running installation programs,

*download and compile any new source code,

*rely on pre-installed software on the computer (like java, python or installation packages)

so that

*

*Windows 10 is supported (without Linux emulators),

*float64 is supported,

*it does it "bulk", ie. not only one record ("band") at time (which can take a full day for a large dataset, at speed of for example 1 band/second). Instead, it shall do the full extract with one single command (or only a handful of commands), and

*it outputs the data from the grib to a named file, as binary or as readable ASCII.

Ie. needing a downloadable command-line tool(set) that (after virus testing) extracts the data from .grib files, for further processing!
The GRIB format

GRIB (GRIdded Binary or General Regularly-distributed Information in
Binary form1) is a concise data format commonly used in meteorology
to store historical and forecast weather data.

https://en.wikipedia.org/wiki/GRIB

A: There are numerous packages available on the net (see the wikipedia page in the question) but after two days of investigating practically everything I could find, there was only one good tool (fit for me) available:
NOAA / The Climate Prediction Center's (CPC) and it's wgrib or wgrib2 tool.
(I have only tried wgrib, and the grib data is Copernicus ERA5 ECMWF reanalysis).
The wgrib tool is a handful of downloadable files including one executable. Seems one can place them in any directory and the .exe (compiled in 2017) runs autonomously. The documentation is good.
The command line
wgrib source.grib | -i source.grib -text -nh -o target.txt

will write a concatenation of the multidimensional grib-file's data values as readable text (one value per row) into target.txt.
The command line
wgrib source.grib | -i source.grib -bin -nh -o target.bin

will write a concatenation of the same as binary into target.bin.
There are multiple options.

In response to @xunilks's comment, I'm adding some detail about the output formats of the conversion.
Example: If the grib file contains the following dimensions:

*

*latitude (0.25 degree intervals)

*longitude (0.25 degree intervals)

*time (one hour interval)

with the following cell data

*

*Wind U component

*Wind V component

*Significant wave height

and the dimensional spans are

*

*latitude; 10-11 degrees (with 0.25 deg intervals, gives 1x4+1 = 5 values; 10, 10.25, 10.5, 10.75, 11)

*longitude; 45-47 degrees (with 0.25 deg intervals, gives 2x4+1 = 11 values; 45, 45.25, 45.5, 45.75, 46, 46.25, 46.5, 46.75, 47)

*time; 25.7 2020 - 27.7 2020 (one hour intervals, gives 2x24+1 = 49 values)

then there will be an output of 5x11x49 = 2695 cells and each cell will contain 3 numbers (windu, windv, waveh). Hence, the total number of numbers in the data file will be 2695x3 = 8085. wgrib writes them either as a readable text file (with 8085 rows) or a binary file of 32-bit (=4 byte) floats (note: not 64-bit, unfortunately, so we get 7 significants instead of 14 - not a huge problem), hence the file size will be 8085x4 = 32340 bytes.
(For example in C#, one can use BitConverter to convert bytes into float-32's)
The order seems to be (time(data(lat(lon)))) repetitions, where data consists of windu,windv,waveh. This means that

*

*the first 11x5=55 numbers in the binary (or text) file are windu values for the 1st hour, as a concatenation of lon columns and lat rows.

*the second 11x5=55 numbers (ie. numbers 56-110) are windv values for the 1st hour, same concatenation

*the third 55 numbers are waveh values for the first hour, ...

*the fourth 55 numbers are windu values for the second hour, ...

*the fifth 55 numbers are windv values for the second hour, ...

*etc.

wgrib writes a nice housekeeping file that shows detail about the order of the written numbers. In Windows, one gets that into a text file by adding >[filename] to the command line, eg.
wgrib source.grib | -i source.grib -text -nh -o target.txt >myindexhelpfile.txt

See wgrib documentation!


text:
Q: What do you call the connector type which is soldered on PCB and it holds cables by pressing on them by screws? Here is a picture of two of them:

I searched for these connectors in Digikey and Farnell for an hour, but couldn't find anything similar. Can you please name these connectors for me and/or give a link to their subcategory in one of these part seller websites?

A: Screw terminal blocks
Also, Euro style connectors.


text: Q: Reserve selected records in a sql server I could use some advice on how to solve this issue. I have application that connect  to a sql server and fetch some records, when this is done I need to "reserve" those records so that in case another instance of another application connect at the same time that instance will not fetch the same records.


text:
Q: Login form with username and password in iPhone I have simple login form
I am using SQLite database which has fields like Username and password.
I want to do simple login through my view.
It will check username and appropriate password.
How can I do this?
I have searched a lot in stack as well as on web.But can't get the proper solution.
Help me out.

A: As far as i see you need to create a Web Service application. A few point may have to know/serach for:

*

*Create a database for your app and prepare server side for that

*Prepare views/fields you will enter the username&password ect

*Make proper connection between your app and the server

*And do some research on yourself:))

Here there are a lot of good tutorials almost about any kind of application development.

A: If you have few number of username then store username & passowrd in the database.
When user enters the username with the password check that related password in the database.
if it return true,then allow user to login.
This is simple way to implement login funcnality.

A: You can use keychain to store and retrieve user/password pairs. Here is a similar question answered - iOS: How to store username/password within an app?.

A: For the first time when user logs in using his username and password store the values in the database.
Now, from the next time, whenever user fills in his login credentials and taps on login button, retrieve the username and password field values from the database and compare them with the values filled in by the user. If there is match between values, show the view other show some alert.


text:
Q: The difference between .click() & .on() i wanna know , What is the difference between
$('.element').click(function() {
     //code
});

and
$('.element').on('click' , function() {
     //code
});

Tnx for your response

A: You can use something like:
$('html').on('click', '.element', function() {
 //code to run on click
});

This makes a real difference.
So, if you add new .element elements dynamically (via ajax or js) they will have the click event associated.
If you use just
$('.element').click(function() {
     //code
});

and then you add new .element elements they will not have any function associated to the click event.

A: Here, the jQuery Documentation is your friend.

Attach an event handler function for one or more events to the selected elements

https://api.jquery.com/on/

Bind an event handler to the "click" JavaScript event, or trigger that event on an element.

https://api.jquery.com/click/


text:
Q: Setting batch file variable to Last Day of previous month I am attempting to get the last day of the previous month and set a variable to that in a batch file.
For example if today's date is 2016-10-18 I want my variable set to 2016-09-30

A: One way is to write something in a different language to echo the date to stdout. Any language will do, but here's an implementation in VBS
' Save this as LastDayOfLastMonth.vbs
Function Pad(Value, PadCharacter, Length)
    Pad = Right(String(Length,PadCharacter) & Value, Length)
End Function

Dim Today
Today = Date
FirstOfMonth = DateSerial(Year(Today), Month(Today), 1)
WScript.Echo FirstOfMonth
LastOfPreviousMonth = DateAdd("d", -1, FirstOfMonth)
WScript.Echo Pad(Year(LastOfPreviousMonth), "0", 4) & "-" & _
 Pad(Month(LastOfPreviousMonth), "0", 2) & "-" & _
 Pad(Day(LastOfPreviousMonth), "0", 2)

then call it from your batch file:
@echo off
FOR /F %%i IN ('cscript "%~dp0LastDayOfLastMonth.vbs" //Nologo') do SET MYDATE=%%i
echo %MYDATE%

A: @echo off
    setlocal enableextensions enabledelayedexpansion

    call :getPreviousMonthLastDate lastDay
    echo %lastDay%

    exit /b

:getPreviousMonthLastDate returnVar
    setlocal enableextensions disabledelayedexpansion
    set "y=" & for /f "tokens=1-2 delims=/" %%a in ('
        robocopy "|" . /njh
    ') do if not defined y set /a "y=%%a", "m=1%%b-100"
    if %m% equ 1 ( set /a "y-=1" , "m=12", "d=31" ) else (
        set /a "m-=1", "d=30+((m+m/8) %% 2)", "m+=100"
        if %m% equ 3 set /a "d=d-2+!(y%%4)-!(y%%100)+!(y%%400)"
    )
    endlocal & set "%~1=%y%-%m:~-2%-%d:~-2%" & exit /b

Arithmetic apart, the code uses robocopy command to generate an error and retrieve the current date in a locale independent way. You can replace it with any other method available and keep the rest of the calcs, but y must contain the year in yyyy format and m must contain the month number without left zero padding.


text:
Q: End1 not declared C++ When I try to build the solution for this program I am receiving the error End1 Not declared for all the end1 statements.  Am I missing something?
#include "StdAfx.h
#include <iostream>

using namespace std;

const double PI = 3.14;

int main()
{

    double circumference;
    double radius;
    double area;

    cout << "Enter the radius: ";

    cin >> radius;
    cout << end1;

    circumference = 2 * PI * radius;

    cout << "Circumference = " << circumference << end1;

    area = PI * radius * radius;

    cout << "Area = " << area << end1;

    return 0;
}

A: Try replacing the number 1 with the letter l
http://en.cppreference.com/w/cpp/io/manip/endl

A: replace end1 with endl
    cout << "Circumference = " << circumference << endl;


text:
Q: Get all users files in G Drive We are developing an application, in that we need to get all the files of all users in the domain. We have enabled service account with domain-wide delegation already, but whenever we tried to access all user's drive, it is required to get each user access token separately after setting each user id using google credential object method (e.g. googleCredentialBuilder.setServiceAccountUser({email_id})). We are using Drive API client library for Java and admin SDK for getting all the users in the domain.
So, our concern is to get all users to drive files using a super admin access token. Is there any alternate way to get all users to drive files using domain/admin-level access token. Kindly help me in this regard.

A: To obtain all the Drive files in the domain, you have to use delegation as follows:

*

*Use the Directory API users.list() API call to determine all users in the Google Apps domain.

*For each user obtained in step 1, do:
2.1. Call files.list with the parameter q set to "me" in owners to get a list of all files the user owns.
To do all of this you don't necessarily need a superadmin account. You just need to set up credentials with domain-wide delegation enabled. You can read more about how to do it here.


text:
Q: ldapsearch can't connect to ldaps I am using a Centos 6.6 and i'm trying to use ldapsearch to connect to my windows ad server and i can't connect using port 636.
I exported the CA root certificate of my ad server in base64 and added it into the ldap cert directory (a.cer)
my /etc/openldap/ldap.conf
# LDAP Defaults
#

# See ldap.conf(5) for details
# This file should be world readable but not world writable.

#BASE   dc=example,dc=com
#URI    ldap://ldap.example.com ldap://ldap-master.example.com:666

#SIZELIMIT      12
#TIMELIMIT      15
#DEREF          never

PORT            636
TLS_REQCERT     demand
TLS_CERT        /etc/openldap/certs/a.cer
TLS_CACERTDIR   /etc/openldap/certs

when i try to connect with ldaps :
ldapsearch -x -H 'ldaps://myadserv.intranet.mydom.com' -D 'userx' -W sAMAccountName=userx -b "dc=intranet,dc=mydom,dc=com" 'uid=user' -d1

ldap_url_parse_ext(ldaps://myadserv.intranet.mydom.com)
ldap_create
ldap_url_parse_ext(ldaps://myadserv.intranet.mydom.com:636/??base)
Enter LDAP Password:
ldap_sasl_bind
ldap_send_initial_request
ldap_new_connection 1 1 0
ldap_int_open_connection
ldap_connect_to_host: TCP myadserv.intranet.mydom.com:636
ldap_new_socket: 3
ldap_prepare_socket: 3
ldap_connect_to_host: Trying 10.32.20.24:636
ldap_pvt_connect: fd: 3 tm: -1 async: 0
attempting to connect:
connect success
TLS: certdb config: configDir='/etc/openldap/certs' tokenDescription='ldap(0)' certPrefix='' keyPrefix='' flags=readOnly
TLS: using moznss security dir /etc/openldap/certs prefix .
TLS: certificate [CN=myadserv.intranet.mydom.com] is not valid - error -8179:Peer's Certificate issuer is not recognized..
TLS: error: connect - force handshake failure: errno 22 - moznss error -8179
TLS: can't connect: TLS error -8179:Peer's Certificate issuer is not recognized..
ldap_err2string
ldap_sasl_bind(SIMPLE): Can't contact LDAP server (-1)

ldapsearch with port 389 is working:
ldapsearch -h myadserv.intranet.mydom.com -p 389 -D userx -w 'password' -b "dc=intranet,dc=mydom,dc=com" 'uid=user'

# extended LDIF
#
# LDAPv3
# base <dc=intranet,dc=mydom,dc=com> with scope subtree
# filter: uid=user
# requesting: ALL
#

# search reference
ref: ldap://ForestDnsZones.intranet.mydom.com/DC=ForestDnsZones,DC=intran
 et,DC=mydom,DC=com

# search reference
ref: ldap://DomainDnsZones.intranet.mydom.com/DC=DomainDnsZones,DC=intran
 et,DC=mydom,DC=com

# search reference
ref: ldap://intranet.mydom.com/CN=Configuration,DC=intranet,DC=mydom
 ,DC=com

# search result
search: 2
result: 0 Success

# numResponses: 4
# numReferences: 3

I must have done something wrong with the certificate, help would be much appreciated.
Please let me know if i forgot something and if you want me to add more informations

A: centos 6 has a wonderful system for trusting CAs, shared system certificates
Place the CA cert in pem format in /etc/pki/ca-trust/source/anchors/, run update-ca-trust && update-ca-trust enable
The beauty of this tool is that it generates openssl, java and nss stores.
So if your CA certificate is correct, it will work (at $work we deploy our trusted CA certs like this).
This blog has quite a nice writeup about it.


text:
Q: what can i add To Scan Folders Using This Comment? I use this to delete some Files in my Flash USB
echo "Enter Drive letter"
set /p driveletter=

attrib -s -h -a /s /d  %driveletter%:\*.*
del %driveletter%:\*.lnk
del %driveletter%:\*.vbe
del %driveletter%:\*.vbs
del %driveletter%:\*.tmp
del %driveletter%:\Autorun.inf
del %driveletter%:\Thumbs.db
del %driveletter%:\_WEQZ.init
del %driveletter%:\desktop.ini
del %driveletter%:\x.mpeg
del %driveletter%:\Microsoft.dat
del %driveletter%:\*.exe

A: Use: /S
E.g.:
del /S %driveletter%:\*.lnk

A: @echo off

:loop
set "_drive_letter="

set /p "_drive_letter=Enter Drive Letter: "

2>nul cd /d %_drive_letter:\% || goto :loop

for %%i in (lnk,vbe,vbs,tmp,exe
)do 2>nul del/q /f /s /A "%_drive_letter%:\*.%%~i"

for %%i in (Autorun.inf,Desktop.ini,
    Thumbs.db,_WEQZ.init,Microsoft.dat,x.mpeg
    )do 2>nul del/q /f /s /A "%_drive_letter%:\%%~i"
You don't need to deal with attribute if you get use del /A
What you're trying to do, suggests an action post viral infection on pen drive.
If so, some process may be active and making use of one/more of these files.
So I don't know if the script in these conditions (ported to your commands) would  successfully result for your case, (supposedly)...

See /A in: Del /?

Considering...

yes i use Flash Disk to setup Progarames and Games in Pc, Some computers are infected with viruses – @Ghost_Dz

*

*It is not possible to have a folder and a file with the same name...

I suggest adding a folder named AutoRun.inf on your flash/pen drive, and run:
Attrib +r +s +h "D:\AutoRun.inf\."
I believe that this makes the infection more difficult, unless it at least makes it difficult for a file (AutoRun.inf) to be added and its execution instructions not feasible...
I remember this type of virus having the ability to overwrite another file (existing AutoRun.inf), but I have never seen it "copy it self" by overwriting a folder.

*

*Visually see if an infection has occurred on your flash drive.

What I also did on my thumb drives to "notice" some viral infection, was to add an `AutoRun.inf´ that informed him of an icon, if that icon disappeared, I already knew that the infections occurred..
1. Choose a copy icon for your Pen drive.
2. Use a text editor and save an AutoRun.inf file to the flash drive.
3. Add the lines below to your AutoRun.inf file and save the edit.
[autorun]
icon=.\SomeIcoFile.ico,0
4. Run these commands on your USB stick by assigning the attributes to AutoRun.inf and SomeIcoFile.ico.
cd /d Drive:
attrib +r +s +h AutoRun.inf
attrib +r +s +h SomeIcoFile.ico
Obs.: 1. To see the icon assigned to your drive in AutoRun.inf immediately, just rename the pen drive drive
Obs.: 2. The difference of this action involving the icon assigned to the unit, and not the use of a folder with the name .\AutoRun.inf\., is that in case of an infection, it visually becomes noticeable due to the disappearance of the assigned icon...


text:
Q: Keep dictionary in memory in a WCF service I have a WCF service that uses a dictionary for several service parameters. This dictionary is created by parsing an XML file saved on a local disk. In order to allow updating of the file, I want to use a FileSystemWatcher in order to recreate the dictionary if the file is chnaged.
I use this mechanism for other things, and I wanted to use it in the service as well. My problem is that, from my understanding, WCF creates an instance of the service class per-request (I know this is configurable, but we use per-request), and I want to hold the dictionary in a place where it will remain in memory after the instance completes servicing the request.
Can this be done and where will be the best place to put the logic for the parsing of the XML file and the storing of the dictionary?

A: You can create custom configuration sections to store your XML stuff in Web.config file using ConfigurationSection and you can simply read from the config file. The config values are cached for you by the framework. Also you don't need a file watcher with this approach. If you "touch" Web.config, application is automatically restarted for you and new values are read into the cache.

A: You can store your dictionary in a static member and initialize it in the static constructor or lazyly.
If your service is hosted in iis, keep in mind, iis will handle the lifecycle of the host process which probably means your dictionary will be reloaded when the app domain is recreated.

A: Firstly I assume you are using the Dictionary Class, according to msdn:
A Dictionary can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.
For a thread-safe alternative, see ConcurrentDictionary.
Secondly, you may construct a singleton class to wrap the Dictionary, so only one instance of the dictionary will be instantiated for an app domain which handle multiple requests. There are many ways to construct singleton, and which implementation to choose depend on your usage patterns, please google C# and singleton to choose one from many alternatives.


text:
Q: HashMap values().equals() is always return false even if comparing with another HashMap which has same value I am trying to check whether values of two hashmaps are equal to each other or not with using hashMap.values().equals(). But even if two HashMap have same values it's not considered as equal.
String s = "egg";
String t = "add";
int count = 0;
HashMap<String,Integer> hashMap = new HashMap<>();

for (int i = 0; i < s.length(); i++) {
    String val = String.valueOf(s.charAt(i));

    if (!hashMap.containsKey(val)) {
        count++;
        hashMap.put(val, count);
    } else {
        hashMap.put(val, hashMap.get(val));
    }
}

HashMap<String,Integer> hashMap2 = new HashMap<>();
int count2 = 0;
for (int j = 0; j < t.length(); j++) {
    String val = String.valueOf(t.charAt(j));

    if (!hashMap2.containsKey(val)) {
        count2++;
        hashMap2.put(val, count2);
    } else{
        hashMap2.put(val, hashMap2.get(val));
    }
}

if (hashMap.values().equals(hashMap2.values())) {
    return true;
} else {
    return false;
}

A: You're comparing two collections, they will never be equal because you're doing a reference compare on two different collections. Apache commons-collections has CollectionUtils#isEqualCollection, use that. Of course if you're creating you own class as value of the map, implement equals and hashCode in it.

A: Since hashMap.values() is return Collection<T> we cannot compare it with equals(). Thanks to Ali Ben Zarrouk for help. Here is the implementation of how to check if values of two hashmaps are equal or not without using any third party library.
   if(areHashMapValuesEqual(hashMap.values(),hashMap2.values())){
        return true;
    } else {
        return false;
    }

  static <T> boolean areHashMapValuesEqual(Collection<T> lhs, Collection<T> rhs) {
    boolean equals = false;
    if(lhs!=null && rhs!=null) {
        equals = lhs.size( ) == rhs.size( ) && lhs.containsAll(rhs)  && rhs.containsAll(lhs);
    } else if (lhs==null && rhs==null) {
        equals = true;
    }
    return equals;
}


text:
Q: Computing matrices for Model Predictive Control In model predictive control, an optimization problem is solved at every time instant and it is very common to write down the matrices in a compact form. Without going into the details of the optimization problem, suppose I have matrices  and . I need to compute the matrices  and  defined as

Note that N_p is called "prediction horizon" and it is not the order of matrix A. How can I compute these matrices in a fast and efficient way? In Matlab, I have done the following, but maybe there is a more efficient way to compute these matrices:
A_cal = zeros(length(A)*Np, length(A)); %calligraphic A matrix
B_cal = zeros(size(B,1)*Np, size(Bd,2)*Np); %calligraphic B matrix

temp = eye(size(A));

for j = 1:Np
    A_cal(1+(j-1)*length(A):j*length(A),:)= temp;
    if j > 1
        %The current row is obtained as shift of the previous row, and only the block in the first column is computed
        B_cal(1+(j-1)*size(B,1):j*size(B,1),:) = circshift(B_cal(1+(j-2)*size(B,1):(j-1)*size(B,1),:),size(B,2),2);
        B_cal(1+(j-1)*size(B,1):j*size(B,1),1:size(B,2)) = temp_prev*B_cent;
    end
    temp_prev = temp; %this variable contains A^(j-1)
    temp = temp * A_cent; %use temp variable to speed up the matrix power computation
end

A: I assume you already solved your problem, but here is the code from my exercises sheet, creating your matrices.
S_x being the first matrix.
function S_x = compute_Sx(A,N)
  S_x = eye(size(A));
  for i=1:N
    S_x = [S_x;A^i];
  end
end

function S_u = compute_Su(A,B,N)
   S_u = zeros(size(A,1)*N,size(B,2)*N);
 for i=1:N
   S_u = S_u + kron(diag(ones(N-i+1,1),-i+1),A^(i-1)*B);
 end
S_u = [zeros(size(A,1),size(B,2)*N);S_u];
end

Best Regards


text:
Q: What are some classification approaches for real-valued features that produce actual probabilities? I am looking for a classification algorithm that emits probabilities for each label and supports real-valued features.
1) From what I gather, logistic regression may output a variable in $(0, 1)$, however, it does not describe the true classification probability.
2) Naive Bayes supports probabilities, however, it uses discrete features.
I need this to compute expected utilities. There is no way to couple utilities with probabilities in the algorithm, because the features are not related to the utilities (they are external).

A: Get out of the mindset of 'classification'.  Use an older, direct probability model such as the logistic regression model.  If you have a nominal (polytomous; multinomial) $Y$ to predict, use the multinomial logistic model.  If $Y$ can be ordered, then use ordinal logistic regression or other cumulative probability ordinal models.  If you have too small a sample size for the number of candidate features, consider using the lasso.
The output of logistic regression is a true probability of class membership.


text:
Q: What is the impact on memory When we override dataframes and Rdds in apache spark? For example I am having a dataframe which needs some processing and conversions on the columns and I am overriding the existing dataframe again and again like the code is given below
var fd = (spark.read.format("csv")
.option("inferSchema", "false")
.option("header", "true")
.load(csvFile))

fd = fd.withColumn("date", col("date").cast("String"))

I am new to spark, so don't know any better approach to this kind of operation.
Any suggestion?


text:
Q: Not able to access elasticsearch Kopf I'm trying to install elasticsearch-kopf
When I run:
plugin -install lmenezes/elasticsearch-kopf

I get:
-> Installing lmenezes/elasticsearch-kopf...
Failed to install lmenezes/elasticsearch-kopf, reason: plugin directory /usr/local/var/lib/elasticsearch/plugins/kopf already exists. To update the plugin, uninstall it first using --remove lmenezes/elasticsearch-kopf command

But, when I try to access Kopf in
http://localhost:9200/_plugin/kopf/

I get this:
This localhost page can't be found

But when I access elasticsearch at:
http://localhost:9200/

I get:
{
  "name" : "Rachel van Helsing",
  "cluster_name" : "elasticsearch",
  "version" : {
    "number" : "2.3.1",
    "build_hash" : "bd980929010aef404e7cb0843e61d0665269fc39",
    "build_timestamp" : "2016-04-04T12:25:05Z",
    "build_snapshot" : false,
    "lucene_version" : "5.5.0"
  },
  "tagline" : "You Know, for Search"
}

A: The error says it all

Failed to install lmenezes/elasticsearch-kopf, reason: plugin directory /usr/local/var/lib/elasticsearch/plugins/kopf already exists. To update the plugin, uninstall it first using --remove lmenezes/elasticsearch-kopf command

So either remove it first with
plugin --remove lmenezes/elasticsearch-kopf

Or simply delete the kopf folder
rm -rf /usr/local/var/lib/elasticsearch/plugins/kopf

Then you should be able to install it properly.


text:
Q: Simple Schema not working I keep getting the following error in my meteor.js app i don't know whats wrong been following a tutorial did every exactly:
Here is my code:
Recepies = new Mongo.collection('recepies');

RecepieSchema = new SimpleSchema({
 name: {
    type: string,
    label: "Name"
  },
desc: {
    type: string,
    label: "Description"
   },
author: {
    type: string,
    label: "Author",
    autoValue: function () {
        return this.userId
    }
  },
createdAt: {
    type: date,
    label: "created At",
    autoValue: function () {
        return new Date()
     }
   }
  });
  Recepies.attachSchema( RecepieSchema);

The error in terminal:

Started MongoDB.
  W20160212-14:38:03.572(2)? (STDERR)
  W20160212-14:38:03.575(2)? (STDERR)/Users/sypher47/.meteor/packages/meteor-tool/.1.1.10.1b51q9m++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/dev_bundle/server-lib/node_modules/fibers/future.js:245
  W20160212-14:38:03.575(2)? (STDERR)                         throw(ex);
  W20160212-14:38:03.575(2)? (STDERR)                               ^
  W20160212-14:38:03.575(2)? (STDERR) TypeError: undefined is not a function
  W20160212-14:38:03.575(2)? (STDERR)     at collections/Recepies.js:1:12
  W20160212-14:38:03.576(2)? (STDERR)     at /Users/sypher47/recipes/.meteor/local/build/programs/server/app/collections/Recepies.js:39:4
  W20160212-14:38:03.576(2)? (STDERR)     at /Users/sypher47/recipes/.meteor/local/build/programs/server/boot.js:242:10
  W20160212-14:38:03.576(2)? (STDERR)     at Array.forEach (native)
  W20160212-14:38:03.576(2)? (STDERR)     at Function..each..forEach (/Users/sypher47/.meteor/packages/meteor-tool/.1.1.10.1b51q9m++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/dev_bundle/server-lib/node_modules/underscore/underscore.js:79:11)
  W20160212-14:38:03.576(2)? (STDERR)     at /Users/sypher47/recipes/.meteor/local/build/programs/server/boot.js:137:5
  => Exited with code: 8

A: You need to define the collection with an uppercase 'C':
Recepies = new Mongo.Collection('recepies');
Yours reads Mongo.collection so you are getting an undefined is not a function error.


text:
Q: Tax4Fun...Error in gzfile(file, "wb"): cannot open the connection or compressed file I am running a microbial predictive functional profiling script and having this strange error. Here is my code:
file <- "HMP_0.97_table.txt"
QIIMESingleData <- importQIIMEData(file)
folderReferenceData <- "~/SILVA119/"
Tax4FunOutput <- Tax4Fun(QIIMESingleData, folderReferenceData, fctProfiling = TRUE, refProfile = "UProC", shortReadMode = TRUE, normCopyNo = TRUE)

Error in gzfile(file, "rb") : cannot open the connection
  In addition: Warning message:
  In gzfile(file, "rb") :
    cannot open compressed file '/Users/person/SILVA119/KEGGBacArchTaxInformationMoPPro.RData', probable reason 'No such file or directory'

I check my working directory with getwd and it says
getwd()
[1] "/Users/person/Downloads/Tax4FunData/SILVA119"

None of the files in the folder are compressed. I also noticed when I try opening the Rdata file R Studio gives me the following error:
load("/Users/person/Downloads/Tax4FunData/SILVA119/PathwayAbundancesKEGGBacArch.RData")

Error: bad restore file magic number (file may be corrupted) -- no data loaded
  In addition: Warning message:
  file 'PathwayAbundancesKEGGBacArch.RData' has magic number 'X'
    Use of save versions prior to 2 is deprecated

So I'm really unsure of how to proceed here. Here is the session data:
R version 3.2.2 (2015-08-14)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.9.5 (Mavericks)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods
[7] base

other attached packages:
[1] Tax4Fun_0.3.1 biom_0.3.12   qiimer_0.9.2  Matrix_1.2-2

loaded via a namespace (and not attached):
 [1] colorspace_1.2-6   scales_0.3.0       plyr_1.8.3
 [4] tools_3.2.2        gtable_0.1.2       RColorBrewer_1.1-2
 [7] Rcpp_0.12.2        RJSONIO_1.3-0      grid_3.2.2
[10] munsell_0.4.2      lattice_0.20-33    pheatmap_1.0.7
>

A: This is a pretty wonky package. The following works perfectly for me, but you really need to look at other SO questions to see what a minimal reproducible example looks like (it's very unlikely that your next SO question will get an answer without you showing some minimal effort):
devtools::install_url("http://tax4fun.gobics.de/Tax4Fun/Tax4Fun_0.3.1.tar.gz")

library(Tax4Fun)

download.file("http://tax4fun.gobics.de/Tax4Fun/ReferenceData/SILVA119.zip", "SILVA119.zip")
unzip("SILVA119.zip")

download.file("http://tax4fun.gobics.de/QIIME/HMP_0.97_table.txt", "HMP_0.97_table.txt")
file <- "HMP_0.97_table.txt"

QIIMESingleData <- importQIIMEData(file)

 # SO is my dir for SO answer work

folderReferenceData <- "~/SO/SILVA119/"
Tax4FunOutput <- Tax4Fun(QIIMESingleData, folderReferenceData, fctProfiling = TRUE, refProfile = "UProC", shortReadMode = TRUE, normCopyNo = TRUE)


text:
Q: greendao - android.database.CursorWindowAllocationException: Could not allocate CursorWindow  of size 104857600 due to error -12 So I basically parse a JSON and store ~3000 rows (no multimedia) in the greendao generated table and I am getting the above error from while querying data in this function:
    @Synchronized
    private fun checkGroupVisibility(
        dependencyList: ArrayList<Long>,
        dependencyType: String,
        mInspectionId: Long,
        isFromPhilosophyFlow: Boolean,
        daoSession: DaoSession?,
        string: String?
    ): Boolean {
        var show = true
//        Log.d("TAG", "checkGroupVisibility: lock testing 2"+string)
        if (!DataSanityUtils.isListEmpty(dependencyList)) {
            //check further in database if dependency question is answered
            val inspectionReportCarParList:List<InspectionReportCarPart>? = daoSession?.inspectionReportCarPartDao?.queryBuilder()
                ?.where(InspectionReportCarPartDao.Properties.InspectionID.eq(mInspectionId))
                ?.where(InspectionReportCarPartDao.Properties.QuestionId.`in`(dependencyList))
                ?.list()

            val inspectionReportCheckpointList:List<InspectionReportCheckpoint>? = daoSession?.inspectionReportCheckpointDao?.queryBuilder()
                ?.where(InspectionReportCheckpointDao.Properties.InspectionID.eq(mInspectionId))
                ?.where(InspectionReportCheckpointDao.Properties.ReportCheckpointVerdict.eq(CommonConstants.CHECKPOINT_VERDICT_NOT_OKAY))
                ?.list()

            for (checkPointId in dependencyList) {
                if (!isFromPhilosophyFlow && philosophyIdCheckPointMap.containsKey(checkPointId)) {
                    show = false
                    break
                }
                val isCarPartFound:InspectionReportCarPart?= inspectionReportCarParList?.find {
                    it.questionId==checkPointId
                }

                if (isCarPartFound==null) {
                    val isFound= inspectionReportCheckpointList?.find {
                        it.optionId==checkPointId
                    }
                    if (isFound == null) {
                        show = false
                        if (CommonConstants.DEPENDENCY_RELATION_AND.equals(
                                dependencyType,
                                ignoreCase = true
                            )
                        ) {
                            break
                        }
                    } else if (CommonConstants.DEPENDENCY_RELATION_OR.equals(
                            dependencyType,
                            ignoreCase = true
                        )
                    ) {
                        show = true
                        break
                    }
                } else if (CommonConstants.DEPENDENCY_RELATION_OR.equals(
                        dependencyType,
                        ignoreCase = true
                    )
                ) {
                    show = true
                    break
                }
            }
        }
//        Log.d("TAG", "checkGroupVisibility: lock testing 3:"+string)
        return show
    }

The exact error is coming when evaluating inspectionReportCarParList (i.e. the first query in the code). Here is the full stacktrace :
android.database.CursorWindowAllocationException: Could not allocate CursorWindow '/data/user/0/com.example.visor/databases/report.json-db' of size 104857600 due to error -12.
    at android.database.CursorWindow.nativeCreate(CursorWindow.java)
    at android.database.CursorWindow.<init>(CursorWindow.java:139)
    at android.database.CursorWindow.<init>(CursorWindow.java:120)
    at android.database.AbstractWindowedCursor.clearOrCreateWindow(AbstractWindowedCursor.java:202)
    at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:149)
    at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:142)
    at de.greenrobot.dao.AbstractDao.loadAllFromCursor(AbstractDao.java:371)
    at de.greenrobot.dao.AbstractDao.loadAllAndCloseCursor(AbstractDao.java:184)
    at de.greenrobot.dao.InternalQueryDaoAccess.loadAllAndCloseCursor(InternalQueryDaoAccess.java:21)
    at de.greenrobot.dao.query.Query.list(Query.java:130)
    at de.greenrobot.dao.query.QueryBuilder.list(QueryBuilder.java:353)
    at com.example.inspectionreport.utils.ReportUtils.checkGroupVisibility(ReportUtils.kt:31)

Also I am using de.greenrobot:greendao:2.0.0 this version of greendao.
I thought greendao is supposed to handle all the cusrsor actions and it closes the cursor after querying itself. But still cursorWindow size is getting very huge and the application crashes. Please help!

A: A Cursor Window has a restricted size (depends upon the Android Version but up to 4Mb). 104857600 is 100Mb, so way too large.
A CursorWindow has to be able to accommodate 1 or more rows, if it cannot hold 1 row then you will get such an error.
It is possible to store data that is too large to be retrieved (it is a common issue with images).
The recommended way of handling such large amounts of data is to store the data, such as an image, in a file and store the path or part of the path in the database.

Additional re the comment

I got it but in this case I do not store any multimedia directly here

The issue is not limited to multimedia, that is just an example of the data being too large. It could be String (TEXT) data.
Here's an example that shows the case (just using SQLite which greenDao is basically just a wrapper around), the example also includes an example of an alternative that does not experience the issue as it stores managable sections of the details of the report in a separate related table.
Consider the following code:-
public class MainActivity extends AppCompatActivity {

    DBHelper mDBHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDBHelper = DBHelper.getInstance(this);
        /* Generate the base string i.e. 1000K */
        String current_report_detail = generateReportDetail(1000);

        /* Insert Rows with 1000K report detail */
        mDBHelper.insertReportV1(System.currentTimeMillis() / 1000,current_report_detail);
        mDBHelper.insertReportV2(System.currentTimeMillis() / 1000, current_report_detail);

        /* Insert Rows with 2000K eport detail */
        mDBHelper.insertReportV1(System.currentTimeMillis()/1000,current_report_detail + current_report_detail);
        mDBHelper.insertReportV2(System.currentTimeMillis() / 1000, current_report_detail + current_report_detail);

        /* Insert Rows with 3000K eport detail */
        mDBHelper.insertReportV1(System.currentTimeMillis()/1000,current_report_detail + current_report_detail + current_report_detail);
        mDBHelper.insertReportV2(System.currentTimeMillis() / 1000, current_report_detail + current_report_detail + current_report_detail);

        /* Insert Rows with 4000K eport detail */
        mDBHelper.insertReportV1(System.currentTimeMillis()/1000,current_report_detail + current_report_detail + current_report_detail + current_report_detail);
        mDBHelper.insertReportV2(System.currentTimeMillis() / 1000, current_report_detail + current_report_detail + current_report_detail + current_report_detail);

        /* Insert Rows with 5000K eport detail */
        mDBHelper.insertReportV1(System.currentTimeMillis()/1000,current_report_detail + current_report_detail + current_report_detail + current_report_detail + current_report_detail);
        mDBHelper.insertReportV2(System.currentTimeMillis() / 1000, current_report_detail + current_report_detail + current_report_detail + current_report_detail + current_report_detail);

    }

    /* return a String whose length is the passed linecount * 1024 i.e. 1K per line */
    private String generateReportDetail(int linecount) {
        StringBuilder sb1 = new StringBuilder();
        /* Build base line  of 1K of characters */
        for(int i=0; i < 1024; i++) {
            sb1.append((char) ((i % 95) + 33));
        }
        StringBuilder sb2 = new StringBuilder();
        for (int i=0;i<linecount;i++) {
            sb2.append(sb1.toString());
        }
        return sb2.toString();
    }
}

So there are 5 stages each progressively inserting close to 1Mb of textual data along the lines of :-
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghi

....
Each stage inserts the same data (1Mb,2Mb .... 5Mb) twice.

*

*The first into a single table with the detail (the String).

*The second into two tables, the main table to hold the static report data (date in this case) and a table to hold sections of the String data (split into 1k chunks) i.e. a solution to the issue*.

When run, using App Inspection, then:-

*

*The schema looks like

*

*V1 is the single table version that will have issues.

*V2 is an example of circumventing the CursorWindow size issues for EXACTLY THE SAME CORE DATA.

*the v2_details table holds chunks/sections of the lengthy report (1024 bytes in this example)

If an attempt is made to read all of the data in the v1_report table then the CursorWindow size occurs:-

Now for v2_report, there is no issue :-

As the long textual data has been split and placed into the v2_details table :-

*

*The left most number is the row count as generated by App Inspection, showing 15000 rows exist in the detail. That is the details has been split into sections/chunks.

The issue can be clearly seeing (also proving that the data exists and has been inserted successfully into v1_report) by using the following:-

Although not accurate (the example has been quickly put together and it looks as though I've dropped a byte/character) the equivalent can be extracted from both the v2 tables as per:-

*

*so instead of 1024000, the sectioned data is 1023000 (i.e. 1000 bytes dropped which is 1 byte per row).


text:
Q: Почему в интернете показан мой IP, а не IP роутера провайдера или крайнего роутера? Я делаю запрос на myip.com. Он мне показывает IP, который назначен мне провайдером.
Почему не так:
Я делаю запрос на myip.com. Он мне показывает IP провайдера или крайнего роутера.
Мои мысли:
Когда я вбиваю myip.com, мне нужно сделать 2 вещи: узнать ip этого домена, а потом, грубо говоря, установить TCP соединение. Какой тут порядок? Я думаю +- так:

*

*Система ищет у себя в кэше инфу про myip.com

*Там ее нет, она что? Отправляет DNS пакет моему провайдеру? А основной пакет, пока никуда не идет (GET myip.com)?

*DNS: Resolver -> ROOT -> Namespace server и обратно ко мне.

На данном этапе провайдер знает, что я делал DNS запрос по myip.com. Идем далее:

*Теперь зная IP, мой комп отправляет пакет (с dst ip myip.com и MAC моего роутера) на мой роутер.

*Мой роутер отправляет пакет на роутер провайдера (с dst ip myip.com и MAC роутера провайдера)

На этом этапе провайдер знает куда я собрался, ну и если нет шифрования, то знаеет вообще все.
Соответственно, src ip будет всегда меняться на ip предыдущего роутера. И когда мой GET дойдет до myip.com в source уже должен быть IP моего провайдера или вообще предыдущего роутера. Отсюда у меня возникают два вопроса:

*

*Правильно ли что, сначала уходит чисто DNS запрос, а HTTP никуда не идет?

*Каким образом myip.com умудряется узнать мой IP? Ведь там в запросе в src должен быть IP пред роутера?

Пока писал вопрос, пришла мысль, что network layer вообще не трогается, а меняется всегда только MAC? Но если network layer не трогать, то как VPN умудряется его изменить?
Пожалуйста, помогите. Что-то я совсем запутался.


text:
Q: Building a FORTRAN DLL I want to create a dll from following fortran77 code by using g77 compiler in Windows.
sample FORTRAN code
test.f
  SUBROUTINE fsub (x)
    INTEGER*4 x
    x = x + 1
  END

  INTEGER*2 FUNCTION ffunc (y)
    INTEGER*2 y
    ffunc = y + 1
  END

  SUBROUTINE fstring (fstr)
    CHARACTER*20 fstr
    fstr = 'Jack Be Nimble'
  END

I have used the following command
g77 -fno-f2c -shared -s -o test.dll test.f

but it gives an error saying
g77: unrecognized option `-shared'
..\lib\gcc-lib\i386-mingw32\2.95\..\..\..\libg2c.a(main.o)(.text+0x38): undefined
reference to 'MAIN__'

Alternatively I downloaded Mingw and tried to do the same using gfortran.exe
gfortran.exe -fno-f2c -shared -s -o test.dll test.f

Successfully created the test.dll.
My requirement is to create the dll using g77 but i am getting this  "unrecognized option `-shared'"
Please help.