text:
Q: Checking a map statically at compile time? So, I'll preface this question with that I am not sure if this is even possible.
Anyways, I am attempting to have a static const map (or something similar) checked at compile time to verify it will have a matching value (an id in this case). Specifically, I currently have something bad like this (but it doesn't compile):
template<typename T>
struct TypeMapChecker
{
    static const std::map<std::type_info, MessageID> type_map;
    static const bool contains = (type_map.count(typeid(T)) > 0);
}

template<typename T>
const std::map<std::type_info, MessageID> TypeMapChecker<T>::type_map = {
    { typeid(ClassA), MESSAGE_A_ID },
    { typeid(ClassB), MESSAGE_B_ID }
};

..........

template<typename T0, typename T1>
class MessagePair
{
    static const bool t0Has = TypeMapChecker<T0>::contains;
    static const bool t1Has = TypeMapChecker<T1>::contains;
    static_assert (t0Has && t1Has, "I'M ASSERTING MY AUTHORITY, YOU MALIGNANT CODERS");
}

Something like that. This doesn't build because "expected a constant expression" at:
static const bool contains = (type_map.count(typeid(T)) > 0);

Just want to validate that when I access the type_map in MessagePair I am guaranteed a value at build time, and don't have to rely on runtime shenanigans since this is a large code base modified by many (and I can't stop them from doing bad things at runtime). Other implementations or any help would be greatly appreciated. Thanks.

A: Store the map as a type.
Use the type to build your runtime typeid map.
Here is the key-value pair for your compile-time map:
template<class Key, class Value>
struct entry {
  using key=Key;
  using value=Value;
};

We then make a map from it:
template<class T> struct tag_t{using type=T; constexpr tag_t(){};};
template<class T> constexpr tag_t<T> tag{};

template<class...Entries>
struct compile_time_map:Entries... {
  template<class Key>
  struct lookup {
    template<class Value>
    constexpr tag_t<Value> operator()( entry<Key, Value> const& ) const { return {}; }
  };
  template<class Key>
  constexpr
  std::result_of_t< lookup<Key>( compile_time_map ) > operator()( tag_t<Key> ) const {
    return {};
  }
  template<class...Key>
  constexpr std::false_type operator()( tag_t<Key...> ) const {
    return {};
  }
  template<class MessageID>
  std::map< std::type_index, MessageID > make_map() const {
    return { {typeid(typename Entries::key), typename Entries::value{}}... };
  }

  template<class Key>
  constexpr auto has(tag_t<Key> ={}) const {
    return std::integral_constant<bool, !std::is_same< std::result_of_t< compile_time_map(tag_t<Key>)>, std::false_type >{}>{};
  }
};

This map can generate a run-time map of a type of your choice.
using ID=unsigned;

template<class T, ID id>
using make_entry = entry<T, std::integral_constant<ID, id>>;

using ctm = compile_time_map<
  make_entry< int, 7 >,
  make_entry< double, 3 >,
  make_entry< std::string, (unsigned)-1 >
>;

auto rtm = ctm{}.make_map<ID>();

we can do compile-time lookups with ctm{}( tag<int> ).  We can do runtime lookups with rtm[ typeid(int) ].
We can check if there is an entry at compile time with ctm{}.has<int>() or ctm{}.has( tag<int> ).
live example.


text:
Q: preg_match wildcard, require at least one character The preg_match below matches 'empty' (0 characters) against the wildcard. I want to disable that:
preg_match('/site.com\/subsection\/.*?/', $page_url);

So the thing above should match site.com/subsection/subpage, but shouldn't match the root dir site.com/subsection/
How can I adjust the regex above? Thanks in advance!

A: The .*? at the end of the pattern matches empty string. You need to make it match one or more characters using .+:
'/site\.com\/subsection\/.+/'
                         ^

Now, it requires at least 1 char after site.com/subsection/.
Note the dot must be escaped to match a literal dot.
Also, it might be a good idea to use regex delimiters other than / (as OcuS suggests in the comments below) if you have many slashes in the pattern itself. I usually use tildes:
'~site\.com/subsection/.+~'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Function App keys noting being created for new Function App I'm deploying a Storage Account and Function App via an ARM template, but after a successful deployment, I'm unable to use the the Function App because no keys are being created.

We are not able to retrieve the runtime master key. Please try again later.

From what I understand (see this issue on GitHub), there should be a folder created in the associated Storage Accont that contains hosts.json: storage-account/azure-webjobs-secrets/function-app.  However, this folder does not exist.
I was hoping that upon deployment of a Function, hosts.json would be created.  I believe there should also be a file named FunctionName.json that contains Function specific keys, but still the aforementioned folder does not exist and neither does this file.  This leads to an additional error being displayed.

We are not able to retrieve the keys for function FunctionName. This can happen if the runtime is not able to load your function. Check other function errors.

Just in case anyone from MS picks this up, both errors should hopefully be recorded under Session ID a814072a75d643d89c71d64d20c3dd55.
Is there some bug with Function App deployment via an ARM template, or am I doing something wrong?

ARM Template
Can be found in this Pastebin
Example output
DeploymentName          : DEV-FunctionAppName
ResourceGroupName       : a-resourece-group
ProvisioningState       : Succeeded
Timestamp               : 02/10/2017 10:30:28
Mode                    : Incremental
TemplateLink            :
Parameters              :
                          Name                 Type                       Value
                          ===============      =========================  ==========
                          environment          String                     DEV
                          environmentSettings  Object                     {
                                                                            "applicationInsightsName": "service-name-app-insights",
                                                                            "functionAppName": "DEV-FunctionAppName",
                                                                            "storageAccountName": "servicenamedevstorene"
                                                                          }
                          serviceName          String                     Service Name
                          location             String                     northeurope
                          serverFarmName       String                     NorthEuropePlan
                          storageAccountSku    Object                     {
                                                                            "name": "Standard_GRS",
                                                                            "tier": "Standard"
                                                                          }
                          tags                 Object                     {
                                                                            "Application": "Service Name",
                                                                            "Environment": "DEV"
                                                                          }

