Passing a variable between pipes in Gulp 3.9.1

Question: Using gulp 3.9.1
I am attempting to return a bunch of files and perform a task that requires a var to be passed between two pipes.

I'm using node uuid to create a v3 UUID for each file path to
ultimately end up with a uuid for each page. I'm grabbing the file path with gulp-print.
I want to store that uuid value as a var. In the next pipe Im using
gulp-inject-string to write it into the page during the build.

Help: Either I need help getting the file path inside the gulp-inject-string pipe or I need to pass the var between the two different pipes. If I globally set a var with a default value outside the src it gets passed easily to the pipe(inject).
Super simplified code below:
// test code
var gulp = require('gulp');
var print = require('gulp-print');
var inject = require('gulp-inject-string');
var reload = browserSync.reload;

const uuidv3 = require('uuid/v3');
var uuid;

gulp.task('uuid', function() {

    return gulp.src('**/*.html'])

        // create uuid
        .pipe(print(function(filepath) {
            uuid = uuidv3(filepath, uuidv3.URL);
            return "compiled: " + filepath + ' uuid: ' + uuid;
        }))

        // need to to add UUIDv3 to each page
        .pipe(inject.before('', '<meta name="dc.identifier" content="' + uuid + '">'))
        .pipe(gulp.dest('/prod/./'))

        .pipe(reload({ stream: true }));
});

It's worth noting that I need a cross platform way to get the file path starting in the root of the project and including forward slashes. The gulp(print) does this perfectly starting at the root of the project and ignoring anything upstream from that point. The format of the path is important because it's one half of the equation in creating the uuid and the uuid's must match on Mac or PC platforms.
examples:
/index.html
/dir1/file.html
/dir1/dir2/dir3/file.html

Comment: Just declare a var before "return gulp.src...….", (or before the task altogether) , set it in the print pipe and refer to it later.  If you are worried about correct slashes look at path.sep from node's path library (and path.join too).
Comment: I can't declare the var outside the gulp src (or before the task) because then I wouldn't be using the file path of the file(s) that's returned in the src.
Answer: var gulp            = require('gulp');
var print           = require('gulp-print');
var inject          = require('gulp-inject-string');
const uuidv3        = require('uuid/v3');

var tap = require('gulp-tap');

// you can declare here
var uuid;

gulp.task('pages', function() {

    // or you can declare here
    var uuid;

return gulp.src('**/*.html')
    // bunch of stuff happens here involving templating/minifying
    // create uuid
    .pipe(print(function(filepath) {

        // then set it here and use it further below
        // it will be available

        uuid = uuidv3(filepath, uuidv3.URL);

        return "compiled: " + filepath + ' uuid: ' + uuid;
    }))
    // need to to add UUIDv3 to each page
    //.pipe(inject.before('', '<meta name="dc.identifier" content="' + uuid + '">\n'))

  .pipe(tap(function(file, t) {

    return t.through(inject.before('', '<meta name="dc.identifier" content="' + uuid + '">\n');

   })

    .pipe(gulp.dest('/prod/./'))
    .pipe(reload({stream:true}));
});

You are just creating a variable at a higher scope that you can set and refer to later.  If you need a bunch of them create an array with filepath as an index.  But I would try it first as just a simple value.
Comment: I tried declaring an empty variable both above the task and just inside the task before the gulp.src as you have it in your example and I made sure I didn't declare it again inside the pipe(print) by removing the text "var" before the uuid and I keep getting a ReferenceError "udid is not defined" in terminal on the line in the code that starts with .pipe(inject.before....

no idea how to set a variable array I also tried this

     var uuid = []; //Define array pages

    //loop through all pages
    for (i = 0; i < (1000); i++) {
        uuid.push( i + ".tmpl"); //Add to array
    }
Comment: "udid" is not defined - do you mean "uuid" there?
Comment: It's in your original code too - I changed it in my code previously.  In the inject pipe.
Comment: Bad code in original question a result of typing directly in web form on this site - my fault there. I have updated original question without typo. Still doesn't work, What about wrapping with gulp-foreach?
Comment: If I set the var uuid = "apples"; at the top I'll get a valid UUID returned in the console "uuid: b20be24d-3916-33c2-ab15-ff3446ed34d8" and "apples" returned in the injected HTML.
Comment: Is uuidv3() a synchronous function?
Comment: Have a look at https://stackoverflow.com/questions/22026389/passing-variables-between-pipes-in-gulp  gulp-tap looks promising.  I modified my answer above to show it.
Answer: I solved the problem. It was an amateur mistake. I returned the statement where the var was set so the var was essentially killed. Updated code that allows the var to pass through the pipes.
var gulp     = require('gulp');
var print    = require('gulp-print');
var replace  = require('gulp-replace');
const uuidv3 = require('uuid/v3');

var uuid;

gulp.task('build', function() {
    return gulp.src('**/*.html')
    // get a cross-platform filepath and create a uuid
    .pipe(print(function(filepath) {
        uuid = uuidv3(filepath, uuidv3.URL);
    }))
    // inject uuid
    .pipe(replace('dc.identifier" content=""', function() {
        return 'dc.identifier" content="' + uuid + '"';
    }))
    .pipe(gulp.dest('/prod/./'));
});

The var uuid passes through the pipes just fine now. This code creates a UUID based on a cross-platform file path and injects it into an empty dc.identifier meta tag.
Comment: Worth noting that you have to wrap those two pipes in a gulp-foreach because as the stream returns a bunch of files a UUID is created in one pipe but it may not inject the same var into the original file, Another file grabs it in the second pipe sometimes. The foreach makes it pass each page through one at a time.


Help me answer this optimization problem.

Question: What two nonnegative real numbers $a$ and $b$ whose sum is 23 maximize $a^2+b^2$? Minimize $a^2+b^2$?
Answer: Hint:
$$2(a^2 + b^2) = (a + b)^2 + (a - b)^2 = 23^2 + (a - b)^2.$$
So to maximize (minimize) $a^2 + b^2$, you should maximize (minimize) $(a - b)^2$.
Answer: If $a+b = 23$ then $b=23-a$. So just maximize and minimize $2a^2-46a+23^2$  (for $0\le a \le 23$) using calculus.
Comment: Should be $-46$
Answer: You could make use of the following inequality.
$$(a+b)^2\leq 2(a^2+b^2)$$
The inequality comes from the fact that $(a-b)^2\geq 0$ or can be thought as Cauchy-Schwarz applied to the vectors $\vec{x}=(1,1)$ and $\vec{y}=(a,b)$.
Answer: Hint:
$$a^2+b^2=(a+b)^2-2ab=23^2-2ab$$Now, it is enough to find the maximum and minimum value of $ab$.


Rounded corners of NSCollectionViewItem

Question: Simple question, but I can't find any answers... How I can change corner radius of NSCollectionViewItem instance?
Comment: item.layer.cornerRadius. import CoreGraphics.
Comment: @GeneCode here I need to set its property? In `viewDidLayout` of item? Of delegate method in controller that has `NSCollectionView` as subview?
Comment: Should be in the collectionview subclass. (alternatively in the delegate)
Comment: @GeneCode I dont want to subclass `NSCollectionView`, in which delegate method I need to change corner radius?
Comment: itemForRepresentedObjectAtIndexPath i think.
Comment: @GeneCode It doesn't work
Comment: Did you set the item background color?
Comment: If you set the item bg color, then you need to set [item.layer setMaskToBounds:YES];
Answer: view of NSCollectionViewItem doesn't have layer by default. You need to set wantsLayer to true, for example:
import Cocoa

class TestCellItem: NSCollectionViewItem {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.red.cgColor
    }

    override func viewDidLayout() {
        super.viewDidLayout()
        view.layer?.cornerRadius = 20
    }
}

Rounded corners of NSCollectionViewItem


$f: [0,1]\rightarrow \mathbb{R}$ be an injective function, then :

Question: Question is :
$f: [0,1]\rightarrow \mathbb{R}$ be a one one function, then which of the following statements are true?
$(a)$ $f$ must be onto
$(b)$ range of $f$ contains a rational number
$(c)$ range of $f$ contains an irrational number
$(d)$ range of $f$ contains both rational numbers and irrational numbers
I can see that $f$ need not be onto function by considering :
$f : [0,1]\rightarrow \mathbb{R}$ with  $f(x)=x$  is one-one , but not onto.
Now, I should not take a continuous function to show a contradiction for $(b)/(c)/(d)$ because, any continuous function takes intervals to intervals and thus, Range of $f$ will have both rational and irrational numbers.
I recalled all functions i have thought could be discontinuous but those are not helping me at all.
I would be thankful if some one can help me to crack this problem and similar kind of problems.
THank You.
Comment: Since $[0,1]$ is uncountable, the range would have to contain an irrational number. Not sure what else can be said though.
Comment: Continuity is not given and is irrelevant - this question is all about the cardinalities of the sets involved.
Comment: @PrahladVaidyanathan : yes.. This does makes lots of sense to me :)
Comment: @PrahladVaidyanathan : can we say anything about the rational numbers presence??
Comment: I would guess that you can avoid all rational numbers, but I would suspect that constructing such a function would involve the axiom of choice.
Answer: Consider $f : [0, 1] \to \mathbb R$ defined as:
$$
f(x) = \begin{cases}
x &: x \text{ irrational} \\
x + \sqrt{2} &: x \text{ rational}
\end{cases}
$$
It is easy to show that this is an injective function from $[0, 1]$ into $\mathbb R - \mathbb Q$.


Why are packages installed rather than just linked to a specific environment?

