text:
Q: Is submersion in a canal a good way to shelter from a nuclear strike? I live 1.5 miles from the center of a city in a nuclear-armed country, and an adversarial country has just put its nuclear forces on high alert during a time of extraordinary geopolitical tension. I am thinking about what I could do to shelter from a nuclear strike. A 1Mt airburst over the centre of the city would result in widespread damage to/collapse of structures in my neighborhood with widespread death and near-universal injury according to an online simulator I used, and I have no cellar.
However, I am very near a canal path which radiates outwards from the center of the city. If upon hearing an air raid siren I got on my bike, cycled outwards along the canal for 16-minutes (tripling the distance between me and the city centre to 4.4 miles), jumped off my bike into the canal with ballast as soon as the buildings around me light up due to the explosion, and held my breath for 2 minutes at a depth of 1.5m [edited from 3m after my friend corrected me about the depth of that canal], would the water protect me from the heat and shockwaves? Would sheltering in a body of water at 1.5m depth be better than sustaining injuries in a house?

A: Apart from assuming that the warning systems indeed sound air raid siren some time before the actual explosion (which should not be taken for granted), the scenario is highly unrealistic.
The primary effects of nuclear explosion are the shock wave, the thermal wave, and the electromagnetic pulse. These are however limited to a radius from a few to a few dozen kilometers from the center of the explosion, depending on whether the bomb hits the ground or explodes in the air, the charge, the presence of mountains, high buildings etc. Note that the resulting shock wave propagates with supersonic speed. Thus, whatever is within radius of a few kilometers from the center will be destroyed instantly - not enough time to jump off a bike. Thermal wave is similarly lethal - in particular, the water in the channel might simply evaporate.
Penetrating radiation propagates much further. Although radiation is nowadays commonly associated with nuclear energy, it was not considered the main factor when the bomb was created, and wasn't the major cause of destruction during the two nuclear bombings. Harmful effects of radiation became known much later - in fact, decades later after numerous open-air tests on Nevada testing grounds. Still, in the case one survives the explosion, one will be left to die more or less slowly from the radiation sickness.
It is naive to hope to survive a nuclear war - a fact that was widely known some 30 years ago, but apparently forgotten (or never learned) in the post-Cold-War era (see Mutually Assured Destruction)

A: Good question from a purely physics point of view.  Here is an answer I found from Karl Lembke, Supervisor, Water Quality Inspectors, Los Angeles Department of Water and Power
In many cases, what you want for absorbing or blocking radiation is a lot of mass. Water, at about one metric ton per cubic meter, is a lot of mass. It's also useful because you can see through it, and it will assume the shape of whatever container you pour it into, so you don't have to worry nearly as much about gaps in the shielding.
For gamma rays, you have three major mechanisms for absorbing radiation: the photoelectric effect, Compton scattering, and pair production. At low photon energies, the photoelectric effect matters, and water is less effective than, for example, lead. But if space isn't an issue, that just means you add more water. At higher photon energies, Compton scatter is pretty much independent of the atomic number of the matter involved, so concrete is often used for shielding. It's cheaper than lead. Ditto for pair production when photon energies get above about 1.1 MeV.
Water, or anything else that's rich in hydrogen atoms, is great for stopping neutrons by elastic collision. In a collision between a neutron and a proton (a hydrogen nucleus), most of the kinetic energy can wind up being transferred to the proton, leaving the neutron slowed way down. At this point, a neutron may be absorbed by an atomic nucleus, or failing that, it undergoes a beta decay leaving behind a proton and an electron. (Half-life is 10.8 minutes.)
But in the final analysis, water makes a good radiation shield because it's relatively heavy and you can put a lot of it around a radiation source for not a lot of money.
For your particular question, I just think you'd need to stay under the water for a long time until the radiation dissipated.

A: Water readily transmits shock waves, so while being under water and in a ditch shields you from infrared and gamma radiation the shock wave may still kill you, dependent on the distance from the blast, the altitude of the detonation and the size of the bomb.
For a 1 Mt bomb at an altitude chosen for a maximum blast radius, 4.4 miles or 7 km is just outside of the area of total blast destruction: Wikipedia estimates a blast radius of 6 km for a 1 MT nuke. As with tsunamis there will be effects of terrain and structures deflecting and diffracting the shock wave, leading to local deviations from the average. While you want to be in a canal running tangentially to the blast, and find a spot on the shore facing the blast for additional shielding from the dirt, it would bee ill-advised to be close to buildings or under bridges which may collapse and bury you under water, which would limit the extension of your life span to a few minutes until oxygen runs out, unless you die from the mechanical impact first.
Water absorbs electromagnetic radiation in the infrared spectrum, so being under water is a a great idea in order to protect against it. 7 km is well within the conflagration radius, according to the same Wikipedia source. Avoiding instant conflagration is a good first step towards survival. I am not sure whether the absorbed energy is sufficient to heat the water significantly; if so, the upper layers would be heated most, so the deeper you immerse yourself the better, in case that wasn't obvious, and don't dawdle when you climb out.
Long term survival depends on so many contingencies that it is impossible to predict. The most important one is that all things considered, nuking your city is likely not a fluke, so you'll find yourself in the middle of a nuclear war zone which somewhat dims your outlook.
But the immediate effect of the nuke may be survivable, and being under water should improve the odds. The general factors determining mid- and long term survival are:

*

*Wind transporting the fallout

*Equipment to protect yourself

*Access to potable water, food and medical supplies

*Availability of transportation to leave contaminated and inhospitable areas

*Depending on your location, the time of year and the weather: Access to shelter

A: As mentioned in mmesser's comment, I see no reason to suspect that a nuclear exchange is likely in the foreseeable future.
For explosions generally, if you live long enough to start making decisions, and aren't trapped in a firestorm, you are concerned about pressure waves, shrapnel, and falling debris.
For pressure waves, being behind something solid, durable, and low to the ground is good. Making yourself small and covering your ears is good. Being underwater might help, I'm not sure. This applies to any explosion - being near to an accidental explosion or a conventional bomb is more likely than getting nuked. If you see an explosion, don't watch it and don't try to run away: immediately get low, get behind something, make yourself small, and cover your ears until well after you hear the sound.
When it comes to shrapnel and falling debris, distance, being behind something solid that can't be turned into shrapnel or blasted into falling rubble, and being low to the ground, are good. Having any kind of barrier between you and falling debris is good. (It's popular to mock "duck and cover" as a useless placebo, but if you've seen an explosion and you aren't already injured, shrapnel and falling debris are your most likely sources of injury and "duck and cover" is your optimal survival strategy. Again, this goes for any explosion.)
Shockwave and shrapnel hazards are reasonably well satisfied by the wall of a canal with sufficient distance to be out of line of sight of the airburst. (Shelter against the wall closer to the blast, make yourself small, and cover your ears.) So would a metro/subway station, a highway overpass, an underground structure without a tall building on top of it, or even being on the far side of a hill and as low to the ground as possible.
The best defense against hazardous materials (including radioactive fallout) is to be upwind. This is probably worth taking half an hour to have a plan for: bookmark a couple of websites with your city's current prevailing wind direction, and know your evacuation route in at least two directions. Again, this applies to non-nuclear threats, in particular forest fires.
Secondary exposure to irradiated objects, especially metals, is a last hazard to consider. Salvaging metal objects (gold, tools, weapons) may inadvertently put you in long-term proximity to radioactive materials.
I don't think being underwater would help against a nuclear weapon's UV pulse (water is mostly transparent to UV at depths of a few meters, and would heat up to lethal temperatures anyway), or against the firestorm. WWII accounts of firestorms inflicted by conventional weapons indicate rivers being no escape for the unfortunate souls who tried. It might protect you from direct gamma radiation, but if you have fatal burns it doesn't matter what your gamma dose is.
There's no guarantee that a weapon will go off in a particular specific place, or a specific time after sirens, so you might end up running in the wrong direction or find yourself in the open at the worst moment. For any major disaster including a nuclear strike, I think it's probably better to seek shelter as near as possible to wherever you are and hope for the best, then work on making your way away from and upwind from the epicenter.

A: By the time you see the buildings around you light up, you have already got the gamma radiation dose. The neutron dose is not far behind. Probably they arrive before your reaction time after the light. The neutron energy depends on the design. But a tritium-deuterium weapon will make a big whack of 14 MeV neutrons that arrive at about 5% the speed of light.
As well, there is sky shine. Both gamma and neutron radiation can scatter off air. So you will be getting dosed off the buildings and the air above you.
The blast wave is coming quite stupendously fast behind that. At 6 km, you might well not have time to react before it reached you. If you leaped into the water after only 0.25 seconds (a not-bad reaction time) you might well still be in mid air when the blast hit.
So the plan of waiting and jumping in is not good. You would not have time to benefit from any protection you might get.
You would be better behind a substantial earthwork. Say a hill that is at least 10 meters tall, taller the better. And with as much of the sky blocked as possible. Earth or stone will block radiation at least as well as water. And it will also block blast wave. If there was a honking-big-and-thick stone wall you could shelter behind, that might give you some chance. A hill full of trees might be a bad choice, since they could be on fire in a second or two.
Better still would be a honking-thick-walled enclosure. Say a subway tunnel at least 10 meters under ground, more the better. And not running towards the city center. The blast wave might well find the tunnel. You do have the concern of getting out after, if there is a lot of rubble on the entrance. There is always the chance of tunnel collapse due to the explosion. And every ventilation shaft is going to be dusting down fallout.
Or maybe go stay with your relatives in Outer Nowhere for a few months. One way or the other, this is going to come to a head fairly soon.

A: You have also forgotten that from ground zero out water will evaporate to a point. Once the pressure dissipates water will rush back into the canal from further upstream to take the place of the evaporated water, likely pulling you closer to ground zero, think tsunami as the water flows back.

