text:
Q: How can I maximise a video in a tiled window only? Say I have 3 windows tiled on my workspace.

*

*A vim terminal session tiled vertically on the right

*A pdf tiled in the top left corner

*A youtube video playing in chrome and tiled in the bottom left corner

Here's a screenshot of my workspace
Is there a way to maximise the video to the size of the chrome tile? Currently I play videos in theatre mode, but there's still a lot of unused screen real estate wasted by the address bar and my bookmark bar for example.
I use Linux Mint Cinnamon 19.1, im using whatever the default windows manager is (I'm sorry, I have no idea what it is)


text:
Q: why are my colorPrimory and .. in theme.xml not color ? i am a begginer when I open color.xml there are purple and purple dark in my color.xml why are my colorPrimory and .. in theme.xml not color ? i am a begginer when I open color.xml there are purple and purple dark in my color.xml and when I copy and paste my chosen color into color.xml from theme.xml activity_main will destroy

A: idk if I get it right but you should first declare your color in colors.xml and then  import it to themes.xml, like this:
in colors.xml:
<color name="custom_red"> #9F0F17 </color>

in themes.xml, inside the style tag
<item name="colorPrimary">@color/custom_red</item>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Charge 18650 3S pack through USB C I have 3x 18650s wired in a series, connected to the BMS seen here. The two outputs of the BMS are wired to a MOSFET that drops the voltage from 12 to 5, in order to power an Arduino Trinket Pro.
During prototyping I was using your basic DC jack to connect to the Arduino and charge the battery pack. However with the 3D printed part I have this all in I am using a different battery contact to connect the battery pack and Arduino.
Now I am needing to find a different way to charge the battery pack, preferably through a micro USB or USB C charging port, like you see on portable power packs.
I've picked up the TP4056, seen here, and the USB C version. My question is can I / would it be a good idea to splice off of the BMS outputs, and insert a diode into the connection between the battery contact that connects to the Arduino and a diode into where the TP4056 runs.
The first time I had tried it with a standard micro USB port, no diodes, which heated up very quickly.
Or, would I be better off just running the TP4056 straight to the positive and negative terminals on the pack itself, bypassing the USB.

A: Three 18650 lithium battery cells will be 12.6V when fully charged. The TP4056 is made to charge one cell or a few paralleled cells to 4.2V so it will not charge your cells that are in series. A Mosfet by itself will not regulate the 12.6V down to 5V.


text:
Q: angular template function call Is it possible to call the convert function in an angulat template like covert{{item.size}} ? if it is possible what is the correct syntax? Thanks.
 <mat-cell *matCellDef="let item" fxHide fxShow.gt-xs fxShow.gt-md [matTooltip]="item.size">
                                            covert{{item.size}}
                                        </mat-cell>

#code converter
 convert(x){
    const units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
     let l = 0, n = parseInt(x, 10) || 0;
     while(n >= 1024 && ++l){
         n = n/1024;
     }
     return(n.toFixed(n < 10 && l > 0 ? 1 : 0) + ' ' + units[l]);
   }

A: Angular provides a way to achieve this via pipes. You can create one pipe and put you conversion logic there. It is a good choice because if you need anywhere else in you application it can be easily consumed binding such logic to component function is not a good idea.
Create pipe using angular cli or just by creating pipe and its spec.
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'convert'})
export class convert implements PipeTransform {
  transform(x: number): number {
   const units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
     let l = 0, n = parseInt(x, 10) || 0;
     while(n >= 1024 && ++l){
         n = n/1024;
     }
     return(n.toFixed(n < 10 && l > 0 ? 1 : 0) + ' ' + units[l]);
  }
}

I haven't changed any logic for the conversion as I assume it is not having any issues. Now, you can use this pipe in your component like this:
<mat-cell *matCellDef="let item" fxHide fxShow.gt-xs fxShow.gt-md [matTooltip]="item.size">
        {{item.size | convert}}
</mat-cell>

A: Try it.
{{ convert(item.size) }} or convert(item.size)


text:
Q: PhpStorm 'Find in Path' doesn't search everywhere I'm using PhpStorm 2017.2.4 on Win 8.1.
I'm trying to search for a string within every file in the project.
For that I've opened 'Find in Path', set the File mask to "*", selected the option "Recursively" and began typing.
It seems that the tool is limiting it search to maximum of 100 files, and thus doesn't find that which I'm looking for. If I limit the search to be below 100 files it will work, but that's pointless.
The filetype is not ignored and is added under settings and 'File Types'.
Should I use the Notepad++ 'Find in Files' search function instead, or does PhpStorm/IntelliJ-IDEA has a function like that?

A: Please follow the related issue on YouTrack: https://youtrack.jetbrains.com/issue/IDEA-178771


text:
Q: toggle javascript function I'm using this code to start a log file :
function startTail(str) {
if (str== "stop") {
stopTail();
} else {
t= setTimeout("getLog()",1000);
}
}

This is called using :
<button id="start" onclick="getLog('start');">

and stopped using :
<button id="stop" onclick="getLog('stop');">

Is there anyway I can change this to one button that will toggle start / stop ?

A: Try:
<button id="start" value="Toggle Log" onclick="getLog('start', this);">

function startTail(str, element) {
    if (str == "stop") {
        stopTail();
        element.setAttribute('onclick', "getLog('start', this);");
    } else {
        element.setAttribute('onclick', "getLog('stop', this);");
    }
}

A: You could try this
var flag = false;
function startTail() {
 if (flag)
  {
    stopTail();
    document.getElementById('start').value = "Start";
    flag = false;
  }
 else
  {
    t= setTimeout("getLog()",1000);
    flag = true;
    document.getElementById('start').value = "Stop";
  }
}

<button id="start" onclick="startTail();" value="Start">


text:
Q: How to get rid of black line above UITabBar when changing color of tab bar I have a code that changes a tab bar color like this
    UITabBar *tabBar = [vc.view.subviews objectAtIndex:1];
    CGRect rectAdjust = CGRectMake(roundf(screenWidth - 305.0f) / 2.0f, screenHeight - 54.0f - 10.0f,  305.0f, 54.0f);
    tabBar.frame = rectAdjust;

    UIColor *tabbarBg = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0];
    tabBar.tintColor = tabbarBg;

The code should change color of tab bar without any flaw however, I got this result

notice that there has a black line above my tab bar. I don't know where this comes from.
How to get rid of that?

A: If you want to remove black line on top of the UITabBar then use  following suggestion,
Add following framework in your project
#import <QuartzCore/QuartzCore.h>

And write following code
self.tabBar.layer.borderWidth = 0.50;
self.tabBar.layer.borderColor = self.tabBar.tintColor.CGColor;

Edited
I did not tried but I think @Nav's comment should be work if not then use above suggestion.


text:
Q: Structuremap, odd behavior when using default instance and named instance Options Is anybody able to explain the following behavior?
Especially why TestInitializeAndConfigure_Fails failes when TestUseAndAdd does not ... and why TestUse_Fails failes when TestUseOrderChanged does not.
Thanks
code
interface IResource {}
class TheFirstResource : IResource {}
class TheSecondResource : IResource {}

[TestFixture]
class Test
{
    [Test]
    public void TestUse_Fails()
    {
        ObjectFactory.Initialize(init =>
        {
            init.For<IResource>().Singleton().Use<TheFirstResource>();
            init.For<IResource>().Singleton().Use<TheSecondResource>().Named("test");
        });

        IResource r1 = ObjectFactory.GetInstance<IResource>();
        IResource r2 = ObjectFactory.GetNamedInstance<IResource>("test");

        Console.WriteLine(string.Format("TestUse_Fails \n{0}\n{1}", r1, r2));
    }

    [Test]
    public void TestUseOrderChanged()
    {
        ObjectFactory.Initialize(init =>
        {
            init.For<IResource>().Singleton().Use<TheSecondResource>().Named("test");
            init.For<IResource>().Singleton().Use<TheFirstResource>();
        });

        IResource r1 = ObjectFactory.GetInstance<IResource>();
        IResource r2 = ObjectFactory.GetNamedInstance<IResource>("test");

        Console.WriteLine(string.Format("TestUseOrderChanged \n{0}\n{1}", r1, r2));
    }

    [Test]
    public void TestUseAndAdd()
    {
        ObjectFactory.Initialize(init =>
        {
            init.For<IResource>().Singleton().Use<TheFirstResource>();
            init.For<IResource>().Singleton().Add<TheSecondResource>().Named("test");
        });

        IResource r1 = ObjectFactory.GetInstance<IResource>();
        IResource r2 = ObjectFactory.GetNamedInstance<IResource>("test");

        Console.WriteLine(string.Format("TestUseAndAdd \n{0}\n{1}", r1, r2));
    }

    [Test]
    public void TestInitializeAndConfigure_Fails()
    {
        ObjectFactory.Initialize(init =>
        {
            init.For<IResource>().Singleton().Use<TheFirstResource>();
        });

        ObjectFactory.Configure(init =>
        {
            init.For<IResource>().Singleton().Add<TheSecondResource>().Named("test");
        });

        IResource r1 = ObjectFactory.GetInstance<IResource>();
        IResource r2 = ObjectFactory.GetNamedInstance<IResource>("test");

        Console.WriteLine(string.Format("TestInitializeAndConfigure_Fails \n{0}\n{1}", r1, r2));
    }
}

output
TestUse_Fails
Smtesting.TheSecondResource
Smtesting.TheSecondResource

TestUseOrderChanged
Smtesting.TheFirstResource
Smtesting.TheSecondResource

TestInitializeAndConfigure_Fails
Smtesting.TheSecondResource
Smtesting.TheSecondResource

TestUseAndAdd
Smtesting.TheFirstResource
Smtesting.TheSecondResource

A: Just to help the people who will stumble upon this, here is an answer from the man Jermey himself. He answered the question on his blog here.

For().Use() is destructive. Do For().Use() once to get the default, and a second call to For().Add() to get the 2nd registration. Look at the Xml comments for those 2 API calls.