Question: I've noticed that normally when packages are installed using various package managers (for python), they are installed in /home/user/anaconda3/envs/env_name/ on conda and in /home/user/anaconda3/envs/env_name/lib/python3.6/lib-packages/ using pip on conda.
But conda caches all the recently downloaded packages too.
So, my question is:
Why doesn't conda install all the packages on a central location and then when installed in a specific environment create a link to the directory rather than installing it there?
I've noticed that environments grow quite big and that this method would probably be able to save a bit of space.
Answer: Conda already does this. However, because it leverages hardlinks, it is easy to overestimate the space really being used, especially if one only looks at the size of a single environment directory at a time.
To illustrate the case, let's use du to inspect the real disk usage.  First, if I count each environment directory individually, I get the uncorrected per environment usage
$ for d in envs/*; do du -sh $d; done
2.4G    envs/pymc36
1.7G    envs/pymc3_27
1.4G    envs/r-keras
1.7G    envs/stan
1.2G    envs/velocyto

which is what it might look like from a GUI.
Instead, if I let du count them together (i.e., correcting for the hardlinks), we get
$ du -sh envs/*
2.4G    envs/pymc36
326M    envs/pymc3_27
820M    envs/r-keras
927M    envs/stan
548M    envs/velocyto

One can see that a significant amount of space is already being saved here.
Most of the hardlinks go back to the pkgs directory, so if we include that as well:
$ du -sh pkgs envs/*
8.2G    pkgs
400M    envs/pymc36
116M    envs/pymc3_27
 92M    envs/r-keras
 62M    envs/stan
162M    envs/velocyto

one can see that outside of the shared packages, the environments are fairly light.  If you're concerned about the size of my pkgs, note that I have never run conda clean on this system, so my pkgs directory is full of tarballs and superseded packages, plus some infrastructure I keep in base (e.g., Jupyter, Git, etc).
Comment: @Tian sure. That's because `pkgs` is the central repository for package code and much of what is hardlinked goes back to there. Everything goes into there first and gets linked out to the envs whenever possible.
Comment: Can I ask why does the size of your envs change before and after you included ```pkgs```?
Comment: @merv For me, `for d in envs/*; do du -sh $d; done` and `du -sh envs/*` shows same result...(They both show 3~5GB for each env) Why is it so? Does it mean it never use hardlink thing? (I'm using `miniconda` and `conda` version is `4.8.3`)
Comment: @user3595632 Possibly. Is your package cache on a different file system? For example, check`conda config —show pkgs_dirs envs_dirs`. Or there are other config settings related to linking behavior that may be worth checking.
Comment: Since different environments are likely to be created at different times, would it be accurate to say that package versions may differ between environments, thus limiting the actual sharing of files?
Comment: @user2153235 correct - there is no underlying mechanism to reuse existing packages if newer ones are available. One can use `conda create --clone` or create new environments using dumped environment definitions (`conda env export`, then `conda env create`) to exactly reuse another environment's packages.
Comment: @merv: I don't quite follow that last comment.  If package versions differ between environments, I wouldn't expect sharing of package files.  If package versions are the same, however, it seems that hard links are used to share files.  However, I expect package versions to often differ because environments aren't necessarily created at the same time.  This makes it hard to share files.  I was just hoping to get confirmation on this.  Thanks.
Comment: Yes, I'm confirming your reasoning. The additional comments are just to say that there are ways to force using the same versions across environments - though they're not great.


Ubuntu install hangs at "Installing the 'grub2' package..."

Question: So i'm trying to install Ubuntu on my laptop, it seems to work fine until it tries to install grub. I haven't seen progress the past hour and this is the second attempt.
I'm trying to install 13.10, using a Linux Live USB. I don't care about the contents of the laptop.
I've been trying to find instructions about installing grub before starting the installation, hoping that would solve my issues, but I came up empty.
Laptop is 2 years old, it used to run dual-boot windows 7 and Ubuntu. I'm now doing a fresh install of just Ubuntu.
I hope anyone knows how I can find out why it is happening.
Comment: Could you describe your partitions and error message if anyone is shown.
Comment: I haven't seen any error message. I just rebooted to get you the partition info, currently it shows me 3 partitions: 510MB efi, 495GB ext4 and 4 GB Swap. at /dev/sda1 through 3.
Answer: During the installation, there's a way to skip installing grub. Look at the "Device for boot loader installation" dropdown.
Instead of choosing the entire device "/dev/sda", choose the partition you'll install Ubuntu, such as: "/dev/sda1"

If you choose "dev/sda", you're supposed to rewrite the boot record for the entire drive, which I believe is what's your issue is all about.
But when you choose "dev/sda1" (or sda2,sda3...) you get to place the boot flag at the beginning of the partition, not the entire drive. That does not make you go for a change in your bootloader. In other words, you place a boot flag as a "subtitle" to your pre-existing bootloader.
After you apply the fix, if you ever want to switch to Grub2 for any reason, use the Ubuntu Boot Repair disk: Ubuntu Boot Repair
If all else fails, try to "rewrite your MBR" because during your uninstallation of Windows, its boot sector may have accidentally remained there. Since you are doing a fresh install of Ubuntu, this may stand as the final option since there's a small chance that Ubuntu failed to handle your Windows partition's boot flags correctly.
Answer: In case you have issue when installing on UEFI BIOS (not sure if this issue is adressed only to Acer Laptops) there is a topic here that helped me solve this issue.
I will copy the commands in case it disappears, but all credit goes to Pueseso from Acer Community forum.
-- Boot Ubuntu Live USB
-- open terminal
sudo -s
ubiquity -b
-- Press Continue testing after installation is over.

--Now we will return to the CLI (  https://wiki.debian.org/GrubEFIReinstall  )

sudo mount /dev/sda2 /mnt #sda2 is the root partition
sudo mkdir /mnt/boot/efi
sudo mount /dev/sda1 /mnt/boot/efi #sda1 is the efi partition
for i in /dev /dev/pts /proc /sys; do sudo mount -B $i /mnt$i; done

modprobe efivars # make sure this is loaded

-- notice the bootx64 file
efibootmgr --verbose

-- We will reinstall grub-install for a 64bit version
apt-get install --reinstall grub-efi-amd64

grub-install —no-nvram —root-directory=/mnt
chroot /mnt
update-grub
cd /boot/efi/EFI
cp -R ubuntu BOOT
cd BOOT
cp grubx64.efi bootx64.efi

-- You are finished, reboot the system.


How to fill hole near shower drain

Question: Our shower is leaking slowly from somewhere, causing the ceiling of the room below to stain. We had the silicone sealant around the edge of the shower professionally replaced and it looks like a good job, but the leak persists.
The shower has no visible tray - it's basically a wet room with the floor tiles extending into the shower area. The room was fitted before we bought the house but I'd estimate it was probably done between 5 and 10 years ago. Some of the grout between the tiles on the shower floor is looking worn and cracked so I decided to regrout the floor in a further attempt to fix the leak.
After removing the metal drain cover and plastic insert, I found a thick layer of grout around the edge of the square plastic drain surround, which was quite flakey and crumbly, so I removed it all.
After doing so, I found a couple of holes between the tiles and the drain surround. Also, with this layer of grout removed, when I put the plastic insert back there is a large gap between it and the edge of the tiles.
My questions are: How should I fill the holes that I've found between the tiles and the drain surround? And how should I fill/seal the gap between the plastic insert and the edge of the tiles, given that the gap varies quite a lot in width and is quite wide wide in places, whatever I do will be visible when the job is finished, and the plastic insert is somewhat flexible when the metal drain cover isn't in place?
Comment: @Huesmann I'm in the process of removing it at the moment.
Comment: Do you have no grout between your tiles???
Answer: I believe there could be serious issues with the construction of the shower floor.  Having water weep through the grout and around the drain is not unusual, however there should be waterproofing under the tile base that directs this to the drain.
It sounds as if this is not a part of your shower system.
You can try to use a polyester caulk, like this vulkem to fill the gap between the drain and tile.  Then find a grouting caulk that matches the color of your grout, ( it's more flexible than grout ) and fill in any grout lines that are open.   Finally seal the grout with a quality sealer.
If the problem persists, you will have to remove the shower floor and repair from there.
Comment: What are the particular properties of the Vulkem that I should be looking for in an alternative? I'm struggling to find anywhere that sells it in the UK. I think you're right about the shower's construction. I expected there to be a tray under the tiles but there appears not to be. The whole room is tiled the same so retiling could end up being very costly.
Comment: The Vulkem is a polyester caulk that stays flexible in a wide temperature range and is waterproof.  It does not support mold growth like some silicones. It has a flow grade to it that makes it "flow" into voids better than silicones.  Clean up does require mineral spirits..

How to fill hole near shower drain


How to include both import and require statements in the bundle using rollup

Question: When I use only const Example1 = require('./example1.js) statement then code inside example1.js file is getting included in the bundle. And if I use only import Example2 from './example2.js' then also code inside example2.js is getting included in the bundle. But if I use both the statements only import is working and require is not working.
I am using rollup for bundling.
My rollup configuration looks like this
import babel from 'rollup-plugin-babel'
import commonjs from 'rollup-plugin-commonjs'
import external from 'rollup-plugin-peer-deps-external'
import postcss from 'rollup-plugin-postcss'
import resolve from 'rollup-plugin-node-resolve'
import url from 'rollup-plugin-url'
import svg from 'rollup-plugin-svg'
import json from 'rollup-plugin-json';
import { terser } from 'rollup-plugin-terser'

export default {
  input: 'src/sdk/test.js',
  output: [
    {
      file: "src/sdk/sdk.js",
      format: 'cjs'
    },
    {
      file: "src/sdk/sdk.es.js",
      format: 'es'
    },
    {
      file: "src/sdk/sdk.iife.js",
      format: 'iife'
    }
  ],
  plugins: [
    resolve({
      browser: true,
    }),
    commonjs(),
    external(),
    postcss({
      modules: true
    }),
    url({
      limit: 100 * 1024,
      emitFiles: false
    }),
    svg(),
    babel({
      exclude: 'node_modules/**',
      "plugins": ["@babel/plugin-proposal-class-properties"]
    }),
    terser(),
    json()
  ]
}

Comment: Well, no, just don't mix the two module syntaxes.
Comment: I wish I could @Bergi
Answer: By default, rollup supports 'esm' modules as entry. If you like to include commonjs files in the project, you can include '@rollup/plugin-commonjs' into plugins field, it usually works.
Maybe the following config will help, I tried with very simple example:
commonjs({transformMixedEsModules:true})

transformMixedEsModules
Instructs the plugin whether or not to enable mixed module transformations. This is useful in scenarios with mixed ES and CommonJS modules. Set to true if it's known that require calls should be transformed, or false if the code contains env detection and the require should survive a transformation.
https://github.com/rollup/plugins/tree/master/packages/commonjs
Comment: But it doesn't include the code from ```require``` statement in the final bundle. ```require``` statement with path will remain as it is. Only ```import``` statement code will be included.
Comment: is it  third party modules or codes you wrote doesn't get bundled? You did not explain
Comment: its a third party library tweenjs
Comment: I want to add `https://firstname.lastname@example.com/dist/js/bootstrap.bundle.min.js` to the rollup. How can I do that? I mean, I want to add this Alert message to my widget `https://www.w3schools.com/bootstrap4/tryit.asp?filename=trybs_alerts_fade&stacked=h`. But JS files are not working.
Comment: @OsandaGamage did you figure it out?


best lifecycle method to replace onLeave with

Question: In router v3, we used onLeave. In v4, the closest to onEnter seems to be componentWillMount.  However, componentWillUnmount does not seem to be as effective for me in relation to onLeave.
What is the best lifecyle method (or other practice) to use in place of onLeave?
Answer: The appropriate API to use in place of onLeave is Prompt

Used to prompt the user before navigating away from a page. When your
  application enters a state that should prevent the user from
  navigating away (like a form is half-filled out), render a .

Here is the link to official documentation
Comment: Thanks for an answer. I was thinking more in the vein of firing a function or messing with session (if one uses session), not a prompt or interacting with the user to make sure they did everything correctly.

`onEnter:  function doThis`
`onLeave:  function doThat`


Reference Shared Object AS3

Question: I am trying to reference a shared object (one that saves data), but whenever I try to, I get a crash.
This code works fine:
var var1:Object = { value:1 };
var varRef:Object = var1;

if(var1.value == 1) {
    varRef.value = 50;
}

trace(varRef.value); // outputs 50;
trace(var1.value); // outputs 50;

But when I try to use shared objects, it doesn't work.
import flash.net.SharedObject;
var iapso:SharedObject = SharedObject.getLocal("purchases");
var varRef:Object = iapso.data.testing;

varRef = 90
trace ("The shared value is " + iapso.data.testing);
trace ("This should mirror it" + varRef);

If you're able to figure out the issue, please post a fixed version.
Thanks.
Answer: You must come from a programming background where pointers can be dereferenced.
In this case, varRef is not varRef = &iapso.  Setting its value does not change the value of iapso.data.testing;
Initially, you set varRef as a pointer to iapso.data.testing:
var varRef:Object = iapso.data.testing;

Then, you immediately change it to a constant value object literal 90:
varRef = 90;

This does not set the value of testing to 90 - this changes the value of varRef.
You could set varRef to iapso.data, then set testing as in:
var varRef:Object = iapso.data;
varRef.testing = 90;

Then, the following would produced expected results:
trace(iapso.data.testing); // 90
trace(varRef.testing); // 90

Comment: Jason Sturges you did it again! Great answer.
Answer: setting varRef will not update the value in iapso.data - numbers are copied, not referenced.
var bar:Object = { data:1 };
var foo:Object = bar.data;

trace(foo); //"1"
bar.data = 2;
trace(foo); //"1"

If you really want to use a reference, use data instead, eg:
import flash.net.SharedObject;
var iapso:SharedObject = SharedObject.getLocal("purchases");
var varRef:Object = iapso.data;

varRef.testing = 90
trace ("The shared value is " + iapso.data.testing);
trace ("This should mirror it" + varRef.testing);

Reference Shared Object AS3


What approaches to online commenting best promote high-value discussions and content?

Question: Anyone who's read a news article online... ever... can see that old-style commenting ( ie: Enter your name, email address, and website (optional) ) is broken. StackOverflow's reputation model, and Quora's identity-based approach are two commenting systems that come to mind that seem to be effective in keeping people on, or near, topic.
What is the most effective method of soliciting comments?
Answer: There are a number of factors, some of which are beyond the interface's control like the nature of the content, but one factor in your control is how to handle identity.
Disqus published a blog post and infographic a few months ago looking at policies of real-names vs. pseudonyms vs. complete anonymity, and found that pseudonyms (stable but user-defined) produced the best quality of commentary. Give the post a read, it's worth it and not very long.


How do you write (portably) reverse network byte order?

Question: Background
When designing binary file formats, it's generally recommended to write integers in network byte order. For that, there are macros like htonhl(). But for a format such as WAV, actually the little endian format is used.
Question
How do you portably write little endian values, regardless of if the CPU your code runs on is a big endian or little endian architecture? (Ideas: can the standard macros ntohl() and htonl() be used "in reverse" somehow? Or should the code just test runtime if it's running on a little or big endian CPU and choose the appropriate code path?)
So the question is not really about file formats, file formats were just an example. It could be any kind of serialization where little endian "on the wire" is required, such as a (heretic) network protocol.
Comment: You have three questions there, but only two stand out.
Comment: @user2096041, re-arranged, is it clearer?
Comment: In order to find the endianness of the host system you can follow this link: http://stackoverflow.com/questions/1001307/detecting-endianness-programmatically-in-a-c-program
Answer: Warning: This only works on unsigned integers, because signed right shift is implementation defined and can lead to vulnerabilities (https://stackoverflow.com/a/7522498/395029)
C already provides an abstraction over the host's endianness: the number† or int†.
Producing output in a given endianness can be done portably by not trying to be clever: simply interpret the numbers as numbers and use bit shifts to extract each byte:
uint32_t value;
uint8_t lolo = (value >> 0) & 0xFF;
uint8_t lohi = (value >> 8) & 0xFF;
uint8_t hilo = (value >> 16) & 0xFF;
uint8_t hihi = (value >> 24) & 0xFF;

Then you just write the bytes in whatever order you desire.
When you are taking byte sequences with some endianness as input, you can reconstruct them in the host's endianness by again constructing numbers with bit operations:
uint32_t value = (hihi << 24)
               | (hilo << 16)
               | (lohi << 8)
               | (lolo << 0);

† Only the representations of numbers as byte sequences have endianness; numbers (i.e. quantities) don't.
Comment: `hihi`, `lolo`, those are the best names I've seen. What do you mean quantities?
Comment: It basically means that C++ makes knowing the host's endianness irrelevant. You don't need to detect it, you just need to write out the bytes in the desired order.
Comment: `int`s, `uint32_t`, etc, are numbers (they don't have endianness).
Comment: @AmigableClarkKant the abstract idea of a number, as opposed to its representation.
Comment: Ok, maybe you should link to some kind of C++ ref for number instead. Anyway, how does it help with serialization and endianness? I understand (and approve of the rest of the answer)
Comment: How would I do that with Numbers? Not that I care really, I would accept your answer for the hihi, lolo thing, but I can't accept an answer I don't understand 100%.
Answer: Here's a template based version:
#include <iostream>
#include <iomanip>

enum endianness_t {
   BIG,         // 0x44332211  => 0x44 0x33 0x22 0x11
   LITTLE,      // 0x44332211  => 0x11 0x22 0x33 0x44
  UNKNOWN
};

const uint32_t test_value    = 0x44332211;
const bool is_little_endian  = (((char *)&test_value)[0] == 0x11) && (((char *)&test_value)[1] == 0x22);
const bool is_big_endian     = (((char *)&test_value)[0] == 0x44) && (((char *)&test_value)[1] == 0x33);

const endianness_t endianness =
   is_big_endian ? BIG:
  (is_little_endian ? LITTLE : UNKNOWN);

template <typename T>
T identity(T v){
  return v;
}

// 16 bits values ------

uint16_t swap_(uint16_t v){
  return ((v & 0xFF) << 8) | ((v & 0xFF00) >> 8);
}

// 32 bits values ------

uint32_t swap_(uint32_t v){
  return ((v & 0xFF) << 24) | ((v & 0xFF00) << 8) | ((v & 0xFF0000) >> 8) | ((v & 0xFF000000) >> 24);
}

template <typename T, endianness_t HOST, endianness_t REMOTE>
 struct en_swap{
  static T conv(T v){
    return swap_(v);
  }
};

template <typename T>
struct en_swap<T, BIG, BIG>{
  static T conv(T v){
    return v;
  }
};

template <typename T>
struct en_swap<T, LITTLE, LITTLE> {
  static T conv(T v){
    return v;
  }
};

template <typename T>
T to_big(T v) {

  switch (endianness){
  case LITTLE :
    return en_swap<T,LITTLE,BIG>::conv(v);
  case BIG :
    return en_swap<T,BIG,BIG>::conv(v);
  }
}

template <typename T>
T to_little(T v) {
   switch (endianness){
   case LITTLE :
     return en_swap<T,LITTLE,LITTLE>::conv(v);
   case BIG :
     return en_swap<T,BIG,LITTLE>::conv(v);
  }
}

int main(){

  using namespace std;

  uint32_t x = 0x0ABCDEF0;
  uint32_t y = to_big(x);
  uint32_t z = to_little(x);

  cout << hex << setw(8) << setfill('0') << x << " " << y << " " << setw(8) << setfill('0') << z << endl;

}

Answer: In fact, the MSDN functions ntohl() and htonl() are the inverse of eachother:

The htonl function converts a u_long from host to TCP/IP network byte
  order (which is big-endian).
The ntohl function converts a u_long from TCP/IP network order to host
  byte order (which is little-endian on Intel processors).

Yes, runtime detecting endianness is a very sane thing to do, and basically what any ready-to-use macro/function would do at some point anyway.
And if you want to do little-big endian conversions yourself, see answer by @R-Martinho-Fernandes.
Comment: I disagree that detecting endianness being a very sane thing to do.  You normally shouldn't need to know.  Unless you're writing performance-critical code, writing endian-independent code is a better idea.
Comment: @jamesdlin when writing a crossplatform process, the same code may run on either little-endian or big-endian hardware. When the process communicates via network or files, you'd want them to talk the same language. Code can check endianness at runtime, and accommodate process output/input accordingly.
Comment: That doesn't make sense.  If you're writing proper endian-agnostic code, your code is still cross-platform and doesn't need to do any runtime (or compile-time) checks.  For example, if you do: `fputc((x >> 24) & 0xFF, fp)` where `x` is a 32-bit integer, you will always be writing out the most significant byte regardless of the platform.  See R. Martinho Fernandes' answer.


Can't change brightness at all

Question: Here is what it looks like when I go to the "change brightness" option. I am booting in recovery mode because when I boot to normal Ubuntu mode there is nothing you can see on the screen, I can only hear the login sound.
So I thought I would need to change the  brightness but neither Fn + F6 works, nor do I get an option to change the brightness in the settings.
Comment: Perhaps my answer [here](http://askubuntu.com/a/589574/295286) may be a useful workaround. As for the normal mode, I'd suggest you install different greeter - like lightdm-gtk-greeter
Comment: got this after enter this in terminal bash: /sys/class/backlight/acpi_video0/brightness /sys/class/backlight/acpi_video0/brightness: No such file or directory
Comment: what does this say: `ls /sys/class/backlight/`
Comment: it does nothing when i enter ls /sys/class/backlight/
Comment: Did you verify that your Fn+... keys work? That they weren't hijacked or shadowed?
Comment: Your question may boil down to same case as in "Dell Chromebook 11 - unable to set backlight and /sys/class/backlight/ folder is empty" or in "/sys/class/baclight folder is empty, leading to blank screen". Former has an answer that I partially quoted. You may want to pick it up with answer's author - he might know more.
Comment: well then then is nothings there i can do then cause ubuntu thinks i have a crt but i have to have some brightness cause the screen is really blank on normal ubuntu mode i have to boot it up in recovery also when i hibernate in recovery it kinda opens up in normal ubuntu mode
Comment: got my brightness back http://i.imgur.com/nT0Oaae.png. i booted up in the third option of the advanced settings and i somehow have my brightness back yesss!!!!
Answer: Manual way
Works for some systems, though not yours, apparently, since ls /sys/class/backlight/ shows nothing for you. Sometimes instead of intel_backlight you'll have acpi_video0, or something else.

You can manually change the brighntess level all the way down (to
  disable it altogether) by doing echo 23 > /sys/class/backlight/intel_backlight/brightness as a root. "23" is the desired brightness level. If you put "0",
  the screen will look blank.

From Adam Ryczkowski's comment here, which helped my friend in similar case.
Empty /sys/class/backlight/ means unrecognized hardware
When I noticed your exchange with @Serg, I thought "why would that folder be empty" and search showed this:

If /sys/class/backlight/ is empty, that means that the kernel thinks
  you have a big bad old CRT attached to the system and that you have to
  turn the big fat knobs named "Brightness" and "Contrast" on the from
  to change... well, brightness and contrast...

source: @Fabby's answer to another AskUbuntu question.

Can't change brightness at all


Swift: Pass UITableViewCell label to new ViewController

Question: I have a UITableView that populates Cells with data based on a JSON call. like so:
var items = ["Loading..."]
var indexValue = 0

// Here is SwiftyJSON code //

for (index, item) in enumerate(json) {
    var indvItem = json[index]["Brand"]["Name"].stringValue
    self.items.insert(indvItem, atIndex: indexValue)
    indexValue++
}
self.tableView.reloadData()

How do I get the label of the cell when it is selected and then also pass that to another ViewController?
I have managed to get:
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    println("You selected cell #\(indexPath.row)!")

    // Get Cell Label
    let indexPath = tableView.indexPathForSelectedRow();
    let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;

    println(currentCell.textLabel.text)
}

I just cant figure out how to pass that as a variable to the next UIViewController.
Thanks
Comment: @DharmeshKheni Yeah, Ive used that on a previous controller - I don't know how to pass the variable with the label test to the prepareForSegue before the click even for the performSegue initiates.
Answer: Passing data between two view controllers depends on how view controllers are linked to each other. If they are linked with segue you will need to use performSegueWithIdentifier method and override prepareForSegue method
var valueToPass:String!

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    println("You selected cell #\(indexPath.row)!")

    // Get Cell Label
    let indexPath = tableView.indexPathForSelectedRow();
    let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;

    valueToPass = currentCell.textLabel.text
    performSegueWithIdentifier("yourSegueIdentifer", sender: self)

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if (segue.identifier == "yourSegueIdentifer") {

        // initialize new view controller and cast it as your view controller
        var viewController = segue.destinationViewController as AnotherViewController
        // your new view controller should have property that will store passed value
        viewController.passedValue = valueToPass
    }

}

If your view controller are not linked with segue then you can pass values directly from your tableView function
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    println("You selected cell #\(indexPath.row)!")

    // Get Cell Label
    let indexPath = tableView.indexPathForSelectedRow();
    let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;
    let storyboard = UIStoryboard(name: "YourStoryBoardFileName", bundle: nil)
    var viewController = storyboard.instantiateViewControllerWithIdentifier("viewControllerIdentifer") as AnotherViewController
    viewController.passedValue = currentCell.textLabel.text
    self.presentViewController(viewContoller, animated: true , completion: nil)
}

Comment: How could you access the "valueToPass" from didSelectRowAtIndexPath to prepareForSegue? It definitely cannot access the identifier since they are different function. The variable inside didSelectRowAtIndexPath is cover by {} and it can't access outside of the function.
Comment: @jefferyleo My answer covers two different scenarios and ofc they are not linked to each other. `valueToPass` belongs to first scenario (where vc are connected with segue) and `didSelectRowAtIndexPath` is the seconds scenario
Comment: `viewController.passedValue = currentCell.textLabel.text'` is .passedValue not existing anymore? :/
Comment: For some odd reason, my data is always passed on the second tap.
Comment: @V1P3R be aware of using `didSelectRowAtIndexPath ` instead of `didDeselectRowAtIndexPath `. If you didn't notice the difference is select and deselect
Comment: Yes, I'm using the correct one. Maybe it's a bug in simulator?
Comment: @Zell B. what the `.passedValue` look like on the next viewcontroller class code? @V1P3R
Comment: Also i cant override prepareforseguefunc
Answer: You asked:

How do I get the label of the cell when it is selected and then also pass that to another ViewController?

I might suggest rephrasing the question as follows: "How do I retrieve the data associated with the selected cell and pass it along to another view controller?"
That might sound like the same thing, but there's an important conceptual distinction here. You really don't want to retrieve the value from the cell label. Our apps employ a MVC paradigm, so when you want to pass data information from one scene to another, you want to go back to the model (the items array), not the view (the text property of the UILabel).
This is a trivial example, so this distinction is a bit academic, but as apps get more complicated, this pattern of going back to the model becomes increasingly important. The string representation from the cell is generally is a poor substitute for the actual model objects. And, as you'll see below, it's just as easy (if not easier) to retrieve the data from the model, so you should just do that.
As an aside, you don't really need a didSelectRowAtIndexPath method at all in this case. All you need is a segue from the table view cell to the destination scene, give that segue a unique identifier (Details in my example), and then implement prepare(for:sender:):
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? DetailsViewController {
        let selectedRow = tableView.indexPathForSelectedRow!.row
        destination.selectedValue = items[selectedRow]
    }
}

Alternatively, if your segue is between the cell and destination scene, you can also use the sender of the prepare(for:sender:):
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? DetailsViewController {
        let cell = sender as! UITableViewCell
        let selectedRow = tableView.indexPath(for: cell)!.row
        destination.selectedValue = items[selectedRow]
    }
}

But the idea is the same. Identify what row was selected, and retrieve the information from the model, the items array.
The above is Swift 3. For Swift 2.3, please see the previous version of this answer.
Comment: This answer gave me the help I needed, even though I'm using Swift 3.  I was missing the "let selectedRow" line in the sending controller's prepareForSegue (Swift 3 prepare(for segue:) )  func to only get the data from the selected cell.  Thank you so much Rob!
Answer: Okay..Its been 2 days I was searching for the answer that how could I be able to save the selected UITableViewCell label text data and display that data to an another label on an another View Controller which will come out after tapping on a cell. At last I have completed with the task and its successful. Here is the complete code with steps using Swift.I am using Xcode 6.4.
Step 1.
I have Two class assigned to the storyboard view controllers named "iOSTableViewControllerClass.swift" which is a Table View Controller and "iOSTutorialsViewControllerClass.swift" which is a normal View Controller.
Step 2.
Now make segue from iOSTableViewControllerClass to iOSTutorialsViewControllerClass by Control-dragging on the storyboard area and choose "show" from drop down menu. Click on this highlighted button according to the below image and perform the segue.

Step 3.
Now select the segue by clicking on the storyboard and give it an identifier on the Attributes Inspector. In this case I named it as "iOSTutorials"

Step 4.
Now on this step put a label on your cell as well as on the other view controller and make outlets of them on their corresponding classes.
 In my case those are "@IBOutlet weak var iOSCellLbl: UILabel!" and " @IBOutlet weak var iOSTutsClassLbl: UILabel!".
Step 5.
Make a string type variable on the first Table View Controller Class. I did this as "var sendSelectedData = NSString()" also Make a string type variable on the second class. I did this as "var SecondArray:String!".
Step 6.
Now we are ready to go.
Here is the complete Code for first Class --
 // iOSTableViewControllerClass.swift

  import UIKit

  class iOSTableViewControllerClass: UITableViewController, UITableViewDataSource,UITableViewDelegate {

  // Creating A variable to save the text from the selected label and send it to the next view controller

  var sendSelectedData = NSString()

 //This is the outlet of the label but in my case I am using a fully customized cell so it is actually declared on a different class
@IBOutlet weak var iOSCellLbl: UILabel!

//Array for data to display on the Table View
var iOSTableData = ["Label", "Button", "Text Field", "Slider", "Switch"];
override func viewDidLoad() {
    super.viewDidLoad()

//Setting the delegate and datasource of the table view

    tableView.delegate = self
    tableView.dataSource = self

//Registering the class here
    tableView.registerClass(CustomTableViewCellClassiOS.self, forCellReuseIdentifier: "CellIDiOS")

//If your using a custom designed Cell then use this commented line to register the nib.
    //tableView.registerNib(UINib(nibName: "CellForiOS", bundle: nil), forCellReuseIdentifier: "CellIDiOS")
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // Return the number of rows in the section.
    return iOSTableData.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let CellIDentifier = "CellIDiOS"

 //In this case I have custom designed cells so here "CustomTableViewCellClassiOS" is the class name of the cell
    var cell:CustomTableViewCellClassiOS! = tableView.dequeueReusableCellWithIdentifier(CellIDentifier, forIndexPath: indexPath) as? CustomTableViewCellClassiOS
    if cell == nil{
        tableView.registerNib(UINib(nibName: "CellForiOS", bundle: nil), forCellReuseIdentifier: CellIDentifier)
        cell = tableView.dequeueReusableCellWithIdentifier(CellIDentifier) as? CustomTableViewCellClassiOS

    }
 //Here we are displaying the data to the cell label
    cell.iOSCellLbl?.text = iOSTableData[indexPath.row]
    return cell
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    println("You selected cell #\(indexPath.row)!")

    // Get Cell Label text here and storing it to the variable
    let indexPathVal: NSIndexPath = tableView.indexPathForSelectedRow()!
    println("\(indexPathVal)")
    let currentCell = tableView.cellForRowAtIndexPath(indexPathVal) as! CustomTableViewCellClassiOS!;
    println("\(currentCell)")
    println("\(currentCell.iOSCellLbl?.text!)")
    //Storing the data to a string from the selected cell
    sendSelectedData = currentCell.iOSCellLbl.text!
    println(sendSelectedData)
//Now here I am performing the segue action after cell selection to the other view controller by using the segue Identifier Name
    self.performSegueWithIdentifier("iOSTutorials", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

//Here i am checking the Segue and Saving the data to an array on the next view Controller also sending it to the next view COntroller
    if segue.identifier == "iOSTutorials"{
//Creating an object of the second View controller
        let controller = segue.destinationViewController as! iOSTutorialsViewControllerClass
//Sending the data here
        controller.SecondArray = sendSelectedData as! String

 }

Here is the complete code for the second Class..--
//  iOSTutorialsViewControllerClass.swift

import UIKit

class iOSTutorialsViewControllerClass: UIViewController {

//Creating the Outlet for the Second Label on the Second View Controller Class
@IBOutlet weak var iOSTutsClassLbl: UILabel!

//Creating an array which will get the value from the first Table View Controller Class
var SecondArray:String!

override func viewDidLoad() {
    super.viewDidLoad()

//Simply giving the value of the array to the newly created label's text on the second view controller
   iOSTutsClassLbl.text = SecondArray
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

Answer: I do it like this.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

 let selectedName = nameArray[indexPath.row]

let newView: nextViewName = self.storyboard?.instantiateViewController(withIdentifier: "nextViewName") as! nextViewName

   newView.label.text = selectedValue
   self.present(newView, animated: true, completion: nil)

}


Is it possible to control your character's movement with the analog stick?

Question: I recently purchased Harvest Moon: Back To Nature on the PSN Store, however it appears as if I can only control my character's movement with the D-Pad, but I would greatly prefer to use the analog stick.
Is there any way to control my movement with the analog stick instead of the D-Pad?
Answer: Yes, it is possible, via the menu brought up by pressing the Home button. Once inside this menu, do the following:

controller settings > switch analog mode > analog mode`

Setting this to analog mode will enable the analog stick. I'm uncertain what digital mode does, and the PS3 manual isn't that helpful either. The only thing I can gather is that certain games only support one of the two modes, but doesn't offer any insight on what these two modes are.
Comment: The _Analog Mode_ setting is identical to pressing the _Analog_ button on the DualShock controllers. This switches the analog stick between reporting analog events for games that support them, and reporting the same events as the directional pad for games made before the DualShock.


SharePoint JavaScript Execute Asynchron functions after another

Question: i have many functions that read informations from SharePoint lists and write informations in SharePoint lists. These functions depent on each other meaning for example, in the first function i write information in the list. After that first function i call the secound function that reads the writen informations.
To read and write informations i use executeQueryAsync.
My problem is because of the async the data gets read before the first function can write it in the list.
In the moment i work with timeouts and hope the informations are written down when the timeout ends, then i read them. But this is not a very good solution.
Is there a way i can execute the functions that work with executeQueryAsync one by another.
Example:
functionA(); // writes information in list A
functionB(); // reads and write information from list A
functionC(); // reads information from list A

How can i tell the functions to wait for each other? Only if a function is fully executed the next functions starts.
Does anyone have an idea?
Many thanks!
Answer: By design SP.ClientContext.executeQueryAsync function
accepts two parameters:

succeededCallback A function or a delegate of the method to call if
the request executes successfully.
failedCallback A function or a delegate of the method to call if the
request fails to execute.

Given that fact, you could consider the following approach to execute the next function once the previous one is completed:
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle('Announcements');
var properties = {'Title' : 'New announcement',
              'Body' :  'Welcome to a new site'};

var itemCreateInfo = new SP.ListItemCreationInformation();
var listItem = list.addItem(itemCreateInfo);
for(var name in itemProperties)
      listItem.set_item(name, itemProperties[name]);
listItem.update();
ctx.load(listItem);
ctx.executeQueryAsync(
   function(){
       //execute next function here...
   },
   function(sender,args){
    console.log(args.get_message());
});

Alternatively you could consider to execute functions in a chainable manner via Promise, for example using jQuery.Deferred as demonstrated below
function executeQueryPromise(ctx, result) {
    result = result || {};
    var d = jQuery.Deferred();
    ctx.executeQueryAsync(function () {
         d.resolve(result);
    }, function (sender, args) {
         d.reject(args);
    });
    return d.promise();
}

Usage
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle('Announcements');

var properties = {'Title' : 'New announcement',
                  'Body' :  'Welcome to a new site'};
createListItem(list,properties)
.then(function(item){
    return readListItems(list);
},logError)
.then(function(items){
    console.log("Done");
},logError);

where
function logError(sender,args){
    console.log(args.get_message());
}

function createListItem(list,itemProperties){
    var ctx = list.get_context();
    var itemCreateInfo = new SP.ListItemCreationInformation();
    var listItem = list.addItem(itemCreateInfo);
    for(var name in itemProperties)
          listItem.set_item(name, itemProperties[name]);
    listItem.update();
    ctx.load(listItem);
    return executeQueryPromise(ctx,listItem);
}

function readListItems(list){
    var ctx = list.get_context();
    var listItems = list.getItems(SP.CamlQuery.createAllItemsQuery());
    ctx.load(listItems);
    return executeQueryPromise(ctx,listItems);
}

Comment: i have trouble understanding your code a bit. can you see my comment about that?
Answer: To handle the async call in a sequential manner, there is a provision given by jquery: Deferred ( factory function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.)
reference link: https://api.jquery.com/jquery.deferred/
http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/
Answer: Try nesting the function calls within the success() methods of the previous call.  That will ensure that the functions will not execute until the previous one completes.


How to remove this water shut off valve under the kitchen sink?

Question: I'm trying to remove the sink cabinet but I'm stuck at these water shut off valves and the escutcheons.
Water is off already. Tried to use a wrench but didn't seem to do much.
Comment: Small frame challenge: if it happens that you're removing the cabinet for replacement, you could consider cutting the cabinet away from the pipes. You'll still need to disassemble the piping to install the new cabinet but doing things "in the wrong order" could make it a little easier to work on the bottom of that white tee where space is tight.
Answer: That plumbing is PEX which uses compression fittings. You have two styles of compression rings on it, the black-ish ones with the aqua copper corrosion are "copper crimp rings" and the different steel one on the far left of the tee is a "cinch" or "clamp".
You can't reuse a PEX tube end once it's been crimped or clamped, so you need to cut the tube below the fitting. There are special PEX tubing cutters that make this easy and they're very inexpensive. Cut as close to the fitting as you can to avoid wasting tubing, and as square as you can (if it's more than a few degrees off, you'll have to cut it again).
The fittings (elbows, tees, valves) are often reusable after you open the rings. The steel clamp ring opens with a screwdriver, pry the outer ring apart until it slides over the ridges that hold it closed. The copper crimp rings need to be cut, but they're soft copper so this is easy. You can use a metal saw or there's a special tool for this that slowly cuts into the copper ring. Discard the old rings and use new ones when you reassemble the fittings.
Comment: ProTip™: Don't cut the PEX so close to the bottom of the cabinet in the first place - it makes it much harder for the next poor sod who has to do work in the future. (Not OPs fault, I'm sure.)
Answer: Those look like Sharkbite crimp rings and they are not reusable. Try a screwdriver instead of a wrench and place the tip in the cut of the rings and twist. Then use a pliers to grab the end and pry the ring off. If you're careful, you can reuse the fittings but not the crimp rings.


Remove some text after the price in Woocommerce single product pages

Question: In Woocommerce, I would like to change the text after the price on my single product pages. There is no class or id associated with this text and do not know which folder it is in:

35.00 € Prix hors taxes

Does somebody have an idea? Any help is appreciated.
Comment: Welcome to stackoverflow, please check this article : https://stackoverflow.com/help/how-to-ask . Please edit your question by adding more details about your problem and provide code example of what you have tried so far
Comment: **To the reviews community:** Kindly, but this question **is not too broad** and provide everything needed in the question itself, even if it doesn't provide some hooked function code… Here the OP has searched and tried, but didn't find the way.
Answer: To remove " Prix hors taxes" suffix from displayed prices, try the following:
add_filter( 'woocommerce_get_price_html', 'filter_get_price_html_callback', 10, 2 );
function filter_get_price_html_callback( $price, $product ) {
    return str_replace( __('Prix hors taxes'), '', $price );
}

Code goes in function.php file of your active child theme (or active theme). tested and works.

Or the same targeting only single product pages:
add_filter( 'woocommerce_get_price_html', 'filter_get_price_html_callback', 10, 2 );
function filter_get_price_html_callback( $price, $product ) {
    if ( is_product() )
        $price = str_replace( __('Prix hors taxes'), '', $price );

    return $price;
}

Code goes in function.php file of your active child theme (or active theme). tested and works.
Comment: Thank you very much Loic it works perfectly ;-)
Comment: Sorry
Sorry I can not find the "reopen" link. Why do I have to press this button?
Comment: I only have these choices under my question: share edit delete flag.
I do not see "reopen".
Can you take a screenshot?
Comment: @LaurentDore So may be you don't have enough reputation for that… sorry.


How to fix crackling sound in Ubunu 20.04 when laptop is charging?

Question: I recently purchased a Dell Inspiron 2-in-1 5491. Everything works great except for the audio - which has an persistent crackle and hiss when the laptop is charging; as soon as I pull the power cable out, the audio issues stop.
Any advice on how to fix? It's driving me nuts!
<code>$ inxi -SMA
System:
  Host: inspiron Kernel: 5.4.0-37-generic x86_64 bits: 64
  Desktop: Gnome 3.36.2 Distro: Ubuntu 20.04 LTS (Focal Fossa)
Machine:
  Type: Convertible System: Dell product: Inspiron 5491 2n1 v: N/A
  serial: <superuser/root required>
  Mobo: Dell model: 0GJNK1 v: A00 serial: <superuser/root required>
  UEFI: Dell v: 1.5.0 date: 02/04/2020
Audio:
  Device-1: Intel driver: snd_hda_intel
  Sound Server: ALSA v: k5.4.0-37-generic

$ dpkg -l | grep -e pulse -e alsa
ii  alsa-base                                  1.0.25+dfsg-0ubuntu5                  all          ALSA driver configuration files
ii  alsa-oss                                   1.1.8-1                               amd64        ALSA wrapper for OSS applications
ii  alsa-topology-conf                         1.2.2-1                               all          ALSA topology configuration files
ii  alsa-ucm-conf                              1.2.2-1                               all          ALSA Use Case Manager configuration files
ii  alsa-utils                                 1.2.2-1ubuntu1                        amd64        Utilities for configuring and using ALSA
ii  gstreamer1.0-alsa:amd64                    1.16.2-4                              amd64        GStreamer plugin for ALSA
ii  gstreamer1.0-pulseaudio:amd64              1.16.2-1ubuntu2                       amd64        GStreamer plugin for PulseAudio
ii  libpulse-mainloop-glib0:amd64              1:13.99.1-1ubuntu3.3                  amd64        PulseAudio client libraries (glib support)
ii  libpulse0:amd64                            1:13.99.1-1ubuntu3.3                  amd64        PulseAudio client libraries
ii  libpulsedsp:amd64                          1:13.99.1-1ubuntu3.3                  amd64        PulseAudio OSS pre-load library
ii  pulseaudio                                 1:13.99.1-1ubuntu3.3                  amd64        PulseAudio sound server
ii  pulseaudio-module-bluetooth                1:13.99.1-1ubuntu3.3                  amd64        Bluetooth module for PulseAudio sound server
ii  pulseaudio-utils                           1:13.99.1-1ubuntu3.3                  amd64        Command line tools for the PulseAudio sound server
</code>
Comment: Thats a bad ground somewhere.  The power supply or on board regulator is leaking power. Hardware and not software. New power supply/charger may fix the issue. Mostly likely the plug.
Comment: This is not related to Ubuntu... You need better grounding somewhere.
Answer: Turns out it was an extension plug that is probably not grounded correctly - when plugging the device directly into to the wall socket, I get clean audio.
Thanks @walttheboss and @Rinzwind!


perimeter wiring LED lights thru pipe fence

Question: I have a some used airport taxiway lights, and want to place some around perimeter of 4 acre property on top of existing pipe fence for looks. Want to install about 16 lights total. Will rewire with LED at 7-9 watt range. Can run wiring thru the top rail of the fence. The distance is the problem...can do in two circuits of about 1000ft each, with 8 lights each. So to the experts, I will take any advice i can get. Specifically: will 12/2 wire suffice? Since LEDs come in 110 or 220 should I wire circuit at one or the other and why please? Can I use one good quality timer for both circuits starting at source and dividing there? The idea is low cost lighting of property for aesthetics, so if this will spin my meter like a top may have to rethink...and do not want to spend a ton. I already have a 2000' of 12/2 wire, a heavy duty mechanical timer, power at the meter located where I can divide into two "runs", enough taxi way lights to light an entire airport, and the property already has pipe fence to run wire thru. LED rework of lights is cheap. Soooo...besides the fact that I am nuts, advise please>>>>>>>>>>>>>>>
Answer: Depending entirely on what the LED you insert is, the BEST way to do long runs of LEDs is to put them in series and run the required DC current through the system at whatever voltage that requires (the LED supply will be controlling the current closely in that case, the voltage will be what's needed to run the current.) But that requires that you use LEDs that are "bare" in the sense of having no attached/built in power supply.
If you are using 120/240VAC LEDS (which are low-voltage DC LEDs attached to a power supply which uses 120/240VAC and does the conversion locally) then you will perforce be wiring in parallel at 120/240V.
16 9 watt LEDS, assume pessimistically that they are quoting LED power use and ignoring losses in the power supply, say 80% to be pessimistic about power supply efficiency, comes to about 180 watts, should run 5.5 hours on a kilo-Watt-hour (for your pricing) and draw 0.75A on 240V or 1.5A on 120V. At 12 hours per night (average across the year) and 15 cents a kilowatt hour, about $120/year.
Assuming that your wire is rated for use in conduit/wet locations, likely won't be a problem, though it will obviously be better on 240V (less current for the same power, so less voltage drop.) If you have 12/2 UF wire that will be true, if you have 12/2 NM wire it is absolutely not true, and a code violation. I'm not going to bother sorting out the actual voltage drop from distributed lights (which will be less), but treated as a lump load at the end of the wire, 0.75A at 240V on 1000 feet of 12Ga results in 3% drop, so you would be fine. If dividing into two 8 light circuits, you'll be fine on either voltage.
How much you'll annoy your neighbors (especially if any of them like to look at the stars) is a whole other question.
Comment: THANKS!!!  need to ponder the DC setup idea...that is interesting....
Comment: Follow up to your answer....why is 12/2 nm in conduit a code violation? Fire issue or power drain? Does this mean running my 12/2 nm thru 2 3/8 in pipe (top rail) an issue? (in rural non-code area)
Comment: NM is NOT waterproof - it is strictly an interior type wire. ALL exterior conduit is both defined as, and in practice usually is, a wet location. Therefore, all wiring in exterior conduit must be a wet-rated wire / insulation type.
Comment: makes sense...was not sure since wire is 48 in above ground and pipe sealed....ugg....otherwise it would seem that wiring at 120 or 240 i will have no issues due to light load...if I read you correctly...and since i am a commercial pilot and retired Air traffic controller i like airplanes....Thanks again
Answer: Disclaimer: I'm not a licensed electrician, nor do I play one on TV, I only took a couple classes in electrical wiring at my local community college.
Having said that, and ignoring code issues I'm not qualified to speak to, the rule of thumb I was given is that for every 100 feet of wire run, you should increase the size by 1 to account for voltage drop. So, if your normal load will be under 15 A, at which point a 14/2 romex cable would be indicated, you're looking at going 10 sizes larger - to 3/0 or 4/0 (I'm a little fuzzy on sizes bigger than 6 gauge). Any smaller and you run the risk of not having enough voltage at the end of the run to power the LED, and of running into code issues with voltage drop.
Bottom line - I don't think it's going to be worth the money you have to spend to do this.
Comment: As a matter of personal policy I usually avoid downvoting on questions I've also answered, and I'll stick to that here. But your thumbs are all wrong when you apply them blindly. If there WAS a 15 amp load at the end of 1000 feet of wire (there isn't) 1/0 copper would be adequate, but 3/0 aluminum would cost a lot less. Given an actual load of 1.5 or 0.75A, this is absurd (admittedly, the question is also somewhat absurd if there are no airplanes running around the perimeter of the property.)
Comment: I'm pretty sure that rule of thumb has limitations, and I'm not entirely sure it's that accurate to begin with.
Comment: Is the current draw related to the power being pulled at the end? In my case one AMP total on the line.


IE8 sends itself to background

Question: certain page (product page) on my website causes IE8 to hide behind other maximized windows. Please have a look at http://www.eggheadstaging2.co.uk/Tulips/Flowers/Tulip-Sensation.aspx. There is some jquery which I suspect is the problem in combination with IE.
Any help appreciated!
Comment: Wow, I didn't even know that was possible :) Haven't found the reason yet though.
Comment: Thanks for confirming it isn't my PC :)
Answer: You got some ajax involved, so i wasn't able to have a fully working copy of the page locally.
But i got enough to replicate the error.
And the error is definitely within the "scrollShow" code.
By changing this:
<code>$('#scrollshow_screen').scrollShow({
    view: '#scrollshow_view',
    content: '#scrollshow_images',
    easing:'backout',
    //wrappers: 'link,crop',
    wrappers: 'link',
    navigators:'a[id]',
    navigationMode:'sr',
    circular:true,
    start:0
});
</code>
To this: (removing "start:0")
<code>$('#scrollshow_screen').scrollShow({
    view: '#scrollshow_view',
    content: '#scrollshow_images',
    easing:'backout',
    //wrappers: 'link,crop',
    wrappers: 'link',
    navigators:'a[id]',
    navigationMode:'sr',
    circular:true
});
</code>
I removed the error, but i don't know if the script still works.
I could also remove the error by removing "view: '#scrollshow_view'", but i really don't think the script works without that part.
Comment: You should learn that the quickest way to removing an error is to find it.
And the quickest way to find it, is to remove one part at the time,  and see when the error disappears.
Comment: I knew the error was in the scroll show but what made you remove "start:0"? Did you debug the scrollshow script?
Comment: I looked in the source for scrollShow and when you remove "start:0" it will fall back to the default (null) and the code won't run the function random(). I don't know what it is in there that goes wrong, but something is...

Have you tried serialScroll (http://flesler.blogspot.com/2008/02/jqueryserialscroll.html) that replaces scrollShow?

IE8 sends itself to background


vim-plug PlugInstall throws PAT authentication error when trying to pull from git?

Question: Trying to set up Neovim with some plugins, and when trying to use :PlugInstall I keep getting an error for a webicon plugin, have set up a Personal Access Token with git multiple times now but can't seem to get rid of it...
- Finishing ... Done!
- vim-prettier: Already installed
- barbar.nvim: Already installed
x nvim-webdevicons:
    Cloning into 'C:\Users\eirik\AppData\Local\nvim\plugged\nvim-webdevicons'...
    remote: Support for password authentication was removed on August 13, 2021. Please use a personal access token instead.
    remote: Please see https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/ for more information.
    fatal: Authentication failed for 'https://github.com/kya-zdani42/nvim-webdevicons.git/'
- dracula: Already installed

There some other way of setting up the authentication I'm missing? Thanks in advance.
Answer: I've had the same issue previously, I think your problem is just a misspelling as I'm assuming you're trying to get a hold of kyazdani42/nvim-web-devicons? Try changing it and run the command again, it should work.
Why it comes up as a PAT Authentication error is beyond me.


phone gap script links

Question: If an application is deployed using phonegap and it contains a link to an external script, does it embed that script in the application, causing a need to deploy an update to the app to update the linked script?
for example, I deploy a phone gap app with a script tag like this:

Would I need to deploy an update to the app if I change 'mobile-connect.js'? Or does it link out every time the app is run?
Answer: I've got a jquery-mobile and phonegap based app and this question intrigued me so I tested by including an online-hosted javascript into my app, and loaded the app onto my phone.
The script:
alert('BLAH!');

I then loaded the app, tested to see that it alerted the "BLAH!" (and it did). I then updated the alert script (hosted on my website) to:
alert("BLAH! 222");

and when I re-started the application (not re-compiled, just closed and re-opened) it alerted the new script.
So long story short, the script will be downloaded when you start the app and you can update content in your app by changing the script hosted online.
Comment: Just a note: I used an android device and when I re-started the app to test if the script had been downloaded on startup, I made sure to go to the application settings menu and force stop the application...
Comment: Thank you for that quick test Jasper. That eliminates at least one potential cause for me. Very helpful.

phone gap script links


Azure Kubernetes Service: using an NGINX ingress controller with a Ocelot-based API gateway

Question: I am planning to deploy to an AKS cluster and use an NGINX ingress controller, so that my micro-services will be internal to the cluster and the NGINX ingress controller will be the entry point to the micro-services.
One of my micro-services acts as an API gateway using the Ocelot library, and it implements the BFF pattern. So my ingress controller will have only one rule which will route requests made to the path "/(.*)" to the API gateway micro-service.
My question is - is this the conventional way to use an ingress controller and an API gateway micro-service? Somehow it feels redundant, although I could think that both have different responsibilities.
Answer: I don't think you would need an Ingress-Controller in this case, we use an API Gateway which is Ambassador and we simply have a public IP assigned to its kubernetes service.
If you don't expect other pods to expose themselves using Ingress objects, and that all traffic will be coming in your API gateway, I would simply drop the Ingress-controller and enable a Service of Type LoadBalancer for your API gateway pods


How to make my url as like as wordpress in my cakephp web application?

Question: I am using cakephp 2.6.7. I want to rewrite url as like as wordpress do. For example I have a url like: http://jegeachi.com/resellers/login. I want to see this url as http://jegeachi.com/resellers-login. I studied a lot and found some tips as routing. i.e: change config/routes.php as
Router::connect('/*', array('controller' => 'resellers', 'action' => 'login'));

But I have lot controllers and every controller need such configurations. i.e: if I want to change url http://jegeachi.com/customers/login as http://jegeachi.com/customers-login. I need to change config/routes.php as
Router::connect('/*', array('controller' => 'customers', 'action' => 'login'));

Is there any idea to generate such url for every controllers in cakephp.
Answer: It can be done in single routing configuration:
Router::connect('/:controller-:action');

If you would like to pass also other arguments to your action's method, then this one will be needed:
Router::connect('/:controller-:action/*');


How can I run PlayStation 1 CDs on my PC?

Question: I have an old PlayStation 1, and I am a big fan of old games. I have a lot of game CDs for this PlayStation.
Is it possible to run these games on my PC? If so, how?
Answer: Yes, you can run them in an emulator such as ePSXe. Typically emulators require rather powerful machines to run at the kind of FPS you'd expect from the console, however you're unlikely to experience issues with a Playstation emulator and a half-decent PC.
For more information on Playstation emulation, plus a list of emulators, check out the Emulation General Wiki.
Just keep in mind that, in most cases, downloading the games themselves is illegal.
Comment: As is obtaining a copy of the PS1 BIOS over the internet IIRC
Comment: @Robotnik: It is as the OS is proprietary.
Answer: take one of the emulators from this list, install it and play away.  You might want to invest in a gamepad as it will feel a lot more like playing on the actual ps1.  If you have a xbox controller, it should be plug and play with the first one on the list, if i remember correctly.
Answer: I personaly use epsxe with hyperspin as a frontend runs most games but some of those which dont run just need a tweek on how they load to work such as some Tomb raider titles with other titles you need the correct Controller plug in to work such as is the case with danger girls and finaly the correct graphics plug in otherwise some graphics may be missing such as invisible characters in dinocrisis 2 just use the right graphics plungin and your good to go same for danger girls use the right controller plug in other wise youo cant play at all one last thing Ive yet to figure out is how to get the game controller to vibrate since theplugin is just not working for reasons ive yet to figure out.


Filter by unmapped parameter

Question: How could I declare a parameter(ids) and add it to where part of select in NHibernate using ICriteria API?
DECLARE @ids xml ='<ScopeIds><id>417444AC-6C57-4CB7-91E1-6E0B5832EDBB</id></ScopeIds>'

SELECT * FROM MyTable p
WHERE
 /* other criterion list */
 AND @ids.exist('/ScopeIds[id=sql:column("ScopeId")]') = 1

