text:
Q: .xcdatamodeld file not showing data model structure in Xcode I have .xcdatamodeld file in my project but it not opening up into the data model.
When I click on the file in the left sidebar in Xcode, it continues to display the contents of the previously selected file instead of displaying the data model. Likewise, when I right click on the file and choose "Open As >", I cannot select to display it as a Data Model—nothing comes up. I checked out the code from the SVN repo and even the filer owner is not able to see it in his workspace.

A: I encountered the same issue in Xcode 6.3
The only solution that worked for me was to move the .xcdatamodeld file out of my 'Resources' folder and into the project root folder in the Xcode project explorer (location on the filesystem doesn't matter)
I'm still not sure why, just moving the location of the file in the project structure causes it to not show up at all when clicked.. but apparently, at least in my setup, it doesn't like living in the Resources folder..

A: For some dark reasons, sometimes Xcode needs the xcdatamodeld fiel to be in the root folder.
I wrote an answer here that explain how to do this, but also a workaround to have this file where ever you would like to.
Cheers!

A: The .xcdatamodeld file is a package. It contains .xcdatamodel packages, one for each version of the model. Inside every .xcdatamodel there is a contents file, which is an XML with entities description. To see what is inside your packages, right-click them in Finder and choose Show Package Contents option.

Perhaps you didn't add the contents file into your repository. This way you will not be able to see your model when you create a brand new working copy from it.

A: I was victim of this problem today on Xcode8.
I solved it simply by placing the xcdatamodeld file outside any group in the Project navigator (left pane). As soon as I move it into a group, I can't open the little guy anymore.

A: This is a symptom that I have seen from time to time. In at least one case, this was due Xcode having the wrong path stored in the path component of the XCVersionGroup section of the project.pbxproj file, and having an apparently unnecessary additional name component in that section. It would probably be possible to manually edit this file, but I'm always reluctant to monkey around with the project file directly, and fortunately there's an easier way.

*

*Navigate to your .xcdatamodeld file in the Finder. The easiest way to do this is Right click/Ctrl-click on the .xcdatamodeld file and select "Show in Finder".

*Drag the file from the Finder and drop it immediately above or below the current reference to the .xcdatamodeld in the Project Navigator in your Xcode project.

*Click OK to accept the import, ensuring that you are adding it to the correct targets. (Which targets are correct will depend on your project.)

*You will now have two references to the same file in your Project Navigator. Clicking on either of them will now bring up the desired data model structure.

*Remove the duplicate reference to the model file. Click on one of the file references (doesn't appear to matter which, though it may be better to remove the old one) and press Delete.

*In the resulting confirmation dialog, be sure to select "Remove Reference" only, and do NOT move the file to the trash. (The two references point to only one actual file in the file system. Moving to trash would thus trash the only copy.)

You're now left with just one reference to the data model, and it works.
One thing that appears to trigger this bug is moving the .xcdatamodeld file in the file structure on disk. Even after correctly re-associating the file with the new location (i.e., it no longer appears in red in the sidebar), the one section of the Project file mentioned above is not correctly updated, and thus the file is not treated fully correctly as an Xcode Data Model file.

A: I had a similar problem with Xcode 7.3.1.
It turned out to be related to the way the data model packages were configured.
I discovered that there was one embedded model package nested inside another. Let's say a top level data model called FolderNodes.xcdatamodeld containing  another with exactly the same name ... FolderNodes.xcdatamodeld. Inside FolderNodes.xcdatamodeld is the actual contents file that has the model info.
The solution for me was to drag the embedded package FolderNodes.xcdatamodeld ( number 2) into the Xcode project and NOT its enclosing folder.
Apple uses the package for versioning but I think the logic associated with moving the data model file somehow breaks the original package creating a redundant wrapper.

A: Make sure your Version Editor is not active.
Having the Version Editor open results in the xml code to be displayed instead of the Data Model. You will also not be able to choose Data Model in the context menu of the xcdatamodeld file within the Project Navigator.

A: Happens on XCode 8.3 as well.
For me, moving the physical file to a different folder, then deleting the original reference, then adding it back to same place and establishing the reference again does the job.


text:
Q: Does the TCP connection created by requests persist when using Celery workers? I plan to have celery workers sending notifications to mobile devices (e.g. through GCM) and wish to avoid opening needlessly many TCP connections
I have a celery task defined like this:
@task()
def send_push_notification(
    requests.post(...)
)

Suppose this task is executed by a worker on a single machine.  Will each subprocess open only one TCP connection?  Or will a new connection be created each time the task is executed?
If I want to reuse the same TCP connection for each subprocess, how would I go about doing that?
Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to expand macros in strings read from a file in a ksh script? I want to read a list of file names stored in a file, and the top level directory is a macro, since this is for a script that may be run in several environments.
For example, there is a file file_list.txt holding the following fully qualified file paths:
$TOP_DIR/subdir_a/subdir_b/file_1
$TOP_DIR/subdir_x/subdir_y/subdir_z/file_2

In my script, I want to tar the files, but in order to do that, tar must know the actual path.
How can I get the string containing the file path to expand the macro to get the actual path?
In the code below the string value echoed is exactly as in the file above.
I tried using actual_file_path=`eval $file_path` and while eval does evaluate the macro, it returns a status, not the evaluated path.
for file_path in `cat $input_file_list`
do
    echo "$file_path"
done

A: With the tag ksh I think you do not have the utility envsubst.
When the number of variables in $input_file_list is very limited, you can substitute vars with awk :
awk -v top_dir="${TOP_DIR}" '{ sub(/$TOP_DIR/, top_dir); print}' "${input_file_list}"

A: I was using eval incorrectly. The solution is to use an assignment on the right side of eval as follows:
for file_path in `cat $input_file_list`
do
    eval myfile=$file_name
    echo "myfile = $myfile"
done

$myfile now has the actual expansion of the macro.


text:
Q: $ \Bbb Q [ \sqrt{2} + \sqrt{3} ] = \Bbb Q [ \sqrt{2} , \sqrt{3} ] $ Prove, that
$ \Bbb Q [ \sqrt{2} + \sqrt{3} ] = \Bbb Q [  \sqrt{2} , \sqrt{3} ]  $
I don't know the definition of
$\Bbb Q [  \sqrt{2} , \sqrt{3} ]$, can anyone help me with this?

A: First we have : $\mathbb Q(\sqrt 2,\sqrt 3)=\mathbb Q[\sqrt 2,\sqrt 3]$ because $\sqrt 2,\sqrt 3$ are algebraic over $\mathbb Q$
$\mathbb Q(\sqrt 2,\sqrt 3)$ this is the smallest field containing $\mathbb Q,$ $\sqrt 2$ and $\sqrt 3$
Since  $\sqrt 2+\sqrt 3\in \mathbb Q(\sqrt 2,\sqrt 3) $ we have $\mathbb Q(\sqrt 2+\sqrt 3)\subset\mathbb Q(\sqrt 2,\sqrt 3)$ then it suffice to prove that $[\mathbb Q(\sqrt 2,\sqrt 3):\mathbb Q]=[\mathbb Q(\sqrt 2+\sqrt 3):\mathbb Q],$ as $[\mathbb Q(\sqrt 2,\sqrt 3):\mathbb Q]=[\mathbb Q(\sqrt 2,\sqrt 3):\mathbb Q(\sqrt 2)][\mathbb Q(\sqrt 2):\mathbb Q]$  we have $[\mathbb Q(\sqrt 2,\sqrt 3):\mathbb Q]=4$ (because Irr($\sqrt 3$,$\mathbb Q(\sqrt 2))=X^2-3.$) you can easily check by calculating that : deg(Irr($\sqrt 3+\sqrt 2$,$\mathbb Q)$=4
so $\mathbb Q(\sqrt 2,\sqrt 3)=\mathbb Q(\sqrt 2+\sqrt 3)$


text:
Q: How to make iterable the returned value(s) of a function? I am trying to write a decorator that can handle various number and type of returned values, and I am having trouble to deal with numbers/iterables of numbers.
Say I want my decorator to operate "+1" on each returned values of the function it decorates. I found this way to do it, although I don't find it elegant (especially the "try/except" block, and the "return tuple(x) if len(x) >1 else x[0]" line):
# Plus-one decorator
def plus_one_decorator(func):
    """Decorator that adds one to each returned values"""
    def decorated(*args, **kwargs):
        raw_res = func(*args, **kwargs)
        # Making raw_res iterable (since it could be any length)
        try:
            raw_res = tuple(raw_res)
        except:
            raw_res = [raw_res]
        # Creating a list to store the decorated-outputs
        output_list = []
        for res in raw_res:
            output_list.append(res + 1)
        # Sugar to not return a one-tuple
        return tuple(output_list) if len(output_list) > 1 else output_list[0]
    return decorated

# Decorated func
dec_minus = plus_one_decorator(lambda x: -x)
dec_dbl_tpl = plus_one_decorator(lambda x: (x*2, x*3))

# Checking
print(dec_minus(1)) # >>> 0 (as expected)
print(dec_dbl_tpl(3)) # >>> 7, 10 (as expected)

So this does work for plain numbers, but what if I use it with a numpy.ndarray :
import numpy as np

foo = np.array([1, 1, 1])

print(dec_minus(foo)) # >>> (0, 0, 0) (! Expected array([0, 0, 0]))
print(dec_dbl_tpl(foo)) # >>> (array([3, 3, 3]), array([4, 4, 4])) (as expected)

For the second function, that returns a tuple, it does work as expected, since the raw-returned value is already a tuple (since tuple((array_1, array_2)) --> (array_1, array_2)). BUT, the ndarray array([0, 0, 0]) is converted into a tuple (0, 0, 0).
So, in the end, my question is :
is there an elegant way to make iterable the returned values of a function, when these values can be of different number and different types ?
I guess I could test the type of each returned value, but again it doesn't seem very elegant.
Cheers

A: Yes, there is.
For instance:
from collections.abc import Iterable
from copy import deepcopy
...
    # in your decorator
    if not isinstance(raw_res, Iterable):
        raw_res = [raw_res]

    output = deepcopy(raw_res)
    for i, res in enumerate(output):
        output[i] = res + 1
    return output if len(output) > 1 else output[0]

In your example you created a list of values named output_list, but you should copy all data to the output and then modify a data in it


text:
Q: Converting SVG created with d3 returns DOMException: The source image cannot be decoded for one chart but not another with exact same code I am at my wits end. The following works with one type of chart and not with another, yet the code is the same and although the error happens later I suspect it is in the SVG string.
Could that be?
I have this set up:
    <svg id="Scatter" viewBox={`-20 -20 ${width + margin.left + margin.top } ${height + margin.bottom + margin.top}`} bind:this={vis}>
    </svg>

Click to download
<canvas class = "hidden"  id="ScatterCanvas" width={resFactor*width} height={resFactor*height}></canvas>

And this convertSvg function that should return an image of the canvas with the SVG in it.
function convertSvg(vis) {
    const svgStringPrefix = "data:image/svg+xml;utf8,";

    // A string representation of the SVG
    const svgString = `${svgStringPrefix}${new XMLSerializer().serializeToString(
      document.getElementById("Scatter") //id of svg
    )}`;
    console.log('scatter', svgString);
    // A temporary image
    const svgImage = new Image();
    // console.log(svgImage.decode().then(d => d))
    svgImage.src = svgString;

    // console.log(svgImage.decode().then(d => d))

    // Runs once the temporary image is decoded
    svgImage.decode().then(() => {
      // Draw the temporary image to the canvas
      console.log("Getting this far");
      const canvas = document.getElementById("mScatterCanvas"); // id of canvas
      const context = canvas.getContext("2d");
      context.clearRect(0, 0, canvas.width, canvas.height);
      context.drawImage(svgImage, 0, 0, width*resFactor, height*resFactor);

      // Convert the canvas to a binary image blob
      canvas.toBlob((blob) => {
        // Get a URL for the blob
        const url = URL.createObjectURL(blob);

        // Make the image in the document display the blob
        const newImage = document.getElementById("ScatterImage"); //id of image
        newImage.src = url;

        // Make the link point to the blob
        const myLink = document.getElementById("ScatterLink"); //id of link
        myLink.href = url;
        window.open(url);
      });
    });
}

I appreciate any ideas of why or suggestions of what to check next, I think I've tried quite everything.
It works with several bar charts I have but not anymore with scatter charts.
I added a function that hides labels that overlap, could that be it?
I can't say for sure that's what broke it, because when I comment out the function it still doesn't work, but in the very beginning it did work without it.
I'm using svelte.
Edit: Ok this makes no sense at all, when I remove () from const svgImage = new Image(); it works.
But in the bar chart it works with () and I actually copied over the whole code.
I am so confused.


text:
Q: open infowindow on google maps marker when app launch I'm new to iOS development as well as Google Maps SDK for iOS.
I'm currently working on an iPhone application & I want to open the info window of the Google Map Markers when the app is launching. (Pop up the info window by default, without clicking on the marker balloon).
Is there any way to accomplish this task?
Here is my code:
GMSMarker *marker = [[GMSMarker alloc] init];
marker.flat = YES;
marker.appearAnimation=YES;
marker.position = CLLocationCoordinate2DMake(lt,ln);
marker.title = name;
marker.snippet = type;

[self.mapView setSelectedMarker:marker];

marker.map = self.mapView;

A: If you try to create marker in didTapAtCoordonate, you should create your marker in:
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
   //create your marker here
}];

From here: infowindow not displaying with marker in didTapAtCoordinate method

A: Where are you calling that code? You might want to try putting it in viewWillAppear or viewDidAppear. It may be that setting the selected marker doesn't work until after the map has started rendering.


text:
Q: finding similar strings in each row of two different data frame I would like to check two data set. one data has many columns (this example has two columns df1) and one data has one column (df2)
At first, I want to check the first column of df1 each row with all part of df2 if any similar part is found, then the row number of df1 and df2 is written
for example
Column 1 of df1 has two similar part of the row to df2 Q9Y6Q9 in row 3 of df1 with Q9Y6Q9 in row 4 of df2 . so the output is 3-4 , the same for others

A: Maybe you should normalize your data first. For instance, you could do:
normalize <- function(x, delim) {
    x <- gsub(")", "", x, fixed=TRUE)
    x <- gsub("(", "", x, fixed=TRUE)
    idx <- rep(seq_len(length(x)), times=nchar(gsub(sprintf("[^%s]",delim), "", as.character(x)))+1)
    names <- unlist(strsplit(as.character(x), delim))
    return(setNames(idx, names))
}

This function can applied to each column of df1 as well as the lookup table df2:
s1 <- normalize(df1[,1], ";")
s2 <- normalize(df1[,2], ";")
lookup <- normalize(df2[,1], ",")

With this normalized data, it is easy to generate the output you are looking for:
process <- function(s) {
    lookup_try <- lookup[names(s)]
    found <- which(!is.na(lookup_try))
    pos <- lookup_try[names(s)[found]]
    return(paste(s[found], pos, sep="-"))
    #change the last line to "return(as.character(pos))" to get only the result as in the comment
}

process(s1)
# [1] "3-4" "4-1" "5-4"
process(s2)
# [1] "2-4"  "3-15" "7-16"

The output is not exactly the same as in the question, but this may be due to manual lookup errors.
In order to iterate over all columns of df1, you could use lapply:
res <- lapply(colnames(df1), function(x) process(normalize(df1[,x], ";")))
names(res) <- colnames(df1)

Now, res is a list indexed by the column names of df1:
res[["sample_1"]]
# [1] "4" "1" "4"


text:
Q: Does gdal2tiles strip elevation data? I have a GEOTiff file that has elevation data associated with it .  It seems like the resulting png/jpg files I get after feeding it to gdal2tiles does not have elevation data. Same thing with the tms tiles provided by Geoserver.  Does tiling a GEOTiff file strip away the elevation data?

A: Gdal2tiles is a Python script and you can check what is does from the source code or from your own computer where the script in in plain text in the GDAL directory. Link to the trunk version is https://trac.osgeo.org/gdal/browser/trunk/gdal/swig/python/scripts/gdal2tiles.py
I am not so good in reading the code but script seems to read source data and split it into tiles in GDAL Memory format, and then a copy is written from MEM into png (row 1364).
GDAL png driver supports only byte and 16-bit unsigned data types http://www.gdal.org/frmt_various.html. I can't say directly it the script scales dataType into "byte" already when the MEM tile is created. If that happens the script should be able support 16-bit png tiles if the conversion into byte is first disabled and the source data type is 16-bit unsigned.
Nothing prevents from modifying gdal2tiles.py script to support tiles in other formats and bit depths but it requires some Python programming.
EDIT
Because it was not obvious for me from the code I made a test with a source image of type Uint16. Gdal2tiles converts also that into png tiles of type "byte".
The answer to the question is "Yes, gdal2tiles.py as the script stands at the moment creates tiles always as 8-bit per channel png images and elevation data is stripped".


text:
Q: Is it normal for suspensions to increase slightly ahead of elections? I'm participating in my first election on SE right now (specifically, the 2016 Moderator Election for Science Fiction & Fantasy), and I've noticed that a couple of suspensions that are at least partially related to the election have occurred recently.
Without getting into specifics, which, I realize, is off limits:
Is this normal?  Do elections frequently lead to escalated emotions and suspensions, or is this case unusual for the network?

A: Elections definitely led to increased flags on Stack Overflow, which might have the side effect of increased suspensions. A lot of people who are either trying to become a moderator or who are reading the requirements for the first time are encouraged to flag more during elections, so you end up with a (temporary) higher flag volume.

A: There was at least one case where a user flipped out about a particular candidate in an election and got himself suspended. In that case the suspension was handled by SE, and only after everything else they tried failed to calm down the user.
Usually we focus on the posts, not the user. This helps to keep things calm and avoids personal attacks. But in an election a certain amount of criticism of persons is allowed and welcome. It should of course be constructive, but it still happens that it doesn't stay that way, or some people just don't take that criticism well. So I'm not surprised that elections lead to occasional incidents that require suspensions.
But my impression is still that this is not a very common occurrance, it just tends to be more visible and everyone is paying closer attention at elections.


text:
Q: Javascript Discount Calculation for each item I have an existing document that has pre existing pricing. So on the page I have a bunch of elements for example price here with each one having different pricing of course.
How can I write a jquery/javascript script to take each of those prices and divide them by 24 and then append a p tag that shows that calculation, this should happen on page load.
so far i have this, just testing it on click but it gives me the same answer for each, which is the very first occurrence of the price divided by 24.
for ex if they price is 1600, or 500, or 100000 the answer it gives me is always based on 1600.
  $(".button").click(function () {
            var value = $('.price').text();
            var price = parseFloat(value)/24;
            $('.price').append('
' + price + '
');
        });

Can someone help please?
Thank you :)

A: In the above code, your use of the text() method selects only the first element with the class price.
You need to loop over all the elements with the class price.
  $(".button").click(function () {
            $('.price').each(function(index, el) {
                var price = parseFloat($(el).text())/24;
                $(el).append('
' + price + '
');
            });
        });

A: This is because of var value = $('.price').text(); it selects the first price it finds.
You should use a variable in the event handler to get access to the item that was clicked on. Then get the price from that.
Assuming the button has a descendant with a price class :
$(".button").click(function (e) {
    var value = $(event.currenttarget).find(".price")
    ...
}

A: I think something like the following implementation should work:
document.querySelectorAll('.button').forEach(element => {
  const priceElement = element.querySelector('.price');

  const price = parseFloat(priceElement.textContent) / 24;

  const childElement = document.createElement('p');
  childElement.textContent = price;

  priceElement.appendChild(childElement);
});

A:

 $(".button").click(function () {
             $('.price').each(function(p){
           $('.price')[p].innerHTML =  $('.price')[p].innerHTML/24});

        });

240

480


text:
Q: how to addition new value with answer value in JQuery? I am trying to add new value in eval value but it replaces it. How can I add, subtract, divide and multiply with answer value?

$(document).ready(function() {
  var evaluated = false;
  $(".oprator").click(function() {
    const val = evaluated ? $(this).text() : ($(".input").val() + $(this).text())
    $(".input").val(val)
    evaluated = false;
  });

  $("#butnplus").click(function() {
    $(".input").val($(".input").val() + $("#butnplus").text())
  });
  $("#equal").click(function() {
    $(".input").val((eval($(".input").val())))
    evaluated = true;
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<input type="text" class="input">
<button class="oprator" id="butn4">4</button>
<button class="oprator" id="butn6">6</button>
<button id="butnplus">+</button>
<button id="equal">=</button>


text:
Q: Error message while initializing Anaconda I'm having the following error message while trying to initialize the Anaconda Application. Would appreciate if you anyone guide me to solve the issues and explain the cause of the error message. Thanks in advance. And appreciate for your time and energy. :)
Ubuntu Version: 22.04
anaconda_initialization_error


text:
Q: Some margin I don't know where is  I'm creating a website (http://mat3.us/ba/) and as you can see If you access it there is some kind of border, I don't know, It's like the content width is not 100%, only the menu. I tried to find what It is but I couldn't.

A: It looks like you're using Bootstrap. That issue happens when you don't have containers or rows nested correctly.
In your case, the issue is in section#contact. The first div inside #mapa is a .container, but its sibling is a .row. That messes up the Bootstrap grid system, and causes your layout issue.
I figured this out by going into the browser's Inspect Element, and deleting elements (in the Source Tree, you can select and element and hit Delete/Backspace to remove it) until the issue cleared up. I then Undo the delete, and delete stuff inside it. Repeat until the issue has been identified.
This link does a great job of explaining the grid system in more detail.


text:
Q: Javascript array, for every increment create a nested array I have an array which always has a length of 50, which looks like so:
var array = [
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  ...
];

What I need to do is loop through that array and create a nested array every 5 items, so the end result will be array containing 10 nested arrays which contain 5 items each, looking something like:
var array = [
  [
    'item',
    'item',
    'item',
    'item',
    'item'
  ],
  [
    'item',
    'item',
    'item',
    'item',
    'item'
  ],
  [
    'item',
    'item',
    'item',
    'item',
    'item'
  ],
  [
    'item',
    'item',
    'item',
    'item',
    'item'
  ],
  ...
];

I've tried quite a few things which always ends up in a complete mess of spaghetti loops, any help would be greatly appreciated. I'm even open to using jQuery if needs be.

A: var array = ['item','item','item','item','item','item','item','item','item','item','item','item','item'];
var new_arr = [];
while(array.length) new_arr.push(array.splice(0,5));

console.log(new_arr);

A: Just have one for loop.
var temp=[], newArray=[];
for(i=0;i<array.length;i++){
    temp.push(array[i]);
    if(temp.length==size){//size in your case = 5
        newArray.push(temp);
        temp=[];
    }
}


text:
Q: When using Microsoft Access to collect data by using email messages, how do I change the from email address? I am using Microsoft Access to collect data by using email messages, as described here:
https://support.office.com/en-US/article/Collect-data-by-using-e-mail-messages-800DAEF3-86D3-4B62-9A2C-A4E41A14FA98
The from address in all of the emails sent by Access is my individual address, but I would like to send the emails from the team's group account.
Is there a way I can change the from address?


text:
Q: node.js redis select and smembers in aync I have a lot of pain with asyncronous call in node.js. I understand that I must enjoy it, but actually I hate it, just because node.js force you to use it, and there is no another option.
I try to run smembers on different databases. So here I want to be sure that I use all 3 databases therefore I use _.after. However it doesn't work.
var redisfetcher = function(string, callback1)
{
   var retrieved = []

    var callback = function(){
        callback1(retrieved)
    }

    var afterAll = _.after(3,callback)

    for (var col=0; col<=2; ++col) {
        client.select(col, function() {
            client.smembers(string, function (err, replies) {
             if(!err){
                retrieved.push(replies)
                }
            })
        afterAll();
        })
    }

redisfetcher("offer", function(returnValue) {
    console.log(returnValue)
    })

I would appreciate if you could help me.
I would appreciate even more if you could show how to run the following code in sync mode.

A: Use async module.
var async = require('async');

async.mapSeries([0, 1, 2], function (db, done) {
    // Here `db` will be `0`, or `1` or `2`, i.e. each element of the array.
    // The `done` is an internal callback used by the `async` module
    // to track whether a particular element of the array is completed
    // to be processed. When you're "done" consuming the `db` element of the
    // array, you must call `done` to indicate that `async` can now give you
    // yet another element to consume, if there is any left to process.
    // When all elements are processed, `async` calls the final function
    // passes to it as the last argument. For more information refer to
    // very detailed docs of `async` module at
    // https://github.com/caolan/async#mapSeries.
    async.waterfall([
        function (cb) {
            client.select(db, cb);
        },
        function (cb) {
            client.smembers(string, cb);
        }
    ], done);
}, function(err, resultArr) {
    err && console.trace(err);

    // `resultArr` now contains 3 replies.
});

Notice the above code calls mapSeries which is sequential (don't confuse with synchronous), not parallel as opposed to map. I suggest using a different Redis connection for each DB in your case, because if called in parallel, such async calls may conflict due to selecting different databases. This may result in running the command against the same database instead of a different as intended. A single connection is ok if you run multiple command against the same database.
For connection pooling, use node-pool.


text:
Q: How to send multiple data from one fragment to another simultaneously by clicking a button? My problem is how to update all fragment simultaneously when getting the result of string from other fragment. There are 3 fragment name MainFragment , Menu4 , Menu5.
For example, I have 2 variable string array in MainFragment. String array A and String array B. Because I am using a fragment , I will use bundle which will transfer the string to Menu4 and it WORKS.
This is the code for the bundle in MainFragment.When button click ,it will send to other fragment.
 FragmentTransaction transection = getSupportFragmentManager().beginTransaction();
                Menu4 mfragment=new Menu4();
                //using Bundle to send data
                Bundle bundle=new Bundle();
                bundle.putString("email", populateRpmData1[0]);
                mfragment.setArguments(bundle);
                transection.replace(R.id.content_frame, mfragment);
                transection.commit();

As you can see , populateRpmData1[0] is my String array A which will transfer to Fragment Menu4.But how can I do when button click, String array B also will transfer simultenously to other fragment called Menu5 ?


text:
Q: using git for images I'm considering using GIT or our family photos. The scenario is that both me and my girlfriend uses digital cameras, upload the photos to each our own computer. But still want to organize the photos into folders for different events, and have that organization replicated between our two computers.
By having the GIT repository master on our central server we can also view the images from our TV or access them through FTP if we need them while away from home.
This implies a structure where the images won't change very often. Rarely they'll get moved around. The most common action will be to add folder with new images to the repository and commit it to the master branch so the images are avaliable to everyone.
Now the question: How will the images be handled in Git? Will the Git repository be bloated up by maintaining an image for each version of the repository? Or will it only keep history of an image when it actually changes its content?
The difference in diskspace usages should be quite large for the two given scenarios.

A: I think you should consider using rsync. From what I understood you just want to synchronize your network folders, right? Is there a real need for versioning?

A: Every object in your repository will be stored once and referenced by it's SHA1 sum.  This means that placing three copies of a 100KB image in two directories of your repo will use 100KB, plus some inconsequential amount of overhead.
The same applies to pushing, pulling and branching: So long as the SHA1 sum of the image doesn't change, git will never store a second copy or have to move more than one copy across the network.
You'll be using twice the disk space on each machine though: Git maintains a copy of all it's data in a hidden .git directory in the root of your repo.

A: It is smart enough to only track changes and not create a full replica of the image repository


text:
Q: Running queries in BigQuery without being a project User It seems the only way to share a dataset so that another person can run queries on the tables from the dataset is to make that person a Project user. See permissions
This means that the user would have access to all the datasets on the project. This seems to me that is is highly inconvenient. Am I missing something?

A: For user to run query - user need to have bigquery.jobs.create permission
If your user already has this permission in any other project - you can just simply share your dataset with this user with Can View Access Level
If user is new and does not have yet bigquery.jobs.create in any other project - you can just add this user to your project with this permission only.

And still you need add this user to ACL for that
specific dataset
Important: Please also note - if you give user permission to create jobs in your project  - you will be billed for respective queries.
If user has its "own" project and only has view access to you data - in this case bill goes to user's project


text:
Q: Scala Parallel Print Hanging the console I am new to this Scala world and I am trying some exercises from a book. So, I have an example that print a vector in sequential and parallel fashion. The former works perfectly and the later hangs the console.
Code
val v = Vector.range(0, 10)
v.foreach(println)

Code output
0123456789

But if I use the same code, but instead of using foearch, use par, it freezes the console
val v = Vector.range(0,10)
v.par.foreach(println)

The book I am using says that the output should be something like:
5678901234

But it hangs and the program never finishes.
Can someone explain me why?

A: It is better to post whole the program wich is hanged.
I've just tested it with scala 2.12.8 and jvm 1.8.0_161:
object MainClassss {
  def main(args: Array[String]): Unit = {
    val v = Vector.range(0,10)
    (0 to 999999).foreach(_ => v.par.foreach(println))
  }
}

the program has executed well with output and hasn't hanged.
If your program reproduced the aforementioned issue you need to take a thread dump by:
$ jstack <PID>

where PID is the process id.
Or you can take by jvisualvm jvm tool.
You can analyze why your program is hanged owing to caught thread dump if the program has some code blocking it from execution.


text:
Q: strait query produces results. sp_execute sql does not Maybe I'm going blind.  I can't figure out why this query
select * from sys.tables where name = N'foobar'

produces the row for that table but
exec sp_executesql N'
select * from sys.tables where name = N''@TableName''
', N'@TableName nvarchar(128)',@TableName=N'foobar'

returns no rows.
What am I missing?

A: No quotes required in your query.
exec sp_executesql N'select * from sys.tables where name = @TableName', N'@TableName nvarchar(128)',@TableName=N'foobar'
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql


text:
Q: How can I make ID field in MySQL immutable Is there are way to make ID fiels in MySql immutable?
It's possible in postgreSQL using PGAdmin for example.
ID field sets as primary key and auto incr but can be changed manually.


text:
Q: Internet connection gets unstable when Windows laptop joins I recently started renting out a room to someone who has a Windows-laptop.
Everything we have is Apple (2 Macbooks, 1 iPad, 2 iPhones, 1 iMac) connecting to an Apple Airport Extreme which extends the internet from the modem/router we got from the ISP.
The network is perfectly stable and I have no problems using it in the other apartments in this building. (3 apartments in total).
But since the new renter moved in, the Internet gets really unstable as soon as his computer connects to it. It's not the WiFi-signal, because that works fine (I can stream from one device to the other without a problem when the internet is "down"), but when he connects his computer, the Internet just stops working about every 10 minutes. It takes a minute before the internet is back up again.
One weird thing: Torrents keep on downloading and uploading, even though the Internet is "down" (I can't browse to any page while it's "down").
I tried Google, but the results all point me to Windows laptops crashing when they connect to the WiFi, not the Internet itself. I checked and it's on every device using my Internet connection. Also my Wii U and my GF's Kindle (I have nothing connected through an Ethernet-cable, so I can't say if that works). Also, whenever classmates come over to do homework, they can connect without a problem and without killing the Internet connection.
I hope someone can help me out, because I can really not live with an unstable Internet-connection for 6 months, haha! Now using my iPhone for tethering, but I would much rather just use the WiFi.


text:
Q: Drive boots in desktop, not in laptop, can not find OS We have a laptop that quit working.
We removed the internal SSD and placed it in a desktop and it booted cleanly to Windows 10.
We placed it into 3 different laptop models, and it would not boot.
The BIOS reports that it can not find an OS.
Placed back into another desktop, it boots perfectly.
Let me clarify here... the OS does not fail.
The OS never gets a chance to start.  The BIOS reports that no OS is found.  Something in the MBR?  Or an issue with UEFI vs legacy?  Or ...?
We tried making a clone onto a mechanical hard drive, and it behaves the same way.
We tried turning on Legacy Support in the BIOS on one laptop, and it made no change.
We tried a program to restore the MBR on the clone, and it didn't help.
At this point we have no idea what else to try.  We have read up on the boot process, and are overwhelmed (we don't understand it... it seems overly complicated).
The attached images show what Aomei's partition assistant knows about the partitions.
Any help would be appreciated.  We want the disk to run again in a Laptop.

(My friend and I volunteer with our retirement community to help people with their computer problems.  The original laptop belongs to a resident.  The computers we have tried it in are ones that have been donated to the community's associated non-profit organization for refurbishment and resale.)
Thanks,
Mark


text:
Q: MVC IoC Construtor sem parametros Ola.
Minha aplicação esta disparando um erro ao tentar criar um novo item.
Estou recebendo esta mensagem de erro: Nenhum construtor sem parâmetros foi definido para este objeto.
Mas minha classe controller possui esse construtor sem parametros:
public AlocacaoController()
{

}

public AlocacaoController(IAlocacaoService alocacaoService, IProfissionalService profissionalService, IContratoService contratoService)
{
            _alocacaoService = alocacaoService;
            _profissionalService = profissionalService;
            _contratoService = contratoService;
            _alocacaoMapper = new AutoMapperAlocacao();
            _contratoMapper = new AutoMapperAlocacaoContrato();
}

Esse erro ocorre antes de acionar este metodo.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(AlocacaoViewModel model)
{
    try
    {
        //Carregar lista de clientes
        model.ListaContratos = new SelectList(_contratoService.ListarAtivos(), "ContratoID", "Nome", model.ContratoID);
        model.ListaProfissionais = new SelectList(_profissionalService.ListarAtivos(), "ProfissionalID", "Nome", null);

        if (ModelState.IsValid)
        {

        }
        return View(model);
    }
    catch
    {
        return View();
    }
}

Todas as interfaces estão configuradas na minha clase para injeção de dependência:
private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind(typeof(IBaseService<>)).To(typeof(BaseService<>));
            kernel.Bind(typeof(IAlocacaoService)).To(typeof(AlocacaoService));
            kernel.Bind(typeof(IClienteService)).To(typeof(ClienteService));
            kernel.Bind(typeof(IClienteIpService)).To(typeof(ClienteIpService));
            kernel.Bind(typeof(IClienteLocalService)).To(typeof(ClienteLocalService));
            kernel.Bind(typeof(IContratoService)).To(typeof(ContratoService));
            kernel.Bind(typeof(ILancamentoService)).To(typeof(LancamentoService));
            kernel.Bind(typeof(IProfissionalDispositivoService)).To(typeof(ProfissionalDispositivoService));
            kernel.Bind(typeof(IProfissionalService)).To(typeof(ProfissionalService));
            kernel.Bind(typeof(IUsuarioService)).To(typeof(UsuarioService));

            kernel.Bind(typeof(IBaseRepository<>)).To(typeof(BaseRepository<>));
            kernel.Bind(typeof(IAlocacaoRepository)).To(typeof(AlocacaoRepository));
            kernel.Bind(typeof(IClienteRepository)).To(typeof(ClienteRepository));
            kernel.Bind(typeof(IClienteIpRepository)).To(typeof(ClienteIpRepository));
            kernel.Bind(typeof(IClienteLocalRepository)).To(typeof(ClienteLocalRepository));
            kernel.Bind(typeof(IContratoRepository)).To(typeof(ContratoRepository));
            kernel.Bind(typeof(ILancamentoRepository)).To(typeof(LancamentoRepository));
            kernel.Bind(typeof(IProfissionalDispositivoRepository)).To(typeof(ProfissionalDispositivoRepository));
            kernel.Bind(typeof(IProfissionalRepository)).To(typeof(ProfissionalRepository));
            kernel.Bind(typeof(IUsuarioRepository)).To(typeof(UsuarioRepository));
        }

Stack Trace:

[MissingMethodException: Nenhum construtor sem parâmetros foi definido
  para este objeto.] System.RuntimeTypeHandle.CreateInstance(RuntimeType
  type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached,
  RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
  System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean
  skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113
  System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly,
  Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
  +206 System.Activator.CreateInstance(Type type, Boolean nonPublic) +83 System.Activator.CreateInstance(Type type) +11
  System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext
  controllerContext, ModelBindingContext bindingContext, Type modelType)
  +197
[MissingMethodException: Nenhum construtor sem parâmetros foi definido
  para este objeto. Object type 'System.Web.Mvc.SelectList'.]
  System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext
  controllerContext, ModelBindingContext bindingContext, Type modelType)
  +233 System.Web.Mvc.DefaultModelBinder.BindSimpleModel(ControllerContext
  controllerContext, ModelBindingContext bindingContext,
  ValueProviderResult valueProviderResult) +285
  System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext
  controllerContext, ModelBindingContext bindingContext) +299
  System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext
  controllerContext, ModelBindingContext bindingContext,
  PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
  +17 System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext,
  PropertyDescriptor propertyDescriptor) +382
  System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext
  controllerContext, ModelBindingContext bindingContext) +122
  System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext
  controllerContext, ModelBindingContext bindingContext, Object model)
  +55 System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext
  controllerContext, ModelBindingContext bindingContext) +1230
  System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext
  controllerContext, ModelBindingContext bindingContext) +348
  System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext
  controllerContext, ParameterDescriptor parameterDescriptor) +338
  System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext
  controllerContext, ActionDescriptor actionDescriptor) +105
  System.Web.Mvc.Async.<>c__DisplayClass21.b__19(AsyncCallback
  asyncCallback, Object asyncState) +743
  System.Web.Mvc.Async.WrappedAsyncResult1.CallBeginDelegate(AsyncCallback
  callback, Object callbackState) +14
System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback
  callback, Object state, Int32 timeout) +128
  System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext
  controllerContext, String actionName, AsyncCallback callback, Object
  state) +328 System.Web.Mvc.Controller.b__1c(AsyncCallback
  asyncCallback, Object asyncState, ExecuteCoreState innerState) +25
  System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback
  callback, Object callbackState) +30
