text:
Q: Cannot autowire argument $tourist of "App\Controller\TouristController::edit()": it references class "App\Entity\Tourist" but no such service exists Изучаю Symfony 5. С помощью make:crud создал контроллер Tourist:
<?php

namespace App\Controller;

use App\Entity\Tourist;
use App\Form\TouristType;
use App\Repository\TouristRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/tourist")
 */
class TouristController extends AbstractController
{
/**
 * @Route("/", name="tourist_index", methods={"GET"})
 */
public function index(TouristRepository $touristRepository): Response
{
    return $this->render('tourist/index.html.twig', [
        'tourists' => $touristRepository->findAll(),
    ]);
}

/**
 * @Route("/new", name="tourist_new", methods={"GET","POST"})
 */
public function new(Request $request): Response
{
    $tourist = new Tourist();
    $form = $this->createForm(TouristType::class, $tourist);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($tourist);
        $entityManager->flush();

        return $this->redirectToRoute('tourist_index');
    }

    return $this->render('tourist/new.html.twig', [
        'tourist' => $tourist,
        'form' => $form->createView(),
    ]);
}

/**
 * @Route("/{id}", name="tourist_show", methods={"GET"})
 */
public function show(Tourist $tourist): Response
{
    return $this->render('tourist/show.html.twig', [
        'tourist' => $tourist,
    ]);
}

/**
 * @Route("/{id}/edit", name="tourist_edit", methods={"GET","POST"})
 */
public function edit(Request $request, Tourist $tourist): Response
{
    $form = $this->createForm(TouristType::class, $tourist);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $this->getDoctrine()->getManager()->flush();

        return $this->redirectToRoute('tourist_index');
    }

    return $this->render('tourist/edit.html.twig', [
        'tourist' => $tourist,
        'form' => $form->createView(),
    ]);
}

/**
 * @Route("/{id}", name="tourist_delete", methods={"DELETE"})
 */
public function delete(Request $request, Tourist $tourist): Response
{
    if ($this->isCsrfTokenValid('delete'.$tourist->getId(), $request->request->get('_token'))) {
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->remove($tourist);
        $entityManager->flush();
    }

    return $this->redirectToRoute('tourist_index');
}
}

Перейдя по ссылке /tourist/71/edit получаю ошибку:

Cannot autowire argument $tourist of "App\Controller\TouristController::edit()": it references class "App\Entity\Tourist" but no such service exists.

Я могу исправить эту ошибку, изменив метод edit:
public function edit($id, Request $request, TouristRepository         $touristRepository): Response
{
$tourist = $touristRepository->findOneBy(['id' => $id]);
$form = $this->createForm(TouristType::class, $tourist);
$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
    $this->getDoctrine()->getManager()->flush();

    return $this->redirectToRoute('tourist_index');
}

return $this->render('tourist/edit.html.twig', [
    'tourist' => $tourist,
    'form' => $form->createView(),
]);
}

Вопрос: правильное ли это решение, и, если нет, то как правильно? И почему CRUD сгенерировался неправильно?
Спасибо.

A: Круд в общем и целом сгенерен верно.
Предполагается что в случае с edit методом (как собственно и с другими) отрабатывает ParamConverter который вам должен возвращать Tourist взятый по id, однако в силу того что с 3.4 версии Symfony Container инжектит в методы контроллера сервисы автоматически, очень вероятно что из за этого происходит странность. Вообще говоря в документации пишут о том что аннотацию @ParamConverter можно опускать при определенных условиях, но у вас по какой то  причине происходит попытка внедрить Tourist как сервис.
Попробуйте использовать @ParamConverter явным способом, как , например, указано в документации. Ну и проверьте что он у вас не отключен (хотя в других методах ведь работает).


text:
Q: Emulate Server-Client TCP Communication I have a device (made in china) that works great but with a very annoying flaw. It's a massage device that will only work if it is connected to the internet at startup. Once it starts, it would work without the internet until it is turned off. So in short, if the internet is down, it will never work or it is impossible to bring this device on an area with no connection.
What I'm planning to do is emulate its server/client communication at start-up by using an old-PC that would run the server emulator software and some DNS re-routing and a WiFi router (using the PC as WAN).
I'll connect the device on the router, and its communication with the Chinese Server is emulated by the PC.
Can anyone give me an idea where to start, tools needed etc? I'm a programmer but new to packet emulation/replay. I've sniffed packets that the device does and its always consistent on every start/restart of the device. Here's the wireshark capture (IMG):
WireShark Packet Capture

A: You have two tasks, IMHO neither of them requires special tools:
Redirect requests to local address
You need to setup local DNS server and configure it to provide local IP address on hengdetech lookup. I didn't dive into this part, but google has plenty of forums discussing necessary config for different DNS servers.
Device most likely gets DNS server address from DHCP server. So you need to point device to local DNS instead of default one by configure DHCP server (which is run on your router, I suppose).
Once your DHCP configures local DNS and local DNS redirects hedgdete to local IP address, you are free to go to the second part which is
Emulate server behavior
Server must wait for some initial data from client before sending some data back. Such logic doesn't fit well into common "replay packets" tool capabilities, but it's quite easy to implement dumb TCP server with desired functionality on whatever language you like. Open socket, wait for data, send data, not a big deal, isn't it? So I wouldn't bother searching for the right tool, but would creat new instead.
If you need quick proof of concept, that you understand data flow right, before start coding, you may try netcat utility on Unix system for quick server emulation. I did the following once: extracted exchanged payload data from traces and saved as binaries (e.g. file1.bin is sent by server after the first request, file2.bin is sent after the second etc), then used something like this: cat - file1.bin - file2.bin | nc -l -p <local_port> -n. Using cat without dashes results into nc sending all files content to client, once it connects. Dash means "use data from console input rather than file" and they are used only as flow control. cat hangs on the first dash waiting for user input, so pressing ctrl+d proceeds to next file content and sends file1.bin, then hangs on the second dash. So you wait for the first request, press ctrl+d to send file1.bin content, then wait for the second request, press ctrl+d to send file2.bin content and so on.
EDIT
You generally got the idea of extracting data from wireshark traces right, but I want to clarify some subtlenesses.

When you said "saved binaries", did you mean to save individually captured packets as binaries so that netcat could send them to clients as a reply one by one (with the help of dash) ? If so, how do I save captured packets as binaries? Can I just extract them from the wireshark capture files, paste it on a new file and save as binary?

Only payload part of the packet needs to be saved, not the whole packet. TCP header, IP header and so on shouldn't be extracted, only tcp data section should be saved. Check second part of this answer for howto. I suppose, TCP data in your case consists of binary data rather than plain text, so you need to copy it as "raw binary" and use some binary editor allowing to paste "raw binary" into file such as frhed. So yes, you create new file and paste data copied from wireshark into it, so file consists of exactly the same bytes as packet payload.
Another thing to mention, TCP is a stream protocol, one packet doesn't always mean one response message. If you see several TCP packets of maximum size (aka MTU, which is usually 1.5 Kbytes) without PSH flag followed by packet of lesser size with PSH flag, they all contain parts of the single response message, so their payloads should be combined into one "fileX.bin".

redpajama_set_name: RedPajamaStackExchange


text:
Q: Invalid argument supplied for foreach() - Yet output is showing I am working to show editable fields based on query results. I know the query is functioning properly, and it is returning an array. The array is populating the form fields properly, however, I am getting the "Invalid argument supplied for foreach()" warning. I am new at this, and at a loss as to what is happening. I appreciate any suggestions.
Here is the code:
// Grab the profile data from the database
$query8 = "SELECT * FROM EDUCATION WHERE ID_NUM = '" . $_SESSION['IDNUM'] . "' ORDER BY RECORD";
$data = mysqli_query($dbc, $query8);

echo '
' . print_r($data, true) . '
';
$rowcount = 1;
while ($row = mysqli_fetch_assoc($data))
{
    if (is_array($row))
    {
        echo '
 It is an Array
';
    }
    foreach($row as &$item)
    {
        $record = $row['RECORD'];
        $school = $row['SCHOOL'];
        $type = $row['TYPE'];
        $degree = $row['DEGREE'];
        $major = $row['MAJOR'];
        $grad = $row['GRAD'];

        ?>
        <form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

        <fieldset>
        <legend>Education History </legend>
        <?php
        echo '<input type="hidden" id="record" name="record" value="' . $record . '">';
        echo 'Rowcount' . $rowcount. '
';
        // Insert Listbox here
        $queryschool = "SELECT * FROM SCHOOL";
        $list = mysqli_query($dbc, $queryschool);
        if($list)
        {
            echo 'School Type? ';
            echo '<select name="school_code">';
            while($row = mysqli_fetch_assoc($list))
            {
                echo "<option value={$row['CODE']}>{$row['TYPE']}" ;
                echo '</option>';
            }
            echo '</select>';
        }

        echo '
';
        echo 'School Name:';
        echo '<input type="text" id="school" name="school" size="40" maxlength="40" value="' . ( (!empty($school)) ? $school : "") . '" />
';

        // Insert Listbox here
        $querydegree = "SELECT * FROM DEGREE";
        $list = mysqli_query($dbc, $querydegree);
        if($list)
        {
            echo 'Degree Type? ';
            echo '<select name="degree_code">';
            while($row = mysqli_fetch_assoc($list))
            {
                echo "<option value={$row['CODE']}>{$row['DEGREE']}";
                echo '</option>';
            }
            echo '</select>';
        }
        echo '
';
        echo 'Field of study:';
        echo '<input type="text" id="major" name="major" size="40" maxlength="40" value="' . ( (!empty($major)) ? $major : "") . '" />
';
        echo 'Did you graduate?:';
        echo '<input type="radio" id="grad" name="grad" value="Y" ' . ($grad == "Y" ? 'checked="checked"':'') . '/>Yes ';
        echo '<input type="radio" id="grad" name="grad" value="N" ' . ($grad == "N" ? 'checked="checked"':'') . '/>No
';
        ?>
        </fieldset>
        <?php
        $rowcount++;
    }
}
;
echo 'Do you need to enter more educational experience?:';
echo '<input type="radio" id="another" name="another" value="Y" ' . ($another == "Y" ? 'checked="checked"':'') . '/>Yes ';
echo '<input type="radio" id="another" name="another" value="N" ' . ($another == "N" ? 'checked="checked"':'') . '/>No
';

?>

<input type="submit" value="Save Profile" name="submit" />
</form>

A: foreach ($row as &$item)

replace this with:
foreach ($row as $item)

And then for each variable you should probably change
$record = $row['RECORD'];

to
$record = $item['RECORD'];

A: foreach($row as &$item) should be
 foreach($row as $item)

there is no need to use the foreach here  you can just do this like  like
while ($row = mysqli_fetch_assoc($data))
{

$record = $row['RECORD'];
$school = $row['SCHOOL'];
$type = $row['TYPE'];
$degree = $row['DEGREE'];
$major = $row['MAJOR'];
$grad = $row['GRAD'];
}