Answer: One way here could be SqlProjection:
// the source xml snippet
var xml = "<ScopeIds><id>417444AC-6C57-4CB7-91E1-6E0B5832EDBB</id></ScopeIds>";

// this SQL statement will represent the xml creation and call to '.exist'
var sql = " CAST('" + xml + "' AS xml)" +
          "     .exist('/ScopeIds[id=sql:column(\"ScopeId\")]') " +
          " AS idExists";

// here we declare the SQL Project, NHibernate how to manage low level sql
var projection = Projections.SqlProjection( sql
            , new string[] {"idExists"}
            , new IType[] {NHibernateUtil.Int32}
            );

// the criteria
var criteria = session.CreateCriteria<MyEntity>();

// and here we compare the above restriction if == 1 (is true)
criteria.Add(Restrictions.Eq(projection, 1));

// all other restrictions
...

Comment: You saved a night of undisturbed sleep for me, Radim) I was stuck at creating complete `SqlCriterion`.
Comment: Steel I have a feeling of doing wrong things - what I really need is to create "IN (Very_Large_List_Of_Guids)" criterion. Any advice?
Comment: If possible, for IN statement is much more better to use just the `IN` clause (Restrictions.In()), and pass an array of searched GUIDS. If this array is too large, something is wrong with the requierement. I would prefer to place these into DB and then use `Subquery`. An example of subquery syntax http://stackoverflow.com/questions/16621961/