System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback
  callback, Object state, Int32 timeout) +128
  System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback,
  Object state) +556 System.Web.Mvc.Controller.b__14(AsyncCallback
  asyncCallback, Object callbackState, Controller controller) +18
  System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback
  callback, Object callbackState) +20
System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback
  callback, Object state, Int32 timeout) +128
  System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext,
  AsyncCallback callback, Object state) +420
  System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext
  requestContext, AsyncCallback callback, Object state) +16
  System.Web.Mvc.MvcHandler.b__4(AsyncCallback asyncCallback, Object
  asyncState, ProcessRequestState innerState) +52
  System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback
  callback, Object callbackState) +30
System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback
  callback, Object state, Int32 timeout) +128
  System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase
  httpContext, AsyncCallback callback, Object state) +369
  System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext,
  AsyncCallback callback, Object state) +48
  System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext
  context, AsyncCallback cb, Object extraData) +16
  System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
  +103 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

A: Descobri o problema.
O funcionamento do ListBox e um pouco diferente.
Quando você utiliza o metodo ListBoxFor, e necessario passar duas listas.
Uma que armazena os itens que serão apresentados na lista e outra lista que armazena os valores dos itens selecionados.
//Itens da lista
public SelectList ListaProfissionais { get; set; }
//Selecao de valores
public IEnumerable<string> Profissionais { get; set; }

