text:
Q: Uploaded image not saved in Web folder [symfony2.8] I'm trying to upload a picture, but the picture is not saved in the web folder. When i check in the database in the entity image i can see the name of the picture.

AvatarType.php
 ->add('image', 'file', array(
                'label' => 'Image',
                'required' => false
            ))

PostController.php
public function avatarAction(Request $request)
{
    $user = $this->container->get('security.context')->getToken()->getUser();
    $entity = new Avatar();
    $form = $this->createForm(new AvatarType(), $entity);
    if ($this->get('request')->getMethod() == 'POST') {
        $form->handleRequest($request);
        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity->setUser($user);
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('avatar'));
        }
    }
    return $this->render('FLYBookingsBundle:Post:avatar.html.twig', array('user' => $user,
        'entity' => $entity,'form' => $form->createView()));

}

Avatar.php
<?php

namespace FLY\BookingsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Application\Sonata\UserBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
 * Avatar
 *
 * @ORM\Table(name="avatar")
 * @ORM\HasLifecycleCallbacks
 */
class Avatar
{

    /**
     *
     *
     * @ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User")
     * @ORM\JoinColumn(onDelete="CASCADE")
     * @Security("user.getId() == post.getUser()")
     */
    private $user;
    /**
     * @return User
     */
    public function getUser()
    {
        return $this->user;
    }

    /*
     * @param User $user
     */
    public function setUser(User $user)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string $image
     *
     * @ORM\Column(name="image", type="string", length=255)
     */
    private $image;

    /**
     * @Assert\File(
     * maxSize="1M",
     * mimeTypes={"image/png", "image/jpeg", "image/gif"}
     * )
     */
    public $imageFile;

    /**
     * @var text $description
     *
     * @ORM\Column(name="description", type="text", nullable=true)
     */
    private $description;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set image
     *
     * @param string $image
     */
    public function setImage($image)
    {
        $this->image = $image;
    }

    /**
     * Get image
     *
     * @return string
     */
    public function getImage()
    {
        return $this->image;
    }

    /**
     * Set description
     *
     * @param text $description
     */
    public function setDescription($description)
    {
        $this->description = $description;
    }

    /**
     * Get description
     *
     * @return text
     */
    public function getDescription()
    {
        return $this->description;
    }

    // Upload d'image

    public function getFullImagePath()
    {
        return null === $this->image ? null : $this->getUploadRootDir().$this->image;
    }

    protected function getUploadRootDir()
    {
        // the absolute directory path where uploaded documents should be saved
        return $this->getTmpUploadRootDir().$this->getId()."/";
    }

    protected function getTmpUploadRootDir()
    {
        // the absolute directory path where uploaded documents should be saved
        return __DIR__ . '/../../../../web/uploads/';
    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUploadImage()
    {
        if (null !== $this->imageFile) {
            $this->image = 'image.' .$this->imageFile->guessExtension();
        }
    }

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function uploadImage()
    {
        if (null === $this->imageFile) {
            return;
        }

        if(!is_dir($this->getUploadRootDir())){
            mkdir($this->getUploadRootDir());
        }

        $this->imageFile->move($this->getUploadRootDir(), $this->image);

        unset($this->imageFile);
    }

    /**
     * @ORM\PostRemove()
     */
    public function removeImage()
    {
        unlink($this->getFullImagePath());
        rmdir($this->getUploadRootDir());
    }
}

ADD:
edit_profile.html.twig
<img src="{{ asset( 'uploads/brochures/' ~ entity.brochure) }}" />

User.php
   /**
     * @ORM\Column(type="string")
     *
     * @Assert\NotBlank(message="Please, upload the product brochure as a PDF file.")
     * @Assert\File(
     *     maxSize="3M",
     *     mimeTypes={"image/png", "image/jpeg", "image/pjpeg"}
     * )
     */
    private $brochure;

    public function getBrochure()
    {
        return $this->brochure;
    }

    public function setBrochure($brochure)
    {
        $this->brochure = $brochure;

        return $this;
    }
    /**
     * @ORM\PrePersist()
     */
    public function preUpload()
    {
        if (null !== $this->brochure) {
            // do whatever you want to generate a unique name
            $this->path = uniqid().'.'.$this->brochure->guessExtension();
        }
    }

    /**
     * @ORM\PostPersist()
     */
    public function upload()
    {
        if (null === $this->brochure) {
            return;
        }

        $this->brochure->move($this->getUploadRootDir(), $this->brochure);
        $this->brochure = null;
    }

service.yml
application.brochure_uploader:
       class: Application\Sonata\UserBundle\Controller\FileUploader
       arguments: [ '%brochures_directory%' ]

application.doctrine_brochure_listener:
       class: Application\Sonata\UserBundle\EventListener\BrochureUploadListener
       arguments: [ '@application.brochure_uploader' ]
       tags:
         - { name: doctrine.event_listener, event: prePersist }
         - { name: doctrine.event_listener, event: preUpdate }

BrochureUploadListener.php
class BrochureUploadListener
{
    private $uploader;

    public function __construct(FileUploader $uploader)
    {
        $this->uploader = $uploader;
    }

    public function prePersist(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();

        $this->uploadFile($entity);
    }

    public function preUpdate(PreUpdateEventArgs $args)
    {
        $entity = $args->getEntity();

        $this->uploadFile($entity);
    }

    private function uploadFile($entity)
    {
        // upload only works for Product entities
        if (!$entity instanceof User) {
            return;
        }

        $file = $entity->getBrochure();

        // only upload new files
        if (!$file instanceof UploadedFile) {
            return;
        }

        $fileName = $this->uploader->upload($file);
        $entity->setBrochure($fileName);
    }
}

FileUploader.php
class FileUploader
{
    private $targetDir;

    public function __construct($targetDir)
    {
        $this->targetDir = $targetDir;
    }

    public function upload(UploadedFile $file)
    {
        $fileName = md5(uniqid()).'.'.$file->guessExtension();

        $file->move($this->targetDir, $fileName);

        return $fileName;
    }
}


text:
Q: Vertical centering in percent I am trying to center a block of dynamic height. I followed the nice guide at Vanseo Design and implemented the solution with negative margins. After a while of tweaking I got it to work in Chrome, but when trying in IE and Firefox the negative margins were way off! Chrome and Safari handles the position as expected, but not IE and FF. Had it been only IE I could have done a classic IE-CSS-hack, but with Firefox in the mix as well... Anyone who know how to get vertical cenetring with dynamic element to work in all browsers?
Screenshot from Chrome / Safari (Correct):

Screenshot from Firefox / IE (Wrong):

<!DOCTYPE html>

<title>Dead Centre</title>

This box should be centered vertically

A: Well, you put a height of 64% for your element, so let do mats :)
100-68 = 36 ,., so there is only 36% left.
then devide this by 2 and you have 18
By putting your content ID to 18% from top and removing your margin, everything should work just fine. :)
#content
{
    position: absolute;
    top: 18%;
    left: 0%;
    height: 64%;
    width: 100%;
    text-align:center;
    background-color:#339;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Exception parsing classes in android at runtime in android studio I am getting this error while running the application on device.
The error is stated below:

Error:Error converting bytecode to dex:
  Cause: java.lang.RuntimeException: Exception parsing classes
Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
  com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: Return code 1 for dex process.


text:
Q: Can i change existing SharePoint sql connection from hostname to fqdn? We are currently using sql server hostname and instance name for connecting the SharePoint farm to SQL database instance.
e.g: sqlserver1\instance1
Now we are required to use the sql fqdn name instead of host name like sqlserver.domain.com\instance1.
How can we achieve this?

A: Renaming SQL for SP is problematic, but there is great workaround for it and it is best practice for configuration anyway.
User server alias to point it to the FQDN. Set alias to sqlserver to sqlserver.domain.com (as you use instace name in config that should suffice)
To run the server alias console run the cliconfg from the run console on the server.
Step by step details can be found here:
https://www.toddklindt.com/blog/Lists/Posts/Post.aspx?ID=255


text:
Q: jQuery get complex multiple checked values from checkbox to array I want to dynamically display the content of a site in relation to choice of visitors when it selects checkbox. No problem for sends information in Ajax and the php side. But I can not create an array like I want in jQuery.
HTML :

        <input type="checkbox" data-group="size_catalog" data-value="32">
        <input type="checkbox" data-group="size_catalog" data-value="36">
        <input type="checkbox" data-group="size_catalog" data-value="38">
        <input type="checkbox" data-group="size_catalog" data-value="40">

        <input type="checkbox" data-group="color_catalog" data-value="red">
        <input type="checkbox" data-group="color_catalog" data-value="blue">
        <input type="checkbox" data-group="color_catalog" data-value="black">

The object with multiple array I would like to have (it is necessary to group the same data-group) :
var myArray = {size_catalog : ["32", "36", "38"], color_catalog: [red, blue]};

My current code (found on the internet and adapted) that create a simple array:
    function getChecked(){
        var opts= [];
        $checkboxes.each(function(){
            if(this.checked){
                opts.push(this.value);
            }
        });
        return opts;
    }

    function updateSearch(opts){
        $.ajax({
            type: "POST",
            url: "class.search.php",
            dataType : 'json',
            cache: false,
            data: {filterOpts: opts},
            success: function(records){
                ...
            }
        });
    }

    var $checkboxes = $("input:checkbox");
    $checkboxes.on("change", function(){
        var opts = getChecked();
        updateSearch(opts);
    });

    updateSearch();

Thank you for your help!

A: You do that by iterating and creating an object with the size-catalog as keys, and an array you push to as a value.
var $checkboxes = $("input:checkbox");

$checkboxes.on('change', function() {
    var obj = {};

    $checkboxes.filter(':checked').each(function() {
        var n = $(this).data('group'),
            v = $(this).data('value');

        n in obj ? obj[n].push( v ) : obj[n] = [v];
    });

    $.post('class.search.php', {filterOpts: obj}, 'json').done(function(records) {

    });

});

FIDDLE

A: Thats not a multidimentional array, thats an object containing 2 different arrays. If you want that, then something like this is what you want:
function getChecked() {
  var sizeArray = [];
  var colorArray = [];

  $checkboxes.each(function() {
    if ($(this).is(':checked')) {
      if ($(this).data('group') == 'size_catalog')
        sizeArray.push($(this).data('value'));
      else if ($(this).data('group') == 'color_catalog')
        colorArray.push($(this).data('value'));
    }
  });

  return {
    size_catalog: sizeArray,
    color_catalog: colorArray
  };
}

Here is a working example


text:
Q: I can connect to a server via named pipes with sqlcmd but a vendor tool is getting Named Pipes Provider, error: 40 I have a windows service running on my workstation that is part of a vendor supplied tool that connects to a database. It will not startup the error I get 4 errors in the event log with the following inner exception:
Inner Exception
---------------
Type : System.Data.SqlClient.SqlException, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Message : A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
Source : .Net SqlClient Data Provider
Help link :
Errors : System.Data.SqlClient.SqlErrorCollection
Class : 20
LineNumber : 0
Number : 53
Procedure :
Server :
State : 0
ErrorCode : -2146232060
Data : System.Collections.ListDictionaryInternal
TargetSite : Void OnError(System.Data.SqlClient.SqlException, Boolean)
Stack Trace :    at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
   at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
   at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
   at System.Data.SqlClient.SqlConnection.Open()
   at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure)