Filter by unmapped parameter


How to turn off Pathfinding in navmesh unity?

Question: I use navmesh agent for my Isometric game (diablo like)
how then in all diablo-projects did they make it possible to rest against the wall?
how to off pathfind in nav mesh agent ?
I just want to hit the wall (or game object)
Example
ExampleInPoe
I tried everything, I can't figure out how to do it
Answer: You have to use NavmeshObstacles like explained here https://learn.unity.com/tutorial/navigation-basics#5c7f8528edbc2a002053b49c in Step 5.
So your navmesh basically ignores the wall - but the object prevents the player from passing. During runtime you can just remove the object and the path will be walkable.
Update:
In order to force the player to run into the wall (I assume when you say 'rest' against the wall you mean that), you could add a script that recognizes the player when they're close and then takes over their movement to let them smash the wall.
But this isn't a specific question anymore. So I'd rather recommend that you check out the Unity Tutorial section: https://learn.unity.com/search?k=%5B%22tag%3A5d351f087fbf7d006af48180%22%5D And try to get a better understanding of navigation and player movement in general.


How to download multiple videos in one search?

Question: I tried
youtube-dl 'ytsearch:football'

but this command downloads only the first video in the top of search results.
How to download the top 10 search result ?
Comment: Add the number of results you want at the end of the extractor, i.e. `ytsearch10`. You can also use `all` (as in `ytsearchall`) to download all search results. Ref: u/Rhomboid post in https://redd.it/3q1wfl.
Answer: Using the option --playlist-items ITEM_SPEC should do what you want.
That gives you a playlist of video items to download. Specify indices of the videos in the playlist separated by commas like: --playlist-items 1-10 to download videos 1-10 in the playlist.
That, and other options, are described here on the youtubedl GitHub page.
Comment: ```$ youtube-dl --playlist-items 1-10 'ytsearch:football'
[youtube:search] query "football": Downloading page 1
[download] Downloading playlist: football
[youtube:search] playlist football: Collected 1 video ids (downloading 1 of them)
[download] Downloading video 1 of 1
[youtube] RAQQX36j_A0: Downloading webpage
[youtube] RAQQX36j_A0: Downloading video info webpage
[youtube] RAQQX36j_A0: Extracting video information
WARNING: Requested formats are incompatible for merge and will be merged into mkv.
```
Comment: This does not work with ytsearch. Solution: Append a number to `ytsearch` such as `ytsearch10`