@Html.ListBoxFor(model => model.Profissionais, Model.ListaProfissionais, new { style = "width:250px" })

Eu estava passando a mesma lista nos dois metodos.
Por isso o erro ocorria. Só que pela descrição do erro apresentado fica meio difícil adivinhar o que é. Tive que apanhar um pouco para descobrir.

A: Provavelmente sua classe AlocacaoViewModel possui um construtor, mas está sem um construtor padrão.
Adicione a ela um construtor padrão, depois teste novamente:
public AlocacaoViewModel()
{

}


text:
Q: Recording sound from TV tuner card thorough Alsa driver on Ubuntu I have a TV tuner card with its output connected to the CD in of an integrated sound card. Video is OK, and the sound also gets thorough (to the line out) when running xawtv, for example. However, I found no ways yet for recording it.
I'm running Ubuntu 10.10 with ALSA drivers. Pulseaudio was running in the beginning, now it doesn't, but it doesn't seem to make much difference.
Some things I've already tried:

*

*capturing with VLC, using plughw:0,0 as the audio capture device. (Result: no sound track at all in the resulting video.)

*arecord, then aplay.

*alsamixer. The capture source is set to "CD" (and on the input side it's also "CD" where I can effectively modify the volume for audio going through...), but still no result.

Do you have any ideas what else could I try? (I seem to have run out of them...)

A: From my experience with ALSA on Natty (11.04), you can get a list of the input devices with the command arecord -l (dash lowercase-L).  I've used this successfully to identify the ALSA device for my capture card (pcHDTV HD5500) and play live TV with sound from the analog capture using mplayer:
mplayer tv://6 -tv alsa:adevice=hw.2,0:immediatemode=0:audiorate=32000:forceaudio

where the hw.2,0 came from the output of arecord -l (it listed "card 2: CX8801 [Conexant CX8801], device 0: CX88 Digital [CX88 Digital]", thus "2,0"; you want the "hw" device for this, so it should be "hw:2,0" for ALSA, but mplayer wants the colon replaced with a period).
To my chagrin, I do not know how to reproduce the effects of these settings in MythTV.  I would welcome some help with that.

A: I've used MythTV for recording TV on Ubuntu in the past and it works quite well. You can get some workable configurations on https://help.ubuntu.com/community/MythTV
One year back, I had seen it working at a cable TV operator and it worked pretty well.

A: After another round of experimenting, here is the answer: buy a better sound card.
As it turned out, the integrated sound chip on my motherboard had a buggy linux driver that wasn't able to record audio at all. Under Windows, it worked somehow, but probably this was the reason for the half-second delay between video and audio there... (upgrading to Ubuntu 11.10 didn't help, either.)
Everything works perfectly now with an SB Live!, bought for $12... What I use is:
mencoder tv:// -tv driver=v4l2:alsa=1:adevice=hw.1:norm=PAL-BG:input=1:width=768:height=576 (...)

