text:
Q: Make Hangfire Dashboard Full Width (and custom styling) For now, there doesn't seem to be a documented way to easily change Hangfire's Dashboard layout and styling to accomplish tasks like:

*

*Use the full browser width (annoying when you have long Job Ids and Names)

*Can't tweak the styling to better match a parent's site look, adjust grid column widths, etc

There have been Hangfire pull requests to add this type of feature, but nothing that's been integrated into Hangfire.Core, nor a plugin that I could find.  After looking at the core source myself, I figured it would be too much of a pain to maintain my own fork just to add this customization.
So, what's a dev to do?

A: Here's one way to re-style the Hangfire Dashboard that is fairly lightweight, but requires same origin.
High-level:

*

*Setup Hangfire per usual, setup the Dashboard, make sure things are working

*Instead your linking directly to your configured Hangfire Dashboard link (e.g. /Admin/Hangfire), create an page on your site with an iframe that points to the Hangfire Dashboard.

*Use a combo of js and css to tweak the dashboard iframe from the parent page.

Quick example:
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="iframeTest.aspx.cs" Inherits="WebApp.iframeTest" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

</asp:Content>

And the result (full width, styling reapplied when navigating within the iframe, grid column adjustments to get rid of annoying text wrapping, and a quick iframe height auto-adjustment):