A: Partial answer re: depth charges, underwater sound and shockwaves
People have commented several places that being underwater may make shockwave effects worse because it is a known phenomenon that water transmits shockwaves somehow "more" than air, and the human body contains hollow air-filled structures (lungs, sinuses) where energy will be deposited.
I'm not confident in my knowledge, so I'm hesitant to say anything, but I think this is a mistake that doesn't need an expert to correct, and which will be clear once anyone thinks about it. This also may be a bit long winded since I'm talking myself through it as I go.
what's going on with depth charges
Water doesn't magically make sounds more energetic. Energy is energy and the inverse square law is the inverse square law. So why can submarines or whales detect sounds many kilometers away with great clarity? Why are underwater explosions so harmful? Why can the clicks of whale communication be harmful to smaller animals like humans?
First let's define harm in a language we can do physics with. Harm is something that has to do with energy deposited into a target much more rapidly than the target can dissipate or radiate energy. Physical structures in the target can be approximated as locally stable energy equilibria. Breaking them means pushing them from that equilibrium, up and over the edge of an energy well.
How you apply the energy affects how fast it can be dissipated or radiated - for instance, shooting a high power laser pulse at somebody might vaporize part of their skin, but steam will carry the energy away as fast as it is put in, so the injury will be superficial. Shooting an equivalent energy bullet at the person will shatter bones and rupture organs, because there's no mechanism for the energy to escape as fast as the bullet is putting it in, except out through the exit wound with what's left of the bullet. Conversely, a high school pitcher throwing a baseball at a person has the same mechanism (physical impact of a mostly rigid object) and the same energy as a handgun bullet (around 500 joules). But it applies the energy much more slowly because of its much lower velocity. Even if it strikes a rigid, small-area structure like the forehead, it will leave only a bruise.
Pressure waves deposit energy into a target. We can therefore infer that, all other things being equal, more energy in less time means more damage.
As I said at the beginning, energy is energy and the inverse square law is the inverse square law. Immersing a bomb in water doesn't make it more energetic. Bombs are solid objects with a well defined minimum radius, so there's no way to cheat the inverse square law. Let's use an old timey spherical bomb: the total energy at the surface of the bomb, is (approximately) the same as the total energy at any larger spherical shell, and the ratio of energy densities is the same as the ratio of squared radii.
So underwater we are doing more "harm" - that is, more energy in less time - with the same energy. It is the speed (literally) with which we are applying that energy that makes the pressure wave more harmful.
The speed of sound about 5 times larger underwater than in air. I have no idea how or if supersonic shockwaves work underwater, but suppose that in any case all pressure waves created by a given explosion propagate much more quickly underwater than in air, and therefore deposit energy in the target much faster than an equivalent energy density pressure wave in air. Same energy flux in less time equals more damage.
so what about in-air explosions underwater
Now let's say we detonate the same bomb above the water surface. Suppose for the sake of argument that no energy is reflected at the water-air interface. (This is not realistic - in reality most energy is reflected at the interface.)
The water can't transmit energy to a submerged target any faster than the surface of the water receives energy. That would violate energy conservation or at least require the water to have some mechanism for storing the energy for delayed release. In terms of power flux, then, the power flux through a target's cross-section at some distance $l$ from a surface which is itself a distance $r$ from the source of an in-air pressure wave is somewhere between the power flux at a distance $r$ from the source in air and the power flux at a distance $r+l$ from the source in air.
If we're 1.5 meters under water, ignoring other factors, our power flux is some value less than what it would be at the surface, and more than what it would be another 1.5m away from the weapon in atmosphere.
That would be a big range if you're talking about a bomb 3 meters away, and experiment or calculation would be needed to determine whether you'd be better off in air or underwater. But we're talking about a bomb at least 3 kilometers away - otherwise we're already dead no matter what we do. Our maximum increased power flux from diving 1.5m instead of walking 1.5m is $1-(3000m)^2/(3001.5m)^2 \approx 0.001 $ times more power flux.$^1$
So, in terms of power flux, water needs only to reflect less than 0.1% of incoming energy in order for you to receive less "harm" than someone standing at the same radius in air.
what about the human body interfaces?
Okay, but maybe there's something about getting hit in water that makes a given pressure wave power flux worse in water than in air. Pressure waves deposit most of their energy when they reflect at interface changes, so in water, your arms, legs, and guts will mostly transmit the energy unperturbed, while your lungs and sinuses will mostly reflect the pressure wave, and therefore the pressure wave will deposit lots of energy in those places. One imagines that one's lungs and sinuses might be more fragile than arms and legs, even accounting for how the articulation of the body will transmit most of that energy to vulnerable joints.
Again, this is a mistake that is easily seen and I don't need to know anything about the relative structural strengths of lungs and joints to know it. All I need to know is that in both cases, there are the same number of interface changes made of more or less the same thing.
That is: suppose a human is a bag of water (flesh, bone, etc) around a bag of air (lungs, sinuses)
If you are hit by a pressure wave in atmosphere, there is an interface change at your skin and a second interface change at your lungs. At the first interface (air to body) a certain amount of energy is reflected, a certain amount is deposited at the interface, and a certain amount is transmitted. The transmitted amount reaches the second interface (body to lungs). A certain amount is reflected, a certain amount is deposited, and so on.
If you are hit by a pressure wave in water that originated in atmosphere, there is an interface change at the surface of the water and a second interface change at your lungs. At the first interface (air to water) a certain amount of energy is reflected, a certain amount is deposited at the interface, and a certain amount is transmitted. The transmitted amount reaches the second interface (body to lungs). A certain amount is reflected, a certain amount is deposited, and so on.
Which would you rather absorb whatever percent of the energy is deposited by the wave on the air-to-water phase transition? The surface of the water, or your body?
Now, it may be that the energy deposited at the surface of the water is, in practical assessment, as bad for you at a depth of 1.5m as if it was deposited to you directly. Water deforms and a cataclysmically violent event like a large bomb might blast all the water away with a fraction of the energy deposited to the surface, making there be no practical benefit. I don't know. But surely, it's not significantly worse for the energy to be deposited, at least at first, a distance 1.5m away from you than inside your own body.

1: It's more complicated than this because of ground effect (the ground reflects most of the energy, so shockwaves propagate along the ground with somewhere between $1/r$ and $1/r^2$ dependency). And because of barriers (as noted in my other answer, taking cover behind something heavy and solid will cause a drastic reduction in the amount of energy you're exposed to, and the surface of the planet is a very heavy and solid thing to hide behind). But for a general idea of why 1.5m of distance doesn't matter much, I think it's true enough.


text:
Q: how to use certificates file and ssl on c# selfhost webApi? I implimenting a server using selfhost webApi.
I need to use ssl with certificates that will load a .cer file ( = Used to store a public key ) that will be load from disk when the server will start.
I loaded the the .cer file
X509Certificate2 certificate = new X509Certificate2(fullpath, password);
but i don't know how to set the webapi to use this certificate  file.
I don't find any example or how to do it.
Any help please
Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to do this with for loop I am trying to practice for loops and I cannot get the for loop to do this for me, how can I have the code that would give me this result ?
1 2 3 4 5 6 7 8 9 10
3
4
5
6
7
8
9
10

I know simple for loop
    for(int y = 1; y <= 10; y++){

        System.out.println(y);
        }

result
1
2
3
4
5
6
7
8
9
10

A: Try this:
    for (int y = 1; y <= 10; y++) {

        System.out.print(y + " ");
    }
    System.out.println();
    for (int y = 3; y <= 10; y++) {

        System.out.println(y);
    }

A: You could do this
for (int i = 1; i < 11; i++) {
  System.out.print(i);
  if (i == 1) {
    for (int t = i + 1; t < 11; t++) {
      System.out.print(" " + t);
    }
  }
  System.out.println();
}


text:
Q: Ranking values with repeats. Matlab My question is simple, but I can't find the answer...
I have a 100,000 rows x 30 colums matrix for a simulation, and I need to rank the 100k values of each column.
I'm looking for something similar to tiedrank but I need that repeats does count (and not the average).
Suppose: data = [-1 2 0 -2 0] what I need is rank= [2 5 3 1 4]
Any suggestion?
Thank you very much!
Juan

A: It seems like you need sort:
data = [-1 2 0 -2 0];
[ignore, idx] = sort( data );
rank( idx ) = 1:numel(idx)

rank =

    2     5     3     1     4