(the rest of the line is only about output codecs and filters.)


text:
Q: find and replace word with elasticsearch [elasticsearch] How can I find and replace partial data in elasticsearch?
I have tried update_by_query. However, it replaces the whole value in a certain field which is not what I am looking for. What I am trying to achieve is to find 'cat' in a sentence and replace it with 'dog'
"this is a cat" ===> "this is a dog"
I have tried the following query:
        //     body: {
        //         script: {source: ctx._source.aa = params.term,
        //                 params: {term: dog},
        //                 lang: "painless"
        //         },
        //         query: {term: cat}
        // }};

A: You can use replace method in script to do this
POST {index_name}/{type}/{id}/_update
{
  "script" : {
    "source": "ctx._source.aa=ctx._source.aa.replace(\"cat\", params.term)",
    "params": { "term": "dog" },
    "lang": "painless"
  }
}

NOTE: The script syntax uses Elasticsearch 6.x.x


text:
Q: Quantifying similarity between two representation methods Given, a set of entities, which are represented in two different representation spaces. Is there any existing way to quantify how similar two representation spaces are i.e. to what extend, order of closeness between points is preserved?
Given: set of entities $(e_1, e_2, e_3 , \ldots, e_n)$, corresponding representations in $j$-dimensional space $(v_1, v_2, v_3 , \ldots, v_n)$ corresponding representation in $k$-dimensional space $(u_1, u_2, u_3 , \ldots, u_n)$
Output: Measure of similarity between $j$-dimensional space and $k$-dimensional space

