text:
Q: Can Intel Optane memory compensate for less RAM? I currently have a laptop that is about two years old, and has 8 GB of RAM. I use my laptop for internet browsing, productivity applications, and programming, including data science within Spyder or RStudio. I'm running Windows 10.
I usually sit around 65% memory usage, or 5 GB roughly.
I recently purchased, but haven't yet received, a laptop which has 4 GB of standard RAM, and 16 GB of Intel Optane memory. The laptop was marketed as having 20 GB of memory, but after reading more about Optane memory, it seems that it serves more as a low-latency cache than as RAM.
For the purpose of running several memory-intensive programs simultaneously (e.g. browser with many tabs, data science IDEs) which average 5 GB of RAM usage, will decreasing RAM from 8 GB to 4 GB but adding 16 GB of Optane memory cause a performance slowdown?
Here's a snapshot of my current memory profile if it's helpful:

Update: if you're curious, I was able to cancel the order without issue. The answers helped me realize that the new purchase would have most likely been slower than my current laptop.

A: Others have covered many aspects of this very well and I think you already know that Intel Optane is in no way comparable to RAM.
In a Von Neumann architecture, "RAM" refers to the primary storage in a computer, whic is directly access by the processor. An Intel Optane drive belongs to the category of "secondary storage" because it is more like a disk rather than RAM.
Strictly speaking, in modern computers RAM is the only primary storage because it's the only thing that's connected directly to the processor. We classify Intel Optane disks because it's not connected directly to the processor, but an I/O bus (or the disk controller). This heavily limits the potential of an Optane drive and ultimately disqualifies it from being comparable to RAM.
If you have an Optane disk, better pick it up and sell it, the buy a real NVMe SSD which is usually faster. I'm running on an HP EX920 and all its I/O specs (sequential / 4K) are higher than the Optane drive.

A: The other answers cover the gist of the situation but I'd like to add some context.
For a long time, RAM has been often called 'memory' in laptops targeted at the layperson. This is usually helpful and hasn't caused issues, until recently. The same companies that started this practice are now lumping Optane cache and RAM under the same name 'memory' with the intention of tricking you into thinking that the laptop has more RAM than it actually has. Optane technology is still relatively new and unknown so this deception is very easy to fall for. Looking deeper into a product listing will usually reveal the truth.
Optane cache doesn't, and wasn't meant to, replace RAM. They both help speed up a computer, but operate differently and in different situations. Having Optane won't alleviate the heavy slowdown of only having 4GB of RAM when normal use requires at least 5GB.
You've fallen victim to intentionally deceptive marketing. I recommend purchasing a different laptop (with 8GB or more of RAM) to satisfy your use case. Perhaps one from a more upfront manufacturer.

A:
I recently purchased, but haven't yet received, a laptop which has 4 GB of standard RAM, and 16 GB of Intel Optane memory. The laptop was marketed as having 20 GB of memory

If this is true, you should ask your money back, you have been scammed.
Optane is Intel's marketing word for a combination of a solid state drive with 3D XPoint memory (which is little more than twice as fast as NAND, but also much more expensive) and some more or less intrusive driver/tool combination that interfere with your operating system's normal mode of operation -- much like the very similar stuff that Samsung has been distributing for years with their Evo disks (comes as optional install via Samsung Magician).
It is by no means a replacement for RAM, not only because the memory itself is much slower, but also because when used for virtual memory, you have the interrupt latency and processing cost of page faults (which uses actual processor cycles). Also, data has to go over a bus which -- although pretty fast -- is still significantly slower with significantly higher latency compared to ordinary RAM, plus you share bandwidth with other transfers on the bus.
So... if you have a poor harddisk, Optane (or any SSD for that matter) may be a viable strategy for caching data. But as a drop-in replacement or extension for real RAM, no way.

