text:
Q: Doctrine DQL Extention not working in Zend Framework 2 I have just added a DQL extension into my ZF2 app but it is not working.
The extension should allow a match against query.
In my module.config.php I have
'doctrine' => array(
        'driver' => array(
            'Application_driver' => array(
                'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
                'cache' => 'array',
                'paths' => array(__DIR__ . '/../src/Application/Entity')
            ),
            'orm_default' => array(
                'drivers' => array(
                    'Application\Entity' => 'Application_driver'
                ),
            ),
        ),
        'configuration' => array(
            'orm_default' => array(
                'string_functions' => array(
                    'MatchAgainst' => 'Freedom\Doctrine\ORM\AST\Functions\MatchAgainstFunction',
                ),
                'datetime_functions' => array(),
                'numeric_functions'   => array(),
                'metadata_cache'     => 'filesystem',
                'query_cache'        => 'filesystem',
                'result_cache'       => 'filesystem',
            ),
        ),
    ),

and in my DQL I have
$builder->andwhere('MATCH (`t.title`) AGAINST (:title)')
        ->setParameter('title', $param);

The extension is not even being executed all I get is an error.
Error: Expected known function, got 'MATCH'
Does anyone know what I am missing?
Many thanks in advance.
EDIT
I have got the extension working by changing the line from 'MatchAgainst' => 'Freedom\Doctrine\ORM\AST\Functions\MatchAgainstFunction', to 'Match' => 'Freedom\Doctrine\ORM\AST\Functions\MatchAgainstFunction',.
The problem I am having now is the DQL query is still not working.
My DQL extension looks like
namespace Freedom\Doctrine\ORM\AST\Functions;

use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;

/**
 * MatchAgainstFunction ::=
 *  "MATCH" "(" StateFieldPathExpression {"," StateFieldPathExpression}* ")" "AGAINST" "("
 *      StringPrimary ["BOOLEAN"] ["EXPAND"] ")"
 */
class MatchAgainstFunction extends FunctionNode
{

    /** @var array list of \Doctrine\ORM\Query\AST\PathExpression */
    protected $pathExp = null;

    /** @var string */
    protected $against = null;

    /** @var boolean */
    protected $booleanMode = false;

    /** @var boolean */
    protected $queryExpansion = false;

    public function parse(Parser $parser)
    {
        // match
        $parser->match(Lexer::T_IDENTIFIER);
        $parser->match(Lexer::T_OPEN_PARENTHESIS);

        // first Path Expression is mandatory
        $this->pathExp = array();
        $this->pathExp[] = $parser->StateFieldPathExpression();

        // Subsequent Path Expressions are optional
        $lexer = $parser->getLexer();
        while ($lexer->isNextToken(Lexer::T_COMMA)) {
            $parser->match(Lexer::T_COMMA);
            $this->pathExp[] = $parser->StateFieldPathExpression();
        }

        $parser->match(Lexer::T_CLOSE_PARENTHESIS);

        // against
        if (strtolower($lexer->lookahead['value']) !== 'against') {
            $parser->syntaxError('against');
        }

        $parser->match(Lexer::T_IDENTIFIER);
        $parser->match(Lexer::T_OPEN_PARENTHESIS);
        $this->against = $parser->StringPrimary();

        if (strtolower($lexer->lookahead['value']) === 'boolean') {
            $parser->match(Lexer::T_IDENTIFIER);
            $this->booleanMode = true;
        }

        if (strtolower($lexer->lookahead['value']) === 'expand') {
            $parser->match(Lexer::T_IDENTIFIER);
            $this->queryExpansion = true;
        }

        $parser->match(Lexer::T_CLOSE_PARENTHESIS);
    }

    public function getSql(SqlWalker $walker)
    {
        $fields = array();
        foreach ($this->pathExp as $pathExp) {
            $fields[] = $pathExp->dispatch($walker);
        }

        $against = $walker->walkStringPrimary($this->against)
                . ($this->booleanMode ? ' IN BOOLEAN MODE' : '')
                . ($this->queryExpansion ? ' WITH QUERY EXPANSION' : '');

        return sprintf('MATCH (%s) AGAINST (%s)', implode(', ', $fields), $against);
    }

}

and in my DQL I have
$builder->andWhere('MATCH (t.title) AGAINST (:title)')
        ->setParameter('title', $param);

Now I am getting the error
[Syntax Error] line 0, col 204: Error: Expected =, <, <=, <>, >, >=, !=, got 'ORDER'
Does anyone know why Doctrine is looking for a comparison operator?

A: I have got the extension working by changing the line from 'MatchAgainst' => 'Freedom\Doctrine\ORM\AST\Functions\MatchAgainstFunction', to 'Match' => 'Freedom\Doctrine\ORM\AST\Functions\MatchAgainstFunction',
In answer to my second question I found this works
$builder->andWhere('MATCH (t.title) AGAINST (:title BOOLEAN) > 0')
        ->setParameter('title', $param);


text:
Q: Term for an image that briefly appears on computer screen What do you call an image, usually fragmented, that appears on a computer screen for a split second, such as when a webpage is loading or an app is launching? I know the term exists, but can't remember it for the life of me.
An example of what I'm talking about:

In this example, the scroll bar to the left appears for a split second when changing the size of the window and immediately disappears.

A: The term I was looking for was FOUC, short for "flash of unstyled content". It is specifically about web pages before CSS is loaded, so I was a little off in terms of what I thought it meant.

A: One term is toast — because it pops up! Please read this stackoverflow question. I searched three dictionaries but did not find this meaning for toast.

A: I believe the term you're looking for is the happily intuitively named ghost, which is briefly defined as "a spurious image resulting from an echo".
A more in-depth definition can be found on the dedicated Wikipedia page for video ghosts:

Ghost
In television, a ghost is a replica of the transmitted image, offset in position, that is super-imposed on top of the main image. It is often caused when a TV signal travels by two different paths to a receiving antenna, with a slight difference in timing.

The more general term for unintentional issues during rendering is artifact. From Wikipedia's glossary of video terminology:

Artifact (video)
A defect or distortion of the video image, introduced along the sequence from origination and image capture to final display. Artifacts may arise from the overload of channel capacity by excess signal bandwidth. Artifacts may also result from: sampling effects in temporal, spatial, or frequency domains; processing by the transfer functions; compromises and inadequacies in the system employed; cascading of minor defects; basically any other departure of the total system from "complete transparency" resulting in visual errors.

A related term is noise, mostly used for widespread and random effects impacting the entire image (like snow on old TV sets or static on the radio).
If there is a more specific term, I didn't find it in a quick scan of that entire glossary.

A: These are called skeleton screens.
While explaining the history of the technique, writer Parimala Hariprasad defines a skeleton screen:

A skeleton screen is essentially a blank version of a page into which information is gradually loaded

Her first example image looks similar to what you asked about:

A recent Viget Article notes:

Progressive loading with skeleton screens is thought to benefit the user by indicating that progress is being made, thereby shortening the perceived wait time. Google, Medium, and Slack all use skeleton screens to make their apps feel more performant.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP: Simple HTML DOM Parser : content of I'm trying to get the content of the meta tag "article:publisher" with the php code
$html = str_get_html($str);
$ret = $html->find('meta[property=article:publisher]');
$value = $ret->content;
echo "publisher val = ".$value[0];
can anyone see what I'm doing wrong ?

A: If the meta tag is something like:
<meta property='article:publisher' content="Article Publisher Name" />

This works for me:
$html = str_get_html($str);
$value = $html->find('meta[property=article:publisher]', 0)->content;
echo "publisher val = ".$value;

Or you can get the $value in two steps if you wish:
$ret = $html->find('meta[property=article:publisher]');
$value = $ret[0]->content;

A: try this:
$html = str_get_html($str);
$ret = $html->find('meta[property=article:publisher]');
$value = $ret[0]->plaintext;
echo "publisher val = ".$value;