A: If the two different representations or feature vectors are related by some output/behavioral function, you could try representation dissimilarity matrices (RDMs), which have been used in the field of computational neuroscience to compare artificial neural network feature representations with that of organic brains via comparing the similarity of response patterns to varying stimuli in each type of modality (making the final comparison between feature vectors agnostic to their dimensionality). Here are a couple of papers that implement that approach:

*

*https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2605405/

*https://www.ncbi.nlm.nih.gov/pubmed/25375136
From the Khaligh-Razavi & Kriegeskorte paper (2nd link):
"RSA enables us to relate representations obtained from different modalities (e.g. computational models and fMRI patterns) by comparing the dissimilarity patterns of the representations. In this framework representational dissimilarity matrices (RDMs) are used for making the link between different modalities. RDM is a square symmetric matrix in which the diagonal entries reflect comparisons between identical stimuli and are 0, by definition. Each off-diagonal value indicates the dissimilarity between the activity patterns associated with two different stimuli. RDM summarizes the information carried by a given representation from an area in the brain or a computational model.
We had 96 stimuli, of which half were animates and the other half were inanimates. To calculate the RDM for a brain region or a computational model, a 96×96 matrix was made in which each cell was filled with the dissimilarity value between the response patterns elicited by two stimuli. For each pair of stimuli, the dissimilarity measure was 1 minus the Pearson correlation between the response patterns elicited by those stimuli in a brain region or a computational model."


text:
Q: Redirect from visualforce to another without using apex controller Is it possible to invoke a visualforce page from another visualforce, without using apex controller?

A: Yes, if you use an action that resolves to a URL, you can redirect. Here's an example:
<apex:page>
  <apex:form>
    <apex:commandButton value="Go to page 2" action="{!URLFOR($Page.page2)}" />
  </apex:form>
</apex:page>

You can use this for any attribute that expects an action.

A: Yes, you can using client side redirection methods using window,location objects in javascript.
  Worst case - not advisable you can use anchor tags to redirect with relative urls

A: Thanks sfdcfox it worked.
Freaker87 proposed a solution using javascript. What is the best approach: using native SF VF tags or to use javascript?
I think Javascript in VF is less save because it could expose (for example in the case of SF public sites) to the public internal links and code if we use browser developer console. Is it true what I'm saying?


text:
Q: Storing large text containing functions and hyperlinks in resource file Please help me I am struggling with one issue that I am not very much familiar with that is using resource file in asp.net.
I am working on code in asp.net which is checking multiple if conditions in business layer class and on the basis of if conditions, it should display pargraphs of information text to users in either english or french.
The text contains date formatting functions, anchor tags and onclick events of anchor tags.
Example is:
if((a=b)&&(c=a))
{

    mpus odio feugiat ac. Nulla blandit dolor vitae

  ccumsan in sit amet erat. Quisque ac nulla tempus, maximus risus sed, dapibus arcu. Nullam nec enim tellus.
    Click here ctus aliquam, eu lacinia.
eget nibh est. In eu bibendum mi. Quisque quis est a risus tincidunt gravida. Morbi id finibus magna. Aene

m et lectus aliquam, eu lacinia elit viverra. Donec a libero sed sem vestibulum posuere. Proin tristique enim purus click heres est a risus tincidunt gravida. Morbi. m et lectus aliquam, eu lacinia elit viverra. Donec a libero sed sem vestibulum posuere. Pr

     Nulla blandit dolor vitae

    Click here  Donec a libero sed sem vestib

tudin non lacus. In hac habitasse platea dictumst. Donec molestie efficitur ante eget  <%= FormatDateTime(oRs("ExpiryDate"),1) %>tudin non lacus. In hac habitasse platea dictumst. Donec molestie efficitur ante eget
}
else if
{
}

I want to store this result text to resource file. Such that, if a condition is true, I should pass the keys of resource file to aspx file. But, I am sure how to achieve this?
Should I store the complete paragraph into resource file and pass a single key back to label in aspx file then, how would anchor tag and functions would work?
OR should I break it into parts? If I break it into different keys, how should I pass the resource keys back to aspx file and what should I do with date formatting functions and hyperlinks?
Another question is on passing back result to aspx file, should I display paragraphs of text in label text?
Please help.

A: You should break it up.
Static text resources should go in your .resx file, and can be retrieved using a bit of c# code (e.g. GetString).  Normally you should not store code in a resource file, as it will not be validated, compiled, or minified in there; plus, there isn't much point, as code does not need any localization support (Javascript in German is exactly the same as Javascript in English).
ASP markup and inline server-side code should go in .aspx files.  Also, static HTML should usually go into the .aspx file too (just omit the runat="server" tag).  It is OK to store some text there if you think your application will never need multi-lingual support, but it is better to use resource files if you can.
Javascript code in the best case should go in separate .js files and referenced from your page, e.g. like this

If you absolutely require inline Javascript, you can include it in the .aspx file, or add it via c# codebehind, using the ClientScriptManager.


text:
Q: Check that a link has been clicked I would like to keep track of how many times a certain link in Google Spreadsheets has been clicked. I have been searching but I can't seem to be able to find how to check whether a link has been clicked or if it is possible to attach onclick event on a link.

A: A quick solution is to use the Google URL shorten service for the links. This page gives you the number of clicks per link.

A: its not possible, you cant detect cell or link clicks.
Two possibilities here:
One way is to have a server (or an apps script service) be the link "proxy" and redirect to the final site as in:
script.google.com/.../exec?url=myurl.com
your script tallies the hit and then redirects the user. redirecting without an extra click might not be possible with apps script htmlService but its possible on your own server.
you can make the urls look pretty by using =hyperlink in the cells so users dont see the long url (until click)
Another way if you have control of the links you are pointing to is to use analytics on those pages. You can use the referer to tally views that came from a spreadsheet click, or you can explicitly add parameters to each url so that youcan later filter those comming from your sheet.


text:
Q: datepicker in dynamic data Any help is appreciated.
I'm new to Dynamic Data. I want to users be able use datepicker when filling date fields. I have a date picker component which is a dll file. How can I use it in Dynamic Data?

A: which dll are you using?
I used the AjaxControlToolkit.dll in my project. when you register this file, you get an option to "Add Extender" on every textbox you add to your page among which there is datepicker extension..
alternatively you can use jquery... to check this out, you may visit http://jqueryui.com/demos/

A: Create a custom Dynamic Data Filter (called something like "DatePickerFilter") which implements the datepicker of you choice : (jQUery, Ajax, asp.net, etc.)
Then apply metadata on the column to reference that filter like so
[FilterUIHint("DatePickerFilter")]
[Display(Name = "Date of Enrollment", AutoGenerateField = true, AutoGenerateFilter = true)]
public object EnrollmentDate { get; set; }


text:
Q: How can I stop my MIPS .data section's char variables from being overwritten? In my MIPS program's .data section, I define two char variables, d and h.
.data
d:  .word
h:  .word

In my .text section, I attempt to set the value of d to 'i' and the value of h to 'k'.
.text

#setting d = to 'i'
la $s0, d
li $s1, 'i'
sb $s1, 0($s0)

#setting h =  to 'x'
la $s0, h
li $s1, 'x'
sb $s1, 0($s0)

However, when I print out the value of d and the value of h afterward, they are both 'x'.
#printing d
lb $a0, d
li $v0, 11
syscall

#printing h
lb $a0, h
li $v0, 11
syscall

I seem to be overwriting the value of 'i.' What am I doing incorrectly?

A: You never give d and h initial values, so no space is reserved for them, hence they both have the same address.
You can see this by looking at the addresses that are used after you assemble in MARS. In QtSPIM this wouldn't even assemble because it requires you to specify an initial value.
To fix this, change those two variable declarations to
d:  .word 0
h:  .word 0


text:
Q: Is it possible to check progress of URLconnection.getInputStream()? I want to check progress of downloading file by URLconnection. Is it possible or should I use another library? This is my urlconnection function:
public static String sendPostRequest(String httpURL, String data) throws UnsupportedEncodingException, MalformedURLException, IOException {
    URL url = new URL(httpURL);

    URLConnection conn = url.openConnection();
    //conn.addRequestProperty("Content-Type", "text/html; charset=iso-8859-2");
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "ISO-8859-2"));
    String line, all = "";
    while ((line = rd.readLine()) != null) {
        all = all + line;
    }
    wr.close();
    rd.close();
    return all;
}

I understand that whole file is downloaded in this line (or worng)?:
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "ISO-8859-2"));

So is it possible to do this in this code?

A: Just check if the HTTP Content-Length header is present in the response.
int contentLength = connection.getContentLength();

if (contentLength != -1) {
    // Just do (readBytes / contentLength) * 100 to calculate the percentage.
} else {
    // You're lost. Show "Progress: unknown"
}

Update as per your update, you're wrapping the InputStream inside a BufferedReader and reading inside a while loop. You can count the bytes as follows:
int readBytes = 0;

while ((line = rd.readLine()) != null) {
    readBytes += line.getBytes("ISO-8859-2").length + 2; // CRLF bytes!!
    // Do something with line.
}

The + 2 is to cover the CRLF (carriage return and linefeed) bytes which are eaten by BufferedReader#readLine(). More clean approach would be to just read it by InputStream#read(buffer) so that you don't need to massage the bytes forth and back from characters to calculate the read bytes.
See also:

*

*How to use java.net.URLConnection to fire and handle HTTP requests?

A: Wrap it in a javax.swing.ProgressMonitorInputStream. But note that Java may buffer the entire response before it starts delivering it to the stream ...

A:     BufferedReader rd = new BufferedReader(new InputStreamReader(new FilterInputStream(conn.getInputStream())
    {
        public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException
        {
            int count = super.read(buffer, byteOffset, byteCount);
            // do whatever with count, i.e. mDownloaded += count;
            return count;
        }
    }, "ISO-8859-2"));


text:
Q: How to declare several properties on one line I'm developing a class with several lateinit properties of one type. I think it's too verbose to declare each of them on separate line like this:
lateinit var a: String
lateinit var b: String

so I would like to declare them on one line like this:
lateinit var b, c: String // error: Property getter or setter expected