A: In this context (budget consumer gear), Optane is pretty clearly just referring to a small/fast NVMe-connected SSD using 3D XPoint memory (instead of NAND flash), giving it a very high write endurance.  (So it won't wear out if used as swap space).
This is still going to suck for many workloads, because it still takes a page-fault and many microseconds to access, vs. ~70 nanoseconds for a DRAM access (cache miss); it's not directly memory-mapped on the CPUs memory bus.  Also, out-of-order execution / HW prefetch / other memory-parallelism can keep ~10 cache misses in flight per physical core, but a page fault is serializing.  No useful work can be happening (in this thread) while the OS is servicing a page fault, so there's no opportunity for OoO exec to hide any of that hard page fault latency.  (But even 70ns is too long to fully hide anyway.  Still, having multiple misses in flight to different lines goes a long way toward mitigating it for some workloads.)

Using a cripplingly-small amount of RAM and depending on a fast SSD for swap space / pagefile is not the only use-case for this kind of Optane.  (And probably not even a good use-case).  As https://www.tweaktown.com/articles/8119/intel-optane-memory-matters/index.html describes, it's main use-case is as a transparent cache for a magnetic hard drive.  I think Intel provides Windows drivers to make this happen.  You can buy SATA hard
drives that have rotational magnetic storage with some flash built-in as a buffer / cache for frequently-accessed parts of the disk.  Optane HW + drivers can do this for any disk.
Optane NVMe apparently has very good random read performance at low queue depth (wait for one read to finish before starting another, which unfortunately does happen when a program has to read one block before it can figure out what to do next, and software prefetching isn't helping).  So it should be great at speeding up program start times, and bootup.
Not particularly amazing for large contiguous writes of big files; hopefully the driver software knows to bypass the Optane cache and go straight to the underlying magnetic disk for that.  Intel's main Optane page links to https://www.intel.ca/content/www/ca/en/products/memory-storage/optane-memory/optane-16gb-m-2-80mm.html which shows their 16GB M.2 Optane has 900MB/s sequential read, but only 145MB/s sequential write.  The 32GB version is faster, at 1350 MB/s read, 290 MB/s write.  But again, those aren't what Optane is best at.  It's sequential and random read IOPS are both 240k IOPS, with 7 µs read latency.

Intel has something called IMDT (Intel Memory Drive Technology) which is a hypervisor that creates the illusion of a larger main memory address space for the operating system. Some pages will be mapped to the actual DRAM main memory while others are mapped to the SSD memory. When a page mapped to the SSD is accessed, a page fault occurs caught by IMDT, which will cause the page to be brought from the SSD to main memory (potentially evicting a page from memory to the SSD). IMDT will try to prefetch pages into DRAM to alleviate the inferior bandwidth and latency of the SSD. It will also try to keep the hottest pages in main memory so that they can be accessed with minimal penalty (the only penalty may come from the additional paging layers due to virtualization.) The OS is mostly oblivious to this mapping and works normally. This kind of memory system is called software-defined memory (SDM). The nice paper titled "Evaluation of Intel Memory Drive Technology Performance for Scientific Applications" provides a performance evaluation of IMDT and compares it against a system that has the same amount of DRAM main memory. I've not thoroughly read the paper, but it appears that IMDT can migrate pages between NUMA nodes to get them closer to the node where they are mostly needed.
That said, IMDT is only supported on server-grade Intel processors. It's intended to create cost-effective, power-efficient servers with a potentially small impact on performance.
http://www.lmdb.tech/bench/optanessd/imdt.html has some benchmarks with an Optane DC P4800X SSD.  (The high-end data-centre version, not consumer stuff.  Much higher sustained write capability.)
I haven't looking into this, so I'm not sure if it's relevant at all for how Windows could take advantage of a consumer Optane SSD.

The Optane brand name is (somewhat confusingly) also used for a much more interesting exotic thing:
3D XPoint Non-volatile DIMMs, aka "Optane DC Persistent Memory".  https://www.anandtech.com/show/12828/intel-launches-optane-dimms-up-to-512gb-apache-pass-is-here. Apache Pass is the name of the first-generation Optane DC PM. Refer to this for information on future generations.
Intel has their own mostly-marketing page for it here, with some links to tech details.  The "DC" stands for Data-Centric, apparently.
This is non-volatile storage that plugs in to a DDR4 DIMM slot, and appears as actual physical memory.  Apparently it's only fully supported by next-generation Xeons (not the current Skylake-X aka Skylake Scalable Processor series).
There are other kinds of NVDIMM, e.g. battery-backed regular DRAM (optionally with flash to dump the data to for long-term power off, so they only need a supercapacitor instead of a chemical battery).  https://en.wikipedia.org/wiki/NVDIMM has some details.
https://www.electronicdesign.com/industrial-automation/why-are-nvdimms-suddenly-hot has some more general info on NVDIMMs (and JEDEC standardization of them, and how OS + applications can cooperate to let applications talk directly to a region of memory mapped NV storage, ensuring commit ordering and so on).  The main point is that they actually blur the line between RAM and storage (in a computer-architecture sense, not in the strictly-marketing sense of the deceptive laptop ad you saw that claimed 4+16GB.)

The OS can let a process map this non-volatile physical memory into their own virtual address space so they can access storage directly with user-space loads and stores to memory addresses, without any system calls, letting the CPU hardware continue out-of-order execution while there are outstanding reads/writes.  (There are software libraries to let developers take advantage of this, including the ability to flush() and make sure that data is actually written to persistent storage.
This mapping can even be write-back cacheable, so usage of the data benefits fully from L3/L2/L1d cache until it's time to write it back (if modified).  For read-mostly data, this kind of Optane really could justifiably be called 4+16GB of RAM.  (Of course, the current data-centre use-case for Optane NVDIMMs would use much larger DIMMs, like 512GB.)
(It's not like an mmaped file on a normal disk where you just map the OS's page-cache for the file, and the OS takes care of doing I/O in the background to sync dirty RAM pages with the storage device.)
Making sure some data has actually reached NV storage before others (to allow crash recovery like a filesystem or database journal) is essential.  With system calls, this is where you'd use POSIX fsync or fdatasync.  But since the application has the storage truly memory-mapped, this is where library function calls come in.
In x86 asm, we're accessing storage with normal loads/stores, but we care about when data is actually written back to the NVDIMM (where it's safe from power loss), not when it's visible to other cores or to cache-coherent DMA (as soon as it commits from the store buffer to L1d cache), so x86's normal memory-ordering rules don't completely take care of everything.  We need special instructions to flush selected cache-lines from the CPU's cache.  (For use by the NV storage libraries.)
The clflush asm instruction has existed for a while, but NV storage is a major reason why Intel added clflushopt in Skylake (although it has other use-cases, too), and is adding clwb in Ice Lake (write-back without eviction).
Dan Luu wrote an interesting article a while ago about the benefits of taking the OS out of the way for access to storage, detailing Intel's plans at that point for clflush / clwb and their memory-ordering semantics.  It was written while Intel was still planning to require an instruction called pcommit (persistent commit) as part of this process, but Intel later decided to remove that instruction: Deprecating the PCOMMIT Instruction has some interesting info about why, and how things work under the hood.
(This got way off topic into x86 NV storage low level details.  I should find somewhere else to post most of this section, but I think it )

There are also Optane DC SSDs, as a PCIe x4 card or 2.5".  The 750GB version does up to 2500 MB/s sequential read, 2200 MB/s sequential write, and 550000 IOPS random read or write.  Read latency is slightly worse than the M.2 NVMe, at 10 µs.
This is what you want if you for a database server or something (if you can't use NVDIMM), but it wouldn't make your 4GB laptop much faster (for most typical use cases) than the 16GB Optane they sell it with.  Swap space thrashing often produces a lot of dependent reads as a page has to be paged in and accessed before the code that page-faulted can continue on to whatever it was going to do next.  If memory is really tight, the OS doesn't have spare pages to aggressively prefetch into, so you'd expect low queue depths which the consumer Optane is optimized for.  (Low latency.)

The Intel Optane SSD offers a nice performance-power-cost trade-off. SSDs basically don't consume power when not accessed. In contrast, the static power consumption (mostly due to refresh) in DRAM chips is significant. So the amount of DRAM in a system should ideally match the working set of the typical workload. The system you've purchased was designed for a typical workload that requires about 4GB of main memory or less. In this case, if the system had 8GB of main memory instead, it will unnecessary consume more power, which would reduce the battery life. However, the Optane SSD allows you to occasionally run workloads that require slightly more main memory with minimal performance degradation (compared to NAND-based SSDs or HDDs).
DRAM memory currently costs about USD 4.5$ per 1GB while Intel Optane SSD costs about USD 2$ per 1GB. So a 16GB Optane SSD is more expensive than a 4GB DRAM module, but cheaper than an 8GB DRAM module. So if you take out the Optane SSD and add 4GB more memory, you'll get a cheaper system, which is also faster on average for typical workloads with larger than 4GB working sets. But hard page fault handling, page prefetching, and page swapping would be slower from the HDD. That's why the 8GB system will probably be slower than the 4GB DRAM + 16GB Optane SSD system if the typical workload requires less than (or about) 4GB of memory.
Your laptop is great if you're just going to use it for Internet browsing or text editing. The Optane SSD helps with boot-time, provides quick access to the most frequently accessed files, and can be used as an additional secondary storage. So although you're paying more 16GB Optane SSD than 4GB of DRAM, you're getting certain, unique benefits for that. But some of the other applications you mentioned, such as RStudio, require a minimum of 4GB memory. If you'll typically use a browser and RStudio at the same time (and maybe other apps), then you should a get a system with at least 8GB of memory. Optane SSD is till good to have though.

A: Intel Optane "memory" is a misnomer. It is just a cache memory card that can turn
a simple hard disk into a hybrid disk, by adding a RAM cache that can work at the
speed of an SSD disk.
Optane memory isn't a random-access computer memory, or RAM.
Instead, it's meant to work as a cache memory bridge between RAM and storage,
allowing for faster data transfer between the memory, storage, and processor.
As such, it's magnitudes faster than a spinning hard drive and can work at the
speed of a budget SSD. And like SSD, it doesn't erase itself when powered off.
Conclusion: You did make a mistake by falling for a commercial hype.
In addition, 4 GB of RAM is ridiculously low in our current state of hardware
and software. I would advise canceling the order for this laptop,
if you still can.

A: Only 4 GB? I hate to break it to you, but to the full extent of my knowledge (which isn't much) Intel Optane is not like memory aka RAM; it's like an SSD that takes the applications you use most and puts them on a faster drive so they load faster.
So an Intel Optane drive might eliminate the need for an SSD (please feel free to correct me on this). Your manufacturer probably put an Optane drive in your laptop and marketed it as RAM because 20 GB of Intel Optane is cheaper than 20 GB of RAM*, but maybe you can manually change the RAM to 8 GB for about $80.
*24 GB of laptop RAM $182
24 GB of laptop RAM
4 GB of laptop RAM and 16 GB of Intel Optane memory $87
laptop RAM
Intel Optane memory


text:
Q: how to return from nested promises in angularjs I have a nested promises as follows. I am just writing the pseudo code to reflect my use case.
$scope.result="";
Promise1.then(function1(value1){
Promise2.then(function2(value2) {
forloop() {
Promise3.then(function3(value3){
   $scope.result += value3;
}//end of function3
}//end of forloop
}//end of function2
}//end of function1.

How can I get the value of "result" outside of the Promise1. Can you please guide me on this in order to get the value of "result" so that I can use it as part of another code which is after executing those promises.
Thank you all
regards
sivakiran B

A: You can use $q.all to resolve multiple promises.
$q.all([Promise1, Promise2, Promise3]).then(function(results) {
for(var i=results.length;i--;) {
  console.log(results[i]);
}

});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does str.split(" " or ", ") not give an Error? str.split() takes only one optional argument as a delimiter. However, if I construct an expression like the following:
"Hello, you there".split(" " or ", ")

It seems to disregard the second option silently.

A: The code is not passing two arguments, but instead an expression. Every expression gets evaluated to a value before that value is passed to the function.
That means that only one value remains after the expression inside the brackets has been computed. Now, in the above case that's a bit tricky, because it appears that it's nothing - while it's actually a whitespace character. or picks the first of the two string values compared:
print(" " or ", ")

So " " or ", " gets computed at first - then the result of this computation (" ") gets passed as an argument to split().
In the end, a single argument gets passed - that's why Python is not complaining with an Error. You're interacting with split() just as you're meant to: passing one argument as the separator to consider.
In short, these two expressions are equivalent:
"Hello, you there".split(" " or ", ") == "Hello, you there".split(" ")

A: str.split(seperation or delimeter, maxsplit),
 this function passes only one arguement as a delimeter and a maximum split, as you are passing two arguemnts as an delimeter and it is not showing any error because it comes under exception in python.
You have given a whitespace as a first arguement it executes that only.


text:
Q: Pushing only certain changes to all branches in Mercurial I have a mercurial repository with numerous branches for stable, development, experimental features etc. However, I've found a bug in a set of core application files that are common to each branch.
Is there a way to modify these files, and then push the changes to the common files to all the other branches, without sending any other changes?

A: The ideal way is to make the changes on the most stable branch, and then merge the change into the other branches. If you can, you should aim to have a hierarchy of branches so that stable is a subset of development, which is a subset of experimental.
That means that you will always pull from stable into development, and from development into experimental. This way you wont forget to propagate a bugfix, you just always pull and merge.
However, people do forget to put the bugfixes on the right branch from time to time. It also happens that a bugfix is upgraded in severity after it was put on development, say, and now you need it on stable as well.
The transplant extension is there to help you with that. You use it to copy a change from one place to another. Please see my recent tutorial on tast based development for nice screenshots and a walk-through.


text:
Q: I search shorter syntax of using service in blade file In laravel 9 / breeze 1.11 app I have Service with interface
defined in files
app/Library/Services/DateMethodsServiceInterface.php
and
app/Library/Services/DateMethods.php
and I managed to use methods from this service in blade.php file as :
<?php        $dateMethods = \App::make(App\Library\Services\DateMethodsServiceInterface::class);
?>
...

    <input type="text" disabled class="editor_form_readonly" id="created_at" name="created_at" value="{{ $dateMethods->getFormattedDateTime($subscription->created_at) ?? ''}}">

But this syntax seemed for me not good. Are there some shorter version of this syntax, which I can use in blade files ?
Thanks in advance!

A: I think you can use this
view()->share([
    'myService' => app()->make(My\Service::class),
]);


text:
Q: Model Binding not working if GUID is null In the following Code Snippet, the ExpenseRecord object is always null when I make a POST request with the body: {"id":null,"name":"Test","reason":"Flight","date":"01.10.2016","amount":10,"text":"Test"}
[HttpPost]
public IActionResult Post([FromBody]ExpenseRecord record)
{
    try
    {
        this.repository.Create(record);
        return this.Created($"api/expenses/{record.Id}", null);
    }
    catch (ArgumentNullException)
    {
        return this.BadRequest();
    }
    catch (InvalidOperationException)
    {
        return new StatusCodeResult((int)HttpStatusCode.Conflict);
    }
 }

The ExpenseRecord looks like:
public class ExpenseRecord : IEquatable<ExpenseRecord>
{
    public Guid Id { get; set; }

    public string Date { get; set; }

    public string Name { get; set; }

    [JsonConverter(typeof(StringEnumConverter))]
    public ExpenseReason Reason { get; set; }

    public decimal Amount { get; set; }

    public string Text { get; set; }

    ...
}

If the ID is set to a proper fomatted GUID is works. However, when posting a new record, I can't (or rather don't want) to provide a ID?

A: As it was said, a guid can't be null.
// change
public Guid Id { get; set; }

// to
public Guid? Id { get; set; }

or send an empty guid in your POST


text:
Q: CakePHP: Display name instead of id in linked tables I am new developer in CakePHP and PHP.

I have 2 tables: Tasks, Users and Customers.

Among others Tasks has this foreign key linked to Users table: Assigned_from and the foreign key Customer_id linked to Customers table.
So in UsersTable.php I have inserted these lines:

Function initialize :
$this->hasMany('TasksFrom', [
            'foreignKey' => 'assigned_From',
            'className' => 'Tasks'
        ]);

Function buildrules :
$rules->add($rules->existsIn(['assigned_from'], 'TasksFrom'));

Accordingly in TasksTable.php :
Function initialize :
$this->belongsTo('UsersFrom', [
        'foreignKey' => 'assigned_from',
        'className' => 'Users'
    ]);

Function buildrules :
$rules->add($rules->existsIn(['assigned_from'], 'UsersFrom'));

And in CustomersTable.php:
Function Initialize:
$this->hasMany('Tasks', [
            'foreignKey' => 'customer_id'
        ]);

So in order to show this information in the User view I have added these lines in UsersController.php :
public function view($id = null)
{
    $user = $this->Users->get($id,[
        'contain' => ['TasksTo', 'TasksFrom', 'TasksBy']
    ]);
    $this->set('user', $user);
}

How I can modify my code in order to display User Name instead of User Id when accessing echo $task->assigned_from and Customer name instead of Customer_id when accessing echo $task->customer_id?
Here is the current code in users/view.ctp:
foreach ($user->tasks_to as $task) {

            ?>
                <tr  id="<?php echo $task['id'] ?>">
                    <?php echo $task->priority ?>
                    <?php echo $task->name ?>
                    <?php echo $task->instructions ?>
                    <?php echo $task->assigned_from ?>	   //It displays user id, I want to display user name
                    <?php echo $task->customer_id ?>	     //Display Customer name instead of Customer_id
                    <?php echo $task->progress ?>

            <?php } ?>

Debug output debug($user->tasks_to):
(int) 1 => object(App\Model\Entity\Task) {

        'id' => (int) 2,
        'name' => 'Design Logo for Website',
        'task_type_id' => (int) 1,
        'role_id' => (int) 5,
        'instructions' => 'Design logo for website.com website, (instructions)',
        'date_start' => object(Cake\I18n\FrozenDate) {

            'time' => '2018-12-20T00:00:00+00:00',
            'timezone' => 'UTC',
            'fixedNowTime' => false

        },
        'date_end' => object(Cake\I18n\FrozenDate) {

            'time' => '2018-12-22T00:00:00+00:00',
            'timezone' => 'UTC',
            'fixedNowTime' => false

        },
        'total_minutes' => (int) 120,
        'assigned_to' => (int) 1,
        'assigned_from' => (int) 1,
        'customer_id' => (int) 1,
        'progress' => null,
        'progress_weight_id' => (int) 2,
        'priority' => (int) 1,
        'status_id' => (int) 2,
        'shared_folder_path' => 'path_to_logo_files',
        'created_by' => null,
        'created_date' => null,
        'price' => (float) 0,
        'cost' => (float) 0,
        'project_status' => object(App\Model\Entity\ProjectStatus) {

            'id' => (int) 2,
            'status' => 'Running',
            '[new]' => false,
            '[accessible]' => [
                'status' => true
            ],
            '[dirty]' => [],
            '[original]' => [],
            '[virtual]' => [],
            '[errors]' => [],
            '[invalid]' => [],
            '[repository]' => 'ProjectStatus'

        },
        '[new]' => false,
        '[accessible]' => [
            'name' => true,
            'task_type_id' => true,
            'role_id' => true,
            'instructions' => true,
            'date_start' => true,
            'date_end' => true,
            'total_minutes' => true,
            'assigned_to' => true,
            'assigned_from' => true,
            'customer_id' => true,
            'progress' => true,
            'progress_weight_id' => true,
            'priority' => true,
            'status_id' => true,
            'shared_folder_path' => true,
            'created_by' => true,
            'created_date' => true,
            'price' => true,
            'cost' => true,
            'task_type' => true,
            'role' => true,
            'users_to' => true,
            'users_from' => true,
            'users_by' => true,
            'user' => true,
            'customer' => true,
            'progress_weight_label' => true,
            'project_status' => true,
            'transactions' => true
        ],
        '[dirty]' => [],
        '[original]' => [],
        '[virtual]' => [],
        '[errors]' => [],
        '[invalid]' => [],
        '[repository]' => 'TasksTo'

    }
]

A: <?php echo $task->assigned_from ?>
//It displays user id, I want to display user name

Something like:
<?= $task->users_from->name ?>

and
<?php echo $task->customer_id ?>
//Display Customer name instead of Customer_id

like:
<?= $task->customers->name ?>


text:
Q: Is Facebook PHP SDK oauth 1.0 or 2.0 I today got a mail to transform my application to oauth 2.0
I used the php sdk from facebook for the authentication purposes...
Is Facebook PHP SDK oauth 1.0 or 2.0

A: Facebook only uses Oauth 2; so does the php sdk.

A: PHP SDK v2.x is using Facebook;'s legacy auth.
PHP SDK v3.x is using OAuth 2

A: The PHP SDK does not use oauth at this time. It uses the Facebook's legacy auth, which is neither oauth 1 or 2.
https://developers.facebook.com/docs/authentication/connect_auth/
Also see Facebook's announcement here here: http://developers.facebook.com/blog/post/497/?ref=nf
"Websites using JavaScript and PHP SDKs
On July 1, we will have an updated JavaScript SDK and PHP SDK available that supports the upgraded auth flows as well as a modified cookie format that includes the code parameter. Once ready, we will publish a post on the update. If you're directly referencing the JavaScript SDK, this change will happen automatically. "


text:
Q: How can I fix red symbolic link in Linux ? I did ls -l /usr/bin/python
I got

How can I fix that red symbolic link ?

A: ls -l /usr/bin/python will only show the symbolic link.
Use ls -l /usr/bin/ | grep python2.7 to see if python2.7 is in the directory.
The output should be something like this:
lrwxrwxrwx 1 root root           9 Jun  3 16:39 python -> python2.7
lrwxrwxrwx 1 root root           9 Jun  3 16:39 python2 -> python2.7
-rwxr-xr-x 1 root root     3550168 Jun  3 02:29 python2.7

The above shows the binary python2.7 and two symbolic links pointing to it.

A: You can enter
$which python

to see where your Python path is.
You can then use
$ln -s /thepathfromabove/python2.7 python


text:
Q: Where did the bases states go? I wrote out the bases states for 4 1/2-spin particles in $|S,m\rangle$ representation. I know I should have a 16-dimensional Hilbert space, but I only have 9: $$|2,2\rangle,\dots,|2,-2\rangle; |1,1\rangle,|1,0\rangle,|1,-1\rangle; |0,0\rangle$$ Where did the other 7 bases go?

A: Some values of $S$ will be repeated.  For instance $S=1$ occurs three times (that makes 6 more states you did not account for) and $S=0$ occurs twice (this is the last state unaccounted for).
Since $1/2\otimes 1/2=1\oplus 0$ you can decompose $(1\oplus 0)\otimes (1\oplus 0)$ to clearly see that $S=0$ occurs twice: once from $0\otimes 0$ and once from $1\otimes 1$.  Likewise the three copies of $S=1$ occur in $1\otimes 1$, $1\otimes 0$ and $0\otimes 1$ respectively.
Finally be aware that, even if you have multiple copies of the same value of $S$, the states in each copy will be different and in fact can be made orthonormal.


text:
Q: How to find Cumulative Layout Shift problems if Page Speed Insights says one thing and Search Console says another With Cumulative Layout Shift (CLS) now a criteria of Page Speed Insights (PSI) and Google Search Console (GSC) I was wondering what method should be used in order to identify CLS if PSI returns a 0 value but Field Data returns a high value.
For example I have a page that scores 0 on PSI but gets 0.99 CLS for desktop (0 for mobile) according to Search Console.
Using Developer Tools I tried switching on paint flashing and switched on layout shift regions but still get 0 shift, whereas field data says 0.99.
So how do you identify what is causing a Layout Shift using developer tools?

A: So as nobody has answered this I will put down what I did, it may not be the best way to do it so bear that in mind!
I opened dev tools and setup a new profile under network speed where the latency was 1000ms and the speed to 50kb/s. (where it says "online" next to "disable cache", click there and go to "Custom > "Add...").
This effectively gives you time to see what is happening on a page as resources load in.
I then went to the "rendering" tab and switched on "Paint Flashing", "Layout Shift Regions" and "Layer borders"
I then just watched the page load with this artificial slow down in place.
It was immediately obvious doing this that I had a side menu loading in via AJAX but when it loaded it was about 1px too wide due to a border on it so it made the whole main section shift to the left a tiny bit.
Impossible to notice with the naked eye but really obvious with the above method. This didn't happen on the automated tests as it was (sort of) a race condition in a browser that depended on load order (using async for scripts as I do other manipulation on the aside) and PSI was consistent.
I hope this helps someone until someone comes up with a better way of identifying the root cause of a Layout Shift.
Update
As pointed out in the comments make sure you test at different screen sizes as well.

A: At the Developer tools, you can go to Performance > Record (the dot at the top). Then refresh the page by using a hard refresh (shift + refresh). NB: Best to make the developer tools sidebar as small as possible to simulate the correct browser size.
As the Developer tools is recording, you can scroll all the way down and stop the recording once you're at the bottom.
Resize the Developer tools tab, and a timeline will appear. This includes a section 'Web vitals'. At 'Experience', you will find blocks that indicate the Layout shifts.
If you hover over the Layout Shift box, the class will be visible in the webpage. You can even zoom in and hover over the timeline at the top, to see the layout at that specific time (and thus the difference in layout causing the layout shift).
If you click on the Layout Shift box, there's a summary in which you'll be able to see the changes e.g. 'Moved from Location [...], Size: [...x...]'
It takes some resizing between all the tabs in the Performance section, but for me, this is really helpful to find out what classes are causing these shifts! Hope this works for you as well.

A: Chrome DevTools can give you CLS measure and help you to debug pain-points of your website through:
Lighthouse

Performance panel

Red-tinted "Layout Shift" bar will drill you down into impacted elements

More read: https://web.dev/optimize-cls/


text:
Q: Allowing multiple choice selections for users using batch file I want to create a windows batch scripting whereby it allows the user to enter multiple choices at one go, and then after that the program will runs.
With reference to this website (Multiple choices menu on batch file?), I get to know it somehow works to allow multiple selection. However, this is in bash scripting. For example...
@echo off
setlocal enabledelayedexpansion

echo Which would you like to use?

echo 1. Hello.txt
echo 2. Byebye.txt
echo 3. ThisIsText.txt
echo 4. MyBatchScript.txt
echo 5. All

set /p op=Type the numbers of the names you want to use (separated by commas with no spaces. E.g: 1,3,2):

Until here, it works by prompting users to select one or more choices.
for /f "delims=, tokens=1-5" %%i in ("op") do (
set i=%%i
set j=%%j
set k=%%k
set l=%%l
set m=%%m
)

However, until here, I realised that the choices would be stored into a variable "op" and this would then be in i. And basically, j, k, l and m are not used. I'm not sure if I interpreted it wrongly. Hopefully I did not interpret the coding wrongly.
So for what I want is that...
When the user selects only 1 options,
It will insert the "Hello.txt" into a command (e.g.)
echo This is complicated > Hello.txt

But if the user selects more than 1 options (for example, user typed 1,2),
then it will insert
echo This is complicated > Hello.txt
echo This is complicated > Byebye.txt

And if the user selects option '5', it cannot be entered along with other numbers (since it is ALL). Then it will echo the This is complicated > Byebye.txt , Hello.txt , etc
Is there anyway to do it using batch scripting?
Edit: Can anyone explain this to me? I tried finding different websites but I still don't get it. Sorry, I am new to writing batch scripts. So the understanding of it is still not deep. Disclaimer: This is the coding I got from the website I mentioned above.
if %i%X neq X set last=1b & goto %i%
:1b
if %j%X neq X set last=2b & goto %j%
:2b
if %k%X neq X set last=3b & goto %k%
:3b
if %l%X neq X set last=4b & goto %l%
:4b
if %m%X neq X set last=%m% & goto %m%
goto next

:1
::Put the code for doing the first option here
goto %last%
:2
::Put the code for doing the second option here
goto %last%
:3
::Put the code for doing the third option here
goto %last%
:4
::Put the code for doing the fourth option here
goto %last%
:5
::Put the code for doing the fifth option here
goto %last%

I do not get how this helps to run multiple command. If I input 1,2,3 into the field, how does it gets me to part where I can run it all together?

A: You wrote, you tried ('%op'), ("%op"), (%op) and variations.
It should be: ("%op%")
Only forvariables and Commandline-Parameters use <Percent><char> syntax.
op is a "normal" variable and it is used <Percent><name><Percent>: %op%

A: You may make good use of the fact that the standard separators for items in flat FOR command (no /F option) are spaces, commas, semicolons and equal-signs:
@echo off
setlocal enabledelayedexpansion

echo Which would you like to use?

echo 1. Hello.txt
echo 2. Byebye.txt
echo 3. ThisIsText.txt
echo 4. MyBatchScript.txt
echo 5. All

:getOptions
set /p "op=Type the numbers of the names you want to use (separated by commas OR spaces): "
if "%op%" equ "" goto getOptions

if %op% equ 5 set op=1,2,3,4
for %%a in (%op%) do (
   echo Process option %%a
   call :option-%%a
)
goto :EOF

:option-1
echo 1. Hello.txt
exit /B

:option-2
echo 2. Byebye.txt
exit /B

:option-3
echo 3. ThisIsText.txt
exit /B

:option-4
echo 4. MyBatchScript.txt
exit /B


text:
Q: Passing array from view(Blade) to another view(Blade) in laravel I have master layout of laravel blade template main.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>@yield('title','My Site')</title>
</head>
<body>
    @yield('container','Content area')

    {{ HTML::script('assets/js/jquery-1.9.0.js') }}

</body>
</html>

I extended it for another view index.blade.php
@extend('main')

I want to add javascript links to master layout(main.blade.php) if exists in child layout(index.blade.php)
added code in index.blade.php
$extraJs = array('plugins1.js','plugins2.js');

@section('extraJs')
{{ $extraJs }}
@stop

So, How can I add javascript to master layout if exists in child blade?
In php:
<?php
if(isset($extraJs)):
foreach($extraJs as $js):
?>
<script src="assets/js/<?php echo $js ?>" type="text/javascript" />
<?php endforeach; endif; ?>

A: You can just add a yield in your main.blade.php, like this:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>@yield('title','My Site')</title>
</head>
<body>
    @yield('container','Content area')

    {{ HTML::script('assets/js/jquery-1.9.0.js') }}

    @yield('javascripts')
</body>
</html>

Then, in your child layout, you add a section for it, like you did. For example:
@section('javascripts')
    @foreach($scripts as $script)
        {{ HTML::script('ets/js/' . $script) }}
    @endforeach
@stop

If you add another child view which doesn't need to use extra javascripts, Laravel won't complain because the section is optional.

A: I wouldn't really encourage this method but since you asked. It is definitely possible to pass something "up" in the view tree. You can just define a PHP variable in your view and it will be available anywhere in the layout.
index.blade.php
<?php $extraJs = array('plugins1.js','plugins2.js'); ?>

main.blade.php
@if(isset($extraJs))
    @foreach($extraJs as $js)
        <script src="{{ asset('assets/js/'.$js) }}" type="text/javascript" />
    @endforeach
@endif

As you can see I also converted your code in the layout to blade and made use of the asset() function to generate absolute URLs
Note Instead of doing it this way there are other methods. For example View composers or defining the plugins in the controller.


text:
Q: Logarithmic equations [Solve for x] The number of solutions of the equation $$3x^{\log(2)/\log(5)} + 2^{\log(x)/\log(5)} = 64$$

A: If $a=x^{\frac{\log2}{\log5}}$, then
\begin{align}
\log a&=\left(\frac{\log 2}{\log 5}\right)\log x\\
\end{align}
If $b=2^{\frac{\log x}{\log5}}$, then
\begin{align}
\log b&=\left(\frac{\log x}{\log 5}\right)\log 2\\
&=\log a
\end{align}
Hence $a=b$.
The equation can be written as
\begin{align}
3a+a&=64\\
a&=16\\
\log a&=\log 16\\
\log x&=\frac{\log 16\log 5}{\log 2}\\
&=4\log 5\\
x&=625
\end{align}

A: Hint: Use the fact that:

$$x^{\log_5 2} = 2^{\log_5 x}$$

A: simplifying your equation we obtain
$$2^{\frac{\log (x)}{\log (5)}}-16=0$$ from here we get
$$\log(x)=\log(625)$$ thus $$x=625$$


text:
Q: Pass two dimensional array in function I am trying to pass two dimensional array in function, but is has two errors which I don't know why. I have some articles about passing two dimensional array in function but also can't understand why I fail.
#include <iostream>

using namespace std;

// prototypes
void matrixSwap(double** matrix, int rows, int columns);

int main()
{
    const int ROWS = 5;
    const int COLUMNS = 5;

    double matrix[ROWS][COLUMNS] =
    {
      { 1,  2,  3,  4,  5},
      { 6,  7,  8,  9,  0},
      {11, 12, 13, 14, 15},
      {16, 17, 18, 19, 20},
      {21, 22, 23, 24, 25}
    };

    matrixSwap(matrix, ROWS, COLUMNS);
    /* it says
       1) argument of type "double (*)[5U]" is incompatible with parameter of type "double **"
       2) 'void matrixSwap(double *[],int,int)': cannot convert argument 1 from 'double [5][5]' to 'double *[]'
    */
}

void matrixSwap(double** matrix, int rows, int columns) {}

A: The multidimensional double array matrix you're trying to pass in the function matrixSwap() to the argument double**, actually doesn't represents a multidimensional array.
Use arrays correctly as shown:
#include <iostream>

using namespace std;

const unsigned short MAXROWS = 5;

// prototypes
void matrixSwap(double matrix[][MAXROWS], int rows, int columns);

int main()
{
    const int ROWS = 5;
    const int COLUMNS = 5;

    double matrix[ROWS][COLUMNS] =
    {
      { 1,  2,  3,  4,  5},
      { 6,  7,  8,  9,  0},
      {11, 12, 13, 14, 15},
      {16, 17, 18, 19, 20},
      {21, 22, 23, 24, 25}
    };

    matrixSwap(matrix, ROWS, COLUMNS);
}

void matrixSwap(double matrix[][MAXROWS], int rows, int columns) {}

Just changed into [][MAXROWS] where MAXROWS contains an unsigned integer of value 5.

The declaration:
void matrixSwap(double matrix[][MAXROWS], int rows, int columns)

is equivalent to:
void matrixSwap(double (*matrix)[MAXROWS], int rows, int columns)

Notice that here I've used *matrix and then appended [MAXROWS] which does the same job as matrix[][MAXROWS].
So you may do the same thing in another way as follows:
void matrixSwap(double (*matrix)[MAXROWS], int rows, int columns) {
    for (int i = 0; i < columns; i++) {
        for (int j = 0; j < rows; j++) {
            std::cout << matrix[i][j] << ' ';
        }
        std::cout << std::endl;
    }
}

This will give you the output:
1 2 3 4 5
6 7 8 9 0
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25

To see if the matrix is successfully passed into the function by the new argument.


text:
Q: Node.js keeps a copy of a global variable inside local scope I have a Node.js application that uses the request library to GET a number of URLs. The code is something like this:
for(var i = 0; i < docs.length; i++){

        var URL = docs[i].url;

        request(URL, function(error, response, html){
            console.log(URL);
            // Other code...
}

For the sake of simplicity, let's say docs contain URLs like [URL1, URL2, URL3, ...]. With the first iteration, URL = URL1 and a request is sent to that URL. With the second iteration, a request is sent to URL2 and so on. However, at the end of the loop, URL = URLn. Inside the event complete function, when I log URL, I always get URLn. However, I need to able to get the respective URLs that is [URL1, URL2, URL3, ...].
Any idea, how I can maintain a local copy of the URL, that remains unchanged event when the global URL gets changed?
This must be something easy, but I can't figure it out.

A: Basically, what you experience is normal behavior in JavaScript and no special behavior of Node.js.
The only thing in JavaScript that defines a scope are functions, and functions can access their own scope as well as any "outer" scopes.
Hence, the solution is to wrap your code in a function that takes the global variable as a parameter and provides it to the code within the function as a parameter: This one is evaluated for each call of the function, hence your inner code will get its own "copy".
Basically you have two options. Either use an immediate executed function expression. This is basically nothing but a name-less (i.e. anonymous) function that is called immediately where it is defined:
for(var i = 0; i < docs.length; i++){
  (function (url) {
    request(url, function(error, response, html){
      console.log(url);
    });
  })(doc.url);
}

Or use the built-in forEach function of an array which automatically wraps its body in a function (which results in the same effect):
docs.forEach(function (url) {
  request(url, function(error, response, html){
    console.log(url);
  });
});

A: You should read about closures in JavaScript here.
Meanwhile, in simpler terms, the value of i would reach n at the end of all iterations. Hence rightly you would get URLn every time. If you wrap the request inside a immediately invoked function expression, you are creating another level in the scope chain. By doing so, the callback to request method won't refer to the variable i in global scope, but to the variable i that was available in the scope of the function at the time of sending the request. And that value of i you expect.
Code would be something like this then:
for(var i = 0; i < docs.length; i++){
    var URL = docs[i].url;

    (function(currentURL) {
        //now the URL is preserved as currentURL inside the scope of the function
        request(currentURL, function(error, response, html){
            console.log(currentURL);
            // This value of currentURL is the one that was available in the scope chain
            // Other code...
        });
    })(URL);
}

A: Just wrap the code in a function or use forEach. This happens because of closure scope.
docs.forEach(functiom(doc) {
    var URL = doc.url;

    request(URL, function(error, response, html){
         console.log(URL);
         // Other code...
    })
});

Another fix
for(var i = 0; i < docs.length; i++){
    makeRequest(docs[i]);
}

function makeRequest(doc) {
    var URL = doc.url;

    request(URL, function(error, response, html){
        console.log(URL);
    });
}

And another a bit more uglier fix with a closure inside the for loop
for(var i = 0; i < docs.length; i++){
    (function(doc) {
        var URL = doc.url;

        request(URL, function(error, response, html){
            console.log(URL);
            // Other code...
        });
    })(docs[i]);
}

If you use something like JSHint, it will warn you not to create functions inside for loops as it will cause problems like this.

A: Just use let instead of var, i.e.:
for(let i = 0; i < docs.length; i++){

        let URL = docs[i].url;

        request(URL, function(error, response, html){
            console.log(URL);
            //other code...
}


text:
Q: Unable to load Eclipse runtime jar using Maven in IntelliJ I am experiencing following exception while downloading Eclipse run time jar from Maven.
https://mvnrepository.com/artifact/org.eclipse.core/runtime/3.10.0-v20140318-2214
My Maven entry is:
<dependency>
                <groupId>org.eclipse.core</groupId>
                <artifactId>runtime</artifactId>
                <version>3.10.0-v20140318-2214</version>
            </dependency>

Failed to read artifact descriptor for
  org.eclipse.core:runtime:jar:3.10.0-v20140318-2214 less... (Ctrl+F1)
  Inspects a Maven model for resolution problems.

How do I resolve this in IntelliJ?

A: posting answer to those if anyone face the same problem and tried to resolve it. All I have to do is build ($mvn clean install) the project and re-import it again in intellij.


text:
Q: comparing Gregorian calendar date values I am trying to set up part of a program that allows a person to view transactions of an account based on the date of the transaction. The user enters the month day and year to view transactions and that is compared to the date that is connected to a given transaction. I am having difficult writing the lines of code that determine if the date is equal
if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.MONTH).compareTo(month)==0){
                        if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.DAY_OF_MONTH).compareTo(day)==0){
                            if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.YEAR).compareTo(year)==0){

The error that I am receiving is "cannot invoke compareTo(int) on the primitive type int"
see full code below:
System.out.println("Enter the account number of the account that you want to view transactions for");
            number=keyboard.nextLong();
            System.out.println("Enter the month day and year of the date that the transactions were completed");
            int month=keyboard.nextInt()-1;
            int day=keyboard.nextInt();
            int year=keyboard.nextInt();
            found=false;
            try{
            for(int i=0;i<aBank.getAccounts().size();i++){
                if (aBank.getAccounts().get(i).getAccountNumber().compareTo(number)==0){
                    found=true;
                    System.out.println("Below is a list of transactions completed on "+month+ "/" +day+ "/" +year);
                    for (int j=0;j<aBank.getAccounts().get(i).getTransaction().size();j++){
                    if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.MONTH).compareTo(month)==0){
                        if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.DAY_OF_MONTH).compareTo(day)==0){
                            if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.YEAR).compareTo(year)==0){
                                aBank.getAccounts().get(i).getTransaction().get(j).toString();
                                break;
                            }
                        }

                    }

                }

A: For primitive values you can just use ==
aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.YEAR)==year

A: Just use:
aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.MONTH) == month

A: If all of the XYZ.getTransDate() returns Calendar, then
XYZ.getTransDate().get(SOMETHING) returns  primitive int. Primitives do not have comapreTo method, just use ==
so instead of XYZ.getTransDate().get(MONTH).compareTo(month) == 0 use
XYZ.getTransDate().get(MONTH) == month

A: This should work:
Calendar transDate = aBank.getAccounts().get(i).getTransaction().get(j).getTransDate();
if (transDate.get(Calendar.YEAR) == year &&
    transDate.get(Calendar.MONTH) == month &&
    transDate.get(Calendar.DAY_OF_MONTH) == day) {

    // do something
}

Even better if you use something like Apache Commons Lang:
if (DateUtils.isSameDay(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate(),
                        Calendar.getInstance().set(year, month, day)) {
    ...
}


text:
Q: How can I use setAttribute on an input without an ID or class attribute? I have a search input tag that is being added by a jQuery plug-in:
<input type="search" />

Note that this does not have an ID, CLASS, or NAME. I need the search input tag to look like this:
<input type="search" name="myname" />

A simple solution is for me to update the jQuery plug-in. However, I do not want to do this as it will cause challenges when I upgrade this plug-in in the future.
This JavaScript works properly and adds the name attribute:
$(document).ready(function() {
   document.getElementsByTagName("input")[0].setAttribute("name", "myname");
});

The problem is that the "[0]" in this function relies on the search input being the first input field in the form. I do not think this solution is sustainable.
There are other inputs in the form. This is the only one with the type attribute equal to "search." Is there a way to identify it by this attribute? Or, is there another solution you propose?
Thank you for your time!

A: You can use the document.querySelector:
document.querySelector("input[type='search']")

Below is an example (you can inspect the output to see name attribute):

document.querySelector("input[type=search]").setAttribute("name", "myname");
<input type="search" value="foo" />
<input type="bar" value="bar" />

A: You can target a selection by anything. So, the selector input[type="search"]' will work.
If you want to apply this to all input's of type search, this is good enough, and you get all of them in here:
$('input[type="search"]')

This works without jQuery too:
document.querySelectorAll('input[type="search"]')

A more targeted approach would be
document.querySelectorAll('div.filter input[type="search"]')


text:
Q: fork()ing - Idle Children So I need to iterate fork() several times, creating child processes. The child processes are supposed to "do little or not processing" for example;
while(1)
 sleep(1)

The parent is then supposed to gather the PID's of the children and kill them (harsh, I know!).
However they way I'm doing it at the minute executes the code in the "parent" block several times, but I only need it to execute once.

A: Here is an example; you need to store the pids in a table (here p[]).
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

#define NSUB 10

int main ()
{
    int i, n = NSUB, p[NSUB], q;

    for (i = 0; i < n; i++) {
        printf ("Creating subprocess %d ...\n", i);
        p[i] = fork();
        if (p[i] < 0) { perror ("fork"); exit (1); }

        if (p[i] == 0) {  /* subprocess */
            printf ("Subprocess %d : PID %d\n", i, (int) getpid());
            while (1) pause ();
            exit (0);
        }
    }

    sleep(2);
    for (i = 0; i < n; i++) {
        printf ("Killing subprocess %d ...\n", i);
        if (kill (p[i], SIGTERM) < 0) perror ("kill");
    }

    for (i = 0; i < n; i++) {
        printf ("waiting for a subprocess ...\n");
        q = wait (NULL);
        printf ("Subprocess terminated: PID %d\n", q);
    }

    exit (0);
}


text:
Q: How to limit the number of uses of a command (Discord.js) I recently had to create a command to add a role to register for an event, however I would need to be able, using another command, to limit the number of uses of the first command.
Example: If I write !limit-inscriptions 20, I want the !inscrit command to be used only 20 times.
The problem being that I'm a beginner and I have no idea how to do the !limit-inscriptions command. So I'm calling you if you have any ideas on how to do it. Here is my (functional) code of the !inscrit command:
 if(message.content === '!inscrit') {
        message.delete();
        let role = message.guild.roles.find(r => r.name === "Inscrit");

        if (message.member.roles.find(r => r.name === "Inscrit")) {
            message.member.removeRole(role)
            message.reply('vient de se désinscrire!')
        }
        else {
            message.member.addRole(role)
            message.reply(`vient de s'inscrire!`)
        }
    }

A: it's a good idea but I would like to host the bot on Heroku so I can't really, here is the beginning of the modification of the code of the command !inscrit, unfortunately this one doesn't work (I first wanted to put the limit from the command !inscrit then I would do it with the command !limit-inscriptions) :
var participants = 1;
var nbInscrit = 0;
if (message.content === '!inscrit') {
     message.delete();
     let role = message.guild.roles.find(r => r.name === "Inscrit");

     if (nbInscrit < participants) {

       if (message.member.roles.find(r => r.name === "Inscrit")) {
         message.member.removeRole(role)
         nbInscrit = nbInscrit - 1
         message.reply('vient de se désinscrire!')
       }
       else {
         message.member.addRole(role)
         nbInscrit = nbInscrit + 1
         message.reply("vient de s'inscrire!")
       }
     } else {
       message.channel.send('Le nombre Maximal de Participants est déjà atteint!');
     }
   }


text:
Q: Lock project in Visual Source Safe as ReadOnly We are currently migrating our projects to TFS over a period of around 6 months.
We are not migrating history, instead we are just unbinding the projects from Source Safe and then adding them to TFS.
Is it possible to somehow lock the projects in Source Safe so that no one can accidentally checkout a project in Source Safe rather than TFS?

A: if some projects must remain in ss (is there a good reason why you shouldn't just switch to tfs? Especially as you can migrate the entire DB including the history in one easy go?) then some options might be:

*

*individual users can get properties on folders in ss and Cloak the folder so ss effectively ignores it.

*you could set exclusive check-outs and get one user (possibly a new user for this purpose) to check out any files that you have migrated.

*simply delete migrated files in ss. The history is still there and they are being developed in tfs, so why keep them live in ss at all?


text:
Q: How to determine, in a service worker, which HTML5 page orginated the fetch request? Is there a mechanism in a service worker, which I am unaware, which can allow me to know from which page a fetch request is fired from?
Example:
I have an HTML page uploaded to my website at /aPageUploadedByUser/onMySite/index.html, I do want to make sure none of the authorization headers gets passed to any fetch request made by /aPageUploadedByUser/onMySite/index.html to any source.
If my service worker does somehow know the originating page of this request, I can modulate them for safety.

A: To answer your question (but with a caveat that this is not a good idea!), there are two general approaches, each with their own drawbacks:

*

*The Referer: request header is traditionally set to the URL of the web page that made a request. However, this header may not always be set for all types of requests.

*A FetchEvent has a clientId property, and that value can be passed to clients.get() to obtain a reference to the Client that created the request. The Client, in turn, has a url property. The caveats here are that clients.get() is asynchronous (meaning you can't use its result to determine whether or not to call event.respondWith()), and that the URL of the Client may have changed in the interval between the request being made and when you read the url property.
With those approaches outlined, the bigger problem is that using a service worker in this way is not a safe practice. The first time a user visits your origin, they won't have a service worker installed. And then on follow-up visits, if a user "hard" reloads the page with the shift key, the page won't be controlled by a service worker either. You can't rely on a service worker's fetch event handler to implement any sort of critical validation.


text:
Q: How to manage multiple menus for voice and touch input in Android / Google Glass I'm developing a Google Glass app that displays n cards to the user, each with its custom menu.
The user should be able to access the menu through Voice ('Ok Glass') and Touch ('Tap'). The following example deals only with two cards (and two menus):
public class JobActivity extends Activity {
    // Manages CardScrollView and CardScrollAdapter
    private CardHolder mCardHolder;

    private Menu mCustomMenu;
    private GestureDetector mGestureDetector;

    @Override
    protected void onCreate(Bundle bundle)
    {
        super.onCreate(bundle);
        mCardHolder = new CardHolder(this);

        getWindow().requestFeature(WindowUtils.FEATURE_VOICE_COMMANDS);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(mCardHolder.getView());
    }
    mGestureDetector = createGestureDetector(this);
}

private GestureDetector createGestureDetector(Context context) {
    GestureDetector gestureDetector = new GestureDetector(context);

    gestureDetector.setBaseListener(new GestureDetector.BaseListener() {
        @Override
        public boolean onGesture(Gesture gesture) {
            if (gesture == Gesture.TAP) {
                openOptionsMenu();
                return true;
            } else if (gesture == Gesture.SWIPE_RIGHT) {
                if (mCardHolder.getCurrentCardPos() == 0) {
                    // Moves to the next card automatically
                    updateOptionsMenu(getCardTwoMenuItems());
                }
                return true;
            } else if (gesture == Gesture.SWIPE_LEFT) {
                if (mCardHolder.getCurrentCardPos() == 1) {
                    // Moves to the previous card automatically
                    updateOptionsMenu(getCardOneMenuItems());
                }
                return true;
            }
            return false;
        }
    });
    return gestureDetector;
}

@Override
public boolean onGenericMotionEvent(MotionEvent event) {
    if (mGestureDetector != null) return mGestureDetector.onMotionEvent(event);
    return false;
}

@Override
protected void onResume() {
    super.onResume();
    mCardHolder.activate();
}

@Override
protected void onPause() {
    mCardHolder.deactivate(); }
    super.onPause();
}

@Override
public boolean onCreatePanelMenu(int featId, Menu menu) {
    if (featId == WindowUtils.FEATURE_VOICE_COMMANDS || featId == Window.FEATURE_OPTIONS_PANEL) {
        List<String> itemList = getCardOneMenuItems();
        mCustomMenu = menu;

        for (int i = 0; i < itemList.size(); i++)
            mCustomMenu.add(Menu.NONE, i, Menu.NONE, itemList.get(i));

        super.onCreatePanelMenu(featId, mCustomMenu);
        return true;
    }
    return false;
}

private void updateOptionsMenu(List<String> itemList) {
    if (mCustomMenu != null) mCustomMenu.clear();

    for (int i = 0; i < itemList.size(); i++)
        mCustomMenu.add(Menu.NONE, i, Menu.NONE, itemList.get(i));

    if (mCustomMenu != null) onPrepareOptionsMenu(mCustomMenu);
}

@Override
public boolean onMenuItemSelected(int featId, MenuItem menuItem) {
    if (featId == WindowUtils.FEATURE_VOICE_COMMANDS || featId == Window.FEATURE_OPTIONS_PANEL) {

        if (mCardHolder.getCurrentCardPos() == 0) {
            // An item was selected from the menu in the first card

            if (menuItem.getItemId() == 0) {
                // User selected 'Goto the next card'
                updateOptionsMenu(getCardTwoMenuItems());
                mCardHolder.next();     // Moves to the next card
            } else if (menuItem.getItemId() == 1) doSomething();
            else if (menuItem.getItemId() == 2) doSomethingElse();

        } else if (mCardHolder.getCurrentCardPos() == 1) {
            // An item was selected from the menu in the second card

            if (menuItem.getItemId() == 0) {
                updateOptionsMenu(getCardOneMenuItems());
                mCardHolder.previous(); // Moves to the previous card
            } else if (menuItem.getItemId() == 1) doSomethingMore();
        }
        return true;
    }
    return super.onMenuItemSelected(featId, menuItem);
}

private List<String> getCardTwoMenuItems() {
    List<String> cardTwoMenuItems = new ArrayList<>();
    cardTwoMenuItems.add(getResources().getString(R.string.card_previous));
    cardTwoMenuItems.add(getResources().getString(R.string.something_more));
    return cardTwoMenuItems;
}

private List<String> getCardOneMenuItems() {
    List<String> cardOneMenuItems = new ArrayList<>();
    cardOneMenuItems.add(getResources().getString(R.string.card_next));
    cardOneMenuItems.add(getResources().getString(R.string.something));
    cardOneMenuItems.add(getResources().getString(R.string.something_else));
    return cardOneMenuItems;
}

The code above works in several situations:

*

*If I say 'Ok Glass' and 'Go to the next card'. Saying 'Ok Glass', now in the second card, brings up the correct menu.

*If I tap and select 'Go to the next card'. Tapping again, now in the second card, brings up the correct menu.

*If I swipe right. Saying 'Ok Glass', now in the second card, brings up the correct menu.
However, the code does not work in the following situations:

*

*If I say 'Ok Glass' and 'Go to the next card'. If I tap, now in the second card, it brings up the incorrect menu (the one from the first card).

*If I swipe right. If I tap, now in the second card, it brings up the incorrect menu (the one from the first card).

*If I tap and select 'Go to the next card'. Saying 'Ok Glass', now in the second card, brings up the incorrect menu (the one from the first card).

A: The solution is in the onPrepareOptionsMenu
public boolean onPrepareOptionsMenu (Menu menu){

    for (int i = 0; i < mJobMenu.size(); i++)
        menu.add(Menu.NONE, i, Menu.NONE, mJobMenu.getItem(i));

}

The onPrepareOptionsMenu is called by the system and the menu items are added to the menu that is passed to it. This happens every time the menu is called (whether by tap or glass). Hence, if you override this method you should  be able to insert values in the menu


text:
Q: Displaying a card on top of a clip-path shape I'm looking to design a website kind of like the duckduckgo's website with a rounded background and cards laying on top of the curve:

But what I have right now looks something like this where the clip-path cuts off the cards:

The code looks something like this with the css of the section :

 .two {
        background-color: #ff6b6c;
        clip-path: ellipse(99% 66% at 48% 77%);
    }
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

                        Featured

Cras justo odio

Dapibus ac facilisis in

Vestibulum at eros

                        Featured

Cras justo odio

Dapibus ac facilisis in

Vestibulum at eros

How can I fix it?

A: I advice you to use background elements as pseudo (::before) elements. If you convert it to a pseudo element it will render in the background.

 .two {
        position: relative;
 }

 .two::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: #ff6b6c;
        clip-path: ellipse(99% 66% at 48% 77%);
    }
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

                        Featured

Cras justo odio

Dapibus ac facilisis in

Vestibulum at eros

                        Featured

Cras justo odio

Dapibus ac facilisis in

Vestibulum at eros

A: I think this is what you are expecting.
.two {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        background-color: #ff6b6c;
        clip-path: ellipse(99% 66% at 48% 77%);
    }

                    Featured

Cras justo odio

Dapibus ac facilisis in

Vestibulum at eros

                    Featured

Cras justo odio

Dapibus ac facilisis in

Vestibulum at eros


text:
Q: Probability of at least two people choosing the same menu
A group of $n>4$ people gathers for a feast. Each
  person brings $n$ dishes of his/her own unique stew. Then, each person
  forms his/her own menu by choosing 4 distinct dishes (of different
  stews), randomly and independently of any of the other people. What is the probability that at least two people chose the
  exact same menu?

What I got so far is since the probability for a person to choose a specific menu is $p=\frac{1}{n \choose 4}$, if $X$ is the random variable of the number of people choosing "that" menu, then $\Pr(X\geq 2)=\sum_{k=2}^{n} {n \choose k}p^k(1-p)^{n-k}\\$, but even after simplyfing this expression it doesn't resemble any of the answers (it's a multiple choice).
So I could really use some guidance here.

A: There are $N=\binom n4$ possible possibilities for a menu, and there are enough dishes of each type so that
the persons are free to choose. So the problem can be restated, and let us better ask for the complementary probability:

$n$ persons choose in the same time, independently one of $N$ menus, that exist in overflow. Which is the probability for $n$ different choices?

The answer is
$$
\frac1{N^n}\cdot (N-0)(N-1)\dots(N-(n-1))
=
\left(1-\frac 1N\right)
\left(1-\frac 2N\right)
\dots
\left(1-\frac {n-1}N\right)
\ .
$$
The complement is the answer to the OP
$$
1-\left(1-\frac 1N\right)
\left(1-\frac 2N\right)
\dots
\left(1-\frac {n-1}N\right)\ ,\qquad
N = \binom n4=\frac 1{24}n(n-1)(n-2)(n-3)
\ .
$$


text:
Q: browser.tabs undefined in Microsoft Edge extension I am writing a Microsoft Edge extension.
I have the following manifest file:
{
  "author": "",
  "description": "Test",
  "name": "Test",
  "version": "1.0",
    "permissions": [
        "tabs",
        "<all_urls>"
    ],
  "content_scripts": [{
    "js": ["script.js"],
    "matches": ["*://*/*"]
  }],
  "icons": {
    "48": "icons/icon-40x40.png"
  }
}

When i put into my script.js:
var currentTab = browser.tabs.getCurrent();
alert(currentTab.index);

It fails because browser.tabs is undefined?
Why?

A: This is not possible from content script as it has limitations.
browser.tabs API can only be used/available in background script and Browser action popup scripts. To achieve your intended functionality you can send a message to background script and in the background script you can utilize the browser.tabs API.

A: You can call this function browser.tabs.getCurrent() in contexts where there is a browser tab, such as an options page. If you call it from a background script or a popup, it will return undefined.But as I see you have used this function in content script, so it shouldn't be a problem.
This is an asynchronous function that returns a Promise.
You can check this site for further information on how to use the function for Edge Extension.
Also you shouldn't leave the author field empty, it may give some error . So try writing you name in it.


text:
Q: How can I add a search function to a treeview? I want to display a row that matches the entry from all of my entry boxes into the treeview.  How can I get the values of the treeview and check if it matches the entry from one of the boxes and display the whole row. Here is my treeview code
tree = ttk.Treeview()
                books_data = pandas.read_csv("List of Books - Sheet1 (3).csv")
                df_column = books_data.columns.values
                print(len(df_column))
                print(df_column)
                tree["column"] = list(books_data.columns)
                tree["show"] = "headings"

                for column in tree['column']:
                    tree.heading(column,text=column)

                df_rows = books_data.to_numpy().tolist()
                for row in df_rows:
                    tree.insert("","end",values=row)
                tree.grid(column=0,row=4,columnspan=8)

A: The short solution
import tkinter as tk
import tkinter.ttk as ttk
import sys
import pandas

# https://gist.githubusercontent.com/netj/8836201/raw/6f9306ad21398ea43cba4f7d537619d0e07d5ae3/iris.csv
df = pandas.read_csv('./iris.csv')
df.head()

class main_window:
    def __init__(self, root):
        self.root = root
        root.title("Treeview Search Example")

        # INITIALIZE TREEVIEW + SCROLLVIEW
        self.tree = ttk.Treeview(root, columns=list(df.columns.values), show='headings')
        self.tree.grid(row=1, column=0, sticky='nsew')

        # https://stackoverflow.com/a/41880534/5210078
        vsb = ttk.Scrollbar(root, orient="vertical", command=self.tree.yview)
        vsb.grid(row=1, column=1, sticky='ns')
        self.tree.configure(yscrollcommand=vsb.set)

        for column in self.tree['column']:
            self.tree.heading(column,text=column)

        df_rows = df.to_numpy().tolist()
        for row in df_rows:
            self.tree.insert("","end",values=row)

        # ADD SEARCH BOXES
        search_frame = tk.Frame(root)
        search_frame.grid(row=0, column=0, columnspan=2, sticky='nsew')
        tk.Label(search_frame, text="sepal.length:").grid(row=0, column=0)
        tk.Label(search_frame, text="sepal.width:").grid(row=0, column=2)
        tk.Label(search_frame, text="petal.length:").grid(row=0, column=4)
        tk.Label(search_frame, text="petal.width:").grid(row=0, column=6)
        tk.Label(search_frame, text="variety:").grid(row=0, column=8)

        # Add Search boxes
        self.sepal_length_ent = tk.Entry(search_frame)
        self.sepal_length_ent.grid(row=0, column=1)
        self.sepal_width_ent = tk.Entry(search_frame)
        self.sepal_width_ent.grid(row=0, column=3)
        self.petal_length_ent = tk.Entry(search_frame)
        self.petal_length_ent.grid(row=0, column=5)
        self.petal_width_ent = tk.Entry(search_frame)
        self.petal_width_ent.grid(row=0, column=7)
        self.variety_ent = tk.Entry(search_frame)
        self.variety_ent.grid(row=0, column=9)

        tk.Button(search_frame, text="Search", command=self.search).grid(row=0, column=10)

    def search(self):
        # https://stackoverflow.com/a/27068344/5210078
        self.tree.delete(*self.tree.get_children())
        build_query = ""
        # https://stackoverflow.com/a/56157729/5210078
        if self.sepal_length_ent.get():
            build_query += f'& {self.sepal_length_ent.get()} == `sepal.length` '
        if self.sepal_width_ent.get():
            build_query += f'& {self.sepal_width_ent.get()} == `sepal.width` '
        if self.petal_length_ent.get():
            build_query += f'& {self.petal_length_ent.get()} == `petal.length` '
        if self.petal_width_ent.get():
            build_query += f'& {self.petal_width_ent.get()} == `petal.width` '
        if self.variety_ent.get():
            build_query += f'& "{self.variety_ent.get()}" in `variety`'
        if build_query:
            print(build_query)
            queried_df = df.query(build_query[1:])
        else:
            queried_df = df

        df_rows = queried_df.to_numpy().tolist()
        for row in df_rows:
            self.tree.insert("","end",values=row)

if __name__ == '__main__':
    main = tk.Tk()
    main_window(main)
    main.mainloop()
    sys.exit()

The explanation of the solution
import tkinter as tk
import tkinter.ttk as ttk
import sys
import pandas

Obviously importing all the needed programs.
# https://gist.githubusercontent.com/netj/8836201/raw/6f9306ad21398ea43cba4f7d537619d0e07d5ae3/iris.csv
df = pandas.read_csv('./iris.csv')
df.head()

Loading the csv dataset. I used the IRIS dataset because it is easily accessible.
Jump ahead to:
if __name__ == '__main__':
    main = tk.Tk()
    main_window(main)
    main.mainloop()
    sys.exit()

Here we load the main_window class into our main tkinter window (makes your code look neater)
The self-explanatory bit (added a ttk treeview with scrollbar):
class main_window:
    def __init__(self, root):
        self.root = root
        root.title("Treeview Search Example")

        # INITIALIZE TREEVIEW + SCROLLVIEW
        self.tree = ttk.Treeview(root, columns=list(df.columns.values), show='headings')
        self.tree.grid(row=1, column=0, sticky='nsew')

        # https://stackoverflow.com/a/41880534/5210078
        vsb = ttk.Scrollbar(root, orient="vertical", command=self.tree.yview)
        vsb.grid(row=1, column=1, sticky='ns')
        self.tree.configure(yscrollcommand=vsb.set)

        for column in self.tree['column']:
            self.tree.heading(column,text=column)

        df_rows = df.to_numpy().tolist()
        for row in df_rows:
            self.tree.insert("","end",values=row)

        # ADD SEARCH BOXES
        search_frame = tk.Frame(root)
        search_frame.grid(row=0, column=0, columnspan=2, sticky='nsew')
        tk.Label(search_frame, text="sepal.length:").grid(row=0, column=0)
        tk.Label(search_frame, text="sepal.width:").grid(row=0, column=2)
        tk.Label(search_frame, text="petal.length:").grid(row=0, column=4)
        tk.Label(search_frame, text="petal.width:").grid(row=0, column=6)
        tk.Label(search_frame, text="variety:").grid(row=0, column=8)

        # Add Search boxes
        self.sepal_length_ent = tk.Entry(search_frame)
        self.sepal_length_ent.grid(row=0, column=1)
        self.sepal_width_ent = tk.Entry(search_frame)
        self.sepal_width_ent.grid(row=0, column=3)
        self.petal_length_ent = tk.Entry(search_frame)
        self.petal_length_ent.grid(row=0, column=5)
        self.petal_width_ent = tk.Entry(search_frame)
        self.petal_width_ent.grid(row=0, column=7)
        self.variety_ent = tk.Entry(search_frame)
        self.variety_ent.grid(row=0, column=9)

        tk.Button(search_frame, text="Search", command=self.search).grid(row=0, column=10)

    def search(self):
        # https://stackoverflow.com/a/27068344/5210078
        self.tree.delete(*self.tree.get_children())

Delete all the rows in the table
        build_query = ""
        # https://stackoverflow.com/a/56157729/5210078
        if self.sepal_length_ent.get():
            build_query += f'& {self.sepal_length_ent.get()} == `sepal.length` '
        if self.sepal_width_ent.get():
            build_query += f'& {self.sepal_width_ent.get()} == `sepal.width` '
        if self.petal_length_ent.get():
            build_query += f'& {self.petal_length_ent.get()} == `petal.length` '
        if self.petal_width_ent.get():
            build_query += f'& {self.petal_width_ent.get()} == `petal.width` '
        if self.variety_ent.get():
            build_query += f'& "{self.variety_ent.get()}" in `variety`'

Build a search query. Use == for integers/floats and use in when searching inside strings. If you want to read more about queries, read this. If you wanted to do something wacky, like make one of your entries a "lower than" box for integers, you could even substitute in a < or >. It basically makes our life much easier here! Because we can do a query, based off a dynamically changing string!
        if build_query:
            print(build_query)
            queried_df = df.query(build_query[1:])
        else:
            queried_df = df

If there is no build_query (no inputs in entry boxes), just reload the table with the data from the df. (if build_query: is shorthand for if build_query != '':)
If there is query data, do a query with the query terms.
        df_rows = queried_df.to_numpy().tolist()
        for row in df_rows:
            self.tree.insert("","end",values=row)

Reload the treeview with the data from the "new" queried df!
If you wanted a solution relate to your actual csv and interface, I'd recommend sharing an example of your csv and the gui design.
What the solution became
         def search():
                    # clear the tree of data
                    tree.delete(*tree.get_children())
                    entries = [
                    title_entry,
                    author_entry,
                    subject_category_entry,
                    publication_date_entry
                    ]
                    build_df = books_data
                    if entries[0].get():
                        build_df = build_df[build_df.TITLE.str.contains(entries[0].get())]
                    if entries[1].get():
                        build_df = build_df[build_df.AUTHOR.str.contains(entries[1].get())]
                    if entries[2].get():
                        build_df = build_df[build_df.SUBJECT_CATEGORY.str.contains(entries[2].get())]
                    if entries[3].get():
                        build_df = build_df[build_df.PUBLICATION_DATE == (entries[3].get())]

                    df_rows = build_df.to_numpy().tolist()
                    for row in df_rows:
                        tree.insert("","end",values=row)


text:
Q: How we can write data to a postgres DB table using R? I need to write data to a postgres DB table using R. If a data  exist for an ID in the table, data should be updated otherwise new data should append to the table.

I tried this using 'RPostgreSQL' Package I got this error message
dbWriteTable(con, 'credit', credit,overwrite=TRUE,row.names=FALSE,append=TRUE)<br>

Error in postgresqlWriteTable(conn, name, value, ...) :overwrite and append cannot both be TRUE

A: You cannot use overwrite and append at once. If use overwrite command as follows, it will truncate the table and rewrite the data.
dbWriteTable(con, 'credit', credit,overwrite=TRUE,row.names=FALSE)

If use append it will Add the rows. But it won't update your results.
dbWriteTable(con, 'credit', credit,row.names=FALSE,append=TRUE)


text:
Q: Read .h5 file in matlab without knowing dataset name I have a .h5 file which I can read in python as pandas.read_pickle('X.h5','r'). Now I want to load this in MATLAB-2014a and I don't know dataset name.
I tried to get info but got error
info=h5info('X.h5');

Error using h5infoc
The HDF5 library encountered an error and produced the following stack trace
information:

H5F_locate_signature    unable to find a valid file signature
H5F_super_read          unable to find file signature
H5F_open                unable to read superblock
H5Fopen                 unable to open file

Can someone help in this regard.

A:
To get a quick view into the contents of an HDF5 file, use the h5disp function.

h5disp('X.h5')

You can find more about the data set using this function.
See more from documentation.


text:
Q: Generate JQuery code inside a PHP foreach loop UPDATE
for JLRiche
html structure below (here is the structure for the entire div id=content_body_right):

Tim Flanagan

02-06-2013 @ 12:00PM

Playin Augusta today. What a beautiful course!

12 Tips of the Cap

                    4 Comments
                    see all
                    collapse

Tim Flanagan

02-06-2013 @ 12:00PM

Nice jealous of you bro.

Tim Flanagan

02-06-2013 @ 12:00PM

Nice jealous of you bro.

Tim Flanagan

02-06-2013 @ 12:00PM

Nice jealous of you bro.

Tim Flanagan

02-06-2013 @ 12:00PM

Nice jealous of you bro.

Let me know if you need more structure, because there is alot above and below it. Hope this helps.
I really appreciate your help!
END UPDATE
Good Evening All,
I need to dynamically create X amount of jquery scripts foreach of the X amount of db results. X meaning the the number will vary. It is sort of a forum type thing where you see the original post with one reply showing and you would click see all or collapse all to view or collapse the rest. I am incrementing my html elements inside a foreach loop with the typical $i variable so I need to output jquery click functions for each as well.
The code I need PHP to create is below:
$jquery .= "$('#see_all$i').click(function () {
    $('#comment2_$i').slideDown('fast');
    $('#collapse$i').css('display', 'inline-block');
    $('#see_all$i').css('display', 'none');
    return false;
});