A: You're not changing the row item, so don't pass by reference to the foreach. Also, shouldn't you be using $item instead of $row?   Do this:
foreach($row as $item)
 {
  $record = $item['RECORD'];
  $school = $item['SCHOOL'];
  ....

Don't do This:
foreach($row as &$item)
  {
  $record = $row['RECORD'];
  $school = $row['SCHOOL'];
  ....


text:
Q: how to annotate trait implemetation which returns Self, has specified lifetime? title seems to be similar with Lifetime parameter for `Self` in trait signature but I create this new post because I believe root cause is different.
I have a trait like following
trait T<'a> {
    fn new(y: &'a Y) -> Self where Self: Sized;
    fn do_something(&self);
}

and want to write generic function that accept type X (which implements trait T<'a>), and reference of Y, then create dyn Trait T<'a>.
fn create_t_from_i<'a, I: T<'a>>(y: &'a Y) -> Box<dyn T<'a>>

my naive implementation is like this
fn create_t_from_i<'a, I: T<'a>>(y: &'a Y) -> Box<dyn T<'a>> {
    return Box::new(I::new(y)) as Box<dyn T<'a>>;
}

then I got this error.
error[E0310]: the parameter type `I` may not live long enough

but parameter type I has constraint T<'a>, I don't figure out why this does not tell rustc to I::new(y) is alive after execution step go out from this function.
I suspect this is happened by I:new() returns Self, which has no lifetime annotation. but also I cannot find the way to give lifetime annotation to Self.
this is full example to cause the error.
struct Y {
    z: i32
}

struct X<'a> {
    y: &'a Y
}

trait T<'a> {
    fn new(y: &'a Y) -> Self where Self: Sized;
    fn do_something(&self);
}

impl<'a> T<'a> for X<'a> {
    fn new(y: &'a Y) -> X<'a> {
        return X::<'a> {
            y: y
        }
    }
    fn do_something(&self) {
        println!("{}", self.y.z)
    }
}

fn create_t_from_i<'a, I: T<'a>>(y: &'a Y) -> Box<dyn T<'a>> {
    // error: the parameter type `I` may not live long enough
    return Box::new(I::new(y)) as Box<dyn T<'a>>;
}

fn main() {
    let y = Y { z: 123 };
    {
        let t = create_t_from_i::<X>(&y);
        t.do_something()
    }
}

if I remove definition of T::new and giving X::new to create_t_from_i as function pointer, code seems work (need to use T + 'a instead of T<'a>). but what essential difference is from 1st example?
struct Y {
    z: i32
}

struct X<'a> {
    y: &'a Y
}

trait T {
    fn do_something(&self);
}

impl<'a> X<'a> {
    fn new(y: &'a Y) -> X<'a> {
        return X::<'a> {
            y: y
        }
    }
}
impl<'a> T for X<'a> {
    fn do_something(&self) {
        println!("{}", self.y.z)
    }
}

fn create_t_from_i<'a, I: T + 'a>(ctor: fn (y: &'a Y) -> I, y: &'a Y) -> Box<dyn T + 'a> {
    // if passing constructor function directly and using annotation I: T + 'a, rustc does not complain.
    let i = ctor(y);
    return Box::new(i) as Box<dyn T + 'a>;
}

fn main() {
    let y = Y { z: 123 };
    {
        let t = create_t_from_i::<X>(X::new, &y);
        t.do_something()
    }
}

anyone have an idea why this happens and how to make `rustc' happy?
regards.

A: fn create_t_from_i<'a, I: T<'a>>(y: &'a Y) -> Box<dyn T<'a>>

is implicitly the same as
fn create_t_from_i<'a, I: T<'a>>(y: &'a Y) -> Box<dyn 'static + T<'a>>

which in turns means that I must also have a static lifetime to be able to store it in the returned box (i.e. you need a I: 'static bound).
To solve this, you can add another lifetime parameter for the lifetime of I, and use that in the returned boxed trait. This will work no matter what the lifetime of I actually is:
fn create_t_from_i<'a, 'b, I: 'b + T<'a>>(y: &'a Y) -> Box<dyn 'b + T<'a>>
//                     ^^^^^^^^^                               ^^^^

Playground example

A: Any trait object has a lifetime annotations, which will implicitly be 'static.
Your function is thus:
fn create_t_from_i<'a, I: T<'a>>(y: &'a Y) -> Box<dyn 'static + T<'a>>

The solution is to explicitly annotate your trait object's lifetime:
fn create_t_from_i<'a, I: 'a + T<'a>>(y: &'a Y) -> Box<dyn 'a + T<'a>>


text:
Q: Flex Bison: Building C Compiler - Line number in error message When I try to print my line number in my yyerror function, I get an error. I'm working on OSX.
(line number in compiler.l)
%{

#include "compiler.tab.h"
int lineNumber = 1;

%}
%%

int { return INT; }
float { return FLOAT; }
void { return VOID; }
do { return DO; }
while { return WHILE; }
if { return IF; }
return { return RETURN; }
else { return ELSE; }
\/\/(.)* { return COMMENT; }
\/\*(.)*\*\/ { return COMMENT; }
[a-zA-Z][a-zA-Z0-9_]* { return IDENT; }
[0-9]+\.[0-9]+ { sscanf(yytext, "%lf", &yylval.reell); return FVAL; }
[0-9]+ { yylval.integer = atoi(yytext); return IVAL; }
\( { return OPA; }
\) { return CPA; }
\{ { return OB; }
\} { return CP; }
\; { return SEMICOLON; }
\, { return COMMA; }
\! { return NOT; }
\-\- { return DECREMENT; }
\+\+ { return INCREMENT; }
\<\< { return LSHIFT; }
\=\= { return EQUALS; }
\<\= { return LTOE; }
\>\= { return GTOE; }
\&\& { return AND; }
\|\| { return OR; }
\= { return ASSIGNMENT; }
\< { return LT; }
\> { return GT; }
\/ { return DIVIDE; }
\* { return MULTIPLY; }
\+ { return PLUS; }
\- { return MINUS; }
[ ]+ { return BLNK; }
[\n]* { ++lineNumber; return NL; }

%%

compiler.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "compiler.h"

extern int lineNumber;

int main (void)
{
    yyparse();
    return 0;
}

void yyerror(char * str)
{
    fprintf(stderr, "Error: %s, Line %d\n", str, lineNumber);
}

I get the following error message:

Undefined symbols for architecture x86_64:   "_lineNumber", referenced
  from:
        _yyerror in compiler.o ld: symbol(s) not found for architecture x86_64 collect2: ld returned 1 exit status

This is the command (shell file) I use to compile:
#!/bin/bash

flex  compiler.l
bison -d compiler.y

gcc -g -c compiler.tab.c -o compiler_y.o
gcc -g -Wall -std=c99 -c lex.yy.c
gcc -g -c compiler.tab.c -o compiler_y.o

gcc -g -Wall -std=c99 -c compiler.c
gcc -g -o compiler compiler.o compiler_y.o lex.yy.o -lm -lfl

A: You can use %option yylineno in your flex source and then the variable int yylineno will give the line-number of your current token. Beware not to use yylineno from the grammar (bison/yacc) as the tokenizer in general is ahead of the parser. If you want to use line numbers in the parser, typically the line numbers are attached to the tokens, so the parser has access through the tokens.
The error message is likely caused by not linking in compiler.tab.o, obtained from compiler.l by running flex on it and then passing it through the C-compiler.


text:
Q: Rank() Over Partition By to rank over a table column to give me the older records THis is what i have -  a query that retrieves all the Persons that have a duplicated email address believe rank over partition by should solve my problem (The filter is the Email Address)
SELECT a.Id, a.EmailAddress,a.UntilDate,a.CreatedOn,a.UserId
    INTO #GetEmployeesWithDuplicateEmails
    FROM Employee a
    INNER JOIN (SELECT
                    Employee.EmailAddress as EmailAddress
                FROM Employee
                GROUP BY Employee.EmailAddress
                HAVING count(Employee.EmailAddress) > 1
                    ) b
    ON a.EmailAddress = b.EmailAddress
    ORDER BY a.Id

this is the output of the query Query Result
What i want - Query below retrieves the users that have duplicated EmailAddresses, i want to keep the most recent record by each email, if the email belongs to the same UserId of course, imagine that there are 5 duplicated emails, if i verify that those 5 duplicates belong to the same UserId i want to keep the newest record based on the CreatedOn field, the other 4 will be updated . I wanted to use rank over partition by, but you can advise me with a better scenario anyways here goes:
    SELECT          #GetEmployeesWithDuplicateEmails.*,
                RANK() OVER (
                PARTITION BY #GetEmployeesWithDuplicateEmails.CreatedOn
                 ORDER BY #GetEmployeesWithDuplicateEmails.CreatedOn DESC) createdon_rank
INTO         #TableValuesToDelete
FROM        #GetEmployeesWithDuplicateEmails
INNER JOIN
(
  (SELECT #GetEmployeesWithDuplicateEmails.[EmailAddress]
    FROM #GetEmployeesWithDuplicateEmails
    GROUP BY #GetEmployeesWithDuplicateEmails.[EmailAddress])
) as temp2 ON #GetEmployeesWithDuplicateEmails.[EmailAddress]=temp2.[EmailAddress]

update
        #TableValuesToUpdate
SET
        #TableValuesToUpdate.EmployedUntilDate=getDate()
WHERE
        created_rank > 1

i want to retain the most recent record by each email if the email belongs to the same UserId, Imagine that there are 5 duplicated emails, if i verify that those 5 duplicates belong to the same UserId i want to keep the newest record based on the CreatedOn field  .
Update: Just Updated my Partion By query but it still can't rank the displayed values

A: If you want email addresses that belong to multiple users, you can use:
select e.*
from Employee e
where exists (select 1
              from Employee e2
              where e2.EmailAddress = e.EmailAddress and
                    e2.id <> e.id  -- or however you identify the same employee
            )
order by e.EmailAddress;


text:
Q: CMake does not find boost_thread I am trying to install the OpenGM library. However, while using CMake, I get the following error:
 CMake Error at /usr/local/share/cmake-3.6/Modules/FindBoost.cmake:1753 (message):
   Unable to find the requested Boost libraries.

   Boost version: 1.62.0

   Boost include path: /usr/local/include

   Could not find the following Boost libraries:

           boost_thread

   Some (but not all) of the required Boost libraries were found.  You may
   need to install these additional Boost libraries.  Alternatively, set
   BOOST_LIBRARYDIR to the directory containing Boost libraries or BOOST_ROOT
   to the location of Boost.

However, when I do:
ls -l

in
/usr/local/include

I get the following line:
 lrwxr-xr-x   1 Florian  admin   36 13 oct 19:11 boost -> ../Cellar/boost/1.62.0/include/boost

which suggests that it looks in the right directory.
In:
/usr/local/lib

I have:
libboost_thread-mt.a
libboost_thread-mt.dylib

So, it seems that the boost_thread library does exist...
Regarding the CMake configuration related to Boost, I have:
 Boost_DIR                        Boost_DIR-NOTFOUND
 Boost_INCLUDE_DIR                /usr/local/include
 Boost_LIBRARY_DIR_DEBUG          /usr/local/lib
 Boost_LIBRARY_DIR_RELEASE        /usr/local/lib
 Boost_PYTHON_LIBRARY_DEBUG       /usr/local/lib/libboost_python.dylib
 Boost_PYTHON_LIBRARY_RELEASE     /usr/local/lib/libboost_python.dylib

If it can help, I am under Mac OSX and Boost was installed through:
brew install boost --with-python
brew install boost-python

A: I have managed to handle this error by setting the Boost multithreading flag to ON n CMakeLists.txt.


text:
Q: Entity Framework code first tries to open wrong database I am writing an ASP MVC 3 application. I am using Sql Server 2008 R2 for my database.
I created my data model and my DbContext called EFDbContext.
I created my database which is named SportsStore.
My connection string is:
<add name="EFDbContext" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=SportsStore;Integrated Security=True;Pooling=False" providerName="System.Data.SqlClient" />

I run the app and no data is shown.
I figured out that EF automatically generates a new database SportsStore.Domain.Concrete.EFDbContext, but I want it to use SportsStore which I have previously created, and to automatically map my model properties to table columns.
If I disable the autogenerate database feature I get the following error:

Cannot open database "SportsStore.Domain.Concrete.EFDbContext"
  requested by the login

Shouldn't Entity Framework try to open SportsStore database? Why is it trying to open that one? Do I have a mistaken connection string?

A: Strange... have you tried this for your connection string? I think you need MARS to do some things with DbContext.
<add name="EFDbContext" connectionString="Data Source=LOCALHOST\SQLEXPRESS;Initial Catalog=SportsStore;Integrated Security=True;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />

Those are the only things different than one of my projects where this works. You are sure the class & connection string are named exactly alike? Did you try naming the connection string like this?
<add name="SportsStore.Domain.Concrete.EFDbContext" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=SportsStore;Integrated Security=True;Pooling=False" providerName="System.Data.SqlClient" />

A: I can give you just a suggestion.
I came accross with a similar difficulties when I have my DbContext and corresponding connectionstring in one project (usually class library). However it ignores the latter if you use it in other project like win forms. It tries to get the connection string from the startup project's config file.
If this is your case try to place your connection string in your startup project config file.

A: hmm.I was getting same error.after some effort i realized that i had put connection string in wrong Web.config file.There are two web config files.One under view folder and another under the project.You need to add connection string in one under the project folder

A: I had commented out the default connection string and placed mine underneath:
<connectionStrings>
<!--<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MvcMovie-20130509163734;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-Mvc4Movie-20130509163734.mdf" providerName="System.Data.SqlClient" />-->
<add name="MoveieDBContext" ...

This made EF ignore my connection string and generate its own. Uncommenting the default connection made EF use mine and it all worked.


text:
Q: Problems with link to eval()in RoR What am I doing wrong here?
This seems to work fine earlier in my code:
-@images.each do |img|
          -link_to eval(params[:action] + '_image_path(img)') do
             =image_tag img.image.url(:thumbnail)

But this is not working. Why not?
 -link_to eval(params[:action] + '_image_path(@featured_image)') do
    =image_tag @featured_image.image.url(:display)

I am seeing "Uncaught TypeError: Cannot call method 'bind' of undefined" There seems to be an issue with calling _image_path(@featured_image)'. :(

A: Is it possible that @featured_image is undefined? That seems like what's happening here.


text:
Q: Desktop Launcher not Working on Elementary OS I'm still learning about how to make a desktop launcher. I'm trying to make a desktop launcher for the XAMPP Manager (a.k.a. the GUI).
This is the location of the .run file:
/opt/lampp/manager-linux-x64.run

And here's the desktop entry i'm trying to make with the name xampp-gui.desktop :
[Desktop Entry]
Name=XAMPP Control Panel
Comment=Start and Stop XAMPP Services
Exec=sudo /opt/lampp/manager-linux-x64.run
Icon=/opt/lampp/htdocs/favicon.ico
Type=Application
Categories=Programming
Terminal=false

I also have done the chmod +x to the .run file and the .desktop file.
When i tried to launch it, nothing happens. Perhaps i did any mistake or missing something?


text:
Q: How to access a button using its name as a string in a for loop I need to access a button in a for loop but it's Name has to be changed.
Ex:

*

*There are a number of buttons whose Names are bt1,bt2,bt3,...bt25.

*I'm using a for loop in my code for certain purpose to disable or enable those buttons.

*Can I use a for loop to do this??

Like:
for(int i =1;i<25;i++)
{
    "bt"+"i".Enable = True;
}

How cam I make the string as a control?

A: for(int i =1;i<25;i++)
{
    this.Controls["bt"+ i.ToString()].Enable = True;
}

VB (using code converter):
For i As Integer = 1 To 24
    Me.Controls("bt" & i.ToString()).Enable = [True]
Next

A: You can do it in one line with LINQ
Controls.OfType<Button>().ToList().ForEach(b => b.Enabled = false);

VB (also via converter)
Controls.OfType(Of Button)().ToList().ForEach(Function(b) InlineAssignHelper(b.Enabled, False))

A: you can use following code :
foreach (Control ctrl in this.Controls)
            {
                if (ctrl is Button)
                {
                    ctrl.Enabled = true;
                }
            }

if its inside any container control , then try this :
foreach (Control Cntrl in this.Pnl.Controls)
            {
                if (Cntrl is Panel)
                {
                    foreach (Control C in Cntrl.Controls)
                        if (C is Button)
                        {
                            C.Enabled = true;
                        }
                }
            }

if want to implement in VB, then try this :
For Each Cntrl As Control In Me.Pnl.Controls
    If TypeOf Cntrl Is Panel Then
        For Each C As Control In Cntrl.Controls
            If TypeOf C Is Button Then
                C.Enabled = False
            End If
        Next
    End If
Next

A: for(int i =1;i<=25;i++)
{
    this.Controls["bt"+ i].Enable = True;
 //Or
    //yourButtonContainerObject.Controls["bt"+ i].Enable = True;
    // yourButtonContainerObject may be panel1, pane2 or Form, Depends where
   // your buttons are added. 'this' can be used in case of 'Form' only
}

Above code is valid only if you really have 25 buttonns and named as bt1,bt2,bt3...,bt25
       foreach (Control ctrl in yourButtonContainerObject.Controls)
        {
            if (ctrl is Button)
            {
                ctrl.Enabled = false;
            }
        }

Above code is better if you want to enable all the buttons in a particular container (Form or panel etc).


text:
Q: Can I create a table on my DB without creating a plugin? I have a built in form I created on my WP website .
I want to store the inputs to a table on my DB.
All tutorials that explane how to create a talke include the fact that I have to create a plugin for that.
All my functions are written in functions.php and I prefer to write the function that creates the DB there too.
If I write the function that creates the table in functions.php - will it make multiple tables or something like that? or does it work only once?
can I just create one using PHPMYADMIN ? or it will not include the built-in wordpress security ect'?

A: When I started out with Wordpress I was anti-plugin. I wanted to add everything in my theme's functions.php. When I looked at the bigger picture it began making sense having and leaving some functionalities inside a plugin.
There are many write-ups on the subject of what should go into a plugin and what should go into a theme. I, for one, have done one or two posts on this subject, so do yourself the favor and read up on this. I believe it will be very helpful and insightful.
Functions in a plugin and functions in a theme's functions.php does exactly the same job, there is no difference. The only thing is, you cannot declare a function in plugin and redeclare it in your theme. This will throw a fatal error crashing the site
To answer your issue, yes, if you think logically about this, your functionality should go into a plugin as this gives functionality to your site, and not the theme. This is functionality that you would need when you switch themes. It is just easier in plugin as you don't need to write or copy this code over and over again into a new theme.
But the choice is still yours. Adding it to your theme is your own choice, although, as I said, not really recommended. But either way, the code will work perfectly fine in a theme and in a plugin, so the choice is yours to make where to add it

A: I didn't do this recently but in 2014, in a few WordPress projects that I need additional tables I used Laravel components.
In WordPress, if you want to create your own tables by using wpdb and mysql queries. But with the Laravel database classes I managed to do this much more elegantly.
A quick rundown how I do this:
(note: At the time, I used Laravel 4 components, I haven't tried with 5)
"require": {
    "illuminate/database": "*",
    "illuminate/container": "*",
    "shuber/curl": "dev-master",
    "sunra/php-simple-html-dom-parser": "v1.5.0"

},

I installed the necessary packages (first two) with composer in functions.php (or in a functionality plugin)
I used it for saving an index of magazine articles content, a Recorder class (not very SOLID approach, sorry)
<?php
namespace Dion\Volumes;

use Illuminate\Database\Capsule\Manager as Capsule;

class Recorder {

    public static $table = 'volume_content';

    public function __construct(Page $page){
        $this->recordPage($page);
    }

    public static function createTables()
    {
        if( ! Capsule::schema()->hasTable(static::$table) ) {

            Capsule::schema()->create(static::$table, function($table) {
                $table->increments('id');
                $table->string('volume');
                $table->integer('month');
                $table->integer('year');
                $table->integer('page');
                $table->longtext('page_content');
            });
        }
    }

    public function recordPage($page)
    {
        //check if exists
        $exists = Capsule::table(static::$table)->where('volume',$page->volume)
                                    ->where('page',$page->page)->get();

        if( empty( $exists ) ) {

            $insert = Capsule::table(static::$table)->insert($page->toArray());
        } else {
            $update = Capsule::table(static::$table)->where('volume',$page->volume)
                                                    ->where('page',$page->page)
                                                    ->update($page->toArray());
        }
    }
}

and in the functions.php I added the Laravel database component and made it work like this.
global $wpdb;
$capsule = new Capsule;

$capsule->addConnection(array(
    'driver'    => 'mysql',
    'host'      => DB_HOST,
    'database'  => DB_NAME,
    'username'  => DB_USER,
    'password'  => DB_PASSWORD,
    'prefix'    => $wpdb->prefix,
    'charset'   => DB_CHARSET,
    'collation' => 'utf8_unicode_ci',
));

$capsule->bootEloquent();

// Make this Capsule instance available globally via static methods... (optional)
$capsule->setAsGlobal();

//this one creates table if not exists. Its better to run it in a WP action, like admin_init
$createVolumes = Dion\Volumes\Recorder::createTables();

Hope it helps, if you like this solution and have questions, I'll be happy to add more.

A:
can I just create one using PHPMYADMIN ?

Yes.You can. And its a shortest way to do it.


text:
Q: How to run a group of PowerShell scripts in Azure I have a group of interdependent .ps1 scripts I want to run in Azure (trying to set up continuous deployment with git, Pester unit tests, etc., as outlined in this blog).  How can I run these scripts in azure without needing to manage a server on which those scripts can run?  E.g., can I put them in a storage account and execute them there, or do something similar?
Using an Azure automation account/runbook seems to be limited to a single script per runbook (granted, you can use modules, which is insufficient in my case).
Note that I need to use PowerShell version 5+ (I noticed Azure web apps and functions only have 4.x.)
Thanks in advance!

A: You were on the right track with Azure Functions.  However, given that you need v5+ of PowerShell, you may want to look at Azure Container Instances (ACI) instead.  It's a little different approach (via containers), but should not impose any limitations and will free you from having to manage a virtual machine.
Note: At this time ACI is in preview. Documentation is available here.
There is a PowerShell container image available on Docker Hub that you could start with.  To execute multiple scripts in the container, you can override CMD in the docker file.


text:
Q: how to remove specific parts of string in python I tried to remove specific words have same pattern that is specific same word next to.
doc = ["super man good weather", "bet man nice car", "iron man awesome soup"]
I want to remove 'super man', 'bet man', 'iron man' . these strings have same word 'man' and I want to remove the word in front of the same word 'man' at the same time.
I tried this but, failed.
for string in doc:
    prep = re.sub('.* man =', '', string)

A: Not the elegant way of doing it. But serves the purpose.
doc = ["super man good weather", "bet man nice car", "iron man awesome soup", "a manned mission to mars"]

keyword = " man " # to make sure that you don't remove words that contain man as substring

doc = [string.split(keyword)[1].strip() if keyword in string else string for string in doc]

print(doc)

Output
['good weather', 'nice car', 'awesome soup', 'a manned mission to mars']

See this in action here
Regex based solution
import re
doc = ["man super man good weather", "a bet man nice car", "iron man awesome man soup", "a manned mission to mars"]
doc = [re.sub('\w+ man ', '', string).strip() for string in doc]
print(doc)

Output
['man good weather', 'a nice car', 'soup', 'a manned mission to mars']

See it in action here

A: Try this.. SHould work using re
[re.sub('[a-zA-Z]+\s{1}man', '', txt).strip() for txt in doc]

A: My approach would be
re.sub('\w+ man ', '', t)


text:
Q: dynamic exception specifications are deprecated I have C++ code that used to compile (and work), now I get lots of warnings.  This happened after I did a dist-upgrade to Ubuntu-Mate.

warning: dynamic exception specifications are deprecated in C++11

It happens on lines as simple as this (in a header):
    static Value getPriorityValue(const std::string& priorityName)
    throw(std::invalid_argument);

I got 2545 warning related to this!  Is there anyway to tell the compiler to ignore this warning?  What is the easiest way to make changes to the code.
Most of the errors are in a 3rd party package so I don't want to make too many modifications to this package.
I do have the -std=c++11 flag on in my compiler.

A: You should remove or comment out these exception specifications wherever you can1, e.g.:
static Value getPriorityValue(const std::string& priorityName);
static Value getPriorityValue(const std::string& priorityName) /* throw(...) */;

You can use the -Wno-deprecated option to turn-off depreciation warnings for places where you cannot edit the code. I would recommend only using it when compiling third-party libraries. If you need to include a third-party header that raise such warning, you could do2:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated"
#include "thirdparty.h"
#pragma GCC diagnostic pop

This should work with both gcc and clang and will only disable -Wdeprecated for specific includes.
1 Dynamic exception specifications are deprecated since C++11, and are illegal since C++17, so you might want to get rid of them and upgrade third-party libraries you are using as soon as possible.
2 If you include these headers using a -I argument, you could switch to -isystem to disable all warnings for these headers, as mentioned by @Yakk - Adam Nevraumont. See also How to suppress GCC warnings from library headers?.


text:
Q: Different iphone model on same layout I search what is the great way for creating a different view for any iPhone.
Example, I want to have a different view in portrait mode for iPhone 4s, 5/5s, 6/6s and another in landscape for 4s, 5/5s, 6/6s
I find the idea to create a different storyboard for 4s, 5/5s... But if i want to change anything, I must remember to change it on all storyboard! and this method create unnecessary Mb.
I'm in Xcode 7 and i want to use only storyboard interface because I beginning and I want to understanding how this work.


text:
Q: $cos^2$ identity where $sin^2$ has a coefficient Does $1-\lambda^2 \times \sin^2\ = \lambda^2 \times \cos^2$ ? I'm trying to do Von Neumann analysis for convergence and I'm struggling to reduce the LHS under a square root.

A: Only if $\lambda=\pm1$. Otherwise, generally what we have is
$$\lambda^2-\lambda^2\cdot\sin^2=\lambda^2\cdot\cos^2\,.$$

A: No. The trig identity is $\sin^2x+\cos^2x = 1$. You can of course multiply this entire equation by a constant, say, $\lambda^2$, but that only gives you
$$\lambda^2*\sin^2x+\lambda^2*\cos^2x = \lambda^2.$$
(Unless $\lambda=1$ or $\lambda=-1$, of course.)


text:
Q: Why is my Lazy re-initializing every time I call Value? I have a member of my controller
    private Lazy<MyCache> loadedComponentCache = new Lazy<MyCache>(() =>
    {
        MyCache instance = MyCacheb.Instance;
        instance.LoadStuffAsync().Wait();
        return instance;
    }, LazyThreadSafetyMode.PublicationOnly);

that I'm using to lazy-call a long-running method LoadAsync() that will only need called if a certain API endpoint is hit after the user goes to the page.
    [HttpGet]
    public ActionResult GetStuff()
    {
        var results = from component in loadedComponentCache.Value.All()
                      // ...
    }

Any idea why it's re-loading every time the API endpoint is hit? My understanding is that an instance of my controller is created only when the user goes to the page and thus this will only be hit once per API call per user visiting the page.

A: You could make loadedComponentCache static but that's not ideal. If you are using an IoC container you could register it as a singleton. These long lived objects are generally to be avoided though if possible.
If you you truely need this long lived cache then you should probably consider using something like Redis which is designed and optimised for this sort of scenario and can be distributed across multiple nodes. https://redis.io/topics/introduction


text:
Q: Why are there 3 identical tables in Magento2? We came across three absolutely identical in structure tables in M2 DB:

*

*cataloginventory_stock_status

*cataloginventory_stock_status_idx

*cataloginventory_stock_status_tmp
Anybody has any idea why such redundancy has been introduced?

A: the cataloginventory_stock_status is the one that is used for reading in the frontend.
In order to not interfere with the table reads, when the stock index is running it is writing in the _tmp and/or _idx table and when it's done, the values are moved to the main table.
The temporary table used is determined by this method \Magento\CatalogInventory\Model\ResourceModel\Indexer\Stock\DefaultStock::tableStrategy::getUseIdxTable().
So in case it is true, the _idx table is used as temporary table. Otherwise the _tmp table is used.
The _idx table is used when you rebuild all the indexes, but I didn't find a case when the _tmp table is used, or what's the difference is between them.
I will report back when/if I find our more.


text:
Q: Dialog box is not closing flutter Here's my Alert dialog code: I've added Navigator.pop(context); in the tapped method call. But it's not closing.
 showLoginDialog(BuildContext context,
  {TextEditingController usernameController,
  TextEditingController loginController}) {
var textController = new TextEditingController();
var nameTextController = new TextEditingController();
String dateToPost;
Alert(
    context: context,
    title: "Add Profile",
    content: Column(
      children: <Widget>[
        TextField(
          controller: nameTextController,
          decoration: InputDecoration(
            labelText: 'Name',
          ),
        ),
        TextField(
          controller: textController,
          onTap: () async {
            DateTime date = DateTime(1900);
            //FocusScope.of(context).requestFocus(new FocusNode());

            date = await showDatePicker(
                context: context,
                initialDate: DateTime.now(),
                firstDate: DateTime(1900),
                lastDate: DateTime.now());

            var formatter = new DateFormat('dd MMM yyyy');
            var formatterToPost = new DateFormat('yyyy-MM-dd');
            String formatted = formatter.format(date);
            dateToPost = formatterToPost.format(date);
            print(formatted);

            textController.text = formatted;
          },
          decoration: InputDecoration(
            labelText: 'Birth Date',
          ),
        ),
      ],
    ),
    buttons: [
      DialogButton(
        onPressed: () {
          Navigator.pop(context);
           _saveData(textController.text, nameTextController.text,
               dateToPost);
        },
        child: Text(
          "Add",
          style: TextStyle(color: Colors.white, fontSize: 20),
        ),
      )
    ]).show();

}
Also, is shows error on second time click: The method 'call' was called on null.
Receiver: null
Tried calling: call()

A: I've solved this issue using
Navigator.of(context, rootNavigator: true).pop();

A: You should save the data before you close the application.
And instead of Navigator.pop(context) do Navigator.of(context).pop(true)
onPressed: () {
    _saveData(textController.text, nameTextController.text,
     dateToPost);
    Navigator.of(context).pop(true);
}


text:
Q: How to add System.Windows.Controls.WebBrowser in a System.Windows.Forms.Form I want to add a WebBrowser(System.Windows.Controls)
in a Form(System.Windows.Forms) I try this
this.Controls.Add(webBrowser);

but I have an error
cannot convert from 'System.Windows.Controls.WebBrowser' to 'System.Windows.Forms.Control'

How I can do that ? I don't want to use WebBrowser(System.Windows.Forms) I don't know what is the difference but I need some method existing in System.Windows.Controls and not in System.Windows.Forms.

A: You need to use an ElementHost control to wrap the WebBrowser control for use in Winforms.
Have a look at: http://msdn.microsoft.com/en-us/library/system.windows.forms.integration.elementhost%28v=vs.110%29.aspx
You need to do something like:
var elementHost = new ElementHost();
elementHost.Child = new System.Windows.Controls.WebBrowser();
this.Controls.Add(elementHost);


text:
Q: Yii Manual Ajax Post I am trying to manually send a ajax post request. I keep getting a "400 Bad Request". I am using yii 1.1.x on my localhost.
Here is my view:
view admin.php

<?php
$this->widget('zii.widgets.grid.CGridView', array(
        'id'=>'dealers-grid',
        'dataProvider'=>$model->search(),
        'filter'=>$model,
    'template' => '{summary}{pager}{items}{pager}{summary}',
    'columns'=>array(
                'name',
                'address1',
                'city',
                'state',
                'phone',
                array(
                        'header'=>Yii::t('multi', 'Settings'),
                        'htmlOptions' => array('class' => 'button-column'),
                        'type'=>'raw',
                        'value'=> function($data) {
                                        return 'did.');$("#mydialog").dialog("open"); return false;" class="settings" title="Update Setting" href="#">';
                                }
                ),

                array(
                        'class'=>'EButtonColumnWithClearFilters',
            'label'=>Yii::t('multi', 'Clear Search'),
        ),

        ),
));
?>

Controller - DealersController.php:
    public function accessRules()
    {
            return array(
                    array('allow', // allow dealerSettings user to perform 'manage' action
                            'actions'=>array('manage'),
                            'roles'=>array('dealersettings')
                    ),
        array('allow', 'actions'=>array('dealercontextswitch'), 'roles'=>array('authenticated')),
                    array('allow', // allow admin user to perform 'admin' and 'delete' actions
                            'actions'=>array('admin','delete', 'create', 'view', 'update', 'ajaxDs'),
                            'roles'=>array('admin'),
                    ),
                    array('deny',  // deny all users
                            'users'=>array('*'),
                    ),
            );
    }

...

    public function actionAjaxDs(){
            if (!YII_DEBUG && !Yii::app()->request->isAjaxRequest) {
                    throw new CHttpException('403', 'Forbidden access.');
            }
            echo "Made it";

    }

I had to add the accessRules for ajaxDs in order to access ajaxDs
From this code I am able to use js to alert the did. After that I get a 400 Bad Request error for http://localhost/dealers/ajaxDs
When I actually go to http://localhost/dealers/ajaxDs I get a page that says "Made it", Like it is supposed to.
I do not know why my ajax is not work.
How do I manually enter in an ajax url for yii
Any Help would be greatly appreciated!
**************EDIT*****************
If I remove the type: 'POST' it works

I'm not sure why, and I need to post the data

A: You could have error in your path


text:
Q: Python dictionary with math symbols I want to make a dictionary in Python, but with math symbols (because then i want to plot that with the symbols).
So, i have something like this:
    dict_particles = {1: "Gamma",
              2: "e+",
             -2: "e-",
              3: "mu+",
             -3: "mu-",
              4: "pi0",
             -4: "pi+",
                  etc...}

Instead of the name "Gamma", for example, I want the symbol of the greek letter. Also i want to put super and subscripts to them.
Is it possible?

A: Yes, you can use any Unicode symbols in your Python code, even in variable names (applicable for Python 3.x, for Python 2.6+ look at @a_guest's comment).
You can also use unicode escapes ("π" = "\u03c0")

A: What are you using to plot them? If you are using matplotlib, you can just write latex:
https://matplotlib.org/users/mathtext.html
Then your dict might look like this:
dict_particles = {1: r"\gamma",
              2: r"\epsilon",
                  etc...}

and matplotlib will replace the latex by the correct symbols.

A: I have never tried to see if it is possible in other environments, but I achieved this using IDLE in python 3.x sometime last year; I used the alt codes to input the greek letters into my original code, so I would have it say
print("δ")
print("φ")

And they would print out as the literal strings without a problem.

A: If you are using matplotlib.pyplot, you could simply use the syntax mentioned here:
text = r'$\alpha > \beta$'

Which matplotlib.pyplot will translate into pretty greek symbols, for example with
plt.title(text)

For your concrete example:
dict_particles = {1: r"\Gamma",
                  2: r"\epsilon+", ...}


text:
Q: Homography from 3D plane to plane parallel to image plane I have an image in which there is a calibration target (known geometry) in a scene (let's say a simple 2" x 2" square lying on a table). I would like to perform a perspective transformation (using warpPerspective()) so that resulting image is an orthogonal view of the table (as if the camera axis was parallel with the table normal). The standard procedure for computing a homography is from a general plane to a different general plane where at least 4 correspondences are known in two images of the same scene (using getPerspectiveTransform()). In this case where I only have one image, is the correct thing to do to simply "make up" a plane and force the correspondences to some arbitrary position on that plane? For example, in this this situation I would simply make correspondences between the 4 detected corners (A,B,C,D) in the image and four points of my choosing (which essentially just define the pixel->real world scale. For example, I could choose A' = (0,0), B' = (20,20), C' = (0,20), D' = (20,0) to indicate in the resulting image there are 10 pixels per inch. Of course I could choose any scale here, and I could also choose any position for the square target to land in the output (i.e. A' = (100,100), B' = (120,120), C' = (100,120), D' = (120,100) ).
Is this the "correct" way to do this? Is there a better way to compute a projective transform that looks directly at a plane defined by a set of points in the image known to be in the plane?

A:
In this case where I only have one image, is the correct thing to do to simply "make up" a plane and force the correspondences to some arbitrary position on that plane?

Yes.
Note that getPerspectiveTransform in its present implementation requires exactly 4 correspondences. It finds a 3x3 perspective transform, which has 8 degrees of freedom (the [3,3] element is fixed 1), so it only needs 4 non-colinear correspondences, and any such correspondences will be enough. In contrast, findHomography uses RANSAC to deal with uncertainty and can figure out which of the correspondences should be trusted and which are outliers. If you prefer to stick to linear least squares, you could adopt getPerspectiveTransform to accept >=4 pairs.
However, if you apply a perspective transform that converts some distorted square target T onto a perfect square, this will only make planes that are coplanar with T also line-parallel. Other planes (e.g., perpendicular to T) will not be line-parallel after transform.
If you want to remove the perspective, i.e., change the projection to be orthographic, you can't do it with a perspective transform alone. You'd also need to know the depth of the objects in the scene, then project it onto the plane without perspective.


text:
Q: Downloading excel(.xlsx) with blob and FileSaver.js in vue project getting coruppted I am trying to download file by sending an Api request in my Vue project, and with response data I am trying to save the file using blob and FileSaver.js
sendAjaxCall.then(response => {
      let file = new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})
      FileSaver.saveAs(file, 'Export2.xlsx')
}

But I can not open the file, it is getting corrupted.

A: try this
     return Vue.axios.get(`api/excel_sheet`, {
        responseType: 'blob',
      }).then(response => {
      FileSaver.saveAs(response.data, 'Export2.xlsx')
};

u need to specify the response type as blob


text:
Q: Slickgrid v2.1 bug On Slickgrid example7-events.html
https://github.com/mleibman/SlickGrid/blob/master/examples/example7-events.html
if one changes the value of a cell on column Title and then immediately clicks on the Priority cell of the same row, the value of the cell on column Title looses the changes that were made, returning to its previous value. For example, on row 1, if we change the value of the Title cell from "Task 0" to "Whatever" and then immediately click on the corresponding Priority cell, changing its value to "High", the value of the Title cell annoyingly returns to "Task 0". But if we, instead of clicking in row 1 Priority cell, click on any other row's Priority cell, the value of the Title cell of the first row keeps the value "Whatever" as it should.
I'm using Slickgrid on a personal project and I also have this problem, but my onClick subscribe method is quite similar to the one on the example. So, the following questions raises: is this really a Slickgrid 2.1 bug, or is it a bug of example7-events.html? Does anyone has encountered this problem and somehow fixed it or found a workaround?

A: I ended up opening an issue on SlickGrid's project on GitHub and it was the example that was defective, not the framework. Here is the issue: https://github.com/mleibman/SlickGrid/issues/496.
Best regards


text:
Q: MacBookPro Core i7 - system profiler says "Number of cores: 2" I thought that "quad core" meant quad core. My system says that it has 2 cores, but perhaps I'm thinking of it wrong, or perhaps the OS ignores 2 cores. What do you know about the issue.
(Note: Intel isn't shipping the new dual core i5 / i7s until the 20th, so if mine actually is a "dual core", I'm gonna be mad).
Profiler output:
Model Name: MacBook Pro
  Model Identifier: MacBookPro6,2
  Processor Name:   Intel Core i7
  Processor Speed:  2.66 GHz
  Number Of Processors: 1
  Total Number Of Cores:    2
  L2 Cache (per core):  256 KB
  L3 Cache: 4 MB
  Memory:   4 GB
  Processor Interconnect Speed: 4.8 GT/s
  Boot ROM Version: MBP61.0057.B0C
  SMC Version (system): 1.58f16

A: You have the Intel i7 M620 with 2 cores. Mactracker confirms CPU model (i7 M620) for your device.
Apple doesn't advertise number of cores in tech specs, but the store clearly says:

Intel didn't offer models with 2+ GHz and 4 cores until 2011.


text:
Q: GNU GRUB - Is there any negative in using a grub text-only mode to boot into Ubuntu/Mint? Is "text" (GRUB_GFXPAYLOAD_LINUX=text) an acceptable long-term grub setting? Can it be presumed that the "GUI" (Mint Cinnamon X server etc) will faithfully take over to normal function after "text" booting?
Detail:
New to GNU GRUB. Limited Linux and Unix experience. Seeking education on this to avoid any future problem. Perusing the manuals at gnu.org informed the workaround below.
Experienced "boot to black screen" type problems with installs in a certain legacy situation, nomodeset did not work, but rather adding GRUB_GFXPAYLOAD_LINUX=text to /etc/default/grub worked to boot as a "normal" quiet black screen which continues to open an apparently normally running Linux Mint 21.
(also noted that GRUB_CMDLINE_LINUX="text" if paired with GRUB_TERMINAL=console worked similarly)
Final /etc/default/grub was
GRUB_TIMEOUT_STYLE=hidden
GRUB_TIMEOUT=0
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
GRUB_GFXPAYLOAD_LINUX=text```

A: No downside
At least none that I know of. There are some situations where the virtual terminal keeps the low resolution GRUB started with. However, this is irrelevant to you since you are using the graphical interface anyway.


text:
Q: Postgresql: Is there any need to define single-column index on a column which is part of composite unique constraint? Let say I have Item table, with composite unique constraint on company_id and code columns.
As documented, postgresql creates index on this constraint automatically. But if some queries
filter by company_id column but not code column, then to increase performance, should I define index on company_id column too?

A: It depends on how you defined your unique index (or constraint, which will automatically create a unique index with the affected columns, in that order).

A multicolumn B-tree index can be used with query conditions that involve any subset of the index's columns, but the index is most efficient when there are constraints on the leading (leftmost) columns. The exact rule is that equality constraints on leading columns, plus any inequality constraints on the first column that does not have an equality constraint, will be used to limit the portion of the index that is scanned ...

More in docs about Multicolumn Indexes


text:
Q: UI Bootstrap dropdown directive causes multidir issue Hi I'm trying to get the dropdown directive from UI Bootstrap to work. Whenever I try to use the 'dropdown' directive, I get this error message:
Console error msg:
Multiple directives [dropdown, dropdown] asking for 'dropdown' controller on:

http://errors.angularjs.org/1.3.9/$compile/multidir?p0=dropdown&p1=dropdown&p2='dropdown'ontroller&p3=%3Cli%class%3D%dropdown%20pos-stc%22%20dropdown%3D%22%22%3E
    at http://localhost:9000/bower_components/angular/angular.js:63:12
    at assertNoDuplicate (http://localhost:9000/bower_components/angular/angular.js:7990:15)
    at applyDirectivesToNode (http://localhost:9000/bower_components/angular/angular.js:7339:11)
    at compileNodes (http://localhost:9000/bower_components/angular/angular.js:6997:15)
    at compileNodes (http://localhost:9000/bower_components/angular/angular.js:7009:15)
    at compileNodes (http://localhost:9000/bower_components/angular/angular.js:7009:15)
    at compile (http://localhost:9000/bower_components/angular/angular.js:6904:15)
    at link (http://localhost:9000/bower_components/angular/angular.js:22225:9)
    at invokeLinkFn (http://localhost:9000/bower_components/angular/angular.js:8213:9)
    at nodeLinkFn (http://localhost:9000/bower_components/angular/angular.js:7722:11) angular.js:11594(anonymous function) angular.js:11594(anonymous function) angular.js:8544invokeLinkFn angular.js:8215nodeLinkFn angular.js:7722compositeLinkFn angular.js:7075publicLinkFn angular.js:6954boundTranscludeFn angular.js:7093controllersBoundTransclude angular.js:7749(anonymous function) angular.js:22173processQueue angular.js:13171(anonymous function) angular.js:13187Scope.$eval angular.js:14384Scope.$digest angular.js:14200Scope.$apply angular.js:14489done angular.js:9646completeRequest angular.js:9836requestLoaded

Can somebody tell me what the mistake could be? When I remove the directive everything is fine, except that the dropdowns dont't work :(
HTML:

      John.Smith

300mb of 500mb used

        <progressbar value="60" class="progress-xs m-b-none bg-white"></progressbar>

          30%
          Settings

        Profile

          new
          Help

        Logout

A: Assuming you are not using the latest version of bootstrap. Previous versions (ex: 0.11.0) have the directives class restricted (C) as well apart from attribute restricted (A). So you are repeating the directive for the element by specifying the class as well as with the attribute. That causes multiple directive error. You could just go with the classname, because you would need it anyways for appropriate built-in bootstrap css rules to apply. i.e change
 to
 or upgrade it to bootstrap 0.12.0.
Try:

And remember that when you upgrade it to version 0.12.0  or greater they have removed the class restriction on the directives and they will be default directive restricted based on the angular version used. So you would need to switch back to the way you have it right now. See this answer for more details.
Seems like the cause of the issue might be because you referred to the demo from the official website but with older version of bootstrap.


text:
Q: Clustering Docker containers behind load-balancers for HA Most Docker literature boasts that you can run hundreds, even thousands of containers on the same physical server. I'm wondering what this looks like from a load-balancing/clustering perspective.
Say I have a RESTful web service, fizz-service.war. Typically, with "normal" VMs, I might deploy this service to 50 VMs (say, fizzsvc01.example.com through fizzsvc50.example.com) and then cluster/load balance those VMs behind a service URL, such as http://fizz-service.example.com. When a request comes in, the load balancer select a node to forward the request on to, say, fizzsvc34:8080/fizz-service.
I'm wondering how this works with Docker containers. If I have the same 50 containers running across, say, 5 nodes:

*

*Can those nodes be either VMs or physical servers?

*For the containers running on the same nodes, do they each run on their own port? Otherwise, how could you have 50 instances of the service running on the same port?

*Whereas with "normal VMs", the load balancer is configured with all the VMs that make up the pool, and then I just deploy my service to each VM in the pool, how does this change with Docker containers? How does my load balancer (likely a separate piece of infrastructure such as F5 or nginx) "know" about all the containers available to distribute load to?

Or does my whole approach to HA/load balancing need to change when I step into Docker-land?

A: Each container will be running on a dedicated port (normally allocated by Docker) and you'll need some mechanism to keep track of each container, in order to generate the configuration for your load balancer.
So nothing really changes, except the number of containers is potentially much larger, requiring automation in order to be practical. Containers are much more instant compared to virtual machines.


text:
Q: Jqwidget Pie chart labels How to use the pie chart of jqxChart with custom labels?
This is the main demo:
http://www.jqwidgets.com/jquery-widgets-demo/demos/jqxchart/index.htm#demos/jqxchart/javascript_chart_pie_series.htm
In the pie I would like to have the description (in the example the Browser name) instead of percentage in the labels. Is it possibile? I found how to set it only for the legend but not in the label inside the pie.

A: Have you tried to implement the Chart's formatFunction which is used for formatting the Labels?


text:
Q: How to deal with matches pairwise in regex? I have a basic understanding of regex (I think) - but lookahead and all that just escapes me :(
So I have a sense that this should be doable with rx, but I have no idea how to do it.
I want to copy Markdown from Notion into MediaWiki. Both support MD - but different flavours. So I thought I could do some search & replace in a text editor to deal with the differences.
But: strikeout text is "~~text~~" in Notion and "<s>text</s>" in MediaWiki.

A: Interesting how one can think overly complex. It suddenly hit me that I don't have to worry about counting or doing advanced stuff looking at individual occurences of ~~, but that I could look at the paired case using a search string "~~(.*?)~~" and a replacement "<s>$1</s>".
Nice & easy


text:
Q: Java String ordering inside an android Textview I have a name like this
"3":"BBB, AAA, Location","2":"BBB, AAA, Location,"1":"BBB, AAA, Location"

I want the result like this
1. BBB, AAA, Location
2. BBB, AAA, Location
3. BBB, AAA, Location

I tried with this
Name.setText(Name.replace("\"", "").replace(":", ". "));

I know that /n will be use for new line. But, Still I bit confused How can I achieve that.

A: String[] newText = Name.split("\",\""); //it returns an array of strings
for (int i=0; i<newText.length; i++)
    newText[i] = newText[i].replace("\"", "").replace(":", ". ");
Arrays.sort(newText);
String ultimateText = "";
for (String s : newText)
    ultimateText = ultimateText+s+"\n";
Name.setText(ultimateText);

It's quite tricky. import Arrays.

A: As @HunterMcMillen stated you should use a Json libary, Gson is a good choice but can be a little advanced, maybe try http://json.org/java/ there are free librarys to use the JSON string.
Using any JSON library what you would do is get a JSON Object or array of those 3 options, put them in a array list and sort them. Then add it to your output formatted. I would start with changing the way you store that string you posted by storing as a JSON Object (be it Gson or Json.org). Then go from there.


text:
Q: Find the length of the line that connects Cylinder's bases
Points $A$ and $B$ are on different bases of the Cylinder. Line $AB$ is on plane $\alpha$, which is parallel to Cylinder's axis. Find the length of line $AB$, if it creates $45^\circ$ angle with the base of the cylinder. Also, cylinder's base has radius $=5$, the distance from the Cylinder's axis to the plane $\alpha$ is $4$.

I translated this problem, so if anything's ambiguous please do comment.
The picture wasn't given, but here's my best attempt (interpretation):

The dotted line is supposed to be a plane... The perpendicular line is the distance from the the axis to the plane $\alpha$, since it's parallel to the axis, the perpendicular will just lie on the base of the cylinder.. Correct me if i'm wrong here.
So after that, I couldn't really go anywhere, As far as i'm concerned, A and B could be anywhere on the bases... Please try to provide a geometrical view / explanation.

A: So far as I understood the plane parallel to cylinder axis cuts the cylinder at 4 distance units away, making a rectangular shaped intersection area width 6 units in the base plane. Line $AB$ makes minimum $45^{\circ}$ angle to its projection ( or width of rectangle, but not radius!) in this plane of intersection.

So $AB= 6 \sqrt{2}.$


text:
Q: How to Conditionally format cells based on if the most recent weekday (e.g. a Monday) is present as a date out of a list of dates
I want to make a box for each day of the week automatically turn green or red depending upon if a event occurred on a corresponding day.
So far I've found the formula '=date- WEEKDAY (date - 2)'

Ideally I want to be able to specify per person. and had a green/red button for each day of the week for each person.
Can anyone help me please?
I've tried everything I can think of


text:
Q: Strange behavior using goto for error handling in C I am developing a basic application in C, using the OP-TEE (TrustZone Secure OS) libraries. I am running the code in QEMU. Here is the code in which the strange behavior occurred:
void prepare_rsa_operation(TEE_OperationHandle *handle, uint32_t alg, TEE_OperationMode mode, TEE_ObjectHandle key) {
    TEE_Result ret = TEE_SUCCESS;
    TEE_ObjectInfo key_info;

    ret = TEE_GetObjectInfo1(key, &key_info);
    if (ret != TEE_SUCCESS) {
        EMSG("TEE_GetObjectInfo1: %#" PRIx32, ret);
        goto err;
    }

    ret = TEE_AllocateOperation(handle, alg, mode, key_info.keySize);
    if (ret != TEE_SUCCESS) {
        EMSG("Failed to alloc operation handle : 0x%x", ret);
        goto err;
    }
    DMSG("========== Operation allocated successfully. ==========");

    ret = TEE_SetOperationKey(*handle, key);
    if (ret != TEE_SUCCESS) {
        EMSG("Failed to set key : 0x%x", ret);
        goto err;
    }
    DMSG("========== Operation key already set. ==========");

err:
    TEE_FreeOperation(handle);
    return 1;
}

Problem that occurred:
Both successful messages were being printed (for operation allocated and key setting), but the err label was being reached even though: the TEE_FreeOperation(handle); should be written TEE_FreeOperation(*handle);. I fixed this and removed the return, since my function returns void. Now, the code is working fine, but, in my understanding, the err label should be reached only if one of the conditional tests (if's) fail, since the goto command is just inside them.
Am I wrong with this understanding? Can anyone explain me why the err label was being reached even though no error occurred before?

A: The err: label is reached either if you goto it or after executing DMSG("========== Operation key already set. ==========");. Meaning you get a clean-up no matter if the function was successful or not. That's the whole reason for using "on error goto" patterns to begin with.
A more readable alternative to the goto, is to return upon error and leave the clean-up in an external wrapper function.

A: There's no special logic that prevents code from progressing past a label.
By convention, goto is typically used in C for this type of error handing but it doesn't have to be that way.  Labels for goto can be freely placed anywhere in a function.  You could for example do this:
void f()
{
    int i;
start:
    printf("i=%d\n", i);
    i++;
    if (i < 10) {
        goto start;
}

But please don't.

A: A labeled statement doesn't get skipped over if it's reached through normal flow of execution.  IOW, given code like
if ( condition )
{
  goto err;
}

err:
  // error handling code

// regular code

If condition evaluates to false, the code following err still gets executed because it follows the if statement.  You can avoid it by using second label and goto:
if ( condition )
{
  goto err;
}
goto normal;

err:
  // error handling code

normal:
  // regular code

but figuring out a goto-less way to handle the problem is better.

A: Much like Case labels in a switch-case statement, a label will just fall through to the next instruction when reached through the normal flow of code.  It is simply a place that can be jumped to.  This functionality is taken advantage of when doing clean-up after an error.  For example, if you're mallocing a bunch of things and an error occurs, you can jump to different sections of the clean up code depending on when you hit your error:
int func(void) {
    int ret = -1;
    int *x = malloc(sizeof(*x));
    if (/* some error condition */) {
        goto CLEANUP1;
    }
    int *y = malloc(sizeof(*y));
    if (/* some error condition */) {
        goto CLEANUP2;
    }
    int *z = malloc(sizeof(*z));
    if (/* some error condition */) {
        goto CLEANUP3;
    }
    ret = 0;
    /* do whatever successful operations you want here */

    CLEANUP3:
    free(z);
    CLEANUP2:
    free(y);
    CLEANUP1:
    free(x);
    return ret;
}

So with the above snippet, with normal error-free execution, all of the malloc'd variables get freed before leaving the function.  If there is an error after mallocing x, you jump to the CLEANUP1 label and free x.  if there is an error after mallocing z, then you've also malloc'd x and y, so you jump to the CLEANUP3 label which will free z and then fall through to the other two frees.


text:
Q: Render Picker Items from React-Native picker to populate drop-menu selections I am successfully using the react-native picker to render a drop-menu in one of my components. Right now, in the picker code I am hardcoding the values used to populate the drop-menu items. What I'd ideally like to do is pass these in as props, and have them dynamically generate as many items as necessary within the picker. I'm not sure how to do that, though. I tried using a for-loop but I can't run that kind of conditional logic within the component code itself. This is what it looks like with hard coded values.
export const DropDownMenu = (props) => {
  const [selectedValue, setSelectedValue] = useState(null);
  return (
    <View style={styles.container}>
      <Picker
        selectedValue={selectedValue}
        style={{ height: 50, width: 150 }}
        onValueChange={(itemValue, itemIndex) => {
          props.onSelectMenuValue(itemValue),
          setSelectedValue(itemValue)
        }}
      >
        <Picker.Item label="A" value="a" />
        <Picker.Item label="B" value="b" />
        <Picker.Item label="C" value="c" />
      </Picker>
    </View>
  );
}

How could I render Picker.Item values based on the props passed in?

A: You can pass an options prop as an array of objects with a label and a value property and use map like this:
<Picker /*whatever you need for picker here*/>
{props.options.map(option => <Picker.Item label={option.label} value={option.value}/>)}
</Picker>


text:
Q: Different treatment of NaN in sort for Series and DataFrame NaNs are treated differently when I use a Series than when I use a DataFrame of the same data containing NaN values and do a sort in descending order. In the Series they are put at the end (which is what I want), in the DataFrame they are put at the front, which is not what I want. Any reason for the difference in behavior? Any way to put the NaNs at the end when sorting a DataFrame in descending order?
a = Series(data = array([1,5,3,7,nan,10]))
a.sort(ascending=False)
print a  # Gives correct result with NaNs at end

b = DataFrame(array([1,5,3,7,nan,10]))
b.sort(columns=0,ascending=False)  # Gives wrong result with NaNs at beginning


text:
Q: CSS border-style being reset to "none" In the following code my "column" borders get reset to style=none if I remove the !important attribute but I can't figure out why. The debugger shows "none" and when I set the style to "solid" through the debugger, my borders show up. I added !important as a last resort and it worked, but the consensus is to avoid using !important.

#selection_td {
  width: 100%;
  position: absolute;
  border-style: solid;
  border-color: green;
  border-width: 2px;
  margin-left: auto;
  margin-right: auto;
  height: 75px;
}

#selection_div {
  position: relative;
  width: 100%;
  border-style: solid;
  border-color: blue;
  border-width: 2px;
  margin-left: auto;
  margin-right: auto;
  height: 75px;
}

.child_row {
  position: relative;
  visibility: visible;
  width: 99%;
  min-width: 99%;
  height: 75px;
  border-style: solid;
  border-color: red;
  border-width: 2px;
  margin-left: auto;
  margin-right: auto;
}

.column {
  border-style: solid !important;
  border: 2px;
  border-radius: 10px;
  border-color: black;
  display: inline-block;
  overflow: hidden;
  width: 50px;
  height: 75px;
}

.color_img {
  width: 50px;
  height: 75px;
}

A: Instead of border: 2px; use border-width: 2px;. Using just border you will reset all other attributes to defaults.

A: Conflicting border rules. You can combine to avoid this :
.column{
     border: solid 2px black;
     border-radius: 10px;
     display: inline-block;
     overflow:hidden;
     width: 50px;
     height: 75px;
}


text:
Q: How to save word special symbols into oracle database with jdbc? I want to insert words special symbols like ≥, ©, £, ... into oracle database with jdbc connection, but when command execution done completely, it saves ? character instead of orginal symbol. this is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class TestSecialChar {

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

        Connection connection = null;
        try {
            connection = DriverManager.getConnection("jdbc:oracle:thin:@192.168.251.80:1521:db", "db", "dbadmin");
        }
        catch (Exception e) {
            System.err.println("get connection failed!");
        }

        PreparedStatement preparedStatement = null;
        String sql = "insert into test_char " +
                "(fname, description) " +
                "values (?, ?)";

        preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setString(1, "User");
        preparedStatement.setString(2, "≥"); // save as ? into database

        try {
            preparedStatement.executeUpdate();
            System.out.println("OK!");
        }
        catch (Exception e) {
            System.err.println("Execution failed!");
        }

    }

}

A: you should use the CHR function while inserting in oracle
INSERT INTO test_chr(fname,description) values (1,chr(172));

you can check the values of ascii in oracle
select ascii('©') from dual

I dont know how to use the same in preparedStatement. might be you can check other resource.


text:
Q: Merge MySQL Rows Together I have a table laid out a bit like this:
ID  | Date       | Description          | Notes
 1  | 2015-03-25 | Action Completed     |
 2  | 2015-02-12 | Action Not Completed |
 1  |            |                      | Completed With Ease
 2  |            |                      | Difficulty Performing

Is there any code that I can use to merge them together by ID, like this?
 ID | Date       | Description          | Notes
 1  | 2015-03-25 | Action Completed     | Completed With Ease
 2  | 2015-02-12 | Action Not Completed | Difficulty Performing

I have already looked, but couldn't find anything that worked properly.

A: Group by the column that should be unique an then use aggregate functions on the other columns like max()
select id,
       max(date) as date,
       max(description) as description,
       max(notes) as notes
from your_table
group by id

A: Fiddle : http://sqlfiddle.com/#!9/305b7/1
SELECT id,
  max(`date`),
  GROUP_CONCAT(Description),
  GROUP_CONCAT(Notes)
FROM table1
GROUP BY id


text:
Q: Insert and select from other table and contant value I'm looking to "mark" entries of my SQLite database. This following command will add new entries from the other_table:
INSERT OR IGNORE INTO landing_table (idx)
SELECT gidx FROM other_table

However, I want to update only the entries that don't exist in landing_table that do exist in other_table to have the value computed set to 1.
INSERT OR IGNORE INTO landing_table idx (idx, computed)
SELECT gidx FROM other_table
AND SET computed=1

Obviously this isn't correct. I would like to do this in a single insert statement rather than an insert and future UPDATE statement.

A: Select a constant value for computed.
INSERT OR IGNORE INTO landing_table idx (idx, computed)
SELECT gidx, 1 FROM other_table


text:
Q: AngularJS Unit Test: Module 'admin.module' is not available I'm testing an Angular controller using Karma and Jasmine but I can't seem to load in my module from my main class.
Here's my main class: admin.controller.js
angular.module('admin.module').controller('admin.controller', ['$scope', function ($scope) {
$scope.SaveChanges = function()
{
    return true;
}
}]);

Here's my test class: admin.controller.tests.js
describe('admin.controller tests', function () {

    beforeEach(module('admin.module'));
    var $controller = {};

    beforeEach(inject(function (_$controller_) {
        $controller = _$controller_;
    }));

    describe('$scope.SaveChanges', function () {
        it('Should return true', function () {
            var $scope = {};
            var controller = $controller('admin.controller', { $scope: $scope });
            expect($scope.SaveChanges()).toBe(true);
        });
    });
});

My karma.conf.js file points to the following files in my project:
// list of files / patterns to load in the browser
files: [
  '../TriAngular/scripts/angular.js',
  '../TriAngular/scripts/angular-mocks.js',
  '../TriAngular/app/admin/*.js',
  'app/admin/*.js'
],

The admin.controller.js file is inside ../TriAngular/app/admin and my admin.controller.test.js is inside 'app/admin'.
I have tried to directly reference the files in my karma config file which has not worked. The full error is:

Module 'admin.module' is not available! You either misspelled the
  module name or forgot to load it. If registering a module ensure that
  you specify the dependencies as the second argument.

A: The issue turned out to not be obviously from the exception being shown. I was missing a angular-route.js file which needed to be included as it looked like my admin module was dependent on it.
List of includes in my karma.conf.js file:
// list of files / patterns to load in the browser
files: [
  '../TriAngular/scripts/angular.js',
  '../TriAngular/scripts/angular-mocks.js',
  '../TriAngular/scripts/angular-route.js',
  '../TriAngular/app/admin/*.js',
  'app/admin/*.js'
],

A: Try;
beforeEach(function(){
module('admin.module');
    }
});

I'm not familiar with Karma, but you also need to register your module as well, I've only ever used Jasmine with resharper so what I do to register files is;
/// <reference path="../scripts/app.js" />

At the top of the file.
Also don't forget to reference your module's dependencies as well.


text:
Q: How to predict microtask order across Promise.then chains? What is the JavaScript rule that determines the output of this code?:
Promise.resolve()
    .then(() => console.log("Microtask 1"))
    .then(() => console.log("Microtask 11"));

Promise.resolve()
    .then(() => console.log("Microtask 2"))
    .then(() => console.log("Microtask 22"))

This is the output:
Microtask 1
Microtask 2
Microtask 11
Microtask 22

But why isn't this the output?:
Microtask 1
Microtask 11
Microtask 2
Microtask 22

A: You see the output you see because the microtask for Microtask 11 isn't queued until the microtask for Microtask 1 runs, at which point the microtask for Microtask 2 is already in the queue waiting. So the order is (skipping some details; more below):

*

*Queue microtask for Microtask 1

*Queue microtask for Microtask 2

*Task is compelete, start processing microtasks:

*

*Execute microtask queued in #1

*

*Output Microtask 1

*Queue microtask for Microtask 11

*Execute microtask queued in #2

*

*Output Microtask 2

*Queue microtask for Microtask 21

*Execute microtask queued in #3.1

*

*Output Microtask 11

*Execute microtask queued in #3.2

*

*Output Microtask 21
Thus,

Microtask 1
Microtask 2
Microtask 11
Microtask 21

But: Writing code that relies on the order of execution of disconnected promise chains / microtask sequences is asking for trouble. :-) You can only reason about it in relation to promises you know are already settled, and of course in the normal case, you don't know when (or even if) a promise will settle. Instead, if you need a specific order, connect the chains to ensure order.

Re skipped details: I sort of glossed over things in the main explanation to keep it short and clear, but for accuracy, let's look at:
Promise.resolve()
    .then(() => console.log("Microtask 1"))
    .then(() => console.log("Microtask 11"));

...just on its own, ignoring the second promise chain to keep things simple.
Here's how that code is executed (my blog post on promise terminology may be helpful while reading the below):

*

*Execute Promise.resolve(), creating a promise that in this particular case is fulfilled with the value undefined.

*Execute .then(() => console.log("Microtask 1")), creating a new function and calling then with it on the promise from Step 1. This creates and returns a new promise, and in this particular case, queues a microtask to call the function because the promise is already fulfilled.

*Execute .then(() => console.log("Microtask 11")), creating a new function and calling then with it on the promise from Step 2. That creates and returns a new promise (which we throw away in that code) and, since the promise from Step 2 is still pending, adds the function to it as a fulfillment handler.

*The task running this code ends, so the JavaScript engine processes the microtask queue:

*

*Execute the first microtask in the queue:

*

*Call the function logging Microtask 1.

*Since the function returns undefined, which isn't a promise or other thenable, the engine fulfills the promise from Step 2 with undefined. (If the function has returned a promise or other thenable, the promise would instead be resolved to the promise that was returned.)

*

*That queues a microtask to call the fulfillment handler that was registered on that promise in Step 3, the one that will log Microtask 11 when called.

*Execute the next microtask in the queue (remember that we're ignoring the other promise chain in this description, so in this case the next microtask is the one logging Microtask 11 that was just added to the queue, not the one logging Microtask 2):

*

*Call the function logging Microtask 11.

*Since the function returns undefined, which isn't a promise or other thenable, the engine fulfills the promise from Step 3 with undefined.

*

*That doesn't do anything, because that promise doesn't have any fulfillment handlers registered on it.

A: "Microtask 1" and "Microtask 11" are sequential under one Promise & the then callbacks await for the response in the first then once it is resolved then it moves on to the next then in the promise chain in the sequence.
Hence, the output you see in the order Microtask 1, Microtask 2, Microtask 11, Microtask 22.
But if you do you chain all the promises you will see the expected output i.e Microtask 1, Microtask 11, Microtask 2, Microtask 22.:

Promise.resolve()
    .then(() => console.log("Microtask 1"))
    .then(() => console.log("Microtask 11"))
    .then(() => console.log("Microtask 2"))
    .then(() => console.log("Microtask 22"))

NOTE: then callbacks (and awaits) are executed after the synchronous JavaScript code and in order.


text:
Q: How to show video in webView on Android I want to show text, image and video in my application. For this issue I use webView because I should show image and video between texts.
for set webView I write this codes:
    WebSettings settings = post_content_web.getSettings();
    post_content_web.setWebChromeClient(new WebChromeClient());
    settings.setPluginState(WebSettings.PluginState.ON);
    settings.setJavaScriptEnabled(true);

    settings.setDefaultTextEncodingName("utf-8");

    String myCustomStyleString = "";

    post_content_web.loadDataWithBaseURL("", myCustomStyleString + "
"
            + title + "\n\n" + content + "
", "text/html", "utf-8", null);

I use Embed code from video, such as this :

My application shows video frame (border) and video thumbnail but when I click on video to play, does't show any video and just show black screen!!!!
How can I fix it?

A: To support the video available in div tag(
),
You will have to add some extra properties for WebView Settings.
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setAppCachePath(getApplicationContext().getFilesDir().getAbsolutePath() + "/cache");
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setDatabasePath(getApplicationContext().getFilesDir().getAbsolutePath() + "/databases");

I had the same issue, and adding this snippet solved BLACK SCREEN.
May this helps you too!


text:
Q: How to catch exact date format from value? In MyTable is column named Values of NVARCHAR datatype. Here are placed many values like:
Alisa
20150111
Something 12
Etc 2222
4444
01/21/2015 11:01:12 AM
etc

I need select all values from this column but where format is like mm/dd/yyyy hh:mm:ss AM/PM I need to convert it to DATE (without time) mm/dd/yyyy
I've tried to use ISDATE, but It not working as I want, It converting other values to date too, like from my sample list 4444 to date format.
This is my query for now:
SELECT CASE WHEN ISDATE(Values) = 1 THEN CONVERT(VARCHAR(20), Values, 101)
            ELSE Values
       END AS Val1
FROM MyTable

So list should be returned in following:
Alisa
20150111
Something 12
Etc 2222
4444
01/21/2015 -- this line should be changed
etc

A: try
SELECT CASE WHEN Values LIKE '__/__/____%' THEN CONVERT(VARCHAR(20), Values, 101)
            ELSE Values
       END AS Val1
FROM MyTable

A: This script will validate the date of the right format and take the first 10 characters if it is a date otherwise, it will pick the original value of values. Note values is a reserved word. In other situations you can use try_convert from sqlserver 2012.
DECLARE @t table([Values] varchar(50))

INSERT @t values ('01/20/2015 01:01:01 AM')
INSERT @t values ('02/28/2014 01:01:01 PM')
INSERT @t values ('02/35/2014 01:01:01 PM')
INSERT @t values ('4444')

SELECT
  CASE WHEN [Values] like
   '[01][0-9]/[0-3][0-9]/[1-2][0189][0-9][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9] [AP]M'
   and isdate([Values]) = 1
    THEN
      left( [Values], 10) -- format of date was already verified
            ELSE [Values]
       END AS Val1
FROM @t MyTable

Result:
Val1
01/20/2015
02/28/2014
02/35/2014 01:01:01 PM
4444

A: Maybe try to check if string contains / as below:
SELECT CASE WHEN ISDATE(Values) = 1 and CHARINDEX('/',Values) > 0
            THEN CONVERT(VARCHAR(20), Values, 101)
            ELSE Values
       END AS Val1
FROM MyTable

A: if your format is exaclty mm/dd/yyyy hh:mm:ss AM/PM
select *
from somewhere
where Values like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9] [AP]M'
   AND ISDATE(Values) = 1


text:
Q: Bootstrap Modal close button issue after print action I am working on bootstrap modal. I had a set of gallery images. A modal popup is opened on clicking the image. The popup has two buttons one for print the modal content and  second to close the modal.
The problem is when the user click print button every thing is ok and modal content will be printed, but when the user click in close button to close the modal after print the content nothing happen the modal doesn't closed. Please help me to fix this.
Here is my code

title

                            <button type="button" class="close" data-dismiss="modal" title="Close" >X</button>

                                        <button class="btn-sm" type="button" data-dismiss="modal" style="float:left;" onclick="printDiv('myGallery')">Print</button>

A: //add this button to your main html
<button type="button"  class="btn btn-default" onclick="javascript:test()" id="myBtn" data-dismis`enter code here`s="modal">Close</button>

//add this script to your main html
function test() {
    $('#myModal').modal('toggle');
    }

//add this style to your main html
.modal-backdrop {
      position: fixed;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      background-color: #000000;
    }

A: In my case Using bootstrap 4, using setTimeout helped me out.
By using setTimeout function, we hide modal after clicking print button.
function printDiv(div) {

 var printContents = document.getElementById(div).innerHTML;
 var originalContents = document.body.innerHTML;
 document.body.innerHTML = printContents;
 window.print();
 document.body.innerHTML = originalContents;
 setTimeout(function(){ $('#myModal').modal('hide'); }, 1000);
 }

A: try this
function printDiv(divName) {
    var elem = document.getElementById(divName)

    var domClone = elem.cloneNode(true);

    var $printSection = document.getElementById("printSection");

    if (!$printSection) {
        var $printSection = document.createElement("div");
        $printSection.style = "width: 100%;";
        $printSection.id = "printSection";
        document.body.appendChild($printSection);
    }

    $printSection.innerHTML = "";
    $printSection.appendChild(domClone);
    window.print();
}


text:
Q: Как сделать контекстное меню по правой кнопке мыши в полях Text или Entry Недавно начав изучать python, столкнулся с проблемой.
Собственно, при создании графического интерфейса, содержащего поля ввода текста, не могу найти как прикрутить контекстное меню, выпадающее по правой кнопке мыши. Без него пользоваться буфером обмена по горячим кнопкам можно, но как-то не очень удобно.
Спинным мозгом понимаю, что надо использовать Bind, но что дальше?

A: На примере данного кода создается меню self.menu и добавляются 2 кнопки. В результате при нажатии на ПКМ у вас вылезает список с этими кнопками.
self.menu.post(event.x_root, event.y_root) обозначает расположение мышки при нажатии на область для вызова меню.
try:
    from Tkinter import Tk, Frame, Menu # python2
except ImportError:
    from tkinter import Tk, Frame, Menu # python3

class Main(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.parent.title("context")
        self.menu = Menu(self.parent, tearoff=0)
        self.menu.add_command(label="Print Hello Word", command=lambda: print('Hello word'))
        self.menu.add_command(label="Exit", command=lambda: self.close())
        self.parent.bind("<Button-3>", lambda event: self.menu.post(event.x_root, event.y_root))
        self.pack()

if __name__ == '__main__':
    root = Tk()
    root.geometry('400x400')
    app = Main(root)
    root.mainloop()

пример выполнения контекстного меню в tkinter.Text
try:
    from Tkinter import Tk, Frame, Menu, Text, Label, END  # python2
except ImportError:
    from tkinter import Tk, Frame, Menu, Text, Label, END  # python3

class Main(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.parent.title("context")
        label = Label(self.parent, text='какой то текст ')
        label.pack()
        self.text = Text(self.parent)
        self.text.pack()
        self.menu = Menu(self.text, tearoff=0)
        self.menu.add_command(label="Print Label text", command=lambda: label.config(text=self.text.get(1.0, END)))
        self.menu.add_command(label="Exit", command=lambda: self.close())
        self.text.bind("<Button-3>", lambda event: self.menu.post(event.x_root, event.y_root))
        self.pack()

if __name__ == '__main__':
    root = Tk()
    root.geometry('400x400')
    app = Main(root)
    root.mainloop()


text:
Q: BSOD error 0xc000021a BSOD error 0xc000021a on windows 8.1 64 bit.

*

*unable to access safe mood.

*unable to access all the other options in Advanced Boot Options.

*no minidump file for this BSOD.

*I can access Windows 7 in the other partition so I can access to 8.1 files.

I'm not sure but I suspect its the windows update, so I need help how to troubleshoot this.

A: We do need the actual log files (called a DMP files) as they contain the only record of the sequence of events leading up to the crash, what drivers were loaded, and what was responsible.
Please follow our instructions for finding and uploading the files we need to help you fix your computer. They can be found here
If you have any questions about the procedure please ask
http://answers.microsoft.com/en-us/windows/wiki/windows_10-update/blue-screen-of-death-bsod/1939df35-283f-4830-a4dd-e95ee5d8669d
Please read this wiki to find out how to find and upload your event viewer logs
http://answers.microsoft.com/en-us/windows/wiki/windows_10-update/event-viewer-what-is-going-on-in-your-computer/fdda2010-d4df-4fed-863b-89ce0142419d


text:
Q: Format for/creation of PTR and SPF records? Let's say that I have a server that resides at Linode that I use for my business, mybusiness.com.  It has an IP Address of 1.2.3.4, and an A record of myserver.mybusiness.com.  I own the domain name and host my DNS through DNSimple, and everything at this point works fine.
As a part of my business, I have a contract with othercompany.com.  They control their own domain name, and someone else runs their DNS for them.
For this contract, I need to send emails as "them" (web@othercompany.com) from a process that is running on myserver.  Myserver currently has Jenkins (for running the jobs) and Exim (for sending the emails) installed on it.  We don't control the email addresses we're sending emails to; they're our clients' email addresses.  Some of them are Google.
This was working fine for nearly a year.  About a month or so ago, we started noticing bounces most specifically from GMail.  Comcast has always presented a problem for us sending email as well.
SMTP error from remote mail server after end of data:
host aspmx.l.google.com [2607:f8b0:400c:c06::1a]:
550-5.7.1 [2600:3c03::f03c:91ff:fe73:138] Our system has detected that this
550-5.7.1 message does not meet IPv6 sending guidelines regarding PTR records
550-5.7.1 and authentication. Please review
550-5.7.1  https://support.google.com/mail/?p=ipv6_authentication_error for more
550 5.7.1 information. h1si10102273ywc.225 - gsmtp

So the first question I have is...Who should set up PTR and/or SPF records so that myserver.mycompany.com can properly send emails as web@othercompany.com and have places like GMail and Comcast accept those emails?  Is it me (through my DNSimple account), or is it the company that controls their DNS?  And secondly, what should those record(s) look like?  Thanks!

A: In short:

*

*reverse DNS (PTR) entries can be set by your server's ISP (Internet Service Provider).

*SPF entries can be set in forward DNS service, use TXT type records for this.

The "other company", though, may have a policy to not allow sending e-mails claiming to come from their domain but from servers not under their control. This is smart and you shouldn't try to change that. Instead, cooperate with them - point your MTA to forward the messages to their server, they should allow you such a submission from given IP.