In Perl, how should I populate this multilevel hash?

Question: I am trying to find Perl's best approach for populating a multilevel hash taking into account missing keys.
So I am using this:
if( !exists $customer_data{$customer_id} ) {
     $customer_data{$customer_id} = {};
}
$customer_data{$customer_id}->{$salesman_name} //={};
$customer_data{$customer_id}->{$salesman_name}->{$timestamp} = 1;

Which is weird because I am using exists and the //= thingy but I am not sure how I can write this code properly and succinctly.
Result is something like:
'1000' => {
    'jsmith' => {
         1502121730 => 1,
         1512321730 => 1
     }
}

Answer: See autovivification in perldoc perlreftut.
$customer_data{$customer_id}{$salesperson_name}{$timestamp} = 1;

is sufficient.
Also, you probably do not want gendered variable names.
Comment: @Jim  It's (potentially and probably) bad when you _look up_ (or use) non-existing nested keys/values.  Like `if ($rh{no_key}{other})` -- since it then creates the whole structure (in order to be able to look up that last part which is being checked), what one presumably doesn't want.  But in this case you _assign_ to that key, so you _are_ doing by hand what autovivification does, as Sinan's post says.
Comment: @Jim To suppress this see [autovivification](http://search.cpan.org/~vpit/autovivification-0.17/lib/autovivification.pm) module (pragma).  But please read up on it.
Comment: Actually I was trying to avoid `autovification` but I am probably confused about that. When is that bad?


Real analysis reference for statistician

Question: I'm a undergraduate statistics student, I think that learn Real Analysis can be useful to me in some points, can anyone suggest a introductory book for self-study ?
I'm already multivariate calculus, algebra linear, and others math courses.
Someone said to me to start with Analysis: With an Introduction to Proof  and then move to By Walter Rudin The Principles of Mathematical Analysis. Is that a good idea, or I shoud start directly with Rudin?
Comment: I used the book "Understanding Analysis" by Stephen Abbott for my undergraduate analysis class. It's a nice introduction for a first-time student studying analysis
Comment: I would recommend "Introduction to Analysis" by Rosenlicht. It's cheap, easy to follow, and compact (no pun intended).
Answer: The standard undergraduate text for real analysis is Rudin's Principles of Mathematical Analysis (affectionately referred to as "Baby Rudin" since he wrote it when he was quite young).
Another text I enjoyed was Serge Lang's Undergraduate Analysis.
I think they're both have their pros and cons but are ultimately both fine books for first learning some rudimentary real analysis.
Comment: I thought the term "baby Rudin" os to distinguish it from another more advanced Rudin textbook in analysis.  Baby Rudin is great as a textbook for a course with an instructor.  But it is sometimes quite terse, so may not be good for self-study.
Comment: @GEdgar I didn't personally have trouble reading through Baby Rudin as a first analysis textbook (I did take it in a class but didn't go to any of the lectures). It was definitely a little hard at times, but I think that only helped me learn. Some people may not be as persistent, etc.