A: TestUse_Fails makes sense to me, because calling Use<>() essentially means you are specifying the default instance for the type (and adding it).  Last one in generally wins--I can't find explicit docs on this, but that's the way most containers work.  The r1 call gets TheSecondResource (the last one set to be default), and the r2 call gets the named resource.
TestUseOrderChanged works because the default after init/config is the TheFirstResource, but TheSecondResource has still been added to the container with a name.  So r1 gets TheFirstResource (as it was last in and thus the default), and r2 correctly gets TheSecondResource as the named instance.
TestInitializeAndConfigure_Fails is the odd one.  From where I sit, r1 should get TheFirstResource, since the default has not been overwritten--Use<>() has not been called again.  Calling Configure after calling Initialize should not reset the container according to the docs.  I would try calling ObjectFactory.WhatDoIHave() and see if TheFirstResource is even registered after the Initialize() and Configure() calls.
To me, this looks like a bug, and I would consider submitting it to the structuremap users group (http://groups.google.com/group/structuremap-users).


text:
Q: Best way to use checkboxes with PHP first off I am a rookie so please forgive my basic question. I am trying to use an html checkbox to let me know when to check a serial number. The problem is no matter what i do I get an error telling me "Notice: Undefined index: sncheck in XYZ".
I tried using a ternary operator to set the value as it was posted (If the checkbox was not checked) but it still fails on me. Any suggestions would be
Here is the code, below im using a checkbox with the name sncheck and a value of ok. thanks!
if (isset($_POST['submit'])){
    $gov = mysqli_real_escape_string( $dbc, trim($_POST['gov']));
    $pctype = mysqli_real_escape_string( $dbc, trim($_POST['pctype']));
    $compname = mysqli_real_escape_string( $dbc, trim($_POST['compname']));
    $username = mysqli_real_escape_string( $dbc, trim($_POST['username']));
    $compmodel = mysqli_real_escape_string( $dbc, trim($_POST['compmodel']));
    $serialnumber = mysqli_real_escape_string( $dbc, trim($_POST['serialnumber']));
    $sncheck = ($_POST['sncheck']== 'ok') ? $_POST['sncheck'] : '';
    $purchdate = mysqli_real_escape_string( $dbc, trim($_POST['purchasedate']));
    $os = mysqli_real_escape_string( $dbc, trim($_POST['os']));
    $memory = mysqli_real_escape_string( $dbc, trim($_POST['memory']));
    $monitor1 = mysqli_real_escape_string( $dbc, trim($_POST['monitor1']));
    $monitor2 = mysqli_real_escape_string( $dbc, trim($_POST['monitor2']));
    $warranty = mysqli_real_escape_string( $dbc, trim($_POST['warranty']));
    $warrantyend = mysqli_real_escape_string( $dbc, trim($_POST['warrantyend']));
    $status = mysqli_real_escape_string( $dbc, trim($_POST['status']));
    $notes = mysqli_real_escape_string( $dbc, trim($_POST['notes']));

    if (dateformat($purchdate) == 1 && $sncheck == "ok"){
            $querysn = "SELECT serialnumber FROM inventory" .
                                " WHERE serialnumber = '" . $serialnumber . "'";
            $data = mysqli_query($dbc, $querysn) or die('Error querying the Database for Serial Numbers');
            if (mysqli_num_rows($data) == 0){
                $queryupdate = "UPDATE inventory SET government = '$gov', pctype = '$pctype', compname = '$compname'," .
                                    " username = '$username', compmodel = '$compmodel', serialnumber = '$serialnumber', purchased = '$purchdate'," .
                                    " operatingsystem = '$os', `memory` = '$memory', monitor1 = '$monitor1'," .
                                    " monitor2 = '$monitor2', warranty = '$warranty', warrantyend = '$warrantyend', `status` = '$status', notes = '$notes'" .
                                    " WHERE serialnumber = '" . $_POST['serialnumber'] . "'";
                mysqli_query($dbc, $queryupdate);
                echo 'PC was sucessfully saved';
            }
            else{
                echo '
The serial number has already been used, please try another
';
            }
    }
    else{
        echo '
The date format does not match
';
    }

    if (dateformat($purchdate) == 1){
            $querysn = "SELECT serialnumber FROM inventory" .
                                " WHERE serialnumber = '" . $serialnumber . "'";
            $data = mysqli_query($dbc, $querysn) or die('Error querying the Database for Serial Numbers');
            if (mysqli_num_rows($data) == 0){
                $queryupdate = "UPDATE inventory SET government = '$gov', pctype = '$pctype', compname = '$compname'," .
                                    " username = '$username', compmodel = '$compmodel', purchased = '$purchdate'," .
                                    " operatingsystem = '$os', `memory` = '$memory', monitor1 = '$monitor1'," .
                                    " monitor2 = '$monitor2', warranty = '$warranty', warrantyend = '$warrantyend', `status` = '$status', notes = '$notes'" .
                                    " WHERE serialnumber = '" . $_POST['serialnumber'] . "'";
                mysqli_query($dbc, $queryupdate);
                echo 'PC was sucessfully saved';
            }
            else{
                echo '
The serial number has already been used, please try another
';
            }
    }
    else{
        echo '
The date format does not match
';
    }
}

A: EDITED ANSWER: Based on your edited question, try changing:
$sncheck = ($_POST['sncheck']== 'ok') ? $_POST['sncheck'] : '';

to:
$sncheck = isset($_POST['sncheck']);

If a checkbox is checked, it will be set in $_POST. If it's not checked it will not be.
ORIGINAL ANSWER:
It's tough to answer your question without seeing code, so I'm just stabbing in the dark, but here goes. Here's an example:
<?php

$serial_numbers = array('1','2','3'); // Put your real serial numbers here...

if(isset($_REQUEST['submit']))
{
    if(isset($_REQUEST['serial_numbers']) && is_array($_REQUEST['serial_numbers']))
    {
        foreach($_REQUEST['serial_numbers'] as $serial)
        {
            // Do something with this serial number
            echo "You checked $serial
";
        }
    }
}
else
{
    // Show a form to select serial numbers:

    echo "<form action=\"$PHP_SELF\">";
    foreach($serial_numbers as $serial)
    {
        $serial_ht = htmlspecialchars($serial);
        echo "<input type=\"checkbox\" name=\"serial_numbers[]\" value=\"$serial_ht\">$serial_ht
";
    }

    echo '<input type="submit" name="submit" value="Submit">';
}

This is a complete guess because I'm not sure what you're doing. But this will take an array of serial numbers and display a form containing them all with checkboxes next to each one. When the form is submitted, the selected serial numbers will be in $_REQUEST['serial_numbers'] (which will be an array). The script will loop through each member of this array and print those serial numbers back. Not very useful, but again, it's just an example. Please post some code if you'd like more direction and I'll edit my answer.

A: Use isset($_GET['id']); or isset($_POST['id']) to check if a field - such as a checkbox - was submitted in a form.
(Note however, that textfields and some other form inputs will be "" and will therefore be considered as "submitted" using the method above)
EDIT:
Also, you didn't get an error, but a notice. Notices doesn't mean that something is wrong, but that you for instance should have done something instead of what you actually did etc. for the PHP script to be better. Warnings, however, are "non-fatal errors", and errors are simply fatal errors that will cause the script to halt execution.


text:
Q: Where should the apostrophe go on a possessive abbreviation? When expanding an abbreviation in parentheses, sometimes the thing that was abbreviate was used in a possessive context.
Consider the following example:

If the Giant Ostrich Bomb's (GOB) fuse is too short, you may be too close when it goes off and you may get kicked in the face.

Is the above correct, or should it be rewritten this way instead:

If the Giant Ostrich Bomb (GOB)'s fuse is too short, you may be too close when it goes off and you may get kicked in the face.

If this is a matter of style, do any of the popular style manuals have a recommendation?

A: In your question, the two alternatives that you permit readers (and yourself) to consider are

If the Giant Ostrich Bomb's (GOB) fuse is too short, you may be too close when it goes off and you may get kicked in the face.

and

If the Giant Ostrich Bomb (GOB)'s fuse is too short, you may be too close when it goes off and you may get kicked in the face.

But there are clearly at least two other plausible options whose existence you don't acknowledge. These are (1) rewriting to avoid the possessive (as suggested in Love's answer):

If the fuse of the Giant Ostrich Bomb (GOB) is too short, you may be too close when it goes off and you may get kicked in the face.

and (2) rewriting to include the possessive in both the full wording and the abbreviation:

If the Giant Ostrich Bomb's (GOB's) fuse is too short, you may be too close when it goes off and you may get kicked in the face.

It seems to me that either of these latter two approaches is superior to either of the earlier two approaches because the latter two approaches are internally consistent and don't call attention to themselves in a distracting way, as the earlier two approaches do.
The style guides I consulted (Oxford, Chicago, Words into Type, and AP) offer no guidance on how to deal with this situation, although most do discuss the practice of following a complete term or proper name with its abbreviation in parentheses. The reason for this silence, I believe, is that style guides view it as a matter of common sense to recast the sentence to avoid the 's spelling altogether.
But if such a restructuring seems impossible for some reason, the next question to ask, I think, is, "How I would I say this if I were saying the words to someone in conversation?" In that case, I think "the Giant Ostrich Bomb's (GOB's) fuse" is easier for the hearer to make sense of than either "the Giant Ostrich Bomb's (GOB) fuse" or "the Giant Ostrich Bomb (GOB)'s fuse." But this is ultimately a style question—and a matter of opinion—not an issue of syntactical right and wrong.

A: I would rather you reword the sentence to avoid the possessive. Probably something like this:

If the fuse of the Giant Ostrich Bomb(GOB) is too short, you may be too close when it goes off and you may get kicked in the face.

If I had to pick out of the two, the first one seems logical.


text:
Q: Table cell creation warning/error about IBlockElement Just starting to try and use iText (latest version) and following some online examples. However, this bit of code in Visual Studio 2019, VB:
Dim cell1 = New Cell
cell1.Add("Name")

gives me an intellisense warning/error in the editor saying:

Runtime errors might occur when converting 'String' to 'IBlockElement'.

Why doesn't the cell.ADD argument accept strings as per online code examples please?
(I am also not well versed in using Interfaces either!)
Thank you

A:
Why doesn't the cell.ADD argument accept strings as per online code examples please?

Apparently the online code examples you saw were created at the time of the early 7.0.x versions. But the whole table API has been overhauled in 7.1.0 including some breaking changes.
Thus, in the current version create an IBlockElement (e.g. a Paragraph) containing your text and add that block element to your table cell.


text:
Q: What do the screens say after you are set free? In the video game Superhot, after

 being uploaded and freed from your useless, disposable body,

there is some tiny red text against a black background that shows up for a few seconds on the monitors. What does it say?

A:

Software failure. Press left mouse button to continue.
Guru Meditation ?000000004.48454C50

I'm not sure what the ? is. Possibly a block ▊ or a hash #

A: It says

Software failure. Press left mouse button to continue.
           Guru Meditation #00000004.48454C50

I managed to freeze-frame it on this "ending" video

As @Fuzzyboots has pointed out in his answer, the words relate to an (old) easter egg error message used on Commodore Amiga computers. In this instance, a software failure that would require a reboot, the numbers 48454C50 spelling out "help" in ASCII code, which signifies a fatal error that the computer can't diagnose.

A: Riffing off of Valorum's answer, guru meditation is a reference to a famous Amiga error. From The New Hacker's Dictionary:

Amiga equivalent of panic in Unix (sometimes just called a guru or guru event). When the system crashes, a cryptic message of the form "GURU MEDITATION #XXXXXXXX.YYYYYYYY" may appear, indicating what the problem was. An Amiga guru can figure things out from the numbers. Sometimes a guru event must be followed by a Vulcan nerve pinch.This term is (no surprise) an in-joke from the earliest days of the Amiga. An earlier product of the Amiga corporation was a device called a 'Joyboard' which was basically a plastic board built onto a joystick-like device; it was sold with a skiing game cartridge for the Atari game machine. It is said that whenever the prototype OS crashed, the system programmer responsible would calm down by concentrating on a solution while sitting cross-legged on a Joyboard trying to keep the board in balance. This position resembled that of a meditating guru. Sadly, the joke was removed fairly early on (but there's a well-known patch to restore it in more recent versions).


text:
Q: Symfony2 Controller won't catch exception This is the route handler for my delete action.  It works well as long as the item does not have any associations.
public function projectDeleteAction()
{
    try {
        $request = $this->get('request');
        $my_id = $request->query->get('id');

        $em = $this->get('doctrine.orm.entity_manager');

        $item = $em->find('MyBundle:Main', $my_id);

        $em->remove($item);
        $em->flush();

        $info = $item->getName();
        $result = 0;
    }
    catch (Exception $e) {
        $info = toString($e);
        $result = -1;
    }

    return $this->render('MyBundle:Main:response.xml.twig',
            array('info' => $info, 'result' => $result ));
}

I have already solved the error of trying to delete an item with associations, but through this process, the "flush" was throwing PDOException.  I tried various ways to catch it, but it appears to be getting caught inside Symfony2 and then it responds with a HTTP 500 error.  Is there a way that I can have Symfony2 not catch this so that I can handle it?  This is an XML response using AJAX and so I would rather just send an error code per above.

A: It is better to catch the exception you really want to catch. In this example that is probably Doctrine/DBAL/DBALException and/or Doctrine/DBA/DBAException.
Thus
catch (Doctrine\DBAL\DBALException $e) {
  $result = -1;
};

I would recomment doing something like:
    } catch (\Exception $e) {
        switch (get_class($e)) {
            case 'Doctrine\DBAL\DBALException':
                echo "DBAL Exception
";
                break;
            case 'Doctrine\DBA\DBAException':
                echo "DBA Exception
";
                break;
            default:
                throw $e;
                break;
        }
    }

This actually catches the DB exceptions, and if for some reason some other exception occures, this is rethrown back into Symfony2.

A: Try to change Exception → \Exception if you didn't specified PDOException as Exception in a use statement. PHP tries to find \YourNamespaceWithController\Exception instead of \Exception (and it does not check the existence of such exception).

A: I had to do the following which might help for some users;
try{
    $this->doctrine->em->persist($user);
    $this->doctrine->em->flush();
}catch(Exception $e){
    if($e->getPrevious()->getCode() == 23505){
        //handle duplicate error, 23505 is for postgres, 23000 is mysql unique constraint.
    }
}


text:
Q: How to clean url when using get method I currently have a single product.php page that displays the data of each individual product on the products.php page
I am looking for a way to clean up the URL of each item that has it's data displayed through the product.php file.
current URL 'rubberholds/product.php?item=item1'
desired URL 'rubberholds/product/product-one' for example
products.php
<?php foreach ($limestoneItems as $item => $limestone): ?>

<a href="product.php?item=<?php echo $item; ?>">
<img
    src="assets/img/limestone/<?php echo $limestone[img]; ?>.jpg"
    alt="<?php echo $limestone[alt]; ?>">

<?php endforeach ?>

product.php
<?php
  if (isset($_GET['item'])) {
    $limestoneProduct = $_GET['item'];
    $product = $limestoneItems[$limestoneProduct];
  }
?>

Array
$limestoneItems = array(
  "item1" => array(
    title => "Product-One",
    img => "product1",
    alt => "Product1"
  )
);

Does anyone have any suggestions on how to achieve this? I want to remove .php extensions and replace '?item=item1' with $limestone[title]
EDIT
I have created a .htaccess file with the following code which is not working:
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [L]

RewriteCond %{REQUEST_FILENAME}\.php -f

RewriteRule ^product/([0-9a-zA-Z_-]+) product.php?item=$1 [NC,L]

A: *

*rubberholds/product - Test here

*rubberholds/product/product-one - Test here
.htaccess
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^rubberholds/product/?(.*)$ rubberholds/product.php?item=$1 [QSA]

Test data :
$limestoneItems = [
    'item1' => [
        'title' => 'Product-One',
        'img'   => 'product1',
        'alt'   => 'Product1',
    ],
    'item2' => [
        'title' => 'Product-Two',
        'img'   => 'product2',
        'alt'   => 'Product2',
    ],
    'item3' => [
        'title' => 'Product-Three',
        'img'   => 'product3',
        'alt'   => 'Product3',
    ],
];

product.php
$title = strtolower($_GET['item']);
$data  = array_filter($limestoneItems, function ($v) use ($title) {
    $v['title'] = strtolower($v['title']);

    return in_array($title, $v);
});

if ($data) {
    $key     = array_keys($data)[0];
    $product = $limestoneItems[$key];

    var_dump($product); // Data found
} else {
    var_dump('Not found'); // Data not found
}

A: You may follow the bellow steps:
1) changes in .htaccess file to accept file without .php extension
RewriteEngine On
RewriteRule ^([^\.]+)$ $1.php [NC,L]

2) products.php
<?php
$limestoneItems = array(
  "item1" => array(
    "title" => "Product-One",
    "img" => "product1",
    "alt" => "Product1"
  )
);

foreach ($limestoneItems as $item => $limestone) {
    echo '

';
}
?>

3) product.php
<?php
$limestoneItems = array(
  "item1" => array(
    "title" => "Product-One",
    "img" => "product1",
    "alt" => "Product1"
  )
);

if (isset($_GET['item'])) {
    $limestoneProduct = $_GET['item'];
    foreach ($limestoneItems as $key => $val) {
        if ($val['title'] === $limestoneProduct) {
            $product = $limestoneItems[$key];
            echo implode(" ",$product);
        }
    }
}
?>

A: In .htaccess file

RewriteRule ^([^/])/([^/])/([^/])\product-([^/])$
  rubberholds/product.php?item=item1[L]

In your code change products.php
<a href='product.php/product-<?php echo $item; ?>'>

A: For a given URL with the following format:
http://example.org/rubberholds/product.php?item=item1

Will result in the following format:
http://example.org/product/item1

Use the following Rewrite Rule in your .htaccess:
RewriteEngine On
RewriteRule ^product/([^/]*)$ /rubberholds/product.php?item=$1 [L]

A: Please find below steps:
(1) Changes in .htaccess file to accept file without .php extension and with the change, you want in URL.
Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REQUEST_FILENAME}.php -f
#Below line will perform /product(any_file_name) as product.php
RewriteRule ^(.*)$ $1.php [NC]
#Below line will perform /product/product-one(any_product_name) as product.php?item=product-one
RewriteRule ^product/([a-z0-9-]+) product.php?item=$1 [NC]

for more details on how to write url rules in .htaccess, please visit:
http://www.wbcsoftwarelab.com/wbcblog/url-rewriting-examples-using-htaccess
(2) product.php
While displaying products change url format
from:
<a href="product.php?item=<?php echo $item; ?>">

to:
<a href="product/<?php echo $limestone[title]; ?>">

(3) product.php
When user clicks on that url, you will get the product name in $_GET["item"] and use it like below to get its key:
if (!empty($_GET)) {
    if (isset($_GET['item'])) {
        $product = $_GET['item'];
        foreach ($limestoneItems as $key => $value) {
            if ($value['title'] === $product) {
                $item = $key; //here you will get the item number for the product
                $productDetails = $value; //this will be details of the item
                echo "Item: ".$item."\n";
                echo "Product Details: " . implode(" ", $productDetails);
            }
        }
    }
}


text:
Q: How to change input value onfocus and onblur (no jquery) I wrote some code, kind of like an alternative for HTML5 placeholder using JavaScript, but it's not working. As far as I can figure (with my mediocre knowledge of js), everything should work, but it's not. Please help!!! Here's my code:
JavaScript:
(function(){
    var field = document.getElementById('placeholder');
    var placeholdertext = "Search box"; // << change this to whatever you want the placeholder text to be

    field.setAttribute("onblur", "if(value=='') { value = '" + placeholdertext + "'")
    field.setAttribute("onfocus", "if(value=='" + placeholdertext + "') { value = '' }")
})();

HTML
<input type="search" value="Search box" id="placeholder">

Edit:
I don't want to use jQuery or inline-html-coding, please. Thanks for any help, guys!!!

A: Replace value with this.value in your code (as you need to check the value of the element that triggers an event, and not some global variable) and it will work.
As a sidenote, perhaps I'd prefer still using placeholder attribute here, providing a JS shim only for the browsers that don't support it. This would simplify the javascript code part too, as you wouldn't have to use some variable just to store some DOM-related data:
field.onblur = function() {
  if (this.value === '') {
    this.value = this.getAttribute('placeholder');
  }
};

field.onfocus = function() {
  if (this.value === this.getAttribute('placeholder') ) {
    this.value = '';
  }
};

... and in fact I'd prefer using addEventListener/attachEvent here instead of onblur/onfocus, as described in this answer.

A: <input type="text" value="Enter The User Name" onblur="if(this.value == '') { this.style.color='#f00'; this.value='Enter The User Name'}" onfocus="if (this.value == 'Enter The User Name') {this.style.color='#000'; this.value=''}" />

Try This without Jquery

A: Without jQuery:
field.onblur = function() {
  if (field.value == '') {
    field.value = placeholdertext;
  }
};

field.onfocus= function() {
  if (field.value == placeholdertext ) {
    field.value = '';
  }
};

A: I haven't tested this but if i'm understanding your question this should work.  If it works don't forget to hit the check mark.
    var field = document.getElementById('placeholder');
    var placeholdertext = "Search box";

    field.bind('onblur', function() {
        if (field.text() === '') {
            field.text(placeholdertext);
        }
    });

    field.bind('onfocus', function() {
        if (field.text() === '') {
            field.text(placeholdertext);
        }
    });


text:
Q: get set operators from dict on python If I have two or more sets, and a string that describe de operation that must be done between them, like 'and', 'or', 'xor', it can be obviously get done like this:
if string == 'and':
    return set1.intersection(set2)
elif string == 'or'
    return set1 | set2

and so on. What if I want to do it with a dictionary?
I have something like this:
dictionary = {'and': set.intersection, 'or': set.union}
return set1.dictionary[string](set2)

And also tried
operation = dictionary.get(string)
return set1.operation(set2)

But none worked. How can I achieve the same result that I get through ifs but with a dictionary?

A: You can use set.itersection(), set.union(), etc. as static methods, passing multiple sets to them:
>>> ops = {'and': set.intersection, 'or': set.union}
>>> set1 = {1, 2, 3}
>>> set2 = {3, 4, 5}
>>> ops['and'](set1, set2)
{3}
>>> ops['or'](set1, set2)
{1, 2, 3, 4, 5}

Alternatively, you could map operations to method names and use getattr():
>>> ops = {'and': 'intersection', 'or': 'union'}
>>> getattr(set1, ops['and'])(set2)
{3}
>>> getattr(set1, ops['or'])(set2)
{1, 2, 3, 4, 5}

A: You can try attrgetter
from operator import attrgetter

set_methods = {"and": attrgetter("intersection"), 'or': attrgetter("union")}

Call it like: set_methods[method_string](set1)(set2).


text:
Q: Constructing a promise without a resolver or reject I have a asynchronous function sayHello() which is called inside greeting() function:
function greeting() {
    let P = new Promise();
    sayHello().then(function(){
       //manipulate DOM
       P.resolve();
    }).catch(function(error)){
       //manipulate DOM
       P.reject();
    });
    return P;
}

I want greeting() to return a promise, so the caller would know when sayHello's work  is finished. But this code doesn't seem to be correct, as it says Promise should have resolve and reject functions defined when being constructed. What should I do ?

A: Just return the Promise returned by sayHello():
function greeting() {
  return sayHello().then(function(){
    //manipulate DOM
  }).catch(function(error)){
    //manipulate DOM
  });
}