To rank all columns of matrix as once you can use the following code
data = [ -1 2 0 -2 0; -1 -1 -2 2 2]' ; %'
[n m] = size( data ); % number of rows and columns
[ignore idx] = sort(data); % sort columns
rank = zeros( size(data) ); % allocate
rank( sub2ind( size(rank), idx, bsxfun(@times, 1:m, ones(n,1) ) ) ) = ...
    repmat( (1:n)', 1, m )

rank =

     2     2
     5     3
     3     1
     1     4
     4     5


text:
Q: Orange Liveobjects - Data tab > Kibana button always give 403 permission denied error while pressing kibana button in data tab I'm always getting error page with permission denied, I've checked the user's roles and found that it has reading access to kibana role,

A: this means that Kibana has not been provisioned correctly on your account. If you contact Live Objects support, they will repair it.
regards


text:
Q: Avoid certain combinations on a Math.random() function I have to list of words:

  apple
  sea
  ship

  duck
  tale
  jewelry

the client can add any word to these list so it's not only going to be these 6 words.
I'm using a function that when on click event, it changes the word creating a combination between these two lists on this structure:

$('.first-word').click(function(){
  $('.first-word').text($(".first-word-list span").eq(Math.floor(Math.random()*firstWordLength)).text());
});

$('.second-word').click(function(){
  $('.second-word').text($(".second-word-list span").eq(Math.floor(Math.random()*firstWordLength)).text());
});

So, if the user clicks on .first-word and on .second-word it displays this:

sea

tale

but lets say I want to block/avoid to display the combination of ship and jewelry. Since I'm using a random function and like I wrote before, the word list will grow I need a way to control which words combinations won't be shown. Any idea how to do this?
Update
The client will write the banned combinations on two new custom fields which will output on a new list like this:

shipjewelry

appleduck

A: Here is a snippet that allows you to dynamically add words to either list, and to select words from those lists in order to mark them as forbidden combinations. Once you have everything entered as you want to have it, you can click the two random words to have them replaced by a new random word (which could be just the same word again), taking into account the forbidden combinations:

// Allow adding words to either word list:
$(".add-word").on("change keydown", function (e) {
    if (e.which && e.which != 13) return;
    $(this).before($("").text($(this).val()));
    $(this).val('');
});

// Allow selecting words by clicking them
$(".word-list").on("click", "span", function () {
    $(".selected", $(this).parent()).removeClass("selected");
    $(this).addClass("selected");
    showButton();
});

// Allow forbidding pairs of selected words:
$("#forbid").click(function () {
    $(".forbidden").append(
        $("
").append(
            $(".selected").removeClass("selected").clone(),
            $("<button>").addClass("del").text("Del")
        )
    );
    showButton();
});

// Remove forbidden pair:
$(document).on("click", ".del", function () {
    $(this).parent().remove();
});

// Hide/show button depending on whether we have enough selected words:
function showButton() {
    $("#forbid").toggle($(".selected").length == 2);
}

// Main algorithm:
$(".random-word").click(function () {
    var index = $(this).index(".random-word");
    // Get word that is not clicked:
    var otherword = $(".random-word").eq(1-index).text();
    // Get all words from corresponding list
    var words = $("span", $(".word-list").eq(index)).map(function () {
        return $(this).text();
    }).get();
    // Get list of forbidden words that are linked with the other (non-clicked) word
    var forbidden = $('.forbidden div').filter(function () {
        return $('span', this).eq(1-index).text() == otherword;
    }).map(function () {
        return $('span', this).eq(index).text();
    }).get();
    // Derive the list of allowed words, taking all words, filtering out what is forbidden
    var allowed = words.filter(function (txt) {
        return forbidden.indexOf(txt) == -1;
    });
    // Pick a random from these allowed words:
    $(this).text(allowed.length
        ? allowed[Math.floor(Math.random() * allowed.length)]
        : "(none)"
    );
});

showButton();

// *** Upon special request following was added ***
// Algorithm for choosing random pair in one go:
$("#choose").click(function () {
    // Get all words from both lists
    var words = $(".word-list").get().map(function (list) {
        return $("span", list).get().map(function (span) {
            return $(span).text();
        });
    });
    // Get list of forbidden words pairs
    var forbidden = $('.forbidden div').get().map(function (div) {
        return $('span', div).get().map(function (span) {
            return $(span).text();
        });
    });
    // Derive the list of allowed pairs, taking all pairs, filtering out what is forbidden
    var allowed = words[0].reduce(function (pairs, word) {
        // Get list of forbidden second words, given the first word
        var exclude = forbidden.filter(function(pair) {
            return pair[0] == word;
        }).map(function (pair) {
            return pair[1]; // extract second word of the pair
        });
        // Filter all second words, excluding those that are forbidden pairs with first word.
        return pairs.concat(words[1].filter(function (word2) {
            return exclude.indexOf(word2) == -1;
        }).map(function (word2) {
            return [word, word2];
        }));
    }, []);
    // Pick a random pair from these allowed pairs:
    var randomPair = allowed.length
        ? allowed[Math.floor(Math.random() * allowed.length)]
        : ["(none)", "(none)"];
    // Display the pair
    $(".random-word").each(function (i) {
        $(this).text(randomPair[i]);
    });
});
span {margin-left: 2px; margin-right: 2px}
span.selected {background-color: yellow}

First word list:

  apple
  sea
  ship
  <input class="add-word" size=10>

Second word list:

  duck
  tale
  jewelry
  <input class="add-word" size=10>

<button id="forbid">Add combination as forbidden</button>

Forbidden combinations:

Random Pair (click a word to reselect a random, allowed word):

sea

tale

<button id="choose">Random Pick Both</button>

A: I'm not sure how you want to handle adding banned options but if everything needs to be dynamic then you could always utilize a dictionary (object).
var bannedOptions = {
    'ship': {
        'jewelry': true
    }
};

When you go to check if an option is valid you can simply do something like:
// Here I'm using truthy checks,you can always add a != null
// if you want false or something to be a valid value
if(bannedOptions[word1] && bannedOptions[word1][word2]) {
    // It's invalid
} else {
    // Valid
}

When you want to add a new invalid option you could
if(!bannedOptions[newWord]) bannedOptions[newWord] = {};
bannedOptions[newWord][invalidWord] = true;

If you wanted to remove an invalid option you could do:
bannedOptions[word1][word2] = false;

or
delete bannedOptions[word1][word2];

Using a dictionary allows you to have super fast checks when you want to see if a combination is invalid.
It's super dynamic so you don't have to worry about indices or anything because the words themselves are keys... and as long as the word is accessed as a string you can have symbols like -,',/, etc. in the words.


text:
Q: SharePoint 2013 App Deploy Error: "A different version of this App is already installed with the same version number" I have developed a very simple Provider-Hosted App which I was deploying to our SharePoint Online Developer Site.
Testing was going fine, and I had deployed it several times to the site, before I suddenly received this error in Visual Studio 2012 after I hit F5:
Error occurred in deployment step 'Install app for SharePoint': A different version of this App is already installed with the same version number.  You need to delete the app from the site and the site recycle bin to install this version.
The thing is, I had just deleted / removed my app from the Developer site and from the recycle bin right before I received this error.
Not sure if this is relevant: but one of the changes I made to the program was to give the App Write permissions for the Web scope via the AppManifest.xml file.
I'm not finding anyone with this exact error on Google search results, so I thought I'd be the first to post it here.
Any help / ideas?  I'm fairly new to developing for SP13.
Thanks in advance

A: First off welcome to the world of SharePoint dev. SharePoint can be quite painful with holding onto things, but the solution in your case is fairly easy - anytime you make a change to the AppManifest increment the version number. This is done on the general tab of the AppManifest, or if you're directly editing the xml then it should be the third item in the App tag.

Changing to 1.0.0.1 should fix your problem straight away, it is also a good habit to get into as then when you are deploying an app manually (not hitting f5) you will be able to update the old version of the app instead of having to completely remove it.


text:
Q: insert from form submission to database My html code:

                                Total Duration in Second
                                <input type="text" class="form-control" id="duration" name="total_duration">

                                Description Duration
                                <input type="text" class="form-control" id="duration" name="desc_duration">

the php:
<?php

                    include('lib/conn_sqli.php');
                    include ('lib/conn.php');
                    $total_duration = $_POST['total_duration'];
                    $desc_duration = $_POST['desc_duration'];

                    $sql = "INSERT INTO vote.duration (id_duration, total_duration, desc_duration) VALUES (null, $total_duration, $desc_duration)";
                    mysql_query($sql);
                    if ($sql){
                        echo ("succeed");
                    }
                    ?>

The conn_sqli.php:
<?php
    // connect database -------------------------------------------->
    $db = new mysqli ( "localhost" , "abc" , "123" , "vote" );
    echo $db->connect_errno?'Connection failed : '.$db->connect_error:'';
    //<--------------------------------------------------------------
    ?>

The conn.php:
<?php
$db_host    = "localhost";
$db_user    = "abc";
$db_pass    = "123";
$db_name    = "vote";
$konek  = mysql_connect($db_host,$db_user,$db_pass,$db_name) or die ("Gagal Koneksi ke Server");
mysql_select_db($db_name, $konek) or die ("Gagal Mengaktifkan Database".mysql_error());
?>

The code simply doesn't work. The php will echo "Succeed", but no data is inserted. I know this is so simple but I can't seem to figure it out. Thanks

A: Notes:

*

*Don't combine the deprecated mysql_* and mysqli_* API

*Use at least *_real_escape_string() function before binding a raw data to your query

*Use a single tick (') to bind variables to your query, better yet, use prepared statement

*Do error reporting
Here's a simple example of your code in prepared statement (assuming that id_duration column is your primary key and in auto-increment):
<?php

    include('lib/conn_sqli.php');
    // include ('lib/conn.php'); COMMENT THIS OUT OR REMOVE THIS
    $total_duration = $_POST['total_duration'];
    $desc_duration = $_POST['desc_duration'];

    if($stmt = $db->prepare("INSERT INTO duration (total_duration, desc_duration) VALUES (?, ?)")){
        $stmt->bind_param("ss", $total_duration, $desc_duration);
        $stmt->execute();
        $stmt->close();
        echo ("succeed");
    }

?>

A: You are totally in the wrong way.
The HTML Form:
    <form method="post" action="insert.php">
       Total Duration in Second
       <input type="text" class="form-control" id="total_duration" name="total_duration">
        Description Duration
        <input type="text" class="form-control" id="desc_duration" name="desc_duration">
        <input type="submit" name="submit" />
    </form>

The insert to the database, let me say it insert.php:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$total_duration = $_POST['total_duration'];
$desc_duration = $_POST['desc_duration'];

$sql = "INSERT INTO vote.duration(total_duration, desc_duration) VALUES ($total_duration, $desc_duration)";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "
" . $conn->error;
}

$conn->close();
?>

Why are you setting NULL the id_duration? Make it AutoIncrement if you don't want to insert value every time.


text:
Q: DevExpress cxDBFilterControl value enumeration I am trying to enumerate the criteria in cxDBFilterControl, including any groups.
The field name, operator, value fields.
cxDBFilterControl1.ApplyFilter;
Memo1.Lines.Add(cxDBFilterControl1.FilterCaption);
Memo1.Lines.Add('');
for ci := 0 to cxDBFilterControl1.Criteria.Root.Count - 1 do begin
  if not cxDBFilterControl1.Criteria.Root.Items[ci].IsItemList then begin
    Memo1.Lines.Add(
//    ((cxDBFilterControl1.Criteria.Root.Items[ci] as TcxFilterCriteriaItem).ItemLink as TcxFilterItem).FieldName +' : '+ // typecast issue
      (cxDBFilterControl1.Criteria.Root.Items[ci] as TcxFilterCriteriaItem).Operator.DisplayText +' : '+
      (cxDBFilterControl1.Criteria.Root.Items[ci] as TcxFilterCriteriaItem).DisplayValue
);
  end
  else begin
  end;
end;

The above code will list the root level criteria without the field names, how can I get the field names also along with any added groups and their operators?
cxDBFilterControl1.FilterCaption output:
(id = 1) and (ttype > 4) and ((tdate < 2/2/2014) or (outcome = test))

The enumerated output should be something like:
id equals 1
AND
ttype equals 4
AND
  tdate lessthan 2/2/2014
  OR
  outcome equals test

A:
procedure Form1.Test
begin
  PrintFilter(Memo1, cxDBFilterControl1.Criteria.Root);
end;

procedure PrintFilter(Memo: TMemo; ARoot: TcxFilterCriteriaItemList; Level: integer = 0);
var
  I: Integer;
  Op: string;
  Line: string;
  LItemLink: TObject;
  LItem: TcxFilterCriteriaItem;
begin
  for I := 0 to ARoot.Count - 1 do
  begin
    //extract into a function?
    case ARoot.BoolOperatorKind of
      fboAnd: Op := 'AND';
      fboOr: Op := 'OR';
      fboNotAnd: Op := 'NOT AND';
      fboNotOr: Op := 'NOT OR';
    end;
    //
    if not ARoot.Items[I].IsItemList then
    begin
      if I <> 0 then
        Memo.Lines.Add(StringOfChar(' ', Level * 2) + Op);
      LItem := (ARoot.Items[I] as TcxFilterCriteriaItem);
      LItemLink := LItem.ItemLink;
      if (LItemLink <> nil) and (LItemLink is TField) then
        Line := TField(LItemLink).DisplayName;
      Line := Line + ' ' + LItem.Operator.DisplayText +' '+ LItem.DisplayValue;
      Memo.Lines.Add(StringOfChar(' ', Level * 2) + Line)
    end else
    begin
      if TcxFilterCriteriaItemList(ARoot.Items[I]).Count > 0 then
        Memo.Lines.Add(StringOfChar(' ', Level * 2) + Op);
      PrintFilter(Memo, TcxFilterCriteriaItemList(ARoot.Items[I]), Level + 1);
    end;
  end;
end;


text:
Q: Does maximum likelihood minimize a kind of generalized "0-1 loss"? A very good point was raised here about how the optimal betting strategy under 0-1 loss was to bet on the mode, while under MSE loss the optimal strategy was to bet on the mean.
Maximum likelihood is, in many cases, equivalent to a posterior mode. Does the "all-or-nothing loss function" analogy extend to more general cases? Is MLE sub-optimal, in a decision-theoretic sense, for statistical inference, as compared to something like least squares?

A: I am not sure what you mean by "does 0-1 loss function analogy extend to more general cases?"
As you noted, depending on your loss function, you can find a different point estimate that maximizes your posterior.  For e.g., if you care about least-squares error, you would pick the posterior distribution's mean.  For absolute value loss, you pick the median.  Here is a doc that outlines proofs for all these http://www.cogsci.ucsd.edu/~ajyu/Teaching/Tutorials/bayes_dt.pdf.
However, note that the full information for decision making is contained in the distribution in the spirit of true Bayesian thinking.


text:
Q: hangs after install of PV drivers After installing the 32-bit PV drivers (0.97.4) on a 32-bit Windows Server 2003
SP2 guest, the system will hang and/or BSOD on subsequent reboots.
Version-Release number of selected component (if applicable):
dom0: RHEL 5.3 x86_64
domU: Windows 2003 Server SP2 (32-bit)
xenpv-win-32-bit-0.97.4-3.el5
How reproducible: always
Steps to Reproduce:
1. Create win2k3 guest
2. Install PV drivers
3. Reboot
4. Configure PV NIC driver
5. Reboot
Actual results:
System will hang immediately after login on final reboot
Expected results:
No hang
Additional info:
I've found that if I apply all the latest patches to Win2k3 after guest OS
install that instead of a hang I get a BSOD. If I do not install the latest
patches it simply hangs (totally unresponsive to all user input).
If I do not install the PV drivers, everything works fine. I can reboot
multiple times with no issues. As I'm only utilizing the PV NIC in my
configuration, my assumption is that the issue is with the PV NIC driver.

A: The issue is probablt with the PV disk controller driver. If you installed windows using generic IDE/SCSI, changing the controller type to PV will make the VM BSOD on boot.
The VM should have been installed with the PV drivers slipstreamed into the windows installation CD


text:
Q: External file (image, css, js) can not loaded in Struts2 I want to ask why my external css/js was not load in my jsp.
My struts.xml content :
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
  "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<constant name="struts.action.extension" value=""/>

<package name="default" namespace="/" extends="struts-default">

    <default-action-ref name="home" />

    <action name="home">
        <result name="success">index.jsp</result>
    </action>

</package>

</struts>

My web.xml content :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
       http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
       version="2.5">

<display-name>Test</display-name>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<error-page>
    <error-code>404</error-code>
    <location>error404.jsp</location>
</error-page>

</web-app>

I load my css in my jsp using this code
<link rel="stylesheet" type="text/css" href="../style/css/style.css"/>

I also try use this code
<link rel="stylesheet" type="text/css" href="<s:url value="/style/css/style.css"/>"/>

even, it's get error when I want to display an image on my jsp
<img src="<s:url value="/style/images/icon/car.png"/>" />

What wrong with this, whether cause of this code (web.xml)
<filter-mapping>
   <filter-name>struts2</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

Thank you for your response.

A: turned out just because this code in my struts.xml
<constant name="struts.action.extension" value=""/>

when i remove it, everything work fine. Sorry n thank u

A: For sure this is a path problem. You can use Firebug with Network to see which exact URL the browser is trying to load. After that, you will be able to correct the css URL. For sure you can't use  insite a tag.

A: Your Filters are blocking those images,CSS

A: Your external folder is not in the root of the webserver; so it dosen't recognize it, then you have to add it


text:
Q: Get data from sql datasource into asp.net controls I have a sqldatasource with a very simple select statement that should always return one row. I have textboxes on a page that i want to fill with that data from the datasource. how could i do this for textboxes? If there is no data in the database then i want the textboxes to remain empty. How can I accomplish this?
<asp:Panel ID = "Panel2" runat="server" DefaultButton = "save" >
                        <fieldset style="width: 524px"><legend>Rouse InterChange Details</legend>
                        <asp:FormView runat="server" ID="MyFormView" DataSourceID="SqlDataSource3" DefaultMode="Edit">
                        <ItemTemplate >

                                Interchange ID:

                                    <asp:TextBox ID="txtIntID" runat="server" size="1" MaxLength = "2" Text='<%# Bind("Interchange_Id") %>'></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator8" ValidationGroup = "rouse"  Display ="None" ControlToValidate = "txtIntID" runat="server" ErrorMessage="You Must Provide an Interchange ID."> </asp:RequiredFieldValidator>
                                             <ajaxToolkit:ValidatorCalloutExtender ID="ValidatorCalloutExtender11" TargetControlID="RequiredFieldValidator8" HighlightCssClass="validatorCalloutHighlight" runat="server">
                                             </ajaxToolkit:ValidatorCalloutExtender>

                                Sender ID:

                                    <asp:TextBox ID="txtsender" runat="server" MaxLength = "15" ></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator9" ValidationGroup = "rouse"  Display ="None" ControlToValidate = "txtsender" runat="server" ErrorMessage="You Must Provide a Sender ID."> </asp:RequiredFieldValidator>
                                     <ajaxToolkit:ValidatorCalloutExtender ID="vce12" TargetControlID="RequiredFieldValidator9" HighlightCssClass="validatorCalloutHighlight" runat="server">
                                     </ajaxToolkit:ValidatorCalloutExtender>

                                Interchange Standard ID:

                                    <asp:TextBox ID="ISI" runat="server" size="1" MaxLength = "1" ></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator10" ValidationGroup = "rouse"  Display ="None" ControlToValidate = "ISI" runat="server" ErrorMessage="You Must Provide an Interchange Standard ID."> </asp:RequiredFieldValidator>
                                     <ajaxToolkit:ValidatorCalloutExtender ID="ValidatorCalloutExtender12" TargetControlID="RequiredFieldValidator10" HighlightCssClass="validatorCalloutHighlight" runat="server">
                                     </ajaxToolkit:ValidatorCalloutExtender>

                                Version:

                                    <asp:TextBox ID="Verstxt" runat="server" size="5" MaxLength = "5" ></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator11" ValidationGroup = "rouse"  Display ="None" ControlToValidate = "Verstxt" runat="server" ErrorMessage="You Must Provide a Version."> </asp:RequiredFieldValidator>
                                     <ajaxToolkit:ValidatorCalloutExtender ID="ValidatorCalloutExtender13" TargetControlID="RequiredFieldValidator11" HighlightCssClass="validatorCalloutHighlight" runat="server">
                                     </ajaxToolkit:ValidatorCalloutExtender>

                                Functional ID:

                                    <asp:TextBox ID="FuncID" runat="server" size="1" MaxLength = "2" ></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator12" ValidationGroup = "rouse"  Display ="None" ControlToValidate = "FuncID" runat="server" ErrorMessage="You Must Provide a Functional ID."> </asp:RequiredFieldValidator>
                                     <ajaxToolkit:ValidatorCalloutExtender ID="ValidatorCalloutExtender14" TargetControlID="RequiredFieldValidator12" HighlightCssClass="validatorCalloutHighlight" runat="server">
                                     </ajaxToolkit:ValidatorCalloutExtender>

                                Group Control #

                                    <asp:TextBox ID="txtGroupcontrol" runat="server" size="6" MaxLength = "9" ></asp:TextBox>

                        </ItemTemplate>
                        </asp:FormView>
                        <asp:SqlDataSource ID="SqlDataSource3" runat="server"
                        ConnectionString="connectionstring"
                        SelectCommand="select * from table1 "></asp:SqlDataSource>
                        </fieldset></asp:Panel>

A: You should consider using a FormView control to do this.  Using the binding controls is much easier and cleaner than trying to cram all of your code into the code-behind of the page.  I also feel that it makes the page much easier to maintain, since you don't have all of the C#/VB code to manage as well.
<asp:FormView runat="server" ID="MyFormView" DataSourceID="MySqlDataSource" DefaultMode="Edit">
    <EditItemTemplate>

                Interchange ID:

                    <asp:TextBox ID="txtIntID" runat="server" Text='<%# Bind("InterchangeID") %>' size="1" MaxLength = "2"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator8" ValidationGroup = "rouse"  Display ="None" ControlToValidate = "txtIntID" runat="server" ErrorMessage="You Must Provide an Interchange ID."></asp:RequiredFieldValidator>
                    <ajaxToolkit:ValidatorCalloutExtender ID="ValidatorCalloutExtender11" TargetControlID="RequiredFieldValidator8" HighlightCssClass="validatorCalloutHighlight" runat="server">                                             </ajaxToolkit:ValidatorCalloutExtender>

    </EditItemTemplate>
</asp:FormView>
<asp:SqlDataSource runat="server" ID="MySqlDataSource"
    SelectCommand="SELECT * FROM MyTable" ConnectionString="<%$ ConnectionStrings:MyConnectionString %>" >
</asp:SqlDataSource>

See these links for more information:

*

*http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.formview.aspx

*http://quickstarts.asp.net/QuickStartv20/aspnet/doc/ctrlref/data/formview.aspx

A: The easiest way (that I would think to do this) is to write all the data access and form population in the code-behind. I am a little confused, however, that you tagged this as both C# and VB.net. I'll update this post shortly with some C# example code; in the meantime feel free to start comment-spamming with questions. :)

A: I like using this in the code behind:
GridView1.DataSource = getQuery(ConnectionString, "select * from mytable");
GridView1.DataBind();

 private DataTable getQuery(string ConnStr, string query)
    {
        DataTable dt = new DataTable();

        try
        {
            using (SqlConnection conn = new SqlConnection(ConnStr))
            using (SqlDataAdapter cmd = new SqlDataAdapter(query, conn))

                cmd.Fill(dt);
        }
        catch { }
        return dt;
    }

of course not all the details are here

A: I do this all the time in C# as opposed to "default" loading data from the controls themselves. That way I know that when my webpage loads, I control the data load, not ASP! My method below is also great in avoiding generating connectors, datasets, and other controls just to get one piece of data from one row, from one table for example.
                SqlDataSource sdsClogdetails = (SqlDataSource)gvRow.FindControl("sdsCLdetails");
                if (sdsClogdetails != null)
                {
                    DataView dv = sdsClogdetails.Select(DataSourceSelectArguments.Empty) as DataView;
                    if (dv != null)
                    {
                        DataTable dt = dv.ToTable() as DataTable;
                        if (dt != null)
                        {
                            DataRow dr = (DataRow)dt.Rows[0];
                            txtCLOG.Text = dr.ItemArray[3].ToString();
                        }
                    }
                }

So in my example, the ASP control I want to place data into is called txtCLOG, which is a TextBox control. Obviously the data is inside the dataset 3 cells along. So if your datasource returns 10 columns of data, then my example would bring in the 3rd column's data into the textbox control.
Using the above code, or similar, I get to hit many birds with one stone and I don't have to manage disposing of controls held in memory either. Of course a better way to have done the above is to use the USING statement.


text:
Q: Product of a digit with a shell script How do I get the product of a 1 number in bash? (12345 > 1x2x3x4x5)
I am trying to get a script to do multiplication, I have tried escaping the * char but no luck, I have also tried fiddling with expr.
echo -n "Enter number "
read n

len=$(echo $n | wc -c)

len=$(( $len - 1 ))

for (( i=1; i <= $len; i++ ))
do
   prod=$(($prod \* $(echo $n | cut -c $i) ))
done
echo "Product of $n is $prod"

A: You can get the length of a string from parameter expansion, no need to call external tools.
#!/bin/bash
read -p 'Enter number: ' n

product=1
for (( i=0; i < ${#n}; ++i )) ; do
    d=${n:i:1}
    (( product *= d ))
done
printf '%d\n' $product

And, for fun, using Perl:
perl -MList::Util=product -le 'print product(split //, shift)' -- "$n"

A: gawk (GNU awk) solution:
echo 12345 | awk -v FPAT="[0-9]" '{ r=$1; for(i=2;i<=NF;i++) r=r*$i }END{ print r }'

The output:
120

*

*FPAT="[0-9]" - represents field value so that each field contains a digit

A: As I understood you want to get value of digits multiplication in number
Suppose you have number:
number=12345

You have to insert * between digits:
echo $number | sed 's/\([0-9]\)/\1*/g'

We will get string:
1*2*3*4*5*

We don't need last asteriks - let's remove it:
echo $number | sed 's/\([0-9]\)/\1*/g' | sed 's/.$//g'

We will get this:
1*2*3*4*5

We can now redirect it to calc:
echo $number | sed 's/\([0-9]\)/\1*/g' | sed 's/.$//g' | calc -p

It's stdout is:
120

A: \* is wrong in an arithmetic expression, it should be * alone. But even then running your code gives:
$ bash product.sh
Enter number 12
product.sh: line 10: * 1 : syntax error: operand expected (error token is "* 1 ")
Product of 12 is

The reason for the error is that $prod variable is not set to an
initial value before so it's expanded to an empty value, for example
try it in your terminal:
$ echo $prod

$

In your script you should set prod to an initial value before using
it for the first time. It should be:
echo -n "Enter number "
read n

len=$(echo $n | wc -c)

len=$(( $len - 1 ))

prod=1

for (( i=1; i <= $len; i++ ))
do
    prod=$(($prod * $(echo $n | cut -c $i) ))
done
echo "Product of $n is $prod"

There are a few more problems with your code:

*

*always put a shebang line at the top

*always double quote the variables

*using $ on variables is not necessary in arithmetic expressions in Bash


text:
Q: Swashbuckle No Operations Defined on PCF. Works local dev I have read numerous articles, upgraded, downgraded, even sidegraded and nothing is working to show swagger definitions on PCF.
What makes it extra tough is that it works locally running VS 2019 IIS Express but when I push to PCF it fails. What I mean by fails is the swagger UI loads but there are no operations defined.
Tech Spec:
AspNetCoreAll 2.2.0
Swashbuckle.AspNetCore 4.0.1
Swashbuckle.AspNetCore.Annotations 4.0.1
swagger-codegen-cli-2.3.0
PCF
buildpack: dotnet_core_buildpack_2_2_5
stack: cflinuxfs3
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services
            .AddSwaggerGen(c =>
            {
                c.SwaggerDoc("1.0.0", new Info
                {
                    Version = "1.0.0",
                    Title = "MyAPI",
                    Description = "MyAPI (ASP.NET Core 2.2)",
                    Contact = new Contact()
                    {
                       Name = "Production Support Team",
                       Url = "https://github.com/swagger-api/swagger-codegen",
                       Email = "email@domain.com"
                    },
                    TermsOfService = ""
                });
}

public void Configure(...)
{
        .UseSwagger()
        .UseSwaggerUI(c =>
        {
            //string swaggerJsonBasePath = string.IsNullOrWhiteSpace(c.RoutePrefix) ? "." : "..";
            //c.SwaggerEndpoint($"{swaggerJsonBasePath}/swagger/1.0.0/swagger.json", "ipt-client-mobile-bff");

            c.SwaggerEndpoint("/swagger/1.0.0/swagger.json", "MyAPI");

        });

I also found this: openapi-original.json and that looks a lot like my swagger operations....??
Some things I am unclear on.
I thought the swagger.json was generated on the fly when you hit the /swagger endpoint and the Swagger-UI loads.
However the PCF guy is saying it is generated at build time and the reason it isn't showing on PCF is because my PCF packaging and build process isn't including it.
Whichever it is I can't find a swagger.json on disk making me suspect it is generated on the fly and in memory.
Also there are no errors thrown in the PCF logs or the F-12 Dev tools.
Any ideas would be greatly appreciated.
TIA

A: Quite interestingly...I removed a 3rd party library because it failed a security scan and then pushed to dev / qa...and my swagger started working again!
I have notified the manufacturer of the third party library of both issues.


text:
Q: How do I add tag to a document that is added dynamically to a template? I was able to successfully add a document to a template via the API and now I would like to add multiple signature tabs and initial tabs to the document that I just added via the API using the .net c# library.  I created the tabs below and created the envelope and added the document.  Do I have to add the tabs to the document or the template or something else?
//Create tabs to be added to do the document.
Tabs tabList = new Tabs()
{
    signHereTabs = new Tab[]
    {
        new Tab()
        {
            documentId = 5,
            pageNumber = 1,
            xPosition = 100,
            yPosition = 150
        }
    },
    initialHereTabs = new Tab[]
    {
    new Tab(){
        documentId = 5,
        pageNumber = 1,
        xPosition = 100,
        yPosition = 150
    }
    }
};

//Create template envolope and its template role

byte[] ips = GetIPS("");

RestSettings.Instance.DocuSignAddress = "https://demo.docusign.net";
RestSettings.Instance.WebServiceUrl = RestSettings.Instance.DocuSignAddress + "/restapi/v2";
RestSettings.Instance.IntegratorKey = integratorKey;

DocuSign.Integrations.Client.Account account = new DocuSign.Integrations.Client.Account();
account.Email = username;
account.Password = password;
var loginResult = account.Login();

Template template = new Template();

template.TemplateId = templateId;
template.Login = account;

template.EmailSubject = emailSubject;
template.EmailBlurb = emailMessage;
var documents = template.GetDocuments();

var roles = new List<TemplateRole>();

//Handle Primary Client
roles.Add(new TemplateRole
{
    roleName = "Primary Client",
    name = primaryClientName,
    email = primaryClientEmail,

    tabs = new RoleTabs
    {
    textTabs = new RoleTextTab[] {
        new RoleTextTab {
        tabLabel = "FeeEffectiveDate",
        value = effectiveDate
        },
        new RoleTextTab {
        tabLabel = "FeePercentage",
        value = fee
        }
    },
    },
});

if (secondaryClientName.Trim().Length != 0)
{
    roles.Add(new TemplateRole
    {
    roleName = "Secondary Client",
    name = secondaryClientName,
    email = secondaryClientEmail,
    });
}

roles.Add(new TemplateRole
{
    roleName = "President",
    name = presidentName,
    email = presidentEmail
});

roles.Add(new TemplateRole
{
    roleName = "Css",
    name = cssName,
    email = cssEmail
});

template.TemplateRoles = roles.ToArray<TemplateRole>();

template.Status = "created";
var result = template.Create();

//Add the document to the template
bool status = template.AddDocument(ips, "IPS.pdf", 5);

//-------------------------------------------------------------------------
//Now I need to add tabslist created previously to the document.  How do I do this?
//--------------------------------------------------------------------------

template.Status = "sent";
result = template.UpdateStatus();
return result;

A: I was able to do this after several trial and error.  The Tag/Tabs needs to be added to the template using its AddTabs function.
TabCollection ipsTabs = new TabCollection();
ipsTabs.signHereTabs = new List<Tab>();
ipsTabs.signHereTabs.Add(new Tab()
{
    documentId = 5,
    anchorString = "soc1",
    recipientId = "1",
    xPosition = 100,
    yPosition = 150
});
ipsTabs.signHereTabs.Add(new Tab()
{
    documentId = 5,
    anchorString = "soc2",
    recipientId = "2",
    xPosition = 100,
    yPosition = 150
});
ipsTabs.initialHereTabs = new List<Tab>();
ipsTabs.initialHereTabs.Add(new Tab()
{
    documentId = 5,
    anchorString = "ci1",
    recipientId = "1",
    xPosition = -100,
    yPosition = 150
});
ipsTabs.initialHereTabs.Add(new Tab()
{
    documentId = 5,
    anchorString = "ci2",
    recipientId = "2",
    xPosition = -100,
    yPosition = 150
});
var tabstatus = template.AddTabs(ipsTabs);


text:
Q: How can I make the card component work with react-split-pane component? Here is my code.
My problem is, how can I use the card component to fill the first pane of the SplitPane without using h-100 class?
It is because when I use h-100 class for the Card component, it spoils the layout when the users click on the input box on the mobile platform.
I tried to use the "flex-grow-1" class to solve the problem, however, it does not work.
Besides that, I am not sure whether the react-split-pane its own handling method for the orientation change event. If so, please let me know.

A: Implementation using flex-grow-1 will not work because if you inspect the elements, the parent of the Card component is an additional div element generated by the SplitPane and is not a flex container.
You can still use h-100 but in order to solve the layout issues on "small window.innerHeight" devices (such as the scenario you described like opening the virtual keyboard on a mobile devices), you simply need to make tweaks in your condition statements to assess whether the SplitPane should switch split prop of horizontal or vertical
In my example below you can see that I factor in a "minimum width" for the left pane to consider the width of the input field on your StackBlitz example code which is set to 182px as I reviewed.
this.setOrientation = () => {

  let leftPanelMinWidth = 182;

  if (window.innerHeight > window.innerWidth - leftPanelMinWidth) {
    this.setState({ splitDirection: "horizontal" });
  } else {
    this.setState({ splitDirection: "vertical" });
  }
}

I imagine you can implement the same in logic when the component mounts.


text:
Q: Angular displacment and "normal" displacment of a minutes hand in a clock/watch Note : i'm using "normal" because i'm not really sure what is its correct name, i suppose linear is more correct.
as a backstory, we were solving questions in today's class and this came up ( roughly translated ) :

does each part of the minutes hand have the same angular displacment? Does it have the same "normal" displacment?

Now me and the teacher both agreed that the angular displacment should be equal and weren't sure about the other one, but it says in the solutions manual that :

the "normal" displacment isn't equal, because $d$ is a function of $r$.

we use the relation $d=r\theta$ ( i suppose it should be $\Delta\theta$ but i will stick with curriculum, also r is the radius )
here was my argument :
if for the sake of contradiction we indeed had the "normal" displacment $d$, isn't equal then we should be able to find $d_1$ and $d_2$ such that for $d_1\not=d_2$ :
$$d_1=r\theta \implies \theta=\frac{d_1}{r}$$
similarily :
$$d_2=r\theta \implies \theta=\frac{d_2}{r}$$
now since the angular displacment is the same :
$$ \frac{d_1}{r} = \frac{d_2}{r} \implies d_1 = d_2 $$
which is a contradiction.
Now this would be evidently correct ( i think ) if the clock/watch was a circle, since r is fixed ( wasn't mentioned in the question ).
am i missing something?, everywhere i looked said that the " normal " displacment isn't the same, but i don't find it logical

A: Is arc length the term you are looking for?
The angular displacement of each part of the minute hand is the same. But each travels a different arc length. This is because r is not the same for all parts of the minute hand.
If the point at the end of the minute hand is at distance $r$ from the center, the point in the middle is at $r/2$.


text:
Q: How can I await multiple futures, at once, that are nested inside a map? I have a Map<String, List<Future<Foo>>> that I want to convert to a Map<String, List<Foo>> (wait for futures to finish). Currently, this is how I perform the operation:
// source contains values with an async operation; convert to a map
final futures = source.map(
  (k, v) => MapEntry(k, v.map((e) async => await e.asyncOperation())),
);

final json = {};

// works, but must wait for each entry to process
for (final kvp in futures.entries) {
  json[kvp.key] = await Future.wait(kvp.value);
}

This will block for every entry sublist, is there a way to generate the proper Map<String, List<Foo>> while at the same time awaiting all of the inner list futures?
I can do await Future.wait(futures.values.flattened);, but how would I reassign the results back to the proper map key?

A: One reason to complete all the futures immediately would be that they already exist, and if you don't await all of them immediately, one of them might complete with an (unhandled!) error, which is bad.
The standard provided way to wait for more than one future at a time is Future.wait, which takes an Iterable<Future<X>> and returns a Future<List<X>>.
That will directly help you with the individual lists, but then you'll have a Future<List<Foo>> per key in the map. You'll have to convert those to a list too.
So, maybe something like:
Future<Map<String, List<Foo>>> waitAll(
    Map<String, Iterable<Future<Foo>>> map) async =>
  Map.fromIterables(map.keys.toList(), await Future.wait(map.values.map(Future.wait));

A: You will want to call Future.wait<Foo> on each of the inner List<Future<Foo>>s.  Each of those will return a Future<List<Foo>>; collect those Futures into their own list, and then use Future.wait again on that.
As you mentioned, the tricky part is assigning to results to the desired locations.  You can use Future.then to register a completion callback for each of the Future<List<Foo>>s that assigns the resulting List<Foo> to the new Map.  This is one situation where mixing Future.then with await is a little bit more straightforward than using just await. (It's still possible with await, but it's more awkward.)
For example:
import 'dart:async';

/// Randomized delays to test correctness.
final delays = <int>[for (var i = 0; i < 9; i += 1) i]..shuffle();

/// Returns `result` after a randomized delay.
Future<int> f(int result) async {
  var index = result - 1;
  assert(index >= 0);
  assert(index < delays.length);
  await Future.delayed(Duration(seconds: delays[result - 1]));
  return result;
}

var map = <String, List<Future<int>>>{
  'foo': [f(1), f(2), f(3)],
  'bar': [f(4), f(5), f(6)],
  'baz': [f(7), f(8), f(9)],
};

Future<void> main() async {
  var newMap = <String, List<int>>{};
    await Future.wait<void>([
    for (var key in map.keys)
      Future.wait<int>(map[key]!).then((list) => newMap[key] = list),
  ]);

  print(newMap); // Prints: {foo: [1, 2, 3], bar: [4, 5, 6], baz: [7, 8, 9]}
}

Note that the above does not guarantee that newMap preserves the order of keys in the Map.  If you care about that, then an easy way to preserve the key order is to pre-add them to the new Map:
var newMap = {for (var key in map.keys) key: <int>[]};

or alternatively, remove and re-add them in the desired order afterward:
for (var key in map.keys) {
  newMap[key] = newMap.remove(key)!;
}


text:
Q: bash remove duplicate string from list I want to delete duplicate strings from a String. Example:
A="Dog Cat Horse Dog Dog Cat"

The string A should look like this:
A="Dog Cat Horse"

How can I write a Shell script for that?

A: You could use this,
echo "a a b b c c" | tr ' ' '\n' | sort | uniq | tr '\n' ' ' | sed -e 's/[[:space:]]*$//'

A: If order is not important, you can use an associative array:
declare -A uniq
for k in $A ; do uniq[$k]=1 ; done
echo ${!uniq[@]}

A: *

*(Safely) split the string on blanks, creating an array with each word:†
read -r -d '' -a words < <(printf '%s\0' "$A")

*Loop on the fields of the array, storing the words into an associative array; if the word was already seen, ignore it
declare -A Aseen
Aunique=()
for w in "${words[@]}"; do
    [[ ${Aseen[$w]} ]] && continue
    Aunique+=( "$w" )
    Aseen[$w]=x
done

*You can print the Aunique array to standard output:
printf '%s\n' "${Aunique[@]}"

which yields:
Dog
Cat
Horse

or create a new string with it
Anew="${Aunique[*]}"
printf '%s\n' "$Anew"

which yields:
Dog Cat Horse

or join the array with a separator, e.g., with the character ,:‡
IFS=, eval 'Asep="${Aunique[*]}"'
printf '%s\n' "${Asep[@]}"

which yields:
Dog,Cat,Horse

All these use Bash≥4 features. If you're stuck on older Bash versions, there are workarounds but it won't be as safe and nice and easy…
Note. This method will not sort the string: the words remain in the original order, only with the duplicates removed.

†This is the canonical (and safe!) way to split a string on space characters (or, more generally on the characters contained in the special variable IFS, which has default value space-tab-newline). Don't use horrors like words=( $A ): it's subject to filename expansion (globbing). Another method widely encountered is read -r -a words <<< "$A"; this is fine (i.e., safe), but will not handle newlines in A.
‡The use of eval here is 100% safe (because of the single quotes); it's actually the canonical way to join the elements of an array in Bash (or to join the positional parameters in POSIX shells).

A: With gawk:
 awk -v RS="[ \n]" -v ORS=" " '!($0 in a){print;a[$0]}' <(echo $A)


text:
Q: How to navigate to a working directory in ProcessBuilder I am trying use Process builder and execute a cleartool command from a drive setup for clearcase. Below is my code and it seems to return null. Can any one please suggest how to fix this issue.
String[] cmdList = {"cmd.exe","/C","M:", "cd Test_SrcCd_Dev_Dyn","cleartool lsactivity -l TestActivity@My_PVOB"};
ProcessBuilder builder = new ProcessBuilder(cmdList);

My clearcase repository is configured in M: drive.
Thanks in advance.

A: Try to simplify the sequence of command to make sure you are in the right directory.
But first:
cleartool lsactivity -l TestActivity@My_PVOB

This should work from any directory (except you need to be in the view to resolve the extended pathnames of the file)
Can you first confirm that this works?
String[] cmdList = {"cmd.exe","/C", "cleartool lsactivity -l TestActivity@My_PVOB"};

You can also replace in your original command your cleartool lsact by a:
cleartool pwv

To check you are in the right directory/view.
Try also to display the path, to check that 'cleartool.exe' is in it.


text:
Q: Problem sending data over UDP sockets This is kind of a followup to the question I had yesterday. I had a homework assignment to send and receive data with a client/server TCP socket connection. I would like to make a version of it using UDP. The idea is that I can redirect standard I/O and send the streams using UDP. For example, if I type in:
 server: java UDPServer 5555 < file1.txt
 client: java UDPClient localhost 5555 > file2.txt

It should send the data in file1.txt from the server to client's file2.txt. When I run the client/server pair in separate terminals, file2.txt is created but the data is never actually sent. Instead it seems like I am stuck in an infinite loop, where I cannot enter anything into the terminal unless I kill the application.
The server code is:
public static final int BUF_SIZE = 256;

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

    port = Integer.parseInt(args[0]);

    DatagramSocket serverSocket = new DatagramSocket(port);

    BufferedInputStream input = new BufferedInputStream(System.in);
    BufferedOutputStream output = new BufferedOutputStream(System.out);

    byte[] receiveData = new byte[BUF_SIZE];
    byte[] sendData = new byte[BUF_SIZE];
    byte[] buf = new byte[BUF_SIZE];
    String sentence;

    if(System.in.available() > 0) {
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        serverSocket.receive(receivePacket);
        InetAddress address = receivePacket.getAddress();
        int bytesRead = 0;
        while((bytesRead = input.read(buf, 0, BUF_SIZE)) != -1) {
            sentence = new String(buf, 0, bytesRead);
            sendData = sentence.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address, port);
            serverSocket.send(sendPacket);
        }
    } else {
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        serverSocket.receive(receivePacket);
        sentence = new String(receivePacket.getData());
        output.write(sentence.getBytes());
    }

    serverSocket.close();
    input.close();
    output.close();
}

And the client code is:
public static final int BUF_SIZE = 256;

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

    String hostName = args[0];
    port = Integer.parseInt(args[1]);

    DatagramSocket clientSocket = new DatagramSocket();
    InetAddress address = InetAddress.getByName(hostName);

    BufferedInputStream input = new BufferedInputStream(System.in);
    BufferedOutputStream output = new BufferedOutputStream(System.out);

    byte[] sendData = new byte[BUF_SIZE];
    byte[] receiveData = new byte[BUF_SIZE];
    byte[] buf = new byte[BUF_SIZE];
    String sentence;

    if(System.in.available() > 0) {
        int bytesRead = 0;
        while((bytesRead = input.read(buf, 0, BUF_SIZE)) != -1) {
            sentence = new String(buf, 0, bytesRead);
            sendData = sentence.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address, port);
            clientSocket.send(sendPacket);
        }
    } else {
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.receive(receivePacket);
        sentence = new String(receivePacket.getData());
        output.write(sentence.getBytes());
    }

    clientSocket.close();
    input.close();
    output.close();
}

I am still new to socket programming so I am basing this off of example code in my textbook. Is there some glaring mistake that I am making that is preventing the data from being transferred? Thanks very much for your patience and help!

A: The first problem you have is that client.main doesn't run because your shell command is wrong. For some reason, with Java you can't redirect output how it's traditionally done. You can simply put a few print statements at the beginning of client.main to see nothing executes. Try this:
java UDPClient localhost 5555 | tee file2.txt

See redirect Java output.
The other problem you have is that both the client and server are waiting to receive a datagram. You have in the server code:
if(System.in.available() > 0) {
    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);

And you have in the client code:
else {
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        serverSocket.receive(receivePacket);
        sentence = new String(receivePacket.getData());
        output.write(sentence.getBytes());
        }

Note that the else statement will always execute because System.in.available will always return 0. Remember your not redirecting input to the client, so there's nothing in System.in. To fix this you need to first send a client datagram so that the server can respond with the contents of file2.txt.

A: You're missing all the things you need to do to make this work. Where's the code to do transmit pacing, retransmissions, acknowledgements, reordering, and so on? If you want to use UDP, you have to do yourself all the things TCP does for you.
See, for example RFC 1350 for an example of a file transfer protocol layered on top of UDP.


text:
Q: LUKS LVM device mapped by UUID instead of e.g. sda5_crypt I have a laptop with what I believed to be basic LUKS single-disk from a fresh 14.04 install. After updating to 16.04, I found my initrd had no LUKS support so I couldn't boot.
The culprit seems to be that my /dev/mapper has no "sda5_crypt" entry but instead dm-0 is linked by the physicald disks UUID.  Presumably this is because something in the initrd does the equiv of cryptsetup open /dev/sda5 UUID=xxx (instead of sda5_crypt as the last parm)
$ ls -l /dev/mapper
total 0
crw------- 1 root root 10, 236 Aug  3 13:05 control
lrwxrwxrwx 1 root root       7 Aug  3 13:05 f401322a-1596-47e7-a1c8-844ba27ef326 -> ../dm-0
lrwxrwxrwx 1 root root       7 Aug  3 13:05 ubuntu-root -> ../dm-1
lrwxrwxrwx 1 root root       7 Aug  3 13:05 ubuntu-swap_1 -> ../dm-2

$ sudo sfdisk -l /dev/sda
Disk /dev/sda: 238.5 GiB, 256060514304 bytes, 500118192 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x000a9196

Device     Boot  Start       End   Sectors   Size Id Type
/dev/sda1  *      2048    499711    497664   243M 83 Linux
/dev/sda2       501758 500117503 499615746 238.2G  5 Extended
/dev/sda5       501760 500117503 499615744 238.2G 83 Linux

 sudo lsblk
NAME                                     MAJ:MIN RM   SIZE RO TYPE  MOUNTPOINT
sda                                        8:0    0 238.5G  0 disk
├─sda1                                     8:1    0   243M  0 part  /boot
├─sda2                                     8:2    0     1K  0 part
└─sda5                                     8:5    0 238.2G  0 part
  └─f401322a-1596-47e7-a1c8-844ba27ef326 252:0    0 238.2G  0 crypt
    ├─ubuntu-root                        252:1    0 230.3G  0 lvm   /
    └─ubuntu-swap_1                      252:2    0   7.9G  0 lvm   [SWAP]
sr0                                       11:0    1  1024M  0 rom

On a "normal" install w/ LUKS,  /dev/mapper/sda5_crypt would be the link to dm-0.  The /usr/share/initramfs-tools/hooks/cryptroot finds this device by name and looks for it as the FIRST column in /etc/crypttab which is what breaks me.
How can I influence the name in /dev/mapper?

A: Blindly answering your exact question

How can I influence the name in /dev/mapper?

Generally speaking, if you were to manually mount the LUKS encrypted hard drive  as a separate drive (not the system you're running off of) then the "sda5_crypt" mapped name is declared when you run cryptsetup luksOpen as covener has pointed out.
Since you're booting up from a system that boots and it asks you for the passphrase to continue, this process happens automatically (in the sense that you're not typing the command out yourself) and occurs behind the scenes so the name is declared by the script executing cryptsetup.
So if you want to affect the name, you would simply need to modify the script that runs cryptsetup on boot. And that is found in either:
/usr/share/initramfs-tools/scripts/local-top/cryptroot

or
/etc/initramfs-tools/scripts/local-top/cryptroot

Which you would just modify using sudo vi or sudo nano to accomplish what you're asking for.
There is likely some textbook lessons on which one should be modified here but I presume a system-wide change would be appropriate and accomplished with the latter. When you're done just remember to run the following command afterward to ensure the changes are applied:
update-initramfs -u

That's it...for your answer. It's also worth mentioning this bug from 2012 that might give good reason for not wanting to change the target name of root in /etc/crypttab

But Here's the Problem!
If your goal was to resolve boot issues, it's important to note that the reference provided above in reference to ls -l /dev/mapper is not quite what you think.
The output of ls -l is simply information about files in a given directory whereas the -l simply tells it to use a long list format. what you're seeing on the right with dm-1 and dm-02 is an indication that ubuntu-root and ubuntu-swap_1 are symbolic links that lead to dm-1 and dm-2 respectively. You can see for yourself by navigating to /dev/mapper to see for yourself:
cd /dev/mapper
stat ubuntu-root

will output something like:
File:'ubuntu-root' -> '../dm-1'
Size: 7              Blocks: 0    IO Block: 4096   symbolic link
...

So what does this all mean?
If you're having boot issues, it might not have anything to do with your /dev/mapper directory at all. You are correct, however, about the usage of the disk's UUID instead of some other mapped name such as "sda5_crypt" though that has very little to do with how you or the system would call upon the partition or would interact with the partition. And actually, when using the UUID, it offers a more robust reference where the system can even see the proper UUID prior to decryption and know that eventually, it will be the root drive it's looking for.
To elaborate, when you ran sudo lsblk above, then based on the output at that moment in time, it is known that your system has already mounted the 2 LVM drives appropriately. It's just that your "sda5" which you are expecting to become "sda5_crypt" after decryption, is what's known as an LVM, or in logical volume management form. So if you saw sda5 how the system sees it now, you'd actually see it as 3 partitions whereas if you ran lvscan it would probably report the partitions as:
/dev/ubuntu/root  mounted at "/" (AKA your current root)
/dev/ubuntu/swap_1   mounted as [SWAP] (AKA nowhere but marked as a SWAP device)
Whereas if you hypothetically were accessing it from another system where mounting it at /mnt would represent where you access this drive's root, you would've manually mounted them using a more exact 'device mapping' so-to-speak:
mount /dev/mapper/ubuntu-root  /mnt
mount /dev/mapper/ubuntu-swap_1 /rfs

Notice the difference between the two, and how it is recognized by the system using lvscan and in my hypothetically outside system view, AKA the "physical view" whereas the first would be the "virtual view".
And just for the sake of reference, if you had not decrypted the drive, you would not have been able to see the LVM partitions by its mapped name or even that there were 2 partitions within sda5.
Can't address the problem with the requested answer
Since the system seems to have mounted all the drives properly, it's best at this point to explore other causes of boot-related issues as "LUKS support" is a matter of software and meeting specific minimum hardware requirements, just to be clear.
So to recap, though it seems to indicate the root drive has an association with dm-1, it's actually showing it's a symbolic link for dm-1 and the naming scheme is actually ubuntu-root. If you have a script that calls for "sda5_crypt" then that should be changed in the script rather than attempt to change the whole system.
If you have reason to believe it boot issue is a matter of disconnect, I would check
that the UUID is mapped properly in fstab
cat /etc/fstab

and if you're still doubtful, you can check the script for cryptroot's target scheme by using
cat /etc/initramfs-tools/conf.d/cryptroot

As you'll find a line that associates cryptroot with the mapped name and assigns the source using the drive's UUID, similarly to how it's pronounced within fstab.
Notes
Other Useful tidbits for a non-booting system

*

*Running fsck which is most easily done by holding down Esc or Shift while booting up to enter the Grub Menu, selecting Advanced settings, and selecting a recovery mode which will eventually offer a menu to check filesystems, boot files, etc.

*Sometimes, a portion of the LUKS header could become corrupted which could render the header useless and thereby the data inaccessible. if you don't have a backup of the header, it may be that the corrupt key used to decrypt the masterkey may have been compromised

*dev_mapper can't see the drives until the system runs lvscan as LUKs runs as a container on top of your physical drive using LVM. Hence the need to use a "device-mapper" in the first place.

*That is to say that a udev script runs in init-premount to expose sda5_crypt before it finally will be mounted by fstab.

A: It seems like the root of this problem is using the 16.04 as a rescue CD to unlock/mount/chroot/fix packages/update-initramfs.
If you unlock the LUKS device in the boot CD's unity, it happens to call cryptsetup with the UUID.  /usr/share/initramfs-tools/hooks/cryptopen then fails to understand the slightly different naming in /etc/crypttab and decides you don't have a root device w/ LUKS.
The fix is to once again boot into the rescue CD, don't double-click the device in the unity launcher. Run
cryptsetup -v lukeOpen /dev/sda5 sda5_crypt

and proceed with the same mount/chroot/update-initramfs dance.


text:
Q: Type '[]' is missing the following properties from type ''" graphql I have a simple Resolver in typeGraphQL which findOne and returns a record against the query,i have a similar implementation for Company model that works just fine, but the Product doesnot work, let me show you my code
entity/Product.ts
import { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from "typeorm";
import { ObjectType, Field, ID } from "type-graphql";

//the field decorator represents which fields user can query

@ObjectType()
@Entity()
export class Product extends BaseEntity {
  @Field(() => ID)
  @PrimaryGeneratedColumn()
  id: number;

  @Field({nullable: true})
  @Column({length: 300, nullable: true})
  description: string;

  @Field({nullable: true})
  @Column({length: 300, nullable: true})
  image: string;

  @Field({nullable: true})
  @Column({ length: 300, nullable: true })
  stock: string;

  @Field({nullable: true})
  @Column({ length: 300, nullable: true })
  color: string;

  @Field()
  @Column({length: 300})
  name: string;

  @Field()
  @Column({length: 300})
  company_id: string;
}

Resolver
import { Resolver, Query,Arg } from "type-graphql";
import { Product } from "../../entity/Product";

@Resolver()
export class ProductResolver {

  @Query(() => Product)
  async companyProducts(
    @Arg("name") company_id: string,
  ): Promise<Product | null> {
    const product=await Product.findOne({ where: { company_id } });
    console.log(product)
    return product;
    // return product;
  }
}

the console.log() does print out the expected object but when i return I am getting
Type 'Product | undefined' is not assignable to type 'Product | null'.

any idea what might be the reason?

A: *

*Make your query nullable by @Query(() => Product, { nullable: true }).

*Change your query method return type signature to Promise<Product | undefined> or return null when product is undefined.


text:
Q: click handler not working in content script I have the following code being run via chrome extension content script. I can't get the click handler to work though. Via the run_at flag in manifest.json the script is being run at document_end. Any ideas?
$(document).ready(function () {
  var enabled = true;

  $('body').append("<button id='#alarmButton'>Disable Alarm</button>");

  $('#alarmButton').on('click', function () {
    console.log('clicked');
    if (enabled == true) {
      enabled = false;
      $('#alarmButton').text('Enable Alarm');
    } else {
      enabled = true;
      $('#alarmButton').text('Disable Alarm');
    }
  });
});

A: You don't need to add # in your id attribute.
Change
$('body').append("<button id='#alarmButton'>Disable Alarm</button>");

to
$('body').append("<button id='alarmButton'>Disable Alarm</button>");

and for click event use:
$('body').on('click', '#alarmButton', function () {})

Jsfiddle

A: You can bind the click event to the button, on create time, before appending to the document. This should work:
$(document).ready(function() {
  var enabled = true;
  $("<button id='#alarmButton'>Disable Alarm</button>")
    .appendTo('body')
    .click(function() {
      console.log('clicked');
      if (enabled == true) {
        enabled = false;
        $('#alarmButton').text('Enable Alarm');
      } else {
        enabled = true;
        $('#alarmButton').text('Disable Alarm');
      }
    });
});


text: Q: Speed up audio by time and not by percentage Is it possible to speed up audio by time and not by percentage? I have thousands of audios and I need all of them to be 1 minute. I already searched but I haven't found anything. Thank you!


text:
Q: Determine if Value in Final Column exists in respective rows I have a dataframe as follows:
df1

ColA     ColB    ColC    ColD     ColE     COlF    ColG      Recs
   1      A-1   A - 3       B        B       NA                 C
   1              B-1     C R        D        E      NA         B
   1       NA       A       B        A                          B

How do I determine if the last from the column Recs is found in it's respective row?
I tried below but it doesn't work because there are duplicates in my normal dataset:
df1$Exist <- apply(df1, 1, FUN = function(x)
            c("No", "Yes")[(anyDuplicated(x[!is.na(x) & x != "" ])!=0) +1])

There are also blanks, NA's, and character values that have spaces and dashes.
Final output should be:
ColA     ColB    ColC    ColD     ColE     COlF    ColG      Recs    Exist?
   1      A-1   A - 3       B        B       NA                 C        No
   1              B-1     C R        D        E      NA         B        No
   1       NA       A       B        A                          B       Yes

Thanks

A: For efficiency, you could use data.table here.
library(data.table)
setDT(df)[, Exist := Recs %chin% unlist(.SD), .SDcols=-"Recs", by=1:nrow(df)]

which gives

   ColA ColB ColC ColD ColE COlF ColG Recs  Exist
1:    1  A-1  A-3    B    B   NA   NA    C  FALSE
2:    1       B-1  C R    D    E   NA    B  FALSE
3:    1   NA    A    B    A        NA    B   TRUE

Original data:
df <-structure(list(ColA = c(1L, 1L, 1L), ColB = c("A-1", "", NA),
    ColC = c("A-3", "B-1", "A"), ColD = c("B", "C R", "B"), ColE = c("B",
    "D", "A"), COlF = c(NA, "E", ""), ColG = c(NA, NA, NA), Recs = c("C",
    "B", "B")), .Names = c("ColA", "ColB", "ColC", "ColD", "ColE",
"COlF", "ColG", "Recs"), row.names = c(NA, -3L), class = "data.frame")

A: exist <- rep(NA, nrow(df1))
for (i in 1:nrow(df1)) {
exist[i] <- df1$Recs[i] %in% df1[i, 1:7]
}
df1 <- cbind(df1, exist)

A: If I understood you correctly, this should work:
# Compute column index of reference variable
col_ind <- which(colnames(df1) == "Recs")

# Compute boolean vector of presence
present_bool <- apply(df1, 1, function(row) {
  any(row[col_ind] == row[-col_ind], na.rm = TRUE)
})

# Create the desired column
df1$Exist <- ifelse(present_bool, "Yes", "No")

A: This should be another way of obtaining the desired result:
f.checkExist <- function(x) {
 grepl(df[x, 8], df[x, 1:7])
}

df$exists <- grepl(T, lapply(1:nrow(df), f.checkExist))


text:
Q: Eclipse Mars disable 'revert file' button When I right click and go to save my class I have accidentally clicked this a couple of times, making it rather annoying. Is there a way I can move/disable this option?

A: If you are talking about the Revert menu item on the File menu, you can remove it by customizing the current perspective.  To do this:
Open Window=>Perspectives=>Customize Perspective
Select Menu Visibility tab
Click the '>' in front of File
Uncheck the Revert item
Click OK


text:
Q: How to overlay hatches on shapefile with condition? I've been trying to plot hatches (like this pattern, "//") on polygons of a shapefile, based on a condition. The condition is that whichever polygon values ("Sig") are greater than equal to 0.05, there should be a hatch pattern for them. Unfortunately the resulting map doesn't meet my requirements.
So I first plot the "AMOTL" variable and then wanted to plot the hatches (variable Sig) on top of them (if the values are greater than equal to 0.05). I have used the following code:
import contextily as ctx
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as ticker
from matplotlib.patches import Ellipse, Polygon
data = gpd.read_file("mapsignif.shp")
Sig = data.loc[data["Sig"].ge(0.05)]
data.loc[data["AMOTL"].eq(0), "AMOTL"] = np.nan
ax = data.plot(
    figsize=(12, 10),
    column="AMOTL",
    legend=True,
    cmap="bwr",
    vmin = -1,
    vmax= 1,
    missing_kwds={"color":"white"},
)
Sig.plot(
    ax=ax,
    hatch='//'
)
map = Basemap(
    llcrnrlon=-50,
    llcrnrlat=30,
    urcrnrlon=50.0,
    urcrnrlat=85.0,
    resolution="i",
    lat_0=39.5,
    lon_0=1,
)
map.fillcontinents(color="lightgreen")
map.drawcoastlines()
map.drawparallels(np.arange(10,90,20),labels=[1,1,1,1])
map.drawmeridians(np.arange(-180,180,30),labels=[1,1,0,1])

Now the problem is that my original image (on which I want to plot the hatches) is different from the image resulting from the above code:
Original Image -

Resultant image from above code:

I basically want to plot hatches on that first image. This topic is similar to correlation plots where you have places with hatches (if the p-value is greater than 0.05). The first image plots the correlation variable and some of them are significant (defined by Sig). So I want to plot the Sig variable on top of the AMOTL. I've tried variations of the code, but still can't get through.
Would be grateful for some assistance... Here's my file - https://drive.google.com/file/d/10LPNjBtQMdQMw6XmXdJEg6Uq4icx_LD6/view?usp=sharing

A: I'd bet this is the culprit:
data.loc[data["Sig"].ge(0.05), "Sig"].plot(
    column="Sig", hatch='//'
)

In this line, you're selecting only the 'Sig' column, eliminating all spatial data in the 'geometry' column and returning a pandas.Series instead of a geopandas.GeoDataFrame. In order to plot a data column using the geometries column for your shapes you must maintain at least both of those columns in the object you call .plot on.
So instead, don't select the column:
data.loc[data["Sig"].ge(0.05)].plot(
    column="Sig", hatch='//'
)

You are already telling geopandas to plot the "Sig" column by using the column argument to .plot - no need to limit the actual data too.
Also, when overlaying a plot on an existing axis, be sure to pass in the axis object:
data.loc[data["Sig"].ge(0.05)].plot(
    column="Sig", hatch='//', ax=ax
)


text:
Q: Add an array of objects to a PSObject at once I want to join programmatically json data from a master and a details list. A simplified example of my code would be:
$master = '[{"Sample": 1.3085},{"Sample":  1.4567}]' | ConvertFrom-Json
$detail = '[{"foo":1, "bar":2},{"foo":3, "bar":4}]' | ConvertFrom-Json

$master  | %{
    $_ | Add-Member -MemberType NoteProperty -Name 'Detail' -Value $detail -PassThru
} | ConvertTo-Json

I expect this:
[{
        "Sample": 1.3085,
        "Detail": [
                {"foo" :1, "bar":2},
                {"foo" :3, "bar":4}
            ]
        }
    }, {
        "Sample": 1.4567,
        "Detail": [
                {"foo" :1, "bar":2},
                {"foo" :3, "bar":4}
            ]
        }
    }
]

But I get that:
[{
        "Sample": 1.3085,
        "Detail": {
            "value": [
                "@{foo=1; bar=2}",
                "@{foo=3; bar=4}"
            ],
            "Count": 2
        }
    }, {
        "Sample": 1.4567,
        "Detail": {
            "value": [
                "@{foo=1; bar=2}",
                "@{foo=3; bar=4}"
            ],
            "Count": 2
        }
    }
]

It would appear to me that the Add-Member snippet converts the PSObject value to a string instead off taking it as-is.
Also: when the $master array contains only one element it works better, though not as expected, but if there are more than one it does the string-ified result shown above.
This is the results with one single item in $master:
{
    "Sample":  1.3085,
    "Detail":  {
                   "value":  [
                                 {
                                     "foo":  1,
                                     "bar":  2
                                 },
                                 {
                                     "foo":  3,
                                     "bar":  4
                                 }
                             ],
                   "Count":  2
               }
}

What am I doing wrong?

A: There are two problems with your code:

*

*You're running into a bug still present in Windows PowerShell, but since fixed in Powershell Core, which causes the unwanted value and Count properties to appear in arrays - see this GitHub issue.

*In order to ensure that the full depth of your input object tree is converted to JSON, you need to increase the default -Depth to (at least) match the actual depth.[1]
Fixing both problems yields:
# Windows PowerShell workaround for array-serialization bug.
# See https://github.com/PowerShell/PowerShell/issues/3222
Remove-TypeData -ErrorAction Ignore System.Array

$master = '[{"Sample": 1.3085},{"Sample":  1.4567}]' | ConvertFrom-Json
$detail = '[{"foo":1, "bar":2},{"foo":3, "bar":4}]' | ConvertFrom-Json

$master | ForEach-Object {
  $_ | Add-Member -MemberType NoteProperty -Name 'Detail' -Value $detail -PassThru
} | ConvertTo-Json -Depth 3  # Note the required -Depth value.

[1] Perhaps surprisingly, -Depth defaults to 2, which is a frequent pitfall for users - see this question.

A: Alright so after messing around with this for a while this is as close as I can get.
$master = '[{"Sample":1.3085},{"Sample":1.4567}]'

$detail = '[{"foo":1,"bar":2},{"foo":3,"bar":4}]'

$master = ConvertFrom-Json -InputObject $master
$detail = ConvertFrom-Json -InputObject $detail

$i = 0
$master | % {

$_ | Add-Member -Name 'Detail' -Value $detail.GetValue($i) -MemberType NoteProperty -PassThru

$i++
} | ConvertTo-Json -Depth 3

There is a problem when adding the new members to the [PSCustomObject], nothing is specifying where each value should go. Instead it is just appending all values to the new 'Detail' member. I was able to bypass this by running through a foreach loop and each iteration adds 1 to the variable $i