Of course the key thing of note is (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
However, if I do a runas /user:serviceuser cmd I can connect via named pipes to server just fine:
C:\Windows\system32>sqlcmd -S np:\\%%SERVER_NAME%%\pipe\sql\query
1> SELECT @@servername, db_name()
2> go

--------------------------------------------------------------------------------
------------------------------------------------ -------------------------------
--------------------------------------------------------------------------------
-----------------
SERVER_NAME
                                             master

(1 rows affected)

What other troubleshooting steps do I take?

A: Check Ring Buffers output for Connectivity errors and also check the error log if you see a Login Failed error message. Check the login that the tool is using and see if you can login into the SQL instance using the same login. Also find out the server name that they are providing to see if they are using an alias.


text:
Q: How to use the memoir package to make a custom title page There's probably an easy way to do this, but how can I add a memoir title page style to an existing document? I have tried this code, but I still get the basic title page.
\documentclass[12pt,a4paper,twoside]{memoir}
\usepackage[T1]{fontenc}
\usepackage{geometry}
\usepackage{titlesec}  %needs recent version of »titlesec«
\usepackage{xcolor}

\newcommand*{\titleGM}{\begingroup% Gentle Madness
\drop = 0.1\textheight
\vspace*{\baselineskip}
\vfill
\hbox{%
\hspace*{0.2\textwidth}%
\rule{1pt}{\textheight}
\hspace*{0.05\textwidth}%
\parbox[b]{0.75\textwidth}{
\vbox{%
\vspace{\drop}
{\noindent\HUGE\bfseries Some\\[0.5\baselineskip]
Conundrums}\\[2\baselineskip]
{\Large\itshape Puzzles for the Mind}\\[4\baselineskip]
{\Large THE AUTHOR}\par
\vspace{0.5\textheight}
{\noindent The Publisher}\\[\baselineskip]
}% end of vbox
}% end of parbox
}% end of hbox
\vfill
\null
\endgroup}

\title{\Huge\textbf{ORTHODOX RULE OF PRAYER}}
\author{\Large\textbf{Father Thomas Moore, Michael Dykes}}
\date{\Large{\today}}

\begin{document}

\title{\Huge\textbf{ORTHODOX RULE OF PRAYER}}
\author{\Large\textbf{Father Thomas Moore, Michael Dykes}}
\date{\Large{\today}}

Towards evening, we stand before the holy icons (having lit a candle and        maybe some incense), with reverence and fear of God; we gather our thoughts, make the        Sign of the Cross, and say:

\end{document}

Thanks!!!

A: You only need to create the \drop length and invoke \titleGM in your document (I did two other minor changes, setting the page style to empty an changing the height for the rule to prevent an overfull \vbox):
\documentclass[12pt,a4paper,twoside]{memoir}
\usepackage[T1]{fontenc}
\usepackage{geometry}
\usepackage{titlesec}  %needs recent version of »titlesec«
\usepackage{xcolor}

\newlength\drop
\newcommand*{\titleGM}{%
\thispagestyle{empty}
\begingroup% Gentle Madness
\drop = 0.1\textheight
\vspace*{\baselineskip}
\vfill
\hbox{%
\hspace*{0.2\textwidth}%
\rule{1pt}{\dimexpr\textheight-28pt\relax}%
\hspace*{0.05\textwidth}%
\parbox[b]{0.75\textwidth}{
\vbox{%
\vspace{\drop}
{\noindent\HUGE\bfseries Some\\[0.5\baselineskip]
Conundrums}\\[2\baselineskip]
{\Large\itshape Puzzles for the Mind}\\[.37\baselineskip]
{\Large THE AUTHOR}\par
\vspace{0.5\textheight}
{\noindent The Publisher}\\[\baselineskip]
}% end of vbox
}% end of parbox
}% end of hbox
\vfill
\null
\endgroup}

\title{\Huge\textbf{ORTHODOX RULE OF PRAYER}}
\author{\Large\textbf{Father Thomas Moore, Michael Dykes}}
\date{\Large{\today}}

\begin{document}

\titleGM

Towards evening, we stand before the holy icons (having lit a candle and        maybe some incense), with reverence and fear of God; we gather our thoughts, make the        Sign of the Cross, and say:

\end{document}

To automatically use the information contained in the standard commands \author, \title, some modification is required:
\documentclass[12pt,a4paper,twoside]{memoir}
\usepackage[T1]{fontenc}
\usepackage{geometry}
\usepackage{titlesec}  %needs recent version of »titlesec«
\usepackage{xcolor}

\makeatletter
\newlength\drop
\newcommand*{\titleGM}{%
\thispagestyle{empty}
\begingroup% Gentle Madness
\drop = 0.1\textheight
\vspace*{\baselineskip}
\vfill
\hbox{%
  \hspace*{0.2\textwidth}%
  \rule{1pt}{\dimexpr\textheight-28pt\relax}%
  \hspace*{0.05\textwidth}%
  \parbox[b]{0.75\textwidth}{%
    \vbox{%
      \vspace{\drop}
      {\Huge\bfseries\raggedright\@title\par}\vskip2.37\baselineskip
      {\Large\bfseries\@author\par}
      \vspace{0.5\textheight}
    }% end of vbox
  }% end of parbox
}% end of hbox
\vfill
\null
\endgroup}
\makeatother

\title{ORTHODOX RULE OF PRAYER}
\author{Father Thomas Moore, Michael Dykes}

\begin{document}

\titleGM

Towards evening, we stand before the holy icons (having lit a candle and        maybe some incense), with reverence and fear of God; we gather our thoughts, make the        Sign of the Cross, and say:

\end{document}


text:
Q: How to find out who is receiving files or cancel old transfers in Skype? Every once in a while I hear the sound "file received" in Skype. I haven't sent any files recently but there are probably files I sent earlier to group chats and it's probably some members of group chats receiving files sent weeks ago. Is there a way to find out who is receiving these files? Or at least cancel old file transfers without erasing history every time?

A: In Skype go to View → Files Sent and Received and check all the files that you have send and received. you can cancel them as well.


text:
Q: How can we prevent page refresh on click of back button in angular 8? GoBack()`
 Window.history.back
Using GoBack() when I will navigate to previous page, but I want to prevent page reload at that time
How its possible, please help me on this.

A: You can use Location service. Inject Location service in constructor then call back method on injected service like this:
component.ts:
     constructor(private locationService: Location) {}

     goBack() {
      this.locationService.back();
     }

A: Inject the Router into your app.component and set its canceledNavigationResolution property to 'computed'.
@Component({
    selector: 'app-root',
   standalone: true,
   imports: [RouterModule],
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.scss'],
})
export class AppComponent {
   constructor(router: Router) {
      router.canceledNavigationResolution = 'computed';
   }
}


text:
Q: Convert the first element of an array to a string in PHP I have a PHP array and want to convert it to a string.
I know I can use join or implode, but in my case array has only one item. Why do I have to use combine values in an array with only one item?
This array is the output of my PHP function which returns an array:
Array(18 => 'Something');

How do I convert this to a string?

A: You can use the reset() function, it will return the first array member.

A: implode or join (they're the exact same thing) would work here. Alternatively, you can just call array_pop and get the value of the only element in the array.

A: If your goal is output your array to a string for debbuging: you can use the print_r() function, which receives an expression parameter (your array), and an optional boolean return parameter. Normally the function is used to echo the array, but if you set the return parameter as true, it will return the array impression.
Example:
    //We create a 2-dimension Array as an example
    $ProductsArray = array();

    $row_array['Qty'] = 20;
    $row_array['Product'] = "Cars";

    array_push($ProductsArray,$row_array);

    $row_array2['Qty'] = 30;
    $row_array2['Product'] = "Wheels";

    array_push($ProductsArray,$row_array2);

    //We save the Array impression into a variable using the print_r function
    $ArrayString = print_r($ProductsArray, 1);

    //You can echo the string
    echo $ArrayString;

    //or Log the string into a Log file
    $date = date("Y-m-d H:i:s", time());
    $LogFile = "Log.txt";
    $fh = fopen($LogFile, 'a') or die("can't open file");
    $stringData = "--".$date."\n".$ArrayString."\n";
    fwrite($fh, $stringData);
    fclose($fh);

This will be the output:
Array
(
    [0] => Array
        (
            [Qty] => 20
            [Product] => Cars
        )

    [1] => Array
        (
            [Qty] => 30
            [Product] => Wheels
        )

)

A: You could use print_r and html interpret it to convert it into a string with newlines like this:
$arraystring = print_r($your_array, true);

$arraystring = '<pre>'.print_r($your_array, true).'</pre>';

Or you could mix many arrays and vars if you do this
ob_start();
print_r($var1);
print_r($arr1);
echo "blah blah";
print_r($var2);
print_r($var1);
$your_string_var = ob_get_clean();

A: A For() loop is very useful. You can add your array's value to another variable like this:
<?php
    $dizi=array('mother','father','child'); //This is array

    $sayi=count($dizi);
    for ($i=0; $i<$sayi; $i++) {
        $dizin.=("'$dizi[$i]',"); //Now it is string...
    }
         echo substr($dizin,0,-1); //Write it like string :D
?>

In this code we added $dizi's values and comma to $dizin:
$dizin.=("'$dizi[$i]',");
Now
$dizin = 'mother', 'father', 'child',

It's a string, but it has an extra comma :)
And then we deleted the last comma, substr($dizin, 0, -1);
Output:

'mother','father','child'

A:
Is there any other way to convert that array into string ?

You don't want to convert the array to a string, you want to get the value of the array's sole element, if I read it correctly.
<?php
  $foo = array( 18 => 'Something' );
  $value = array_shift( $foo );
  echo $value; // 'Something'.

?>

Using array_shift you don't have to worry about the index.
EDIT: Mind you, array_shift is not the only function that will return a single value. array_pop( ), current( ), end( ), reset( ), they will all return that one single element. All of the posted solutions work. Using array shift though, you can be sure that you'll only ever get the first value of the array, even when there are multiple.

A: Use the inbuilt function in PHP, implode(array, separator):
<?php
    $ar = array("parth","raja","nikhar");
    echo implode($ar,"/");
?>

Result: parth/raja/nikhar

A:
Is there any other way to convert that
  array into string ?

Yes there is. serialize(). It can convert various data types (including object and arrays) into a string representation which you can unserialize() at a later time. Serializing an associative array such as Array(18 => 'Somthing') will preserve both keys and values:
<?php
$a = array(18 => 'Something');
echo serialize($a);                                   // a:1:{i:18;s:9:"Something";}
var_dump(unserialize('a:1:{i:18;s:9:"Something";}')); // array(1) {
                                                      //   [18]=>
                                                      //   string(9) "Something"
                                                      // }

A: Since the issue of whitespace only comes up when exporting arrays, you can use the original var_export() for all other variable types. This function does the job, and, from the outside, works the same as var_export().
<?php

function var_export_min($var, $return = false) {
    if (is_array($var)) {
        $toImplode = array();
        foreach ($var as $key => $value) {
            $toImplode[] = var_export($key, true).'=>'.var_export_min($value, true);
        }
        $code = 'array('.implode(',', $toImplode).')';
        if ($return) return $code;
        else echo $code;
    } else {
        return var_export($var, $return);
    }
}

?>

http://www.php.net/manual/en/function.var-export.php#54440

A: Convert an array to a string in PHP:

*

*Use the PHP join function like this:
$my_array = array(4, 1, 8);

print_r($my_array);
Array
(
    [0] => 4
    [1] => 1
    [2] => 8
)

$result_string = join(',', $my_array);
echo $result_string;

Which delimits the items in the array by comma into a string:
4,1,8

*Or use the PHP implode function like this:
$my_array = array(4, 1, 8);
echo implode($my_array);

Which prints:
418

*Here is what happens if you join or implode key value pairs in a PHP array
php> $keyvalues = array();

php> $keyvalues['foo'] = "bar";

php> $keyvalues['pyramid'] = "power";

php> print_r($keyvalues);
Array
(
    [foo] => bar
    [pyramid] => power
)

php> echo join(',', $keyvalues);
bar,power
php> echo implode($keyvalues);
barpower
php>

A: A simple way to create a array to a PHP string array is:
<?PHP
    $array = array("firstname"=>"John", "lastname"=>"doe");
    $json = json_encode($array);
    $phpStringArray = str_replace(array("{", "}", ":"),
                                  array("array(", "}", "=>"), $json);
    echo phpStringArray;
?>

A: Convert array to a string in PHP:
Use the PHP join function like this:
$my_array = array(4,1,8);

print_r($my_array);
Array
(
    [0] => 4
    [1] => 1
    [2] => 8
)

$result_string = join(',' , $my_array);
echo $result_string;

Which delimits the items in the array by comma into a string:
4,1,8

A: For completeness and simplicity sake, the following should be fine:
$str = var_export($array, true);

It does the job quite well in my case, but others seem to have issues with whitespace. In  that case, the answer from ucefkh provides a workaround from a comment in the PHP manual.


text:
Q: Remove unused packages from conda environment I was provided with a complex Python program and a conda environment file for the dependencies of this program. However, I realized after installing the environment from the environment file that most packages in this environment are not used by this Python program. Is there a way to automatically identify the packages that are not used and remove them from the environment to make it smaller ? I guess that conda doesn't provide this functionality as it would require to parse the Python code to identify the packages that are imported or not, and conda is language agnostic.
I know the existence of conda clean --packages, but this command only clear the local cache of conda, which is not what I need.
Thanks


text:
Q: Bookmark does not work at Shiny Dashboard? I am able to use Bookmark at Shiny ,But does not work at Shiny Dashboard .
bookmarkButton() give me a new url. But i enter it ,it dose not get me the new result.
library(shinydashboard)

ui <- dashboardPage(
dashboardHeader(title = "Basic dashboard"),
dashboardSidebar(),
dashboardBody(
# Boxes need to be put in a row (or column)
fluidRow(

    box(plotOutput("plot1", height = 250)),

    box(
    title = "Controls",
    sliderInput("slider", "Number of observations:", 1, 100, 50),
    bookmarkButton()
  )
  )
  )
  )

server <- function(input, output,session) {
set.seed(122)
histdata <- rnorm(500)
output$plot1 <- renderPlot({
data <- histdata[seq_len(input$slider)]
hist(data)
})
}
enableBookmarking(store = "url")
shinyApp(ui, server)

A: Your UI should be a function, as is indicated by the error you get, see also the documentation
Working example:
library(shinydashboard)

ui <- function(request) {
  dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(),
  dashboardBody(
    # Boxes need to be put in a row (or column)
    fluidRow(

      box(plotOutput("plot1", height = 250)),

      box(
        title = "Controls",
        sliderInput("slider", "Number of observations:", 1, 100, 50),
        bookmarkButton()
      )
    )
  )
)
}

server <- function(input, output,session) {
  set.seed(122)
  histdata <- rnorm(500)
  output$plot1 <- renderPlot({
    data <- histdata[seq_len(input$slider)]
    hist(data)
  })

}
enableBookmarking(store = "url")
shinyApp(ui, server)

Hope this helps!


text:
Q: How to generate the name of model in the layout when access to view When access to a specific view in wanting to generate a model name for this view in layout.
I need a passing model name from view to layout "dynamic way to all views"

A: In the view you can try this:
@model.GetType().Name  // in the view

And if you want get model name in the controller then:
var model = new MyCustomViewModel();
var modelName = model.GetType().Name;

Edit:
As you explained in comment if you want access some view data in layout you can try this:
var currentControllerName = Url.ActionContext.RouteData.Values["controller"].ToString();
var currentActionName = Url.ActionContext.RouteData.Values["action"].ToString();

Or you can share data between layout and view with ViewBag.
Set ViewBag in view:
@ViewBag.Title= @model.GetType().Name;

Then you can read it in layout:
@ViewBag.Title// in layout


text:
Q: Extract all rows containing first value for each unique value of another column I am looking for something similar to this Select only the first rows for each unique value of a column in R
but I need to keep ALL rows containing the first values of year per ID.
 In ither words, I need to subset the dataset on the first year listed, by individual ID. IDs can have their first
  year in 1 2 or 3, and all of the rows in the first year should be retained.
  For example:
  ID <- c("54V", "54V", "54V", "54V", "56V", "56V", "56V", "59V", "59V", "59V")
  yr <- c(1, 1, 1, 2, 2, 2, 3, 1, 2, 3)
  test <- data.frame(ID,yr)
  test

    ID yr
1  54V  1
2  54V  1
3  54V  1
4  54V  2
5  56V  2
6  56V  2
7  56V  3
8  59V  1
9  59V  2
10 59V  3

The expected result:
  ID   yr
1 54V   1
2 54V   1
3 54V   1
4 56V   2
5 56V   2
6 59V   1

My dataset has many columns and I need to retain them all.
Any directions with R or sqldf in R are helpful!

A: We can do this with dplyr
library(dplyr)
test %>%
    group_by(ID) %>%
    filter(yr==first(yr))
#   ID    yr
#  <fctr> <dbl>
#1    54V     1
#2    54V     1
#3    54V     1
#4    56V     2
#5    56V     2
#6    59V     1

Or using data.table
library(data.table)
setDT(test)[, .SD[yr==yr[1L]], ID]

Or using base R
test[with(test, as.logical(ave(yr, ID, FUN = function(x) x==x[1L]))),]


text:
Q: WorkingPrecision causes issue in the NIntegrate I really can't figure out why my code sometimes is not working. My integrals involve two variables (k and kz). The integration range for both of them are from zero to infinity. I found out that in some cases (not often) when the working precision is in some specific range, Mathematica gives me an error message saying that "the integrand has evaluated to non-numerical values...". However, if I change WorkingPrecision to higher or lower value, it works just fine. I am not sure why. Hope you can help me with this.
I copy my code here. Thanks a lot!
Clear[sofindmassz];
sofindmassz[λ_, T_, μ_, Δ_, opt : OptionsPattern[{workprec -> 16}]] :=
 Module[{wp, ϵ, ξ, E, dϵ, ddϵ, fBCSE, fBCSξ, f1d, mInth, mInt},
  wp = OptionValue[workprec]; ϵ[h_] := k^2 + kz^2 + 2 λ h k; ξ[h_] := ϵ[h] - μ;
  E[h_] := √(ξ[h]^2 + Δ^2);
  dϵ[h_] := 2 kz; ddϵ = 2;
  f1d[h_] := -Exp[ξ[h]/T]/(T (Exp[ξ[h]/T] + 1)^2);
  fBCSE[h_] := Tanh[E[h]/(2 T)];
  fBCSξ[h_] := Tanh[ξ[h]/(2 T)];
  mInth[h_] := k ((2 f1d[h] + E[h]/Δ^2 ((1 + ξ[h]^2/E[h]^2) (fBCSE[h] - fBCSξ[h]) +
      (1 - ξ[h]/E[h])^2 fBCSξ[h])) (dϵ[h])^2 - 1/2 (fBCSξ[h] - ξ[h]/E[h] fBCSE[h]) ddϵ);
  mInt = mInth[1] + mInth[-1];
  Return[-Quiet[
      NIntegrate[
       NIntegrate[mInt, {k, 0, kz},
        Method -> {Automatic, "SymbolicProcessing" -> 0},
        WorkingPrecision -> wp], {kz, 0, ∞},
       Method -> {Automatic, "SymbolicProcessing" -> 0},
       WorkingPrecision -> wp]] -
    Quiet[NIntegrate[
      NIntegrate[mInt, {kz, 0, k},
       Method -> {Automatic, "SymbolicProcessing" -> 0},
       WorkingPrecision -> wp], {k, 0, ∞},
      Method -> {Automatic, "SymbolicProcessing" -> 0},
      WorkingPrecision -> wp]]]]

For this code, if I run the following values,
sofindmassz[0, 0.14921714620005236`, 0.07455393513003296`, 1.016522853606922`, workprec -> 15]

