text:
Q: Assign variable read from file in Makefile recipe I am trying to do the following in a Makefile recipe. Get the server container-ip using a python script. Build the command to run within the docker container. Run the command in the docker container.
test:
    SIP=$(shell python ./scripts/script.py get-server-ip)
    CMD="iperf3 -c ${SIP} -p 33445"
    docker exec server ${CMD}

I get this
$ make test
SIP=172.17.0.6
CMD="iperf3 -c  -p 33445"
docker exec server
"docker exec" requires at least 2 arguments.
See 'docker exec --help'.

Usage:  docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
Run a command in a running container
make: *** [test] Error 1

A: I ended up with something like this.
SERVER_IP=$(shell python ./scripts/script.py get-server-ip); \
    SERVER_CMD="iperf3 -s -p ${PORT} -4 --logfile s.out"; \
    CLIENT_CMD="iperf3 -c $${SERVER_IP} -p ${PORT} -t 1000 -4 --logfile c.out"; \
    echo "Server Command: " $${SERVER_CMD}; \
    echo "Client Command: " $${CLIENT_CMD}; \
    docker exec -d server $${SERVER_CMD}; \
    docker exec -d client $${CLIENT_CMD};

This seems to work ok. Would love to hear if there are other ways of doing this.

A: You could write something like this. Here I used a target-specific variable assuming
the IP address is required only in this rule. iperf_command is defined as a variable
as the format looks rather fixed except the IP address which is injected by call function.
Also, as the rule doesn't seem to be supposed to produce the target as a file, I put .PHONY target as well.
iperf_command = iperf3 -c $1 -p 33445

.PHONY: test
test: iperf_server_ip = $(shell python ./scripts/script.py get-server-ip)
test:
    docker exec server $(call iperf_command,$(iperf_server_ip))


text:
Q: Error building 32-bit OS X app? I'm working on my first Mac OS X app. My project was set-up with XCode defaults and I haven't touched any Build Settings. When building for Mac 64-bit, the app runs fine. However, when building for Mac 32-bit, I get a seemingly arbitrary error that says:
Semantic issue: Synthesized property 'myProperty' must either be named the same as a compatible ivar or must explicitly name an ivar.
What kind of things can I check for?

A: It sounds like you have found the error but I think I can answer your question just in case someone else later finds it.
Apple has made a lot of changes in the 64 bit Objective-C runtime which they couldn't do before since it would break binary compatibility. One of the things that is different is that in the 32 bit runtime synthesized properties have to be backed by instance variables. On the 64-bit runtime synthesized properties sill needs that but they are created automatically for you. By default the name of the instance variable should be the same as the name of the property.
So in case you need to support 32 bit then make sure that you create instance variables for all your properties. If you only support 64 bit then you can still do that so that your code can be built for both 32 bit and 64 bit at the same time but you don't have to.

A: You can set the NS_BUILD_32_LIKE_64 preprocessor macro in Xcode for the the 32bit build target. This will save you the trouble of maintaining separate code for 32bit and 64bit versions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the best way to draw skinnable "buttons" in a video game? I'm looking for ideas on how to draw a skinnable "button" in a game application. If I use a fixed sprite non-vector image for the button background, then I can't size the button easily. If I write code to draw a resizable button (like Windows buttons are drawn), then the programmer has to get involved -- and it makes skinning difficult. Another option is to break the button into 9 smaller images (3x3) and stretch them all -- kindof like rounded corners are done in HTML.
Is there another "easier" way? What's the best approach?