(24"W Monitor, 1920px resolution)

A: I currently use Stylus, and create some css for hangfire dashboard.
Here very simple css. Paste into Stylus editor
.container,
.navbar > .container {
    width: 90%
}

Before Stylus

After Stylus


text:
Q: How to implement a weather forecast with automatic updates? Please help, at the moment I have a mistake `TypeError: weather.sys is undefined.
I work with Open Weather Map.
I want for each block to automatically update the date, water and air temperature depending on the city.
I must say right away that geolocation will focus on Russia
I will be glad for your answers.

const api = {
 key: "11c85ec89d2ab590110511a07349dd25",
 baseurl: "https://api.openweathermap.org/data/2.5/"
}

const weather__wrapper = document.addEventListener('DOMContentLoaded', setQuery);
var check = document.querySelector('.weather__city').textContent;

function setQuery(evt) {
 const wrappers = document.querySelectorAll('.weather__wrapper');

 wrappers.forEach( w => {
    var city = w.querySelector('.weather__city');
    getResults(city);
 });
}

function getResults (query) {
 fetch(`${api.baseurl}weather?q=${query}&units=metric&APPID=${api.key}`)
 .then(weather=> {
  return weather.json();
 }).then(displayResults);
}

function displayResults(weather) {
 console.log(weather);
 let city = document.querySelectorAll('.weather__text .weather__city');
 city.innerText = `${weather.name}, ${weather.sys.country}`;

 let now = new Date();
 let date = document.querySelector('.weather__text .weather__date');
 date.innerText = dateBuilder(now);
}

function dateBuilder(d) {
 let months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];

 let date = d.getDate();
 let month = months[d.getMonth()];
 let year = d.getFullYear();

  return `${date}.${month}.${year}`;
}
.weather__wrapper {
 height: 186px;
 width: 355px;
 border-radius: 5px;
 background-color: #e4e8ef;
 padding: 24px 24px 24px 24px;

 margin-left: 30px; /* убрать */
}

.weather__icon {
 float: left;
 margin-top: 26px;
}

.weather__icon i {
 color: #fab165;
 font-size: 5.938em;
}

.weather__text {
 float: right;
}

.weather__city  { /* Локация, на видел input */
 font-weight: 400;
 font-size: 1.500em;
 margin-bottom: 0!important;
}

.weather__temperature {
 font-weight: 800;
 font-size: 1.500em;
 margin-bottom: 0!important;
}

.weather__date {
 font-size: 1.250em;
 font-weight: 200;
 margin-bottom: 0!important;
}

.slide-weather__items {
 display: flex;
 outline: none;
}

.slide-weather {
 margin-bottom: 100px;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="css/main.css">

        Hello

Sochi

+23oC - air

+23oC - water

29.05.2020

Novorossiysk

+23oC - air

+23oC - water

29.05.2020

Gelendzhik

+23oC - air

+23oC - water

29.05.2020

A: It happens because you're passing whole tag as a city name instead of innerHTML:
getResults(city.innerHTML);

You were getting weather.sys error because weather variable didn't contain any data. So you should add some error handling inside displayResults function or before calling it.
EDIT: Added temperature update:
var parent = document.querySelector('.' + weather.name.toLowerCase()).parentNode
parent.querySelector('.weather__current-temp .weather__temperature').innerHTML = Math.round(weather.main.temp) + 'oC - air';

This code is quite ugly, but its just an example of how it should work. You should move both temperature html building and parent searching to a separate function. This will work if you have city classes for all weather__city elements.
If you dont want to add city classes and you want to search parent by innerText, then check this answer: How to get element by innerText
It works like this:

const api = {
 key: "11c85ec89d2ab590110511a07349dd25",
 baseurl: "https://api.openweathermap.org/data/2.5/"
}

const weather__wrapper = document.addEventListener('DOMContentLoaded', setQuery);
var check = document.querySelector('.weather__city').textContent;

function setQuery(evt) {
 const wrappers = document.querySelectorAll('.weather__wrapper');

 wrappers.forEach( w => {
    var city = w.querySelector('.weather__city');
    getResults(city.innerHTML);
 });
}

function getResults (query) {
 fetch(`${api.baseurl}weather?q=${query}&units=metric&APPID=${api.key}`)
 .then(weather=> {
  return weather.json();
 }).then(displayResults);
}

function displayResults(weather) {
 let city = document.querySelectorAll('.weather__text .weather__city');
 city.innerText = `${weather.name}, ${weather.sys.country}`;

 let now = new Date();
 let date = document.querySelector('.weather__text .weather__date');
 date.innerText = dateBuilder(now);

    document.querySelector('.' + weather.name.toLowerCase()).parentNode.querySelector('.weather__current-temp .weather__temperature').innerHTML = Math.round(weather.main.temp) + 'oC - air';
}

function dateBuilder(d) {
 let months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];

 let date = d.getDate();
 let month = months[d.getMonth()];
 let year = d.getFullYear();

  return `${date}.${month}.${year}`;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="css/main.css">

        Hello

Sochi

+23oC - air

+23oC - water

29.05.2020

Novorossiysk

+23oC - air

+23oC - water

29.05.2020

Gelendzhik

+23oC - air

+23oC - water

29.05.2020

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can not save cookies with axios request I have added this in my backend
app.use(cors({
    origin: "http://localhost:3000",
    credentials: true,
    allowedHeaders: [
        'Content-Type',
        'Authorization',
    ]
}))

I can save cookies to my browser with this fetch request
    const res = await fetch("/signin", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          email, password
        })
      })

but can not save with the axious request below
   const res = await Axios.post('/signin',
        { email, password },
        {
          headers: {
            'Content-Type': 'application/json'
          }
        })

What am I doing wrong?
const res = await Axios.post('/signin',{ email, password },
    {
      headers: {
        'Content-Type': 'application/json'
      }
  })

I want this to save the cookies in my browser.


text:
Q: Test Error: Base table or view not found: 1146 Table 'testing.users' doesn't exist I make this simple test:
public function test_my_awesome_test()
{
    $user = User::find(1);
    $response = $this->actingAs($user)->get('/awesome/test');

    $response->assertStatus(200);
}

But after run test it's display me error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table
'testing.users' doesn't exist (SQL: select * from users where
users.id = 1 limit 1)

I had this same error if I needed to print some data from database. This tables exist and website works correctly. Who know where is problem?

A: make .testing file in root of project and set database connection config like .env file in that . if you run a test , laravel use .testing instead of .env to read enviroment

A: According to the Laravel documentation, Sail overrides the DB name you defined in the .env file when you run the tests. You need to remove the following line from your phpunit.xml file:
<env name="DB_DATABASE" value="testing"/>


text:
Q: While trying to see the content of a zipped file, I only get information about the zipping process In Ubuntu, installed on Windows Subsystem for Linux, I want to see the content of a zip file, using gzip --list.
I expected to see a list of included files like this:
FileName    ratio
File1       10%
File2       35%
...

Instead I just see some information on the compression of the zip file:
gzip --list "2019_02_04 05_01_24_Internal_File_2019_02_04 06_00_02.zip"
     compressed        uncompressed  ratio uncompressed_name
          38994                  -1   0.0% 2019_02_04 05_01_24_Internal_File_2019_02_04 06_00_02.zip

… and it's bogus information!
How do I obtain a list of the files archived in that zip file?

A: Gzip (.gz) and Zip (.zip) are two different file formats - you're using the gzip tool on a zip archive.
Try using unzip -lv 2019_02_04 05_01_24_Internal_File_2019_02_04 06_00_02.zip
The output should look something like this:
#unzip -lv test.zip
Archive:  test.zip
 Length   Method    Size  Cmpr    Date    Time   CRC-32   Name
--------  ------  ------- ---- ---------- ----- --------  ----
     528  Defl:N      334  37% 2017-06-19 17:33 b9fd9cb9  test.py
--------          -------  ---                            -------
     528              334  37%                            1 file


text:
Q: Publish/Deploy Visual Basic 2010 project (.exe file for other PCs) Hello I have developed a simple application that uses an Access database. In my application my provider and datafile paths for the DB are
Dim provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Dim dataFile As String = "C:\Users\blanca\Desktop\Serna Impresos 2016\Serna Impresos 2016\Serna Impresos 2016\bin\Debug\SIDB.accdb"
Dim connString As String = provider & dataFile

I know that whenever I download the installation files on another computer it will not work because I used explicit path definition [C:.....\file.accdb] which refers to my own local files.
How do I use a working directory path? What path should I use for it to work on different computers (not the one used to develop)
The error message is this...
clic for image
Changed this and still doesn't work
Dim provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Dim dataFile As String = "\SIDB.accdb"
Dim startup As String = Application.StartupPath
Dim connString As String = provider & startup & dataFile

A: First, you don't want your database in your application directory.  Users with lower-level privileges will not be able to gain write access to it, and you will pull your hair out trying to figure out why different users end up with different data until you understand that some versions of Windows have a "trick" that creates separate copies of files for each user when you don't have admin privileges.
First determine if the database is supposed to be the same for all users, or if each user should have their own copy.
If they should have their own copy, the AppData folder
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

is where you'd want to put the database.
If they should all be working off of a single copy, then you need to make the path an application setting, and make it part of the setup process to stage the database and locate that path.


text:
Q: php password, compare, return true or false I have a file on my server called "pform.php", this is what it looks like:
<form action="password.php" method="get">
<input type="text" name="password13"/>
<input type="submit" value="Submit!"/>
</form>

I have it transfer to another file called "password.php", this is what it looks like:
<?php

$text=$_GET["password13"];
$right="You entered the right password!";
$wrong="You entered the wrong password!";

if($password13)=="test"
{
    echo $right;
}
else
{
    echo $wrong;
}
?>

What can I change on line 7 that makes it compare the password "test" and  return true or false?
Thanks!

A: if($password13)=="test"

should be
if($text=="test")

A: That's very simple:
$trueOrFalse = ($password13=="test");
if ($trueOrFalse) {
   ...

Or put it into the if clause directly:
if ("test" === $password13)
{
    ...

A: if ($text == "test")

not
if ($text) == "test"


text:
Q: upper bound of sequence of functions What function will be an upper bound of the sequence
$f_{n}(x)=\Bigl(1-\frac{x}{n}\Bigr)^{n}\ln(x)$
since $\displaystyle\lim_{n\to\infty}\Bigl(1-\frac{x}{n}\Bigr)^{n}=e^{-x}$ so we should probably bound above by the exponential function.
Someone knows how to do that?

A: $f_{n}(x)\leq e^{-x}\ln{x}$ for all $n$. You already know that
$\displaystyle\lim_{n\rightarrow\infty}(1-\tfrac{x}{n})^{n}=e^{-x}$. For any $n$ and $x$, $(1-\tfrac{x}{n})^{n}\leq e^{-x}$ so you are done.

A: Since $$\left(1 - \frac {x} {n}\right)^n < e^{-x}$$ for $n \geqslant 1$, we obtain $f_n (x) < e^{-x} \log x$. We also have, as $n \to +\infty$, that $$f_n (x) \to e^{-x} \log x.$$

A: You need to prove that
$$ f_{n}(x)=\Bigl(1-\frac{x}{n}\Bigr)^{n} $$
is an increasing bounded above sequence in order to use $e^{-x}$ as an upper bound for the sequence.


text:
Q: angular-responsive-carousel installation issue - IvyCarouselModule I am trying to install npm i angular-responsive-carousel, but I am getting following error
npm ERR! While resolving: agp.v2.ui@0.0.0
npm ERR! Found: @angular/common@13.1.3
npm ERR! node_modules/@angular/common
npm ERR!   @angular/common@"~13.1.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @angular/common@"^11.2.14" from angular-responsive-carousel@2.1.2
npm ERR! node_modules/angular-responsive-carousel
npm ERR!   angular-responsive-carousel@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

A: There's no version compatible with angular 13 just yet.
However, I had the same problem with angular 12 and decided to share the fix too:
use the version 2.1.0 of the angular carousel package like this
npm i angular-responsive-carousel@2.1.0.
Hope this helps somebody.
Reference: https://github.com/ivylaboratory/angular-carousel/issues/114#issuecomment-995196654

A: You can check my fork version:
https://github.com/PikusSpbSandbox/carousel-angular or
npm i carousel-angular
It's upgraded to compatible with Angular 14+ with a few changes and bugfixes.

A: I had the same problem but I fixed it with legacy-peer-deps it will allow you to ignore old dependencies for this package.
here is the code
npm i angular-responsive-carousel  --legacy-peer-deps

A: install angular-responsive-carousel2:
npm install angular-responsive-carousel2

link of npm project
link of github project
link of demo


text:
Q: Maximal area/volume of (d-1)-dimensional object in d-dimensional hypercube What is the largest area/volume of any $(d-1)$-dimensional flat object that fits into the $d$-dimensional unit hypercube? For instance, for $d=2$, the answer is $\sqrt 2$, as this is the length of the (1-dimensional) diagonal. But how does this quantity grow as a function of $d$?

A: The maximal area of a $d-1$ dimensional slice through a $d$-dimensional hypercube is $\sqrt 2$ in any dimension, this was proven by K.M. Ball, Cube slicing in $\mathbb{R}^n$ (1986).


text:
Q: Reading a text file into MatLab as a Matrix with arbitrary delimiters I have a text file of the form:
[  1.80000000e+02   1.00000000e+01   1.00000000e+01   1.00000000e+01
   6.00000000e+00   6.00000000e+00   1.10371666e+02   1.70305901e+01
   9.97633591e+01   1.80011719e+02   3.40282347e+38   3.40282347e+38
   6.00000000e+00]
[  1.80000000e+02   1.00035019e+01   1.00000000e+01   1.00000000e+01
   6.00000000e+00   6.00000000e+00   1.10371666e+02   1.70305901e+01
   9.97633591e+01   1.80011719e+02   3.40282347e+38   3.40282347e+38
   3.00000000e+00]
.
.
.

[  1.80000000e+02   1.00035019e+01   1.00000000e+01   1.00000000e+01
   6.00000000e+00   6.00000000e+00   1.10371666e+02   1.70305901e+01
   9.97633591e+01   1.80011719e+02   3.40282347e+38   3.40282347e+38
   3.00000000e+00]

I would like to load this data into MatLab as a Matrix, where the numbers in each list of the text file are the contents of a single row. So, in effect, each row in the Matrix will contain one whole list. I tried doing various things but nothing is getting me the right result. I think it is due to the weird formatting, where each new line has white space at the beginning + also after every new '['. Any help would be appreciated?

A: I don't know of a super elegant solution. I would bang out something with sscanf like this:
f = fopen('mytmp.txt') ;
s = textscan(f,'%s','Delimiter','[ ]','MultipleDelimsAsOne',true) ;
fclose(f) ;
m = numel(s{1}) ;
v = NaN(m,1) ;
for ii = 1:m
    v(ii) = sscanf(s{1}{ii},'%f') ;
end
m = reshape(v,13,[])' ;


text:
Q: applicationContext classpath not found For some reason (a shiro filter) I saved my application context file in WEB-INF folder. Everything works when I run tomcat but, when I try to get an application context from a controller using :
context = new ClassPathXmlApplicationContext(fileContext);

I receive always this exception:
IOException parsing XML document from class path resource [applicationContext.xml]; nested exception is java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist

It seems that under ecplise I'm not able to include WEB-INF under classpath. I took a look to a lot questions here in stackoverflow but I didn't find yet a solution.
If I move the applicationContext.xml file under src/main/java folder, I'm able to get the context but, the shiro filder defined into web.xml file is not able to see the shiro bean defined under applicationContext file (I double checked and the bean is correctly worked). How can I tell to web.xml to get content from src/main/java? Or, how can I reach the applicationContext.xml

A: WEB-INF is not in your CLASSPATH. WEB-INF/classes is. So why dont you put it in a source folder and package the application?

A: Do not create an instance of ApplicationContext in your controller. The spring DispatcherServlet already creates one for you. All you need to do is access all bean declarations in you application context file using @Autowired.

A: use
context = new FileSystemXmlApplicationContext(fileContext);

instead of
context = new ClassPathXmlApplicationContext(fileContext);

A: Problem has been solved moving all configuration file under WEB-INF/classes and adding the prefix classpath:
<import resource="classpath:spring-data.xml"/>

thanks to all for the help! I really appreciate that!
cheers, Andrea


text:
Q: How do you sort in Excel using two pairs of cells? I am working on a spreadsheet where I have certain data organised in this format:
    Row 1: [Train Origin]
    Row 2: [Train Destination]
    Row 3: [Train Code]

The items are organised in columns.
What I need is to sort this information by pairs i.e. by one destination and one origin, for example: The first trains that would be listed would be going from destination A to destination B, then from B to A and then from C to D and D to C, etc. Then I would sort by train codes alphabetically. How could this be done using a native function or potentially VBA? I've tried using the native sorting function but without success.
Here's a screenshot of how Excel is currently sorting it:

And how I would like it:

Thanks in advance.

A: The simplest solution would be to create a helper row with
an appropriate key and then sort the table by this key.
The top level order is a pair Origin/Destination
or Destination/Origin.
One way to construct a group identifier prefix
is to join the pair, placing the lexicographically smaller one first
and using a separator, which is not used in the table, e.g:
both Paris/SPI and SPI/Paris will have a prefix Paris@SPI.
To make a key, concatenate this prefix with all the three fields
using separator.
For example, assuming that the table is in A1:Z3,
type
=if(A1<A2,A1&"@"&A2,A2&"@"&A1)&"@"&A1&"@"&A2&"@"&A3

in A4, copy/drag this formula to the end of the table row

and then use this row to sort the table data:

Sorted table:


text:
Q: const class can extend lifetime of const member ref of temporary? struct  A {

// something

~A() { std::cout <<  "A destruct!\n"; }

};

class  refWrapper {

public:

refWrapper(const  A&  a) : a_(a) {}

~refWrapper() { std::cout <<  "refWrapper destruct!\n"; }

private:

const A& a_;

};

void  func(const  refWrapper&  ref  =  A()) {

// why ~A after ~refWrapper

// Rather than after refWrapper constructor complete

}

A: With default arguments, the call
func();

is equivalent to
func(A()); // so func(refWrapper(A()));

So,

*

*temporary A is created first (destroyed at end of full expression)

*temporary refWrapper is created second (bound to parameter reference)

*temporary refWrapper destroyed.

*temporary A destroyed.

Notice that there is an exception for lifetime extension or parameter:

A temporary object bound to a reference parameter in a function call ([expr.call]) persists until the completion of the full-expression containing the call.

So refWrapper is destroyed at end of full expression, and not at the end of func call (which is the same moment in given example though). So destruction should be done in reverse order of construction.


text:
Q: Customization of error messages at chekout page in woocommerce I am trying to change the error messages displaying in checkout page.(Image attached for Default  error message)
Image of Default error messages at checkout page

Ex. I want to change error message Billing First name is a required field to  First name can not be left blank.
To achieve this at present i am using the following -

First I removed the Billing keyword from the message.For this i used
the following code in my function.php.

        function remove_billing_keyword_error( $error ) {
        if ( strpos( $error, 'Billing ' ) !== false ) {
            $error = str_replace("Billing ", "", $error);
        }
        return $error;
    }
add_filter( 'woocommerce_add_error', 'remove_billing_keyword_error' );

Output after remove_billing_keyword_error function -

After that I am using woocommerce_after_checkout_validation action hook for custom validation & error messages. But it is executing after the default validation  & both messages are displaying (image attached).

function woocommerce_checkout_extra_validation($fields, $validation_errors)
{
    if(is_user_logged_in())
    {
        error_log("User is logged in :: Callback Name woocommerce_checkout_extra_validation");
    }else{

           if ( isset( $_POST['billing_email'] ) && empty( $_POST['billing_email'] ) ) {
        $validation_errors->add( 'confirm_email_error', __( 'Confirm email address cannot be left blank.', 'woocommerce' ) );
    }

    }
    return $validation_errors;
}
add_action( 'woocommerce_after_checkout_validation', 'woocommerce_checkout_extra_validation', 10, 2);

Output -

Ex. For Email both messages Email address is a required field & Confirm email address cannot be left blank are showing.

Any Advice ?
UPDATE 1
As per @CBroe suggested link, i modified my code & by this now i am able to modified the error message at checkout page. Following is my modified version of code -
function woocommerce_checkout_extra_validation($fields, $validation_errors)
{
    if(is_user_logged_in())
    {
        error_log("User is logged in :: Callback Name woocommerce_checkout_extra_validation");
    }else{

        // if any validation errors
    if( !empty( $validation_errors->get_error_codes() ) ) {

        // remove all of them
        foreach( $validation_errors->get_error_codes() as $code ) {
            $validation_errors->remove( $code );
        }

        // add our custom one
        //$validation_errors->add( 'validation', 'Please fill the fields!' );

        if ( isset( $_POST['billing_first_name'] ) && empty( $_POST['billing_first_name'] ) ) {
            $validation_errors->add( 'billing_first_name_error', __( 'First name cannot be left blank.', 'woocommerce' ) );
        }

        if ( isset( $_POST['billing_last_name'] ) && empty( $_POST['billing_last_name'] ) ) {
                $validation_errors->add( 'billing_last_name_error', __( 'Last name cannot be left blank.', 'woocommerce' ) );
        }

        if ( isset( $_POST['billing_email'] ) && empty( $_POST['billing_email'] ) ) {
            $validation_errors->add( 'confirm_email_error', __( 'Billing email address cannot be left blank.', 'woocommerce' ) );
        }
        if ( $fields['billing_email_cnfrm']  != $fields['billing_email']  ) {
            error_log("Confirm Email - " . $fields['billing_email_cnfrm'] ."And User Email - " . $fields['billing_email']);
            $validation_errors->add( 'email_not_match_error', __( 'Chekcout Error Email not match! .', 'woocommerce' ) );
        }
        if ( $fields['user_password_again']  != $fields['account_password']  ) {
            error_log("Checkout Password Log Block Run");
            $validation_errors->add( 'password_not_match_error', __( 'Chekcout Error Passwords do not match.', 'woocommerce' ) );
        }
        error_log("User is Not logged in :: Callback Name woocommerce_checkout_extra_validation");

    }

    }
    return $validation_errors;
}
add_action( 'woocommerce_after_checkout_validation', 'woocommerce_checkout_extra_validation', 100, 2);

At this my point, my question is there any inbuilt mechanism for validate the mobile number,email,number etc in woocommerce or i need to write everything from scratch.

UPDATE 2
For custom validating the postcode i am using is_postcode() function. I am using this with woocommerce_after_checkout_validation action hook in function.php file. But i am getting Fatal error:
[29-Dec-2021 06:17:27 UTC] PHP Fatal error:  Uncaught Error: Call to undefined function is_postcode() in D:\xampp\htdocs\wpreg\wp-content\themes\ljschildtheme\functions.php:703
Stack trace:
#0 D:\xampp\htdocs\wpreg\wp-includes\class-wp-hook.php(303): woocommerce_checkout_extra_validation(Array, Object(WP_Error))
#1 D:\xampp\htdocs\wpreg\wp-includes\class-wp-hook.php(327): WP_Hook->apply_filters(NULL, Array)
#2 D:\xampp\htdocs\wpreg\wp-includes\plugin.php(470): WP_Hook->do_action(Array)
#3 D:\xampp\htdocs\wpreg\wp-content\plugins\woocommerce\includes\class-wc-checkout.php(887): do_action('woocommerce_aft...', Array, Object(WP_Error))
#4 D:\xampp\htdocs\wpreg\wp-content\plugins\woocommerce\includes\class-wc-checkout.php(1161): WC_Checkout->validate_checkout(Array, Object(WP_Error))
#5 D:\xampp\htdocs\wpreg\wp-content\plugins\woocommerce\includes\class-wc-ajax.php(466): WC_Checkout->process_checkout()
#6 D:\xampp\htdocs\wpreg\wp-includes\class-wp-hook.php(303): WC_AJAX::checkout('')
#7 D:\xampp\htdocs\wpreg\wp-includes\class-wp-hook.php(327): WP_Hook->apply_filters('', Array)
#8 D:\xampp\htdocs\wpreg\wp-includes\plugin.php(470): WP_Hook->do_action(Array)
#9 D:\xampp\htdocs\wpreg\wp-content\plugins\woocommerce\includes\class-wc-ajax.php(90): do_action('wc_ajax_checkou...')
#10 D:\xampp\htdocs\wpreg\wp-includes\class-wp-hook.php(303): WC_AJAX::do_wc_ajax('')
#11 D:\xampp\htdocs\wpreg\wp-includes\class-wp-hook.php(327): WP_Hook->apply_filters(false, Array)
#12 D:\xampp\htdocs\wpreg\wp-includes\plugin.php(470): WP_Hook->do_action(Array)
#13 D:\xampp\htdocs\wpreg\wp-includes\template-loader.php(13): do_action('template_redire...')
#14 D:\xampp\htdocs\wpreg\wp-blog-header.php(19): require_once('D:\\xampp\\htdocs...')
#15 D:\xampp\htdocs\wpreg\index.php(17): require('D:\\xampp\\htdocs...')
#16 {main}
  thrown in D:\xampp\htdocs\wpreg\wp-content\themes\ljschildtheme\functions.php on line 703

My postcode validation code -
    if ( empty( $_POST['billing_postcode'] )) {
        $validation_errors->add( 'billing_postcode_error', __( 'Post code can not be left blank', 'woocommerce' ) );
    }

    if ( isset( $_POST['billing_postcode'] ) && is_postcode( $_POST['billing_postcode'],  $_POST['billing_city']) ) {
        $validation_errors->add( 'billing_postcode_country_error', __( 'Post code provided is invalid', 'woocommerce' ) );
    }

How can i add custom validations for postcode,phone & email in function.php
if i want to customize the error messages in checkout page. I dont want to use filters to change the error text.

Any advice.

A: You can modify any text that "wrapped" by translation function __() using gettext hook. Like this:
add_filter( 'gettext', function( $translation, $text, $domain ){
if( $domain == 'woocommerce' ){
    if ( strpos($text, 'Billing First name is a required field') !== false ) {
        $translation =  str_replace('Billing First name is a required field', 'irst name can not be left blank.', $text);
    }
}
return $translation;}, 10, 3 );


text:
Q: send excel file as base64 via using WhatsApp api with Ultramsg I am trying to convert excel file to base64 to send WhatsApp API with Ultramsg  :
<?php

require_once ('vendor/autoload.php'); // if you use Composer
//require_once('ultramsg.class.php'); // if you download ultramsg.class.php
$token=""; // Ultramsg.com token
$instance_id=""; // Ultramsg.com instance id
$client = new UltraMsg\WhatsAppApi($token,$instance_id);
$to="";
$filename="test.xlsx";
$document = base64_encode(file_get_contents("test.xlsx"));
$api=$client->sendDocumentMessage($to,$filename,$document);
print_r($api);

But I see this error :
Array
(
    [error] => Array
        (
            [0] => Array
                (
                    [document] => file extension not supported
                )

        )

)

A: You need add MIME types for Microsoft Excel
.xls=application/vnd.ms-excel
or
.xlsx=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
$document ="data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,".$document;

So , Try this code block and enjoy (: :
<?php
require_once ('vendor/autoload.php'); // if you use Composer
//require_once('ultramsg.class.php'); // if you download ultramsg.class.php
$token=""; // Ultramsg.com token
$instance_id=""; // Ultramsg.com instance id
$client = new UltraMsg\WhatsAppApi($token,$instance_id);
$to="";
$filename="test.xlsx";
$document = base64_encode(file_get_contents("test.xlsx"));
$document ="data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,".$document;
$api=$client->sendDocumentMessage($to,$filename,$document);
print_r($api);


text:
Q: Battery not working/charging but detected i have a thinkpad t 410 and ubuntu 14.04 LTS installed. everything worked fine for a long time, but since a week or so my battery is not working properly any more (orange battery light flashing) it says it's on 97% and not charging. when i unplug the AC the cumputer turns off. i bought a new battery right away because i need it anyway but it's the same problem. i did a "hardware reset" (shut down, unplug AC, remove battery, press and hold power for 45 secs, plug in AC, turn on,shut down, connect battery) but thats not working,
and i booted ubuntu with bootparameter "apci=off" but that did not help ether.
here is what upower shows (battery 1)

and here battery two

has anyone got an idea what is going on?


text:
Q: Set shipping cost on the product, fix configurable products in Magento I extend the flatrate carrier model of Magento 1.9 as suggested here because I want to set shipping cost on the single product.
When I add configurable products in the cart, shipping cost is double.
Magento consider inside the cart a configurable product and simple product variant.
So when I add a configurable product Magento sum shipping cost of both configurable and single products.
I add a condition to exclude configurable products. Is it ok? Is there a way to extract only single products from the cart?
Thanks.
Mage::getSingleton('core/session', array('name'=>'frontend'));
    $session = Mage::getSingleton('checkout/session');
    $cart_items = $session->getQuote()->getAllItems();
    $_helper = Mage::helper('catalog/output');
    $custom_ship = 0;
    foreach( $cart_items as $items ){
        // items are configurable and single products
        $cur_fproduct = Mage::getModel('catalog/product')->load($items->getProduct_id());
        if($cur_fproduct->getTypeId()=='simple') {
            $custom_ship +=($items->getQty())*($_helper->productAttribute($cur_fproduct, $cur_fproduct->getShippingWorld(), 'shipping_world'));
        }
    }

    return $custom_ship ;

A: Instead on this,
$cart_items = $session->getQuote()->getAllItems();

use,
 $cart_items = $session->getQuote()->getAllVisibleItems();

Or you can check
foreach( $cart_items as $items ){
        // items are configurable and single products
        if ($item->getParentItemId) // this is set for simple products of configurable
       {
       }
    }

Hope this helps!


text:
Q: MethodValidationInterceptor and @Validated @ModelAttribute I have a Spring Boot 2 app and I want to be able to validate controller arguments with Hibernate validator - which I'm using successfully. I have all my controller annotated as @Validated and I'm using the validation for request parameters like so @PathVariable @AssertUuid final String customerId - so far so good, everything works.
But, I want to also be able to validate @ModelAttribute from forms.
@Controller
@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(path = "/customers")
@Validated
public class CustomerController
{

    private final CustomerFacade customerFacade;

    public CustomerController(
        final CustomerFacade customerFacade
    )
    {
        this.customerFacade = customerFacade;
    }

    @GetMapping("/create")
    public ModelAndView create(
        final AccessToken accessToken
    )
    {
        return new ModelAndView("customer/create")
            .addObject("customer", new CreateCustomerRequest());
    }

    @PostMapping("/create")
    public ModelAndView handleCreate(
        final AccessToken accessToken,
        @Validated @ModelAttribute("customer") final CreateCustomerRequest customerValues,
        final BindingResult validation
    ) throws
        UserDoesNotHaveAdminAccessException
    {
        if (validation.hasErrors()) {
            return new ModelAndView("customer/create")
                .addObject("customer", customerValues);
        }

        CustomerResult newCustomer = customerFacade.createCustomer(
            accessToken,
            customerValues.getName()
        );

        return new ModelAndView(new RedirectView("..."));
    }

    public static final class CreateCustomerRequest
    {

        @NotNull
        @NotBlank
        private String name;

        public CreateCustomerRequest(final String name)
        {
            this.name = name;
        }

        public CreateCustomerRequest()
        {
        }

        public String getName()
        {
            return name;
        }

    }

}

But this causes the MethodValidationInterceptor to throw ConstraintViolationException when I send invalid data. This would normally make sense and I want this behaviour in every other case, but in this case, as you can see, I want to use the BindingResult to handle the validation errors - which is neccesary when working with forms.
Is there a way I could tell Spring to not validate this particular parameter with MethodValidationInterceptor, because it's already validated by the binder and I want to handle it differently?
I've been digging around in the spring code and it looks like is not designed to work together. I have the some ideas how to fix this:

*

*remove the @Validated from the argument and

*

*call validator.validate() explicitly in the controller method - ugly and dangerous (you might forget to call it)

*create another AOP interceptor, that would find "pairs" of @ModelAttribute and BindingResult and call the validator there, forcing the validation globally

Am I going about this completely wrong? Am I missing something? Is there a better way?

A: I've come up with a solution that allows me to continue working, but I don't consider this problem solved.
As I've hinted in the original question, this Aspect forces validation of the @ModelAttribute when it isn't annotated with @Validated or @Valid.
This means that the ConstraintViolationException is not thrown for invalid @ModelAttribute and you can handle the errors in method body.
import com.google.common.collect.Iterators;
import com.google.common.collect.PeekingIterator;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.MethodParameter;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@SuppressWarnings({"checkstyle:IllegalThrows"})
@Aspect
public class ControllerModelAttributeAutoValidatingAspect
{

    private final Validator validator;

    public ControllerModelAttributeAutoValidatingAspect(
        final Validator validator
    )
    {
        this.validator = validator;
    }

    @Around("execution(public * ((@org.springframework.web.bind.annotation.RequestMapping *)+).*(..)))")
    public Object proceed(final ProceedingJoinPoint pjp) throws Throwable
    {
        MethodSignature methodSignature = MethodSignature.class.cast(pjp.getSignature());
        List<MethodParameter> methodParameters = getMethodParameters(methodSignature);

        PeekingIterator<MethodParameter> parametersIterator = Iterators.peekingIterator(methodParameters.iterator());
        while (parametersIterator.hasNext()) {
            MethodParameter parameter = parametersIterator.next();
            if (!parameter.hasParameterAnnotation(ModelAttribute.class)) {
                // process only ModelAttribute arguments
                continue;
            }
            if (parameter.hasParameterAnnotation(Validated.class) || parameter.hasParameterAnnotation(Valid.class)) {
                // if the argument is annotated as validated, the binder already validated it
                continue;
            }

            MethodParameter nextParameter = parametersIterator.peek();
            if (!Errors.class.isAssignableFrom(nextParameter.getParameterType())) {
                // the Errors argument has to be right after the  ModelAttribute argument to form a pair
                continue;
            }

            Object target = pjp.getArgs()[methodParameters.indexOf(parameter)];
            Errors errors = Errors.class.cast(pjp.getArgs()[methodParameters.indexOf(nextParameter)]);
            validator.validate(target, errors);
        }

        return pjp.proceed();
    }

    private List<MethodParameter> getMethodParameters(final MethodSignature methodSignature)
    {
        return IntStream.range(0, methodSignature.getParameterNames().length)
            .mapToObj(i -> new MethodParameter(methodSignature.getMethod(), i))
            .collect(Collectors.toList());
    }

}

Now you can just keep using validation annotations in your controller methods as you're used to, and at the same time, the final BindingResult validation works as expected.
@PostMapping("/create")
public ModelAndView handleCreate(
    final AccessToken accessToken,
    @ModelAttribute("customer") final CreateCustomerRequest customerValues,
    final BindingResult validation
)

A: Thank you for sharing this solution.
I used it as inspiration and as a base for creating a more general method arguments validator that I intend to use on selected methods.
Validation is triggered for methods annotated by @Validate:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Validate {
}

Example:
@Validate
public void testMe(BindingModel bindingModel, Errors errors) {
    if (!errors.hasErrors()) {
        // bindingModel is valid
    }
}

And here's the modified aspect class:
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Aspect
@Component
public class ValidateAspect {

    private final Validator validator;

    public ValidateAspect(Validator validator) {
        this.validator = validator;
    }

    @Around("@annotation(Validate)")
    public Object proceed(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        List<MethodParameter> methodParameters = getMethodParameters(methodSignature);

        for (int i = 0; i < methodParameters.size() - 1; i++) {
            MethodParameter parameter = methodParameters.get(i);

            MethodParameter nextParameter = methodParameters.get(i + 1);
            if (!Errors.class.isAssignableFrom(nextParameter.getParameterType())) {
                // the Errors argument has to be right after the validated argument to form a pair
                continue;
            }

            Object target = pjp.getArgs()[methodParameters.indexOf(parameter)];
            Errors errors = (Errors) pjp.getArgs()[methodParameters.indexOf(nextParameter)];
            validator.validate(target, errors);
        }

        return pjp.proceed();
    }

    private static List<MethodParameter> getMethodParameters(MethodSignature methodSignature) {
        return IntStream
                .range(0, methodSignature.getParameterNames().length)
                .mapToObj(i -> new MethodParameter(methodSignature.getMethod(), i))
                .collect(Collectors.toList());
    }
}

The above code is tested and (so far) seems to work properly with Spring Boot 2.1.4.RELEASE


text:
Q: Transform ranged data in an Access table I have a table in Access database as below;
Name | Range   | X  | Y  | Z
------------------------------
A    | 100-200 | 1  | 2  | 3
A    | 200-300 | 4  | 5  | 6
B    | 100-200 | 10 | 11 | 12
B    | 200-300 | 13 | 14 | 15
C    | 200-300 | 16 | 17 | 18
C    | 300-400 | 19 | 20 | 21

I have trying write a query that convert this into the following format.
Name | X_100_200 | Y_100_200 | Z_100_200 | X_200_300 | Y_200_300 | Z_200_300 | X_300_400 | Y_300_400 | Z_300_400
A    | 1         | 2         | 3         | 4         | 5         | 6         |           |           |
B    | 10        | 11        | 12        | 13        | 14        | 15        |           |           |
C    |           |           |           | 16        | 17        | 18        | 19        | 20        | 21

After trying for a while the best method I could come-up with is to write bunch of short queries that selects the data for each Range and then put them together again using a Union query. The problem is that for this example I have shown 3 columns (X, Y and Z), but I actually have much more.  Access is starting to strain with the amount of SQL I have come up with.
Is there a better way to achieve this?

A: The answer was simple.  Just use Access Pivotview.  Finding it hard to export the results to Excel though.


text:
Q: Adding an icon to right-to-left ListView items causes the icons to flip in C# WinForms I have a ListView. Its RightToLeft property is set to Yes and its RightToLeftLayout is set to True. The ListView is populated with files in a directory.
In my code, I get the appropriate icon of a file using System.Drawing.Icon.ExtractAssociatedIcon(string filePath) and assign it to the file. This means that the icon come directly from the operating system. I do not have a directory with custom icons.
So the result is this:

As you can see, the PowerPoint file icon is flipped. When I change the layout to LeftToRight it is shown perfectly. How can I fix it?
Thanks.

A: If you only need the icon to be reversed, I suggest putting it into a Bitmap then using the Bitmap.RotateFlip you can flip it horizontally.
Bitmap bm = System.Drawing.Icon.ExtractAssociatedIcon(string filePath).ToBitmap();
bm.RotateFlip(RotateFlipType.RotateNoneFlipX);


text:
Q: the number of roots for a non-polynomial continuous function on a closed interval Is there a general method to find the number of roots for a non-polynomial
continuous function on a closed interval?
For example, I know that $\ln^{2}x-\ln x-1/x+1=0$ has only one solution (other than 1) on the interval of $[0,1]$, but how to prove it?

A: Only few methods

*

*You can sketch a graph if possible, this is most useful.

*You can use intermediate value theorem.

*You can also integrate the function and check if $f(b)=f(a)$, then f'(x) will surely have a solution(rolles theorem).

May be there are many others but these are the primary ones.......


text:
Q: iPhone 5 backup to iCloud not starting I have tried to start my back up manually because the automatic back up isn't working for some reason. The last backup was June 3, 2015. I have the icloud backup on and I have plenty of space in my icloud!

A: In- order to Fix the Automatic iCloud Backup not Working issue on iPhone do the following steps ;
Step:1
Delete your iCloud profile in iPhone
Step:2
Now again reconnect the icloud profile
Step:3
Now you get message sync automatically..
Well also , check this below article to troubleshoot this issue ;
https://support.apple.com/en-in/HT203271
Hope this helps...


text:
Q: Variadic template argument list with changing return type I am trying to make a templated variadic with a changing return type.
If the number of arguments is 1 then it should return a pointer to the only argument, otherwise it should return a tuple of pointer of the argument:
int var = 0;
A *ptr_A = foo<A>(var);
auto *[ptr_A, ptr_B] = foo<A, B>(var);

and this is the code i have so far
template<typename T>
T* AddComp(EntityId entityID)
{
    componentPool<T>* pool = GetOrCreatePool<T>();
    return pool->Create(entityID);
}

template <typename... Args>
decltype(auto) AddComponent(EntityId entityID)
{
    if constexpr (sizeof...(Args) == 1)
    {
        return AddComp <Args>(entityID);
    }
    else
    {
        return std::tuple<decltype(AddComponent<Args>({}))... > {AddComponent<Args>(entityID)...};
    }
}

But i am getting several errors:
In case of A *ptr_A = foo<A>(var); VS says that he cannot convert from void to A*, which says that decltype(auto) is somehow becoming void
And in return AddComp <Args>(entityID); VS says that Args parameter pack must be expanded. Do i still need to somehow expand Args even if its a single parameter?
Thank you!
Edit:
As asked i am providing a minimal example
using EntityId = size_t;

class A
{
public:

int a;
};

class B
{
public:

int b;
};

class componentsManager
{

public:

template<typename T>
T* AddComp(EntityId entityID)
{
    return new T();
}

template <typename... Args>
decltype(auto) AddComponent(EntityId entityID)
{
    if constexpr (sizeof...(Args) == 1)
    {
        return AddComp <Args>(entityID);
    }
    else
    {
        return std::tuple<decltype(AddComponent<Args>({}))... > {AddComponent<Args>(entityID)...};
    }
}

};

componentsManager m_manager;
EntityId id;

A *ptr_A1 = m_manager.AddComponent <A>(id);
auto *[ptr_A2, ptr_B] =  m_manager.AddComponent<A, B>(id);// This will only compile in c++17 i believe, i am using c++14

Edit2:
Error i get in VS 2019

A: The straightforward
if constexpr (sizeof...(Args) == 1)
{
    return AddComp<Args...>(entityID);
}

appears to work just fine. Clang demo, MSVC demo

Here's a solution that works with C++14:
template <typename T>
decltype(auto) AddComponent(EntityId entityID)
{
  return AddComp<T>(entityID);
}

template <typename... Args>
decltype(auto) AddComponent(
    std::enable_if_t<(sizeof...(Args) > 1), EntityId> entityID)
{
    return std::tuple<decltype(AddComponent<Args>({}))...>{
        AddComponent<Args>(entityID)...};
}

Demo


text:
Q: Installing Ubuntu 14.04--Grub Rescue Error after failing to turn off secure boot Whenever I try to start my computer it shows the following error:
file /boot/grub/i386-pc/normal.mod not found
Entering rescue mode...
grub rescue>

I tried installing Ubuntu 14.04 onto my computer which was preloaded with windows 8.1. My goal was to make this a dual boot.
I primarily followed these instructions
I accidentally skipped step 5, which was turning off secure boot, and is most likely what led to my current error. Ubuntu installed on my computer but I was unable to run it past the live session which prompted me to try out Ubuntu and/or install it again. But now I can't even get there.
In frustration, I removed my flash drive and that is when I arrived at this screen, which I can't seem to get out of.
If helpful, entering the command ls on the grub rescue mode prompt outputs:
 (hd0) (hd0,gpt 12) (hd0,gpt 11) (hd0,gpt 10) (hd0,gpt 9) (hd0,gpt 8)... (hd0,gpt 2)
 (hd0,gpt 1)

set outputs:
cmdpath=(hd0) prefix=(hd0,gpt10)/boot/grub root=hd0,gpt10

These are the only two commands that work (that I know of). I've tried things like, quit, exit, lsmod, but none have worked.

A: So I just now was able to successfully make my laptop a dual boot.
The way I got rid of the grub rescue prompt was actually by changing my boot mode from Legacy Mode to UEFI. I did this by booting into the bios menu when I turned on my computer by pressing f2 (for me). I then scrolled over to Boot and switched this under the Boot Mode option.
This got rid of the grub rescue screen upon powering up my machine. When I turned it on, it took me straight into Windows with no option to choose Ubuntu. My next step was to disable secure boot (see http://technet.microsoft.com/en-us/library/dn481258.aspx for more info on this).
NOTE: the disable secure boot option does not appear until after you switch to UEFI. I was now able to turn Secure Boot Off. The way to do this was also on the BIOS menu. I simply scrolled left to the Security tab (NOTICE: you should see an option for Secure Boot on the Bottom. You need not disable this, since my next instruction will disable it). I scrolled all the way down to Reset to Setup Mode and pressed enter. This Clears PK, disables Secure Boot (see for yourself on that screen) and enters Setup Mode. On a side note: I tried simply disabling Secure boot many times, saving it each time but this did not change anything when I restarted my computer (still booted to Windows automatically).
After this, when I rebooted I had the option to choose Ubuntu or Windows (since Ubuntu was already installed).
I did this on a Lenovo P400. My understanding is that this whole UEFI thing is unique to new operating systems, including but not limited to Windows (8 and 8.1)


text:
Q: Bokeh show() not opening in default browser Till an hour ago, upon running my program which has a Bokeh show(plot) statement, the plot used to show in Chrome which is the default browser. However, the same program and statement are now causing Firefox to open up and half of the time Firefox won't show any plot. I am using Spyder 3.1.4 on MacOS Sierra. I checked inside Chrome settings and it shows that Chrome is the default browser. I also checked on General settings in System Preferences where Chrome is showing as the default browser. Uninstalling Firefox and then running the program causes the plots to show in Safari (where the plots at least show up all the time). Is there a way to get the plots to show on Chrome ?

A: Bokeh uses the Python standard library webbrowser module. If it's opening up something besides Chrome, then that's because Python itself has decided that Chrome is not the default browser (for whatever reason, I can't speculate).
However, if you refer to the documentation, you can see that show accepts a browser parameter:
show(browser="chrome")

which will let you specify any browser you like instead of using whatever the Python default is.
Alternatively, there is an environment variable you can set:
BOKEH_BROWSER="chrome" python foo.py

A: There's a bug with the latest version of MacOS' osascript application which is causing a bug in webbrowser.
You can see chatter about it here:
https://bugs.python.org/issue30392


text:
Q: Simple update/edit of data not working with PHP/MySql I am trying to do a simple edit/update of my data in the database. But somehow it will not work.
So I am able to read out the saved data into the form. I also don't have any errors

I have stared at my code and googled for hours but I don't see where I might have made a mistake with my code.
The printed echo gives the following output which seems to be right:

HTML code:
<form id="formAddCategory" class="FrmCat" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

        <input type="hidden" name="hiddenId" value="<?php echo $hiddenID ?>" />
        Category Name:
        <input type="text" class="form-control" id="recipient-name1" name="category" required="" value="<?php echo $category ?>" />

     <button type="submit" id="btnEditCat" class="btn btn-danger" name="editCategory">Save Category</button>
</form>

Part of my php code to edit/update:
<?php
//edit/update data to db
if(isset($_POST['editCategory'])){
  $categoryUpdate = mysqli_real_escape_string($con, $_POST['category']);
  $categoryID = mysqli_real_escape_string($con, $_POST['hiddenId']);
  $qry = "UPDATE tbl_Category SET category = $categoryUpdate WHERE category_id = $categoryID";
  $result = mysqli_query($con, $qry);
  echo $qry;

  if($result){
    header("Location: category.php");
  }
}

?>

A: You need single quote ' to wrap your parameter:
$qry = "UPDATE tbl_Category SET category = '$categoryUpdate' WHERE category_id = '$categoryID'";

A: You should use single quotes (') for values
 $qry = "UPDATE tbl_Category SET category = '$categoryUpdate' WHERE category_id = '$categoryID'";

Also you can use like this to avoid SQL injection (See here)
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);

$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // do something with $row
}


text:
Q: Using live Linux or custom distros as backup? There are tools such as Remastersys (and possibly also Linux Live kit) for creating custom distros and live Linux systems. Is it possible to use them to create a complete system backup, i.e. preserving all configurations, group policies, security settings, network configurations (proxies, VPNs) etc.? Down to what level of detail is the source system reproduced, is it just the /home folder + user packages, or is it equivalent to a complete clone/image of the entire hard drive incl. partition structure? Does disk encryption have an effect, e.g. having LUKS on LVM?
PS.: FWIW, here is a screenshot of gnome-disk with partition information.

A: Clonezilla can create a complete image or cloned copy for you
Clonezilla is smart enough to copy only used blocks in the file systems (and skip free blocks), and there is compression, if you backup to an image. Clonezilla will also backup the bootloader and partition table. A clonezilla image is a directory with a set of files.
I have used this method for years, and I have restored from the backup to a fresh drive (of at least the same size, not one single byte smaller). Do not boot with both the original drive and the cloned copy connected - it can damage both systems! But when the original drive is removed, or if you restore from the backup to the original drive, it will boot (and behave exactly like the system that was backed up.
Instead of making a [compressed] image, you can clone directly to another drive (of at least the same size, not one single byte smaller). Then you can replace the original drive with the cloned copy and it will work just like the original one.
I think compression is automatic when you create an image, but when you clone directly, there will be no compression. (I think a cloned copy is a waste of drive space, so I store compressed images.) You pick the method that works best for you.
Finally, you should play safe - so test that you get everything correct, test that the backup really works now. Do not wait until the original drive fails, it might be too late to fix a failed backup


text:
Q: Get Frisby.js tests to run synchronously I have these API calls in my test that need to run first so I can store the response in a variable to use later. But it looks like my tests are running asynchronously so the second test finishes before the variable gets populated. How can I make the tests run synchronously?
I've heard that one way is to use before and passing the done callback. But I'm not sure how to do that with jasmine-node.
Example of test:
var dataID = '';
frisby.create('Get ID')
  .get(url)
  .expectStatus(200)
  .afterJSON(function(json) {
     dataID = json.id;
  })
.toss();

frisby.create('Get data with ID')
  .get(url, id)
  .expectStatus(200)
  .expectJSON({"id": dataID})
.toss();

EDIT:
So I tried doing my test like this and the done() callback doesn't seem to get called. (The test times out)
describe('API TEST', function() {
  beforeEach(function(done) {
    frisby.create('Get ID')
      .get(url)
      .expectStatus(200)
      .afterJSON(function(json) {
        dataID = json.id;
        done();  //?
      })
      .toss()
  });
  it('should work', function() {
    console.log('TEST');
  }); //"timed out after 5000 msec waiting for spec to complete"
});

A: What I ended up doing was using the async library and doing .timeout(60000) on the actual frisby test like so:
async.series([
  function(cb) {
    frisby.create('Get ID')
      .get(url)
      .expectStatus(200)
      .afterJSON(function(json) {
        dataID = json.id;
        cb();
      })
      .toss();
  },
  function() {
     //other tests using id
  }
]);

A: Jasmine handles asynchronous tests by passing a special done parameter to the test function as an argument -- you have to call done (ie done()) when the asynchronous part finishes.
Here is an example test using done:
describe('my test', function() {
  it('completes on done', function(done) {
    var a = 10;

    // this would normally be a call to the code under test
    setTimeout(function() {
      a = 20;
    }, 250);

    setTimeout(function() {
      expect(a).toEqual(20);
      done();
    }, 1000);
  });
});

In the case of frisby.js, it appears that asynchronous testing is surprisingly still an issue. See the issues on the github repo:
open frisby issues involving async

A: This is a little late but in case someone else might have the same question.
You can nest the second test into the afterJson() of the first test like this to make sure it runs after the first one is done
frisby.create('Get ID')
  .get(url)
  .expectStatus(200)
  .afterJSON(function(json) {
     var dataID = json.id;
     frisby.create('Get data with ID')
        .get(url, id)
        .expectStatus(200)
        .expectJSON({"id": dataID})
    .toss()
  })
.toss();

A: I did smaller modification for me in this function but this works for adding node with escape character in xml
private void somefunctToReplaceTxtinExistingNode(Node tempNode, String texttobeSet){
    String newtext = "<" + tempNode.getNodeName() + ">" + texttobeSet + "</" + tempNode.getNodeName() + ">";
    // create of new temp document .node will be imported from this
    DocumentBuilderFactory dbf = ....
    DocumentBuilder builder = ..
    Document newDoc = builder.parse(new StringBufferInputStream(texttobeSet));

    Node nodeXmlWithEscapeChars = newDoc.getFirstChild();
    // Import the node in old doc
    Document document = tempNode.getOwnerDocument();
    Node impNode = document.importNode(nodeXmlWithEscapeChars, true);
    // lastly . delete old with
    Node parent = tempNode.getParentNode();
    parent.removeChild(tempNode);
    parent.appendChild(impNode);
}


text:
Q: Using $index with the AngularJS 'ng-options' directive? Say that I bind an array to a select tag using the following:
<select ng-model="selData" ng-options="$index as d.name for d in data">

In this case, the associated option tags are assigned a sequence of index values: (0, 1, 2, ...). However, when I select something from the drop-down, the value of selData is getting bound to undefined. Should the binding actually work?
On the other hand, say that I instead do the following:
<select ng-model="selData" ng-options="d as d.name for d in data">

Here, the option tags get the same index, but the entire object is bound on change. Is it working this way by design, or this behavior simply a nice bug or side-effect of AngularJS?

A: Since you can't use $index but you can try indexOf.
HTML
<div ng-app ng-controller="MyCtrl">
    <select
          ng-model="selectedItem"
          ng-options="values.indexOf(selectedItem) as selectedItem for selectedItem in values"></select>
    selectedItem: {{selectedItem}}
</div>

Controller
function MyCtrl($scope) {
    $scope.values = ["Value1","Value2"];
    $scope.selectedItem = 0;
}

Demo Fiddle
Comment:
Array.prototype.indexOf is not supported in IE7 (8)

A: You can also use ng-value='$index' in <option> tag.
<select ng-model="selData">
 <option ng-repeat="d in data track by $index" ng-value="$index">
   {{d.name}}
 </option>
</select>

A: $index is defined for ng-repeat, not select.  I think this explains the undefined.  (So, no, this shouldn't work.)
Angular supports binding on the entire object.  The documentation could be worded better to indicate this, but it does hint at it: "ngOptions ... should be used instead of ngRepeat when you want the select model to be bound to a non-string value."

A: Since arrays are very similar to objects in JavaScript, you can use the syntax for "object data sources".  The trick is in the brackets in the ng-options part:
var choices = [
  'One',
  'Two',
  'Three'
];

In the template:
<select
  ng-model="model.choice"
  ng-options="idx as choice for (idx, choice) in choices">
</select>

In the end, model.choice will have the value 0, 1, or 2.  When it's 0, you will see One; 1 will display Two, etc.  But in the model, you will see the index value only.
I adapted this information from "Mastering Web Application Development with AngularJS" by PACKT Publishing, and verified at the Angular reference documentation for select.

A: Don't use $index inside select tags. Use $index inside the option tags if you want to use the array indexes as either values or options.
<option ng-repeat="user in users" value="{{user.username}}">{{$index+1}}</option>

If you want to use inside values just put it in the value attribute as binding expression like
<option ng-repeat="user in users" value="{{$index+1}}">{{user.username}}</option>

and my controller code be like:
var users = ['username':'bairavan', 'username':'testuser'];


text:
Q: Adding pointers to objects to a vector I am trying to add pointers to an object to a vector in a function like this:
vector:
vector<struct Node*> vars;

function:
void fill_vec(){
    struct Node* temp;
    temp = new Node();
    cout << token << endl;
    temp->name = token;
    temp->value = 0;
    cout << temp << endl;
    vars.push_back(temp);
}

fill_vec is being called in a while loop that stops when there aren't anymore variable names.
It is adding the correct amount of nodes to the vector, but everything is pointing to the same object. Token is being parsed.
output of above:
a
0x9c6010
b
0x9c6050

printing vector:
void print_vars(){
    for(int i = 0; i < vars.size(); i++){
        cout << "Name:" << vars[i]->name << endl;
        cout << "Value:" << vars[i]->value << endl;
    }
}

output:
Name:b
Value:0
Name:b
Value:0

My thought was that when I allocated new memory, the address would change. When I print the address of temp each time I call the function, the address is the same. I was printing the address wrong. The address is different for each call of the function. Thank you in advance for the help.

A:
My thought was that when I allocated new memory, the address would change.

It does indeed.

When I print the address of temp each time I call the function, the address is the same.

That is because you are printing out the address of a local variable, which happens to reside at the same stack memory address each time fill_vec() is called.  You should be printing out the memory address of the allocated Node instead.
Change this line:
cout << &temp << endl;

To this:
cout << temp << endl;

A: As it turns out, it was the token. Token is a char* and I was not using strdup() on it. So every time I updated token, name was being changed in each object.


text:
Q: Forward user back to the previous page after login Can I send my user back to the previous page when he logins in Drupal ?
He can login from different pages in my website. There is not only one login node. I would like to send him back to the page where he was.
Thanks

A: Check out the Login Destination module. One of the configuration options for that module is "Return user to where he/she came from. (Preserve destination)", and I believe it's enabled by default.
Also helpful is LoginToboggan, which offers a few more login/registration tweaks. LoginToboggan includes an option for a "Login successful" message, which is good way to make sure your newly logged-in users don't get confused when they get redirected back to the previous page.

A: $form_state['redirect'] is one way to do it. Set it in your submit handler. You could also use the destination URL param. URL?destination=X.


text:
Q: How to bound the input parameters to a chaotic function to obtain exact result in a finite precision setting? While I was reading the paper entitled (http://dx.doi.org/10.1109/ISCAS.2003.1204947)

Kocarev, Ljupco, and Zarko Tasev. "Public-key encryption based on
  Chebyshev maps." Circuits and Systems, 2003. ISCAS'03. Proceedings of
  the 2003 International Symposium on. 2003.

I encountered a table, Table 1, on page III-30 which has bounded the values of two parameters as follows (N denotes the number of bits used in gnump to do multiprecision computations):
----------------------------------
| N-bit precision | $r_0$, $s_0$ |
----------------------------------
| 256             | ~ $2^{70}$   |
----------------------------------
| 512             | ~ $2^{190}$  |
----------------------------------
| 1024            | ~ $2^{450}$  |
----------------------------------
| 2048            | ~ $2^{970}$  |
----------------------------------

The chebyshev polynomials of the first type are defined recursively as
$$
T_n(x) = 2xT_{n-1}(x) - T_{n -2}(x), \ \ n \geq 2
$$
by starting points $T_0(x) = 1$ and $T_1(x) = x$ for $n \in \mathbb{N}$ and $x \in [-1,1]$.
These parameters are bounded to make $T_{r_0}(T_{s_0}(x))$ without errors. This is where my question arises! How did they obtain this bound?
I understand that the result of multiplying these two numbers with certain bits should not exceed the precision, however, there is a gap, i.e. $70 + 70 = 140 < 256$.

Besides, the intuition of facing such a problem is as follows:
In this paper, there are two parties $A$ and $B$, who share a value $x \in   [-1,1]$ and $B$ wants to send a message to $A$, using $A$'s public key, $(x, T_{s_0}(x))$. Note that $s_0$ is the $A$'s private key.
Party $B$ chooses a random $r_0$ as ephemeral key and then computes $Z = T_{r_0}(T_{s_0}(x))$ and encrypts a number like $M$ by $X = Z \times M$. Then, $(X, T_{r_0}(x))$ is sent as the encryption of $M$ to $B$.
Given that $A$ holds $s_0$, he can compute $Z' = T_{s_0}(T_{r_0}(x))$, which is equal to $Z$ by the semigroup property of Chebyshev. Then, he can recover $M$ by dividing $X$ by $Z'$.
If there are any errors in computing these values, the recovery of plaintext message fails!


text:
Q: Allocate constant strings in container contiguously Lets say I have a std::vector of const std::strings.
std::vector<const std::string> strs;

Now the default behavior here is that the actual string containers can be allocated anywhere on the heap, which pretty much disables any prefetching of data when iterating over the contained strings.
strs.push_back("Foo"); // allocates char block on heap
strs.push_back("Boo"); // allocates char block on heap

However, since the strings are "const" I would like the char blocks to be allocated contiguously or close to each other (when possible) in order to have the most efficient cache behavior when iterating over the strings.
Is there any way to achieve this behavior?

A: You need a custom allocator known as a memory region allocator. You can look on Wikipedia or Google for more information, but the basic idea is something akin to the hardware stack- allocate one large chunk and then simply increment the pointer to mark it as used. It can serve many contiguous requests very quickly but can't deal with frees and allocations- all freeing is done at once.

A: If it really is that simple - pushing strings that will never change, it is easy to write your own allocator. Allocate a large block of memory, set a pointer free to offset 0 in the block. When you need storage for a new string strncpy it to free and increase free with the strlen. Keep track of the end of the memory block and allocate another block when needed.

A: Not really.
std::string isn't a POD, it doesn't keep its contents "inside of the object". What's more - it doesn't even require to store its contents in a single memory block.
Also a std::vector (as all arrays) needs its contents to be of one type (= of equal size), so you can't make a literal "array" of strings of different lengths.
Your best shot is to assume a length and use std::vector<std::array<char, N> >
If you need really different lengths, an alternative is just a std::vector<char> for the data plus a std::vector<unsigned> for the indices where consecutive strings start.

Rolling your own allocator for the string is a tempting idea, you could base it on std::vector<char> and then roll up your own std::basic_string on it, then make a collection of those.
Note that you are actually depending much on a specific std::string implementation. Some do have an internal buffer of N chars and only allocate memory externally if the string length is bigger than the buffer. If that's the case on your implementation, you still wouldn't get a contiguous memory for the whole buffer of strings.
On that grounds, I conclude that with std::string you won't be generally able to accomplish what you want (unless you rely on a specific STL implementation) and you need to provide another string implementation to suit your needs.

A: A custom allocator is great, but why not store all the strings in a single std::vector<char> or std::string, and access the original strings by offset?
Simple and effective.

A: You can always write a private allocator (second template parameter for std::vector) that will allocate all the strings from a continuous pool. Also you can use std::basic_string instead of std::string (which is a private case of std::basic_string), which allows specifying your own allocator similarly. Generally I would say its a case of "premature optimization", but I trust you've measured and saw a performance hit here... I believe the price to pay would be some memory wasted, though.

A: A vector is guaranteed to be contiguous memory and is
interoperable with an array. It is not a singly linked list.
"Contiguity is in fact part of the vector abstraction. It's so important, in fact,   the C++03 standard was amended to explicitly add the guarantee."
Source : http://herbsutter.com/2008/04/07/cringe-not-vectors-are-guaranteed-to-be-contiguous/
Use reserve() to force it to be contiguous and not reallocate.
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
using namespace std;

int main()
{
    // create empty vector for strings
    vector<const string> sentence;

    // reserve memory for five elements to avoid reallocation
    sentence.reserve(5);

    // append some elements
    sentence.push_back("Hello,");
    sentence.push_back("how");
    sentence.push_back("are");
    sentence.push_back("you");
    sentence.push_back("?");

    // print elements separated with spaces
    copy (sentence.begin(), sentence.end(),
          ostream_iterator<string>(cout," "));
    cout << endl;

return 0;
}


text:
Q: How to parse .stl file in Java with best performance? I got the following .stl file, that I'd like to parse and extract the coordinates:
solid WEMtoSTL_0
facet normal 0.999309 0.0262812 0.0262796
outer loop
vertex -49.9111 85.733 -1357.76
vertex -49.9346 86.6265 -1357.76
vertex -49.9346 85.733 -1356.86
endloop
endfacet
facet normal 0.999158 0.0290085 0.0290067
outer loop
vertex -49.9346 85.733 -1356.86
vertex -49.9346 86.6265 -1357.76
vertex -49.9633 86.6745 -1356.82
endloop
endfacet
facet normal 0.996327 0.0262471 0.0815064
outer loop
vertex -49.9346 85.733 -1356.86
vertex -49.9633 86.6745 -1356.82
vertex -50.0151 85.733 -1355.88
endloop
endfacet
endsolid WEMtoSTL_0

The facet and endfacet tags can be repeated as much as needed.
This is what I tried:
Scanner face_scanner = new Scanner(file);
face_scanner.useDelimiter("solid | facet normal | outer loop | vertex | endloop | endfacet");

But face_scanner.next() doesn't result in the following that I want to get:
0.999309 0.0262812 0.0262796
-49.9111 85.733 -1357.76
-49.9346 86.6265 -1357.76
-49.9346 85.733 -1356.86
and so on...

Edit:
I tried now the following:
Scanner face_scanner = new Scanner(file);
face_scanner.useLocale(Locale.US);
face_scanner.useDelimiter("\\s|\n");

while (face_scanner.hasNext()) {
    if (face_scanner.hasNextFloat()) {
        float curr = face_scanner.nextFloat();
    } else {
        String s = face_scanner.next();
    }
}

For my example file with 22402 lines this takes more than 2 minutes. Is it possible to do it in a few seconds or even less? 2 minutes is far too much for me.

A: Antlr would be a good alternative; It has good performance/memory characteristics, and all of the low level tokenization is handled by for you.
There's a grammar here (Disclaimer: I am the author) for the STL ASCII format.
It's part of a larger project that has a Java STL model, see here (Disclaimer: I am the author of this too). A quick test shows a 5.5 second parse time for a ~19MB STL file.


text:
Q: .htaccess edit middle of URL I'm trying to change a specific section of a URL, rewriting the request via .htaccess commands. I just want to change one specific part of it, but the value of that part can vary. The initial URL would be something like:
http://www.domain.website.com/hello/search
Given this, how would I replace hello, knowing it won't always be hello. I've been using htacces.madewithlove.be in order to test my solutions but I've only found things that can append to the end of replace the entire thing
I should also clarify that this is specifically going to have to be in the RewriteCond RewriteRule format. So an expression that would replace the whole thing would be like the following:
RewriteCond %(HTTP_HOST) ^example(A-Za-z0-9\.]*)\.com [NC]
RewriteRule ^(.*)$ http://www.new-website.com/$1

and the result would be http://www.new-website.com/

A: Considering the word you want to replace is the first word after origin, you can use this
(https?:\/\/[^\/]+\/)[^\/]+(\/.*)?

Regex Demo


text:
Q: How to handle ews hang? Sometimes it hangs when you receive email, and because of this, the whole program hangs, how can I check is service hang?
ExchangeService service = new Sender().GetService(sourceEmail);
SearchFilter filter = new
SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
ItemView view = new ItemView(20) { PropertySet = PropertySet.IdOnly };
if (oldest) view.OrderBy.Add(ItemSchema.DateTimeReceived,SortDirection.Ascending);
FolderId sharedMailbox = new FolderId(WellKnownFolderName.Inbox, sourceEmail);

/* hangs on this call */
FindItemsResults<Item> findResults = service.FindItems(sharedMailbox, filter, view);

A: I had an issue where FindItems did hang,
It seems to have been related to that I had a StreamingSubscriptionConnection object that I didn't close.


text:
Q: Is there a way to show image inside text in flutter I have this code to show an image inside text in flutter but when I'm using ImageShader.
I'm getting this error
The method 'asset' isn't defined for the type 'Image'.  Try correcting the name to the name of an existing method, or defining a method named 'asset'
I have also referred to this Repo. This repo link was given in previously asked question on StackOverflow about ImageShader.
I know "dart:ui" doesn't contain any asset method. So I used Image.asset but when I used this method I got this error.

The argument type 'Image (where Image is defined in
/Users/username/Developement/flutter/packages/flutter/lib/src/widgets/image.dart)'
can't be assigned to the parameter type 'Image (where Image is defined
in
/Users/username/Developement/flutter/bin/cache/pkg/sky_engine/lib/ui/painting.dart)'

Link to the similar question asked on stackoverflow
 import 'dart:ui' as ui;
    class _MyAppState extends State<MyApp> {
  Float64List matrix4 = new Matrix4.identity().storage;
  ui.Image img;

  Future<ui.Image> getImage() async{
    img = await ui.Image.asset("assets/images/ob_girl_cropped.png"); // This Line Is showing error. Please Help.
  }
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(
        body: Center(
          child: FutureBuilder(
            future: getImage(),
            builder: (context, snapshot)
            {
              if(snapshot.hasData){
                return Text(
                  'Greetings, planet!',
                  style: TextStyle(
                    fontSize: 40,
                    foreground: Paint()
                      ..shader = ImageShader(
                          img,
                          TileMode.clamp,
                          TileMode.clamp,
                          matrix4),
                  ),
                );
              }
              else{
               return CircularProgressIndicator();
              }
            },
          ),
        ),
      ),
    );
  }
}

A: Two problems:

*

*The way you load image, which I wrote a loadImageFromFile helper funtion

*You should not put getImage() directly in to future field, because flutter will create a new future every time you rebuild the page (so load the image multiple times)

Full Code:
import 'dart:typed_data';
import 'package:flutter/services.dart' show rootBundle;

import 'package:flutter/material.dart';
import 'dart:ui' as ui;

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Float64List matrix4 = new Matrix4.identity().storage;
  Future<ui.Image> imgFuture;

  // New helper function
  Future<ui.Image> loadImageFromFile(String path) async {
    var fileData = Uint8List.sublistView(await rootBundle.load(path));
    return await decodeImageFromList(fileData);
  }

  @override
  void initState() {
    imgFuture = loadImageFromFile("assets/images/ob_girl_cropped.png"); // Works now
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(
        body: Center(
          child: FutureBuilder(
            future: imgFuture,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(
                  'Greetings, planet!',
                  style: TextStyle(
                    fontSize: 40,
                    foreground: Paint()..shader = ImageShader(snapshot.data, TileMode.clamp, TileMode.clamp, matrix4),
                  ),
                );
              } else {
                return CircularProgressIndicator();
              }
            },
          ),
        ),
      ),
    );
  }
}


text:
Q: Trying to call function in DLL - translation from C to Delphi I have to access a DLL with Delphi, but have only the .h file. Most functions are translated and work flawless, but not this part:
FUNCTION_PRE64 ULONG FUNCTION_PRE OpenModuleEx
(
    ULONG moduleID,
    ULONG nr,
    unsigned char *exbuffer,
    ULONG open_options
);

typedef struct
{
    unsigned char address[256];
    ULONG timeout;
    ULONG portno;

    ULONG encryption_type;
    unsigned char encryption_password[32];
} DAPI_OPENMODULEEX_STRUCT;

My translation to Delphi is:
function OpenModuleEx
(
    moduleID:Longint;
    nr:Longint;
    &buffer: exbuffer;
    open_options: longint
): Longint; stdcall; external 'master.dll'

type exbuffer = packed record
    address : array of byte;
    timeout : Longint;
    portno : Longint;

    encryption_type : Longint;
    encryption_password : Array of byte;
end;

I fill the record and call the function:
BinarySize := (Length('10.241.0.147') + 1) * SizeOf(Char);
SetLength(buffer.address, BinarySize);
Move('10.241.0.147'[1], buffer.address[0], BinarySize);
buffer.portno := 9912;
buffer.timeout := 5000;
buffer.encryption_type := 0;
BinarySize := (Length('') + 1) * SizeOf(Char);
SetLength(buffer.encryption_password, BinarySize);
Move(''[1], buffer.encryption_password[0], BinarySize);

lhandle := OpenModuleEx(42, 0, &buffer, 0 );

...but the returned handle is always 0.
I'm no C expert and also no Delphi expert. My Delphi version is XE7. Who can help me to translate the struct to Delphi and how to fill it?

A: The Delphi record translation is incorrect. It should be:
type
  exbuffer = record
    address : Array [0..255] byte;
    timeout : Cardinal;
    portno : Cardinal;
    encryption_type : Cardinal;
    encryption_password : Array [0..31] byte;
  end;

The record should not be packed. ULONG maps to an unsigned 32 bit type. And the arrays must be fixed length arrays.
The function declaration is wrong too. It should be:
function OpenModuleEx(
    moduleID: Cardinal;
    nr: Cardinal;
    exbuffer: PByte;
    open_options: Cardinal
): Cardinal; stdcall; external 'master.dll';

It also may be that the function should be cdecl rather than stdcall, we cannot tell.


text:
Q: How to eject Windows 7 DVD when installing on MacBook Pro? During the installation process of Windows 7 on my MacBook Pro, it asks me to eject the DVD so that I can put in a disk with drivers.  I have the driver disk but I can't figure out how to eject the DVD.  Pressing a holding the eject button doesn't seem to do anything.

A: Write the .iso at 2x not 8x, so that the MacBook can read it and doesn't need you to insert another disk.


text:
Q: Linux - Sort based on 2 fields names I have several txt files "file_i.txt" that look like this:
id, size, price, colour
1, 2, 10, black
2, 8, 5, blue
...

All the files contain those fields, but the fields order may be different.
I would like to sort every file based on two features, price first and then size. I know it is possible to use the command sort to sort on two fields in this way:
sort -k2,3 -k1,2 file_i.txt

However, as the field position is different in every file, is there a way to sort based on the field name instead?
Thanks

A: Basically the sort command should look like this:
sort -k3n -k2n input

where N in -kN is the number of the key, and n means sort numeric.
sort can't sort by field names. You need to get the column number somehow. I'm using awk for that:
kprice=$(awk -F', ' -vfield=price 'NR==1{for(i=1;i<=NF;i++){if($i==field){print i;exit}}}' a.txt)
ksize=$(awk -F', ' -vfield=size 'NR==1{for(i=1;i<=NF;i++){if($i==field){print i;exit}}}' a.txt)

sort -k"$kprice"n -k"$ksize"n a.txt

A: I think you have to write a script by yourself, say "mySort" and launch as:
./mySort "id" "size"

Pseudocode, assuming that the first line of file contains "column" name:
read input list
for each element in list, save the position (parsing first line)
apply sort

A: you could do some preprocessing:
for each file:

*

*transpose file

*sort on first column (the names)

*revert the transposition

Then, all columns will be ordered the same way and you can use your standard sort approach.

Transposing a file in bash is already solved in other questions here on SO:

*

*An efficient way to transpose a file in Bash

*https://unix.stackexchange.com/questions/79642/transposing-rows-and-columns


text:
Q: How do I connect a remote Windows machine by Java? I want to connect to a remote Windows desktop machine from a local machine with a Java program.
I have to check the disk space and several other services on the remote machine.

A: Remote Desktop Connection
Java
// Creating credentials
Process p = Runtime.getRuntime().exec("cmdkey /generic:" + ip +
                                      " /user:" + userName +
                                      " /pass:" + password);
p.destroy();

Runtime.getRuntime().exec("mstsc /v: " + ip + " /f /console");

Thread.sleep(2*60*1000); // Minutes seconds milliseconds
// Deleting credentials
Process p1 = Runtime.getRuntime().exec("cmdkey /delete:" + ip);
p1.destroy();

*

*By using cmdkey we can create or delete our credentials which specific to current user.

Command line
C:> cmdkey /generic:192.168.0.11 /user:XXXXX /pass:XXXXX
     CMDKEY: Credential added successfully.
C:> mstsc.exe /v:192.168.0.11 /w:800 /h:600
     Connecting to Remote Desktop.
C:> cmdkey /delete:192.168.0.11
     CMDKEY: Credential deleted successfully.

A: You could also consider an RDP Java solution.
There are a lot of solutions out there. Check them out on Comparison of Java Remote Desktop projects.

A: The answer depends upon what operating system your local machine (host) is using to connect to your remote target Windows box.
If it is a Unix-based box, I would recommend using the open source library j-Interop.
Note, that you may need to manually modify the registry on the target box, so it can work correctly (make sure you peruse the FAQs of the project's website). If you find weird issues (exceptions thrown while connecting), here's a good article that helped me resolve them: Windows slaves fail to start via DCOM
On the other hand, if you are using a Windows box as your host, then your life will be much easier. I would recommend using:

*

*JACOB

*jWMI

*Jawin
Note that all of the above are opensource projects.
The freeware version out there as mentioned above is j-Integra, but I never tried using it.

A: You could install an SSH server on your remote desktop and you can write a Java program using jcraft and jsch libraries on your local machine to make an SSH  connection to your remote desktop.


text:
Q: Hide/Show function not working on Javascript Here's my load function
        $("html").load(function(){
            $.post("DumpsterService.php", function(result){     //da mettere url
                $("h2").append(data).each;
                });
            });

            $("#QuantitaDep").hide();
            $("#NumDepositi").hide();
        });

But when I load the page, everything is showen, I've also tried with ("canvas#QuantitaDep") and ("canvas#NymDepositi") but still not working
Here the canvas:

Numero depositi:

        <canvas id="NumDepositi" width="300" height="100"></canvas>

I shared only one of the canvas cause they are the same but
<canvas id="QuantitaDep" width="300" height="100"></canvas>
Please help me, I'm not understanding

A: You can try with:
$(document).ready(function() {

instead of:
$("html").load(function(){

Also try to load your JS snippet just before the  tag, and if still not working, try to move it before your   tag.
You should debug first if your jQuery is loading properly, you can try this adding this code between your  tags, with:

and open your browser console (F12 in Chrome) and check the console log, you should see document loaded or window loaded if your JS dependencies are fine.
jQuery documentation: https://learn.jquery.com/using-jquery-core/document-ready/
You can try to load your <canvas> elements with no visibility by default just using CSS:
<canvas id="NumDepositi" name="NumDepositi" width="300" height="100" style="display:none;visibility:hidden;"></canvas>

and change to visible onClick with JS:
$('#NumDepositi').click(function() {
        $("#NumDepositi").show();
        $("#NumDepositi").css('visibility','visible');
        $("#NumDepositi").css('display','block');
    /* you can use 'this' instead, like:
        $(this).show();
        $(this).css('visibility','visible');
        $(this).css('display','block');
    */
});


text:
Q: I used SvcUtil to create classes from WSDL. What do I deserialize into? I used svcUtil.exe to create classes from https://gw.sam.gov/SAMWS/1.0/Entity?wsdl
but I cannot for the life of me find what to deserialize the result into? When I created my own classes the root is envelope but it isn't even in the new classes.
I can paste the classes but it is really long? Is there a general answer to this?
I will paste the classes upon request.
Thanks in advance...
The classes are over 10x too long to post.
Adding code for the pull:
static void Main(string[] args)
        {
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            var _url = "https://gw.sam.gov/SAMWS/1.0/Entity";

            //Run date is a specific date if provided otherwise use yesterday
            DateTime startDateTime = DateTime.Now.AddDays(-1).Date;

            for (int hr = 0; hr < 24; hr++)
            {
                XMLclassRequest xmlSoap = new XMLclassRequest();
                string soap = xmlSoap.BuildSOAPrequest(startDateTime.AddHours(hr));
                //string soap2 = xmlSoap.BuildSOAPrequest2(startDateTime.AddHours(hr));

                string response = null;   //This is the original pull with FAR and DFAR Responses
                //string response2 = null;  //This is FAR and DFAR

                using (MyWebClient client = new MyWebClient())
                {
                    client.Headers.Add("Content-Type", "text/xml;charset=utf-8");
                    client.Headers.Add("SOAPAction", "\"http://tempuri.org/IMyService/MyOperation\"");
                    try
                    {
                        response = client.UploadString(_url, soap);
                        //response2 = client.UploadString(_url, soap2);
                    }
                    catch
                    { } //This will skip the hour attempted and move to next. The error I have been receiving is no data which is differently formatted XML that causes the error

                }

                //File.WriteAllText(@"D:\temp\bigpull.xml", response);

                MemoryStream stream = null;
                if (response != null)
                {

                    byte[] byteArray = Encoding.Unicode.GetBytes(response);
                    stream = new MemoryStream(byteArray);
                }

                getEntities results;
                XmlSerializer serializer = new XmlSerializer(typeof(getEntities));
                try
                { results = (getEntities)serializer.Deserialize(stream); }
                catch
                { } //This will skip the hour attempted and move to next. The error I have been receiving is no data which is differently formatted XML that causes the error
                stream.Close();

                string str;
            }

The response is coming back. I just can't get it into an object to use.

A: I couldn't get this loaded into an object but ended up loading it to an XDocument and parsed that:
    var _url = "https://gw.sam.gov/SAMWS/1.0/Entity";

    //Run date is a specific date if provided otherwise use yesterday
    DateTime startDateTime = DateTime.Now.AddDays(-1).Date;

    for (int hr = 0; hr < 24; hr++)
    {
        XMLclassRequest xmlSoap = new XMLclassRequest();
        string soap = xmlSoap.BuildSOAPrequest(startDateTime.AddHours(hr));
        //string soap2 = xmlSoap.BuildSOAPrequest2(startDateTime.AddHours(hr));

        string response = null;   //This is the original pull with FAR and DFAR Responses
        //string response2 = null;  //This is FAR and DFAR

        using (MyWebClient client = new MyWebClient())
        {
            client.Headers.Add("Content-Type", "text/xml;charset=utf-8");
            client.Headers.Add("SOAPAction", "\"http://tempuri.org/IMyService/MyOperation\"");
            try
            {
                response = client.UploadString(_url, soap);
                //response2 = client.UploadString(_url, soap2);
            }
            catch
            { } //This will skip the hour attempted and move to next. The error I have been receiving is no data which is differently formatted XML that causes the error

        }

        //File.WriteAllText(@"D:\temp\far20190604.xml", response);

        XDocument xdoc = XDocument.Parse(response);

        var entities = from e in xdoc.Descendants("entity") select e;

        foreach (var e in entities)
        {
            string DUNS = e.Descendants("DUNS").FirstOrDefault().Value;
            var provisions = from p in e.Descendants("provision") select p;

            foreach (var p in provisions)
            {
                string ParentID = p.Descendants("id").FirstOrDefault().Value;
                var answers = from a in p.Descendants("answer") select a;

                foreach (var a in answers)
                {
                    var section = a.Descendants("section").Count()>0?  a.Descendants("section").FirstOrDefault().Value : "";
                    var answerText = a.Descendants("answerText").Count() > 0 ? a.Descendants("answerText").FirstOrDefault().Value : "";

                    Console.WriteLine(DUNS + " " + ParentID + " " + section + " " + answerText);

                }
            }
        }


text:
Q: Is it possible to get width of terminal or to print line with fill of 100% width? PHP. fputs(STDOUT, 'some short text')!
Is there any way to get char length for terminal that launch php script?
How to print text with fputs(STDOUT, "Some Error\n"); with full line background of red color?

A: This will output a line with "=" characters filling the whole line of the terminal. Will work on linux-based system.
// 'tput cols' is a shell command which returns
//   the number of chars to fill up the whole
//   line of the current terminal.
$colCount = shell_exec('tput cols');

// Create the string filling the whole line
$string = str_repeat("=", intval($colCount));

// This is the way to print out text with coloured background
// 48, 5, 160 representing 256-colour of red, green and blue.
fputs(STDOUT, "\e[48;5;160m".$string."\e[0m");

Which can be condensed to one line
fputs(STDOUT, "\e[48;5;160m".str_repeat("=", intval(shell_exec('tput cols')))."\e[0m");

Here's a script to ANSI color code in XTerm/ANSI-compatible terminals with a 256-color palette support if you want to know more about displaying colours on terminal.

A: You can use Symfony\Console for this, since it has Terminal class that does exactly what you need:
Install with composer
composer require symfony/console

Create script index.php
<?php

require __DIR__ . '/vendor/autoload.php';

$terminal = new Symfony\Component\Console\Terminal;

$terminalWidth = $terminal->getWidth();
var_dump($terminalWidth);

Test it
$ php index.php
int(80)


text:
Q: Where to put an artifact which will be used only by test I am developing a new feature for a well-established memory package. The feature Im implementing is about loading/copying/moving resources in and out to different type of structures like jars, libraries and so.
I started with writing tests first. I felt i need an test artifact, like a sample file/DLL/txt whatever, however, I do not know where to put it? What is the best practice to follow in this type of situation?

A: I would advise you to put it on your 'test' directory of your project, if the 'test' directory isn't flat (for instance 'mocks' 'unit' etc. as in Rails) I would create a directory called 'data'/'artifact' in there and put the file inside.
Moreover, please make sure to call the file in a name that corresponds to the actual test file. If this file is being used in many test files (with different names), I would advise you to document it so its' usage can be traced in case of cleanup/refactoring.
+There isn't a "best way" and each project is a special case, yet consistency and making it easier for future maintainers to make sense of this file can go a long way.


text:
Q: UEFI Dual boot not recognizing windows 7 partition? Been messing around with Ubuntu, I actually installed it as my only OS but since my graphics card(AMD) kinda sucks on linux(For gaming purposes) -  I have to have a windows partition.
However, dual-booting simply won't work out for me. I currently installed a fresh copy of Windows 7.. That's fine. When I run the Ubuntu installer, it just doesn't recognize Windows 7. I'm left with wiping the entire hard disk and installing only Ubuntu, or basically nothing else(well, there is the "something else", but it doesn't recognize windows either).
What do I do? It's a problem with the new UEFI bios as far as I understand, right?
I tried booting from both USB/SD and CD/DVD with the same result, so I suppose something is up with the file structure or the UEFI/legacy booting. But before I mess with the BIOS, I'd like a pointer to what I should do exactly? I've tried shrinking my hard drive into a 200GB partition which I thought Ubuntu would recognize(and then install on), but it only recognizes all 1TB I have..?
Thanks in advance!
http://i.imgur.com/on7K7uE.jpg
http://i.imgur.com/TcMEFM8.jpg