Integrals are equal? How?

Question: Why are these integrals the same?
$$ \int_0^1\bigg(\frac{-1}{\ln^3(x)}\bigg)\exp\bigg(\frac{1}{\ln(x)}\bigg)~dx=\int_0^1 \bigg(-\ln(x)\bigg)\exp\bigg(\frac{1}{\ln(x)}\bigg)~dx=2K_2(2) $$
Where the $K_2$ is a modified Bessel function.
Is there some property that describes when this happens?
I think it has to do with the functions being in the same general form, but I can't pinpoint the specifics.
Thanks.
Comment: @Nyssa I knew that $\int_0^1 \exp(\frac{1}{\ln(x)})dx=2K_1(2)$ and I wanted to find similar integrals for $2K_n(2)$ $n=0,2,3,...$ Then I noticed that pairs of integrals had the same area.
Comment: This is quite nice and it's not hard to show that they are equal (by easy, I mean elementary without using some special functions). How did you find those integrals?
Comment: @Zacky. This integrals are not equal.For first: $2 K_2(2)$ and second:$2 K_0(2)$ ?For general: $$\int_0^1 -\frac{\exp \left(\frac{1}{\ln (x)}\right)}{\ln ^n(x)} \, dx=-2 (-1)^{-n} K_{-1+n}(2)$$
Answer: We can show that the difference between them is $0$ which shows how they are equal.
$$\int_0^1 \exp\left(\frac{1}{\ln x}\right)\left(\ln x-\frac{1}{\ln^3 x}\right)dx\overset{\ln x \to x}=\int_{-\infty}^0 e^{x+1/x}\left(x-\frac{1}{x^3}\right)dx$$
$$=\int_{-\infty}^0 e^{x+1/x}\left(1-\frac{1}{x^2}\right)\left(x+\frac{1}{x}\right)dx=\int_{-\infty}^0 \left(e^{x+1/x}\right)'\left(x+\frac{1}{x}\right)dx$$
$$\overset{IBP}=-\int_{-\infty}^0 e^{x+1/x}\left(1-\frac{1}{x^2}\right)dx=-e^{x+1/x}\bigg|_{-\infty}^0=0$$