But I get an error Property getter or setter expected. Is there any way to declare several properties on one line in Kotlin?

A: No, there is no way to do that. Declaring multiple properties on the same line is frowned upon by many Java style guides, so we did not implement support for that in Kotlin.

A: You can use kotlin's destructuring declaration, but it doesn't work for lateinit prefix.
var (a, b, c, d) = listOf("fly", 23, "slow", 28)
println("$a $b $c $d")

It is a workaround and creates unnecessary list initialization but it gets the job done.

Also you won't be able to define variable types yourself but the type inference is automatically done when using destructuring declarations.

A: Looking at the grammar this is not possible:
property (used by memberDeclaration, declaration, toplevelObject)
  : modifiers ("val" | "var")
      typeParameters? (type "." | annotations)?
      (multipleVariableDeclarations | variableDeclarationEntry)
      typeConstraints
      ("by" | "=" expression SEMI?)?
      (getter? setter? | setter? getter?) SEMI?
  ;

You can only do destructing declarations with:
val (name, age) = person

A: If you want to initialize multiple fields with the same value, you can do something like this:
val (x, y, z) = List(3) { 1 }
val (x, y, z) = List(3) { "Hello" }
and so on.


text:
Q: Make part of datalabels bold in ChartJS I use chartjs for the charts and chartjs-plugin-databels for the data labels within each bar.
I need make value of line bold and leave the first part unchanged.
I try find solution in documentaion:
https://chartjs-plugin-datalabels.netlify.app/guide/labels.html#multiple-labels and https://www.chartjs.org/docs/latest/charts/bar.html, but there is not result.
Pictures:
It must look.
vs
It looks.
My code
import _ from "lodash";
import { Bar } from "react-chartjs-2";
import ChartDataLabels from "chartjs-plugin-datalabels";

const options = {
  indexAxis: "y" as const,
  responsive: true,
  elements: {
    bar: {
      borderWidth: 1,
    },
  },
  scales: {
    y: {
      ticks: {
        display: false,
      },
      grid: {
        display: false,
      },
    },
    x: {
      grid: {
        borderDash: [10, 10],
      },
    },
  },
  plugins: {
    datalabels: {
      anchor: `start` as "start", import _ from "lodash";
      align: `end` as "end", import _ from "lodash";

      formatter: function (value: any, context: any) {
        return (
          context.chart.data.labels[context.dataIndex] +
          ": " +
          context.dataset.data[context.dataIndex]
        );
      },
    },
    legend: {
      display: false,
    },
    title: {
      display: false,
    },
  },
};

const labels = [
  "Some label 1",
  "Some label 1",
  "Some label 1",
  "Some label 1",
  "Some label 1",
  "Other",
];

const data = {
  labels,
  datasets: [
    {
      data: labels.map(() => Math.floor(Math.random() * 10000)), // random values
      maxBarThickness: 28,
      inflateAmount: 3,
    },
  ],
};

const HorizontalBarChart = () => {
  return (
    <Bar options={options} data={data} plugins={[ChartDataLabels]} />
  );
};

What information to add to make the question clearer?


text:
Q: Spring Async: How to call spring hateoas ControllerLinkBuilder inside Async method I am calling ControllerLinkBuilder.linkTo method inside a spring Async method and it fails to find the current request.
service.setUrl(linkTo(Controller.class, Controller.METHOD_GET,
                headers.getFirst(HEADER_SOURCE), id).toString());

Exception:
java.util.concurrent.ExecutionException: java.lang.IllegalStateException: Could not find current request via RequestContextHolder
Caused by: java.lang.IllegalStateException: Could not find current request via RequestContextHolder

A: Complementing the _Manan reponse, You can set the attribute inheritance to true on your properties file. Please add the following line:
spring.freemarker.request-context-attribute=true

A: I tried to reconstruct your problem and weren't able to. Have you tried using something like the following?

linkTo(methodOn(EnvironmentRequestStateTransitioner.class)
    .approveRegistrationRequest(23L))
    .withRel("approve")

That worked fine for me using spring-boot-starter-parent version 1.3.2.RELEASE.


text:
Q: java util logging.properties: How to log to two different files I am placing a logging.properties in the WEB-INF/classes dir of tomcat
I would like to log to two different files. For example: org.pkg1 goes to one file and org.pkg2 goes to a separate file.
I can get one file configured, but not two. Is that possible?

A: Speaking of logging.properties configuration, I did not found any mechanism to use more that one appender. I made simple workaround that works for me.
public class CustomAFileHandler extends FileHandler {
   public DebugFileHandler() throws IOException, SecurityException {
      super();
   }
}

public class CustomBFileHandler extends FileHandler {
   public DebugFileHandler() throws IOException, SecurityException {
      super();
   }
}

And my logging.properties
...
handlers=<pkg_name>.CustomAFileHandler, <pkg_name>.CustomBFileHandler, java.util.logging.ConsoleHandler

<pkg_name>.CustomAFileHandler.level=ALL
<pkg_name>.CustomAFileHandler.pattern=%h/A%u.log
<pkg_name>.CustomAFileHandler.limit=50000
<pkg_name>.CustomAFileHandler.count=1
<pkg_name>.CustomAFileHandler.formatter=java.util.logging.SimpleFormatter

<pkg_name>.CustomBFileHandler.level=ALL
<pkg_name>.CustomBFileHandler.pattern=%h/B%u.log
<pkg_name>.CustomBFileHandler.limit=50000
<pkg_name>.CustomBFileHandler.count=1
<pkg_name>.CustomBFileHandler.formatter=java.util.logging.SimpleFormatter
...

A: I finally figured this out. In tomcat they extend java util logging ("JULI") to enable this functionality. Here's a logging.properties file that I put in the WEB-INF directory that finally accomplished what I was after......:
handlers=1console.java.util.logging.ConsoleHandler, 2jsp.org.apache.juli.FileHandler, 3financials.org.apache.juli.FileHandler
.handlers=1a.java.util.logging.ConsoleHandler

jsp.level=ALL
jsp.handlers=2jsp.org.apache.juli.FileHandler
org.apache.jasper.level = FINE
org.apache.jasper.handlers=2jsp.org.apache.juli.FileHandler
org.apache.jsp.level = FINE
org.apache.jsp.handlers=2jsp.org.apache.juli.FileHandler

com.paypal.level=ALL
com.paypal.handlers=3financials.org.apache.juli.FileHandler

3financials.org.apache.juli.FileHandler.level=ALL
3financials.org.apache.juli.FileHandler.directory=${catalina.base}/logs
3financials.org.apache.juli.FileHandler.prefix=financials.

2jsp.org.apache.juli.FileHandler.level=ALL
2jsp.org.apache.juli.FileHandler.directory=${catalina.base}/logs
2jsp.org.apache.juli.FileHandler.prefix=jsp.

1console.java.util.logging.ConsoleHandler.level=FINE
1console.java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

A: There's no easy way to get two handlers of the same type with java.util.logging classes that have different arguments.  Probably the simplest way to do this is to create a FileHandler subclass in your logging.properties that passes the appropriate arguments to enable your logging to take place, such as:
org.pkg1.handlers=java.util.logging.FileHandler
org.pkg2.handlers=org.pkg2.FileHandler
java.util.logging.FileHandler.pattern="org_pkg1_%u.%g.log"
org.pkg2.FileHandler.pattern="org_pkg2_%u.%g.log"

org/pkg2/FileHandler.java:
package org.pkg2;

import java.util.logging.*;

public class FileHandler extends java.util.logging.FileHandler {
    public FileHandler() {
        super(LogManager.getLogManager().getProperty("org.pkg2.FileHandler.pattern"));
    }
}

A: It is possible using pure jdk also (try with jdk 7 or jdk 8).
Just create custom file handler; use that similar to "java.util.logging.FileHandler".
public class JULTestingFileHandler extends FileHandler {

    public JULTestingFileHandler() throws IOException, SecurityException
    {
        super();
    }
}

user properties file;
com.xxx.handlers = com.xxx.JULXXXFileHandler

com.xxx.JULXXXFileHandler.pattern   = ./logs/test1_test2.%u.%g.log

A: Having the same problem myself with java.util.logging and not quite satisfied with the given answers, I just found in the documentation:

2.2 Changing the Configuration
Here's a small program that dynamically adjusts the logging
  configuration to send output to a specific file and to get lots of
  information on wombats. The pattern "%t" means the system temporary
  directory.

public static void main(String[] args) {
        Handler fh = new FileHandler("%t/wombat.log");
        Logger.getLogger("").addHandler(fh);
        Logger.getLogger("com.wombat").setLevel(Level.FINEST);
        ...
    }

So, it seems you can't do it just from the .properties file as can't instantiate several appenders, but you can do it programmatically. Also it should be possible using the LoggerManager


text:
Q: Google Sheet How to show a Warning or a Modal with input when a cell has data in it? Basically what i'm trying to say is, this is a spreadsheet for trucks with trailers, if someone inputs a trailer in cell B, can i make it to throw a popup or a Modal or a warning that cell E should have a truck assigned to it, or data and not allow the user to leave cell E empty?. Appreciate the help. how can i do this with a script?
enter image description here
enter image description here

A: You don't need appscript for that, you can easily do it using data validation.

*

*Select range B:B and open Data Validation dialog box.

*Select Custom formula is in criteria.

*Use this custom formula =$E1<>"" , select Reject Input. And set custom validation text to show when user violate the above condition.

A: Try this:
function onEdit(e) {
  const sh = e.range.getSheet();
  if(sh.getName() == "Your sheet name" && e.range.columnStart == 2 && e.range.rowStart > 1 && e.value) {
    if(e.range.offset(0,3).getValue() == '') {
      e.range.offset(0,3).setValue("Please Assign Truck Number Here");
      e.source.toast('Please Assign Truck',"Truck Assignment",15);
    }
  }
}

*

*Dont forget to edit the sheet name


text:
Q: I want to read /reference the gcc compiler documentation. Using the --version command line option I get 'Ubuntu 5.4.0'
Yet https://gcc.gnu.org/onlinedocs/ doesn't have a 5.4 version?  Do I use 5.5 or 4.9 or another version's documentation? I am confused, I thought my system Linux mint 19 is current. Thanks for any clarification you can give. I am looking for a command line option to step through a program line by line for debugging.


text:
Q: File is not Deleting Am trying to deleting particular file in a folder starting with name TRTHIndicative_.
But files are not deleting,am using below code
testMethod(inputDir);
testMethod(outputFile);