the error messages pops up.
If I change workprec to 14. It works! Don't know what's wrong.

A: One way to address the example is to provide input of the same or higher (arbitrary) precision,
sofindmassz[0, 0.14921714620005236`15, 0.07455393513003296`15, 1.016522853606922`15,
  workprec -> 15]
(*  0.643229985259241  *)

One can get overflow, probably from
f1d[h_] := -Exp[ξ[h]/T]/(T (Exp[ξ[h]/T] + 1)^2)

because the size of ξ[h] can be quite large ~ k^2 when integrating to infinity.  The alternative
f1d[h_] := -Exp[-ξ[h]/T]/(T (Exp[-ξ[h]/T] + 1)^2)

leads to underflow and other problems.  Depending on how I played with it, it might lead to a kernel crash from running out of memory or take so long I aborted it.  It you plot the integrand, it looks good and smooth up to k == 1000; but as k exceeds 10000 it starts to get bumpy and the bumps grow larger.
Here are some sample values of the integrand:
Grid@Table[mInt, {k, 1000000, 10000000, 1000000}, {kz, 0, k, 1000000}]

I get the same results no matter what precision I use for the parameters in sofindmassz.  While they are not the same as the sample points used by NIntegrate, the occasional extremely large values (compared to the estimated value of the integral) are disturbing.
It seems likely that numerical precision, underflow and/or overflow play a role in the evaluation of this integral. I've been unable to chase down the clear reasons for the difficulty.  As a result I cannot comment on the accuracy of the result above, other than to say it was the most common result (up to the first 8 or digits).
Using a double integral
NIntegrate[mInt, {k, 0, ∞}, {kz, 0, k},
 Method -> {Automatic, "SymbolicProcessing" -> 0},
 WorkingPrecision -> wp]

instead of nested integrals did not seem to help.  (It behaves somewhat differently, but it does not behave better.)
By the way, I am not a fan of using Quiet, especially to suppress numerics-related messages, unless I know why the warnings and errors are occurring and in fact expect them.  Usually one needs to understand why Mathematica is warning of a possible numerical error.  (If you get a lot, then you can set the preferences to log them in the messages window.)

A: Replace your Return line (the final line in your code by
fkz[z_?NumericQ] := NIntegrate[mInt, {k, 0, z}, WorkingPrecision -> wp];
fk[z_?NumericQ] := NIntegrate[mInt, {kz, 0, z}, WorkingPrecision -> wp];
Quiet[-NIntegrate[fkz[kz], {kz, 0, \[Infinity]}, WorkingPrecision -> wp] -
  NIntegrate[fk[k], {k, 0, \[Infinity]}, WorkingPrecision -> wp]]]

to eliminate the unwanted warning message.  Creating separate functions fkz and fk with argument z_?NumericQ is the solution.  The other changes merely delete code that no longer is necessary.  Note, however, that Quiet hides still other warning messages.


text:
Q: Change displayed business flow process on form Supppose I have two different business process flow for an entity, is it possible, from the onLoad event of the form, to change which flow is displayed ?
Should I try and modify the order in which the flows are shown depending on some conditions ? If that is even possible ?
Thanks

A: Yes.  You want Xrm.Page.data.process.setActiveProcess(processId, callbackFunction)
See Xrm.Page.data.process for reference


text:
Q: C# Windows Service - this keyword error I have the following code which works fine when I use it within a Windows Forms application, however the application I'm writing needs to run as a Windows service, and when I moved my code into the Windows Service template in Visual Studio 2015 Community Edition, I get the following error.

Cannot implicitly convert type "MyWindowsService.Main" to "System.ComponentModel.ISynchronizeVoke". An explicit conversion exists (are you missing a cast?)

Could anyone shed some light on why I am getting this error, and what I need to do to resolve it?
The code which throws the error is the line below, and it is located within the OnStart method of my main class (named Main.cs). The code is used to create an instance of the DataSubscriber class (AdvancedHMI library).
dataSubscribers[dataSubscriberIndex].SynchronizingObject = this;

It has to have something to do with the fact that the code is in a Windows service template, because using this works perfectly in my forms application running the same code.
UPDATE
Correction, I've attempted to cast this to the required type, and now get the following error on run.

Additional information: Unable to cast object of type 'MyWindowsService.Main' to type 'System.ComponentModel.ISynchronizeInvoke'.

Code:
dataSubscribers[dataSubscriberIndex].SynchronizingObject = (System.ComponentModel.ISynchronizeInvoke)this;

UPDATE
I've included the entire contents of the Main.cs file from my Windows Service application.
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using AdvancedHMIDrivers;
using AdvancedHMIControls;
using MfgControl.AdvancedHMI.Drivers;
using MfgControl.AdvancedHMI.Controls;
using System.Collections.ObjectModel;

namespace PLCHistoricDataHarvester {
    public partial class Main : ServiceBase {
        private EthernetIPforCLXCom commObject = new EthernetIPforCLXCom();
        private globals globals = new globals();
        private Dictionary<String, String> operationLines = new Dictionary<String, String>();
        private Dictionary<String, String> tags = new Dictionary<String, String>();
        private Collection<DataSubscriber> dataSubscribers = new Collection<DataSubscriber>();
        private int harvesterQueueCount = 0;
        private string harvesterInsertValues = String.Empty;

        public Main() {
            InitializeComponent();
        }

        protected override void OnStart(string[] args) {
            // Initialize our harvester program
            initializeHarvester();

            Console.WriteLine("The program has started");
        }

        protected override void OnStop() {
            // Call code when the service is stopped
            Console.WriteLine("Program has stopped");
            Console.ReadLine();
        }

        public void initializeHarvester() {
            // First, we connect to the database using our global connection object
            globals.dbConn.DatabaseName = "operations";

            if (!globals.dbConn.IsConnect()) {
                // TODO: Unable to connect to database.  What do we do?
            }

            // Second, we connect to the database and pull data from the settings table
            globals.initializeSettingsMain();

            // Set IP address of PLC
            commObject.IPAddress = globals.getSettingsMain("Processor_IP");

            // Pull distinct count of our parent tags (Machines ex: Line 1, etc)
            operationLines = globals.getOperationLines();

            // If we have at least 1 operation line defined...we continue
            if (operationLines.Keys.Count > 0) {
                //Now we loop over the operation lines, and pull back the data points
                int dataSubscriberIndex = 0;

                foreach (KeyValuePair<String, String> lines in operationLines) {
                    int line_id = int.Parse(lines.Key);
                    string name = lines.Value;
                    tags = globals.getTags(line_id);

                    // If we have at least 1 tag for this operation line, we continue...
                    if (tags.Keys.Count > 0 && tags["tags"].ToString().IndexOf(",") != -1) {
                        // Create our dataSubscriber object
                        dataSubscribers.Add(new DataSubscriber());
                        dataSubscribers[dataSubscriberIndex].SynchronizingObject = (ISynchronizeInvoke)this;
                        dataSubscribers[dataSubscriberIndex].CommComponent = commObject;
                        dataSubscribers[dataSubscriberIndex].PollRate = 1000;
                        dataSubscribers[dataSubscriberIndex].PLCAddressValue = tags["tags"];
                        dataSubscribers[dataSubscriberIndex].DataChanged += new EventHandler<MfgControl.AdvancedHMI.Drivers.Common.PlcComEventArgs>(subscribeCallback);
                        // Increment our dataSubscriberIndex
                        dataSubscriberIndex++;
                    }
                }
            }
        }

        private void subscribeCallback(object sender, MfgControl.AdvancedHMI.Drivers.Common.PlcComEventArgs e) {
            // code removed as it is irrelevant
        }
    }
}

A: The error message says this:

An explicit conversion exists (are you missing a cast?)

So add a cast like this:
dataSubscribers[dataSubscriberIndex].SynchronizingObject = (ISynchronizeInvoke)this;
                                                           ^^^^^^^^^^^^^^^^^^^^
                                                           //Add this

A: If you've got a console app, the easiest way to convert it to a windows service is by using Topshelf, a nuget package which lets you run in either console mode or nt service mode.
Here's the quickstart guide.
We use it to write services all the time and it helps you avoid this kind of fragile shenanigans.


text:
Q: How to make json deserialization fail when detecting duplicate properties in API POST request body I have a POST endpoint which accepts a JSON as request body.
@Path("/drink")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class DrinkResource {

    @POST
    public Drink getDrink(Fruit fruit) {
        return new Drink(fruit.getName());
    }
}

The request body is supposed to be deserialized into this POJO :
public class Fruit {

    private final String name;

    @JsonCreator
    public Fruit(@JsonProperty("name") String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

I'm using Jackson for the deserialization.
Is it possible to make the deserialization fail when the JSON in the request body has duplicate keys ?
For example, if the request body looks like this : {"name" : "banana", "name" : "orange"}, I would like to get a 500 status code or another kind of error instead of having the json deserialized with the last property.
Basically, I'm looking for a solution with the same logic as the JsonParser.Feature.STRICT_DUPLICATE_DETECTION with the ObjectMapper but for a POST endpoint.
I'm also using quarkus so I don't know if there is a property for this. Something similar to quarkus.jackson.fail-on-unknown-properties=true but for the duplicate properties.

A: Add the following:
@Singleton
public class MyCustomizer implements ObjectMapperCustomizer {
    @Override
    public void customize(ObjectMapper objectMapper) {
        objectMapper.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);
    }
}

If you do, the ObjectMapper that Quarkus uses will throw a JsonParseException thus leading to a HTTP 400 response.


text:
Q: Moment.js: Date.now() javaScript analogue Is there any simple way to get a number of milliseconds elapsed since 1 January 1970 00:00:00 UTC simular the Date.now() javaScript function?

A: Use the valueOf method on a moment object:
For local time:
moment().valueOf();

For UTC:
moment().utc().valueOf();

A: To get current date you may use the following line in your js file:
var currentDate = moment().format("DD-MM-YYYY");

It will show the date of the given format 19-Mar-2015
Click here to visit moment.js

A: Date.now() is the simplest. Otherwise the following using simple javascript can be used:-
new Date().getTime()

Using moment.js
moment().valueOf()

can be used.
moment("...").valueOf()

can be used to get the time elapsed since a particular date.


text:
Q: Delay action on touchend This is the first time I'm working with touch events. What I'm making is a button to slide a side menu on a responsive web. The button should only show it a touchstart event exists and dissapear 500ms after the touchend event is triggered.
here is my code:
// EVENT LISTENERS

function touchDown(event) {
    sliderButton.show();
}

function touchUp(event) {
    sliderButton.hide();
}

if (isMobile.any()) {
    sliderButton.hide();
    window.addEventListener("touchstart", touchDown, false);
    window.addEventListener("touchend", setTimeout(function() {
        sliderButton.hide(); //I used to invoke the touchUp function and it also didin't work,
    }, 500), false);

}

Also when I do touchmove (basically just move my finger areound the screen) it doesn't recognize the 'touchend' trigger. Any cluues on how to deal with thhis? Or should I open a new thread for that?
Thanks

A: I'm going to answer this instead of erasing the question because I found the same problem on other forums.
Basically that code works. I don't know why it happens sometimes that it doesn't work after a while. Even emptying the cache deson't help solve this.
It really makes no sense to me but I thought that since no one has answered others might benefit from trying to reset their pageload somehow and try it again.
cheers!


text:
Q: c# Web API 500 error from method after adding authentication I have been trying to fix this all day. I am making a test API to practice my development. I tried adding a bearer authentication error and now none of the methods work.
namespace WebApiTest
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; set; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging(loggingBuilder =>
            {
                loggingBuilder.AddConsole();
            });
            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Name = "Authorization",
                    Type = SecuritySchemeType.Http,
                    Scheme = "Bearer",
                    BearerFormat = "JWT",
                    In = ParameterLocation.Header,
                    Description = "JWT Authorization header. \r\n\r\n Enter the token in the text input below."
                });
                c.OperationFilter<AddAuthorizationHeaderParameterOperationFilter>();
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
        {
            try
            {
                app.UseSwagger();

                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Web API Test");
                });

                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }

                app.UseHttpsRedirection();

                app.UseRouting();

                app.UseAuthorization();

                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "An error occurred while configuring the application.");
                throw;
            }
        }
    }
    public class AddAuthorizationHeaderParameterOperationFilter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            var authAttributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
                .Union(context.MethodInfo.GetCustomAttributes(true))
                .OfType<AuthorizeAttribute>();

            if (authAttributes.Any())
            {
                operation.Security = new List<OpenApiSecurityRequirement>
            {
                new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" },
                        },
                        new string[] {}
                    }
                }
            };
            }
        }
    }
}

namespace AzureWebApiTest.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MainController : ControllerBase
    {
        private readonly LoginRequest loginInformation = new LoginRequest("username", "password");

        [HttpPost("GetToken")]
        public IActionResult GetToken([FromBody] LoginRequest loginRequest)
        {
            if (loginRequest == null)
            {
                return BadRequest("Bad Login Request");
            }

            if (loginRequest.Equals(loginInformation))
            {
                var token = GenerateBearerToken(loginRequest);
                return Ok(new { token });
            }
            else
            {
                return Unauthorized("Incorrect Login Information");
            }
        }

        [HttpGet("GetHello")]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public IActionResult GetHello([FromQuery] string name)
        {
            try
            {
                var token = Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
                var tokenHandler = new JwtSecurityTokenHandler();
                var tokenValidationParameters = new TokenValidationParameters
                {
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("secretKey"))
                };
                var claimsPrincipal = tokenHandler.ValidateToken(token, tokenValidationParameters, out var securityToken);

                return Ok("Hello " + name);
            }
            catch (SecurityTokenExpiredException)
            {
                return Unauthorized("Token has expired.");
            }
            catch (SecurityTokenInvalidSignatureException)
            {
                return Unauthorized("Invalid token signature.");
            }
            catch (Exception)
            {
                return Unauthorized("Invalid token.");
            }
        }

        private string GenerateBearerToken(LoginRequest loginRequest)
        {
            if (ValidateCredentials(loginRequest))
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var key = Encoding.ASCII.GetBytes("secretKey");
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Expires = DateTime.UtcNow.AddHours(1),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };
                var token = tokenHandler.CreateToken(tokenDescriptor);
                return tokenHandler.WriteToken(token);
            }
            return null;
        }

        private bool ValidateCredentials(LoginRequest loginRequest)
        {
            if(loginRequest.Equals(loginInformation))
            {
                return true;
            }
            return false;
        }
    }
}

When I try the method in swagger, I am getting the response:

I've tried getting ChatGPT to fix it but I'm getting nowhere and it's going in circles. Anyone have any ideas?
Edit:
The Validate function returns false at the end, I changed it for testing purposes. Edited back.

A: You are trying to get authorization to work, but you lack a few things.
Authentication
services.AddAuthentication(..options..).AddJwtBearer(..options..)

You need to add authentication to the pipeline, by adding UseAuthentication() before UseAuthorization(), like:
app.UseAuthentication();
app.UseAuthorization();

You need to add / register the authorization service using
services.AddAuthorization(..options..);


text:
Q: Component Solutions of Diffusion Equation with zero flux at boundaries I am looking at the reaction of A and B, which react instantaneously and irreversibly (acid and base for example).  Hence this is just a diffusion or Fick's law problem.
$$\frac{\partial c}{\partial t} = D\frac{\partial ^2 c}{\partial x^2}$$
where $c(x,t)=c_A(x,t)-c_B(x,t).$
The model is a slab of A, with fixed initial thickness of $\delta$, immediately adjacent to a slab of B, with fixed initial thickness of $\delta$. The domain for both slabs is $-\delta$ to $+\delta$. The following are the boundary conditions:
at $t > 0$ and $x = -\delta$:
$$\frac{\partial c_A}{\partial x} = 0$$
or in terms of the defined variable c,
$$\frac{\partial c}{\partial x} = 0$$
at $t > 0$ and $x = +\delta$:
$$\frac{\partial c_B}{\partial x} = 0$$
or in terms of the defined variable c,
$$\frac{\partial c}{\partial x} = 0$$
The initial conditions at $t = 0$ are:
$$c(x,0)=c_{A_0} \hspace{1cm}  for -\delta\leq x<0$$
$$c(x,0)=-c_{B_0} \hspace{1cm}  for\hspace{.2cm}  0< x\leq+\delta$$
Assuming that the diffusion coefficient ($D$) for A equals the diffusion coefficient for B and by defining a single variable $c(x,t)$, a single domain is created and the solution via separation of variables is  (thanks to Ricardo Cavalcanti):
$$c(x,t)= A_0 +\sum_{n=1}^{\infty}A_n\exp\left(-\frac{Dn^2\pi^2t}{4\delta^2}\right)\cos\left[\frac{n\pi}{2\delta}(x+\delta)\right]$$
The coefficients are:
$$A_0  = \frac{c_{Ao} -c_{Bo}}{2}$$
$$A_n=\frac{2}{n\pi}(c_{Ao}+c_{Bo})\sin\left(\frac{n\pi}{2}\right)$$
This solution is for $c$ where $c(x,t)=c_A(x,t)-c_B(x,t)$.  How would I explicitly solve for the variables $c_A$ and $c_B$?
I've attached a chart of what the concentration profiles look like for this solution.  In this chart $c_{Ao}  > c_{Bo}$ and A starts in the left slab.  As A moves into slab B the A domain increases (A and B cannot coexist). The edge of that domain is where $c(x,t)$ is equal to zero.  This is a moving boundary problem.

P.S.  Sorry for the figure showing up twice. I don't know why that is happening. I have tried to fix it, but to no avail.

A: PRACTICAL ANSWER
Since A and B cannot coexist and since $c(x,t) = c_A(x,t) - c_B(x,t)$, then when $c(x,t) > 0$ that means that $c_A(x,t) = c(x,t)$ and $c_B(x,t) = 0$.  When $c(x,t) < 0$, then $c_B(x,t) =c(x,t)$ and $c_A(x,t) = 0$.
Is simply taking the solution given in the original post and applying the caveats in the paragraph immediately above this one a sufficient mathematical solution??


text:
Q: Windows Fall Creator - can't install using node npm After installing Windows Fall Creator version 1709 I cannot install anything using npm. I've tried uninstalling and reinstalling node. It appears to be a permissions issue. Whenever I try I get
ENOENT
o -4058
all rename
nt ENOENT:

I've tried running using Windows bash and it too errors out with nearly the same message. Any ideas?

A: Webroot Secure anywhere was broken with Fall Creators and prevented node from running.
See https://community.webroot.com/t5/Product-Releases/Windows-10-Fall-Creator-Update-Bug-Fix/td-p/305469

A: If it worked before the Fall Creators update, you might just need to update npm and try whatever you wanted to do again.
npm i -g npm

Another thing you might want to try is clearing your package cache with the following command, that sometimes can cause issues on Windows too.
npm cache clear
// or optionally even
npm cache clear -f


text:
Q: Jeffreys prior for inverse gamma distribution Does anybody have the experience of dealing with Jeffreys prior?
I am working with hierarchical model at the moment where the parameter
σ^2 from normal distribution is said to be chosen according to
inverse gamma distribution from Jeffreys prior.
How should it work? And why are inverse gamma distributions used
so often as the prior for variances?
I found in some presentations that I can choose Jeffreys prior as,
for example, IG(0.001,0.001)
But it looks strange cause when both alpha and beta are <1 the gamma
function behaves in a strange manner. If I try to generate values
from IG(0.001,0.001) in R with code like
a=rgamma(1000,0.001,0.001)
aa=1/a
mean(aa)

I recieve Inf value since all values of a are close to 0 and some of
them are exactly 0.
So how should one choose Jeffreys prior?

A:
And why are inverse gamma distributions used so often as the prior for variances?

Because they're conjugate - at least for $\sigma^2$ in normal models.

How should it work?

You seem to have some confusion between Jeffreys' prior and (more-or-less) "uninformative" conjugate priors more generally. If you are taking a Jeffreys' prior, there's no choice involved: $p(\theta) \propto \sqrt{I(\theta)}\,$
where $I(.)$ is the Fisher information.
http://en.wikipedia.org/wiki/Jeffreys_prior


text:
Q: Interfaces with differential pairs during PCB Design I was wondering where I could find a list of interface which require differential pair or particular design rules ?
I know for example that USB require different pair routing. I identify them because their line are called D+ / D-.
However in another application I have a speaker and a mic which also have - and +, does this make them also a differential pair ?

A: Generally, differential pairs are used in high-frequency data lines, which are most prominent in devices used in sophisticated applications (memory buses, digital video, etc). And sophisticated devices tend to have associated literature to assist in the design where they describe which traces need to be routed as differential pairs.
What that means is you don't really need to memorize which kinds of devices do and don't require the special routing technique. You DO however need to always read the datasheets, design guides, and reference designs.
That's how the pros do it.

A: In addition to the comments and answers, there are a class of analogue applications where we use a differential interface.
This is usually where we have very low level signals, such as from a microphone, thermocouple or perhaps a strain gauge.
These interfaces are very susceptible to common mode noise and using a differential interface significantly reduces it (it does not completely eliminate it in practice).
These are not high frequency or high speed interfaces (thermocouple sampling rates are very slow as the device can only respond relatively slowly to changes in temperature anyway) but they are highly sensitive to noise.


text:
Q: How to build specialized components in React I found myself writing code like this, for a bunch of components that have some commonality:
class PropertyBlock extends React.Component {
    render() {
        const { headtext, blockType, selectedId, selectOptions, onChange, extratext } = this.props
        return (

{headtext}

                {blockType == 'dropdown' ? <PropBlk_Dropdown selectOptions={selectOptions} selectedId={selectedId} onChange={onChange} />
                    :
                    blockType == 'inp_line' ? <PropBlk_InputLine value={selectedId} onChange={onChange} />
                        :
                        blockType == 'inpstory' ? <PropBlk_InputStory value={selectedId} onChange={onChange} extratext={extratext} />
                            :
                            blockType == 'showline' ? <PropBlk_ShowLine value={selectedId} lines={selectOptions} />
                                :
                                blockType == 'inp_date' ? <PropBlk_InputDate value={selectedId} onChange={onChange} />
                                    :
                                    blockType == 'inp__chk' ? <PropBlk_Checkbox value={selectedId} onChange={onChange} extratext={extratext} />
                                        :

                                            {selectedId}

                }

        )
    }
}

But somehow I thought that could be better. I was thinking about a parent component and a lot of specialized child components that inherit from that parent. like:
class PropBlk_Type1 extends PropertyParentBlock {
   ...
}

However, reading On React it seems that inheritance should be avoided. So I tried something in line of the React example like this:
class PropertyParentBlock extends React.Component {
    render() {
        const { headtext, myownhtml } = this.props
        return (

{headtext}

                {myownhtml}

        )
    }
}

class PropBlk_Type1 extends React.Component {
    render() {
        const { headtext, value, onChange, extratext } = this.props
        return (
            <PropertyParentBlock headtext={headtext}
                myownhtml={(

                        <input value={value} onChange={(e) => onChange(e.target.value)} />

                )}
            />
        )
    }
}

So the specialized html is loaded into the parent component as a property myhtml. Building this with WebPack gave no syntax errors, and actually running this creates the desired html and it seems to work.
As I am still learning React I am wondering if I am on the right track, or that there are better ways and best practices for this kind of inheritance or composition.

A: There is no need to nest ternary operators like you have, you can do:
class PropertyBlock extends React.Component {
    render() {
        const { headtext, blockType, selectedId, selectOptions, onChange, extratext } = this.props;
        let element;
        switch(blockType){
           case "dropdown" :
               element =  <PropBlk_Dropdown selectOptions={selectOptions} selectedId={selectedId} onChange={onChange} />;
                 break;
            // go on here ...
        }
        return (

{headtext}

                {element}

        )
    }
}

A: By reading the React doc more closely, I found out that I was on the right track. Only my example could be simplified by leaving out one pair of parentheses and utilize the special props.children .
I could rewrite the ugly code of the question to something like this 'parent' component:
class PropBlk_Frame extends React.Component {
    render() {
        const { headtext } = this.props
        return (

{headtext}

                {this.props.children}

        )
    }
}

The above component is used in a number of 'child' components, like:
class PropBlk_InputLine extends React.Component {
    render() {
        const { headtext, value, inputfield, onChange } = this.props
        return (
            <PropBlk_Frame headtext={headtext}>
                <input value={value} onChange={(e) => onChange(true, e.target.value, inputfield)} onBlur={() => onChange(false, null, inputfield)} />
            </PropBlk_Frame>
        )
    }
}

class PropBlk_InputDate extends React.Component {
    render() {
        const { headtext, value, inputfield, onChange } = this.props
        return (
            <PropBlk_Frame headtext={headtext}>
                <input type='date' value={value} onChange={(e) => onChange(true, e.target.value, inputfield)} onBlur={() => onChange(false, null, inputfield)} />
            </PropBlk_Frame>
        )
    }
}

Now I can build my web page with the specialized components like this:
<PropBlk_InputLine headtext='Projectnaam *' value={fields.ProjectNaam} inputfield='inp_projectnaam' onChange={this.onInput} />
<PropBlk_InputDate headtext='Opdrachtdatum *' value={fields.DatumLabOpdracht} inputfield='inp_opdrachtdatum' onChange={this.onInput} />

This approach eliminates the structure with the ternaries, hence saves lines of code, and is more comprehensible.


text:
Q: LS7 filling the gaps image with Google Earth Engine I would like to work with Landsat 7 images, but most of them have gaps... I would like to fill the Gaps by aggregate images bands by month. So I'm looking for a way to deal with this problem.
I have tried to create a composite image with
var collectionLS7 = ee.ImageCollection('LANDSAT/LE7_L1T_TOA') //10m
    // Select the bands of interest to avoid taking up memory.
    .select(bandNames)
    // Filter to get only imagery at a point of interest.
    .filterBounds(roi);
var composite = collectionLS7.median();

But it doesn't work

I have also tried
var customComposite = ee.Algorithms.Landsat.simpleComposite({
  collection: collectionLS7,
  percentile: 75,
  cloudScoreRange: 5,
  maxDepth: 4
});

But with an error Layer 1: Layer error: ImageCollection.reduce: Error in map(ID=LE72040492015361ASN01): Landsat.TOA: Band 'B1' is Type<Float>, expected Type<Short<0, 255>>.

A: What @Kersten proposed is perfect, but I would just like to answer to the specific
 Band 'B1' is Type<Float>, expected Type<Short<0, 255>>

error, which I also get after gap filling, when trying to apply the simpleComposite algorithm.
You can change the type of the image like this:
var imageCollection= imageCollection.map(function(img){
        return img.toByte()
      });

You should then be able to run the simpleComposite algorithm.

A: You could try filling the gaps before you aggregate them by month.
USGS published a LS7 SLC-off gap-filling algorithm.
This algorithm was recreated for Google Earth Engine by Noel Gorelick: https://code.earthengine.google.com/d20cba5268ccbe117e2fc1c5fefc33f3
Building upon this Genadii Donchyts changed the algorithm for faster performance: https://code.earthengine.google.com/2ead14966758793579dfb31b94855275
The relevant thread  can be found on the Google Earth Engine Developers messaging board (after registration).
For completeness, here is the relevant function from Noel Gorelicks Code:
var MIN_SCALE = 1/3;
var MAX_SCALE = 3;
var MIN_NEIGHBORS = 144;

/* Apply the USGS L7 Phase-2 Gap filling protocol, using a single kernel size. */
var GapFill = function(src, fill, kernelSize) {
  var kernel = ee.Kernel.square(kernelSize * 30, "meters", false)

  // Find the pixels common to both scenes.
  var common = src.mask().and(fill.mask())
  var fc = fill.updateMask(common)
  var sc = src.updateMask(common)

  // Find the primary scaling factors with a regression.
  // Interleave the bands for the regression.  This assumes the bands have the same names.
  var regress = fc.addBands(sc)
  regress = regress.select(regress.bandNames().sort())
  var fit = regress.reduceNeighborhood(ee.Reducer.linearFit().forEach(src.bandNames()),  kernel, null, false)
  var offset = fit.select(".*_offset")
  var scale = fit.select(".*_scale")

  // Find the secondary scaling factors using just means and stddev
  var reducer = ee.Reducer.mean().combine(ee.Reducer.stdDev(), null, true)
  var src_stats = src.reduceNeighborhood(reducer, kernel, null, false)
  var fill_stats = fill.reduceNeighborhood(reducer, kernel, null, false)
  var scale2 = src_stats.select(".*stdDev").divide(fill_stats.select(".*stdDev"))
  var offset2 = src_stats.select(".*mean").subtract(fill_stats.select(".*mean").multiply(scale2))

  var invalid = scale.lt(MIN_SCALE).or(scale.gt(MAX_SCALE))
  scale = scale.where(invalid, scale2)
  offset = offset.where(invalid, offset2)

  // When all else fails, just use the difference of means as an offset.
  var invalid2 = scale.lt(MIN_SCALE).or(scale.gt(MAX_SCALE))
  scale = scale.where(invalid2, 1)
  offset = offset.where(invalid2, src_stats.select(".*mean").subtract(fill_stats.select(".*mean")))

  // Apply the scaling and mask off pixels that didn't have enough neighbors.
  var count = common.reduceNeighborhood(ee.Reducer.count(), kernel, null, true, "boxcar")
  var scaled = fill.multiply(scale).add(offset)
      .updateMask(count.gte(MIN_NEIGHBORS))

  return src.unmask(scaled, true)
}

var source = ee.Image("LANDSAT/LE7_L1T/LE70440342016075EDC00")
var fill = ee.Image("LANDSAT/LE7_L1T/LE70440342016027EDC00")


text:
Q: libgdx assetmanager texture loading here is my code:-
manager = new AssetManager();

fps =new FPSLogger();

Resolution[] resolutions = {new Resolution(320, 480, ".320480"), new Resolution(480,    800, ".480800"),
new Resolution(480, 856, ".480854")};

 ResolutionFileResolver resolver = new ResolutionFileResolver(new InternalFileHandleResolver(), resolutions);

manager.setLoader(Texture.class, new TextureLoader(resolver));

 manager.load( "images/flash.png" , Texture.class);
 Texture.setAssetManager(manager);
tex =  manager.get("images/flash.png" ,Texture.class);

tex = new Texture(Gdx.files.internal("images/a.png"));
flsh = new Texture(Gdx.files.internal("images/flash.png"));
tex2 = new Texture(Gdx.files.internal("images/space.jpg"));
ear = new Texture(Gdx.files.internal("images/earth.png"));
newgame=new Texture(Gdx.files.internal("images/shockwave.png"));

and the error that shows up is
 Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: Asset not loaded: images/flash.png
at com.badlogic.gdx.assets.AssetManager.get(AssetManager.java:119)
at main.assets.loading(assets.java:53)
at main.game.create(game.java:43)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:132)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:112)

my image layout is
/main(project name)/assets/images/a.png
please help me rectify this error

A: use manager.finishloading() in between manager.load() and manager.get statements.


text:
Q: IE8 isn't resizing tbody or thead when a column is hidden in a table with table-layout:fixed IE 8 is doing something very strange when I hide a column in a table with table-layout:fixed. The column is hidden, the table element stays the same width, but the tbody and thead elements are not resized to fill the remaining width. It works in IE7 mode (and FF, Chrome, etc. of course). Has anyone seen this before or know of a workaround?
Here is my test page - toggle the first column and use the dev console to check out the table, tbody and thead width:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>bug</title>

          1
          2
          3
          4

          1
          2
          3
          4

    toggle first column

A: A simple work-around for IE8 consists in giving the table a nudge, to get IE8 to adjust the column width based on the remaining columns. Assuming table points the to the table, the following will do the trick:
table.style.display = "inline-table";
window.setTimeout(function(){table.style.display = "";},0);

Credits: I read about this technique first from Srikanth's blog.
And for reference, here is the updated example using this technique.
I should note however that this technique doesn't always work. I am seeing a case in a more complicated app where no style change I could do seem to convince IE take into account that the number of columns changed (sorry, I don't have a simpler reproducable case). Luckily for us, IE9 entirely solves this problem.

A: Just found a nasty hack - Pick a visible column that should fill up the empty space and give it the class "colspanfix". Call this function after the other column is toggled (using jquery for brevity):
function fixColspans(tableId) {
  if ($('#' + tableId).width() > $('#' + tableId + ' tbody').width()) {
    var current = $('#' + tableId + ' .colspanfix').attr('colspan');
    $('#' + tableId + ' .colspanfix').attr('colspan', ++current);
  }
}

It checks to see if the table element is wider than the tbody element then it assigns a colspan value to the elements with the "colspanfix" class. The kicker is that it has to increase the colspan by one for each hide/show. Not very pretty, but it works.


text:
Q: ARC and how it works exactly. I just followed a tutorial on ARC  and was provided with this code.
The following ViewController class and below it a Vehicle class.
What i got from it was that ARC essentially tracks down an instantiated class and allocates a piece of memory for it. As "strong" references for the instance are created, arc increases the increment for how many references there are to the instance. Once all of them are set to nil, ARC deallocates the instance from memory. The instructor also said something along the lines of, once all references are not being used, it deallocates from memory. I did not quite understand the part where they're not being "used", so I decided to add a button which presents another View Controller thats blank with no code. I figured that if I navigate to the next view controller, deinit will get called as the references in view controller 1, are now not being used and thus deallocated from memory. This was not the case, and the deinit did not get called. Therefore, I'm wondering, do references stay in memory unless you set them to nil, always?
Part 2 of question : Also, while you're answering that question, I also have another, I was also wondering if ARC only applied to class instances and references to it since every piece of documentation or tutorial that I have looked up seems to only mention class instances. For example, if I set var number = 2
 var othernumber = number , is "number" also stored in memory, and only deallocated until all references to it are nil. If this is also the case, then the same question applies, is setting all references equal to nil the only way of deallocating from memory? Sorry for the lengthy question, but im quite new to the memory concept.
import UIKit

class ViewController: UIViewController {

var ref1: Vehicle?
var reference2: Vehicle?
var ref3: Vehicle?
var timer: NSTimer!
var count = 0
override func viewDidLoad() {
    super.viewDidLoad()

    ref1 = Vehicle(kind: "Car")
    reference2 = ref1
    ref3 = ref1

    timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(tick), userInfo: nil, repeats: true)

}

func tick() {
count++

    if count >= 3 {
        ref3 = nil
        reference2 = nil

    }

    if count == 5 {
    ref1 = nil

    }

}

}
   class Vehicle {

let type: String

init(kind: String){
self.type = kind
print("\(type) is being initialized")
//when the class is instantiated, we get an initialization message. When class is deallocated, we get a deinit message. As in, all strong references are gone, we can deinitialize.

}
deinit {
//class vehicle not in memory anymore as all strong references to it have been destroyed. This will be tested with segue as well.
    print("\(type) is being deinitialized")

}}

A: *

*The "used" terminology is confusing/misleading (or, at best, imprecise). With ARC, the object will not be released until there are no remaining strong references, plain and simple. If you nil all of those strong references, or those strong references fall out of scope, that's when the object is deallocated.
By the way, be aware that scheduledTimerWithTimeInterval establishes its own strong reference to its target. You have to invalidate the timer to resolve that strong reference.

*ARC only applies to reference types (i.e. class instances). It simply does not apply to value types (such as numeric types or struct types).
Thus, consider
var number = 2
var othernumber = number

The othernumber does not reference the number. It makes a copy. It is a new object whose value happens to be the same value as number. For a discussion differentiating Swift value types from reference types, see WWDC 2015 Building Better Apps with Value Types. (By the way, the behind the scenes memory management of complex value types is actually more complicated than it is for simple value types, but it's not really relevant in this conversation. But it is discussed in some detail in the video if you're interested.)

A: This is a big question.
In order to understand ARC you really need to understand manual reference counting.
Reference counting is a way of keeping track of which objects are still in use, and which can be deallocated.
In manual reference counting, objects have a retain count.
You send a retain message to an object to increase it's retain count, and release to decrease it's retain count. If sending a release message to an object causes it's retain count to drop to 0, the object is deallocated/freed.
There is also an autorelease message which adds the object to an "autorelease pool". Each time your code returns and the event loop is visited, all the objects in the autorelease pool get sent a release message for each time they are in the autorelease pool. (You can send more than one autorelease message to an object, but ignore that.) Autorelease is useful for returning temporary objects that go away if you don't do anything special with them. An autoreleased object sticks around during the current call chain, but get freed when your code returns if nobody has retained it.
Objects are created and returned to the owner with a reference count of 1, and the owner is responsible for sending a release message to the object when it is done with it.
In manual reference counting you have to put retain, release, and autorelease calls in your code at the correct places in order to express your memory management intentions. Getting it wrong causes either memory leaks or crashes.
ARC uses all of the above mechanisms, but the compiler analyzes your code and inserts retain, release, and autorelease calls for you. It also strips out excess retain/release calls to the bare minimum required.
In ARC, you just need to declare your variables as strong or weak and the compiler does the rest. There are still a few gotchas, but for the most part you don't have to worry about memory management.
Storing an object in a strong variable causes the compiler to generate a retain call. Zeroing out the strong variable causes the compiler to send the object a release message.
Unlike garbage collection, the system doesn't have to stop and do time-consuming cleanup passes on memory. Objects get freed as soon as there are no longer any strong references to them.


text:
Q: Bundling gradle dependencies with aar I have a project project A  that has these dependencies:
dependencies {
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.0.0'
    compile 'com.android.support:recyclerview-v7:24.0.0'
    compile 'com.android.support:cardview-v7:24.0.0'
    compile 'com.android.support:palette-v7:24.0.0'
    compile 'com.google.android.gms:play-services-gcm:9.4.0'
    compile 'com.google.android.gms:play-services-auth:9.4.0'
    compile 'com.google.android.gms:play-services-plus:9.4.0'
    compile 'com.google.android.gms:play-services-location:9.4.0'
    compile 'com.android.support:customtabs:24.0.0'
    compile ('com.hannesdorfmann.smoothprogressbar:library:1.0.0'){
        transitive = true
    }
    compile 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1'
    compile 'jp.wasabeef:blurry:2.0.2'
    compile 'com.karumi:dexter:2.3.1'
    compile 'io.card:android-sdk:5.4.0'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.cocosw:bottomsheet:1.+@aar'
    compile 'de.hdodenhof:circleimageview:1.3.0'
    compile 'me.leolin:ShortcutBadger:1.1.3'
    compile 'com.dlazaro66.qrcodereaderview:qrcodereaderview:1.0.0'
    compile 'com.facebook.android:facebook-android-sdk:4.13.2'
    compile 'xyz.danoz:recyclerviewfastscroller:0.1.3'
    compile 'uk.co.chrisjenx:calligraphy:2.2.0'
    compile 'com.android.support:multidex:1.0.1'
//    compile 'joda-time:joda-time:2.9.3'
    compile 'com.github.clans:fab:1.6.3'
    compile files('libs/jsevaluator.jar')
    compile files('libs/libphonenumber-7.0.2.jar')
    compile project(':zoneOrchestra')
    compile project(':scrambledkeyboard')
    compile project(':datelibrary')
    compile project(':phoneNumberValidator')
    compile project(':library')
    compile project(':inputtypepicker')
    compile project(':pagerIndicator')
    compile project(':persistentSearch')
    compile('com.github.KingsMentor:IntentManip:v1.0.2') {
        exclude group: 'com.android.support'
    }
    compile('com.twitter.sdk.android:tweet-composer:0.8.0@aar')
            {
                transitive = true;
            }

    compile('com.crashlytics.sdk.android:crashlytics:2.5.2@aar') {
        transitive = true;
    }

}

the project is bundle to project.aar , which should serve as a dependency to other projects.
The problem is, when project.aar is added to another project, it is unable to build. It requires it's dependencies which for some reasons are not bundled with it.
How do I make sure these dependencies are bundled along with the .aar file?


text:
Q: Update SET Age in HIVE This is just an example , which I encountered while practicing HQL.
How can I update age(currently set as null) of every id for date "1/2/2019" by age+1 from previous date of same ID?
Current data:
id  age     load date
101 200     1/1/2019
101 null    1/2/2019
102 225     1/1/2019
102 null    1/2/2019
103 334     1/1/2019
103 null    1/2/2019

Expected result:
id  age     load date
101 200     1/1/2019
101 201     1/2/2019
102 225     1/1/2019
102 226     1/2/2019
103 334     1/1/2019
103 335     1/2/2019

A: This may help
update t
set age = (select max(age) + 1 from t t2 where t.id = t2.id  and age is not null )
where age is null
  and date = '1/2/2019'


text:
Q: Query without using alias name in SQL Server I am firing the below query in SQL server, but it fails with the error

"No column name was specified for column".

I don't want to give the alias name as the default values passed to the query are huge giving to each one of them is time consuming.
Is there a way in SQL Server to fire the query without alias name?
The below query still goes on with other union clauses added, pasted query only part of it.
I don't want to create a script, want to achieve this in the form of query.
select count(*)
from
    (select distinct
         a.Company, a.BilltoCustomerNo, 0, 'No Customer', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 0, 0, 0, 'n/a', 'n/a', 'n/a', 0, 0, 'n/a', 'n/a', 0, 0, 'n/a', 'n/a', 'n/a', 0, 0, 'n/a', convert(datetime, '19000101', 112), 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 0, 0, 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 0, 'n/a', 'n/a', convert(datetime, '19000101', 112), 'n/a', convert(datetime, '19000101', 112), 0, 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 0, 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 0, 'n/a', 0, 'n/a', 0, 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 0, 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 0, 'n/a', 'n/a', 0, 'n/a', 'n/a', 'n/a', 'n/a', 0, 0, 0, 0, 0, 0, 0, 0, 0, 'na', 'na'
     from
         dJob a
     left outer join
         dCustomer b on a.Company = b.Company and a.BilltoCustomerNo = b.No
     where
         b.Company is null) x

Thanks

A: You could simplify that query into a single statement, and get rid of all those pointless scalar values.
select count(*)
from dJob a
left outer join dCustomer b on a.Company = b.Company and a.BilltoCustomerNo = b.No
where b.Company is null
group by a.Company, a.BilltoCustomerNo

A: You could drop all those columns as they add nothing. The query will be functionally the same without them as the all return constant values, so the only thing the distinct has to work with is the first two columns (which have a name) and you're throwing them all away in the outer query (The SELECT COUNT(*) part) anyway.
select count(*)
from (select distinct a.Company, a.BilltoCustomerNo
      from dJob a
      left outer join dCustomer b on a.Company = b.Company and a.BilltoCustomerNo = b.No
      where b.Company is null) x


text:
Q: Special characters (i.e. '...' character) causing query to fail I am not sure what character set this character '...' belongs to. However, in some cases, users copy and paste data in to the note field of an application I am working on. The note contents contains this special characters and causes the insert / update query to fail.
I was wondering if there is a string function to detect and remove this special character (along with other unwanted characters from this character set), while maintaining all other special characters ?
Example:
$query = 'INSERT INTO notes (note) VALUES ("… hello … world!")';
mysqli_query($conn, $query); //nothing is inserted

Thanks in advance!

A: If I were you I would consider accepting a wider set of characters. (You just need to remember to escape the characters properly.) To strip out certain characters just isn't user friendly, and using UTF-8 just seems limited.
If you really want to strip out UTF-8 characters, you can use
$string = preg_replace('/[^(\x19-\x7F)]*/','', $string);

as described here.

Here's an example:
<?php
$string = "a bc…de f";
echo preg_replace('/[^(\x19-\x7F)]*/','', $string);
?>

Output:
a bcde f

Finally, you need to escape your input:
$string = preg_replace('/[^(\x19-\x7F)]*/','', $string);
$string = mysqli_escape_string($string);
$query = 'INSERT INTO notes (note) VALUES (' . $string . ')';
mysqli_query($conn, $query);

A: Before solving your problem, you shouldnt insert raw input into your database.
What you should do is:
error_reporting(E_ALL);
$string = mysqli_escape_string($conn, "… hello … world!");
mysqli_query($conn, $query);

error_reporting will show you raw errors on screen and escaping the string will:
a) Avoid SQL injections.
b) Insert the record even if it has special chars.
Now, if you need to remove those special chars use something like:
$string = preg_replace($pattern, "", $string);

before escaping it.


text:
Q: MS Graph Chaos Handler Is the tutorial here up to date?   If I follow this tutorial to add the Chaos Handler in the next middleware chain the authProvider fails to load. (config.authProvider). The instance of httpClient.middleware.authenticationProvider remains.  Logged from graphClient in the code below.  Noted out sections are the attempt.
The Chaos handler will appear in the nextMiddleware Chain but as indicated the authProvider is no longer loaded.
const msalApplication = new Msal.UserAgentApplication(msalConfig);
msalApplication.navigateToLoginRequestUrl = true;
const options = new MicrosoftGraph.MSALAuthenticationProviderOptions(graphScopes);

const authProvider = new MicrosoftGraph.ImplicitMSALAuthenticationProvider(msalApplication, options);
const authenticationHandler = new MicrosoftGraph.AuthenticationHandler(authProvider);

const chaosProvider = new MicrosoftGraph.ChaosHandlerOptions(MicrosoftGraph.ChaosStrategy.MANUAL, '429', 429, 100, undefined, undefined);
const chaosHandler = new MicrosoftGraph.ChaosHandler(chaosProvider);

//authenticationHandler.setNext(chaosHandler);

//const clientOptions = { middleware: authenticationHandler };

const clientOptions = { authProvider };

try
{
    graphClient = await MicrosoftGraph.Client.initWithMiddleware(clientOptions);
    console.log(graphClient);
    return graphClient;
}
catch (error)
{
    logOutput("Graph Authorization:" + error);
}

As a followup it appears as though providing a authProvider and a middleware chain is a one or the other scenario.  From the client library.
private constructor(clientOptions: ClientOptions) {
    validatePolyFilling();
    for (const key in clientOptions) {
        if (Object.prototype.hasOwnProperty.call(clientOptions, key)) {
            this.config[key] = clientOptions[key];
        }
    }
    let httpClient: HTTPClient;
    if (clientOptions.authProvider !== undefined && clientOptions.middleware !== undefined) {
        const error = new Error();
        error.name = "AmbiguityInInitialization";
        error.message = "Unable to Create Client, Please provide either authentication provider for default middleware chain or custom middleware chain not both";
        throw error;
    } else if (clientOptions.authProvider !== undefined) {
        httpClient = HTTPClientFactory.createWithAuthenticationProvider(clientOptions.authProvider);
    } else if (clientOptions.middleware !== undefined) {
        httpClient = new HTTPClient(...[].concat(clientOptions.middleware));
    } else {
        const error = new Error();
        error.name = "InvalidMiddlewareChain";
        error.message = "Unable to Create Client, Please provide either authentication provider for default middleware chain or custom middleware chain";
        throw error;
    }
    this.httpClient = httpClient;
}

After client initWithMiddleware(clientOptions) you can inject the middleware with graphClient.httpClient.setMiddleware() with the handler middleware chain and get the expected result.  But there appears to be a conflict with the MSAL authentication library as any attempt to use the .api() function with middleware fails miserably.

A: After upgrading to microsoft-graph-client@2.2.1 and msal-browswer-2.28.1 and including the graph-client-msalBrowserAuthProvider file.  The chaos handler now functions as expected.
Would have been nice if the file requirements were given in the tutorial since the chaos handler is a part of previous versions.
If you are having problems with middleware implementation then upgrading should do the trick.
I'm curious though if the graph-client-msalBrowserAuthProvider would solve the issue on previous versions....but alas I'm not going backwards now.


text:
Q: Until statement/loop python? Is there an until statement or loop in python? This does not work:
x = 10
list = []
until x = 0:
    list.append(raw_input('Enter a word: '))
    x-=1

A: The equivalent is a while x1 != x2 loop.
Thus, your code becomes:
x = 10
lst = [] #Note: do not use list as a variable name, it shadows the built-in
while x != 0:
    lst.append(raw_input('Enter a word: '))
    x-=1

A: while x != 0:
    #do stuff

This will run until x == 0

A: You don't really need to count how many times you're looping unless you're doing something with that variable.  Instead, you can use a for loop that will fire up to 10 times instead:
li = []
for x in range(10):
    li.append(raw_input('Enter a word: '))

As an aside, don't use list as a variable name, as that masks the actual list method.

A: Python emulates until loops with the iter(iterable, sentinel) idiom:
x = 10
list = []
for x in iter(lambda: x-1, 0):
    list.append(raw_input('Enter a word: '))

*

*I was forced to construct a trivial lambda for demonstration purposes; here a simple range() would suffice, as as @Makoto suggested.


text:
Q: Cannot find any information on property in bean... in Hello World I'm just starting out in JSP in Adobe CQ and I'm trying to do a simple Hello World to access data from the world's simplest Bean. From everything I've read, this is correct. What's going on here?
My JSP (html.jsp) is:
<%@page session="false"
        contentType="text/html;charset=UTF-8"
        import="org.apache.sling.api.request.ResponseUtil"
%>
<%@taglib prefix="sling" uri="http://sling.apache.org/taglibs/sling/1.0"%>
<sling:defineObjects/>
<html>
  <body>
<jsp:useBean id="myBean" class="com.example.helloBean.SampleUtil" >
        <jsp:getProperty name="myBean" property="text"/>
      </jsp:useBean>
  </body>
</html>

And I modified the template-generated "Hello World" class (SampleUtil.java) to be as follows:
package com.example.helloBean;
public class SampleUtil{
    private String text;
    public SampleUtil(){
        this.text = "Hello World.";
    }
    public  String getText() {
        return text;
    }
    public void setText(String text){
    this.text = text;
    }
}

When accessing the page I get
Cannot find any information on property 'text' in a bean of type 'com.example.helloBean.SampleUtil'

Possibly relevant details:
I generated this in CQ using the "Create Project" command in CRXDELite on /apps, which made a working Hello World, then modified the two files above.

A: Try to rename package name helloBean to hellobean everywhere. It should contain only lower-case letter.

A: i was also getting the same problem . just change the name of all methods in lowercase letters