$('#collapse$i').click(function () {
    $('#comment2_$i').slideUp('fast');
    $('#collapse$i').css('display', 'none');
    $('#see_all$i').css('display', 'inline-block');
    return false;
})";

Any help would and always will be much appreciated!
Thanks

A: Generating multiple, slightly different copies of the same jQuery code is not a very good design, IMHO.  You should write your jQuery code in a way that it only needs to be in your page once, like:
$('.see_all').click(function(){
     var thisItem = $(this);
     thisItem.parent().find('.comment').slideDown('fast');
     thisItem.parent().find('.collapse').css('display','inline-block');
     thisItem.css('display','none');
     return false;
});

$('.collapse').click(function(){
     var thisItem = $(this);
     thisItem.parent().find('.comment').slideUp('fast');
     thisItem.css('display','none');
     thisItem.parent().find('.see_all').css('display','inline-block');
     return false;
})";

Of course, this would also involve adding collapse, see_all, and comment classes to the relevant HTML elements.

A: html :

...

...

...

...

js :
var $bdy=$(document.body)
$bdy.on("click",".seeall",function(e) {
      var el=$(this).css('display','none').data("elid");
      $('#comment2_'+el).slideDown('fast');
      $('.collapse[data-elid="'+el+'"]').css('display','inline-block');
     })
     .on("click",".collapse", function(e) {
               //same same
     });