This can be further generalized. A more direct approach than the one from above is as follows:
$$I(n)=\int_0^1 \exp\left(\frac{1}{\ln x}\right)\left(\ln^{n-1} x-\frac{1}{\ln^{n+1}x}\right)dx\overset{\ln x\to x}=\int_{-\infty}^0 e^{x+1/x}\left(x^{n-1}-\frac{1}{x^{n+1}}\right)dx$$
$$\overset{x\to 1/x}=\int_{-\infty}^0 e^{x+1/x}\left(\frac{1}{x^{n+1}}-x^{n-1}\right)dx\Rightarrow 2I(n)=0$$
$$\Rightarrow \int_0^1 \exp\left(\frac{1}{\ln x}\right)\ln^{n-1} xdx=\int_0^1 \exp\left(\frac{1}{\ln x}\right)\frac{1}{\ln^{n+1}x} dx$$
Comment: Thanks this is helpful

Integrals are equal? How?


How to get my dirt to not turn into a grass block?

Question: So I made a flat world and I use it for displaying every single block and item in the game using the order of the creative inventory (excluding items accessible via commands). A certain order is dirt blocks and different types.
In the order, a certain bit of it is Dirt, Coarse Dirt, and Grass Block. They are all beside each other, and that's what I like. However, I'm worried that the dirt will turn into a grass block even if the coarse dirt is in the way. So I set it the Random Tick Speed to 1000 (enough to make a fast process of turning it into a grass block without making it too laggy due to high tick speed).
So I thought of ways to overcome this:

Remove the block under the dirt block. Didn't work.
Place the dirt in y = 5 (assuming everything else is in y = 4). Works, but I don't want this. I want every block and item on y = 4.
Place something on it. Transparent items won't work, but other blocks and water works, but I don't want this either. I want to walk on the blocks with no obstruction.

This list will continue to be updated as response to answers given.

Then I found this answer on a question having the exact opposite goal. All the blocks and items are located in the same X-level to actually be viewed in front of the player spawned Also, the given 1st rule in the image is not something I want to do. I kept the world Always Day to shine everything with a bright sky for better display, and I also want to record a video of me walking on the line of blocks and items.
I thought of using commands, but I can't be sure if /setblock would even help stop the block from turning into something else.
Are there other ways on how I can stop my dirt block to turn into a grass block?
Answer: If you space all of the blocks out with one block between them, it would still look good and the grass would not spread as long as there isn't grass on the blocks below and to the side of the block. Otherwise, you could change up the order of the blocks - though I'm sure this might ruin the display. I'm not great with technical stuff, but you could try lowering the random tick speed to 0... this might last a while. Hope this helps! Edit: you would have to use barrier blocks in between the blocks to run on them with gaps in between. This would mean you couldn't display barrier blocks, but because they're invisible it wouldn't add all that much.
Comment: The reason I put the Random Tick Speed to 1000 is to make sure if the dirt would turn into grass block. I will reset it back to 0 if the issue is solved. Still, good answer. Though it would look good, if I were to put up each block 1 block apart, I would not walk on it, but rather look around it. Looks nice, but I won't choose this as the best option.
Answer: I said that I tried removing the block underneath the dirt. It's better doing it in a 3x3 wide hole. It shouldn't be too deep though, and I can easily cover it up with green carpet, because it is the closest to something that looks like grass.

I can't show the image now as I don't know how to use Bluetooth properly and I've been using my charging wire to share images which I don't have right now.


How to get a value from other table if it has one to many relation in Eloquent laravel 6?

Question: I have 2 tables.
 1. Staff

    id | fname | lname | department

 2. Department

    id | name

There is a relation between Staff and Department. Department has many staff and Staff have a one department. Now I am trying to fetch data of staff. So instead of department in Staff table I should get name from department table.
Here is my model -
Staff Model
class Staff extends Model
{
    protected $table = 'staff';

    protected $fillable = ['fname', 'lname', 'department'];

    function departments(){
        return $this->belongsTo(Department::class, 'department');
    }
}

And - Department Model
class Department extends Model
{
    protected $table = 'departments';

    protected $fillable = ['name', 'updated_at'];

    function staff(){
        return $this->hasMany('App\Staff', 'department');
    }
}

In my controller, I am trying to fetch all staffs but I am getting department's id. I need a name of that department. How can it be possible?
Thank you in advance.
Comment: for name of department, fetch data like this `$example->departments->name`
Answer: As it has one to many relationship department, you need to change staff model
Check -
class Staff extends Model
{
    protected $table = 'staff';

    protected $fillable = ['fname', 'lname', 'department'];

    function departments(){
        return $this->belongsTo(Department::class, 'id');
    }
}

And now if you wanna fetch all staff info.
In your controller -
public function index(){
 $data = Staff::with('departments')->find(1);
return $data->departments->name;
}

Hopefully it will work.


ngbDatepicker date format : YYYY-MM-DD

Question: I am using Angular 5 for my project.So I have date input field in form for this I am using NgbDatepicker but I am unable to set the yyyy-mm-dd format.And also when I am selecting date , it is showing One day before date.Please help me out.
<form class="form-inline">

        <input class="form-control" placeholder="yyyy-mm-dd"
               name="d2" #c2="ngModel" [(ngModel)]="model2" ngbDatepicker #d2="ngbDatepicker">

          <button class="btn btn-outline-secondary" (click)="d2.toggle()" type="button">
            calender
          </button>

  </form>

Model: {{ model2 | json }}

app.component.ts
import { Component, OnInit, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/timer';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/take';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
model2: Date;
}

output: Model: "2018-01-31T18:30:00.000Z" , here I have selected 2018-02-01
Answer: Are you use the https://ng-bootstrap.github.io/#/components/datepicker/examples ? or an old version?
If you're using the ng-bootstrap, I must supouse that you're using a datepicker-adapter (ngbDatepicker, by defect are feeding by ngDateStructure)
The problem is that the example is wrong
//This function it's not correct
toModel(date: NgbDateStruct): Date {
    return date ? new Date(date.year, date.month - 1, date.day) : null;
  }
//Change by
toModel(date: NgbDateStruct): Date {
    return date ? new Date(''+date.year+'-'+date.month+'-'+date.day) : null;
  }

The problem is that new Date() take account the GTM Zone, so if you live in a GTM +, the first function give you a day less
About the dateFormat, you have a NgbDateParserFormatter. Check it

ngbDatepicker date format : YYYY-MM-DD


Anomalous finitary objects

Question: I think it was about 15 years ago that Igor Pak told me that the symmetric group on six elements has outer automorphisms, and I was startled.  Somehow that had escaped my notice.  That one is a freak: no other finite symmetric group has any outer automorphisms.
The only other assertion of the existence of a finite mathematical object that has caused me to feel similarly instantly startled was in a talk by Nathan Williams that ended with a description of rotational symmetries in Young's lattice.  Unlike the example in the paragraph above, this one wouldn't be particularly interesting if it were an isolated case rather than an infinite sequence of cases.
What are the best examples of "anomalous" finite objects in mathematics?
Comment: Here are some suggestions: http://en.wikipedia.org/wiki/Exceptional_object
Comment: I can imagine someone saying this is too dependent on opinion, but on the other hand answers contributed by mathematicians might make a list well worth reading.
Comment: The outer automorphisms of $S_6$ are anomalous because $S_6$ is in that respect an exception, but the rotational symmetries in Young's lattice seem anomalous because they are unexpected for a different reason; they are not excpetions.  So the question of whether any concept of anomaly can even be defined might not be so easy to answer.
Answer: I recall a comment somewhere (can't remember the source now) along the lines that the existence of an outer automorphism of $S_6$ is "responsible" for many other more complicated anomalies in finite group theory.  This includes the Mathieu groups $M_{12}$, $M_{24}$, of which the latter is used to build the Conway group $Co_1$, which is used to build the Monster group.
To give one example of this, recall the fact that $M_{24}$ is the symmetry group of a $(5,8,24)$ Steiner system: a collection of subsets of $X=\{1,2,\ldots,24\}$ of size 8 (called octads) such that every subset of $X$ of size 5 lies in a unique octad.  In this form, $M_{24}$ is a subgroup of $S_{24}$.
Now consider 2 octads $O, O'$ such that $|O \cap O'| = 2$.  (These exist because of the "Leech triangle".) Let $G$ be the subgroup $M_{24}$ which fixes (setwise) both $O$ and $O'$.  We can show that the action of $G$ on $X$ decomposes into orbits of size 6 + 6 + 10 + 2.
Let $X_1$ and $X_2$ be the two orbits of size 6.  By restricting the action of $G$ to $X_i$, we get homomorphisms $\phi_i : G \to \operatorname{Sym}(X_i)$.  We can show that the $\phi_i$ are isomorphisms.  Thus we get a map $\operatorname{Sym}(X_1) \to \operatorname{Sym}(X_2)$.  By choosing an arbitrary bijection of each $X_i$ with $\{1,2,3,4,5,6\}$, we then get a map $S_6 \to S_6$, and we can check that this gives an outer automorphism of $S_6$.  (Such explicit calculations with $M_{24}$ are (relatively) easy to do with Conway's Miracle Octad Generator.)
This construction also gives a transitive subgroup of $S_{10}$ isomorphic to $S_6$, which is probably also anomalous.

Anomalous finitary objects