private static void testMethod(String dirName){
    File directory = new File(dirName);

    // Get all files in directory
    File[] files = directory.listFiles();
    for (File file : files) {

        if (file.getName().startsWith("Indicative_")) {
            // Delete each file
            if(file.exists()){
                System.out.println("File is there!");
            }
            if (file.delete()) {
                // Failed to delete file
                System.out.println("Failed to delete " + file);
            } else {
                System.out.println("Deleted file succsfully");
            }
        }

    }

please check and let me know if anything wrong.

A: You have your if and else confused - File#delete() returns true if the file is successfully deleted. So, the condition should be reversed:
if (file.delete()) {
    System.out.println("Deleted file succesfully");
} else {
    // Failed to delete file
    System.out.println("Failed to delete " + file);
}

A: Mureinik is right.
I just tried your peace of code. It works fine. Just do the changes as follows:
public class Main {

public static void main(String[] args) {
    File directory = new File("C:/temp");
    File[] files = directory.listFiles();
    for (File file : files) {

        if (file.getName().toLowerCase().startsWith("blub")) {
            // Delete each file
            if (file.exists()) {
                System.out.println("File is there!");
            }
            if (file.delete()) {
                System.out.println("Deleted file succsfully");
            } else {
                // Failed to delete file
                System.out.println("Failed to delete " + file);
            }
        }
    }
}

}
Note the toLowerCase() I added. It will make your snippet easier to use.

A: I think you have permission error in the file you try to delete.
elToro`s answer is working fine with me as well.
Try to give read/write permission to every user
how to change file permissions in windows


text:
Q: Android Bluetooth GATT timetout with Nordic Thingy:52 I have an android application where, after connecting to the thingy52 through the library (thingylib):
BluetoothDevice dev = scanResultList.get(nordicDeviceEntityList.get(pos).getAddress());
thingySdkManager.connectToThingy(getContext(), device, BaseTService.class);

I would like to read the Nordic thingy:52 data along with the RSSI value, so in an another activity, when I want to collect the data, i attach a new bluetooth GATT:
private void startDataCollection() {
        for (BluetoothDevice dev : thingySdkManager.getConnectedDevices()){
            thingySdkManager.setConstantLedMode(dev, 1, 100, 1);
            ThingyListenerHelper.registerThingyListener(getApplicationContext(), mThingyListener, dev);
            //e vents
            thingySdkManager.enableMotionNotifications(dev, true);

            gatt = dev.connectGatt(getApplicationContext(), true, gattCallback);
        }
}

After that on the Accellerometer event callback of the thingylib i get the data and call the GATT for retrive the RSSI value:
@Override
        public void onAccelerometerValueChangedEvent(BluetoothDevice bluetoothDevice, float x, float y, float z) {
            gatt.readRemoteRssi();
        }

The problem I find is that after a few seconds (not deterministically, sometimes 5/10s) the device disconnects with error 8 on the GATT (timeout error). If I remove the GATT link before collecting the data, the device does not disconnect and works perfectly.
I wanted to know if there is a way to prevent a connected GATT from timeout or if I am doing something wrong.
My android log:
2020-04-02 13:00:16.607 15336-15396/it.chiarani.beacon_detection D/BluetoothGatt: onClientConnectionState() - status=8 clientIf=9 device=F5:EF:EE:8B:92:7C
2020-04-02 13:00:16.609 15336-15380/it.chiarani.beacon_detection D/BluetoothGatt: onClientConnectionState() - status=8 clientIf=11 device=F5:EF:EE:8B:92:7C
2020-04-02 13:00:16.609 15336-15654/it.chiarani.beacon_detection D/BluetoothGatt: onClientConnectionState() - status=8 clientIf=10 device=F5:EF:EE:8B:92:7C
2020-04-02 13:00:16.610 15336-15654/it.chiarani.beacon_detection V/ThingyConnection: Error 8 : F5:EF:EE:8B:92:7C
2020-04-02 13:00:16.611 15336-15654/it.chiarani.beacon_detection D/BluetoothGatt: close()
2020-04-02 13:00:16.611 15336-15654/it.chiarani.beacon_detection D/BluetoothGatt: unregisterApp() - mClientIf=10
2020-04-02 13:00:16.670 15336-15336/it.chiarani.beacon_detection V/ViewRootImpl: The specified message queue synchronization  barrier token has not been posted or has already been removed

A: It seems that the problem is on the firmware side of the device, as indicated on this github issue: https://github.com/NordicSemiconductor/Android-Nordic-Thingy/issues/22


text:
Q: How can grep treat escaped newlines as real newlines? I'm using grep to find a word in some directory:
grep -r my_word directory

In this directory there are files containing my_word with escaped newlines (\n) so the output from grep is similar to:
file_name.txt:first line\n second line my_word\n third line

How can I force grep to treat \n as new lines and show something like:
second line my_word

A: You could pipe the result through sed to convert the newlines, then grep again:
grep -r my_word directory | sed 's/\\n/\n/g' | grep 'my_word'

Alternatively, if your grep supports Perl compatible regular expressions (such as GNU grep), you can use look-arounds:
$ grep -Po '.*^|\\n\K.*my_word.*?(?=\\n|$)' myfile
 second line my_word

This uses a variable-length look-behind, .*^|\\n\K, to greedily remove everything up to the last occurrence of \n before the line with your search term, and .*?(?=\\n|$) non-greedily matches the rest of the line until the next \n (or end of line).
If you don't want the filename in your result in case the match is in the first "subline", you can suppress the filenames with grep -h.


text:
Q: Variant to Scripting Dictionary performance loss I stumbled upon a performance-Bottleneck in my Project, that i would like to improve, but i do not quite understand why its behaving like it does.
The bottleneck is part of a JSON-Parser, that translates Dictionaries and its content to JSON-Text. The function takes Variants, checks its type and translates accordingly like so:
Function parseToJSON(itemToParse As Variant) As String

Select Case VBA.VarType(itemToParse)

    Case vbString
        '...

    Case vbInteger
        '...

    Case vbObject

        'If item is Dictionary
        If TypeOf itemToParse Is Scripting.Dictionary Then

            'Loop through items
                Dim key As Variant
            For Each key In itemToParse.Keys

                'Parse each item (Call oneself with item)
                Call parsetojon(itemToParse(key))
            Next key
        End If

    ' . . .
End Select

End Function

The Bottleneckis the itemToParse(key) that is sent when the function calls itself, where the item of the dictionary is accessed, which i nailed down by testing the isolated parts of the code with timed massed calls.
My suggestion is some kind of implicit typecheck of the variant, but i dont know. Thanks for ideas and ask if something is unclear and i will try to explain better. Still learning how to ask efficiently


text:
Q: Is there a way to implement drag & drop in a phonegap angular js project? I have tried this one: https://github.com/codef0rmer/angular-dragdrop together with touchpunch (http://touchpunch.furf.com/). On the browser it is working fine but when I deploy the app to an android device I receive following error:
$ui.mouse is not defined
Are there other alternatives to implement drag & drop for this combination ?

A: touchpunch requires jquery ui plugin. Verify if you included jquery UI in your page.


text:
Q: Resize /var partition on a remote system (Linux Debian Lenny) At a server that I only have access via ssh and vnc to (which means no booting from a "live" CD/DVD is possible), I would like to shrink the partition assigned to /var (in order to free some space for an additional partition). What would a good and safe way to do it?
Solution (based on David Spillet answer, provided that you have enough space on / to accommodate a copy of /var):

*

*stop anything that is using /var where possible

*remount /var readonly for good measure mount -f -oremount,ro /var (didn't seem to have any effect for me)

*copy /var to / under a different name with mkdir /vartmp; cp -av /var/* /vartmp/

*comment out the entry for /var in /etc/fstab

*reboot

*move things around with mv /var /varmount; mv /vartmp /var

*reboot, partition

*uncomment the entry for /var in /etc/fstap

*reboot

A: If you have room on your root partition for the contents of /var you could:

*

*stop anything that is using /var where possible

*remount /var readonly for good measure mount -f -oremount,ro /var

*copy /var to / under a different name with mkdir /vartmp; cp -av /var/* /vartmp/

*move things around with mv /var /varmount; mv /vartmp /var

*comment out the entry for /var in /etc/fstab

*reboot

You should now have /var in place as-was on your root partition instead of its own. You can now resize the old partition as needed. Step 4 should let you rename the /var directory even though it is in use as a mount-point and otherwise busy (and proceses with open files there will track the change as the open files are not referred to by path+name, but instead by inode, once open).
If you don't have space on / but do on /someotherfs then you could try move it there with a symlink in / like so:

*

*stop anything that is using /var where possible

*remount /var readonly for good measure mount -f -oremount,ro /var

*copy /var with cp -av /var /someotherfs/var

*move things around with mv /var /varmount; ln -s /someotherfs/var /var

*comment out the entry for /var in /etc/fstab

*reboot

This is slightly more risky though as you need to be sure that /someotherfs gets mounted before /var when booting.
If you don't have room where you want to copy it to temporarily you might be able to reduce the size of /var by removing things like cached packages (aptitude clean on Debian style setups, there is no doubt an equivalent yum command), moving other stuff away (for instance, Debian keeps the default httpdocs in /var/www so if it is still there and you have lots of data in there, move it to another partition), and deleting files from /var/log that are not very recent (backing the up first, in case you do need to refer to them later).
As Zoredache says: what ever you do, make sure you are happy with your backup arrangement before proceeding.
Caveat: all the above is from memory, I've not tested it anywhere, follow at own risk!

A: The traditional way is to boot in single-user mode.  That way, /var won't even be mounted by default, so you can mess around with it all you like.

A: *

*stop any services that may be using var (lsof | grep "/var")

*umount /var

*shrink /var

*re-mount /var

*restart the services you've stopped at 1.

A: If you have access to the console (e.g. keyboard-video-mouse via ethernet) then you can do:

*

*init 1 (and give root-password)

*maybe a systemctl stop systemd-timesyncd is required only if you use it

*umount /var

*e2fsck /dev/volume-where-var-is-in-your-system

*resize2fs /dev/volume... to whatever (in my case I wanted to shrink it so I used -M)

*do more stuff (lvresize or whatever)

then reboot

A: Single user is the safest bet:
These instructions cover resizing the var LV/FS on a Red Hat 7.x system
Take inventory before going into single-user:
# df -h /var
Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/vg00-var   13G  6.2G  5.9G  52% /var

# vgs
  VG         #PV #LV #SN Attr   VSize   VFree
  vg00         1   7   0 wz--n- <39.51g <2.63g

# lvs | grep var
  var      vg00       -wi-ao---- <12.86g

Boot into single user mode relevant to the platform you are using.
NOTE: The system will be accessible via /sysroot.
Activate vg00:
# lvm vgchange -ay vg00

Recreate LV device files:
# lvm vgmknodes -vv

# e2fsck -f /dev/vg00/var

To be safe, we'll reduce the FS to 8GB and then the LV to 8.5GB (with a subsequent FS resize to fill it out):
# /sysroot/sbin/resize2fs -p /dev/vg00/var 8G

Some resize math:
VG PE size: PE Size 4.00 MiB

4M * 1024K = 4096K

8.5G * 1024K * 1024K = 8,912,896K

8,912,89 / 4096 = 2176 PEs

NOTE: I received the following error initially and had to manually override locking_type:
"Read-only set locking type. Write locks are prohibited."
# grep locking_type /etc/lvm/lvm.conf
locking_type = 4

Reduce LV:
# lvm lvreduce -l 2176 /dev/vg00/var --config 'global {locking_type=1}'

RE-execute resize to fill the LV container out to 8.5GB:
# /sysroot/sbin/resize2fs /dev/vg00/var

Confirm new size with:
# lvm lvs
# reboot


text:
Q: Run php script in FTP without knowing public http address I need to zip and extract the database from a host. I created 2 php scripts for this but the problem is that i cannot execute them from browser because i don;t know the public path. That's because this is an old hosting i had but surprisingly i still can connect to FTP with the details i had. Since the domain is no longer associated with this hosting i can't find the public path.
My question is, having the ftp access, is there any way i could execute those 2 scripts to zip the entire folder and download the database (i also have the mysql details). I tried logging through SFTP with WinSCP and running the Execute custom command however no success.
Thank you so much, i really don't have any ideas what to do.

A: Two options,
1 If you have ssh access, execute
php yourscript.php
2 If you have remote mysql access, you can export your sql via a mysql client like sequelPro, etc


text:
Q: list of a model with special condition I have three models
class User(models.Model):
    username = models.charField()

class Base(models.Model):
    serialNum = models.CharFields()
    is_active = models.BooleanFields()

class User_Base(models.model):
    user = models.ForeignKey(User, related_name='user_base', blank=True, null=True, on_delete=models.SET_NULL)
    base = models.ForeignKey(Base, related_name='user_base', blank=True, null=True, on_delete=models.SET_NULL)
    status = models.BooleanField()

I'm looking for a list of bases, that base.is_active=True and there are not exist in User_Base table, and if some bases are in User_Base, their status=False.
How can I define my query?

A: I found it
list = Base.objects.filter((Q(user_base__isnull = True) | Q(user_base__isnull = False, user_base__status = False)),
                               is_active = True
                               )


text:
Q: jquery's event.stopImmediatePropagation() doesn't seem to be working I'm working with some existing javascript code which takes an LI and makes it droppable to an input field. I wanted to add an additional constraint to this, and enforce this by making my own event handler, and calling event.stopImmediatePropagation() if the constraint is not met.
This existing javascript is look like this:
$input.droppable({
    accept: accept,
    activeClass: 'droppable_active',
    hoverClass: 'droppable_hover',
    //          tolerance:    'touch',
    drop: function(e, ui)
    {
       // do some stuff;
    }

And is initiated in my code via the following call:
$('form').dmFrontForm();

Which is a custom jQuery UI which sets that event handler.
Before I make this call, I setup my own handler:
$('input').('drop', function(e, ui) {
    if (constraintIsNotMet) {
        e.stopImmediatePropagation();
    }
});

I verified the order that the event handlers were being called by adding in alert statements (actually no matter what order I put these lines of code, my handler always responded first which is a bit fishy to me), but no matter how hard I try, I can't get the first handler to quit.

A: I know this is not a direct answer to your question of why it does not stop the propagation, but why not use the built-in accept method ?
http://docs.jquery.com/UI/Droppable#option-accept
example of usage
$('.selector').droppable('option', 'accept', function(){...});

the function should return false to cancel the drop ..


text:
Q: Plone theme based on default using Diazo In Plone 4, I would like to create a new theme using Diazo that is based on the default Plone theme.  But when I go to control panel and create a new Diazo theme, it basically clears everything and gives me a blank slate.
How do I start with the basic/default theme for Plone 4 and modify that?

A: Install plonetheme.diazo_sunburst first, then modify it instead of the new Diazo theme.


text:
Q: XSLT replace options please, help me with XSLT. Need to take options from  one selectbox and place to another one.
I Have:
<form id="USE-THIS-ID-IN-XSLT">
    <select>id="USE-THIS-ID-IN-XSLT">
        <option>This will be removed</option>
        <option>This will be removed</option>
        <option>This will be removed</option>
    </select>
</form>

and
<select id="USE-THIS-ID-ALSO">
    <option>This will go up</option>
    <option>This will go up</option>
    <option>This will go up</option>
</select>

so result is to be
<form id="USE-THIS-ID-IN-XSLT">
    <select>id="USE-THIS-ID-IN-XSLT">
        <option>This will go up</option>
        <option>This will go up</option>
        <option>This will go up</option>
    </select>
</form>

If possible, need to do it without creating separate xsl:template match... (need to do it in current)

A: Your input is not valid, instead of <select>id="USE-THIS-ID-IN-XSLT"> it should be <select id="USE-THIS-ID-IN-XSLT">. With this correction, following XSLT
<?xml version="1.0" encoding="utf-8"?>
  <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="html" indent="yes" />
  <xsl:strip-space elements="*"/>
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
  </xsl:template>
  <xsl:template match="select[@id='USE-THIS-ID-IN-XSLT']">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()" />
      <xsl:copy-of select="//select[@id='USE-THIS-ID-ALSO']/*" />
    </xsl:copy>
  </xsl:template>
  <xsl:template match="select[@id='USE-THIS-ID-ALSO'] |
       select[@id='USE-THIS-ID-IN-XSLT']/*"/>
</xsl:stylesheet>

when applied to the example input
<html>
  <form id="USE-THIS-ID-IN-XSLT">
   <select id="USE-THIS-ID-IN-XSLT">
    <option>This will be removed</option>
    <option>This will be removed</option>
    <option>This will be removed</option>
   </select>
 </form>
 <select id="USE-THIS-ID-ALSO">
  <option>This will go up</option>
  <option>This will go up</option>
  <option>This will go up</option>
 </select>
</html>

produces the output
<html>
 <form id="USE-THIS-ID-IN-XSLT">
   <select id="USE-THIS-ID-IN-XSLT">
     <option>This will go up</option>
     <option>This will go up</option>
     <option>This will go up</option>
   </select>
 </form>
</html>

The last empty template matches everything that should be removed from the ouput. Instead at the template matching the select that you want to keep  a copy of the options from the removed select is made. What I'm unsure about is that you have in your input <select id="USE-THIS-ID-ALSO"> but don't want to have it in the ouput, maybe this is a minor mistake in the desired output at your question.


text:
Q: Getting Beego to work on AWS I'm currently looking for a place where I can read about running the Beego (or similar GOlang) framework on AWS. Would anyone know a place?

A: You have a (Japanese- google translated) tutorial to install Beego to AWS.
It doesn't involve anything special, except installing git, go and beego
sudo yum install git mercurial
yum install ld-linux.so.2

# Run curl -L -O https://go.googlecode.com/files/go1.2.1.linux-386.tar.gz as root
tar zxvf go1.2.1.linux-386.tar.gz -C / usr / local

/etc/profile.d/go.sh

export GOROOT = / usr / local / go
export GOPATH = / var / local / gocode
export PATH = $ PATH: $ GOROOT / bin: $ GOPATH / bin

go get github.com/astaxie/beego
go get github.com/beego/bee

The article "Setup a website powered by Beego" suggests a few other tools as well, like:

*

*gvm (Go Version Manager)

*go.vim


text:
Q: R: How to combine an arbitrary number of functions and parameters into one computation I am trying to combine vectors of parameters of arbitrary length into one logical computation.  Basically, I am trying to compute:
    get("&")(get("&")(sigBuy(">",
               30.30815,
               30.39961),
            sigBuy(">",
               30.39961,
               30.47286)),
            sigBuy(">",
               30.47286,
               30.519))

from the following sets of parameters:
IndicatorA <- c(30.30815, 30.39961, 30.47286)
IndicatorB <- c(30.39961, 30.47286, 30.519)
BuyConditions <- c(">", ">", ">")
BuySigConditions <- c("&", "&")

and function sigBuy():
sigBuy <- function(BuyCondition, IndicatorA, IndicatorB) {
    out <- get(get("BuyCondition"))(IndicatorA, IndicatorB)
    return(out)
}

The actual logic I am trying to apply in this case is
IndicatorA[1] > IndicatorB[1] &
    IndicatorA[2] > IndicatorB[2] &
     IndicatorA[3] > IndicatorB[3]

In actual practice, I do not know the length of the parameters IndicatorA, IndicatorB, BuyConditions, or BuySigConditions, other than to constrain that the lengths of IndicatorA, IndicatorB, & BuyConditions are equal, and that length of BuySigConditions is one less than the rest.  Additionally, BuyConditions can be any of <, >, <=, >=, ==, !=, and BuySigConditions can be & or |.  I will be functionalizing the logic such that the user will pass in an arbitrary length of vector parameters (following length constraints above), and my function will construct the computation I am trying to obtain, resulting in this example as:
[1] FALSE

A: do.call and mapply can help here.
sigBuy <- function(cond, ...) do.call(cond, list(...))
reln <- mapply(sigBuy, BuyConditions, IndicatorA, IndicatorB)

result <- reln[1]
for(i in seq_along(BuySigConditions))
  result <- do.call(BuySigConditions[i], list(result, reln[i+1]))
result


text:
Q: How to broadcast an intent to a specific appwidget? I am creating a appwidget which needs to update on a specific interval. I use AlarmManager for this.
I want to have the alarm run the onUpdate() method in the AppWidgetProvider.
    //Create the intent
    Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
    pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    //Schedule the alarm
    AlarmManager manager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    manager.setRepeating(AlarmManager.RTC, startAlarmCal.getTime().getTime(), 1000 * 60, pendingIntent);

However, this intent causes all the widget's to update. I want to somehow only send this intent to my own appwidget. How would I do this?

A: Use a custom Intent to send to your widgets. You can register them in the manifest.xml. You cannot update specif widget ids but types of widget if you have many different ones.
<receiver
        android:name=".widget.WidgetProvider"
        android:label="1x1">
        <service
            android:name=".extra.WidgetProvider$WidgetUpdateService1x1" />
        <intent-filter>
            <action
                android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            <action
                android:name="nitro.blub.APPWIDGET_MANUEL_UPDATE" />
        </intent-filter>
        <meta-data
            android:name="android.appwidget.provider"
            android:resource="@xml/widget_info" />

    </receiver>

A: You might try adding this(slightly modified to suit your needs, of course):
// Change the text in the widget
RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.main);
ComponentName thisWidget = new ComponentName(context, [Calling_class].class);

// Run update code here. e.g: //////////////
updateViews.setTextViewText(R.id.text, now);
////////////////////////////////////////////

appWidgetManager.updateAppWidget(thisWidget, updateViews);

Hope this helps.

A: Once again, it's all in the documentation:

updatePeriodMillis How often, in milliseconds, that this AppWidget wants to be updated