The then method return a Promise.
Here's a simple fiddle illustrating this.

A: async function greeting() {
  let response
  try {
    response = await sayHello()
  } catch(err) {
    response = err
  }
  return response
}

greeting().then(response => console.log(response))

function greeting2() {
  return new Promise((resolve, reject) => {
    sayHello().then(_ => {
      //manipulate DOM
      resolve()
    }).catch(err => {
      //manipulate DOM
      reject()
    })
  })
}

greeting2().then(_ => console.log('something'))

A: The other answers offer good solutions, but the actual reason you are seeing the error: Promise should have resolve and reject functions defined when being constructed. is the specific Promise implementation you are using. The latest version expects an "executor" function as the first argument when calling it:
new Promise(/* this is the executor: */ function (resolve, reject) { ... });

You can see the specification here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Older versions of Promise did not follow the same specification.


text:
Q: backgroundColor for pushed view controller I am pushing a viewcontroller (using a .xib) using:
[self.navigationController pushViewController:detailViewController
                                         animated:YES];

I have the background color set to black in Interface builder, but I still see the default iOS gray background when the app is running. The black color shows up in the Interface builder when I look at the .xib file.
Can someone please help?
Thanks.

A: I think you want to provide more information, like what your xib looks like, etc. Otherwise it's pretty hard to figure out what's wrong exactly. And I don't think iOS's default bg color is gray?
But you can set
self.view.backgroundColor = [UIColor blackColor];

in the viewDidLoad: of your detailViewController I guess.

A: Thanks for your input! It turns out a superclass was setting the background image to the default image. The solution turned out to be:
// Remove background image
[[[self.view subviews] objectAtIndex:0] removeFromSuperview];
self.view.backgroundColor = [UIColor blackColor];


text:
Q: Reference request: the dual Coleman family Recently when I want to understand the construction of triple product p-adic L-function, I am really confused by the notion of dual form. To be precise, assume $f^\circ\in{S_k(N,\chi)}$ is an eigenform of weight k, level N (not necessary new) with nebentype $\chi$ and f be (one of the) p-stabilization of $f^{\circ}$,   we can construct several modular forms from f:
assume the $q$-expansion of f is $\sum_{n\geq1}a_nq^n$,
$(i)$ The conjugate form $f^*$ defined by $f^*(\tau)=\overline{f(-\bar{\tau})}$, the q-expansion of $f^*$ is $\sum_{n\geq1}\bar{a}_nq^n$;
$(ii)$ The twisted form $f_{\chi^{-1}}$ by $\chi^{-1}$ whose q-expansion is $\sum_{n\geq1}\chi^{-1}(n)a_nq^n$;
$(iii)$ and moreover as in Def.2.4 of the paper a note on p-adic Rankin-Selberg L-functions, the form $f^c$ which is the unique form which has level $Np^r$ for some r and whose Hecke eigenvalue away from N is same as $f_{\chi^{-1}}$.
What is the relation of the three forms?  Would anyone provide some reference? Thanks
If F is a Coleman family of tame level N and nebentype $\chi$, could we define the corresponding family $F^*$, $F_{\chi^{-1}}$ or $F^c$ satisfying similar description on $q$-expansion? The paper  A p-adic Gross-Zagier formula for diagoanl cycles(page 41) uses $F^*$ (for Hida family), but no details provided there and Lem.3.4 of 1 claims the existence of $F^c$ (at least for F is new at N) but I could not spell out the details. Would anyone please provide me some reference containing more details?
Thanks

A: The definition of $f^c$ that I give in my Canad Math Bulletin paper is only well-defined when $f$ is a p-stabilised newform (i.e. f has level $Np^r$ for some $r \ge 1$ and $p \nmid N$, and either f is new of level $Np^r$, or $r = 1$ and f is the p-stabilisation of a newform of level N). If f is not locally new at the primes dividing N, then I didn't attempt to define $f^c$, and I suspect there is no good way of doing so.
In the "crystalline" case, when f is a p-stabilisation of a level N newform $f^\circ$, then $f^c$ and $f^*$ are both well-defined, and they are both p-stabilised newforms, but they are not generally the same. The relation between the two is the following. There is a level N newform $(f^\circ)^*$, and it has two p-stabilisations at level Np; one of these is $f^*$ and the other one is $f^c$. One computes that $a_p(f^c) = \chi(p)^{-1} a_p(f)$, but $a_p(f^*) = p^{k-1} / a_p(f)$. Hence the observation in my Remark 2.5 that if f is ordinary, then so is $f^c$, but $f^*$ is not ordinary unless k = 1.
(You can see immediately from those two formulae that $a_p(f^*)$ does not interpolate as f varies over specialisations of a Coleman family F, because $p^{k-1}$ is not a p-adically continuous function of k in weight space. I'm not 100% sure what Darmon and Rotger mean by $F^*$ when F is a Hida family, but I suspect they mean what I'm calling $F^c$.)
EDIT. You asked how $F^c$ is constructed. A Coleman family of tame level N has a "tame nebentype" $\chi$, which is a Dirichlet character mod $N$. If you twist $F$ by $\chi^{-1}$, you get another Coleman family whose tame nebentype is $\chi^{-1}$. A priori this family might have tame level larger than $N$, maybe up to $N^2$; but you know that it has many classical specialisations of tame level $N$ (in fact it suffices for it to have a single non-critical-slope specialisation of tame level $N$), so in fact this family has tame level $N$ and you are done.


text:
Q: Attachment size is wrong in msgraph api The property size of FileAttachment is larger than the actrually size of binary.
 {
    "@odata.type": "#microsoft.graph.fileAttachment",
    "@odata.mediaContentType": "application/octet-stream",
    "id": "<the attachment id>",
    "lastModifiedDateTime": "2020-10-26T09:57:36Z",
    "name": "test.bin",
    "contentType": "application/octet-stream",
    "size": 245,
    "isInline": false,
    "contentId": null,
    "contentLocation": null,
    "contentBytes": "aGVsbG8gd29ybGQ="
}

Here is a piece of java code create above json data:
IGraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider(provider).buildClient();
FileAttachment attachment = new FileAttachment();
attachment.oDataType = "#microsoft.graph.fileAttachment";
attachment.name = "test.bin";
attachment.contentBytes = "hello world".getBytes();

Attachment att = graphClient.users().byId(userId).messages().byId(mailId).attachments().buildRequest().post(attachment);
System.out.println(att.size);

A: The attachment size in the Graph should just be the PidTagAttachSize property https://learn.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxprops/917d8d18-adee-4f14-9f2a-9a1d37fff41e . The size returned is basically made up of the size of all the attachment properties (not just the underlying attachment size) in the Attachment object. So it will always be bigger then the actual attachment size. There's another description https://learn.microsoft.com/en-us/office/client-developer/outlook/mapi/pidtagattachsize-canonical-property

This property can be used to check the approximate size of the attachment before performing a remote transfer by modem and to display progress indicators when saving the attachment to disk. It is particularly useful with attached OLE objects.

Given they talk about modems its a little dated.


text:
Q: How to remove ampersand, pound & number from a http response string in Javascript I currently have an API that returns the following string inside parentheses
(Multivitamin Gummies - Berry, Peach & Orange - 150ct - Up&Up™)

I want it to be instead formatted to the user like so
(Multivitamin Gummies - Berry, Peach & Orange - 150ct - Up&Up)

Is there a way to dynamically do this fix this in javascript?
Here is another example:
(Aloe Hand Sanitizer Gel - 8 fl oz - Up&Up™)

should return
(Aloe Hand Sanitizer Gel - 8 fl oz - Up&Up)

A: I hope this helps

var str = 'Aloe Hand Sanitizer Gel - 8 fl oz - Up&Up™';

console.log(str.match(/[^™]+/)[0]);

A: Add the characters you want to replace in the or | like below in the regex and replace using .replace()
/™|&#38|&#8482/g