Outputs                 :
DeploymentDebugLogLevel :


text:
Q: CSS different browser means different output I have a problem with my css.
When I open my page on IE and Firefox it shows up like this (just like it should)
http://tinypic.com/r/14ni5gk/6
But when I open my page on Safari it shows up like this:
http://tinypic.com/r/2mzdxed/6
(notice the last two boxes not floating next to eachother)
I have the following css code:
@charset "utf-8";

body{
    font-family:Verdana, Geneva, sans-serif;
    font-size: 12px;
}

#container{
    width: 600px;
    background: #fff;
}

#header{
    height: 151px;
    background-image:url('../img/tomaat.png');
    background-repeat: no-repeat;
    background-position:center;
}

#recent fieldset{
    width : 600px;
}

#stats fieldset{
    width : 600px;
}

#login fieldset{
    width : 200px;
    float: left;
    height: 150px;
}

#nieuw fieldset{
    width : 290px;
    float:left;
    height: 100px;
}

#verwijder fieldset{
    width: 289px;
    height:100px;
}

label {
    width: 50px;
    float: left;
}

#login label{
    width: 200px;
    float: left;
}

input {
    width: 200px;
}

#nieuw button{
    position:relative;
    top: 5px;
}

#verwijder button{
    position:relative;
    top: 27px;
}

#login button{
    width: 200px;
    position: relative;
    top:5px;
}

#a {
    position : relative;
    top: 43px;
}
#buttonz {
    text-align: center;
}

legend{
    font-weight: bold;
}

And the following index.php page:
<?php
    include_once("db.php");
    session_start();
    if (!isset($_SESSION['uid'])){
        header("location:main_login.php");
        exit();
    }
    if (!isset($_SESSION['upass'])){
        header("location:main_login.php");
        exit();
    }
    $sql="SELECT * FROM users WHERE Naam='".$_SESSION['uid']."' AND Wachtwoord='".$_SESSION['upass']."'";
    $result=mysql_query($sql);
    $count=mysql_num_rows($result);
    if($count < 1){
        header("location:main_login.php");
        exit();
    }

?>

<?php
    $date = date("y-m-d");
    $vandaag = mysql_query("SELECT Type, Naam, Reden, Door FROM turfjes WHERE turfjes.Datum = '" . $date . "'");
    $names = mysql_query("SELECT Naam From users");
    $names2 = mysql_query("SELECT Naam From users");
    $names3 = mysql_query("SELECT Naam From users");
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Tomaten turfjes pagina | 258</title>
        <link rel="stylesheet" type="text/css" href="css/style.css" media="all" />

                    <fieldset>
                        <legend>Vandaag</legend>

                            Type
                            Naam
                            Reden
                            Door
                            <?php
                                while($a = mysql_fetch_array($vandaag)){
                            ?>

                                    <?php echo($a['Type']);?>
                                    <?php echo($a['Naam']);?>
                                    <?php echo($a['Reden']);?>
                                    <?php echo($a['Door']);?>

                            <?php
                                }
                            ?>

                    </fieldset>

                    <fieldset>
                        <legend>Turfjesteller</legend>

                            Naam
                            Aantal
                            Gedaan
                            Resterend

                            <?php
                                while($r = mysql_fetch_array($names)){
                                echo("
");
                            ?>
                                    <?php echo($r['Naam']);?>
                            <?php
                                        $sql="SELECT * FROM turfjes WHERE Naam='".$r['Naam']."' AND Type='Adtje'";
                                        $result=mysql_query($sql);
                                        $count=mysql_num_rows($result); //count = adtjes
                                        $sql2="SELECT * FROM turfjes WHERE Naam='".$r['Naam']."' AND Type='Turfje'";
                                        $result2=mysql_query($sql2);
                                        $count2=mysql_num_rows($result2); //count2 = turfje
                            ?>
                                    <?php echo($count2);?>
                                    <?php echo($count);?>
                                    <?php echo($count2-$count);?>

                            <?php
                                }
                            ?>

                    </fieldset>

                    <fieldset>
                    <legend>Nieuwe turfjes</legend>
                        Naam
                        <select id = "naamnieuw">
                            <option value="" selected></option>
                            <?php
                                while($r = mysql_fetch_array($names2)){
                                    echo("<option value='".$r['Naam']."'>".$r['Naam']."</option>");
                                }
                            ?>
                        </select>

                        Reden <input type="text" name="redennieuw" id="redennieuw"/>

                        Door <input type="text" name="door" id="door" disabled="disabled" value =<?php echo($_SESSION['uid']) ?>>

<button type="button" id="submitnieuw">Turfje uitdelen</button>

                    </fieldset>

                    <fieldset>
                    <legend>Verwijderen turfjes</legend>
                        Naam
                        <select id = "naamverwijder">
                            <option value="" selected></option>
                            <?php
                                while($r = mysql_fetch_array($names3)){
                                    echo("<option value='".$r['Naam']."'>".$r['Naam']."</option>");
                                }
                            ?>
                        </select>

                        Door <input type="text" name="door" id="door2" disabled="disabled" value =<?php echo($_SESSION['uid']) ?>>

<button type="button" id="submitdelete">Turfje verwijderen</button>

                    </fieldset>

                <form name="logout" method="post" action="logout.php">

<input type="submit" name="logout" value="Log uit">

                </form>

The boxes are both in the div action
and are called nieuw and verwijder.
Nieuw is the first one, verwijder is the second one.
Can anyone tell me why this is happening and maybe even how to solve this problem?

A: Browsers have slightly different default settings for thing like padding, margins and font sizes for some elements (for example, the padding on a UL or the size of an H1)
A CSS reset clears these so you can use your own values.
There are many around. I like the Yahoo CSS Reset 2, and for HTML5 there's the HTML5 Boilerplate.


text:
Q: server unexpectedly closed network connection I am working on a Linux server which pop up's an error

"server unexpecdly closed network connection"

but I am able to ping it. Can anyone help me out with this?

A: Is SSH protocol/port being allowed in the server's firewall config?
Is the SSH daemon running on the server?
do you have the correct login details (password/keys)?

A: If you have bad luck, then the server is "pingable", but hangs (100% load in endless loop or whatever) and needs a reboot. Do you have any monitoring on the server?


text:
Q: getChildHtml inside of another .phtml file I have a local.xml file that I have all of my "includes" in (if you want to call them that).
I have a nav.phtml file that is included inside of the header.phtml file with getChildHtml('nav'). In nav.phtml, I have a file that I want included with getChildHtml('topSearch').
Is this possible? Is there a better implementation?

A: Fixed it by including this :)
<?php echo $this->getLayout()->createBlock('core/template')->setTemplate('template/templateName.phtml')->toHtml(); ?>