text:
Q: Decode Cookie String with Scala/Play Framework 2.7.x Ok.
So, the normal way to decode cookies in scala/play framework is like this:
 def admin_scrape[T]:Action[AnyContent] = Action.async {request: Request[AnyContent] => Future {
      println("****************************")
      println("inside admin_scrape")
      println("****************************")
      val body: AnyContent          = request.body
      val jsonBody: Option[JsValue] = body.asJson
      var texts_update: String = "";
      var article_url_update: String = "";
      jsonBody
      .map{json =>
        println("value of json")
        println(json)
        request.session
        .get("access_rights") //access_rights is the token name in the cookie string I set
        .map{access_rights =>
        <...>

However, I've wanted to use sockets in Play.
Unfortunately, the play framework's web socket support (https://www.playframework.com/documentation/2.7.x/ScalaWebSockets) expressly supports flow like structures with the data stream initiating on the front end. Not knocking them, perhaps it was a design choice, but I wanted socketing with requests able to instantiate on the back end as well. So I used this (https://github.com/TooTallNate/Java-WebSocket) to get idiomatic socketing support.
This works.
However, consider the following (it works as one would expect):
override def onOpen(conn: WebSocket, handshake: ClientHandshake): Unit = {
    conn.send("Welcome to the server client!")
    broadcast("new connection everyone: " + handshake.getResourceDescriptor)
    var cookie = "no cookie"
    if(handshake.hasFieldValue("Cookie")){
      println("We found a cookie")
      var cookie = handshake.getFieldValue("Cookie");
      println("value of cookie")
      println(cookie)
      // the following CODE_BLOCK does not work
      // and gives the error:
      // [error] /Users/patientplatypus/Documents/platypusNEST/the_daily_blech/scala_blech_blog/blog/app/sockets/SocketServer.scala:86:32: value decode is not a member of object play.api.mvc.Cookies
      // [error]       val decode_val = Cookies.decode(cookie)
      // [error]                                ^
      // *CODE_BLOCK*
      // val decode_val = play.api.mvc.Cookies.decode(cookie)
      // println("value of decode_val")
      // println(decode_val)
      // *CODE_BLOCK*
      // reasoning - I need a way to get the cookie string into a mapping and this seemed likely.
    }else{
      println("We did not find a cookie")
    }
    <...>

When I run this from an app that has a client side cookie I successfully get printed on the server:
We found a cookie
value of cookie
PLAY_SESSION=SUPERDUPERLONGHASHSTRING

I need to be able to convert this hash string back into a mapping like I could do with requests, but I haven't been able to find the right decoding. An attempt was made above, but I realized I had been reading the documents for play framework 2.0 (https://www.playframework.com/documentation/2.0/api/scala/play/api/mvc/Cookies$.html). I was wondering if some sort of decode function existed in the current 2.7.x version, or how else to convert this hash string back into a cookie map.
EDIT:
The current, most relevant documentation appears to be https://www.playframework.com/documentation/2.7.x/api/scala/play/api/mvc/Cookies$.html, specifically decodeCookieHeader or decodeSetCookieHeader as they take a string and return a sequence of Cookies, according to each methods type signature. However, running
var cookiesDecodeCookieHeader = Cookies.decodeCookieHeader(cookie)
println("value of cookiesDecodeCookieHeader: ")
println(cookiesDecodeCookieHeader)
var cookiesDecodeSetCookieHeader = Cookies.decodeSetCookieHeader(cookie)
println("value of cookiesDecodeSetCookieHeader: ")
println(cookiesDecodeSetCookieHeader)

gives me
value of cookiesDecodeCookieHeader:
List()
value of cookiesDecodeSetCookieHeader:
List()

So, this isn't correct.
EDIT EDIT:
Likewise,
var cookiesFromCookieHeader = Cookies.fromCookieHeader(Some(cookie.toString))
  println("value of cookiesFromCookieHeader: ")
  println(cookiesFromCookieHeader)
  var cookiesFromSetCookieHeader = Cookies.fromSetCookieHeader(Some(cookie.toString))
  println("value of cookiesFromSetCookieHeader: ")
  println(cookiesFromSetCookieHeader)

Results in empty maps. At this point my solutions seem to be centered around looking through the man pages (https://www.playframework.com/documentation/2.7.x/api/scala/play/api) at random, so I've opened up an issue for clarification on the play github: (https://github.com/playframework/playframework/issues/9837).
If anyone has any ideas please let me know. Thanks!
EDIT EDIT EDIT:
I've gotten to the point where I'm investigating other JWT libraries, because apparently play's doesn't work the way I need it to :<. I've looked at https://github.com/pauldijou/jwt-scala/, but it doesn't seem to work with the latest version of play (see here: https://github.com/pauldijou/jwt-scala/issues/153). I've also looked at things like this (which seems nice and tidy) https://dzone.com/articles/jwt-authentication-with-play-framework, but the library they used is deprecated.
Wow, this should not be this hard. Any suggestions would be appreciated.

A: So it looks like in your example of retrieving a value from a cookie you're actually talking about retrieving a session value (request.session.get(...)).

Unfortunately, the play framework's web socket support (https://www.playframework.com/documentation/2.7.x/ScalaWebSockets) expressly supports flow like structures with the data stream initiating on the front end.

I'm not sure what you mean here, it's definitely possible for Play to send the first message in a Websocket communication.
(From the Play websockets documentation)
import play.api.mvc._
import akka.stream.scaladsl._

def socket = WebSocket.accept[String, String] { request =>
  // Just ignore the input
  val in = Sink.ignore

  // Send a single 'Hello!' message and close
  val out = Source.single("Hello!")

  Flow.fromSinkAndSource(in, out)
}

This is a very simple example which will return a "Hello!" message to the websocket client once a connection is established.
This handling code also has direct access to the request: RequestHeader which means that you can just grab things from the session directly from there without having to decode any cookies:
  def ws = WebSocket.accept { request =>

    request.session.get("access_rights") match {
      case Some(value) =>
        println("We found access_rights!")
        println("value of access_rights")
        println(value)
      case None =>
        println("We did not find access_rights!")
    }

    val in = Sink.ignore
    val out = Source.single("Welcome to the server client!")
    Flow.fromSinkAndSource(in, out)
  }

A: I managed to figure it out by backing out the Cookies.scala file in the play framework found here (https://github.com/playframework/playframework/blob/2.7.x/core/play/src/main/scala/play/api/mvc/Cookie.scala). This was more difficult than I think it ought to be just to parse the session cookie data (mostly to know where to look) so I didn't have to import random libraries. This is also an example of using java-websocket package which is much more idiomatic than the play framework way. I'm posting the whole file (it's small) so that all the imports and logic can be seen.
If you are attempting to implement this yourself, then you should find the following output:
value of jws.getBody.asScala.toMap:
Map(data -> {your_cookie_key=your_cookie_value, csrfToken=SUPER-SECRET-LONGHASH},
     nbf -> SECRETNUM, iat -> SECRETNUM)

in your terminal.
Thanks again for all those who were willing to help.
package sockets

import play.api.libs.json._
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.net.InetSocketAddress
import java.net.UnknownHostException
import java.nio.ByteBuffer
import org.java_websocket.WebSocket
import org.java_websocket.WebSocketImpl
import org.java_websocket.framing.Framedata
import org.java_websocket.handshake.ClientHandshake
import org.java_websocket.server.WebSocketServer

import javax.inject._
import play.api.libs.json._
import play.api._
import play.api.mvc._
import play.api.http._

import scala.collection.JavaConverters._

import io.jsonwebtoken.Jwts
import io.jsonwebtoken._

import java.nio.charset.StandardCharsets
import java.time.Clock
import java.util.{ Base64, Date, Locale }

@Singleton
class SocketServer @Inject()() extends WebSocketServer(new InetSocketAddress(8887)){

  def parse(encodedString: String): Map[String, AnyRef] = {
    println("inside parse def and value of encodedString: ", encodedString)
    println("***************")
    println("***************")
    println("***************")

    var newEncodedString = encodedString.slice(13, encodedString.length)
    println("value of newEncodedString")
    println(newEncodedString)
    println("***************")
    println("***************")
    println("***************")

    def jwtConfiguration = new JWTConfiguration();

    val jwtClock = new io.jsonwebtoken.Clock {
      val clock = Clock.systemDefaultZone().instant()
      override def now(): Date = java.util.Date.from(clock)
    }

    val base64EncodedSecret: String = {
      Base64.getEncoder.encodeToString(
        "hellotheresailor".getBytes(StandardCharsets.UTF_8) //note that this secret should ideally be set in your application.conf file and imported via injection
      )
    }

    val jws: Jws[Claims] = Jwts.parser()
      .setClock(jwtClock)
      .setSigningKey(base64EncodedSecret)
      .setAllowedClockSkewSeconds(jwtConfiguration.clockSkew.toSeconds)
      .parseClaimsJws(newEncodedString)

    val headerAlgorithm = jws.getHeader.getAlgorithm
    if (headerAlgorithm != jwtConfiguration.signatureAlgorithm) {
      val id = jws.getBody.getId
      val msg = s"Invalid header algorithm $headerAlgorithm in JWT $id"
      throw new IllegalStateException(msg)
    }

    println("value of jws.getBody.asScala.toMap: ")
    println(jws.getBody.asScala.toMap)

    jws.getBody.asScala.toMap
  }

  override def onOpen(conn: WebSocket, handshake: ClientHandshake): Unit = {
    conn.send("Welcome to the server!")
    broadcast("new connection: " + handshake.getResourceDescriptor)
    var cookie = "no cookie"
    if(handshake.hasFieldValue("Cookie")){
      println("We found a cookie")
      var cookie = handshake.getFieldValue("Cookie");
      println("value of cookie")
      println("parsedCookie: ")
      val parsedCookie = parse(cookie)
      println(parsedCookie)
    }else{
      println("We did not find a cookie")
    }
    println(
      conn.getRemoteSocketAddress.getAddress.getHostAddress +
        " entered the room!")
  }

  override def onClose(conn: WebSocket,
                       code: Int,
                       reason: String,
                       remote: Boolean): Unit = {
    broadcast(conn + " has left the room!")
    println(conn + " has left the room!")
  }

  override def onMessage(conn: WebSocket, message: String): Unit = {
    broadcast(message)
    println(conn + "we heard: " + message)
  }

  override def onMessage(conn: WebSocket, message: ByteBuffer): Unit = {
    broadcast(message.array())
    println(conn + "we heard: " + message)
  }

  override def onError(conn: WebSocket, ex: Exception): Unit = {
    ex.printStackTrace()
    if (conn != null) {}
  }

  override def onStart(): Unit = {
    println("Server started!")
    setConnectionLostTimeout(0)
    setConnectionLostTimeout(100)
  }

}


text:
Q: What is rc stands for I saw a lot of times code where return status of function was set to *rc * variable (e.g. int rc = foo();). I though it some sort of convention and blindly used it all over my code.
Recently was asked by colleague what *rc * stands for and discovered that I indeed don't know the answer.
Thanks

A: It probably refers to
Return Code

A: rc stands for run code for instance when you want a code block or function to run on startup of the code snippet rc will automatically run the code you attach to it


text:
Q: the boo boys come for me I guess "the boo boys come for me" mean "the boys who show strong disapproval for me follow me (hunt me as if I am an evil witch)."  Am I on the right track?
I checked up in Oxford Dictionaries which offer this definition "boo-boy: A spectator or supporter who habitually jeers or finds fault; especially (in plural) a particular section or group among the supporters of a team, distinguished as behaving in this manner." This definition doesn't amount to "witch-hunt".

Sam Harris liked
Bob Servant tweeted hours ago:

Sick of the witch-hunt. I am following the rules to the letter. I exercise once a day, locally, with my pets, and still the boo boys come for me. I simply can't win.

A: "witch hunt" is an idiomatic phrase that indicates persecution of any kind.

2: the searching out and deliberate harassment of those (such as
political opponents) with unpopular views
https://www.merriam-webster.com/dictionary/witch%20hunt

The implication is that there are many opponents who dislike the person and the boo-boys are an active manifestation of this dislike.
P.S. I don't know who Bob Servant is.


text:
Q: Using map and filter/reduce to count how many times things come up in a sequence (python) I need to make a list of 50 random colours, then count how many times each colour has come up in that sequence. the only way i have found to do this is as shown below:
colours = [ "Red", "Blue", "Green", "Yellow", "Purple", "Orange", "White", "Black" ]
numbers = map(lambda x : random.randint(0,7), range(50))
randomcolours = map(lambda i: colours[i], numbers)
print randomcolours
x=collections.Counter(randomcolours)
print x

but i need to do it so i use map and filter or reduce.. i can't work out how to do it this way ?

A: random_colors = [random.choice(colors) for x in range(50)]

#because python's lambda is crappy, an extra local/global function must be defined
def count_color(di, color):
    di.setdefault(color, 0)
    di[color] = di[color]+1
    return di

result = reduce(count_color, random_colors, {})
#The result is what you want

A: You can use random.choice() to populate your random_colors list:
random_colors = [random.choice(colors) for x in range(50)]

And then one way to count all the occurances using map() and filter() can be:
c = dict(map(lambda to_filter: (to_filter, len(filter(lambda x: to_filter == x, random_colors))), colors))


text:
Q: Detecting Spotify Song Plays I'm working on a mobile application that detects song plays from various media players, both on iPhone and Android. We currently support a number of applications in both platforms. Our application works in a similar way to how Last.FM detects and automatically scrobbles plays.
However, we have not been able to get a working solution for detecting Spotify song plays that does not need to use either Last.FM scrobbling (available in Spotify for Android only) or Facebook as a proxy.
I've tried a few things for android but as I understand it (I see lots of posts e.g. Find what song is playing in spotify on android), the Android Application does not broadcasts media related intents for song plays, so we need something more creative. In any case this does not solve our problem for the iPhone use case.
Lib-spotify held some promise for us, and I've manged to build an application that can create a session and navigate some playlists, but I have not figured out if I can load what would appear as "play history" in the Desktop Application via lib-spotify (e.g. is this a special form of playlist?). I have also tried a Spotify App to accomplish the same but the API appears to not to expose required functionality.
It seems like I've exhausted all avenues on this one, but does anybody have any suggestions for something I haven't tried?
Assume that I have spotify credentials for each user whose history I would like to gather.
Thanks

A: Spotify has a metadatachanged intent-action that contains artist, album, track, length, and id values.
See: https://stackoverflow.com/a/22195867/1345586

A: Unfortunately, the desktop play history is local to each machine, meaning it can't be accessed through libspotify or any other API.
At the moment, there isn't a way to reliably achieve what you're wanting to do on mobile platforms.


text:
Q: Failed to install PostgreSQL 8.3, failed to run initdb:1? I am reinstalling PostgreSQL using pgInstaller postgresql-8.3.16-1. An Error occurs in the last step of the install process:

Failed to run initdb:1!

\tmp\initdb.log shows this message:

The application has failed to start because its side-by-side
  configuration is incorrect. Please see the application event log or
  use the command-line sxstrace.exe tool for more detail.

The message is quite simple but I can't locate the root cause of the install failure.
Any one knows what's the reason?

A: You probably already have a database cluster installed in the location where your Posgres8.3 install is trying to init a new one.  You can't really mix and match versions like that.
If possible, install the old version you had when you created the existing database.  Then use pg_dumpall to create a .SQL dump of all of your data.  You can then move or delete the old database (usually at /var/lib/pgsql) and install the new version.  finally, apply the database dump to get the old data back.
For more details on this, read the Upgrading a PostgreSQL cluster manual page.
If you are installing the same version, there's no need to upgrade the cluster, you can probably safely ignore errors about initdb, so long as everything runs Ok.


text:
Q: XAML string format in multibinding w/converter I am implementing this TextBlock and the stringformat is not appearing, only the value of the binding property. Can you tell me what I'm doing wrong?
XAML CODE
<TextBlock>
     <TextBlock.Text>
       <MultiBinding Converter="{StaticResource ResourceKey=myConverter}">
         <Binding Path="loc.country" StringFormat="Country: {0}"/>
         <Binding Path="loc.area" StringFormat="Area: {0}"/>
       </MultiBinding>
     </TextBlock.Text>
 </TextBlock>

Converter
public class MyMultiConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values[1] == null)
            return values[0];

        return values[1];
    }

    public object[] ConvertBack(object values, Type[] targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}

Best regards,

A: See the Remarks section on the StringFormat page on MSDN:

...
When you use a MultiBinding, the StringFormat property applies
  only when it is set on the MultiBinding. The value of StringFormat
  that is set on any child Binding objects is ignored. ...

The reason is that StringFormat is only applied when the target property of the binding is actually of type string, which is not the case in a MultiBinding

So you either set the StringFormat of the MultiBinding (and don't set its Converter), or you do the formatting in your converter.


text:
Q: ClockTimer shows the value in second or ms? I have read this implementation in C++;
int ClockTimer::ClockMS()
{
   return clock() * 1000 / CLOCKS_PER_SEC;
}

double ClockTimer::CLOCK()
{
    return ClockMS() * 0.001;
}

void ClockTimer::StartTimer()
{
   _time_start = ClockMS();
}

void ClockTimer::StopTimer(int verb)
{
   _time_stop = ClockMS();
}

float ClockTimer::GetElapsedTime()
{
    return (_time_stop - _time_start)  * 0.001f;
}

I guess that the result of GetElapsedTime() is in milliseconds, is that right? Why is that?

A: If ClockMS is returning milliseconds, then GetElapsedTime will return the time in seconds.  For example, if the elapsed time (the difference between stop and start) was 1000 ms, then the return value would be 1000 ms * .001 second/ms = 1 second.


text:
Q: C99 complex double - int or float imaginary zero affecting the real value Can someone explain why the following code produces different output for the test4 variable compared to the other 3?  I have checked this with gcc version 4.2.1 and 4.5.3 (and others in between).
Maybe I am missing something obvious, but it looks pretty straightforward...
#include <stdio.h>
#include <complex.h>

main()
{
    double complex test1, test2, test3, test4;

    test1 = 81141117.0;
    test2 = 81141117.0 + I * 0;
    test3 = 81141117 + I * 0.0;
    test4 = 81141117 + I * 0;
    printf("%ld + %ld I, %ld + %ld I, ", (long)creal(test1), (long)cimag(test1), (long)creal(test2), (long)cimag(test2));
    printf("%ld + %ld I, %ld + %ld I\n", (long)creal(test3), (long)cimag(test3), (long)creal(test4), (long)cimag(test4));
}

Output:
81141117 + 0 I, 81141117 + 0 I
81141117 + 0 I, 81141120 + 0 I

It appears that test4, having integer terms only, is being promoted to a float instead of the declared double, and round-off is coming into play.

A: I've tested GCC 4.7.1 on Mac OS X 10.7.5 (home-built GCC), and also the system provided /usr/bin/gcc and /usr/bin/clang, and they all produce the same result you report.
I agree with your analysis that there must be a conversion to float instead of double when both terms of the complex number are expressed as integers.  The C 2011 standard includes the example:
ISO/IEC 9899:2011 §6.7.9 Initialization

¶24 EXAMPLE 1 Provided that <complex.h> has been #included, the declarations
int i = 3.5;
double complex c = 5 + 3 * I;

define and initialize i with the value 3 and c with the value 5. 0 + i3. 0.

This clearly indicates that you should be able to write integer expressions and obtain a valid double complex (though examples are non-normative).  However, it does not address whether the integer value should be converted to float before being converted to double, but there's nowhere else in the language that would do that automatically (obviously, you can force it), so it is unlikely to be the intended interpretation.
On the whole, I think this is likely to be a bug that could be reported to the GCC team (and that's not something I advocate doing lightly).  If you run gcc --help, the output ends with the message:
For bug reporting instructions, please see:
<http://gcc.gnu.org/bugs.html>

I would extend your example as shown below (or, rather, I did extend your example as shown below):
#include <stdio.h>
#include <complex.h>

int main(void)
{
    double complex test1, test2, test3, test4, test5, test6, test7, test8;

    test1 = 81141117.0;
    test2 = 81141117.0 + I * 0;
    test3 = 81141117 + I * 0.0;
    test4 = 81141117 + I * 0;
    test5 = (float)81141117 + I * 0;
    test6 = 81141117 + I * (float)0;
    test7 = 81141117.F + I * 0;
    test8 = 81141117 + I * 0.F;
    printf("%ld + %ld I, %ld + %ld I\n", (long)creal(test1), (long)cimag(test1), (long)creal(test2), (long)cimag(test2));
    printf("%ld + %ld I, %ld + %ld I\n", (long)creal(test3), (long)cimag(test3), (long)creal(test4), (long)cimag(test4));
    printf("%ld + %ld I, %ld + %ld I\n", (long)creal(test5), (long)cimag(test5), (long)creal(test6), (long)cimag(test6));
    printf("%ld + %ld I, %ld + %ld I\n", (long)creal(test7), (long)cimag(test7), (long)creal(test8), (long)cimag(test8));
}

The output I got was:
81141117 + 0 I, 81141117 + 0 I
81141117 + 0 I, 81141120 + 0 I
81141120 + 0 I, 81141120 + 0 I
81141120 + 0 I, 81141120 + 0 I

As you can see, the last two lines, where there was an explicit (float) cast or explicit float constants, produce the same results as your problematic line (but the values are legitimate).
You might (or might not) want to experiment with the CMPLX, CMPLXF (and maybe CMPLXL) macros; I'd only add them to the reported example if they produced 'interesting' values for some definition of 'interesting'.

Compiler version numbers:
$ /usr/gcc/v4.7.1/bin/gcc --version
gcc (GCC) 4.7.1
Copyright (C) 2012 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ /usr/bin/gcc --version
i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)
Copyright (C) 2007 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ clang --version
Apple clang version 4.1 (tags/Apple/clang-421.11.65) (based on LLVM 3.1svn)
Target: x86_64-apple-darwin11.4.2
Thread model: posix
$


text:
Q: Ниже код. Он принимает двузначное положительное число и выводит разницу между большим и меньшим цифрами числа. Прошу помочь сделать код короче     const a = +prompt('enter a positive two-digit integer');
        if (a < 100 && a > 10) {
          const b = String(a).split('').map(i=>Number(i));
          if(+b[0]>+b[1]){
            console.log(+(b[0]-b[1]));
          }else if (+b[0]<+b[1]){
            console.log(+(b[1]-b[0]));
          }else(
            console.log('the numbers are equal')
          );

        } else(
          console.log('enter a positive two-digit integer'));

A: Будем использовать строковое представление пользовательского ввода. По условиям задачи, длина строки равна 2, строка может быть преобразована в положительное целое число.

const number = prompt("Enter a positive two-digit integer");
if (!(c=Number(number)) || c%1 || c<0 || number.length != 2) console.log("Введите положительное двузначное число");
else console.log((r=Math.abs((n = number.split(""))[0]-n[1]))==0?"Числа равны":r);


text:
Q: The Integral of $\int \sin(ax) \cos(ax) dx$ What is the integral of:
$$I=\int \sin(ax) \cos(ax) dx$$
My approach is down below.  I have attempted the problem and posted it as an answer.  I did the problem using trigonometric substitution.
$$u=ax$$
$$\frac{du}a=dx$$
$$\frac{1}a\int\sin u \cos u \ du$$
$$g=\sin u$$
$$dg = \cos u \ du$$
$$\frac{1}a\int g\ dg$$
$$I=\frac{1}a\frac{\sin^2ax}{2}+C$$

A: $$u=ax$$
$$\frac{du}a=dx$$
$$\frac{1}a\int\sin u \cos u \ du$$
$$g=\sin u$$
$$dg = \cos u \ du$$
$$\frac{1}a\int g\ dg$$
$$I=\frac{1}a\frac{\sin^2ax}{2}+C$$

A: $$\sin(ax) \cos(ax)=\frac{1}{2}\sin(2ax)$$


text:
Q: Java multi thread behavior without synchronization I faced the following question during an interview:
Lets assume a simple class
public class Example{

   private int a;

   public void update(){

      a = some new value;
   }

   public int getA(){

      return a;
   }

}

Now there are 2 threads (T1 and T2) which read and update the a value in the following sequence:
T2 (call update() and the value was set to 1)
T1 (call getA())
T2 (call update() and the value was set to 2)
T1 (call getA())

Is it possible for the last call getA() of thread T1 to return the value 1? If yes under what circumstances?

A: The last call to to T1 could return 0, 1, or 2. It doesn't really make sense to ask "under what circumstances." Under the circumstance of running this code, basically. The code isn't written for concurrency, so there's no guarantee.
In to guarantee that a a write to a variable by one thread is visible to a read of that variable by another thread, there needs to be a synchronization point between the threads. Otherwise, the JVM is allowed to optimize things in such a way that changes are only visible to the thread that makes them. For example, the writing thread's current notion of the value can be cached on the processor and written to main memory later or never. When another thread reads main memory for the value, it finds the initial value (0), a stale update (1), or the latest update (2).
The easiest fix in this case would be to declare a as a volatile variable. You'd still need some mechanism to ensure that T2 writes before T1 reads, but only in a weak, wall-clock sense.


text:
Q: Apache/2.4.29 (Ubuntu) Server at Port 443 for wordpress I'm facing an error in Wordpress after installing Let's encrypt certificate in AWS on Ubuntu 18.04.

How to fix this issue?

A: Get solution for the issue, need to change in apache2.conf file after that it will works,
old code in /etc/apache2/apache2.conf
<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

changed in to
 <Directory /var/www/>
            Options Indexes FollowSymLinks
            AllowOverride All
            Require all granted
    </Directory>

after that,
In order for Apache to understand rewrite rules, we first need to activate mod_rewrite. It's already installed, but it's disabled on a default Apache installation. Use the a2enmod command to enable the module:
$ sudo a2enmod rewrite

This will activate the module or alert you that the module is already enabled. To put these changes into effect, restart Apache.
$ sudo systemctl restart apache2

it works for me finally.

A: i hop your 443 port its block
login your aws and check open ports details
more info here


text:
Q: Elegant way to convert active record data into JS chart structure I think convert database data to  chart structure,
It's a really painful job with ruby.
Take a example,
I want to show a line chart.
X-axi (Time: Month), Y-axi (Value)
I need to union the Months among datasets
Then extract values from each datasets,
If there is no data for the corresponding month
You need to padding zero or any other value, you can not leave it null. otherwise the chart will be shifted.
I wonder if there is any elegant way to solve my problem.
Because to generate a chart. it's suck a hard and verbosed job for me. Thanks
datasets 1 (get from active record)
Month: January, value: 65
Month: February, value: 59
Month: April, value: 81

datasets 2 (get from active record)
Month: January, value: 28
Month: March, value: 40

data structure for js chart
    labels: ["January", "February", "March", "April"],
    datasets: [
        {
            data: [65, 59, 0, 81]
        },
        {
            data: [28, 0, 40, 0]
        }
    ]

A: Think in terms of hashes and arrays, and get yourself acquainted with methods such as Array#map.
irb(main):002:0> d1 = [["January", 65], ["February", 59], ["April", 81]];
irb(main):003:0* d2 = [["January", 28], ["March", 40]];

irb(main):007:0> h1 = Hash[d1]
=> {"January"=>65, "February"=>59, "April"=>81}
irb(main):008:0> h2 = Hash[d2]
=> {"January"=>28, "March"=>40}

irb(main):009:0> months = ["January", "February", "March", "April"]
=> ["January", "February", "March", "April"]

irb(main):010:0> months.map{ |month| h1[month] }
=> [65, 59, nil, 81]
irb(main):011:0> months.map{ |month| h1[month] || 0 }
=> [65, 59, 0, 81]

irb(main):012:0> [h1,h2].map{ |dataset| months.map{ |month| dataset[month] || 0 } }
=> [[65, 59, 0, 81], [28, 0, 40, 0]]
irb(main):015:0> [h1,h2].map{ |ds| {data: months.map{ |month| ds[month] || 0 }} }
=> [{:data=>[65, 59, 0, 81]}, {:data=>[28, 0, 40, 0]}]

irb(main):017:0> dsets = [h1,h2].map{ |ds| {data: months.map{ |month| ds[month] || 0 }} }
=> [{:data=>[65, 59, 0, 81]}, {:data=>[28, 0, 40, 0]}]
irb(main):018:0> {labels: months, dataset: dsets}
=> {:labels=>["January", "February", "March", "April"], :dataset=>[{:data=>[65, 59, 0, 81]}, {:data=>[28, 0, 40, 0]}]}


text:
Q: How to make Git only ask password when push to remote repository The requirement is probably odd. But sometimes I really need this functionality. Ok, here is the thing, I'm always working behind proxies. Either at office I'm using corp proxy or at home I'm using VPN and proxy as well (You know, I'm in China, so I hope you can understand).
Usually I'm using git protocol to connect github remote repository, but it's hard for me to set proxy behind git protocol, so I decided to switch back to http(s) with following command
git remote set-url origin https://github.com/<username>/repo.git
git config http.proxy http://proxy:8080
And it works like a charm. But git asks for username and password whenever I connect to the remote server, for example pull/push.
I only have one github account and I want to save some typing, so the question is how to avoid typing github username everytime I want to push. I could accept to type my password, but I don't want to type username. How to achieve that?

A: To complete Nevik's comment, you can change the url of an existing repo:
git remote set-url origin https://<username>@github.com/<username>/repo.git

That will specify the username the proxy authentication needs, leaving for you to enter the password.
I personally store all my different credentials (GitHub, BitBucket, ...) in an encrypted %HOME%\_netrc.gpg (Windows) or ~/.netrc.gpg (Unix) using the _netrc credential helper (git1.8.3+), rather than the memory cache credential helper described in Michael's answer.
See more at "Configure Git clients, like GitHub for Windows, to not ask for authentication".
The difference is:

*

*with the memory cache credential helper, you have to remember your GitHub password

*with a gpg netrc credential helper, you only have to remember your gpg passphrase, for all your different credentials.

Plus, if you activated GitHub two-factor authentication, you can no longer use your regular GitGub password, but you need a "Personal Access Token", which is a 40-lenght random string. One more reason to store that once and for all in an encrypted file, rather than having to enter it once per session.
What I just described is for https url, which, in my opinion, remains easier to manage than ssh url, with their public/private ssh keys that you need to passphrase protect, and that you need to publish  on your GitHub account (one different per workstation, since you shouldn't be reusing ssh keys)

A: This is the simple solution
for saving some typing you can use the following steps in git bash easily..
(1) create the remote repository
git remote add origin https://{your_username}:{your_password}@github.com/{your_username}/repo.git

Note: If your password contains '@' sign use '%40' instead of that
(2) Then do anything you want with the remote repository
ex:- git push origin master

A: Store Password
You could tell git to store your credentials using the following command:
git config --global credential.helper store

Using this method, you only need to enter your username and password once and git will never ask for it again. But please note that your password will be stored in plaintext which is not great in terms of security.
Cache Password
You can also go for caching instead which will store your password after having typed it once in a session for some period of time.
git config --global credential.helper cache

This is more secure as your password won't be stored on disk - just temporarily in memory. You can set the timeout yourself if your not happy with the default:
git config --global credential.helper 'cache --timeout=600'

Once again this is not always ideal.
SSH Agent - The Ideal Solution
What you should really be using is the ssh protocol to push and pull your data. This will allow you to use your private ssh key to authenticate yourself - which will be handled by your operating system's installed key agent. This should work with proxies without any issues so you should definitely give it a go.
You can set it up by setting your remote url as follows:
git remote set-url origin git@github.com:<username>/<project>.git

If you are using another hosting service like bitbucket, just replace "github.com" with your providers domain.
Once you do that, you will need to set up a public and private key pair for communication between github and your computer. There is a very good tutorial on how to set it up here. If you are using Linux or MacOSX you simply need to follow the steps when running the command ssh-keygen.
After that, you can get an SSH agent to store your password for you which is typically more secure. SSH agents usually ask you to input your password just once after turning on your computer - but after that it should do everything automatically for you. Passwords are stored securely this way unlike the first solution which stores passwords in plain text.
The SSH agent you use will depend on your operating system but it shouldn't be hard to set up. With most popular Linux distros you shouldn't need to do anything and I have been informed in a comment below that you can set Windows up as follows:
git config --global credential.helper wincred

I have never used MacOSX so I cannot say for certain whether this is automatically set up like it is in Ubuntu based distributions.


text:
Q: MS Access Update Query Keeps Asking for "Parameter Value" I will try to simplify the situation as best as I can...
I work with a team of field service technicians.  We share a lot of our tools and equipment between us because SOMEONE doesnt want to spend money on us.  I am using MS Access to develope a way to track who has what tool or specific piece of equipment out of a pool of about 2000+ items.  I have got the process figured out down to one last step.  It gos like this:

*

*Tech opens a form that shows current location/ownership of all 2000+ items, which is pulled off a SharePoint List and inserted into
a local table.

*Tech makes changes to local table.

*When Tech is done, the Sharepoint List gets updated FROM the local table (This is where I am stuck).

I have followed every tutorial, walk through, and work around that I can understand.  But every time I run the Query, Access asks me for the "Parameter Value" of each field I am trying to update.  Mind you, everything I have found shows an example of how to update one field in a table.  I am trying to update 5 fields per row.  When I let Access build the SQL for this it looks like:
UPDATE Table1 INNER JOIN Table2
ON Table1.[Asset ID] = Table2.[Asset ID]
SET Table1.Department = Table2.[Department], Table1.[Cal Status] = Table2.
[Cal Status], Table1.[Return Date] = Table2.[Return Date], Table1.Comments =
Table2.[Comments], Table1.[Cal Due] = Table2.[Cal Due], Table1.Active =
Table2.[Active];

The fields are not misspelled, I already checked and double checked that.
I have seen some comments about how Access has problems with UPDATE. But I am self taught with everything I do and I cant switch to something else until I understand this.  I just started with Access and SQL at the begining of this week, so please be patient with me.
EDIT
UPDATE Assets
SET Assets.Department = AssetsSharePoint.[Department],
Assets.[Cal Status]   = AssetsSharePoint.[Cal Status],
Assets.[Return Date]  = AssetsSharePoint.[Return Date],
Assets.Comments       = AssetsSharePoint.[Comments],
Assets.[Cal Due]      = AssetsSharePoint.[Cal Due],
Assets.Active         = AssetsSharePoint.[Active]
FROM Assets
INNER JOIN AssetsSharePoint ON Assets.[Asset ID] = AssetsSharePoint.[Asset
ID];

This gives me a "Syntax Error.  Missing Operator"  Then Highlights FROM
EDIT 2
If I cut it down to 1 field, leave out the FROM, and include WHERE it works. I dont want to make 5 seperate queries for this.  But I guess I am going to have to....

A: Your syntax is off, and it should be UPDATE ... SET ... FROM:
UPDATE t1
INNER JOIN Table2 t2
    ON t1.[Asset ID] = t2.[Asset ID]
SET
    t1.Department    = t2.[Department],
    t1.[Cal Status]  = t2.[Cal Status],
    t1.[Return Date] = t2.[Return Date],
    t1.Comments      = t2.[Comments],
    t1.[Cal Due]     = t2.[Cal Due],
    t1.Active        = t2.[Active]

A: Try this:
UPDATE Assets, AssetsSharePoint
SET Assets.Department = AssetsSharePoint.[Department],
Assets.[Cal Status]   = AssetsSharePoint.[Cal Status],
Assets.[Return Date]  = AssetsSharePoint.[Return Date],
Assets.Comments       = AssetsSharePoint.[Comments],
Assets.[Cal Due]      = AssetsSharePoint.[Cal Due],
Assets.Active         = AssetsSharePoint.[Active]
WHERE Assets.[Asset ID] = AssetsSharePoint.[Asset ID];

Neater statement:
UPDATE Assets INNER JOIN AssetsSharePoint ON Assets.[Asset ID] = AssetsSharePoint.[Asset ID]
SET Assets.Department = AssetsSharePoint.[Department],
Assets.[Cal Status]   = AssetsSharePoint.[Cal Status],
Assets.[Return Date]  = AssetsSharePoint.[Return Date],
Assets.Comments       = AssetsSharePoint.[Comments],
Assets.[Cal Due]      = AssetsSharePoint.[Cal Due],
Assets.Active         = AssetsSharePoint.[Active]


text:
Q: Image alignment issue in table I can't for the life of me get this image to center in the table I made for an HTML email.  Any suggestions?  I keep seeing online to style my  with text-align:center, but that just isn't working for me.

    New Video On American Vineyard Website!

A: Tables by default are display:table;. If you override this property it won't work as a normal table.

    New Video On American Vineyard Website!

A: Remove display:block in table style

            New Video On American Vineyard Website!


text:
Q: Using Worksheets. .Replace function for specific cell instead of entire column/row The following code works well for replacing a specific value in an entire column:
Worksheets("Sheet1").Columns(MyColumnLetter).Replace _
what:=val_Old, Replacement:=val_New, lookat:=xlWhole, _
SearchOrder:=xlByColumns, MatchCase:=False

However I only need to replace value in a specific cell (for example in cell "D9" as part of a vba loop) instead of the entire column or cell range.
Can anyone please suggest the required modification to the code above?
Thanks.

A: Replace value in one cell A2:
Range("A2").Replace oldValue, newValue

Replace value in a range:
Range("A2:A10").Replace oldValue, newValue

A: If you want to loop through the entire Column D (until last row):
Option Explicit

Sub Replace_ColumnD()

Dim sht1 As Excel.Worksheet
Dim LastRow As Long
Dim lrow As Long
Dim val_new As String
Dim val_old As String

Set sht1 = ActiveWorkbook.Worksheets("Sheet1")
LastRow = sht1.Cells(sht1.Rows.Count, "D").End(xlUp).Row

For lrow = 1 To LastRow
     sht1.Cells(lrow, 4).Replace val_old, val_new
Next

End Sub

A: Thanks guys. It was very helpful indeed.
Finally the code looks like this:
For i = 2 To LastRow

MyRange = MyColumnLetter & i

If....condition met:
   Worksheets("Sheet1").Range(MyRange).Replace val_Old, val_New
End If

Next


text:
Q: How do I reset a Cognito user's password that has expired? We're using Cognito.  All is well.  I added a user using the AdminCreateUser API, and they received their temporary password.  Unfortunately they waited over a month to login, and now when they try to login with their temporary password, Cognito returns this error:
User account has expired, it must be reset by an administrator.

How do I do that?  I don't see any reset button in the Cognito UI.  Is there a CLI or API that I can call?

A: The commands admin-reset-user-password and admin-enable-user do not work for an expired user.
The way you reset an expired user is to call admin-create-user again with the parameter MessageAction value = 'RESEND'
For example via CLI command:
aws cognito-idp admin-create-user --region us-east-1 --user-pool-id us-east-1_youruserpoolid --username theusername --message-action RESEND

From the documentation:

"Set to 'RESEND' to resend the invitation message to a user that
already exists and reset the expiration limit on the user's account."

Once you have reset the user, the user will need to change the temporary password otherwise they will be put back into this state again once they have exceeded the expiration time period (by default 7 days according to AWS documentation).


text:
Q: geom_vline with Character xintercept I have some ggplot code that worked fine in 0.8.9 but not in 0.9.1.
I am going to plot the data in theDF and would like to plot a vertical line at xintercept="2010 Q1." theGrid is merely used to create theDF.
theGrid <- expand.grid(2009:2011, 1:4)
theDF <- data.frame(YrQtr=sprintf("%s Q%s", theGrid$Var1, theGrid$Var2),
                    Minutes=c(1000, 2200, 1450, 1825, 1970, 1770, 1640, 1920, 1790, 1800, 1750, 1600))

The code used is:
g <- ggplot(theDF, aes(x=YrQtr, y=Minutes)) +
         geom_point() +
         opts(axis.text.x=theme_text(angle=90))

g + geom_vline(data=data.frame(Vert="2010 Q2"), aes(xintercept=Vert))

Again, this worked fine in R 2.13.2 with ggplot2 0.8.9, but does not in R 2.14+ with ggplot2 0.9.1.
A workaround is:
g + geom_vline(data=data.frame(Vert=4), aes(xintercept=Vert))

But that is not a good solution for my problem.
Maybe messing around with scale_x_discrete might help?

A: When you use a character vector, or a factor, for the x-axis in a plot the default values given to each of the unique items is simply integer starting at 1.  So, if your levels are c("A" "B", "C") then the x-axis locations are c(1,2,3).  There is no such thing as a character location, just a character label.  If you want a vertical line at A then put it at 1.  If you want it half way in between A and B then put it 1.5.  Again, those are the defaults.  If a particular plot did something else you can easily work that out by putting lines at a few locations and seeing what happens.

A: You could try this:
g + geom_vline(aes(xintercept = which(levels(YrQtr) %in% '2010 Q1')))

This avoids the need to create a dummy data frame for the selected factor level. The which() command returns the index (or indices if the right side of the %in% operator is a vector) of the factor level[s] to associate with vlines.
One caution with this is that if some of the categories do not appear in your data and you use drop = TRUE in the scale, then the lines will not show up in the right place.


text:
Q: Why won't this Drupal 7 schema work? I'm having issues with using the schema module and a table I created.  I used schema to create the schema and then when I tried to install the module logo_management, I get this error:
Invalid default    value for 'logoid':

CREATE TABLE {logo} ( `logoid` INT unsigned NULL auto_increment DEFAULT
0 COMMENT 'Unique Logo ID', `date_created` NULL DEFAULT 0 COMMENT
'The date the logo was    added.', `category` VARCHAR(50) NULL DEFAULT
'OTHER' COMMENT 'The category the logo should be in.', `no_of_lines`
INT NULL DEFAULT 1 COMMENT 'Number of lines(1 or 2)',
`line_1` VARCHAR(100) NULL DEFAULT NULL COMMENT 'Line 1 for Logo',
`line_2` VARCHAR(100) NULL DEFAULT NULL COMMENT 'Line 2 for Logo',
`image_path` VARCHAR(100) NULL DEFAULT NULL COMMENT
'Path and filename for image', `activate`
 INT NULL DEFAULT 0 COMMENT 'Boolean if the logo should be active or not.',
PRIMARY KEY (`logoid`) ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COMMENT

Here is the .install schema I have.  I'm assuming it's something wrong with the Invalid default value for 'logoid', however I tried putting the default value and it still gives me the same error.
function logo_management_schema() {
    $schema['logo'] = array(
      'description' => 'Logo Management Module',
       'fields' => array(
        'logoid' => array(
        'description' => 'Unique Logo ID',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
        'date_created' => array(
        'description' => 'The date the logo was added.',
        'type' => 'date',
        'not null' => TRUE,
    ),
    'category' => array(
      'description' => 'The category the logo should be in.',
      'type' => 'varchar',
      'length' => '50',
      'not null' => TRUE,
      'default' => 'OTHER',
    ),
    'no_of_lines' => array(
      'description' => 'Number of lines(1 or 2)',
      'type' => 'int',
      'not null' => TRUE,
      'default' => 1,
    ),
    'line_1' => array(
      'description' => 'Line 1 for Logo',
      'type' => 'varchar',
      'length' => '100',
      'not null' => TRUE,
    ),
    'line_2' => array(
      'description' => 'Line 2 for Logo',
      'type' => 'varchar',
      'length' => '100',
      'not null' => FALSE,
    ),
    'image_path' => array(
      'description' => 'Path and filename for image',
      'type' => 'varchar',
      'length' => '100',
      'not null' => TRUE,
    ),
    'activate' => array(
      'description' => 'Boolean if the logo should be active or not.',
      'type' => 'int',
      'not null' => TRUE,
      'default' => 0,
    ),
  ),
  'primary key' => array('logoid'),
);

return $schema;
}

A: Skill and determination fixed this problem!  Changed the type to int.
$schema['logo'] = array(
      'description' => 'Logo Management Module',
      'fields' => array(
        'logoid' => array(
          'description' => 'Unique Logo ID',
          'type' => 'int',
          'unsigned' => TRUE,
          'not null' => TRUE,
        )

Then I ran into a date problem and changed it to this:
    'date_created' => array(
      'description' => 'The date the logo was added.',
      'type' => 'datetime',
      'mysql_type' => 'DATETIME',
      'not null' => TRUE,
    ),

Now my module installs!


text:
Q: Popcorn-Time installation I downloaded a new Popcorn Time from popcorn-time.se and I don't know how to install a tar.gz file. I extracted the folder that is in tar.gz and then tried to run command sudo ./install but there in no command found.. What should I do? How to install this "new" Popcorn Time source file?

A: Those are directly the files you need to run the program. For opening Popcorn Time, just run from the extracted folder:
./Popcorn-Time

However, if you want to know where to save all those files with the other programs, a good place would be /usr/share.
So, let's say the folder where you extracted the files is ~/popcorn-time. Then, you'll have to run this in a terminal:
# Copy the whole folder into /usr/share, using recursive option
sudo cp -r ~/popcorn-time /usr/share/popcorn-time
# Create a symlink to the binary file
sudo ln -s /usr/share/popcorn-time/Popcorn-Time /usr/bin/popcorn-Time

From now on, you'll be able to run popcorn-Time on the Terminal, and it'll open.
Finally, if you want to have an icon in the launcher, create a new file in your home directory, named popcorn.desktop, and write the following in it:
[Desktop Entry]
Name=Popcorn Time
Comment=Watch torrent movies instantly!
Exec=/usr/bin/popcorn-time
Terminal=false
Type=Application

A: When you unpack it, that already is the installation. It's no source file, it's a binary precompiled proprietary blob.


text:
Q: How to copy using scp on shell script to folders space named? Hey guys I am working on this app that connects to Raspberry Pi through SSH. I use NSTask and NSPipe and shell scripts to execute the shell commands through the Mac app GUI.
The problem is that when I want to copy using "scp" command I get "No such file or directory" error with folders with spaces on its name. If the path is "/Users/home/Desktop/New Files/" doesn't work, but if "/Users/home/Desktop/New Files/" works fine.
The app must be able to use both, separated named folders and not separated, but I just don't know how to do it.
Here is my shell script command:
#!/bin/bash
/usr/bin/ssh pi@192.168.25.144 \
/usr/bin/scp /home/pi/"${1}" home@192.X.X.X:/Users/home/Documents/New Files/

The "X"on the ip was intentionally removed and it's not on the real code.
So, anyone could help????

A: This is tricky because it requires multiple levels of escaping.
First, start with the actual path:
home@192.X.X.X:/Users/home/Documents/New Files/

Now escape it for the shell:
"home@192.X.X.X:/Users/home/Documents/New Files/"

Now escape it for scp, since scp accepts shell glob patterns and not filenames:
/usr/bin/scp /home/pi/"${1}" "home@192.X.X.X:/Users/home/Documents/New\\ Files/"

Now escape it for ssh, since ssh will evaluate it in a shell:
/usr/bin/ssh pi@192.168.25.144 \
    /usr/bin/scp /home/pi/"${1}"  \
      '"home@192.X.X.X:/Users/home/Documents/New\\ Files/"'

This takes care of the "New Files" part, but let's also try to do something about the "${1}" argument:
/usr/bin/ssh pi@192.168.25.144 \
    /usr/bin/scp /home/pi/"$(printf "%q" "$1")"  \
      '"home@192.X.X.X:/Users/home/Documents/New\\ Files/"'

Here's a complete, self contained example of the above, going through localhost twice:
#!/bin/bash
cd ~
mkdir "New Files"
touch "my file"
set -- "my file"  # Assign $1="my file"
/usr/bin/ssh localhost \
      /usr/bin/scp "$(printf "%q" "$1")"  \
        '"localhost:New\\ Files/"'

find "New Files" -type f

The output shows that it did in fact copy a file with spaces over scp over ssh to the dir with spaces:
New Files/my file

Since multilevel escaping is tricky, if you're having any problems, make sure to try this self contained example first without modifications before concluding that it doesn't work.

A: Put "" around the path.
$ mkdir 1 1
mkdir: 1: File exists
$ mkdir "1 1"
$ ll
drwxr-xr-x  2 mikael  staff  68 May 21 22:35 1
drwxr-xr-x  2 mikael  staff  68 May 21 22:36 1 1

A: Try escaping spaces with a backslash:
home@192.X.X.X:/Users/home/Documents/New\ Files/


text:
Q: NSSM: Can't open service! OpenService(): Access is denied I'm trying to install selenium-server-standalone-3.141.59.jar as an nssm service. It installs fine but when I try to run it, I get an error.
I installed via: PS C:\Users\MyUser> nssm install selenium-server java -jar "C:\selenium\selenium-server-standalone-3.141.59.jar
Then running nssm start selenium-server gives me OpenService(): Access is denied.
I tried to follow this but linking to the batch file didn't work either:
NSSM: Can't edit a service I created

A: The problem seems to have fixed itself, I restarted my computer and it seems to be running! Previously, it didn't let me run it on demand so anyone having this problem can just try a restart.
UPDATE: I believe it's because I did not launch Powershell in admin mode on Windows 10, try that if you have problems.

A: I was facing same issue, I did following steps:
1)Check the current status of service using nssm status service_name
2)Close command prompt
3)Run command prompt in Administrator mode
4)Execute nssm start service_name

A: Struggled with the same issue. Fixed it!
The reason was, that the nssm executable also has to be accessible by the given service user, which was not the case in my setting.
Resolution:

*

*Create local user

*Ensure local user has rights to run as a service (https://learn.microsoft.com/en-us/system-center/scsm/enable-service-log-on-sm?view=sc-sm-2019) - Local Group Policy

*Have the nssm.exe ALSO accessible by the created user


text:
Q: Ordenar una tabla en el que el indice de orden sea un valor String Estoy realizando una pagina web en la que agrupa la información de un juego a cada jugador. Está información contiene el rango de la cuenta y los puntos, rango es Bronce, plata etc. Los datos los tengo en una tabla y quiero que se ordenen de mayor rango a menor pero no se como hacerlo.
https://imgur.com/a/m5OkiVd
(esto es como tengo la tabla ahora mismo pero no se ordenarlo.)
Añado el codigo del th :
    echo "";
                    if ($rank[0][tier] != Null ){
                            if ($rank[1][QUEUETYPE] == "RANKED_FLEX_SR" ){
                                $soloq=0;

                            }else{
                                $soloq=1;

                            }

                            echo " ".$summoner[name]." (Nivel  ".$summoner[summonerLevel].") · ".$rank[$soloq][tier]." ".$rank[$soloq][rank]." [".$rank[$soloq][leaguePoints]." LP] W:".$rank[$soloq][wins]." L:".$rank[$soloq][losses]."";

                    }else{
                    echo " ".$summoner[name]." (Nivel  ".$summoner[summonerLevel].") · UNRANKED";
                    }
                    echo "	";

A: Para reordenar arrays multidimensionales puedes usar esto:
<?php

    $users[] = array('name' => 'Sergio', 'age' => 22);
    $users[] = array('name' => 'Carlos', 'age' => 29);
    $users[] = array('name' => 'Iván', 'age' => 24);
    $users[] = array('name' => 'Jorge', 'age' => 21);
    $users[] = array('name' => 'Dani', 'age' => 25);
    $users[] = array('name' => 'Jose', 'age' => 27);
    $users[] = array('name' => 'David', 'age' => 19);
    $users[] = array('name' => 'Esteban', 'age' => 35);

    foreach ($users as $key => $row) {
        $aux[$key] = $row['age'];
    }

    array_multisort($aux, SORT_ASC, $users);

    foreach ($users as $key => $row) {
        echo $row['name'].' '.$row['age'].'
';
    }
 ?>

Fuente: https://www.jose-aguilar.com/blog/multidimensional-array-sort/
  PHP: https://www.php.net/manual/es/function.array-multisort.php

Luego lo pintas.


text:
Q: Handle JWT token with private pages in sails js I want to increase restriction in my system.Then I used JWT token.then i preferred statellizer for the front-end.
once user log into the system.it will generate token like this
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6InRlc3RAZ21haWwuY29tIiwiaWF0IjoxNDU1NzAzNTE5fQ.I6z8jlXx4H1R3gNOAnOysdI0qyeU01GAlnYWeQZKThs
But case is when user successfully log into the system.It will redirect to the dashboard but token did n't bind with the request.
other request are working properly only case in the dashboard.
login function in Controller
         $scope.authLogin = function () {
           $auth.login({
             email: $scope.email, password: $scope.password
           }).then(function(res){
             //userService.setUser(res.data.user);
             toastr.success('Successfully login ', 'Message', {
               closeButton: true
             });
             window.location = '/dashboard';
           }).catch(function onError() {
               toastr.error('Invalid email/password combination.', 'Error', {
                 closeButton: true
               });
           });
         };

routes file
'/login'  : { view: 'static/login'},
'/signup' : { view : 'static/signup'},
'/'       : { view: 'static/login' },
'GET /dashboard' : 'PageController.showDashboard',

policies file
  'UserController':{
    '*':['jwtAuth'],
    authLog : true
   // signUp : true
  },

  'PageController': {
    '*': ['jwtAuth']
  }

I want to make it like anyone can't access dashboard without token.I hope my question is clear.
Thanks

A: Way of I tried,That is wrong because when we called GET /dashboard function then could n't bind token with request.This method perfectly work with session.
I used following method.It work for me.This is more convenient to handle JWT with sails.
json-web-tokens-examples with sails


text:
Q: How can I invoke function jquery with ashx handler? I'd like to know how can I invoke a function in an aspx handler(.ashx).
This is what I've tried:
public void ProcessRequest(HttpContext context) ...

context.Response.ClearContent();
context.Response.ContentType = "text/javascript";
context.Response.Write("<script>$('#showAlert').show();</script>");

but this does nothing, I'd like to know if is it possible and if it is how can I do it.
I can refer that the aler is written in a web user control.
//THIS IS USED TO CALL THE HANDLER
$("#saveChanges").click(function () {
        $("#gif").show();
        $.ajax({
            url: "../handlers/adminSaveResults.ashx?pinAntigo=" + $("#pin").val() + "&pinNovo=" + $("#pinNovo").val() + "&passAntiga=" + $("#old").val() + "&passNova=" + $("#newP").val() + "",
            type: "POST",
            data: {},
            async: true,
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            success: function (data) {
                $("#gif").hide();
            },
            error: function (data) { /*alert("ERRO: " + data.status);*/ $("#gif").hide(); },
            timeout: 15000
        });
    }
  );

Regards

A: If I understand correctly what you want, it should be something like this:
Server:
public void ProcessRequest(HttpContext context) ...
context.Response.ClearContent();
context.Response.ContentType = "application/json";
context.Response.Write("{"ok": 1 }");

And here is the js:
$("#saveChanges").click(function () {
        $("#gif").show();
        $.ajax({
            url: "../handlers/adminSaveResults.ashx",
            type: "POST",
            data: {pinAntigo: $("#pin").val(),
                   pinNovo: $("#pinNovo").val(),
                   passAntiga: $("#old").val(),
                   passNova: $("#newP").val() } ,
            async: true,
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            success: function (data) {
            if(data.ok){
                {
                    $('#showAlert').show();
                }
                $("#gif").hide();
            },
            error: function (data) { /*alert("ERRO: " + data.status);*/ $("#gif").hide(); },
            timeout: 15000
        });
    }
  );


text:
Q: jQuery on() doesn't work on already added DOM items I have this:
$(document).on("click", ".prev", function(){
    $(this).closest("div").find(".slider").animate({
        "left": "+=450px"
    }, 800, "easeInOutBack");
    return false;
});

Which works when new elements are added to the DOM, but it doesn't work for elements that are already in the DOM.
When I do this:
$(".prev").on("click", function(){
    $(this).closest("div").find(".slider").animate({
        "left": "+=450px"
    }, 800, "easeInOutBack");
    return false;
});

It works for elements in the DOM, but not new ones added to the DOM. Is there a way for me to get this to work for both without me having to write this 2 times, or make a call to another function?
Here is a screen shot:

So, Here is a more in depth description of how it works.
<div id="simple-pevs" style="padding-right: 20px;">
    <?php require_once __DIR__ . "/data/get/PEVSection.php"; ?>
</div>

Then When someone wants to add another section they click on the add button which then runs this code:
    $(".add-another-pev").click(function(){
        $.get("./data/get/PEVSection.php?pev="+pevGroup, function(data){
            $("#simple-pevs").append(data);
        });
        pevGroup++;
        return false;
    });

As you can see it is calling the same one that was pre-loaded in the php. The new one works (and any other additional ones added) with the click event and the fist one doesn't
@ArunPJohny
console.log($(".prev")); after a new element is added:
[a.prev, a.prev, prevObject: b.fn.b.init[1], context: document, selector: ".prev", jquery: "1.9.1", constructor: function…]
0: a.prev
1: a.prev
context: #document
length: 2
prevObject: b.fn.b.init[1]
selector: ".prev"
__proto__: Object[0]

A: Below is the content that I copied from Jquery official website, It can explain it very clearly:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.
In addition to their ability to handle events on descendant elements not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its tbody, this example attaches a handler to 1,000 elements:
$("#dataTable tbody tr").on("click", function(event){
alert($(this).text());
});

A delegated-events approach attaches an event handler to only one element, the tbody, and the event only needs to bubble up one level (from the clicked tr to tbody):
$("#dataTable tbody").on("click", "tr", function(event){
alert($(this).text());
});

Note: Delegated events do not work for SVG.
http://api.jquery.com/on/

A: No if you create new elements like this, then you need to rebind the event handler.
function bindHandler() {
    $(document).on("click", ".prev", function(){
        $(this).closest("div").find(".slider").animate({
            "left": "+=450px"
        }, 800, "easeInOutBack");
        return false;
    });
}
bindHandler();

$(".add-another-pev").click(function(){
    $.get("./data/get/PEVSection.php?pev="+pevGroup, function(data){
        $("#simple-pevs").append(data);
    });
    pevGroup++;

    bindHandler();
    return false;
});


text:
Q: MySQL: can I define a query as a variable? I have a query which is a UNION of two Queries:
SELECT first_name, last_name, email
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.promoter = true
AND o.ticket = 'HOTEL'

UNION ALL

SELECT first_name, last_name, email
FROM users u
WHERE u.id IN (
'232drt-erty3-dff3',
'sswer3-ddf33-675t',
'we2311-23xxw-11vb'
)

I would like to know if is it possibile to define the two queries as variables and call them Q1 and Q2
So that my query becomes something like
SELECT *
FROM (
Q1 UNION ALL Q2
)


text:
Q: Serializer behaviour with null=False fields in DRF I've encountered a weird behavior that I don't quite get. For the model
class Tenant:
    name = models.CharField(max_length=155)
    country = models.CharField(max_lengh=155)

I'm using this serializer:
class Serializer(serializers.ModelSerializer):
    class Meta:
        model = Tenant
        fields = (name,)

This set up will allow me to save a tenant instance that doesn't have a country supplied even though the null=True should be enforced on the DB level (Postgres). Only when I add country to the fields, will it enforce the null=False constraint.
This seems quite unintuitive to me.

Edit: Here is a simple code example of my problem:
class AppModel(models.Model):
    name = models.CharField(max_length=255)
    country = models.CharField(max_length=255)

class CrateAppModel(APIView):

    def post(self, request, format=None):
        serializer = AppModelSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class AppModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = AppModel
        fields = (
            "name",
        )

Using simple post requests I'm able to create an instance without a country field. I don't understand why? In my database country is of type string and empty.


text:
Q: Can not apply join from unmatched type of field I am learning mongodb join and it works great. It fail to join when we try to join one filed has ObjectId and another field has simple id.
Thanks in advance


text:
Q: Accessing remote browsers on client machines I have a portal built with flask, through which the selenium gets initialized and opens up the given web application in chrome browser. Here the selenium is ran from the python code to get access to the browsers.
I'm facing problem in deployment of the application.
I have deployed the portal on a virtual box VM. Everthing works perfectly.
But when I try to access the portal from the other machine using Virtual machine ip address, portal is rendering but, the chrome browser is opening on virtual box VM istead of user's (client) machine. This is supposed to be accessable to clients but this is not happening as expected.
Can someone please help me in fixing this issue. Please find the code below.
def run_selenium(passed_url):
    browser = request.user_agent.browser
    version = request.user_agent.version and int(request.user_agent.version.split('.')[0])
    platform = request.user_agent.platform
    uas = request.user_agent.string

    if 'OPR' in uas:
        browser = 'Opera'
        driver = webdriver.Opera()
    elif browser == 'chrome':
        browser = 'Chrome'

    #location of chromedriver needed for running seenium on chrome browser. chromedriver is uploaded to github repo
        driver = webdriver.Chrome(conf.CHROME_DRIVER_PATH[0])
    elif browser == 'firefox':
        browser == 'Firefox'
        driver = webdriver.Firefox()

    driver.get(passed_url) #passing url taken from form
    head_element = WebDriverWait(driver, 30).until(lambda driver: driver.find_element_by_tag_name('head')) # waiting for page to atleast load <head> element fully so script could be injected
    if head_element:
        print ("injecting script")

        # rawgit.com MaxCDN service used.. js file is at github repo annoletjs/master
        driver.execute_script("!function(){function e(){script=document.createElement('script'),script.type='text/javascript',script.src='//rawgit.com/SSS-Studio-development/annoletjs/tagging/annolet_main.js',document.getElementsByTagName('head')[0].appendChild(script)}($=window.jQuery)?e():(script=document.createElement('script'),script.src='//ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js',script.onload=e,document.getElementsByTagName('head')[0].appendChild(script))}();")
        print ("injected")
    return 'annotate'


text:
Q: centering span after transform trying to create one of the animated buttons available on semantic ui specifically the animated shopping cart one https://semantic-ui.com/elements/button.html
I created a fiddle here where I did it using css transforms.
https://jsfiddle.net/n37arru2/100/
my question is, is there a way to vertically and horizontally position the span that slides in on hover without having to use top, left css attributes?
span {
  position: absolute;
  top: -45px;
  left: 14px;
  transition: top .6s linear;
}

button {
  position: relative;
  transition: all .6s linear
}

i {
  color: #FFF;
  font-size: 34px !important;
  /* 24px preferred icon size */
  vertical-align: middle;
  transition: transform .6s linear;
}

span {
  position: absolute;
  top: -45px;
  left: 14px;
  transition: top .6s linear;
}

button:hover > i {
  transform: translate3d(0px, 45px, 0px);
}

button:hover > span {
  top: 12px;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

 <button class="btn btn-primary">
   face
   Face
 </button>

A: Instead of tweaking around the values, you can make use of these:
top: 50%;
left: 50%;
transform:translate(-50%,-50%);

The above is used to center the element having absolute positioning with relation to its parent container. So, initially setting the span to a negative top value and on transition setting to 50% will center it.
span {
  position: absolute;
  top: -50%;
  left: 50%;
  transform:translate(-50%,-50%);
  transition: top .6s linear;
}

button:hover > span {
    top: 50%;
}

button{
  position: relative;
  transition: all .6s linear
}

i {
  color: #FFF;
  font-size: 34px !important; /* 24px preferred icon size */
  vertical-align: middle;
  transition: transform .6s linear;
}

span {
  position: absolute;
  top: -50%;
  left: 50%;
  transform:translate(-50%,-50%);
  transition: top .6s linear;
}

button:hover > i {
    transform: translate3d(0px, 45px, 0px);
}

button:hover > span {
    top: 50%;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

 <button class="btn btn-primary">
   face
   Face
 </button>


text:
Q: MS Teams bot - create conversation in newly created Group returns 405 BadArgument I'm trying to create new convesation for just created channel using Nodejs + botframework v4.9.2.
I've

*

*created new Channel using POST https://graph.microsoft.com/beta/teams/${teamId}/channels

*new tab using POST https://graph.microsoft.com/beta/teams/${req.teamId}/channels/${req.channelId}/tabs

*I can see new channel and tab in Teams UI

*trying to create new conversation via Conversations.createConversation from bot sdk, it's basically calling POST https://directline.botframework.com/v3/conversations with passing new channel id and getting 405 BadArgument This channel does not support this operation
I'm running bot locally and proxying via ngrok.
Also I can access GET /v3/conversations.
Updated code
Get Team Memebers GET ${graphUrl}/groups/${teamId}/members
Create new Channel
const createChannelRequest: IGraphCreateChannelBody = {
    "@odata.type": "#Microsoft.Teams.Core.channel",
    displayName: channelName,
    description: `This channel is for incident id : ${incidentId}`,
    members: membersIds.map(memberId => (
        {
            "@odata.type": "#microsoft.graph.aadUserConversationMember",
            "user@odata.bind": `https://graph.microsoft.com/beta/users('${memberId}')`,
            roles: ["owner"]
        }
    ))
};

return await graphClient.createChannel(teamId, createChannelRequest);

createChannel is basically POST ${graphUrl}/teams/${teamId}/channels
Create new Tab POST ${graphUrl}/teams/${req.teamId}/channels/${req.channelId}/tabs where channelId is createChannelResponse.id
Create new conversation
const client = new BotConnector.ConnectorClient(credentials, {baseUri: serviceUrl});
const {bot} = TurnContext.getConversationReference(activity);
const createConversationResponse = await client.conversations.createConversation({
    bot,
    activity: incidentActivity,
    members: teamMembers.value.map(member => ({
        id: member.id,
        name: member.displayName
    })),
    channelData: {
        channel: {
            id: newIncidentChannelId
        },
        tenant: {
            id: tenantId
        }
    },
    isGroup: true
});

where createConversation fails with 405

A: [Posting a complete answer, based on the comments above]
There's no need (and it won't work), in the context of Teams, to use createConversation, because the conversation is created the moment the Team/Channel/Group chat itself is created (createConversation exists for other Bot Framework scenarios, and is not applicable for Teams). As a result SendToConversation is the correct operation to use.
As to how to use SendToConversation, there are certain important variables you need to have already your side, and the most common time to get these is when your bot is added to the channel/chat/whatever in the first place. You can read more about that here, but more generally, this is considered something called "proactive" messaging, in Teams, and it's worth reading up on that topic more. Please see here and here as good starting points.


text:
Q: Perform Longest Common Prefix I'm working on a Leetcode exercise in regards to finding the Longest Common Prefix in an array of words. Working on improving my skill in Golang and so attempting it in that language. I'm attempting to solve it using a Trie structure. I've racked my brain and am unsure why my counter that keeps track of how many times a node is visited is not incrementing in my struct. My brain thinks its something pointer/reference related but when I look at it, it seems fine.
My thought process is that if you encounter a node that has already been created, you increment its "visited" counter by one. Then, if you determine that the node has been visited the same amount of times as the number of words in the input array and its greater than current LCP, then make that the new LCP.
The issue I'm having is the counter in the Node is not incrementing. When I increment it and then immediately print the value, it appears to have incremented but then when its traveled to in the next iteration, its value has not increased from its original initialized value of 1
func longestCommonPrefix(strs []string) string {
rootNode := Node {CommonPrefixCounter: 0, LinkNodes: make(map[string]Node, 26) }
var currentNode Node
longestPrefix := ""
lengthOfLongestPrefix := 0
if(len(strs) == 1) {
    //Edge case where there is only one word so whatever its length is longest common prefix
    return strs[0]
}
for _, word := range strs {
    currentNode = rootNode
    currentPrefix := ""
    //Split into individual character
    characters := strings.Split(word, "")
    for _, character := range characters {
        fmt.Printf("Current Letter is %s \n", character)
        if currentNode.LinkNodes[character].LinkNodes == nil {
            //Have not seen this letter in this sequence before
            fmt.Println("Making a new node")
            currentNode.LinkNodes[character] = Node{CommonPrefixCounter: 1, LinkNodes: make(map[string]Node, 26)}
            currentNode = currentNode.LinkNodes[character]
        }  else {
            //Have encountered this Node before
            currentPrefix += character
            currentNode = currentNode.LinkNodes[character]
            currentNode.CommonPrefixCounter++
            fmt.Printf("CurrentNode common prefix counter is %d\n", currentNode.CommonPrefixCounter)
            if (currentNode.CommonPrefixCounter > lengthOfLongestPrefix) && currentNode.CommonPrefixCounter == len(strs) {
                lengthOfLongestPrefix = currentNode.CommonPrefixCounter
                longestPrefix = currentPrefix
            }
        }
    }
}
fmt.Printf("Longest Common Prefix was %d and it was %s", lengthOfLongestPrefix + 1, longestPrefix )
return longestPrefix

}
type Node struct {
CommonPrefixCounter int
LinkNodes map[string]Node

}
Any help would be appreciated. Sitting here looking at it for a few hours and decided its time for some help.

A: Your maps are using nodes as value. That means, any time you get a node value from the map, you get a copy of it, and any time you put a value, you put a copy of it. Because of this, currentNode.CommonPrefixCounter++ will update the currentNode copy you have but not the copy in the map.
Declare the map as map[string]*Node and pass node pointers around. There might be other bugs in your code, but this would at least allow you to create a correct trie.


text:
Q: jQuery AJAX process not working (Updating div with JSON results) I am trying to fetch some results from a database, then convert them to JSON and display the results in a div that is updated through AJAX and triggered by the Go! (form submit) button.
The code is not working, and I don't know why. I already checked my database connection, with other simple examples, and I am able to connect and even fetch results from the same database, but whenever I try to use it with AJAX/jQuery it does not work.
NOTE: Whenever I try to see the JSON object in the console, I get nothing but this error:

Uncaught SyntaxError: Unexpected identifier index.php:20

index.php:
<!DOCTYPE html>

    <title>Page</title>

    <form method="post">
        Username:
        <input type="text" name="username" id="usrnfield">

        <input type="submit" value="Go!" id="subForm">
    </form>

Here are the usernames:

fetchuser.php:
<?php
  $dbhost = "localhost";
  $dbname = "database";
  $dbuser = "root";
  $dbpass = "root";

  $pdo = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
  $rows = array();

  if(isset($_POST['username'])) {
    $stmt = $pdo->query("SELECT * FROM userlist WHERE username = ?");
    $stmt->execute(array($_POST['username']));
    $rows = $stmt->setFetchMode(PDO::FETCH_ASSOC);
    echo json_encode($rows);
  }
?>

A: The Uncaught SyntaxError: Unexpected identifier index.php:20 is for a missing trailing comma in the line 19
$.ajax({
  type: "POST" // <-- Missing comma
  url: 'fetchuser.php',

I've made some serious changes at your code, but is all commented... Some things are not 100% optimized for the sake of simplicity.
First, you can try the return value from the url (localhost/site/fetchuser.php?username=Test) with this approach.
In your php there was some errors:
<?php
  $dbhost = "localhost";
  $dbname = "database";
  $dbuser = "root";
  $dbpass = "root";

  $pdo = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
  // We use GET because $.getJSON uses GET =P
  if(isset($_GET['username'])) {
    // You have used the query function with execute, this is not correct
    // You need prepare with execute
    $stmt = $pdo->prepare("SELECT * FROM userlist WHERE username = ?");
    $stmt->execute(array($_GET['username']));
    // FETCH_ASSOC would return the fields indexed by the field name.
    // In your success/done function you are using numbers index.
    // So, you need FETCH_OBJ
    // http://www.php.net/manual/es/pdostatement.fetch.php#refsect1-pdostatement.fetch-description
    $rows = $stmt->fetchAll(PDO::FETCH_OBJ);
    echo json_encode($rows);
  } else {
    // This is not a json response, so it will trigger
    // the fail function in $.getJSON
    echo "Error";
  }
?>

In your HTML we make easy to jQuery interacts
<!DOCTYPE html>

    <title>Page</title>

    <form id="subForm">

        Username:
        <input type="text" name="username" id="usrnfield">

        <input type="submit" value="Go!">
    </form>

      id:

      Username:

      First Name:

      Last Name:

      Email:


text:
Q: How to execute a shell script on startup? I have created a script to start a server (my first question). Now I want it to run on the system boot and start the defined server. What should I do to get this done?
My findings tell me put this file in the /etc/init.d location, and it will execute when the system will boot. But I am not able to understand how the first argument on the startup will be start? Is this predefined somewhere to use start as $1? If I want to have a case startall that will start all the servers in the script, then what are the options I can manage?
My script is like this:
#!/bin/bash

case "$1" in
start)
     start
    ;;
stop)
    stop
    ;;

restart)
    $0 stop
    $0 start
    ;;
*)
    echo "usage: $0 (start|stop|restart)"
;;
esac

A: You don't have to --- and shouldn't --- create files in /etc/rc.d/rcN.d/; what you should do instead is put a comment in your init script reading
# chkconfig NNN A B

where NNN is the set of run-levels in which you want the script active (e.g., 345 if it's active in runlevels 3, 4, and 5), and A and B are the start and stop priorities.  Then chkconfig --add foo (assuming your script is named foo) will create the files in /etc/rc.d/rcN.d/ with the appropriate names.
You can then use service foo bar to send the bar message to your script (e.g., start, stop, whatever -- that's where your $1 comes from).

A: /etc/init.d is the script directory, in which the executable scripts appear. However, in order to run scripts in a particular order after your system starts, you need to add files to the /etc/rc#.d directory. Entries that appear here tell your system in what order and at what run level scripts in /etc/init.d should be run. The number after the rc indicates what run level the machine is running at, according to this chart:
http://en.wikipedia.org/wiki/Runlevel
So if you have:
/etc/init.d/importantscript

Then you need the (empty) files:
/etc/rc.d/rc3.d/S20importantscript
/etc/rc.d/rc6.d/K20importantscript

The S means start, and the K means kill. When your machine starts, the system will say "Ah, I'm running at RunLevel 3, let's pop over to rc3.d to see what scripts in '/etc/init.d' need to be run and in what order." In this case, the system will sort by 'S' and then the number after 'S' and will execute '/etc/init.d/importantscript start'. The 20 is just for ordering purposes... your script will run behind 'S19' and in front of 'S21'. You can create these files simply by doing:
sudo touch /etc/rc.d/rc3.d/S20importantscript
Here's a nice summary as well: http://www.linux.com/news/enterprise/systems-management/8116-an-introduction-to-services-runlevels-and-rcd-scripts

A: The $1 is the command line argument that is passed to your script, it is one of start, stop or restart. In openSUSE, I don't remember having an option to pass other arguments into the script when useing the runlevel editor thingy, so I think that these are probably the only ones you should use.
I don't use CentOS myself, but it seems that the program to control what is started at which runlevel is ntsysv.


text:
Q: How to test an application that uses LinkedIn API? I'm in the process of integrating LinkedIn into my application, via their API. The problem is that I cannot test it.
In order to test it, I need a test user that is administrator of a company page. I cannot create a company page since my test user does not meet the minimum requirements.
How have other users of the API solved this problem?

A: A quick peruse of the documentation for company page administration on LinkedIn's developer website yields this:
https://developer.linkedin.com/docs/company-pages#testing
LinkedIn has a special test company that you can in your test cases for this exact purpose.


text:
Q: Slow response from Identity Server 4.0 (asp.net core 2.0) on connect/token endpoint on high load We have setup Identity Server 4 with Entity Framework Core. We successfully created and Seeded the desired Client to the MSSQL Database and deployed both the Project and the Database to one and the same AWS Datacenter.
In our Startup.cs class we have:
           .AddInMemoryCaching()
          .AddClientStoreCache<CachingClientStore<ClientStore>>()
          .AddResourceStoreCache<CachingResourceStore<ResourceStore>>()
          .AddTestUsers(Config.GetUsers());

           where Config.GetUsers() is

           public static List<TestUser> GetUsers()
          {
              return new List<TestUser>
              {
                  new TestUser
                  {
                      SubjectId = "1",
                      Username = "alice",
                      Password = "password"
                  },
                  new TestUser
                  {
                      SubjectId = "2",
                      Username = "bob",
                      Password = "password"
                  }
              };
          }

We successfully obtain an access_token with the provided configurations without making calls to the DB.
The Issue is as follow:
Using JMeter we face the following results:
2 Containers (1.5GB RAM) /connect/token (POST) endpoint (250 simultaneous requests issued for 1 second)
•    Average response time – 252 ms
•    Min response time – 142 ms
•    Max response time – 597 ms
•    Throughput – 167 req/sec
/connect/token (POST) endpoint (350 simultaneous requests issued for 1 second)
•    Average response time – 780 ms
•    Min response time – 150 ms
•    Max response time – 2382 ms
•    Throughput – 130 req/sec
/connect/token (POST) endpoint (400 simultaneous requests issued for 1 second)
•    Average response time – 1112 ms
•    Min response time – 153 ms
•    Max response time – 3806 ms
•    Throughput – 134 req/sec
/connect/token (POST) endpoint (500 simultaneous requests issued for 1 second)
•    Average response time – 1456 ms
•    Min response time – 153 ms
•    Max response time – 3327 ms
•    Throughput – 139 req/sec
/connect/token (POST) endpoint (750 simultaneous requests issued for 1 second)
•    Average response time – 2379 ms
•    Min response time – 349 ms
•    Max response time – 4936 ms
•    Throughput – 142 req/sec
/connect/token (POST) endpoint (1000 simultaneous requests issued for 1 second)
•    Average response time – 5432 ms
•    Min response time – 497 ms
•    Max response time – 12501 ms
•    Throughput – 82 req/sec
We noticed that the initial requests are processed extremely adequately, but on half of the test, the requests execution freezes, which reflects on the overall result.
Additionally, we have another service that executes similar operations, using the same containers and the same DB Type, an on the same test the results are:
2 Containers (512 RAM)
(500 simultaneous requests issued for 1 second)
•    Average response time – 145 ms
•    Min response time – 124 ms
•    Max response time – 1199 ms
•    Throughput – 148 req/sec
(1000 simultaneous requests issued for 1 second)
•    Average response time – 155 ms
•    Min response time – 124 ms
•    Max response time – 1450 ms
•    Throughput – 211 req/sec
The case we have is that we need to cover 1000 simultaneous requests in 3 seconds interval or less. We have the extensibility to load balance containers and respectively increase the count of the containers, but the tests show that the results in the case of Identity Server 4 are not satisfying enough.
Are there any specific configurations we need to apply in order to achieve the above mentioned results.
Please advise, your contribution is highly appreciated and needed.

A: Turned out that the most time consuming operation is generating the "refresh token". When we turned off that in the Clients (by removing offline_access), then the delay that was mentioned above disappeared. The Identity Server started to fly by increasing its throughput with 22.5 times in our case. Hope this information is going to help others.