var str = 'Aloe Hand Sanitizer Gel - &#8482 8 fl oz - Up&Up™';
console.log(str.replace(/™|&#38|&#8482/g, ""));

A: Looks like you want to replace all Unicode with empty string.
You can use regex str.replace(/(&#\d+;)/g,"") to remove these characters

var str = '(Multivitamin Gummies - Berry, Peach & Orange - 150ct - Up&Up™)';
console.log(str.replace(/(&#\d+;)/g,""));

str = '(Aloe Hand Sanitizer Gel - 8 fl oz - Up&Up™) ';
console.log(str.replace(/(&#\d+;)/g,""));


text:
Q: Is there a name for this design pattern, using hooks/callbacks? I've seen/used some objects that have a structure like so, designed to let children extend the functionality of functions without having to override them. Is there a name for this pattern?
code example:
class CrudModel {
  public function create($data) {
    $data = $this->pre_create($data);
    //create logic
  }

  public function delete($data) {
    $data = $this->pre_delete($data);
    //delete logic
  }

  protected function pre_create($data) { //empty }
  protected function pre_delete($data) { //empty }

}

class SpecificCrudModel extends Model {
    protected function pre_create($data) {
      //custom logic for this object.
    }

}

A: It looks like a template method pattern, but the methods in question are not abstract and the child class is not being forced to implement them. I'd say it's just a common use of inheritance or maybe a borderline template method pattern.
I'd rather implement such things via events/delegates/callbacks, though. It is much clearer then what you can hook up to and you can't accidentally override necessary behaviour. It's also more flexible.

@GSto
Here's an example of using callbacks with PHP. It's not as elegant as in other languages with native event support (like C# offers for example), but it's flexible and you can register such callbacks in the constructor of a child class for example. This website here told me how to implement callbacks in PHP, the heart of it is the call_user_func function of PHP. This can register as many handlers as you like and anything with a reference to the object can register handlers.
class Model {

    protected $_before_create_callbacks = array();
    protected $_after_create_callbacks = array();

    function register_before_create_handler($callback) {
        $this->_before_create_callbacks[] = $callback;
    }

    function register_after_create_handler($callback) {
        $this->_after_create_callbacks[] = $callback;
    }

    function create(){
        $this->before_create();

        //logic of create...

        $this->after_create();
    }

    protected function before_create() {
        foreach ($this->_before_create_callbacks as $callback){
            call_user_func($callback);
        }
    }

    protected function before_create() {
        foreach ($this->$_after_create_callbacks as $callback){
            call_user_func($callback);
        }
    }
}

function someFunction(){
    logSomething();
}

$anyModel->register_before_create_handler("someFunction");

A: This looks like a pretty standard case of any inheritance-based model, depending on how you use it.  It's pretty common to put any implementation specific code in virtual functions in an abstract parent, and to implement them in a child class.
This is literally the exemplar case in c++;  it looks like you're using PHP, here, and this is definitely the preferred method.  Much easier to follow than using callbacks. If you're using this in an MVC framework (Or building one) you might want to prepend a '_' to the setup utility call.


text:
Q: Get generic type of a class extends from a none generic type class I have a class like this
public class RequestDataEditor<T> extends PropertyEditorSupport {
    @Override
    public void setAsText(String text) {

        MyData<T> value;

        try {
            //(ParameterizedType)getClass().getGenericSuperclass()

            value = JacksonUtil.parse(text, new TypeReference<MyData<T>>() {
            });
        } catch (Exception e) {
            value = null;
        }

        setValue(value);
    }
}

When I run (ParameterizedType)getClass().getGenericSuperclass(),
expect to be T, but it's PropertyEditorSupport, and can't be casted to ParameterizedType;
If i remove the extends PropertyEditorSupport, then i can get the generic type.(Proved to be wrong, i made a mistake here.)
It seems that, we can't use (ParameterizedType)getClass().getGenericSuperclass() to get generic type from a class whose parent has no generic type.
So how can I get the generic type with such a class like RequestDataEditor?
not duplicate with the question, I want to know what's the different when use (ParameterizedType)getClass().getGenericSuperclass() with a class has a none generic type super class.

A:
When I run (ParameterizedType)getClass().getGenericSuperclass(),
  expect to be T, but it's PropertyEditorSupport, and can't be casted to
  ParameterizedType;

If you want to have access to the T aka the type-parameter, the appropriate reflection method is Class.getTypeParameters.
// Test.java:
class Generic<T> {
}

class Main {

  public static void main(String[] args) {

     final Generic<Integer> gint1 = new Generic<Integer>();

     System.err.println("gint1's type-parameter: "
                       + gint1.getClass().getTypeParameters()[0]);
  }
}

If you run the code above you get the following:
$ javac Test.java
$ java Main
gint1's type-parameter: T

Notice that the type parameter is not resolved as Integer but as T since this information in not available at run-time.
If access to this information is important for you, then you have two straight forward options.
A. the object contains a reference to the actual type class:
class Generic<T> {

    public final Class<T> type;

    public Generic(Class<T> type) {
        this.type = type;
    }

    public Class<T> type() {
        return type;
    }
}

class Main {
    public static void main(String[] args) {

        final Generic<Integer> gint2 = new Generic<>(Integer.class);
        System.err.println("gint2's type-parameter: " + gint2.type().getSimpleName());
    }
}
// Output will be "gint2's type-parameter: Integer".

B. You create a subclass that gives a concrete class for that type-parameter:
import java.lang.reflect.*;

class Generic<T> {
}

class IntegerGeneric extends Generic<Integer> {
}

class Main {
    public static void main(String[] args) {

        final Generic<Integer> gint3 = new IntegerGeneric();
        final Generic<Double> gint4 = new Generic<Double>() {};
        System.err.println("gint3's type-parameter: "
            + ((ParameterizedType)gint3.getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
        System.err.println("gint4's type-parameter: "
            + ((ParameterizedType)gint4.getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
    }
}
// Output:
// gint3's type-parameter: class java.lang.Integer
// gint4's type-parameter: class java.lang.Double

Notice that gint4 class is not Generic<Double> but at anonymous inner class that extends it due to the {} following the constructor... this is an alternative to a full class DoubleGeneric ... declaration.
Of these two alternatives, A. and B., A. is preferable as in general one should avoid to rely on reflection; amongst other things it is more prone to hide run-time errors and the code is more difficult to maintain.

I want to know what's the different when use
  (ParameterizedType)getClass().getGenericSuperclass() with a class has
  a none generic type super class.

If you look-up the Type documentation, the class of the reference returned by this methods, it indicates that it is an "umbrella" super-interface for all object/data types available in the Java language including even primitives ... so for a class that does not have a generic superclass I guess it would return a subclass of type that reflect that...
A quick experiment reveals that in fact it would return a 'Class' object so it would be equivalent to to getSuperclass().
Perhaps others can give a more informed perspective on this, but I think this might have been a bit of a misnaming ... I think getSuperType() or something like that would have been more appropriate. Perhaps initially it only supported generics in an older Java version (1.5?) and eventually was extended to cover other data types but this is a wild guess of mine without looking into its history.

A: The (ParameterizedType)getClass().getGenericSuperclass() will get the super class of your current class which is not a generic one. You want the generic type of the current class and not its super class. In your example this will be impossible because this data is no longer available at run time. A possible solution could be:
public class RequestDataEditor<T> extends PropertyEditorSupport {

    private final Class<T> genericType;

    public RequestDataEditor(Class<T> genericType) {
        this.genericType = genericType;
    }

    @Override
    public void setAsText(String text,  ) {

        MyData<T> value;

        try {
            //use genericType here

            value = JacksonUtil.parse(text, new TypeReference<MyData<T>>() {
            });
        } catch (Exception e) {
            value = null;
        }

        setValue(value);
    }
}

I know this isn't exactly what you try to achieve but it's the closest you can get (to my knowledge).


text:
Q: How to improve SQL execution query plan for script below I have a slow SQL query which execution plan run mainly on "index scan". I had added index to it which have help improve it to be "index seek". But out of 2 of the index (ixDocQueue_For_C_DocQueueDocManager and ixDocQueueFiles_For_C_DocQueueDocManager), it still using "index scan" rather that "index seek". May I know how can I improve it?
This is the query
SELECT dbo.docqueue.description,
       dbo.docqueue.doccode,
       dbo.docqueue.doctype,
       dbo.docqueue.generated,
       CASE
         WHEN dbo.docqueue.doctype BETWEEN 50 AND 54 THEN 'Word'
         WHEN ( dbo.docqueue.doctype BETWEEN 60 AND 64 )
               OR dbo.docqueue.doctype = 2108 THEN 'Excel'
         WHEN dbo.docqueue.doctype = 55 THEN 'Xml'
         WHEN dbo.docqueue.doctype = 90 THEN 'PDF'
       END                           AS DocumentType,
       CASE dbo.docqueue.generated
         WHEN 0 THEN 'Pending'
         WHEN 1 THEN 'Completed'
         WHEN 2 THEN 'Error'
         WHEN 3 THEN 'In Progress'
       END                           AS Status,
       CASE
         WHEN dbo.docqueue.generated = 0
               OR dbo.docqueue.generated >= 2 THEN dbo.docqueue.keycode
         WHEN dbo.docqueue.generated = 1 THEN dbo.docqueuefiles.mfcode
       END                           AS KeyCode,
       dbo.docqueue.dateenter,
       dbo.docqueuefiles.dixdocnr,
       dbo.docqueue.ucode,
       dbo.docqueue.docnumber,
       dbo.docqueue.machinename,
       dbo.docqueue.repoption,
       dbo.docqueue.reporttags,
       dbo.docqueue.docsel,
       dbo.docqueue.docext,
       dbo.docindex.foldernr,
       dbo.docindex.dateindex,
       dbo.docindex.docnr,
       dbo.docindex.docdate,
       dbo.docindex.confrank,
       dbo.docindex.mfnumber,
       dbo.docindex.docstatus,
       dbo.docindex.docorigin,
       dbo.docindex.keywords,
       dbo.docindex.note,
       dbo.docindex.ucodeupdate,
       dbo.docindex.storestatus,
       dbo.docindex.procstatus,
       dbo.docindex.numfiles,
       dbo.vpuser.uname,
       dbo.reflabels.NAME,
       dbo.docqueuefiles.markdelete,
       dbo.docqueuefiles.docfilenr,
       dbo.docqueuefiles.dateentered AS DateUpdated,
       dbo.docqueuefiles.filename,
       dbo.docqueuefiles.docfileid,
       dbo.doccheckout.cuser,
       dbo.doccheckout.cpath,
       dbo.doccheckout.cdatetime,
       dbo.doccheckout.machinename   AS CMachineName
FROM   dbo.doccheckout
       RIGHT OUTER JOIN dbo.docqueuefiles
                     ON dbo.doccheckout.docfileid = dbo.docqueuefiles.docfileid
                        AND dbo.doccheckout.cstatus = 1
       RIGHT OUTER JOIN dbo.docqueue
                     ON dbo.docqueuefiles.docnumber = dbo.docqueue.docnumber
                        AND dbo.docqueuefiles.doctype = dbo.docqueue.doctype
       LEFT OUTER JOIN dbo.vpuser
                    ON dbo.docqueue.ucode = dbo.vpuser.ucode
       LEFT OUTER JOIN dbo.docindex
                    ON dbo.docqueuefiles.dixdocnr = dbo.docindex.docnr
       LEFT OUTER JOIN dbo.reflabels
                    ON dbo.reflabels.code = ( CASE
                                                WHEN dbo.docqueue.generated = 0
                                                      OR dbo.docqueue.generated
                                                         >= 2
                                              THEN
                                                dbo.docqueue.keycode
                                                WHEN dbo.docqueue.generated = 1
                                              THEN
                                                dbo.docqueuefiles.mfcode
                                              END )

This is the index that still run on index scan,
CREATE INDEX ixDocQueueFiles_For_C_DocQueueDocManager ON DocQueueFiles
(
docfileid,
docnumber,
doctype,
dixdocnr,
mfcode
)
include
(
markdelete,
docfilenr,
dateentered,
filename
)

CREATE INDEX ixDocQueue_For_C_DocQueueDocManager ON DocQueue
(

docnumber,
doctype,
ucode,
generated,
keycode
)
INCLUDE
(
description,
doccode,
dateenter,
machinename,
repoption,
reporttags,
docsel,
docext
)

This is the execution plan. (on test environment, the statistic may not be accurate)
https://www.brentozar.com/pastetheplan/?id=HyXvD-GJ5


text:
Q: JS Jquery Removing hyphen from search/filter input (numbers only) I have a search input field with some connected javascript that I use as a filter on my page. It basically takes the input and searches in a h3 tag for the  name and description but then also searches a table (specifically the tbody -> tr) and if a row doesn't contain a match it hides it.
I've come to one problem with the contents of the table body/rows. Each row has a number, usually 6 digits with a hyphen after 4, but not always (1234-56, 9876-54, etc.).
The problem is: If you search the numbers with the hyphen, it filters properly and only shows that number but if you just type the 6 digits with no hyphen it hides everything since it didn't technically find a match due to it searching exact strings.
I've found a few methods of doing this but they only apply to the filter variable, but I need some help with this even if it's just a small workaround. Basically, when looking in the tbody/tr for a match, I need it to ignore the hyphen. So whether I type 123456 or 1234-56, it will show only the rows that have 1234-56 for the match. I hope that makes sense.
The Javascript:
<script type = "text/javascript">
$(document).ready(function(){
$("#srch-term").keyup(function(){
//For entered search values
// Retrieve the input field text and reset the count to zero
var filter = $(this).val(), count = 0;
var search_regex = new RegExp(filter, "i");

// Loop through the main container as well as the table body and row that contains the match
$(".group-container").each(function(){
    //check if filter matches the group name or description
    var group_name = $(this).children('h3').text()
    var group_description = $(this).children('.uk-text-muted').text()

    if(group_name.search(search_regex)>=0 || group_description.search(search_regex)>=0){ // filter matches
        $(this).show() // show group
        $(this).find("tbody tr").show() // and all children
        return // skip tr filtering
    }

    var no_matches = true

    $(this).find("tbody tr").each(function(){

        // If the list item does not contain the text phrase fade it out
        if ($(this).text().replace('Available','').search(search_regex) < 0) {
            $(this).hide();

        // Show the list item if the phrase matches and increase the count by 1
        } else {
            $(this).show();
            count++;
            no_matches = false
        }
    });

    if(no_matches){ // if no tr matched the search either, hide whole group
        $(this).hide();
    }

    });
  });
});
</script>

A:
If you search the numbers with the hyphen, it filters properly and
  only shows that number but if you just type the 6 digits with no
  hyphen it hides everything since it didn't technically find a match
  due to it searching exact strings.

If you only want to do digit based search then remove the non-digit characters from your grid's text while for comparison using
.replace(/\D/g, "");

and make it
var group_name = $(this).children('h3').text().replace(/\D/g, "");
var group_description = $(this).children('.uk-text-muted').text().replace(/\D/g, "");

and later
if ($(this).text().replace(/\D/g,'').search(search_regex) < 0) {
        $(this).hide();
 }


text:
Q: есть ли примеры разработки многопоточного GUI? Делаю GUI движок для игры на SFML, и я хочу GUI запихнуть в отдельный поток, чтобы он не мешал потоку логики игры.
Есть ли паттерны для разработки GUI? MVC, MVVM рассматриваю, но это довольно древние паттерны.


text:
Q: Calling of c# function using Ajax Javascript on asp:Button click , is not working I am using below code to check that if the value I am entering in Tetxbox already exist in Database, then show an alert "value already exist". For this I am using Ajax Javascript on asp:Button ("Save") click:
Ajax Javascript:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("[id*=btnBar]").bind("click", function () {

                alert("helloooo");

                var chk = {};
                chk.requestID = $("[id*=lblGuidId]").text();
                alert(chk.requestID);
                chk.barCode = $("[id*=txtBar]").val();
                alert(chk.barCode);

                $.ajax({
                    type: 'POST',
                    url: "Demo.aspx/SaveUser",
                    data: '{chk: ' + JSON.stringify(chk) + '}',
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    success: function (data) {

                    var val = data.isUserInserted;
                    alert(val);

                    if (val == true) {
                        alert("Barcode No. alredy exist");
                        window.location.reload();
                    }
                    else {
                        alert("Barcode No. does not exist");
                    }
                },
                error: function (data) {
                    alert("error" + data);
                },
                });
                return false;

                alert("End click");
            });
        });
    </script>

HTML code:
<asp:Label ID="lblGuidId" runat="server" Text='<%# Bind("RequestID") %>'></asp:Label>
<asp:TextBox ID="txtBarcodeNumber" runat="server" MaxLength="11" Width="230px" Text='<%# Bind("BarcodeNo") %>' Display="None" OnTextChanged="TextChanged" AutoPostBack="true"></asp:TextBox>
<asp:Button ID="btnBar" runat="server" Text="Save"/>

c# Code:
public class Check
{
    public Guid? requestID { get; set; }
    public string barCode { get; set; }
}

[WebMethod]
[ScriptMethod]
public static bool SaveUser(Check chk)
{
    bool isUserInserted = false;

    string strcon = ConfigurationManager.ConnectionStrings["MasterDB"].ConnectionString;
    SqlConnection con = new SqlConnection(strcon);
    using (SqlCommand cmd = new SqlCommand("Invoice.usp_tbl_Request_Select_CheckDuplicateBarcode_Test", con))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@RequestID", chk.requestID);
        cmd.Parameters.AddWithValue("@BarcodeNo", chk.barCode);
        cmd.Connection = con;
        con.Open();
        isUserInserted = Convert.ToBoolean(cmd.ExecuteScalar());
        con.Close();
    }
    return isUserInserted;
}

but everytime it goes into else , if data exist in database then also it goes into else part. Here, I want to check that If c# WebMethod bool isuserInserted is returning true then it should prompt alert "already exist" else if c# WebMethod bool isuserInserted is returning false then it should prompt alert "does not exist".
Please reply what is missing in my code.
Please note that I am first time using this Ajax Javascript.

A: Some versions of the .net need you to add a datafilter to ensure it gets the right thing:
Note use data.d is ok but this (dataFilter) makes it version proof so that it works either way and you don't have to change code when you update/upgrade your version on the server side.
This will do that:
dataFilter: function(data)
        {
            var msg;
            if (typeof (JSON) !== 'undefined' &&
            typeof (JSON.parse) === 'function')
                msg = JSON.parse(data);
            else
                msg = eval('(' + data + ')');
            if (msg.hasOwnProperty('d'))
                return msg.d;
            else
                return msg;
        },

SO your code for the ajax call would look like:
$.ajax({
    type: 'POST',
    url: "Demo.aspx/SaveUser",
    data: '{chk: ' + JSON.stringify(chk) + '}',
    contentType: 'application/json; charset=utf-8',
    dataFilter: function (data) {
        var msg;
        if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function') msg = JSON.parse(data);
        else msg = eval('(' + data + ')');
        if (msg.hasOwnProperty('d')) return msg.d;
        else return msg;
    },
    dataType: 'json',
    success: function (data) {

        var val = data.isUserInserted;
        alert(val);

        if (val == true) {
            alert("Barcode No. alredy exist");
            window.location.reload();
        } else {
            alert("Barcode No. does not exist");
        }
    },
    error: function (data) {
        alert("error" + data);
    },
});

A: First check the value of alert(val) if that is returning true.
Then you use === for equality which is check value and data type as well or you parse the value val to Boolean.

A: Use
var val = data.d instead of var val =  data.isUserInserted.
it will be work.


text:
Q: Matlab: find major axis of binary area the output of some processing consists of a binary map with several connected areas.
The objective is, for each area, to compute and draw on the image a line crossing the area on its longest axis, but not extending further. It is very important that the line lies just inside the area, therefore ellipse fitting is not very good.
Any hint on how to do achieve this result in an efficient way?

A: If you have the image processing toolbox you can use regionprops which will give you several standard measures of any binary connected region. This includes
You can also get the tightest rectangular bounding box, centroid, perimeter, orientation. These will all help you in ellipse fitting.
Depending on how you would like to draw your lines, the regionprops function also returns the length for major and minor axes in 2-D connected regions and does it on a per-connected-region basis, giving you a vector of axis lengths. If you specify 4 neighbor connected you are fairly sure that the length will be exclusively within the connected region. But this is not guaranteed since `regionprops' calculates major axis length of an ellipse that has the same normalized second central moment as the connected region.

A: My first inclination would be to treat the pixels as 2D points and use principal components analysis. PCA will give you the major axis of each region (princomp if you have the stat toolbox).
Regarding making line segments and not lines, not knowing anything about the shape of these regions, an efficient method doesn't occur to me. Assuming the region could have any arbitrary shape, you could just trace along each line until you reach the edge of the region. Then repeat in the other direction.
I assumed you already have the binary image divided into regions. If this isn't true you could use bwlabel (if the regions aren't touching) or k-means (if they are) first.


text:
Q: Resharper suddenly gone from Visual studio 2013 I have Resharper 8.2 installed on my computer. I didn't shut down the computer from yesterday and Visual studio 2013 was kept open.
Yesterday, I had Resharper working fine and today, it's gone. I don't have the menu "Resharper" on the top and I don't have the tool at all.
So be it. I reinstalled Resharper from the exe file. Nothing.
I deleted Resharper, cleaned all the files and installed it once more. Nothing in VS 2013.
I also have Visual Studio 2010 and Resharper is here (I have the menu and the tools).
Am I the only one experiencing this "feature"? Does anyone know how to solve this?
I don't know what to try.


text:
Q: Remove outliers based on a preceding value How to remove outliers using a criterion that a value cannot be more than 2-fold higher then its preceding one.
Here is my try:
x<-c(1,2,6,4,10,20,50,10,2,1)

remove_outliers <- function(x, na.rm = TRUE, ...) {
  for(i in 1:length(x))
  x < (x[i-1] + 2*x)
  x
}

remove_outliers(y)

expected outcome: 1,2,4,10,20,2,1
Thanks!

A: I think the first 10 should be removed in your data because 10>2*4. Here's a way to do what you want without loops. I'm using the dplyr version of lag.
library(dplyr)
x<-c(1,2,6,4,10,20,50,10,2,1)
x[c(TRUE,na.omit(x<=dplyr::lag(x)*2))]
[1]  1  2  4 20 10  2  1

EDIT
To use this with a data.frame:
df <- data.frame(id=1:10, x=c(1,2,6,4,10,20,50,10,2,1))
df[c(TRUE,na.omit(df$x<=dplyr::lag(df$x,1)*2)),]

   id  x
1   1  1
2   2  2
4   4  4
6   6 20
8   8 10
9   9  2
10 10  1

A: A simple sapply:
bool<-sapply(seq_along(1:length(x)),function(i) {ifelse(x[i]<2*x[i-1],FALSE,TRUE)})

 bool
[[1]]
logical(0)

[[2]]
[1] TRUE

[[3]]
[1] TRUE

[[4]]
[1] FALSE

[[5]]
[1] TRUE

[[6]]
[1] TRUE

[[7]]
[1] TRUE

[[8]]
[1] FALSE

[[9]]
[1] FALSE

[[10]]
[1] FALSE

resulting in:
x[unlist(bool)]
[1]  1  2  4 10 20  1


text:
Q: Issues Parsing XML File Using xpathSApply, R v3.1.1, XML v3.98-1.1 I'm attempting the parse the following XML file in R: http://reports.ieso.ca/public/GenOutputCapability/PUB_GenOutputCapability_20140517_v24.xml
My script is dead simple so far:
file <- "http://reports.ieso.ca/public/GenOutputCapability/PUB_GenOutputCapability_20140517_v24.xml"
doc <- xmlTreeParse(file, useInternal=TRUE)
rootNode <- xmlRoot(doc)
xpathSApply(rootNode, "//GeneratorName", xmlValue)

Whenever I run this, my output is simply an empty list.
Using this for other XML files, I can extract values no problem, but for this particular file, I can't extract anything. I've tried a number of different nodes, capitalizations, using useInternal=FALSE, and any other combination of things I could, but still no luck.
I can access parts using the rootNode[["IMODocBody"]][["Date"]] syntax to get the date, for example, so I know the file is loaded. Any ideas?

A: You need to use the appropriate namespace:
> head(xpathSApply(doc, "//ns:GeneratorName", xmlValue
                   , namespaces = c(ns = "http://www.theIMO.com/schema")))
[1] "BRUCEA-G1" "BRUCEA-G2" "BRUCEA-G3" "BRUCEA-G4" "BRUCEB-G5" "BRUCEB-G6"

see ?xmlNamespaceDefinitions
> xmlNamespaceDefinitions(doc)
[[1]]
$id
[1] ""

$uri
[1] "http://www.theIMO.com/schema"

$local
[1] TRUE

attr(,"class")
[1] "XMLNamespaceDefinition"

$xsi
$id
[1] "xsi"

$uri
[1] "http://www.w3.org/2001/XMLSchema-instance"

$local
[1] TRUE

attr(,"class")
[1] "XMLNamespaceDefinition"

attr(,"class")
[1] "XMLNamespaceDefinitions"


text:
Q: How do I add the bible.org widget to my site? I hope everyone is having a good day.
I am working with the bible.org API to create a learning app for the bible.
bible.org gives the option to input their widget on your own website.
When you finish creating your widgets they give you this:
Paste the following code into your website or blog.

BIBLESEARCH.widget({
    "background": "FFFFFF",
    "color": "E2615C"
});

I am using Reactjs and would like to implement it in my Header component.
I provided an example of my H

import React from 'react';
import {startNewBookAction} from '../Actions/index';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';

import {Link} from 'react-router-dom';
import axios from 'axios';
import {bibleBooks} from '../../data/bibleBooks';

class Header extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            book:"Genesis"
        };
    }//end of constructor

    handleNewBook() {
        let userBook = this.state.book;
        console.log('The book chosen by the user', this);
        this.props.startNewBookAction(userBook)

    }//handleNewBook

    handleLogout() {
        console.log('loging out..');
        axios.delete('/login').then(res => {
            console.log('back from the server with', res);
            window.location = "/?#/user";
        })
    }//end of handleLogout

    showBibleBooks() {
        //displays the option tag for every book in the bible
        console.log('showing the books');
        let books = bibleBooks;
        return(

                    books.map((b, id) => {
                        return (
                            <option value={b} key={id}>{b}</option>
                        );
                    })
        );//end of return
    }//end og showBibleBooks

    start() {
        console.log('start', this)
    }//end of start

    render() {
        return (

BBS

                        Logout
                        New Book

                                <button type="button" className="close" data-dismiss="modal">×</button>
                                <form onSubmit={this.handleNewBook.bind(this)}>

New Book

                                    Book:
                                    <select name="book"  id="" onChange={event => this.setState({book:event.target.value})}>
                                        {this.showBibleBooks()}
                                    </select>
                                    <input type="button" value="Start0" onClick={this.start.bind(this)}/>
                                </form>

                                <button type="button" className='btn btn-success'  data-dismiss="modal" id="signupSubmit" onClick={this.handleNewBook.bind(this)}> Enter</button>

        );
    }//end of render

}//end of classNameName

function mapDispatchToProps(dispatch) {
    return bindActionCreators({
        startNewBookAction

    },
     dispatch)
}

function mapStateToProps(state) {
    return {
        newBook:state
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Header);

eader component. How can I implement this widget in my app.

A: Try to add after constructor:
componentWillMount () {
    const script = document.createElement("script");
    script.src = "//bibles.org/widget/client";
    script.async = true;
    document.body.appendChild(script);
}


text:
Q: What value should be passed in universalLink? When I try to integrate WeChat Login in my iOS app using swift language, I am getting an error message on the simulator screen.

I am following integration steps from this link.
I also have a query about the universal link which is needed for register app in AppDelegate like:
WXApi.registerApp("-------I HAVE IT-----", universalLink: "")

what should I pass in universalLink?

A: https://developers.weixin.qq.com/doc/oplatform/Mobile_App/Access_Guide/iOS.html
You should configure your own universal link to access to your application.


text:
Q: 06-Conditional Branching Create a program with medialib to draw a dice face from an inputted number:

*

*use the input function to get the user input of an integer number (expected to be 1 to 6), after showing a prompt string like "Input an integer (1-6): "

*Create and call a function to draw the dice face according to the inputted number (n)
When n is 1, 2, ..., 6 draws dice1.png,.......,dice6.png
when n is out of the range (1-6), print a string like "Out of range!" and draw dice0.png


text:
Q: How to detect arrow keys at then time of datagridviewcell editing Not able to detect arrows key. I understand that it's the default behavior of datagridview cell for moving focus to next/previous/up/down. I googled a lot about this topic but didn't find the exact solution.
Here is my code.
private void dgvHP_OPDPrescriptionDiagnosis_Detail____EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    switch (dgvHP_OPDPrescriptionDiagnosis_Detail___.CurrentCell.ColumnIndex)
    {
        case 9:
            TextBox txtDiagnosis = e.Control as TextBox;
            if (txtDiagnosis != null)
                 txtDiagnosis.KeyDown += new KeyEventHandler(DiagnosisKeyDown);
            break;
    }
}

private void DiagnosisKeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyData == Keys.Down)
    {
         MessageBox.Show("Hi");
    }
}

A: Hope it solve your purpose
Link : https://social.msdn.microsoft.com/Forums/en-US/a7e1bfa5-af91-4594-bc39-6b9000af95b4/how-to-detect-arrow-keys-in-a-textbox?forum=winforms
Make your own DataGridView control override the ProcessKeyPreview event as:
class dgv : DataGridView

    {

        protected override bool ProcessKeyPreview(ref Message m)

        {

            KeyEventArgs args1 = new KeyEventArgs(((Keys)((int)m.WParam)) | Control.ModifierKeys);

            switch (args1.KeyCode)

            {

                case Keys.Left:

                case Keys.Right:

                case Keys.Up:

                case Keys.Down:

                    return false;

            }

            return base.ProcessKeyPreview(ref m);

        }

    }

Use this inherited control in your project, you will able to make arrow keys work normally in the textbox.


text:
Q: how to update the state using the redux I need to update the state using react redux.
I can add, delete an article by ID but I tackle with implementing EDIT action
This is my reducer file:
const initialState = {
    articles : [
        { title: 'Article 1', id: 1, content: 'Description'},
        { title: 'Article 2', id: 2, content: 'Description 2'},
        { title: 'Article 3', id: 3, content: 'Description 3'}
    ]
}
function rootReducer(state = initialState, action) {
    switch (action.type) {
        case ADD_ARTICLE: {
            return {
                ...state,
                articles: [...state.articles, action.payload]
            }
        }
        case DELETE_ARTICLE: {
            return {
                ...state,
                articles:  state.articles.filter(i => i.id !== action.payload)
            }
        }
        case EDIT_ARTICLE: {
            const artToEdit = state.articles.find(i => i.id == action.payload)
            return {
                ...state,
                articles:  [...state.articles, ]
            }
        }
    }
    return state
}

export default rootReducer

And this is a component where we can display a list of articles, edit and delete them
const List = ({ articles,  deleteArticle}) => {
return(
    <Container>

List of articles

            { articles.map(el => (

{el.title}

                        {el.content}

                <Button variant="primary" onClick={() => editArticle(el.id)} >
                    Delete
                </Button>
                <Button variant="success" onClick={() => deleteArticle(el.id)} className='ml-3'>
                    Edit
                </Button>

            ))}

        <FormArticle />
    </Container>
)

}

A: case EDIT_ARTICLE: {
   const artToEdit = state.articles.find(i => i.id == action.payload);
   const articles = [...state.articles];
   articles[artToEdit] = // Here you set the data just like you want
   return {
     ...state,
     articles
   }
}

Some observations:
1- In your example, the delete button is dispatching edit action and the edit button is dispatching delete action.
2- I would save a map with id -> article instead of array to improve performance.


text:
Q: How Can I Enhance CSS Value Regularly? it is My button.
<button onclick="myFunction()">Click me</button

and it is script..
function myFunction(){
 document.getElementById("x").style.marginLeft = +35 ;
}

when I push the Button, element x moving but the second push is not working.

A: You are just setting the marginLeft to the number 35. It is not adding 35 to the margin. marginLeft also needs a unit. So you need to say whatever the unit is.
So you need to read the current value, remove the units, and add the new value, and then set the new value.

function myFunction(){
 var elem = document.getElementById("x");
 var current = Number(elem.style.marginLeft.replace("px", ''));
 elem.style.marginLeft = (current + 35) + "px" ;
}
#x {
  margin-left: 0px;
}
<button id="x" onclick="myFunction()">Click me</button>

A: try this
function myFunction(){
 let el = document.getElementById("x");
 el.style.marginLeft = Number(el.style.marginLeft.replace("px", "")) + 35 + "px" ;
}


text:
Q: Failure to initialize a AVAudioCompressedBuffer I'm trying to initialize an AVAudioCompressedBuffer using this format:
<AVAudioFormat 0x2818944b0:  2 ch,  48000 Hz, '.mp3' (0x00000000) 0 bits/channel, 0 bytes/packet, 1152 frames/packet, 0 bytes/frame>

like such:
AVAudioCompressedBuffer* compressedBuffer = [[AVAudioCompressedBuffer alloc] initWithFormat:format
                                                                             packetCapacity:NUM_AQ_BUFS];

But I'm getting this exception:
Thread 1: "required condition is false: maximumPacketSize != 0"

What am I missing?
Thanks

A: You're using the wrong initializer. The header file for [AVAudioCompressedBuffer initWithFormat:packetCapacity:] says

This fails if the format is PCM or if the format has variable bytes per packet (format.streamDescription->mBytesPerPacket == 0).

and as you can see from the format, you have 0 bytes/packet.
Use -[AVAudioCompressedBuffer packetCapacity:maximumPacketSize:] instead
AVAudioCompressedBuffer* compressedBuffer = [[AVAudioCompressedBuffer alloc] initWithFormat:format packetCapacity:NUM_AQ_BUFS maximumPacketSize: 1024];

tbh I don't know what the maximum packet size for mp3 should be. Apparently it's 144 bytes. You can query this with AudioCodecGetPropertyInfo() + kAudioCodecPropertyMaximumPacketByteSize or derive it from your own packet stream.


text: Q: How is this site still using Facebook events API? I came across this site https://london.carpe-diem.events that allows you to add events, and scrapes events from Facebook without even requiring a login. How does it do that? I heard it was impossible! I tried to inspect all the code but I'm drawing blanks.


text:
Q: Как автоматизировать классифицирование текста? Имеется список обращений, каждый из которых представляет собой осмысленный текст. Каждому обращению необходимо задать маркер (тег), классифицировать: жалоба, похвала, ругательство и так далее.
Сейчас это все делается вручную. Хотелось бы автоматизировать этот процесс. Полагаю, что возможно это сделать с помощью машинного обучения.
Может кто-то из присутствующих сталкивался с такой или похожей задачей?

A: Ну у вас же часть данных уже размечена, я так понимаю? То есть есть на чём попробовать "обучение с учителем". На первый прикид даже "мешок слов" подойдёт, то есть CountVectorizer. Дальше надо пробовать TF-IDF, а потом уже всякие эмбеддинги Word2vec. Для текстов, кстати, быстрые и простые вероятностные модели вроде MultinomialNB неплохо работают.
Главное сделать некоторый бейзлайн, а потом его можно улучшать:

*

*чистить мусорные слова/символы

*пробовать разные варианты токенизации: отдельные слова/сочетания слов, стемминг/лемматизация, приводить всё в один регистр или не нужно

*пробовать разные варианты векторизации подготовленных текстов: мешок слов, tf-idf, word2vec, doc2vec, fasttext

*пробовать разные модели, на ваших данных может взлететь разное, как минимум надо пробовать байесовские модели, деревянные модели, бустинги, нейросети; если данных много, то что-то из моделей может не пролезть по времени/памяти, так что процесс творческий

Там ещё есть разные тонкости. Если не знаете вообще как начать, я поищу ссылки, но можно погуглить text classification, наверняка вылезет много примеров, в частности на каггле.

A: Да, это классическая задача машинного обучения. И как для почти всех задач машинного обучения, решающую роль играет качество данных, поданных на вход модели классификатору.
Какие данные вам понадобятся для обучения и проверки модели:

*

*список обращений

*заранее проставленный экспертом вручную тег

Далее делается предобработка текста. Практически все известные мне модели машинного обучения требуют на вход числовые матрицы. Соответственно сначала нужно будет получить такие матрицы. Конкретные детали векторизации текста будут зависеть от выбранного алгоритма классификации.
PS здесь можно посмотреть примеры использования различных алгоритмов классификации текстов для определения эмоциональной оценки комментариев.


text:
Q: Not finding request id in aws cloud trail I am trying to debug a pipeline failing one of its action with an error 403.
I am reaching cloud trail to find more detail about the action, but I can not find the event linked to the request. When I search in cloud trail for the request id, it gives me nothing.
I am in only one region and only one account.
I believe all action are supposed to be log into cloud trail, specially the one with error, am I wrong?
Do I need to configure some service to actually turn on event sent to cloud trail?
Am I missing something?

A: CloudTrail is not a tool used for troubleshooting. Essentially it's an auditing tool that records changes to resources in your AWS accounts.
What is your pipeline built on? If it's on CodePipeline, you should be able to view the details on the console, and you can configure to send the pipeline logs to CloudWatch. Additionally, CloudTrail should record the API calls made by CodePipeline as well, although it may not be detailed enough to actually troubleshoot an error - https://docs.aws.amazon.com/codepipeline/latest/userguide/monitoring-cloudtrail-logs.html


text:
Q: PASSPORT AUTHENTICATION USING EXPRESS NOT RESPONDING I am trying to use passport authentication using nodejs and mongodb,
below is the code, what I have tried, not getting any response for this.
Its not even entering the findOrCreate method.
I am using nodejs v: 10.16.3, npm v: 6.9.0
mongodb version:4.2.0 and Operating system is MAC OS Mojave.
Here is the list of dependencies-
"dependencies": {
    "body-parser": "^1.19.0",
    "connect-flash": "^0.1.1",
    "cookie-parser": "^1.4.4",
    "express": "^4.17.1",
    "express-session": "^1.16.2",
    "flash": "^1.1.0",
    "http": "0.0.0",
    "mongo": "^0.1.0",
    "mongodb": "^3.3.2",
    "mongoose": "^4.3.5",
    "mysql": "^2.17.1",
    "passport": "^0.4.0",
    "passport-local": "^1.0.0"
  }

The passport code is as followed-
 app.post("/signup",(req,res)=>{
    console.log("Inside Signup",req.body);
    res.send(req.body);
    var emails=req.body.Email;
    console.log(emails);
    var names=req.body.Name;
    console.log(names);
    var passwords=req.body.Password;
   console.log(passwords);
    si(names,emails,passwords);
  });
 function si(username,email,password){
      passport.use('signup', new LocalStrategy({
        passReqToCallback : true
      },
      function(req, username, password, done) {
        findOrCreateUser = function(){
          // find a user in Mongo with provided username
    console.log("Step1 success");
          console.log(username);
          console.log(email);
          console.log(password);
          var dbo = db.db("record");
          dbo.collection("records").findOne({'Username':username}, function(err, result) {
            if (err){
              console.log('Error in SignUp: '+err);
              return done(err);
            }
            // already exists
            if (result) {
              console.log('User already exists');
              return done(null, false,
                 req.flash('message','User Already Exists'));
            } else {
              var newUser = new User();
              newUser.Username = username;
              newUser.Password = password;
              newUser.Email = email;
              newUser.save(function(err) {
                if (err){
                  console.log('Error in Saving user: '+err);
                  throw err;
                }
                console.log('User Registration succesful');
                return done(null, newUser);
              });
            }
          });
        };

        // Delay the execution of findOrCreateUser and execute
        // the method in the next tick of the event loop
        process.nextTick(findOrCreateUser);
      }))
};

Can anyone suggest, how I can make it work?

A: Try creating the user by passing an object to the constructor instead of changing the properties individually.
newUser = new User({ username: username, email: emal, password: password });


text:
Q: php array unset not working as expected I have an array of records I want to create a separate array of skills and want to remove duplicate values, unset not providing desired result somehow, I am not able to find out what's wrong. For example I have record (a) in first skills array at index 0 and I have same record in last skills array at index 1 , I just want to remove any duplicate records but unset removing other records also.
$x = 0;
$y = 0;
$z = 0;

$data = array();

$all_data = array ( 0 => array ( "fname" => "Ann",  "skills" => array ( 0 => "a", 1 => "b" )),
1 => array ( "fname" => "Bxx",  "skills" => array ( 0 => "c", 1 => "d" )),
2 => array ( "fname" => "Sdd",  "skills" => array ( 0 => "e", 1 => "a" ))
);

while( $x < count($all_data)){

    while($y < count($all_data[$x]['skills'])){

        $data[$x] = $all_data[$x]['skills'];

        if (in_array($data[$x][$y], $data[$x])){
            unset($data[$x][$y]);
        }

        $y++;
    }

    $y = 0;

    $x++;
}

The result I am getting is this
Array
(
 [0] => Array
    (
        [0] => a
    )

[1] => Array
    (
        [0] => c
    )

[2] => Array
    (
        [0] => e
        [1] => a
    )

)
I am expecting
Array
 (
  [0] => Array
    (
        [0] => a
        [1] => b
    )

[1] => Array
    (
        [0] => c
        [1] => d
    )

[2] => Array
    (
        [0] => e
    )

)

A: You could try something like this :
$keys=[];
foreach ($all_data as $index1 => $item) {
    if (!isset($item['skills'])) continue;
    foreach ($item['skills'] as $index2 => $value) {
        if (!in_array($value, $keys)) {
            $data[$index1][] = $value ;
            $keys[] = $value ;
        }
    }
}
unset($keys);

print_r($data);

Outputs :
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)


text:
Q: Positioning items with CSS I am still learning so I am struggling with CSS. I want to align all items within div centrally and align pics with the text and align them to left.
HTML

  Countries

 {{countryNumber}}

  Customers

 {{customerNumber}}

CSS
    .SectionTop {
     width: 95%;
     margin-left: 3%;
     margin-right: 3%;
     background-color: white;
     border: 2px solid blue;
     border-radius: 25px;
      }

.CardVisual {
width: 15%;
display: inline-block;
text-align: center;
}
.Pic {
width: 30px;
height: 30px;
object-fit: cover;
margin-left: 20px;
align-items: center;
}

A: For the centering purposes, use text-align: center. Unfortunately without a valid image I cant figure out exactly what you require.

.SectionTop {
  width: 95%;
  margin-left: 3%;
  margin-right: 3%;
  background-color: white;
  border: 2px solid blue;
  border-radius: 25px;
  text-align: center;
}

.CardVisual {
  width: 15%;
  display: inline-block;
  text-align: center;
}

.Pic {
  width: 30px;
  height: 30px;
  object-fit: cover;
  margin-left: 20px;
  align-items: center;
}

  Countries

 {{countryNumber}}

  Customers

 {{customerNumber}}

A: You could make use of display: flex to achieve this one.

.SectionTop {
  width: 95%;
  margin-left: 3%;
  margin-right: 3%;
  background-color: white;
  border: 2px solid blue;
  border-radius: 25px;
  align-items: center;
  justify-content: center;
  display: flex;
  height: 250px;
}

.CardVisual {
  width: 15%;
  display: inline-block;
  text-align: center;
}
.Pic {
  width: 30px;
  height: 30px;
  object-fit: cover;
  margin-left: 20px;
  align-items: center;
}

       Countries

001

      Customers

002


text:
Q: How to write relative path for subdirectory domain I am creating a new Wordpress site using some temporary IP address with sub directory, this is the site
All the files stored under this sub directory , now I wants to give relative paths for the images in the pages and post .

I want to give relative url for the above image ..
help me guys I am newbie here how to give all the
/../ methods are failed help me

A: In WordPress you have to use the get_template_directory_uri() function to get path to the template directory and then you can use the path to the folder you wish.
Suppose your folder structure is tamil>images>new.jpg where tamil is your theme folder name and then images folder which has the image.
The code should be
<img src="<?php echo get_template_directory_uri(); ?>/images/new.jpg">


text:
Q: IdentityServer Admin: how to include Admin.EntityFramework? I am exploring IdentityServer and noticed
 https://github.com/IdentityServer/IdentityServer3.Admin and https://github.com/IdentityServer/IdentityServer3.Admin.EntityFramework repositories.
I understand that Admin is the core UI project, Admin EF is a persisting layer for the core.
Out-of-the box Admin uses in-memory generated data.
But I couldn't find how I should replace In-Memory provider with Admin EF persisting layer.
Can anyone give me any tutorial/documentation/steps to do?

A: There is an example of using Admin.EntityFramework within that repository. Check here: https://github.com/IdentityServer/IdentityServer3.Admin.EntityFramework/tree/master/source/Host


text:
Q: Как рандомно выбрать фото и подпись к ней? Суть проблемы такая: надо с помощью функции random запросить элемент из словаря типа
some_dict = {'text1': 'photo1', 'text2': 'photo2', 'text3': 'photo3'}

и передать текст в message, а фото, соответствующее подписи, в attachment (vk_api, если что)
P.S Кому не сложно, скажите, правильно ли я составила вопрос?

A: Можно воспользоваться методом .choice из пакета random. Для нее нужна индексируемая последовательность, поэтому сначала преобразуйте в список:
import random

some_dict = {'text1': 'photo1', 'text2': 'photo2', 'text3': 'photo3'}
text, photo = random.choice(list(some_dict.items()))

>>> text
'text3'

>>> photo
'photo3'


text:
Q: Implement pwelch in matlab I try to implement pwelch function in matlab.
here is my code
len = 65536;

data = randn(1, len);

overlap = 0.5;

w           = 256;
num_w       = len / (w * overlap);
hamming_win = hamming(w)';
win_normal  = mean(hamming_win.^2);

Pxx_sum = zeros(1, w/2+1);
for i = 1:num_w
    if i == 1
        block = [zeros(1, w * (1-overlap)) data(1:w * overlap)] .* hamming_win;
    else
        block = data((1:w) + (i-2) * w * overlap) .* hamming_win;
    end

    block_fd      = fft(block);
    block_fd_half = block_fd(1:w/2+1);

    Pxx = (block_fd_half .* conj(block_fd_half)) / (w * win_normal);
    Pxx_sum = Pxx_sum + Pxx;
end

psd_avg = Pxx_sum / num_w;
figure, plot(psd_avg);

and compare with matlab pwelch
[psd_mat freq] = pwelch(data, w, 0.5*w);
figure, plot(psd_mat)

It seems there are a mismatch gain here.
If I replace my last two lines with
psd_avg = Pxx_sum / num_w * 0.318;  % <-----------
figure, plot(psd_avg);

I want to know

*

*Where do I miss the 0.318 gain? Do I miss something?

*First freq bin and last freq bin have big different with matlab result, why?

I hope someone can help me.

A: Base on Ander and Daniel's comment.
I review my code and compare with Octave's pwelch.
Here is what I found.
I remove block_fd_half like this
for i = 1:num_w

    ...

    block_fd  = fft(block);

    Pxx     = (block_fd .* conj(block_fd)) / (w * win_normal);
    Pxx_sum = Pxx_sum + Pxx;
end

and before plot the result
convert psd result from two sides to one side
psd_avg          = Pxx_sum / num_w;
psd_avg_one_side = psd_avg(1:w/2+1) + [0, psd_avg(w:-1:w/2+2) ,0];

figure, plot(psd_avg_one_side);

This is why my old result has a big difference in the first freq bin and last freq bin.
After these modified, my new result and octave result are exactly the same.
But, My new result also has a (2*pi) gain mismatch which compares with Matlab result.
I think this may be a normalizing factor to normalize sampling frequency?