A: If you really want to accomplish this, the way to do it is with texture coordinates.  Much like you would make a stretchable button/panel design in HTML with a table, you simply define the UV coordinates for the corners, the top stretchable area, the bottom stretchable area, the side stretchable areas, and then the middle.
For an example of this being implemented in an XNA engine (though it's a closed source engine), see this:
http://www.flatredball.com/frb/docs/index.php?title=SpriteFrame_Tutorial

A: Yes. I am working on an Editor. It's a XAML-like language (or OpenLaszlo-like, if you prefer) for XNA. So the buttons can be resized by the editor. The buttons might also be resized by a style sheet.
I guess you're right that it's likely that the buttons will all be the same size in a real design. But even in a window's app, you sometimes need to make a button wider to accomodate text.

A: It should be possible with shaders. You would probably have to do texel lookups, but it would cut down on the number of triangles in a complex UI.


text:
Q: CANNOT receive iCloud calendar on Evolution I was trying to set up iCloud Calendar on Evolution (3.28.5-0ubuntu0.18.04.1).
After everything settled, I found that I could not RECEIVE the calendar online, which says:

The calendar backend servicing "Personal" encountered an error.
  The reported error was "Failed to read resource: HTTP error code 404 (Not Found)".

Error Report Image
However, when I add a new appointment in the Evolution, the appointment will also appeared on iCloud Calendar or masOS Calendar.
Therefore, I suppose my settings are correct because the pushing service works pretty well.
Is there anyone encountered this problem before? I am a newbie in Ubuntu, the Calendar function works perfect on Evolution in Manjaro, and the settings are all the same.
I have already read the posts on Ask Ubuntu, but no one has post questions like this.
The settings are as followings:
Find Calendars Shows Calendar List
Choose Calendar from Find Calendars and get URL


text:
Q: Residue theorem for rational function with high degree denominator $$\int\limits_0^\infty \frac{x^2dx}{(x^4+4)^2} $$
In my complex analysis class problem list I have this integral, it's supposed to be solved by residue theorem. My first attempt was to apply it directly, but calculations in poles were too bad. Then I tried to use substitute, but failed. Looks like it's impossible to make this function a sum of elementary fractions.
So currently I'm looking for a proper substitute or a trick which would let me to use residue theorem without troubles,thanks.

A: Consider the similar integral
$$I=\int_0^\infty \frac{x^2}{(x^4+1)^2}dx$$
Under the variable interchange $x\leftrightarrow\frac{1}{x}$ we get
$$I = \int_0^\infty\frac{x^4}{(x^4+1)^2}dx = \int_0^\infty \frac{1}{x^4+1}-\frac{1}{(x^4+1)^2}dx$$
It is easier to apply residue theorem to the simple pole and the order two pole with a trivial numerator. Can you think of how to apply this to your integral?


text:
Q: TypeScript curious error with generics and inheritance. What's wrong? I am trying to build some base classes for my current project. Currenty I am getting this compiler error:
Type 'IConcreteScope' does not satisfy the constraint 'IEntityScope' for type parameter 'TScope extends IEntityScope'.
When I try to run this code:
// scope
export interface IScope {
    context: any;
}
export class ContextBase<TScope extends IScope> {
    scope: TScope;
}
// entity
export interface IEntity {
    id: string;
}
export interface IEntityScope<TEntity extends IEntity> extends IScope {
    entity: TEntity;
}
export class EntityContextBase<TEntity extends IEntity, TScope extends IEntityScope<TEntity>> {
    operation(entity: TEntity) {...}
}
// concrete
export interface IConcreteEntity extends IEntity {
    name: string;
}
export interface IConcreteScope extends IEntityScope<IConcreteEntity> {
    someprop: boolean;
}
// this is the problem: EntityContextBase<IConcreteEntity,IConcreteScope>
export class ConcretContext extends EntityContextBase<IConcreteEntity,IConcreteScope> {

}

Here the link to the TypeScript playground code
What am I doing wrong?

A: The code is fine; it's a bug in the compiler. This compiles without error in the latest sources from the develop branch.


text:
Q: Right align text in an image with imagettftext(), PHP I am setting up dynamic forum signature images for my users and I want to be able to put their username on the image.  I am able to do this just fine, but since usernames are different lengths and I want to right align the username, how can I go about doing this when I have to set x & y coordinates.
$im = imagecreatefromjpeg("/path/to/base/image.jpg");
$text = "Username";
$font = "Font.ttf";
$black = imagecolorallocate($im, 0, 0, 0);

imagettftext($im, 10, 0, 217, 15, $black, $font, $text);
imagejpeg($im, null, 90);

A: You can use stil/gd-text class. Disclaimer: I am the author.
<?php
use GDText\Box;
use GDText\Color;

$im = imagecreatefromjpeg("/path/to/base/image.jpg");

$textbox = new Box($im);
$textbox->setFontSize(12);
$textbox->setFontFace("Font.ttf");
$textbox->setFontColor(new Color(0, 0, 0)); // black
$textbox->setBox(
    50,  // distance from left edge
    50,  // distance from top edge
    200, // textbox width
    100  // textbox height
);

// text will be aligned inside textbox to right horizontally and to top vertically
$textbox->setTextAlign('right', 'top');

$textbox->draw("Username");

You can also draw multilined text. Just use \n in the string passed to draw() method.
Example generated with this class:

A: Use the imagettfbbox function to get the width of the string and then subtract that from the width of the image to get the starting x-coordinate.
$dimensions = imagettfbbox($fontSize, $angle, $font, $text);
$textWidth = abs($dimensions[4] - $dimensions[0]);
$x = imagesx($im) - $textWidth;

A: Pre-calculate the size of the user's name using imagettfbbox().
From the width you get from there, you can then deduct the x position at which your text needs to start.

A: This will work...............
                  $s = split("[\n]+", $text);
                  $top=20;
                  $left=30;
                  $font_file="yourfont.ttf";
                  $fontsize=20;
               $__H=$top;
               foreach($s as $key=>$val){
                    $_b = imageTTFBbox($fontsize,0,$font_file,$val);
                    $_W = abs($_b[2]-$_b[0]);
                    $_X = ($left+$text_box_width)-$_W;
                    $_H = abs($_b[5]-$_b[3]);
                    $_H +=1;
                    $__H += $_H;
                    $res=imagettftext($image, $this->_fontsize, 0, $_X, $__H, $color, $font_file, $val);
                    $__H += 1;

A: I enhanced sujithayur code, and created function which allows all aligns (left, center, right) & (top, center, middle) and its combinations. It also uses text shadow.
// $x is margin from left, in case of left align, and margin from right, in case of right horizontal align
// $alignHorizontal values can be 'left', 'center', 'right'
// $alignVertical values can be 'top', 'center', 'bottom'
function imagettftext_aligned($image, $fontSize, $x, $y, $color, $colorShadow, $fontPath, $text, $alignHorizontal, $alignVertical) {

      $s = explode("\n", $text);
      $imageWidth = imagesx($image);
      $imageHeight = imagesy($image);

      $top=$y;
      $left=$imageWidth - $x;
      $__H=$top; // default - top
      $lineHeight = $fontSize + 14;

      if ($alignVertical == 'bottom')
        $__H = $imageHeight - $y - (count($s) * $lineHeight);
      elseif ($alignVertical == 'center')
        $__H = $imageHeight/2 - (count($s) * $lineHeight)/2;

      foreach($s as $key=>$val){
            $_b = imageTTFBbox($fontSize,0,$fontPath,$val);
            $_W = abs($_b[2]-$_b[0]);
            $_H = abs($_b[5]-$_b[3]);
            $_H +=1;

            if ($alignHorizontal == 'right')
              $_X = $left - $_W;
            elseif ($alignHorizontal == 'center')
              $_X = $imageWidth/2 - $_W/2;
            else // default - left
              $_X = $x;

            imagettftextblur($image, $fontSize, 0, $_X + 2, $__H + 2, $colorShadow, $fontPath, $val, 4); // 1 can be higher to increase blurriness of the shadow
            imagettftextblur($image, $fontSize, 0, $_X, $__H, $color, $fontPath, $val);

            $__H += $lineHeight + 1;
       }

  return ['bottom' => $__H];

}

// https://github.com/andrewgjohnson/imagettftextblur
if (!function_exists('imagettftextblur'))
{
    function imagettftextblur(&$image,$size,$angle,$x,$y,$color,$fontfile,$text,$blur_intensity = null)
    {
        $blur_intensity = !is_null($blur_intensity) && is_numeric($blur_intensity) ? (int)$blur_intensity : 0;
        if ($blur_intensity > 0)
        {
            $text_shadow_image = imagecreatetruecolor(imagesx($image),imagesy($image));
            imagefill($text_shadow_image,0,0,imagecolorallocate($text_shadow_image,0x00,0x00,0x00));
            imagettftext($text_shadow_image,$size,$angle,$x,$y,imagecolorallocate($text_shadow_image,0xFF,0xFF,0xFF),$fontfile,$text);
            for ($blur = 1;$blur <= $blur_intensity;$blur++)
                imagefilter($text_shadow_image,IMG_FILTER_GAUSSIAN_BLUR);
            for ($x_offset = 0;$x_offset < imagesx($text_shadow_image);$x_offset++)
            {
                for ($y_offset = 0;$y_offset < imagesy($text_shadow_image);$y_offset++)
                {
                    $visibility = (imagecolorat($text_shadow_image,$x_offset,$y_offset) & 0xFF) / 255;
                    if ($visibility > 0)
                        imagesetpixel($image,$x_offset,$y_offset,imagecolorallocatealpha($image,($color >> 16) & 0xFF,($color >> 8) & 0xFF,$color & 0xFF,(1 - $visibility) * 127));
                }
            }
            imagedestroy($text_shadow_image);
        }
        else
            return imagettftext($image,$size,$angle,$x,$y,$color,$fontfile,$text);
    }
}


text:
Q: AtD ruby library - Unexpected response code from AtD service: 503 Service Temporarily Unavailable I am using a relatively recent Ruby library within my Rails (3.2) app which integrates the "After The Deadline" API. The library has two methods that I am passing within the "create" action of a controller which call on the AtD API:
AfterTheDeadline.stats(@table.textcolumn)
AfterTheDeadline.check(@table.textcolumn)

It ends up being the case that when you pass these two calls in rapid succession, the AtD API has some sort of rate limit (which I didn't know about), yielding the following error:
Unexpected response code from AtD service: 503 Service Temporarily Unavailable

Anyway, I'm asking this question in order to answer immediately in case anyone has the same problem in the future...

A: With the kind help of the Gem author, the solution to the problem (some sort of rate limit set inconspicuously by the AtD service) is to add sleep(1) before the check call.


text:
Q: PHP Rector - Look at "Rector\NodeTypeResolver\NodeTypeResolver::isObjectType()" on line 129 I'm trying to run PHP Rector on a very old codebase to convert mysql_* calls into mysqli_* calls however it keeps failing with the following error:
In NodeTypeResolver.php line 129:

  Look at "Rector\NodeTypeResolver\NodeTypeResolver::isObjectType()" on line 129

When I look at the NodeTypeResolver.php line 129 file it's throwing an exception:
        if ($node instanceof \PhpParser\Node\Expr\ClassConstFetch) {
            throw new \Rector\Core\Exception\ShouldNotHappenException();
        }

Looking at the ShouldNotHappenException.php file it gives me no information at to what the possible problem could be. The name of the error message itself seems very cryptic.
My config is pretty basic as I'm only testing this at the moment to see if its viable:
return static function (ContainerConfigurator $containerConfigurator): void {
    // get parameters
    $parameters = $containerConfigurator->parameters();

    // Define what rule sets will be applied
    $containerConfigurator->import(SetList::MYSQL_TO_MYSQLI);

    // get services (needed for register a single rule)
    //$services = $containerConfigurator->services();

    // register a single rule
    //$services->set(TypedPropertyRector::class);
};

Does anyone have an idea of what's going on?

EDIT:
I should probably mention I tried a few different configs to run different things like $containerConfigurator->import(SetList::DEAD_CODE); and $containerConfigurator->import(SetList::CODE_QUALITY); and they run fine so it seems to a specific issue with SetList::MYSQL_TO_MYSQLI


text:
Q: Sudomain automatically redirect to https I'm having HTTPS with my main domain ie https://example.com.
And I want to use subdomain without HTTPS ie, http://hello.example.com but the problem is it automatically redirects to HTTPS. How do I avoid that?
This is my current .htaccess structure:

        Options -MultiViews

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

A: You can make this with a Middleware.
For example:
namespace App\Http\Middleware;
use Closure;
class HttpsProtocol {
    public function handle($request, Closure $next)
    {
            if (!$request->secure() && env('APP_ENV') === 'prod' AND [your chek url without subdomain]) {
                return redirect()->secure($request->getRequestUri()); //with https
            }

            return $next($request);
    }
}

Change [your chek url without subdomain]
And adding setting the rule at Kernel.php:
protected $middleware = [
    ...........

    // append HTTPS middleware
    'App\Http\Middleware\HttpsProtocol'

];

A: UPDATE
Alternatively, You can add this code : (I think It's better one)
RewriteCond %{HTTP_HOST} ^example\.com [NC]

Replace example with your domain name and Add this code after line 9
RewriteCond %{HTTP_HOST} !^([a-zA-Z0-9\-]+)\.example\.com


text:
Q: Multiple calls to sigtrap handler not working I have a small application written in C for Linux on ARM which sets up a signal handler for the SIGTRAP signal and is supposed to catch the bkpt instruction (via the TRAP_HWBKPT code) and effectively skip it.
The handler simply notifies from where the breakpoint was raised and uses an inline epilogue to to redirect codeflow to 4 bytes (due to ARM's RISC architecture) after the breakpoint address (which is the next instruction). I know there should still be some register saving but that's not the problem for now.
What seems to happen is that the first call to a breakpoint-containing function goes fine but the second call doesn't get caught by the custom sigtrap_handler anymore and is passed to the default handler instead (causing the process to terminate):
Does anyone know why this happens and how to fix this so i can achieve the goal of calling the handler for every bkpt instruction and continuing execution as normal?
$ gcc -o break break.c
$ ./break
START
ENTER [0]!
SIGTRAP at 0x856c
EXIT [0]!
ENTER [1]!
Trace/breakpoint trap

This is the code in question:
#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#ifndef TRAP_BRANCH
    #define TRAP_BRANCH 3
#endif

#ifndef TRAP_HWBKPT
    #define TRAP_HWBKPT 4
#endif

static void sigtrap_handler(int sig, siginfo_t* siginfo, void* ptr)
{
    switch(siginfo->si_code)
    {
        case TRAP_HWBKPT:
        {
            printf("SIGTRAP at %p\n", (void*)siginfo->si_addr);

            asm volatile("sub sp, r11, #4\n\t"
                         "pop {r11}\n\t"
                         "sub sp, #4\n\t"
                         "mov pc, %0"
                         :
                         : "r" (siginfo->si_addr + 4) // Proceed to instruction directly after breakpoint
                        );
        }break;

        // misc. SIGTRAP codes (fallthrough)
        case TRAP_BRKPT:
        case TRAP_TRACE:
        case TRAP_BRANCH:
        default:
        {
            exit(-1);
        }break;
    }
}

void dummy_routine(int n)
{
    printf("ENTER [%d]!\n", n);

    // Breakpoint
    asm volatile("bkpt");

    printf("EXIT [%d]!\n", n);
    return;
}

int main (int argc, char *argv[])
{
    int i;
    struct sigaction act;

    // Set up sigtrap handler
    memset (&act, 0, sizeof(act));
    act.sa_sigaction = sigtrap_handler;
    act.sa_flags = SA_SIGINFO;

    if (sigaction(SIGTRAP, &act, 0)) {
        perror("Error: sigaction");
        return 1;
    }

    printf("START\n");

    // Trigger routine containing breakpoint multiple times
    for(i = 0; i < 2; i++)
    {
        dummy_routine(i);
    }

    printf("END\n");

    return 0;
}


text:
Q: How to add background color with my this code in php image create from text to image? <?php

    function create_image($user)
    {

        global $img_source; global $render_folder;
        global $id; global $folder;
        $quality = 9;
        $im = imagecreatefrompng($img_source);
        $clr="";
        foreach ($user as $value)
        {

            if(!empty($_SESSION['img_name']))
            {
                $im = imagecreatefrompng($_SESSION['img_name']);
            }
            $img_width=imagesx($im);
            list($r, $g, $b) = sscanf($value['color'], "#%02x%02x%02x");
            $clr=imagecolorallocate($im, $r, $g, $b);

            $text_a = explode(' ', $value['name']);
            $text_new = ''; $width = $value['box-width']; $linex=1;
            foreach($text_a as $word)
            {
                //Create a new text, add the word, and calculate the parameters of the text
                $box = imagettfbbox($value['font-size'], 0, $folder.$value['font'], $text_new.' '.$word);
                //if the line fits to the specified width, then add the word with a space, if not then add word with new line
                //echo $box[2]." ";
                if($box[2] > $width){
                    $text_new .= "\n".$word; $linex++;  //echo "
";
                } else {
                    $text_new .= " ".$word;
                }
            }
            $text_new = trim($text_new);

                $linslikh=explode("\n",$text_new); $ff=1;
                foreach($linslikh as $linslikh1)
                {

                    if($value['center']=="Y")
                    {
                        //die();
                $xpos = center_text($linslikh1, $folder.$value['font'], $value['font-size'],$width);
                $xpos+=$value['x'];

                    }
                    else
                    {
                        $xpos = $value['x'];
                    }

                    $acfont = $value['font-size']*$ff ; $ypos = $acfont + $value['y'];

                    $ff=$ff+2;

                    imagettftext($im, $value['font-size'], 0, $xpos, $ypos,$clr, $folder.$value['font'],$linslikh1);

                // create the image

                }

                $output_filename = $id.'_render.png';
                imagepng($im, $render_folder.$output_filename, $quality);
                imagedestroy($im);
                $_SESSION['img_name']=$render_folder.$output_filename;
                $_SESSION['render_name']= $output_filename;

        }

    //die();
    }

    function center_text($string, $font, $font_size, $image_width){
        $dimensions = imagettfbbox($font_size, 0, $font, $string);
        return ceil(($image_width - $dimensions[4]) / 2);
    }

     ?>

Data Input File  Code ( From Where Data Input)

            <input required type="text" value="FF8C66"  class="jscolor form-control input-lg" name="clr[]" onChange="setColor(this.value,<?php echo $row; ?>);" >

            <input required type="text" value="FF8C66"  class="jscolor form-control input-lg" name="Bclr[]" onChange="setBColor(this.value,<?php echo $row; ?>);" >

(Data stored from this file ) Other File Code
$new_array[]=array("name"=>$_POST['text'][$i],
                                "font-size"=>$_POST['font-size'][$i],
                                "color"=>$_POST['clr'][$i],
                                "background-color"=>"#".$_POST['Bclr'][$i],

Above is part of my code from some files . I just want to add background color  option in my image. im able to add option and get data. but unable to add output in my php file which make image from input. Hope you understand my point . please help my how i can add background color from input value to in my php file . Sorry for bad English.
Update : i tried this with this way but no luck
 //
//    other code part
//

    $Bclr="";
        $clr="";
                    foreach ($user as $value)
//
//    other code part
//
    list($r, $g, $b) = sscanf($value['Bcolor'], "#%02x%02x%02x");
                    $Bclr=imagecolorallocate($im, $r, $g, $b);
    //
   // Other Code Part
   //
    imagettftext($im, $value['font-size'], 0, $xpos, $ypos,$clr, $Bclr,$folder.$value['font'],$linslikh1);

A: Create another image with imagecreatetruecolor the same size as your image, allocate backgroung color(rgb), use imagecopyresampled to merge the two images

A: Actually, an easier method is explained in the manual :-
imagecreatetruecolor
imagecolorallocate
then create imagefilledrectangle using the colors from imagecolorallocate,
then write your text to the image.
See example from Php.net below
http://php.net/manual/en/function.imagettfbbox.php


text: Q: ARM internal watchdog reset issue The ARM processor watchdog (or the internal watchdog) - Does the watchdog reset trigger immediately after a watchdog counter counts down to 0. Will there be a delay in resetting the processor.


text:
Q: Scrape data from multiple URLs I have a dataframe of two variables and 49 observations that looks like this:
Link                                  URL
1   20 political parties urge govt... http://www.mmtimes.com/index.php/national-news/27265-20-political-parties-urge-govt-to-act-on-rakhine-issue.html
2   Tens of thousands protest across.. http://www.mmtimes.com/index.php/national-news/27236-tens-of-thousands-protest-across-rakhine-over-security-issues.html

I would like to use scrape byline and article text for the articles and create a data frame like so:
data.frame(title=html_text(html_nodes(pg, ".contentheading")),
       authordate=html_text(html_nodes(pg, ".create")),
       text=html_text(html_nodes(pg, "p")),
       stringsAsFactors=FALSE)

I can get the data for each article using:
read_html(df$URL[1]) %>%
html_nodes(".create") %>%
html_text()

How do I scrape all the data from the URLs using the column from my current data frame (df$URL)?
Update: I am now using the following to try and get the data:
mmtimes_data <- data.frame(title=character(),author=character(),text=character())

for (i in url) {
mmtimes <- read_html(i)
title <- mmtimes %>% html_nodes(".contentheading") %>% html_text() %>%     as.character()
author <- mmtimes %>% html_nodes("created") %>% html_text() %>% as.character()
text <- mmtimes %>% html_nodes("p") %>% html_text() %>% as.character()
temp <- data.frame(title, authordate, text)
mmtimes_data <- rbind(mmtimes_data,temp)
cat("*")
}

However, I receive the following error:
Error in doc_parse_file(con, encoding = encoding, as_html = as_html, options =     options) :
expecting a single value

Update #2
I solved this using the following code:
mmtimes_data <- data.frame(title=character(),author=character(),text=character())

for (i in links) {
mmtimes <- read_html(i)
title <- mmtimes %>% html_nodes(".contentheading") %>% html_text() %>% as.character()
author <- mmtimes %>% html_nodes(".create") %>% html_text() %>% as.character()
text <- mmtimes %>% html_nodes("p") %>% html_text() %>% as.character()
temp <- data.frame(title, author, text)
mmtimes_data <- rbind(mmtimes_data,temp)
cat("*")
}


text:
Q: WebGrid data displayed inside first column In my ASP.NET MVC application, I have a partial view which renders a table.
My problem, in short, is that all the values of all the properties of each object in the WebGrid's data source are displayed inside the first column of the table, instead of a property value per column.  I can see the per-property cell borders within each first column cell which hosts them.
The partial view's model is List<ReportTableEntry> where ReportTableEntry is:
public class ReportTableEntry
{
    public DateTime Time             { get; set; }
    public int      OpenedSessions   { get; set; }
    public int      ClosedSessions   { get; set; }
    public int      SnapshotSessions { get; set; }
    public int      TotalSessions    { get; set; }
}

The view which renders the partial view calls
@Html.Partial("Table", Model.TableEntries)

(here Model refers to the parent view's model rather than the partial view's model), where Model.TableEntries is a List, and within the partial view, the contents of Model seems to be valid when I inspect it.
I've tried every combination I can think of:

*

*I used the parent view's model directly and created the WebGrid with source: Model.TableEntries.

*I tried to use a non-typed model in the partial view.

*I specified the grid's column names, and used default values.

*I tried decorating ReportTableEntry's properties with ColumnAttribute.

*I used grid.Html with and without styles, with and without the columns parameters

*I toggled paging, sorting and added/removed the ajaxUpdateContainerId

Nevertheless, all the ReportTableEntry's property values are crammed inside the first table column.
One thing I noticed is that grid.Columns() returns an empty array.
For the sake of completeness, here's the simplest variation which produces these poor results:
@model List<ReportTableEntry>

@{
    if (Model == null)
    {

No data to show

    }
    else
    {
        var grid = new WebGrid(source:                Model,
                               columnNames:           null,
                               defaultSort:           "",
                               rowsPerPage:           100,
                               canPage:               true,
                               canSort:               false,
                               ajaxUpdateContainerId: "reportDataDiv");

        @grid.GetHtml()
    }
}

What am I missing here?

A: How dumb...  site.css, td element, float: left - and that's what happens.


text:
Q: Operations with BigDecimal and double in Java I am trying to use Advogadro's number (6.022*10^23) in a java program and i use BigDecimal variable to store it. However i want to multiply it with an int or a double and still keep the precision, but it throws an error!
bad operand types for binary operator '*'
  first type:  double
  second type: BigDecimal

Is there any simple way to do that? Also is there a way to print the result in scientific notation?
Thanks in advance!

A: Operations are only supported for primitive types (and + for Strings)
BigDecimals has implemented the operations as functions.
you can only uses BigDecimals for operations with BigDecimals. So you need to convert your double value:
BigDecimal result = new BigDecimal(doubleValue).multiply(factor2);

A: Wrap the double into a BigDecimal first:
BigDecimal result = yourBigDecimal.multiply(new BigDecimal(yourDouble));

A: BigDecimal is not a primitive type. So you really cannot apply simple maths (*,-,+) into that. It has many methods in order to support all the basic mathematics. You can use them. As comment suggest read the java doc (http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html).
What big decimal has is a two main parts. One part contains the number, and the second part precision. So if you want to handle special maths which is not standard available you can get those two values separately and try with higher mathematical algorithms
Quate from java doc :

21/110 = 0.190 // integer=190, scale=3

A: Do sthg like this;
 public class Payment
 {
     BigDecimal itemCost;
     BigDecimal totalCost; // You can initialize it if you wish.

     public BigDecimal calculateCost(int itemQuantity, BigDecimal itemPrice)
     {
         itemCost  = itemPrice.multiply(new BigDecimal(itemQuantity));
         totalCost = totalCost.add(itemCost);
         return totalCost;
     }
 }

And read javadoc for BigDecimal.

A: Warning: Unpredictability of the BigDecimal(double) constructor
new Bigdecimal(myDouble) is wrong.
You have to use Bigdecimal.valueOf(myDouble) instead.

A: BigDecimal multi = BigDecimal.valueOf(doubleValue).multiply(bigDecimal)

A: Multiply would be right..
To do (<, ==, >, >=, !=, <=) operations, you can use compareTo of BigDecimal..
resulting in 0,1,-1.
I hope this too helps.. ;)


text:
Q: Firebase 3 database debug output when connecting from node.js SDKerv Recently upgrading to run the firebase 3 sdk both in the client, in e2e tests and on the server.
Previously when using the firebase 2.x sdk you could connect to firebase in the same was as a client using signInWithCustomToken. This meant I could generate a token with the {debug: true} flag and use this for my mocha tests. Meaning I would get verbose output from firebase in the invent of security rejection.
Firebase 3 does not allow you to use client types of auth when running the sdk from node (i.e mocha). You must use service accounts. I have created the service account and have serviceaccount.json. I can connect and spoof the UID by using databaseAuthVariableOverride and everything is running AOK but I cannot figure out how to get firebase to send verbose database output so I can debug new firebase rules from my tests.
I have tried things like adding "Log Viewer" permission to my service account. I have also tried (in vein) to add debug: true to the serviceaccount.json
Any help appreciated.

A: Have you tried the following (in Node.js):
firebase.database.enableLogging(true);


text:
Q: MongoDB aggregation group by month in big collection - optimize pipeline I'm aware that this question has been asked before at SO - but I can't seem to find how to handle aggregation grouping in bigger collections. I have a set of +10 million records, and I just can't get any speed to it.
Running MongoDB v 3.2.
Having a field __createDateUtc (ISODate) in the schema, I'm trying the following pipeline:
db.transactions.aggregate([
    {
        $project: {
            __createDateUtc: 1
        }
    },
    {
        $group: {
            '_id': { $year: '$__createDateUtc' },
            'count': {$sum: 1},
        }
    },
    {
        $limit: 10
    },
])

This runs at +20 seconds. Could it be made faster? This is a fairly simple pipeline - so really - is there any other strategy that might help in this situation?

A: I did some bench marking with four different ways of getting the results that I wanted. The results are a discouraging.
Again, with a schema looking like:
{
    "_id" : ObjectId("5d665491fd5852755236a5dc"),
    ...
    "__createDateUtc" : ISODate("2019-08-28T10:16:49Z"),
    "__createDate" : {
        "year" : 2019,
        "month" : 8,
        "day" : 28,
        "yearMonth" : 201908,
        "yearMonthDay" : 20190829
    }
}

The results:
// Group by __createDate.yearMonth
db.transactions.aggregate([
    { $group: {
        '_id': '$__createDate.yearMonth',
        'count': {$sum: 1},
    } },
    { $limit: 10 },
    { $sort: {'_id': -1 } }
])
// 20 169 ms

// Group by year and month
db.transactions.aggregate([
    {$group: {
            '_id': {year: '$__createDate.year', month: '$__createDate.month' },
            'count': {$sum: 1},
    }},
    { $limit: 10 },
    { $sort: {'_id': -1 } }
])
// 23 777 ms

// Group by calculating year and month from ISODate
db.transactions.aggregate([
    {$group: {
            '_id': {year: { $year: '$__createDateUtc' }, month: { $month: '$__createDateUtc' } },
            'count': {$sum: 1},
    }},
    { $limit: 10 },
    { $sort: {'_id': -1 } }
])
// 16 444 ms

// Last stupid method to just run many queries with count
var years = [2017, 2018, 2019];
var results = {}
years.forEach(year => {
    results[year] = {};
    for(var i = 1; i < 13; i++) {
        var count = db.transactions.find({'__createDate.year': year, '__createDate.month': i}).count();
        if(count > 0) results[year][i] = count;
    }
})
// 10 701 ms

As you can see the last method of just running multiple counts is by far the fastest. Especially since I'm actually fetching a lot more data compared to the three other methods.
This just seems stupid to me. I know MongoDB is no search engine, but still. Aggregation is just not fast at all. Makes me wanna sync data to elastic search and try to aggregate within ES instead.


text:
Q: How to get the Blob image preview in my Uppy Custom setup I learn React and now I use the Uppy so user can select files for upload.
When user have select his file the files are hidden by settting showSelectedFiles={false}
I use my own Component to show the selected files and I get the files using this:
  .on("file-added", (file) => {
    const { setFile } = props;
    setFile(file);
    const newList = this.state.files.concat({ file });
    this.setState({
      files: { newList },
    });
  });

For each file added to the Dashboard the setFile(file); is sending the file object to my Custom view. The problem is that the preview image Blob that is auto created by the Dashboard is not present at this stage.

How can I get the files to my Custom GUI to show them including the image preview Blob?
I'm new to React and JavaScript so please be gentle:)
Complete code:
import React from "react";

import "@uppy/status-bar/dist/style.css";
import "@uppy/drag-drop/dist/style.css";
import "@uppy/progress-bar/dist/style.css";
import "./styles.css";
import "@uppy/core/dist/style.css";
import "@uppy/dashboard/dist/style.css";

const Uppy = require("@uppy/core");
// const Dashboard = require("@uppy/dashboard");
const GoogleDrive = require("@uppy/google-drive");
const Dropbox = require("@uppy/dropbox");
const Instagram = require("@uppy/instagram");
const Webcam = require("@uppy/webcam");
const Tus = require("@uppy/tus");
const ThumbnailGenerator = require("@uppy/thumbnail-generator");

const {
  Dashboard,
  DashboardModal,
  DragDrop,
  ProgressBar,
} = require("@uppy/react");

class DashboardUppy extends React.Component {
  constructor(props) {
    super(props);
    this.form = React.createRef();
    this.state = {
      showInlineDashboard: false,
      open: false,
      files: [],
    };

    this.uppy = new Uppy({
      id: "uppy1",
      autoProceed: false,
      debug: true,
      allowMultipleUploads: true,
      proudlyDisplayPoweredByUppy: true,
      restrictions: {
        // maxFileSize: 1000000,
        maxNumberOfFiles: 100,
        minNumberOfFiles: 1,
        allowedFileTypes: null,
      },
      onBeforeFileAdded: (currentFile, files) => {
        console.log(files);
        const modifiedFile = Object.assign({}, currentFile, {
          name: currentFile + Date.now(),
        });
        if (!currentFile.type) {
          // log to console
          this.uppy.log(`Skipping file because it has no type`);
          // show error message to the user
          this.uppy.info(`Skipping file because it has no type`, "error", 500);
          return false;
        }
        return modifiedFile;
      },
    })
      .use(Tus, { endpoint: "https://master.tus.io/files/" })
      .use(GoogleDrive, { companionUrl: "https://companion.uppy.io" })
      .use(Dropbox, {
        companionUrl: "https://companion.uppy.io",
      })
      .use(Instagram, {
        companionUrl: "https://companion.uppy.io",
      })
      .use(Webcam, {
        onBeforeSnapshot: () => Promise.resolve(),
        countdown: false,
        modes: ["video-audio", "video-only", "audio-only", "picture"],
        mirror: true,
        facingMode: "user",
        locale: {
          strings: {
            // Shown before a picture is taken when the `countdown` option is set.
            smile: "Smile!",
            // Used as the label for the button that takes a picture.
            // This is not visibly rendered but is picked up by screen readers.
            takePicture: "Take a picture",
            // Used as the label for the button that starts a video recording.
            // This is not visibly rendered but is picked up by screen readers.
            startRecording: "Begin video recording",
            // Used as the label for the button that stops a video recording.
            // This is not visibly rendered but is picked up by screen readers.
            stopRecording: "Stop video recording",
            // Title on the "allow access" screen
            allowAccessTitle: "Please allow access to your camera",
            // Description on the "allow access" screen
            allowAccessDescription:
              "In order to take pictures or record video with your camera, please allow camera access for this site.",
          },
        },
      }).use(ThumbnailGenerator, {
        thumbnailWidth: 200,
        // thumbnailHeight: 200 // optional, use either width or height,
        waitForThumbnailsBeforeUpload: true
      })
      .on("thumbnail:generated", (file, preview) => {
        const img = document.createElement("img");
        img.src = preview;
        img.width = 100;
        document.body.appendChild(img);
      })
      .on("file-added", (file) => {
        const { setFile } = props;
        setFile(file);
        const newList = this.state.files.concat({ file });
        this.setState({
          files: { newList },
        });
      });
  }

  componentWillUnmount() {
    this.uppy.close();
  }

  render() {
    const { files } = this.state;
    this.uppy.on("complete", (result) => {
      console.log(
        "Upload complete! We've uploaded these files:",
        result.successful
      );
    });

    return (

            <Dashboard
              uppy={this.uppy}
              plugins={["GoogleDrive", "Webcam", "Dropbox", "Instagram"]}
              metaFields={[
                { id: "name", name: "Name", placeholder: "File name" },
              ]}
              open={this.state.open}
              target={document.body}
              onRequestClose={() => this.setState({ open: false })}
              showSelectedFiles={false}
            />

    );
  }
}

export default DashboardUppy;

A: Ran into this problem as well because I wanted to use the image preview to figure out the aspect ratio of the underlying image.
If you're using Dashboard or ThumbnailGenerator for Uppy, an event is emitted for every upload:
uppy.on('thumbnail:generated', (file, preview) => {
  const img = new Image();
  img.src = preview;
  img.onload = () => {
    const aspect_ratio = img.width / img.height;
    // Remove image if the aspect ratio is too weird.
    // TODO: notify user.
    if (aspect_ratio > 1.8) {
      uppy.removeFile(file.id);
    }
  }
});

I realize though that you already are looking for this event in your code. I guess to answer your question, just put your logic there instead of in file-added.


text:
Q: php creates folder with 341 permissions Didn't got any luck finding an answer on google , so this is my last try before trying other methods.
I have a script like this:
        // get current year and month
        $cur_year = date('Y');
        $cur_month = date('m');
        $long_type = $this->getFile_longtype();

        $folder = $_SERVER['DOCUMENT_ROOT']."/".FOLDER_CMS."/uploads/$long_type/$cur_year/$cur_month";

        // check whether the folder exists
        if(!is_dir($folder)){

            // try to make the folder recursively
            if(!mkdir($folder,"0777",true)){

                logError($message, __FILE__, __LINE__);
                throw new Exception("Failure creating proper directories");

            }

        }

to make it work , I chmod'ed the uploads directory and all it's files and dirs to 777 ( beter suggestion here? )
The long type evaluates to 'images' and this is a directory has already been created on the server.
Now , the script create the folder named with year with the permissions 341. This not wat I want because it terminates the recursive folder buildup or blocks it's content from me.
Any help or suggestions?
php version : 5.2.5
configure command : './configure' '--enable-bcmath' '--enable-calendar' '--enable-exif' '--enable-ftp' '--enable-gd-native-ttf' '--enable-libxml' '--enable-magic-quotes' '--enable-mbstring' '--enable-pdo=shared' '--enable-soap' '--enable-sockets' '--enable-wddx' '--enable-zip' '--prefix=/usr/local' '--with-apxs2=/usr/local/apache/bin/apxs' '--with-bz2' '--with-curl=/opt/curlssl/' '--with-curlwrappers' '--with-freetype-dir=/usr' '--with-gd' '--with-gettext' '--with-imap=/opt/php_with_imap_client/' '--with-imap-ssl=/usr' '--with-jpeg-dir=/usr' '--with-kerberos' '--with-libexpat-dir=/usr' '--with-libxml-dir=/opt/xml2' '--with-libxml-dir=/opt/xml2/' '--with-mcrypt=/opt/libmcrypt/' '--with-mhash=/opt/mhash/' '--with-mssql=/usr/local/freetds' '--with-mysql=/usr' '--with-mysql-sock=/var/lib/mysql/mysql.sock' '--with-mysqli=/usr/bin/mysql_config' '--with-openssl=/usr' '--with-openssl-dir=/usr' '--with-pdo-mysql=shared' '--with-pdo-sqlite=shared' '--with-png-dir=/usr' '--with-pspell' '--with-sqlite=shared' '--with-tidy=/opt/tidy/' '--with-ttf' '--with-xmlrpc' '--with-xpm-dir=/usr' '--with-xsl=/opt/xslt/' '--with-zlib' '--with-zlib-dir=/usr'

A: Don't use the string "0777", use 0777.

A: As mentioned by Alex, you suppose to enter OCTAL value not a STRING also, for security reasons never give full permission to folders use 0755 instead.

A: The real permissions depend on the parameter to mkdir and the umask. The umask is subtracted from the permissions given to mkdir. Try setting your umask to 0 before doing the mkdir.

A: I have also just encountered this issue where PHP sets the permissions to 1314, despite mkdir being set to 0755. This issue was that the folders that were being created were under a parent folder with the permissions 0700. When I changed the permissions with mkdir to 0700 it created the folders with the correct permissions. So it seems (quite logically) you cannot permission a child folder with greater permissions than it's parent.
In your case, a parent folder was probably set to 0755 and you were attempting to create a child with 0777.


text:
Q: Interactive map android v2 I want to build an interactive Android map app. It will have different marker types and lots of of different options when clicking on them.
First approach :
I started with the notion I will use custom infowindows but figured out that a map can have only single InfoWindowAdapter, with that said, this approach has another fault. InfoWindows can't have click listeners registered to them and I need to have some clickable UI to show after marker click.
Second approach :
Marker click triggers an alertDialog which corresponds to the marker type. I'm hesitant because I'll have lots of switch case inside the OnActivityResult.
Example - dialog fragments with OnActivityResult
Any other ideas ? Am I missing something ?

A: I ran into similar problem some time ago and I "hacked" it as follows:
mGoogleMap.setInfoWindowAdapter(new InfoWindowAdapter() {
    @Override
    public View getInfoWindow(Marker pMarker) {
        MarkerDescriptor descriptor = mMarkerDescriptorsMap.get(pMarker);
        mGoogleMap.setOnInfoWindowClickListener(descriptor.getOnInfoWindowClickListener(MapActivity.this));
        return descriptor.getInfoWindowView();
    }
}

MarkerDescriptor should be simple interface that will be implemented for each specific marker type:
public interface MarkerDescriptor {
    public View getInfoWindowView();
    public OnInfoWindowClickListener getOnInfoWindowClickListener(Context pContext);
}

And to keep the references:
private Map<Marker, MarkerDescriptor> mMarkerDescriptorsMap = new HashMap<Marker, MarkerDescriptor>();

Basics of this idea is that GoogleMap can have only one marker selected at the time, so when user chooses another marker, we change the listeners.


text:
Q: Minimum iOS Version 5.0 & The App Store We're talking about making the minimum iOS version of our consumer facing app 5.0+.  We have a few questions, and I was unable to find a great resource for the answers:

*

*For existing users with 4.xx, when the next update is released, will they just not see the update in the App Store?  IE, until they update their iOS version to our new minimum version, they will never see the most recent update and will be "stuck" on the previous version?

*For new customers with 4.xx, when they search for our app on the App Store, will it show up in search results?  If so, what will be displayed when they click Install ?

Thank you for your help.  I found lots of information on specifically 3.xx to 4.xx, but wanted to get a more detailed explanation for the scenarios explained above.  If there is Apple developer documentation for this, please point me in the right direction.:)
Thanks!

A: The App store on the device will filter out apps and updates that are inappropriate for the current iOS device OS version.  The user won't see them (or if they see them on some devices, won't be able to download or install them).
However, the iTunes App Store on the customer's Mac or PC will not filter by OS version.  iTunes will download apps that the user can't install on their devices running older iOS versions, and, far worse, will put any working app versions in the trash after downloading their useless updates.

A: Yes.
If you specify the deployment target for your app as iOS 5.x, your customers running iOS 4.x won't see an update on the app store and will be stuck at the previous versions of your app.
New customers running iOS 4.x will be able to see the app but won't be able to install it. They'll get a system error message that iOS 5 is required to install this app.
Hope that helps.

A: The App store does not filter apps based on the operating system of your device. It will show iOS 5 apps even if your device is iOS 4. The update will definitely appear in iTunes. I don't know about whether it shows up in the updates in the app itself.


text:
Q: jQuery live sibling-selector not working I have this CSS selector, which just won't bind .live(), but works perfectly with .bind():
$('.treeView li ~ :has("ul")').prev('li')
I've read somewhere, that using the .prev() and .next() could be troublesome coupled with .live(), so I wanted to create an pure CSS selector (or ANYTHING that works with .live()!) to do the job - but I just can't figure it out!
Here's what I want to do:
Select all li-elements, which is followed by an li containing an ul.
Here's an HTML markup example, I want to select the ones where the comment says "selected"

Ostetanke
    //selected

Tank 1

Tank 2

Presse
    //selected

Sub-leaf 1

Sub-leaf 2
    //selected

test

test

Any help is much appreciated, since this is a bit of a thorn in my eye :(

A: There is no such Selector to accomplish this task.
What I highly recommend you to do is to add ANYTHING as a flag to use when selecting your desired elements.
add attribute, wrapper, ANYTHING YOU WANT, then the task will be as easy as it should be.

A: This may work: // not css selector
$(".treeView li:has('ul')").prev();


text:
Q: IPython deprecation warning when importing display When I run:
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))

I got

/var/folders/6g/6gqq4lhx4jbcl4_tbrsxj3xr0000gq/T/ipykernel_5625/333572366.py:1:
DeprecationWarning: Importing display from IPython.core.display is
deprecated since IPython 7.14, please import from IPython display
from IPython.core.display import display, HTML

A: replace
from IPython.core.display import display, HTML

with
from IPython.display import display, HTML

source here


text:
Q: How to get command prompt output in java? How to get the output of the command prompt which means i have opend a command prompt like this.
Process process = Runtime.getRuntime().exec("cmd /c start cmd.exe /K \"C:\\Editor\\editorTemp.exe\"");

i can not get the cmd output like this
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

So how can i get the command prompt output ?

A: This is not Java question. Basically what you doing is running Java (Java Main Process A) and from it starting another process (Windows CMD B). This is fine and you can get input/output streams of this process (B) in Java(A).
However this process (B) starts another process (again Windows CMD C) with its own standard input/output. This process has nothing common with processes A&B and uses Windows' standard Input/Output streams. So, there are no connections between A and C.
I'm not sure but I think there are some ways to run Windows CMD with different or not standard IO. Maybe something like this will work:
cmd <tty >tty

but there is no tty in Windows. Pragmatically you can do this as described here - Creating a Child Process with Redirected Input and Output but that would not work for regular CMD.
Nevertheless it became even more problematic when you start your own process from the editorTemp.exe (process D). D has even more disconnection with process A. And all for what? What don't you simply start process D directly from A and have full control on the IO streams and process itself?
Here is good example how to do so.

A: Your java thread is working independently of CMD call. The java code is beating the STDOUT pipe before anything is written.
If you call Process.waitFor(), it will wait until the CMD call is done. The STDOUT should be in the buffer, and then you can read it.

A: When you do a readLine(), your java thread is blocked until you have an actual full line or the input stream is closed.
If the program prints a partial line (without CR or LF at the end), and then waits for input, the readLine will be stuck.
So you will need to read character by character, until you think the proces has no more things to say.
See e.g. Is it possible to read from a InputStream with a timeout?

A: import java.util.Scanner;

Inside the main write this.
Scanner output = new Scanner(System.in);

System.out.println("Enter your name");
String name = output.next();

If you want user to enter an int then you need to do this.
int number = output.nextInt();


text:
Q: JavaFx cannot cast text to textField and cannot cast textField to text? I am trying to do an application for my Java class. Mainly we are learning out to use github, but my problem came with JavaFX. I am suppose to create a form on several panes and Scenes, and right at the last one when the user hits submit the TextFields content should be placed inside a file.
My idea to achieve this was to pass the textfields into the last pane has a parameter and create a bufferedwriter once the submit button is pressed, adding all the text into a new file. so the idea was working perfect, I passed a Pane since all the textFields are inside one VBox and when I write them I cast them has textFields, but when I run it tells me that text cannot be cast to textfield, so when I try to cast to text instead, it would tell me the opposite! that textfield cannot be cast to text! I tried the buffer using the textArea inside the code and it worked fine! I don't understand why is not working with the pane im passing
Note: right at the end I tried concatenating to a string see if the buffer was the problem, but it tells me the same error even doing it this way
this is the code:
    public class RulesPane extends VBox{
    public RulesPane(Stage mainStage, Scene mainScene, Pane pane) {
        this.setAlignment(Pos.TOP_CENTER);

        BackgroundImage background = new BackgroundImage(new Image("water.png",900,600,false,true),
                BackgroundRepeat.REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT,
                  BackgroundSize.DEFAULT);
        this.setBackground(new Background(background));

        File logoPath = new File("src/swimclub_Logo.png");
        Image logoImage = new Image(logoPath.toURI().toString());
        ImageView logo = new ImageView(logoImage);

        TextArea agreement = new TextArea();
        agreement.setEditable(false);
        agreement.setPrefHeight(400);
        agreement.setMaxWidth(600);
        agreement.setWrapText(true);
        agreement.setText("This is text");

        CheckBox agree = new CheckBox("I Agree");

        HBox buttons = new HBox();
        buttons.setPadding(new Insets(50, 0, 0, 60));
        buttons.setSpacing(300);

        Button back = new Button();
        back.setText("Back");
        back.setOnMouseClicked(e->{
            mainStage.setScene(mainScene);
        });

        Button exit = new Button();
        exit.setText("Exit");
        exit.setOnMouseClicked(e->{
            Platform.exit();
        });

        Button submit = new Button();
        submit.setText("Submit Form");
        submit.setDisable(true);
        submit.setOnMouseClicked(e->{
            File file = new File("user_info.txt");
            try {
                BufferedWriter out = new BufferedWriter(new FileWriter(file));
                String contentToSave = "";
                for(int i = 0; i < pane.getChildren().size(); i++)
                    contentToSave += ( (TextField) pane.getChildren().get(i)).getText();

                out.write(contentToSave);
                out.flush();
                out.close();
            } catch (IOException e1) {

                e1.printStackTrace();
            }
        });

        //CheckBox event handler to make the submit button available or unavailable when pressed
        agree.setOnAction(e->{
            if(agree.isSelected())
                submit.setDisable(false);
            else
                submit.setDisable(true);
        });

        buttons.getChildren().addAll(back, exit, submit);
        this.getChildren().addAll(logo , agreement, agree, buttons);
        }
}

This is where is coming from
 public class registration extends Application{

public static void main(String[] args) {
    Application.launch(args);
}

public void start(Stage primaryStage) throws Exception {
    BorderPane main = new BorderPane();
    VBox questions = new VBox();
    VBox titlePane = new VBox();
    HBox buttonPane = new HBox();

    Text title = new Text("Welcome to the Swimming Club Registration!");

    Text question1 = new Text("How did you hear about our club?");
    Text question2 = new Text("Have you ever been in any clubs for swimming before?");
    Text question3 = new Text("Do you swim competitvly or for fun?");

    TextField question1Answer = new TextField();
    TextField question2Answer = new TextField();
    TextField question3Answer = new TextField();
    question1Answer.setPromptText("Enter where you heard about our club (Internet, Flyer, etc)");
    question2Answer.setPromptText("Enter Yes or No");
    question3Answer.setPromptText("Enter Competitvly or Fun");

    Button cancelButton = new Button("Cancel");
    Button continueButton = new Button("Continue");

    File logoPath = new File("src/swimclub_Logo.png");
    Image logoImage = new Image(logoPath.toURI().toString());
    ImageView logo = new ImageView(logoImage);

    buttonPane.getChildren().addAll(cancelButton, continueButton);
    titlePane.getChildren().addAll(title, logo);
    questions.getChildren().addAll(question1,question1Answer,question2,question2Answer,question3,question3Answer);

    titlePane.setAlignment(Pos.CENTER);
    buttonPane.setAlignment(Pos.CENTER);

    titlePane.setPadding(new Insets(10,0,20,0));
    questions.setPadding(new Insets(0,10,0,10));
    buttonPane.setPadding(new Insets(0,0,10,0));

    main.setTop(titlePane);
    main.setCenter(questions);
    main.setBottom(buttonPane);

    Scene scene = new Scene(main, 900, 600);
    primaryStage.setScene(scene);
    primaryStage.show();

    /**
     * @josegeorges
     * here I am adding the rules pane with the rules scene and setting up the
     * continueButton to go to it for now
     * I am also saving the textFields into a string and passing the content to the pane
     */
    continueButton.setOnMouseClicked(e->{
    String contentToSave = "";
    contentToSave += question1Answer.getText() + ",";
    contentToSave += question2Answer.getText() + ",";
    contentToSave += question3Answer.getText() + ",";

    RulesPane rulesPane = new RulesPane(primaryStage, scene, contentToSave);
    RulesScene rulesScene = new RulesScene(rulesPane);
        primaryStage.setScene(rulesScene);
    });

}

 }

A: Since I can't see where the Pane is exactly coming from, I'm gonna assume that when you said you have TextFields in a VBox, that VBox is inside of that pane. If so, the problem looks like you're casting TextFields to Pane, not TextFields to Pane's children, which if it's in a VBox you'd want to get it's (Vbox's) children anyway. So:
  for (int i = 0; i < pane.getChildren().size(); i++) {
     Node child1 = group.getChildren().get(i);
     if (child1 instanceof VBox) {
         for(Node child2:((VBox) child1).getChildren()) {
             if (child2 instanceof TextField) {
                 contentToSave += (TextField) child2.getText();
             }
          }
      }
   }

Instead of  your for loop in the try-block which tries to make a Pane into a TextField, this would get the children of pane, assuming they're vbox (if they are,) then get the children of VBox and assume they're TextFields if (if they are.)
If that doesn't do it, I'd reccomend posting the rest of your code (where Pane is coming from,) and exactly what error it's throwing.


text:
Q: Sending an email with Sidekiq RSpec Test failed because Array is empty and could not change from 0 to 1 I am trying to test sending an email with Sidekiq and I am having an error which means it doesn't enqueue since my test shows it didn't change from 0 to 1 in size. Could it be I am missing something out or how can I fix this?
Error
expected `Array#size` to have changed by 1, but was changed by 0

  0) Sending Mail sends email to sidekiq
     Failure/Error:
       expect do
         OrderPointsMailer.paid_order_email(customer_detail.id).deliver_later
       end.to change(Sidekiq::Worker.jobs, :size).by(1)

       expected `Array#size` to have changed by 1, but was changed by 0
     # ./spec/requests/order_points_mailer_spec.rb:9:in `block (2 levels) in <top (required)>'

1 example, 1 failure, 0 passed

binding.pry
This shows Sidekiq::Worker.jobs is empty array and it is understandable why it failed but I do not know how I could fix this.
[1] pry(#<RSpec::ExampleGroups::SendingMailWithSidekiq>)>Sidekiq::Worker.jobs
=> []

app/jobs/order_points_job.rb
# frozen_string_literal: true

class OrderPointsJob < ApplicationJob
  def perform(customer_email)
    customer_detail = CustomerDetail.find_by(email: customer_email)
    return unless customer_detail

    OrderPointsMailer.paid_order_email(customer_detail.id).deliver_later # This call send email to sidekiq process
  end
end

RSpec
# frozen_string_literal: true

require 'rails_helper'

RSpec.describe 'Sending Mail with Sidekiq', type: :request do
  it 'sends email to sidekiq' do
    customer_detail = create(:customer_detail)

    expect do
      OrderPointsMailer.paid_order_email(customer_detail.id).deliver_later
    end.to change(Sidekiq::Worker.jobs, :size).by(1)
  end
end

rails_helper.rb
require 'sidekiq/testing'
Sidekiq::Testing.fake!

A: You probably should use the method count instead of size:
.to change(Sidekiq::Worker.jobs.reload, :count).by(1)

Take a look at the size implementation:
From: /home/toptal/.rvm/gems/ruby-2.5.5/gems/activerecord-6.0.0/lib/active_record/relation.rb @ line 260:
Owner: ActiveRecord::Relation
Visibility: public
Number of lines: 3

def size
  loaded? ? @records.length : count(:all)
end

Also take a look on the matcher implementation (https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/built_in/change.rb#L82:L85)
I'm guessing that the receiver (Sidekiq::Worker.jobs in your case) will be evaluated once, and then the size would be called twice on the same objects collection, without reloading.
One other approach you could take would be
.to change { Sidekiq::Worker.jobs.reload.size }.by(1)

But this would be a bit wasteful in case you have more records in the DB, because each time the AR objects will need to be created (and they're not used)


text:
Q: Ultraproduct of partitions of an $L^p$-space isomorphic to itself?
Let $L$ be an $L^p$-space, $1<p<\infty$, associated with an arbitrary measure space $(X, \mathcal F, \mu)$. A semi-partition of $X$ is a finite disjoint collection of measurable sets with finite measures. Let $A$ be the set of all semi-partitions of $X$. We introduce a partial order into $A$ as $\alpha\leq \alpha'$ meaning that each set in $\alpha$ is a union of some sets in $\alpha'$, this makes $A$ a directed set. Let $E_\alpha:L\to L$ be the conditional expectation operator with respect to the semi-partition $\alpha$, mapping functions to their average values on the sets of $\alpha$ and to zero outside of these sets. We have that for fixed $f\in L$, the net $\{E_\alpha f\}$ converges to $f$. Let $L_\alpha$ be the range of $E_\alpha$ (this is a finite dimensional $L^p$-space). Let $\mathcal U$ be an ultrafilter on $A$ containing all sets $\{\alpha\in A: \alpha\geq\alpha_0\}$ for arbitrary $\alpha_0\in A$.

I would like to know if the ultraproduct $W$ of the $L_\alpha$ with respect to $\mathcal U$ is isometric isomorphic to $L$ itself. If $A$ contains a largest element this is true of course, but my intuition says it should be also true otherwise.

Here is what I have tried:
Let $\phi: L\to W, f\mapsto (E_\alpha f)_\mathcal U$, where $(x_\alpha)_\mathcal U$ denotes the equivalence class of $(x_\alpha)_{\alpha\in A}$ with respect to $\mathcal U$.
The mapping is isometric: $\|(E_\alpha f)_\mathcal U\| = \lim_\mathcal U\|E_\alpha f\|$. Since $\|E_\alpha f\|$ net-converges to $\|f\|$ this is also true for the ultrafilter limit due to the property we demanded of our ultrafilter.
I have problems with the surjectivity. Let $(f_\alpha)_\mathcal U\in W$ be arbitrary. My idea was to define a functional on $\varphi$ on $L^q(X)$ via $\varphi(g) = \lim_\mathcal U\int_{L_\alpha}(E_\alpha g)f_\alpha$. The limit exists because $\int_{L_\alpha}(E_\alpha g)f_\alpha$ is bounded. This also shows that $\varphi$ is bounded, hence there is $f\in L$ which induces $\varphi$. I think that we should have $(E_\alpha f)_\mathcal U = (f_\alpha)_\mathcal U$, but I can't show that $\lim_\mathcal U\|E_\alpha f-f_\alpha\| = 0$. If $(f_\alpha)_\mathcal U$ is already of the form $(E_\alpha f)_\mathcal U$ then this construction with the functional indeed gives back $f$, but in the general case I don't see it. Can anybody help me?

A: I think that the answer is NO since an ultraproduct of $L^p$-spaces $L^p(\Omega_i)$ is an $L^p$-space on a measure space $\Omega^{\mathcal{U}}$ and such a measure space is a "bigger" measure space and generally no $\sigma$-finite even if the $\Omega_i$'s are $\sigma$-finite.


text:
Q: Why my transition on my hamburger menu not working? I have problem with a transition.
I would like to the transition start after clicking on the icon(bars) on mobile view. But transition doesn't work.When I click on the icon, nav will appear, but transition is not execute.
My code: https://codepen.io/ji-nov-ek/pen/gOwNZea

// Hamburger menu
let toggle = document.getElementById("toggle");
let nav = document.querySelector("nav");

toggle.addEventListener('click', function() {
  if (nav.style.display === "flex") {
    nav.style.display = "none";
    nav.style.opacity = "0";
  } else {
    nav.style.display = "flex";
    nav.style.opacity = "1";
  }
});
/* Global Styles */

@import url("https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap");
* {
  margin: 0;
  padding: 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  text-decoration: none;
  font-family: 'Poppins', sans-serif;
}

html {
  font-size: 10px;
}

ul {
  list-style: none;
}

a {
  text-decoration: none;
  color: #434343;
  font-family: 'Poppins', sans-serif;
}

h1,
h2,
h3 {
  font-family: 'Poppins', sans-serif;
}

body {
  background-color: #ffffff;
}

.case {
  height: 100vh;
}

.case .hero {
  background-color: #ffffff;
}

.case .hero header {
  background-color: #4281C1;
  min-height: 10rem;
  width: 100%;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}

.case .hero header .logo {
  width: 28rem;
}

.case .hero header .logo img {
  width: 100%;
  height: 100%;
}

.case .hero header nav {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -ms-flex-direction: row;
  flex-direction: row;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  min-height: 10rem;
  margin: 1rem 0;
}

.case .hero header nav ul {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -ms-flex-direction: row;
  flex-direction: row;
  margin-left: 10rem;
  margin-right: 20rem;
}

.case .hero header nav ul li {
  font-size: 2rem;
  color: #434343;
  padding: 1rem;
  text-transform: uppercase;
}

.case .hero header nav .icons {
  margin-left: 0rem;
  margin-right: 0rem;
}

.case .hero header nav .icons i {
  font-size: 2rem;
  color: #434343;
  padding: 1rem;
}

.hero {
  height: 70vh;
}

.active {
  color: #ffffff;
  border-bottom: 1px solid #ffffff;
}

#toggle {
  display: none;
}

@media (max-width: 1024px) {
  .case .hero header {
    min-height: 8rem;
  }
  .case .hero header .logo {
    width: 22rem;
  }
  .case .hero header nav {
    min-height: 8rem;
    margin: 1rem 0;
  }
  .case .hero header nav ul {
    margin-left: 5rem;
    margin-right: 8rem;
  }
  .case .hero header nav ul li {
    font-size: 1.8rem;
    padding: 0.8rem;
  }
  .case .hero header nav .icons {
    margin-left: 0rem;
    margin-right: 0rem;
  }
  .case .hero header nav .icons i {
    font-size: 2rem;
    color: #434343;
    padding: 0.8rem;
  }
}

@media (max-width: 768px) {
  .case .hero header {
    min-height: 8rem;
  }
  .case .hero header .logo {
    width: 18rem;
  }
  .case .hero header nav {
    min-height: 8rem;
    margin: 1rem 0;
  }
  .case .hero header nav ul {
    margin-left: 5rem;
    margin-right: 5rem;
  }
  .case .hero header nav ul li {
    font-size: 1.6rem;
    padding: 0.5rem;
  }
  .case .hero header nav .icons {
    margin-left: 0rem;
    margin-right: 0rem;
  }
  .case .hero header nav .icons i {
    font-size: 2rem;
    color: #434343;
    padding: 0.5rem;
  }
}

@media (max-width: 640px) {
  .case .hero header {
    min-height: 8rem;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-direction: column;
    flex-direction: column;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    justify-content: center;
    -webkit-box-align: end;
    -ms-flex-align: end;
    align-items: flex-end;
  }
  .case .hero header .logo {
    width: 18rem;
    display: none;
  }
  .case .hero header nav {
    min-height: 8rem;
    width: 100%;
    margin: 0;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-direction: column;
    flex-direction: column;
    position: absolute;
    top: 80px;
    background-color: #4281C1;
    z-index: 4;
    text-align: center;
    border-top: 2px solid #ffffff;
    border-bottom: 2px solid #ffffff;
    display: none;
    opacity: 0;
    -webkit-transition: all ease-in 0.7s;
    transition: all ease-in 0.7s;
  }
  .case .hero header nav ul {
    margin: 0.5rem 1rem;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-direction: column;
    flex-direction: column;
  }
  .case .hero header nav ul li {
    font-size: 1.6rem;
  }
  .case .hero header nav .icons {
    margin-left: 0rem;
    margin-right: 0rem;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -ms-flex-direction: row;
    flex-direction: row;
  }
  .case .hero header nav .icons i {
    font-size: 2rem;
    color: #434343;
  }
  #toggle {
    font-size: 3rem;
    color: #ffffff;
    padding: 2rem;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
  }
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.1/css/all.css" integrity="sha384-xxzQGERXS00kBmZW/6qxqJPyxW3UR0BPsL4c8ILaIWXva5kFi7TxkIIaMiKtqV1Q" crossorigin="anonymous">

Domů

O nás

Produkty

Kontakt

Test

Don't know what the problem is?
Thanks for your help!

A:

// Hamburger menu
let toggle = document.getElementById("toggle");
let nav = document.querySelector("nav");

toggle.addEventListener('click', function() {
  nav.classList.toggle('active');
});
/* Global Styles */

@import url("https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap");
* {
  margin: 0;
  padding: 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  text-decoration: none;
  font-family: 'Poppins', sans-serif;
}

html {
  font-size: 10px;
}

ul {
  list-style: none;
}

a {
  text-decoration: none;
  color: #434343;
  font-family: 'Poppins', sans-serif;
}

h1,
h2,
h3 {
  font-family: 'Poppins', sans-serif;
}

body {
  background-color: #ffffff;
}

.case {
  height: 100vh;
}

.case .hero {
  background-color: #ffffff;
}

.case .hero header {
  background-color: #4281C1;
  min-height: 10rem;
  width: 100%;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}

.case .hero header .logo {
  width: 28rem;
}

.case .hero header .logo img {
  width: 100%;
  height: 100%;
}

.case .hero header nav {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -ms-flex-direction: row;
  flex-direction: row;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  min-height: 10rem;
  margin: 1rem 0;
}

.case .hero header nav ul {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -ms-flex-direction: row;
  flex-direction: row;
  margin-left: 10rem;
  margin-right: 20rem;
}

.case .hero header nav ul li {
  font-size: 2rem;
  color: #434343;
  padding: 1rem;
  text-transform: uppercase;
}

.case .hero header nav .icons {
  margin-left: 0rem;
  margin-right: 0rem;
}

.case .hero header nav .icons i {
  font-size: 2rem;
  color: #434343;
  padding: 1rem;
}

.hero {
  height: 70vh;
}

.active {
  color: #ffffff;
  border-bottom: 1px solid #ffffff;
}

#toggle {
  display: none;
}

@media (max-width: 1024px) {
  .case .hero header {
    min-height: 8rem;
  }
  .case .hero header .logo {
    width: 22rem;
  }
  .case .hero header nav {
    min-height: 8rem;
    margin: 1rem 0;
  }
  .case .hero header nav ul {
    margin-left: 5rem;
    margin-right: 8rem;
  }
  .case .hero header nav ul li {
    font-size: 1.8rem;
    padding: 0.8rem;
  }
  .case .hero header nav .icons {
    margin-left: 0rem;
    margin-right: 0rem;
  }
  .case .hero header nav .icons i {
    font-size: 2rem;
    color: #434343;
    padding: 0.8rem;
  }
}

@media (max-width: 768px) {
  .case .hero header {
    min-height: 8rem;
  }
  .case .hero header .logo {
    width: 18rem;
  }
  .case .hero header nav {
    min-height: 8rem;
    margin: 1rem 0;
  }
  .case .hero header nav ul {
    margin-left: 5rem;
    margin-right: 5rem;
  }
  .case .hero header nav ul li {
    font-size: 1.6rem;
    padding: 0.5rem;
  }
  .case .hero header nav .icons {
    margin-left: 0rem;
    margin-right: 0rem;
  }
  .case .hero header nav .icons i {
    font-size: 2rem;
    color: #434343;
    padding: 0.5rem;
  }
}

@media (max-width: 640px) {
  .case .hero header {
    min-height: 8rem;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-direction: column;
    flex-direction: column;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    justify-content: center;
    -webkit-box-align: end;
    -ms-flex-align: end;
    align-items: flex-end;
  }
  .case .hero header .logo {
    width: 18rem;
    display: none;
  }
  .case .hero header nav {
    min-height: 8rem;
    width: 100%;
    margin: 0;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-direction: column;
    flex-direction: column;
    position: absolute;
    top: 80px;
    background-color: #4281C1;
    z-index: 4;
    text-align: center;
    border-top: 2px solid #ffffff;
    border-bottom: 2px solid #ffffff;
    visibility: hidden;
    opacity: 0;
    -webkit-transition: all ease-in 0.7s;
    transition: all ease-in 0.7s;
  }
  .case .hero header nav.active {
    opacity: 1;
    visibility: visible;
  }
  .case .hero header nav ul {
    margin: 0.5rem 1rem;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-direction: column;
    flex-direction: column;
  }
  .case .hero header nav ul li {
    font-size: 1.6rem;
  }
  .case .hero header nav .icons {
    margin-left: 0rem;
    margin-right: 0rem;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -ms-flex-direction: row;
    flex-direction: row;
  }
  .case .hero header nav .icons i {
    font-size: 2rem;
    color: #434343;
  }
  #toggle {
    font-size: 3rem;
    color: #ffffff;
    padding: 2rem;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
  }
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.1/css/all.css" integrity="sha384-xxzQGERXS00kBmZW/6qxqJPyxW3UR0BPsL4c8ILaIWXva5kFi7TxkIIaMiKtqV1Q" crossorigin="anonymous">

Domů

O nás

Produkty

Kontakt

Test

Fixed Your Code. Check it out . Don't change display mode like that.

A:
display:none; removes a block from the page as if it were never there. A block cannot be partially displayed; it's either there or it's not. The same is true for visibility; you can't expect a block to be half hidden which, by definition, would be visible! Fortunately, you can use opacity for fading effects instead. More info

So, instead of toggle display(flex/none) toggle height(auto / 0).


text:
Q: How to define in TypeScript interface for merge function? There are some way to define such interface for merge function:
interface mergeFunc<T, S, P exntends T,S>(t:T, s:S):P;

var merge:mergeFunc = function (t:any, s:any):any {
   var res = {};
   for (let x in t) res[x] = t[x];
   for (let x in s) res[x] = s[x];
   return res;
}

?

A: In TypeScript 1.6 (or TypeScript nightly today, use npm install typescript@next), you'll be able to use intersection types to write this:
declare function mergeFunc<T, S>(t:T, s:S): T & S;

See https://github.com/Microsoft/TypeScript/pull/3622

A: For immutable change of T
If you only need to merge properties compatible with the initial type, since TypeScript 1.8 you can use type parameters as constraints :
const merge = function<T extends S, S>
( t: T, s: S ) : T {
  const res: any = {}
  // copy
  for ( const k in t ) {
    if ( t.hasOwnProperty ( k ) ) {
      res [ k ] = t [ k ]
    }
  }
  // merge
  for ( const k in s ) {
    if ( s.hasOwnProperty ( k ) ) {
      res [ k ] = s [ k ]
    }
  }
  return res
}


text:
Q: Find valid parameter combinations of a function I have a function f[a_,b_, c_, d_] which is quite complex (multiple gamma functions and other nasty things). Some parameter combinations of this function produce an "Indeterminate" error. Is there a way to let Mathematica figure out (analytically or numerically) the 'valid' parameter combinations for this function?
Thank you very much!


text:
Q: What is the equivalent terminal command to findsmb on Lion The findsmb command present in SnowLeopard and older, is not available from terminal in Lion. Is there an equivalent?

A: Try using smbutil lookup to resolve IP to NetBIOS names

A: Its looks like you should be able to re install it yourself manually.

*

*Install samba3 using MacPorts

*Put the contents of the source for findsmb perl script into a file named findsmb, make it executable in using chmod and then add it your path to regain the findsmb program.


text:
Q: Regex to match certain value in JSON Working with Jmeter and have a response that is bugging me a bit.
{"iTotalRecords":19844,"iTotalDisplayRecords":19844,"aaData":[["20025","S1409117192","123vn","24 Feb 2014 21:30","1","1","0","0"],["20024","S1409336659","123vn","24 Feb 2014 21:06","4000","4000","0","0"],["20023","S1409509024","123vn","24 Feb 2014 21:03","4000","0","0","4000"],["20022","S1409347541","123vn","24 Feb 2014 21:01","4000","0","0","4000"],["20021","S1408224820","123vn","18 Feb 2014 23:34","4000","4000","0","0"],["20020","S1406490372","123vn","05 Feb 2014 17:04","2000","2000","0","0"],["20019","S1406876597","123vn","05 Feb 2014 16:59","2000","2000","0","0"],["20018","S1405014730","123vn","30 Jan 2014 18:11","2000","2000","0","0"],["20017","S1405306741","123vn","29 Jan 2014 21:25","2000","2000","0","0"],["20016","S1405175540","123vn","29 Jan 2014 18:06","2000","2000","0","0"]],"error":""}

I'm trying to return the value 20025 that is the first one after the aaaData, using regex
Any tips ?
Thanks in advance

A: It looks like that you're getting a JSON answer. JMeter supports JSONPath language via a plugin which provides JSONPath Extractor (you'll need Extras with Libs Set)
Relevant JSONPath query for your 20025 would look like:
$.aaData[0].[0]

See Parsing JSON guide on how to build JSONPath queries.

A: How about this regex:
"aaData":\[\["([^"]+)"

Working regex example:
http://regex101.com/r/eX2rC0

A: I'd use the following regex:
(?<="aaData":\[\[")([^"]+)

http://regex101.com/r/sM4cE2


text:
Q: Как сделать трапецию c треугольником с закруглёнными углами? Подскажите пожалуйста как сделать такую трапецию с треугольником(не знаю как назвать такую фигуру) с помощью css? Спасибо
https://i.stack.imgur.com/5289T.png

A: У меня так вышло
.Rectangle_1{border-width:1 px;
border-color: rgb(255,0,0);
border-style: solid;
border-radius: 30px;
background-color: rgb(255, 0, 0);
position: absolute;
left: 224px;
top: 300px;
width: 527px;
height: 130px;
z-index: 2;
}

A:

body{background: url('https://images.unsplash.com/photo-1453402524241-409afa47033b?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80') no-repeat;
background-size: contain contain;
height: 780px;
width: 1170px;
}
#column{
width: 30px;
height: 500px;
z-index: 1;
background: brown;
justfy-content: center;
font-size: 1.5em;
transform: scale(0.4);
position: absolute;
top: 200px; left: 250px;
}
.goto{
width: 250px;
position: relative;
z-index: 3;
height: 50px;
margin: 15px;
padding: 3px;
text-align: center;
left: -120px;
}
.goto:nth-child(odd):after{right: -15px;content: '';}
.goto:nth-child(even):before{left: -15px;content: '';}

.goto, .goto:after, .goto:before{
border: 1px solid black;
display: block;
border-radius: 10px;
background: skyblue;
}

.goto:after, .goto:before{
position: absolute;
height: 45px;
width: 45px;
transform: rotate(45deg);
z-index: 2;
top: 5px;
}

Москоу

Парыж

там Дубай

тут дубак

а тут ваще ппц

p.s. хотел еще рандомно понаклонять "указатели", но и так сойдёт:3


text:
Q: Application for Differential Equation of higher order We found some interesting insights in differential equations of the form
$y^{(n)}(x)+F_\lambda(y(x),y'(x),...,y^{(n-1)}(x))=0$,
i.e. for ordinary differential equations of $n$-th order with $n\geq2$. The function $F$ is polynomial which can include a set of parameters $\lambda$.
We know, that in physics usually the highest derivative is of order two(?), but we are searching for applications of this kind of differential equations for $n\geq3$ in physics, engineering, or in any other area. If you have an idea or know models or theories in which such equations occur, you input would be appreciated very much.
Thanks for input and best wishes!

A: The stationary / travelling wave / soliton regime of the KdV equation and its cousins give a lot of examples. For the original KdV, under the travelling wave ansatz we have the third order equation
$$ f''' - c f' + 6f f' = 0 .$$

The Euler-Bernoulli beam theory has an equation of the form
$$ [ \alpha f'']'' = F $$
If you somehow have a nonlinear load function $F$, or a nonlinear dependence of the flexural rigidity $\alpha$, then you will get a fourth order equation. (I make no claims on the physicality of such assumptions.)

As an aside, as you mentioned that most physical models start out as second order. The appearance of the higher order derivatives usually comes from the approximation of the original higher dimensional physical model (in the form of a partial differential equation) by a simplified model (in  lower dimensions, often now an ODE), with the higher order derivatives arising as a consequence of the constraints under which the approximations are derived. Both examples above are reductions of more primitive systems of partial differential equations: KdV comes from the equations of fluids after a reduction to one dimensions and imposing a shallow-water assumption; Euler-Bernoulli theory comes from the equations for elasticity under a one dimension reduction and certain assumptions on how the beam bends.

A: The Biharmonic nonlinear Schrodinger equation is of the form
 $$i\psi_t (t,x) + \Delta ^2 \psi  + |\psi |^{2\sigma} \psi = 0$$ for some $\sigma >0$, with $x\in \mathbb{R}^d$ (d=1,2,3) and usually an initial condition $\psi(t=0,x) = \psi_0(x) \in H^2$.
For $d=1$, you look for solitary waves in this equation, then by the solitary wave ansatz $\psi(t,x) = e^{i\omega t}R(x)$ you get an ODE of the sort you were looking for -
$$-\omega R + R^{(4)} +|R|^{2\sigma}R = 0$$
Sometime we also look at the Biharmonic NLS (BNLS) as a pertubation for the NLS, something of the following form:
$$i\psi _t + \Delta \psi - \epsilon \Delta ^2 \psi + |\psi|^{2\sigma} \psi = 0 \, ,$$where $\epsilon \ll 1$. In this case, solitary waves can also be considered in the same manner as before.


text:
Q: GAE - How to make an XML-RPC call? I need to make a standard XML-RPC call to the UPC Database (www.upcdatabase.com) using my Google AppEngine Java application.
I found a lot of information on incorporating XML-RPC within GAE but couldn't find anything on how to make a call from GAE.
Any help or examples would be appreciated ?

A: Well what do you know....
I did the following using the Redstone XMLRPC library and it works. Won't have figured that with all the focus on using URLFetch.
XmlRpcClient client = new XmlRpcClient("http://www.upcdatabase.com/xmlrpc", false);
    Map<String, String> params = new HashMap<String, String>();
    params.put("rpc_key", rpc_key);
    params.put("ean",upc);

    HashMap<?,?> token = null;
    try {
        token = (HashMap<?, ?>) client.invoke( "lookup", new Object[] { params } );
    } catch (XmlRpcException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (XmlRpcFault e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Don't quite know why it works and would love an explanation.

A: Here's a good article about how to do it: http://brizzled.clapper.org/blog/2008/08/25/making-xmlrpc-calls-from-a-google-app-engine-application/
EDIT: Sorry, I missed you were asking about Java specifically. The basic idea is the same in either language, though: make an UrlFetch request.
Here's another blog I found with some discussion: http://blog.techstacks.com/2010/01/xmlrpc-with-gae-java.html -- this one uses HTTPBuilder because at the time it was written UrlFetch wouldn't allow setting the User-Agent. That's been fixed (see http://googleappengine.blogspot.com/2009/04/sdk-version-121-released.html) though so implementing this should be much easier.


text:
Q: Exception Value: string indices must be integers : Render bundle error vue + django im using webpack loader to inyect my vue app into django, here is the code:
Settings :
WEBPACK_LOADER = {
'DEFAULT':{
    'BUNDLE_DIR_NAME':'/',
    'STATS_FILE':os.path.join(BASE_DIR,'aptim-frontend/dist','webpack-stats.json')

}}

vue config file :
const BundleTracker = require("webpack-bundle-tracker");
module.exports = {
  // on Windows you might want to set publicPath: "http://127.0.0.1:8080/"
  publicPath: "http://0.0.0.0:8080/",
  outputDir: "./dist/",

  chainWebpack: (config) => {
    config.optimization.splitChunks(false);

config
  .plugin("BundleTracker")
  .use(BundleTracker, [{ filename: "../frontend/webpack-stats.json" }]);

config.resolve.alias.set("__STATIC__", "static");

config.devServer
  .public("http://0.0.0.0:8080")
  .host("0.0.0.0")
  .port(8080)
  .hotOnly(true)
  .watchOptions({ poll: 1000 })
  .https(false)
  .headers({ "Access-Control-Allow-Origin": ["*"] });},};

And the html line where I get the error is at the index html
 {% render_bundle 'app' %}

ERROR :Exception Value: string indices must be integers

A: Downgrade Webpack-bundle-tracker as told by @Frans
npm install --save-dev webpack-bundle-tracker@0.4.3

In vue.config.js
config
    .plugin('BundleTracker')
    .use(BundleTracker, [{filename: './webpack-stats.json'}])

Then delete the dist folder with the old webpack-stats.json
In this version and with this config webpack-stats.json file is generated in frontend not in frontend/dist
So you must change STATS_FILE in settings.py
(for example if your Vue project is frontend)
'STATS_FILE': os.path.join(BASE_DIR, 'frontend','webpack-stats.json'),

Then restart Vue and Django web-servers.

A: Exception Value: string indices must be integers
i got this strange error too, confirmed downgrade to webpack-bundle-tracker@0.4.3 works.

A: I had the same issue in the great Udemy course The Complete Guide to Django REST Framework and Vue JS. You probably cannot read the answer from Michele Saba if you are not subscribed.
It probably has something to do with the package versions and them being alpha. Downgrading to

*

*webpack-bundle-tracker@0.4.3

*django-webpack-loader==0.7.0

worked for me. Downgrade using:
npm install --save-dev webpack-bundle-tracker@0.4.3


text:
Q: ReactJs - Warning when transitioning off page after successful login I have a straight foward login page which calls an api service to verify user login:
Login.js
@connect(
  state => ({user: state.auth.user}),
  authActions)
class Login extends React.Component {

  ......

  _handleSubmit = (event) => {
     .....
    this.props.login({username: username.value, password: password.value},
     (result) => {
      return result;
    });
    ......
  };

  render() {
    const {user, logout} = this.props;
    return (
      <section>
        {
          !user ?
            ... Show login page with submit button .....

            : this.context.router.replace('/')
        }
      </section>
    )
  }
};

While the component works as intended, I am receiving the warning:

Cannot update during an existing state transition (such as within
  render or another component's constructor). Render methods should be
  a pure function of props and state; constructor side-effects are an
  anti-pattern, but can be moved to componentWillMount

I know the warning is due to the replace state of the router, but I do not know what would be the best way to prevent this warning and still accomplish the goal of moving away from the login page if the User exists.
Any ideas?
UPDATE
Abdud Dayan Adeeb had the solution .....
  componentWillReceiveProps(nextProps ) {
    if (nextProps.user) this.context.router.replace('/')
  }

A: The problem I see here is you are trying to attempt a transition when the component is rendering/updating.
The best thing to do would be to move the transition logic to the componenetWillReceiveProps function of your component
componenentWillReceiveProps(nextProps) {
    if (nextProps.user) this.context.router.replace('/')
}


text:
Q: C# Realtime standard output/error capture of a process I'm developing a C# application and I need to run an external console process (for example a python script) and receive the output data of the script in real-time. The python script is something like this:
import time
while 1:
    print("Hi Foo!")
    time.sleep(.3)

The following C# code prints the python script output on the C# console in real-time:
static void Main(string[] args)
{
    using (Process process = new Process())
    {
        process.StartInfo.FileName = "python.exe";
        process.StartInfo.Arguments = "test.py";
        process.StartInfo.UseShellExecute = false;
        process.Start();
        process.WaitForExit();
    }
}

However, when I try to capture the output data and write them on the console manually, I fail. The recommended solution according to other posts is something like this, but it doesn't work:
static void Main(string[] args)
{
    using (Process process = new Process())
    {
        process.StartInfo.FileName = "python.exe";
        process.StartInfo.Arguments = "test.py";
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.EnableRaisingEvents = true;
        process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
        process.Start();
        process.BeginOutputReadLine();
        process.WaitForExit();
    }
}

The process.StandardOutput.ReadToEnd() works in blocking mode waiting for the process to exit and returns the whole output all at once. What exactly is the problem with the real-time output capturing and how can I fix it?

A:         using (var process = new Process())
        {
            process.StartInfo.FileName = @"python.exe";
            process.StartInfo.Arguments = "-u test.py";
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.UseShellExecute = false;
            process.Start();

            while (!process.StandardOutput.EndOfStream)
            {
                string line = process.StandardOutput.ReadLine();
                Console.WriteLine(line);
                // do something with line
            }
            process.WaitForExit();
            Console.Read();
        }


text:
Q: reorder the div vertically in small screen using twitter bootstrap On the mobile template i want to position the contact widget at first inside the sidebar.  Please check this example. Is there any way to do that

main content goes here

Overview

Mission and Vision

Directors

Management

Structure

Contact Address

some address will go here

A: You can add two navigation instead of one and add show hide class based on media Query. Its a simple method to get the desired result. Markup follows

Overview

Mission and Vision

Directors

Management

Structure

Contact Address

some address will go here

Overview

Mission and Vision

Directors

Management

Structure


text:
Q: Non sum form of an infinite Sum of polar number I'm looking for a non sum form of the equation
$\sum_{n=1}^\infty(ba^{n+1}\angle n\theta^{\circ})$
I've been working on this problem for 8 hours and have been unable to make any progress.
So my question is: how can we rewrite this equation to not include an infinite sum?
And also if you would be so kind as tell me the names of the algebraic steps used, so i can look further into them.

A: You are presumably asking for the sum of the complex numbers $ba^{n+1}e^{in\theta}=ba(ae^{i\theta})^n$.
If true, provided that $|a|<1$ to ensure convergence, by summation of the geometric series,
$$S=\frac{ba^2e^{i\theta}}{1-ae^{i\theta}}=\frac{ba^2(e^{i\theta}-a)}{1-a\cos\theta+a^2}.$$


text:
Q: In my iOS app, is there any reason to set the HttpOnly and Secure flags for the session cookie? I know it's a good security practice for web applications to set both the HttpOnly and Secure flags for session cookies, but I'm not convinced it's necessary for iOS apps that are written in native code (in other words - no Javascript is being used).
Since Javascript isn't being used, is there any way somebody can access the session cookie as a result of the HttpOnly flag not being set?
If the flags should be set, what's the best way to go about doing this?
Thanks.

A: If your users will only ever be using a native iOS app and not a web browser, then no you do not need to set those flags, as long as the native app knows to handle the cookie securely.  Those flags are intended to indicate to the client application (usually a web browser) that it should only submit the cookie under certain conditions, tyically that the connection is using https.  It would be the native app's responsibility to only submit the cookie when appropriate.  If there are conditions where the cookie would not be handled securely and there may be ambiguity, then you should use them.
Regardless, I would use them for future compatibility, and the fact that they're easy to set.  Chances are good that it won't matter now, but you never know what the future will bring and how your app will evolve.