text:
Q: Trying to scrape a page with one cookie I am trying to scrape the table from the URL. I have been using requests library for a while now, along with beautiful soup, but what I don't want to venture into is using a web driver, as I have been down that road before.
So I make a request with requests, and read the response. But I get the following in the header, and nothing else. Can someone explain to me what I need to do (spent all morning on it and beginning to lose the plot)?
<head>
  <meta charset="utf-8">
  <title>SoccerSTATS.com - cookie consent</title>
<style>
.button {

    background-color: #4CAF50; /* Green */
    border: none;
    color: white;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 18px;
    margin: 4px 2px;
    cursor: pointer;
}

.button1 {padding: 10px 24px;}
.button2 {padding: 12px 28px;}
.button3 {padding: 14px 40px;}
.button4 {padding: 32px 16px;}
.button5 {padding: 16px;}
</style>

<script type="text/javascript">
function setCookielocal(cname, cvalue, exdays) {

    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    var originpage = "/team.asp?league=england_2018&stats=20-bournemouth";
    document.cookie = cname + "=" + cvalue + "; " + expires;
    window.location = "//www.soccerstats.com" + originpage;
}
</script>
</head>

A:
The User-Agent request header contains a characteristic string that allows the network protocol peers to identify the application type, operating system, software vendor or software version of the requesting software user agent. Validating User-Agent header on server side is a common operation so be sure to use valid browser's User-Agent string to avoid getting blocked.