A: Yes Possible to use  getChildHtml('topSearch')  in header file.
Your local.xml code:
{{block type="module/blockfile" template="path to template"}}

A: Follow bellow steps
Step : 1 add bellow code in your local.xml file
<?xml version="1.0"?>
<layout version="0.1.0">
    <default>
       <reference name="top.search">
            <block type="core/template" name="top.search.nav" as="topSearchNav" template="page/html/nav.phtml" />
        </reference>
    </default>
</layout>

OR
<?xml version="1.0"?>
<layout version="0.1.0">
    <default>
       <reference name="top.search">
            <block type="{your-module-name/your-block-name}" name="top.search.nav" as="topSearchNav" template="{your-phtml-file-path}" />
        </reference>
    </default>
</layout>

Note: Add your particular block type & template file in above code for eg. block type : catalog/product_list & template : catalog/product/list.phtml
Step : 2 Now add getChildHtml('topSearchNav') under the file app\design\frontend\{your-package\{your-theme}\template\catalogsearch\form.mini.phtml
Like :
<?php echo $this->getChildHtml('topSearchNav'); ?>


text:
Q: Express $\frac{1}{y}\frac{\partial^2 y}{\partial x^2}$ in terms of $\ln$s I know that $$\frac{1}{y}\frac{\partial^2 y}{\partial x^2}$$ can be written as:
$$\frac{\partial^2}{\partial y^2}\ln y+\left(\frac{\partial}{\partial x} \ln y\right)^2$$
because if I take this last form, I can get to the form above by a few lines of algebra.
Assuming I don't know the second line, how could I go from the first line to the second line, knowing that I want $\ln$s in my expression?


text:
Q: Angular and Firebase Cloud Messaging build error I am currently working on an angular project with FCM for notifications but my app won't build anymore. I have per now read everything i can find on the subject and shaped my code thereafter, but I am still getting the same error.

building modules 3/3 modules 0 activeFailed on type {"filePath":"C:/Users/SlyOtis/Documents/Time2Work/src/frontend/src/app/_services/firebase.service.ts","name":"FCMService","members":[]} with error Error: Error encountered resolving symbol values statically. Exp
  ression form not supported (position 15:57 in the original .ts file), resolving symbol FCMService in C:/Users/SlyOtis/Documents/Time2Work/src/frontend/src/app/_services/firebase.service.ts
ERROR in Error encountered resolving symbol values statically. Expression form not supported (position 15:57 in the original .ts file), resolving symbol FCMService in C:/Users/SlyOtis/Documents/Time2Work/src/frontend/src/app/_services/firebase.service.ts

firebase.service.ts
import {Inject, Injectable} from '@angular/core';
import {FirebaseApp} from 'angularfire2';
import * as firebase from 'firebase';
import {StorageService} from './storage.service';
import {Subject} from 'rxjs/Subject';

@Injectable()
export class FCMService {

  private currentToken = '';
  private readonly messaging: firebase.messaging.Messaging;
  private readonly subject: Subject<any>;

  constructor(@Inject(FirebaseApp) private firebaseApp: firebase.app.App,
              private storage: StorageService) {

    this.messaging = firebase.messaging(this.firebaseApp);
    this.subject = new Subject();

    this.messaging.onTokenRefresh(this.onTokenRefresh);
    this.messaging.onMessage(this.onMessage);

    const tmpToken = storage.get('fcm_token');
    if (tmpToken) {
      this.currentToken = <string>tmpToken;
    } else {
      // this.init();
    }
  }

  public init() {
    this.requestPermission();
    this.getToken();
  }

  public requestToken() {
    this.getToken();
  }

  public getObservableSubject(): Subject<any> {
    return this.subject;
  }

  private onMessage(payload: any) {
    console.log('Message received. ', payload);
    // TODO:: Add message structur and observable.
    this.subject.next(payload);
    this.storage.putObject('msg', payload);
  }

  private onTokenRefresh() {
    const token = this.messaging.getToken();
    if (token !== null) {
      token.then(refreshedToken => {
        console.log('Token refreshed.');
        this.sendTokenToServer(refreshedToken);
      }).catch(function (err) {
        console.log('Unable to retrieve refreshed token ', err);
      });
    } else {
      console.log('Unable to retrieve refreshed token ');
    }
  }

  private getToken() {

    const token = this.messaging.getToken();
    if (token !== null) {
      token.then(currentToken => {
        if (currentToken) {
          this.sendTokenToServer(currentToken);
        } else {
          // Show permission request.
          console.log('No Instance ID token available. Request permission to generate one.');
        }
      }).catch(function (err) {
        console.log('An error occurred while retrieving token. ', err);
      });
    } else {
      console.log('An error occurred while retrieving token. ');
    }
  }
  // Send the Instance ID token your application server, so that it can:
  // - send messages back to this app
  // - subscribe/unsubscribe the token from topics
  private sendTokenToServer(currentToken: any) {
    console.log('Current token: ' + currentToken);
  }

  private requestPermission() {
    console.log('Requesting permission...');
    const permission = this.messaging.requestPermission();
    if (permission !== null) {
      permission.then(() => {
        console.log('Notification permission granted.');
        this.getToken();
      }).catch(function (err) {
        console.log('Unable to getObject permission to notify.', err);
      });
    } else {
      console.log('Unable to getObject permission to notify.');
    }
  }

  private deleteToken() {
    const token = this.messaging.getToken();
    if (token !== null) {
      token.then((currentToken: string) => {
        const deleted = this.messaging.deleteToken(currentToken);
        if (deleted !== null) {
          deleted.then(() => {
            console.log('Token deleted.');
            this.getToken();
          })
          .catch(function(err: any) {
            console.log('Unable to delete token. ', err);
          });
      } else {
          console.log('Unable to delete token. ');
        }}).catch(function (err) {
        console.log('Error retrieving Instance ID token. ', err);
      });
    } else {
      console.log('Error retrieving Instance ID token. ');
    }
  }
}

firebase-messaging-sw.js
// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here, other Firebase libraries
// are not available in the service worker.
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js');

const firebaseConfig = {
  apiKey: 'ÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆ',
  authDomain: 'ØØØØØØØØØØØØØØØØØØØØØØØØØ',
  databaseURL: 'ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ',
  projectId: 'asdasdasdasdasd',
  storageBucket: 'asdasdasdasdasdasdasd',
  messagingSenderId: '420'
};
// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp(firebaseConfig);

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();

The project works well with ng serve but not with build, any idea of what im doing wrong?


text:
Q: Javascript alert and back with php In this code, the alert box is not working. I want to redirect page and show a message using alertbox. How can I fix it?
 if($stmt){
?>
    <script type="text/javascript">
        alert("Package Successfully Booked..");
    </script>
<?php
header("location:javascript://history.go(-1)");
}
?>

A: You can alert the user using windows load function.
window.onload = function () {
   alert('Package Successfully Booked!');

}
or you can do it this way

<html>
<head>
<script>
function showAlert()
    {
    alert("Package Successfully Booked!");
    }
    </script>
</head>
<body onload="showAlert()">
</body>
</html>


text:
Q: Connect to multiple AP with one Wifi adapter under Linux/FreeBSD? How can I connect to more than one Wifi access point simultaneously using a single wireless adapter?
I'm currently using pfSense as my home router and I want it to connect to multiple APs wirelessly. Do you know if it's possible?
Alternatively, how can we do that under Ubuntu? Please shed me some light :)
Interesting notes:

*

*pfSense, as well as many router distros, supports using a single wireless adapter as multiple APs, but it's not clear (to me) whether they can act as multiple clients

*The "Virtual Wifi Adapter" in Windows 7 can apparently do just that

*For wired network, one can easily create interface alias (e.g. eth0:1) and obtain multiple IPs with ifconfig. Is this of any help?

A: Under FreeBSD (pfSense is based on FreeBSD and has nothing to do with Linux) you can create multiple wlan interfaces based on the physical interface, then connect them to various APs. For instance, if you have an Atheros card in your computer (and it isn't renamed):
ifconfig wlan0 create wlandev ath0
ifconfig wlan bssid NetworkA [wep/wpa/etc info]
dhclient wlan0 (assuming DHCP)

if you wanted another connection just spin up another:
ifconfig wlan1 create wlandev ath0
ifconfig wlan bssid NetworkB [wep/wpa/etc info]
dhclient wlan1 (assuming DHCP)

If the two networks are on different channels you'll see a reduced throughput, noticeably so if you're actively using both.


text:
Q: htaccess: why final page has GET parameters from start redirect page? I have this rule:
RewriteCond %{QUERY_STRING} someGetParameter=1
RewriteRule ^someoldpage.php$ http://newdomain.ru/page/ [L,R=301]

After redirect I get
http://newdomain.ru/page/?someGetParameter=1

instead of
http://newdomain.ru/page/

Why it is going wrong?

A: It's going 'wrong' because your assumption is wrong, see RewriteRule directive:

Modifying the Query String
By default, the query string is passed through unchanged. You can, however, create URLs in the substitution string containing a query string part. Simply use a question mark inside the substitution string to indicate that the following text should be re-injected into the query string. When you want to erase an existing query string, end the substitution string with just a question mark. To combine new and old query strings, use the [QSA] flag.

So:
RewriteCond %{QUERY_STRING} someGetParameter=1
RewriteRule ^someoldpage.php$ http://newdomain.ru/page/? [L,R=301]


text:
Q: How to create a C# OTA code to create a folders based on the path provided in Excel in Test plan in ALM. Could you please help me on this? I have tried the below code to create a folder structure in Test Plan using OTA, but unable to do so.. I am getting message saying Node not found.. Please help me out with the proper code
Folderpath =  Subject\UAT\UAT2\Testcases

private void Upload_Test_Click(object sender, EventArgs e)
{
if (File_path.Text == null)
{
MetroMessageBox.Show(this, "Please Select a Valid File", "File", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
string path = File_path.Text;
FileInfo fileinfo = new FileInfo(path);
ExcelPackage excel = new ExcelPackage(fileinfo);
var worksheet = excel.Workbook.Worksheets["Test Cases"];
//get te number of rows and columns in the sheet
int rows = worksheet.Dimension.Rows;
int columns = worksheet.Dimension.Columns;
int i = 2;
//loop through the worksheet rows and columsn
while (i <= rows)
{
testfact = (ITestFactory2)LoginForm.qctd.TestFactory;
TreeManager treemgr = LoginForm.qctd.TreeManager;
SysTreeNode tstrr = treemgr.NodeByPath[worksheet.Cells[i, 1].Value.ToString()];
tstrr.AddNode(worksheet.Cells[i, 2].Value.ToString());
tstrr.Post();
tstrr.Refresh();
List testlist = tstrr.NewList();
foreach(Test tset in testlist)
{
tset["TS_NAME"] = worksheet.Cells[i, 2].Value.ToString();
tset.Post();
tset.Refresh();
}
i = i + 1;
}
MessageBox.Show("Test Uplaoded successfully");
}

A: It would be helpful if you added more details about the error (like the row where it happens). I assume you are getting it while calling treemgr.NodeByPath and means that there is no folder with such path - check you ALM folders or adjust your script so it creates missing folders


text:
Q: Insert data in the table with timezone info I am trying to insert data into mysql with the timezone info. I am able to achieve this with column type as TIMESTAMPTZ in postgresql but with mysql I am unable to achieve the same.
I have created mysql table with below command
CREATE TABLE idvalue(id INTEGER NOT NULL, time TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP NOT NULL, value DOUBLE PRECISION NOT NULL);

so mysql is storing time value as 2020-06-18 11:02:29.295868 however in postgresql it store as 2020-06-18 11:02:29.295868+05:30. Is there any way I could achieve this apart from storing the column as string?

A: MySQL will store timestamp in UTC.
It will convert your timestamp to UTC before storing and will convert back when you retrieve it. It will use timezone set by time_zone variable.
See https://dev.mysql.com/doc/refman/8.0/en/datetime.html


text:
Q: jQuery slideToggle Dynamic Content I am trying to implement a toggle button that allows the user to collapse or expand the vertical Kendo UI Menus dynamically.  I got the initial program working when I hard code the slideToggle.  However, as soon as I try to add logic for a simple loop to initialize the slideToggle to each menu, the program breaks.  There seems to be a problem with a counter variable within an array (i.e., the array of strings that represents the classes of each menu). Is there something I am doing wrong here? I am providing the example code below in my JSFiddle; you'll noticed that when you uncomment the hard coded section it works, but the section that I want to work includes the loop logic.  Thank you in advance for your help!
http://jsfiddle.net/brandonq/KE8GX/3/
/////////////////////////////////////////////////
//               This harcode works            //
/////////////////////////////////////////////////

/*
        $("#menu1").click(function () {
          $(".hide1").slideToggle("slow");
        });

        $("#menu2").click(function () {
           $(".hide2").slideToggle("slow");
        });

*/

/////////////////////////////////////////////////
//               This is what I want           //
//                but doesn't work             //
/////////////////////////////////////////////////

// array of the classes assigned to each table
var temp = ["hide1", "hide2"];

   for (z = 1; z <= hides.length; z++) {
      $("#menu" + z).click(function () {
      // The count variable z somehow breaks the tables
      $("." + temp[z - 1]).slideToggle("slow");

      // This below works for one table (the left one)
      // $("." + temp[0]).slideToggle("slow");
      // so when you increment that array of strings, jquery
      // doesn't like it
   });
}

A: What's happening is that your elements aren't being assigned in the click function until the click function is being fired, which makes z = 3 because it's already been all the way through the loop. So it's trying to find $('.' + temp[3-1]) which is undefined.
To fix this, what I've done instead is attach the function to all the .k-items that were not .k-first:
for (z = 1; z <= temp.length; z++) {
    $("#menu" + z).click(function () {
        $('li.k-item:not(.k-first)', this).slideToggle('slow');
    });
}

Fiddle link
And you could actually even drop the for loop if you used this instead:
$("ul.menu").click(function () {
    $('li.k-item:not(.k-first)', this).slideToggle('slow');
});

Fiddle link

A: One problem and one mistake...
Mistake: you wrote for (z = 1; z <= hides.length; z++) { when it should be for (z = 1; z <= tables.length; z++) { i.e. iterate on tables and not in hides.
Problem (the actual error) the value of z in the event handler is the last value and not the value of each element. Try changing every .hide1 and .hide2 by .hide and then your code should be:
// array of the classes assigned to each table
for (z = 1; z <= tables.length; z++) {
    $("#menu" + z).click(function () {
        // The count variable z somehow breaks the tables
        $(".hide", this).slideToggle("slow");
    });
}

See it here: http://jsfiddle.net/OnaBai/KE8GX/6/
Or as @Samsquanch suggests removing the loop as:
// array of the classes assigned to each table
$(".menu").click(function () {
    $(".hide", this).slideToggle("slow");
});

In a much concise code. See it here: http://jsfiddle.net/OnaBai/KE8GX/8/


text:
Q: MiniZinc-Gurobi different results on the same problem but with different domains variable I'm a CS student and I'm using Gurobi for a project.
I am here because I have encountered a little problem with the Gurobi solver used along with the MiniZinc driver. In particular I have noticed that Gurobi returns two different solutions on the same optimisation problem (modelled with MiniZinc) but with a different domains for all the float problem variables.  The first problem uses a domain equal to -2^31.0 .. 2^31.0, while the second uses a domain equal to -3.402823e+38..3.402823e+38.
In the first case Gurobi returns a solution equal to 1.0, in the second case it returns UNSATorUNBOUNDED.


text:
Q: Weird behaviour of a simple gradle copy task I am completely baffled by the gradle behaviour of a Copy task into multiple directories.
I intend to copy all files from src/common into

*

*target/dir1/ps_modules

*target/dir2/ps_modules

*target/dir3/ps_modules
Below is how my build.gradle looks:
project.ext.dirs = ["dir1", "dir2", "dir3"]

// ensures that ps_modules directory is created before copying
def ensurePsModulesDir() {
  dirs.each {
    def psModules = file("target/$it/ps_modules")
    if (!(psModules.exists())) {
      println("Creating ps_modules directory $psModules as it doesn't exist yet")
      mkdir psModules
    }
  }
}

task copyCommons(type: Copy) {
  doFirst {
    ensurePsModulesDir()
  }

  from("src/common")
  dirs.each {
    into "target/$it/ps_modules"
  }
}

The result of running the command ./gradlew copyCommons is completely weird.
The folder creation works as expected, however, the contents/files are copied only in the target/dir3/ps_modules directory. The rest two directories remain empty.
Any help would be appreciated.
Below is the screen grab of target directory tree once the job is run:

A: I think you want to do something like:
task copyCommons(type: Copy) {
    dirs.each {
        with copySpec {
            from "src/common"
            into "target/$it/ps_modules"
        }
    }
}

I think you can get rid of the ensurePsModulesDir() with this change
* edit *
it seems that the copy task is forcing us to set a destination dir. You might think that setting destinationDir = '.' is ok but it's used in up-to-date checking so likely the task will NEVER be considered up-to-date so will always run. I suggest you use project.copy(...) instead of a Copy task. Eg
task copyCommons {
   // setup inputs and outputs manually
   inputs.dir "src/common"
   dirs.each {
       outputs.dir "target/$it/ps_modules"
   }

   doLast {
       dirs.each { dir ->
           project.copy {
               from  "src/common"
               into "target/$dir/ps_modules"
           }
       }
   }
}

A: You can configure a single into for a task of type Copy. In this particular example gradle behaves as expected. Since dir3 is the last element on the list it is finally configured as a destination. Please have a look at this question - which you can find helpful. Also this thread might be helpful as well.


text:
Q: Components Events: Property or method "updatebalance" is not defined I use Laravel. There are 2 Vue components that are exchanged via the event bus. "Order.vue" and "Balance_Label.vue".
When I click on the "Order" button, the Balance is reduced by the order amount, and the balance label is updated immediately (via Axios).
The interaction between these two components is realized via the Event Bus and works well.
But after updating the page I see such 2 warnings at Console:
[Vue warn]: Property or method "updatebalance" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
found in Root)
[Vue warn]: Invalid handler for event "updbalance": got undefined
found in
--->  at resources/assets/js/components/Balance_label.vue
Root
I would not pay attention to these warnings, since everything works as it should, but after the command:
npm run production
there is an error:
**ReferenceError: updatebalance is not defined
    at dn.eval (eval at Ca (app.js:1), <anonymous>:3:465)
    at dn.t._render (app.js:1)
    at dn.<anonymous> (app.js:1)
    at Ie.get (app.js:1)
    at new Ie (app.js:1)
    at app.js:1
    at dn.$mount (app.js:1)
    at dn.$mount (app.js:1)
    at dn.t._init (app.js:1)
    at new dn (app.js:1)**

and on the page I see only the background, but there are no components...
Friends, help please! I googled for 3 days, but to no avail.
Tried all sorts of solutions, but the error remains the same.
The "balance label" is rendered like this:
<balancelabel @updbalance="updatebalance"></balancelabel>

The "Order" button rendered like this:
<order
           :product={{ $product->id }}
           :ordered={{ $product->ordered() ? 'true' : 'false' }}
           productname= "{{ $product->name }}"
></order>

Balance_label.vue
<template>

                    {{ balance }}  dollars

</template>

Order.vue
<template>

            <button v-if="isOrdered"
                @click.prevent="unOrder(product)"
                type="button"
                class="btn btn-block btn-warning btn-xs"
                name="order-button">
                      Cancel Order
            </button>
            <button v-else-if="!isOrdered"
                @click.prevent="order(product)"
                type="button"
                class="btn btn-block btn-success btn-xs"
                name="order-button">
                      Order
            </button>

 </template>

app.js
require('./bootstrap');
window.Vue = require('vue');

Vue.component('order', require('./components/Order.vue'));
Vue.component('balancelabel', require('./components/Balance_label.vue'));

app = new Vue({
    el: '#app',
});

bootstrap.js
window._ = require('lodash');
try {
      require('bootstrap-sass');
} catch (e) {}

window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

window.Vue = require('vue');
window.events = new Vue();

import Vue from 'vue'
import VueNoty from 'vuejs-noty'

//connect event bus
export const bus = new Vue();

Vue.use(VueNoty)

package.json
{
  "private": true,
  "scripts": {
    "dev": "npm run development",
    "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch-poll": "npm run watch -- --watch-poll",
    "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
    "prod": "npm run production",
    "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
  },
  "devDependencies": {
    "axios": "^0.17",
    "bootstrap-sass": "^3.3.7",
    "cross-env": "^5.2.0",
    "jquery": "^3.2",
    "laravel-mix": "^1.0",
    "lodash": "^4.17.4",
    "vue": "^2.5.16"
  },
  "dependencies": {
    "noty": "^3.2.0-beta",
    "sweetalert": "^2.1.0",
    "vuejs-noty": "^0.1.3"
  }
}

P.S.: without a bus, too, received the same warning, so there is no bus - it does not matter
I found this topic but it doesnt help...
what I tried to do to resolve problem:

*

*declare the method in the root element of the vue (app.js file),

*declare a method in the event bus (boostrap.js file)

*declare the method in the order.vue
but the error does not go away... help please...
I read many topics at stackoveflow: all of them about properties, but not about methods...

A: Why are you trying to pass updatebalance as an event when you declare the method in Balance_label.vue? What happens if you remove @updbalance="updatebalance"


text:
Q: MODx Revo setTvValue returns old data $modx -> resource -> setTVValue(11, 1);
print_r($modx -> resource -> getTVValue(11));

$modx -> resource -> setTVValue(11, 2);
print_r($modx -> resource -> getTVValue(11));

I have a snippet that outputs 2 and 2, whereas it should output 1 and 2. Resource caching is turned off; snippet call is not cached either.
I have tried to fix this problem by another way, but it still updates my TV only after the whole page gets reloaded:
$tv = $modx->getObject('modTemplateVar',array('id'=>'11'));
$tv -> setValue($modx->resource->get('id'), 88);
$tv->save();

print_r($modx -> resource -> getTVValue(11));

By the way, if I am not working with TVs, everything is fine!
$modx -> resource -> set("pagetitle", 1);
print_r($modx -> resource -> get("pagetitle"));

$modx -> resource -> set("pagetitle", 2);
print_r($modx -> resource -> get("pagetitle"));

How do I fix this issue with TVs? I've tried to clear cache like this $modx->cacheManager->refresh(); too, but it didn't do the trick.

A: Ok try this
$id_resource = $modx->resource->get('id');
$id_tv = 11;
$value = 88;

$tv = $modx->getObject('modTemplateVar',array('id'=>$id_tv));
$tv -> setValue($id_resource, $value);
$tv->save();

if you need to get resource try this
$id_resource = $modx->resource->get('id');
$id_tv = 11;

$res = $modx->getObject('modResource',array('id'=>$id_resource));
print_r($res->getTVValue($id_tv));

A: You are going to love this:
$changeit = 11;
//$changeit= 'templateVarName';
$r = $modx->getObject('modResource', 177);
// or $r = $modx->resource
$tvs = $r->getTemplateVars();
if ($tvs) {
    foreach ($tvs as $object){
        if (is_object($object) && $object instanceof modTemplateVar){
           print_r($object->toArray());
        }
    }
 }

$r->setTVValue($changeit,'99999fhfhg');
echo '
'. $r->getTVValue($changeit);
$r->setTVValue($changeit,'888885454564');
echo '
'. $r->getTVValue($changeit);
$r->setTVValue($changeit,'123456789');
echo '
'. $r->getTVValue($changeit);

By sending it
$changeit = '11';

It becomes a string and is_string is true and thereby processes the request as if the name is 11, not the ID. You can send either the id or the name of the TV. I personally use only names, as it is much easier to deal with later.
The code I placed works and was tested.
I will be filing a bug report on this, because it should be a tad cleaner.
Also, you retrieve the current resource, update it etc. But you do not reload a "fresh" version of the resource after it is updated. You are in affect looking at the same var at the same state twice.
The mod->resource is the same as when you entered the page.
By making it a var it gets updated as you process through your changes.


text:
Q: Typeorm won't wait for no save Been struggling with typeorm, and I may have gotten something on the back foot.
Writing a database initiation script (to then start using the data). Some of the files have up to a million records, there are some foreign keys in there, and there will be about five files that will be loaded backend to get the base sorted.
My problem is, how do I get typeorm to tell me when save is successful as if I just put await on save
                await profileRepository.save(EUprofile)

I get

"Error:(37, 17) TS1308: 'await' expressions are only allowed within
async functions and at the top levels of modules."

But if I don't use it, it continues the code as soon as the save instruction has been issued.
I can get around this by just opening a new connection for each write, await works, but then I run out of connections very quickly, but the await works, so instead I wrapped the whole file read in:
createConnection().then(async connection => {

Works, but can't use await so I don't know when anything have finished loading.
Full script:
import "reflect-metadata";
import {createConnection} from "typeorm";
import * as csvParser from "csv-parser";
import * as fs from "fs";

// Lets load the profiles
import {EUProfile} from "./config/EUProfile.entity";
import {EUUser} from "./config/EUUsers.entity";

// Lets open up the database
createConnection().then(async connection => {

// Lets set the standard input files
const profileFS:string = "./dbinitdata/ProfileIdName.csv";
const usersFS:string = "./dbinitdata/UserProfiles.csv";
var loadsRunning:number = 1;

    let readCount:number = 0;
    let saveCount:number = 0;

    let readStartDate:number = new Date().getTime();
    console.log("PROFILE: Starting load:" + profileFS + " at " + new Date(readStartDate));
    fs.createReadStream(profileFS)
        .pipe(csvParser())
        .on('data', (data) => {
            // Lets map it
            const EUprofile = new EUProfile();
            EUprofile.id = data.ID;
            EUprofile.profileName = data.NAME
            readCount++;

                const profileRepository = connection.getRepository(EUProfile);
                await profileRepository.save(EUprofile)
                saveCount++;
                if (saveCount == readCount ){
                    var commitTime:number = new Date().getTime()
                    console.log("PROFILE: Records commited to database: " + saveCount +" in " + new Date(commitTime - readStartDate).getMilliseconds() + " MS");
                    loadsRunning--;
                    if (loadsRunning == 0){
                        //console.log("Completed database init at " + new Date());
                        //process.exit();
                    }
                }

        })
        .on('end', () => {

            var readTime:number = new Date().getTime()
            console.log("PROFILE: Records Read from file: "+ readCount + " in " + new Date(readTime - readStartDate).getMilliseconds() + " MS");
    });
}).catch(error => console.log(error));

Database config (
{
  "name": "default",
  "type": "mysql",
  "host": "localhost",
  "port": 3306,
  "username": "node",
  "password": "NOTGONNATELLYOU",
  "database": "eu_stats",
  "synchronize": true,
  "logging": false,
  "entities": [
    "./config/*.entity.js"
  ],
  "migrations": [
    "config/migration/**/*.ts"
  ],
  "subscribers": [
    "config/subscriber/**/*.ts"
  ]
}

P.S. Should admit, this is my first attempt at writing a node app in Typescript, so sorry if I'm missing something obvious :)

A: You need to make the arrow function asynchronous by using async.
Change this line:
.on('data', (data) => {

To this:
.on('data', async (data) => {

A: Andrew Arthurs response making async to data seems to work well, and both seem to give the same result.
Found a second option after asking (you know, the fifteenth google)
You can use the connection.manager save function and .then
   // await profileRepository.save(EUprofile)
    connection.manager.save(EUprofile).then(EUprofile => {
        saveCount++;
        if (saveCount == readCount ){
            var commitTime:number = new Date().getTime()
            console.log("PROFILE: Records commited to database: " + saveCount +" in " + new Date(commitTime - readStartDate).getMilliseconds() + " MS");
            loadsRunning--;
            if (loadsRunning == 0){
                console.log("Completed database init at " + new Date());
                process.exit();
            }
        }
    })


text:
Q: Print Formatted Text to a Serial Port I am trying to write a content to the serial port which will be communicated to a printer using bluetooth. I am using .NET CF 3.5 - Windows Mobile 6.5 and Citizen Printer PD 24.
I am able to write the text to the printer but the problem is that i want to format it like Bold Characters, Increase the Font size and others options. I don't know how to do that.
Any Suggestions?
Write now i am using this following Code:
 string printString = "APPLICATION FORM  \b0 \r\n";
 printString += "Name of First Applicant: " + ApplicantTitle + "." + ApplicantName + "\n";
 port.Write(printString);
 port.Close();

Thanks for reading the post
Regards
Biju

A: You need the programming manual for the printer to know what control codes to send.  You can download it here.


text:
Q: CSS expression for "Not a Descendant Of" Let's say I have this HTML

.A {
  border: thick blue solid;
}

.B {
  border: medium red solid;
}

      DON'T SELECT ME

    SELECT ME

        ALSO DON'T SELECT ME

How do I, for example, set the background to yellow of the "SELECT ME" div, without doing so to the other two? I was thinking it should be something like:
.root>:not(.A) .B { background: yellow; }

... but that doesn't seem to work and I don't understand why; and searching the web isn't turning up anything to my shock and surprise. Is this something that can be achieved with CSS?

A:

.A {
  border: thick blue solid;
}

.B {
  border: medium red solid;
}

.root > .B {
  background-color: yellow;
}

.A > .B {
  background-color: green;
}

      DON'T SELECT ME

    SELECT ME

        ALSO DON'T SELECT ME

Targeting .B as a direct descendant of .root works:
.root>.B { background: yellow; }

Targeting .B as an direct descendant of .A would allow you to target the .A > .B selectors differently:
.A>.B { background: green; }

A: You can use CSS nth-child rule. more details here
.B:nth-child(2) {
   background-color: yellow;
}

.A {
  border: thick blue solid;
}

.B {
  border: medium red solid;
}
.B:nth-child(2) {
   background-color: yellow;
}

      DON'T SELECT ME

    SELECT ME

        ALSO DON'T SELECT ME


text:
Q: Upgrading CakePHP web site to PHP 7 I've taken over a website written for PHP 5.4 and Cake2.x.  I upgraded PHP to 7.2 and Cake to 2.10.  Now no one can log in.  I started debugging but I feel like I'm going down a rabbit-hole.  In FormAuthenticate::authenticate(CakeRequest $request, CakeResponse $response) is the statement $fields = $this->settings['fields']; after which I added $ex = fopen('php://stderr', 'a');
 fputs($ex, "fields=" . json_encode($fields) . "\n"); which output
fields={"username":"username","password":"password"}

rather than the actual username and password which I'd typed on the web page.  I tried re-assigning fields with the actual username and password but the function calls method _checkFields which calls $request->data which returns an empty string.
Obviously I am taking the wrong approach here.  I've done something wrong in the upgrade, or omitted to do something;  something beyond just changing composer.json and running composer update.  Any suggestions?

A: I've solved this problem by downgrading CakePHP to version 2.9.9.