(Source: http://go-colly.org/articles/scraping_related_http_headers/)
The only thing you need to do is to set a legitimate user-agent. Therefore add headers to emulate a browser. :
# This is a standard user-agent of Chrome browser running on Windows 10
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
    }

Example:
from bs4 import BeautifulSoup
import requests

headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}
resp = requests.get('http://example.com', headers=headers).text
soup = BeautifulSoup(resp, 'html.parser')

Additionally, you can add another set of headers to pretend like a legitimate browser. Add some more headers like this:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language' : 'en-US,en;q=0.5',
'Accept-Encoding' : 'gzip',
'DNT' : '1', # Do Not Track Request Header
'Connection' : 'close'
}


text:
Q: I have two small samples of different populations. How do I test if the population variance (not mean) of one is smaller than the other? So, samples a and b; for simplicity's sake suppose that the sample variance of a is less than b, and my null hypothesis is that the population variance of A is not greater than that of B.
I am not concerned with the population means of A or B; they could be the same or they could differ. (However, in my application they should be very similar, so if I can only get a solution if I assume equal means, then that's better than nothing.)
The sample sizes are also very small (n = 5 currently). I can get more data, but the process is tedious, so n < 30 is a given. To further complicate matters, I can't guarantee that the sample sizes will be equal.
It's been a while since stats class, but I don't recall ever covering anything like this.

A: The sample sizes can be different, but balanced designs with equal
sample sizes for A and B are more efficient. For example, if you
have resources to do get 40 observations overall, you will have
a better chance of detecting true differences if you have 20
observations from A and 20 from B than if you have 10 from A and
30 from B. That said, efficient or not, the tests can be done when sizes are unequal,
and I will use unequal sample sizes that are somewhat unequal in my example.
Normal data. Suppose you have 15 observations from A distributed $\mathsf{Norm}(\mu=50, \sigma=4)$ and 10 observations from B $\mathsf{Norm}(\mu=50, \sigma=7).$
If you know that data are normal, then you can use a two-sided F-test
of $H_0: \sigma_A = \sigma_B$ against $H_a: \sigma_A \ne \sigma_B.$
[Often these are written in terms of ratios, because some of the statistical
tests use ratios: $H_0: \sigma_A/ \sigma_B = 1$ against $H_a: \sigma_A/\sigma_B \ne 1.$ The interpretation of test results is the same either way.]
Below is output for such a test from Minitab statistical software.
Test and CI for Two Variances: A, B

Method

Null hypothesis         σ(A) / σ(B) = 1
Alternative hypothesis  σ(A) / σ(B) ≠ 1
Significance level      α = 0.05

F method was used. This method is accurate for normal data only.

Statistics

                                  95% CI for
Variable   N  StDev  Variance       StDevs
A         15  4.076    16.617  (2.984,  6.429)
B         10  7.520    56.555  (5.173, 13.729)

Ratio of standard deviations = 0.542
Ratio of variances = 0.294

95% Confidence Intervals

                            CI for
         CI for StDev      Variance
Method       Ratio           Ratio
F       (0.278, 0.971)  (0.077, 0.943)

Tests

                       Test
Method  DF1  DF2  Statistic  P-Value
F        14    9       0.29    0.040

95% confidence intervals are used. The F-test gives a P-value of 0.04,
so we can reject $H_0$ and conclude there is evidence of unequal
standard deviations (or variances) between A and B.
Whether the difference
between $\sigma = 4$ and $\sigma = 7$ is of practical importance is
for you to decide as you plan sample sizes. If sample sizes were much
smaller than 15 and 9, we may not have seen a statistically significant
difference above.
Non-normal data. There are several alternative 'nonparametric' tests for use on non-normal data. Two of them, due to Bonnet and to Levene, are implemented in Minitab.
Output follows, using the same data as before:
Test and CI for Two Variances: A, B

Method

Null hypothesis         σ(A) / σ(B) = 1
Alternative hypothesis  σ(A) / σ(B) ≠ 1
Significance level      α = 0.05

Statistics

                                  95% CI for
Variable   N  StDev  Variance       StDevs
A         15  4.076    16.617  (2.497,  7.655)
B         10  7.520    56.555  (4.139, 16.994)

Ratio of standard deviations = 0.542
Ratio of variances = 0.294

95% Confidence Intervals

                            CI for
         CI for StDev      Variance
Method       Ratio           Ratio
Bonett  (0.198, 1.412)  (0.039, 1.994)
Levene  (0.165, 1.367)  (0.027, 1.869)

Tests

                       Test
Method  DF1  DF2  Statistic  P-Value
Bonett    —    —          —    0.151
Levene    1   23       2.06    0.164

Neither of the nonparametric tests found the standard deviations to be
significantly different. Knowing that data are normally distributed (if true)
provides useful information that leads to a test with a higher probability
of detecting differences between standard deviations (better 'power', in statistical terminology).  So if, you are
not able to say your data are normal, then you should plan for larger
sample sizes.
Note: Sample size and power. If you can give examples of the standard deviations that are typical in your
work and say roughly how what size difference between standard deviations would
be important to detect, then it might be possible to say what sample sizes
you would need in order to have, say, a 90% chance of detecting such a difference.
For example, here is a graph for a 2:1 ratio in standard deviations, using an F-test (normal data). It
indicates two samples of size around 24.

And for Levene's test, indicating sample sizes around 31.


text:
Q: Can't access API with Lambda and API Gateway I have an aws lambda function that returns the following response:
var responseBody = { cost: price };
var response = {
   statusCode: 200,
   headers: {
          "Access-Control-Allow-Origin": "*"
     },
    body: JSON.stringify(responseBody),
    isBase64Encoded: false
};

callback(null, response);

But I get the following error in my frontend Angular application.

Access to XMLHttpRequest at
  'https://xxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/price' from
  origin 'http://127.0.0.1:8080' has been blocked by CORS policy:
  Response to preflight request doesn't pass access control check: It
  does not have HTTP ok status.

A: If you are using API Gateway HTTP APIs (not sure if this is relevant for the REST APIs):
Lets say I have an endpoint at /POST products. I had to add another endpoint at /OPTIONS products and integrate it with a simple Lambda function that just returns the HTTP 200 OK (or HTTP 204 No Content), and the "Access-Control-Allow-Origin": "*" header (or even better, specify the URL of your origin/client).
This is because browsers issue a preflight /OPTIONS request to the same endpoint, before issuing the actual request (see more), for all HTTP requests except GET and POST with certain MIME types (source).

A: You need to enable CORS on your resource using API gateway, check this link to more information https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html


text: Q: Projection Valued Measure acting on approximate eigenvalues The spectral theorem say that we can always construct a projection valued measure (PVM) associated with an self-adjoint operator. I believe the PVM sends the eigenvalue of the operator to the projection that projects onto the eigenvectors of that eigenvalue, but I'm not so sure (although I strongly believe so due to the fact that $A=\int_R \lambda P(d\lambda)$). I want confirmation on this or proof that this isn't true. However, the more disturbing thing to me is that I have absolutely no idea what the PVM does to the approximate eigenvalues - of course except by letting the PVM act on it. I'm trying to understand this topic in the context of how it relates to the change of a state, $\psi$, in physics after measurement, which is given by $P(E) \psi P(E) \div Tr(numerator) $, where E is the value of the measurement and P is the PVM associated with the observable. I plan to read books on functional analysis later, which I think should contain my answers or at least develop the machinery for me to figure it out by myself, but I absolutely don't have the time right now so I would like to work with what I have and get an answer. Thanks.


text:
Q: I have a query in JAVA regarding f/d Why do we use f/d at the time of initialization of a float/double variable in JAVA?
Eg.,
float var1 = 8.56f;
double var2 = 0.87654d;

Will that increase the speed of compilation? Or what maybe the exact reason?

A: For doubles and float, you need to specify the compiler the type of the input.
Initiailizing 10.0 to a float variable would bring nothing but ambiguity to the compiler, as it would not understand if the value is float or a double.
So by specifying f/d at the end of the value, you're actually removing the ambiguity for the complier by using these format specifiers.


text:
Q: Why can't use left join in indexed view I know that can't use left join in indexed view. but I don't understand why?

A:
Q. Why can't I use OUTER JOIN in an indexed view?
A. Rows can logically disappear from an indexed view based on OUTER JOIN when you insert data into a base table. This makes
  incrementally updating OUTER JOIN views relatively complex to
  implement, and the performance of the implementation would be slower
  than for views based on standard (INNER) JOIN.

Credits go to http://blog.sqlauthority.com/2009/09/25/sql-server-outer-join-in-indexed-view-question-to-readers/


text:
Q: When I click on reset button site stopped responding as it was before I'm making a grammar check website using flask, when I reset the textarea by using the reset button, it allows me to upload the file but it does not display the content in that text file.

document.getElementById('myFile').addEventListener('change', function() {
  var fr = new FileReader();
  fr.onload = function() {
    document.getElementById('txt1').textContent = fr.result;
  }
  fr.readAsText(this.files[0]);
})

  <legend>Enter Your Text</legend>
  <textarea id="txt1" name="text" rows="50" cols="30" autofocus required placeholder="Either type text manually or upload .txt file. ONLY 500 CHARACTER LIMIT." value="">{{sample_input}}</textarea>

    <input id="myFile" name="myFile" type="file" style="font-size:15px; " />
    <button type="submit" value="Submit" onclick="javascript:loading();">Check Grammar Here</button>
    <button id="btn" onclick="javascript:eraseText();" style="display: inline"> Reset </button>

A: *

*No need for the javascript: label in the onclick.

*Why not use eventListeners instead of inline code?

*Where is eraseText? If you have a JS error, like you have now, the page is no longer in a valid state

If you wrap in a form you can use reset and if needed also clear the field if it is prefilled from the server

window.addEventListener("DOMContentLoaded", () => {
  const textarea = document.getElementById('txt1');
  document.getElementById('myFile').addEventListener('change', function() {
    var fr = new FileReader();
    fr.onload = function() {
      textarea.value = fr.result;
    }
    fr.readAsText(this.files[0]);
  })
  document.getElementById("myForm").addEventListener("submit", (e) => {
    e.preventDefault(); // stop submission if you need to AJAX
    // do whatever "loading" was doing
  })
  document.getElementById("clear").addEventListener("click", (e) => {
   e.target.form.reset(); // reset the form
   textarea.value = ""; // clear the area
  })
})

  <form id="myForm">
    <legend>Enter Your Text</legend>
    <textarea id="txt1" name="text" rows="10" cols="30" autofocus required placeholder="Either type text manually or upload .txt file. ONLY 500 CHARACTER LIMIT." value="">{{sample_input}}</textarea>

      <input id="myFile" name="myFile" type="file" style="font-size:15px; " />
      <button type="submit" value="Submit">Check Grammar Here</button>
      <button type="reset" style="display: inline"> Reset </button>
      <button type="button" id="clear" style="display: inline"> Clear </button>

  </form>

A: Based on documentation, to use Form reset method
Have you try to use
document.getElementById("myForm").reset();