text:
Q: How to calculate days of readmission From the following data frame, I would like to make a new column of numbers of days between discharge_date to the next admission_date from each id.
I know how to get the number of days by subtracting dates between rows or between columns, but in this case, I need to subtract dates between columns and between rows (diagonally)
df <- data.table(id = c("A", "A", "A", "B", "B", "B", "C", "C"),
           admission_date = as.Date(c("2017-01-01", "2017-02-01", "2017-05-01", "2017-01-01", "2017-05-01", "2017-10-01", "2017-01-01", "2017-02-01")),
           discharge_date = as.Date(c("2017-01-04", "2017-02-05", "2017-05-06", "2017-01-03", "2017-05-09", "2017-10-04", "2017-01-06", "2017-02-01")))

I expect results like this:
df <- data.table(id = c("A", "A", "A", "B", "B", "B", "C", "C"),
                 admission_date = as.Date(c("2017-01-01", "2017-02-01", "2017-05-01", "2017-01-01", "2017-05-01", "2017-10-01", "2017-01-01", "2017-02-01")),
                 discharge_date = as.Date(c("2017-01-04", "2017-02-05", "2017-05-06", "2017-01-03", "2017-05-09", "2017-10-04", "2017-01-06", "2017-02-01")))
                 DayReadmission <- c("NA", "28", "85", "NA", "118", "145", "NA", "26")

I have just started using R, and have tried various suggestions. However, none of them fit my needs.

A: You can use shift to get value from previous row.
library(data.table)
df[, DayReadmission := as.numeric(admission_date - shift(discharge_date)), id]

df
#   id admission_date discharge_date DayReadmission
#1:  A     2017-01-01     2017-01-04             NA
#2:  A     2017-02-01     2017-02-05             28
#3:  A     2017-05-01     2017-05-06             85
#4:  B     2017-01-01     2017-01-03             NA
#5:  B     2017-05-01     2017-05-09            118
#6:  B     2017-10-01     2017-10-04            145
#7:  C     2017-01-01     2017-01-06             NA
#8:  C     2017-02-01     2017-02-01             26

A: How about this:
library(tidyverse)
df <- df %>%
  group_by(id) %>%
  mutate(DayReadmission = admission_date - lag(discharge_date))

A: Since you're new to R, this is the "old school" approach.
df$DayReadmission <- unlist(lapply(split(df, df$id),
       FUN=function(x) x$admission_date - lag(x$discharge_date)))

#  id admission_date discharge_date DayReadmission
#1  A     2017-01-01     2017-01-04             NA
#2  A     2017-02-01     2017-02-05             28
#3  A     2017-05-01     2017-05-06             85
#4  B     2017-01-01     2017-01-03             NA
#5  B     2017-05-01     2017-05-09            118
#6  B     2017-10-01     2017-10-04            145
#7  C     2017-01-01     2017-01-06             NA
#8  C     2017-02-01     2017-02-01             26


text:
Q: appcompat-v7 Toolbar menu - selection color doesn't effect text background I customized the toolbar in my app to be dark action bar and light menu.
It all seems to be fine except for the 'selection background' of the menu items.
Here is how it looks, notice there is a light gray background (which appears on click) and the background behind the text remains white like it overrides the onClick color. (the menu is total white)

Here is the theme used for the toolbar :
<style name="Theme.Toolbar" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:background">@color/primary_color</item>
    <item name="android:textColorPrimary">@color/primary_light</item>
</style>

<style name="Theme.Toolbar.Menu" parent="ThemeOverlay.AppCompat.Light">
    <item name="android:background">@color/primary_light</item>
    <item name="android:textColorPrimary">@color/primary_dark</item>
    <item name="android:selectedWeekBackgroundColor">@color/primary_dark</item>
</style>

And the toolbar layout :
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:theme="@style/Theme.Toolbar"
    app:popupTheme="@style/Theme.Toolbar.Menu"/>

A: In your popupTheme set
<item name="android:colorBackground">@color/your_color</item>
instead of "android:background" (and remove that completely).
I found this solution at this post and it worked for me:
Style appcompat-v7 Toolbar menu background

redpajama_set_name: RedPajamaStackExchange


text:
Q: $variable OR $variable = $variable in PHP This is a standalone expression in a function:
$var OR $var = $var

What does this expression exactly do?
Never saw this before and can't find the answer as I have no idea how is this called.
Code itself is from: Сodeigniter Template on Github
public function build($view, $data = array(), $return = FALSE)
{
    // Set whatever values are given. These will be available to all view files
    is_array($data) OR $data = (array) $data;
    // Merge in what we already have with the specific data
    $this->_data = array_merge($this->_data, $data);

...

A: Given an expression like yours
is_array($data) OR $data = (array) $data;

we check the precedence table on http://php.net/operators.precedence first. There we see = is above OR. Thus the line is equal to this:
is_array($data) OR ($data = (array) $data);

Next we have to check the table for associativity. or is left associative so it checks is_array($data). If that returns true the orexpression as a whole returns trueand nothing else happens.
If is_array($data) returns false we have to evaluate further, so $data = (array) $data is executed.
In the end this is a "smart" way to write
if (!is_array($data)) {
    $data = (array) $data;
}

Actually in this specific case we could also write only
$data = (array) $data;

As the (array) cast is a no-op if $data already is an array.


text:
Q: Python - nested loop vs 'in' operator resulting in almost double runtime I come from a C++/Java background and have done a simple implementation of the 'TwoNumberSum' algorithm
 below. I first implemented it in a more C/Java way using the conventional nested loop then using the 'in' operator. I was expecting both to execute in similar time as 'in' should ideally also iterate through the list which should result in a nested loop and thus somewhere similar execution time but to my surprise the first algorithm takes double the time of the second.
Can someone explain what is causing such huge gap in runtime?
I am getting below results on executing the snippet.
Execution Time of Algo 1: 1.023191
Execution Time of Algo 2: 0.46218059999999994
from timeit import timeit

# First Algorithm using simple lists/arrays
code1 = """
def TwoNumberSum(list, sum):

    for i in range(0, len(list)-1):
        for j in range(i+1, len(list)):
            if list[i] + list[j] == sum:
                return [list[i], list[j]]
    return []

TwoNumberSum([3, 5, -4, 8, 11, 1, -1, 6], 10)
"""
# Second Algorith similar to first using 'in' operator
code2 = """
def TwoNumberSum(list, sum):

    for i in range(0, len(list)-1):
        if sum-list[i] in list[i+1:-1]:
            return [list[i], sum-list[i]]
    return []

TwoNumberSum([3, 5, -4, 8, 11, 1, -1, 6], 10)
"""

print(f"Execution Time of Algo 1: {timeit(code1, number=100000)}")
print(f"Execution Time of Algo 2: {timeit(code2, number=100000)}")

A: Python is an interpreted language, and for loops in it are notoriously slow.  You probably expect that in is implemented as a for loop, and it is, but it's implemented natively (typically in C), not in Python.  There are a lot of functions like that in Python, otherwise the whole language would be impractically slow (at least on the most common interpreter implementation, which is CPython).
If you care about performance in Python, you'll need to do everything you can to avoid Python loops that are executed many times.  This is a big part of why NumPy exists and is written largely in C (because operating on vectors and arrays takes forever if you use for loops).
You can also write your own Python modules in C (or C++, or other languages which can expose C callable functions), and this is very useful if you need to accelerate custom loops.

Added to address comments from user "Heap Overflow":
If the input list is long, you want an linear time solution.  Here is one:
def TwoNumberSum(nums, target):
    seen = set()
    for num in nums:
        complement = target - num
        if complement in seen:
            return num, complement
        seen.add(num)

This is actually slower for the short example lists given in the question, but will be faster for longer lists.  But it still contains a for loop in Python, which means it won't be blazing fast.  An easy way to fix that is to use Numba, which automatically translates a subset of Python to machine code:
import numba
TwoNumbaSum = numba.njit(TwoNumberSum)

Numba expects NumPy arrays rather than lists, so call it like this:
TwoNumbaSum(np.asarray([3, 5, -4, 8, 11, 1, -1, 6]), 10)

That's it, now you have a linear time solution with no for loops in Python, and you didn't have to write C or C++ code (which would run just as fast but require more effort to develop).


text:
Q: please take a look at this code my signup button doesn't direct me to profile component react native Help me with this so I can carry further on with my work.
Also all the other files which are needed for the solution I can provide you with.
profile.js
import React from "react";
import { StyleSheet, Text, View, StatusBar } from "react-native";
import { render } from "react-dom";

class Profile extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.textStyle}>This is the profile page </Text>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    backgroundColor: "#455a64",
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  textStyle: {
    color: "#fff",
    fontSize: 18,
  },
});

export default Profile;

signup.js
import React from "react";
import {
  StyleSheet,
  Text,
  View,
  StatusBar,
  TouchableOpacity,
} from "react-native";

import { createNewUser } from "/Users/ayeshasiddiquebutt/elearning9thclassapp/sourcefiles/actions/auth.actions.js";
import { render } from "react-dom";
import { connect } from "react-redux";
import Form from "/Users/ayeshasiddiquebutt/elearning9thclassapp/sourcefiles/components/form.js";
import { compose } from "redux";
import Logo from "/Users/ayeshasiddiquebutt/elearning9thclassapp/sourcefiles/components/logo.js";
import SignupForm from "/Users/ayeshasiddiquebutt/elearning9thclassapp/sourcefiles/components/signupform.js";
import { Actions } from "react-native-router-flux";
import { Field, reduxForm } from "redux-form";
import InputText from "/Users/ayeshasiddiquebutt/elearning9thclassapp/sourcefiles/components/InputText.js";
import Loader from "/Users/ayeshasiddiquebutt/elearning9thclassapp/sourcefiles/components/Loader.js";
class Signup extends React.Component {
  goBack() {
    Actions.pop();
  }

  createNewUser = (values) => {
    this.props.dispatch(createNewUser(values));
  };

  onSubmit = (values) => {
    this.createNewUser(values);
  };

  renderTextInput = (field) => {
    const {
      meta: { touched, error },
      label,
      secureTextEntry,
      maxLength,
      keyboardType,
      placeholder,
      input: { onChange, ...restInput },
    } = field;
    return (
      <View>
        <InputText
          onChangeText={onChange}
          maxLength={maxLength}
          placeholder={placeholder}
          keyboardType={keyboardType}
          secureTextEntry={secureTextEntry}
          label={label}
          {...restInput}
        />
        {touched && error && <Text style={styles.errorText}>{error}</Text>}
      </View>
    );
  };

  render() {
    const { createUsers, handleSubmit } = this.props;
    return (
      <View style={styles.container}>
        {createUsers.isLoading && <Loader />}
        <Logo />

        <Field
          name="name"
          placeholder=" First Name"
          component={this.renderTextInput}
        />
        <Field
          name="name"
          placeholder=" Last Name"
          component={this.renderTextInput}
        />
        <Field
          name="email"
          placeholder="Email"
          component={this.renderTextInput}
        />
        <Field
          name="password"
          placeholder="Password"
          secureTextEntry={true}
          component={this.renderTextInput}
        />
        <TouchableOpacity
          style={styles.button}
          onPress={handleSubmit(this.onSubmit)}
        >
          <Text style={styles.buttonText}>Signup</Text>
        </TouchableOpacity>
        <View style={styles.signupTextCont}>
          <Text style={styles.signupText}>Already have an account?</Text>
          <TouchableOpacity onPress={this.goBack}>
            <Text style={styles.signupButton}> Sign in</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}
const validate = (values) => {
  const errors = {};
  if (!values.name) {
    errors.name = "First Name is required";
  }
  if (!values.name) {
    errors.name = "Last Name is required";
  }
  if (!values.email) {
    errors.email = "Email is required";
  }
  if (!values.password) {
    errors.password = "Password is required";
  }
  return errors;
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: "#455a64",
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  signupTextCont: {
    flexGrow: 1,
    alignItems: "flex-end",
    justifyContent: "center",
    paddingVertical: 16,
    flexDirection: "row",
  },
  signupText: {
    color: "rgba(255,255,255,0.6)",
    fontSize: 16,
  },
  signupButton: {
    color: "#ffffff",
    fontSize: 16,
    fontWeight: "500",
  },
  button: {
    width: 300,
    backgroundColor: "#1c313a",
    borderRadius: 25,
    marginVertical: 10,
    paddingVertical: 13,
  },
  buttonText: {
    fontSize: 16,
    fontWeight: "500",
    color: "#ffffff",
    textAlign: "center",
  },
  errorText: {
    color: "#ffffff",
    fontSize: 14,
    paddingHorizontal: 16,
    paddingBottom: 8,
  },
  inputBox: {
    width: 300,
    backgroundColor: "rgba(255, 255,255,0.2)",
    borderRadius: 25,
    paddingHorizontal: 16,
    fontSize: 16,
    color: "#ffffff",
    marginVertical: 10,
  },
});
mapStateToProps = (state) => ({
  createUsers: state.authReducer.createUsers,
});

mapDispatchToProps = (dispatch) => ({
  dispatch,
});

export default compose(
  connect(mapStateToProps, mapDispatchToProps),
  reduxForm({
    form: "register",
    validate,
  })
)(Signup);

auth.reducer.js
import { combineReducers } from "redux";

const createUsers = (state = {}, action) => {
  switch (action.type) {
    case "CREATE_USER_LOADING":
      return {
        isLoading: true,
        isError: false,
        isSuccess: false,
        errors: null,
        isLoggedIn: false,
      };

    case "CREAT_USER_SUCCESS":
      return {
        isLoading: false,
        isError: false,
        isSuccess: true,
        errors: null,
        isLoggedIn: true,
      };

    case "CREAT_USER_FAIL":
      return {
        isLoading: false,
        isError: true,
        isSuccess: false,
        errors: action.payload,
        isLoggedIn: false,
      };

    default:
      return state;
  }
};
/*const authData = (state = {}, action) => {
  switch (action.type) {
    case "AUTH_USER_SUCCESS":
      return {
        token: action.token,
        isLoggedIn: true,
      };

    case "AUTH_USER_FAIL":
      return {
        token: null,
        isLoggedIn: false,
      };
    default:
      return state;
  }
};

const loginUser = (state = {}, action) => {
  switch (action.type) {
    case "LOGIN_USER_LOADING":
      return {
        isLoading: true,
        isError: false,
        isSuccess: false,
        errors: null,
      };

    case "LOGIN_USER_SUCCESS":
      return {
        isLoading: false,
        isError: false,
        isSuccess: true,
        errors: null,
      };

    case "LOGIN_USER_FAIL":
      return {
        isLoading: false,
        isError: true,
        isSuccess: false,
        errors: action.payload,
      };

    default:
      return state;
  }
};*/
export default combineReducers({
  createUsers,
  //loginUser,
  //authData,
});

routes.js
import React, { Component } from "react";
import {
  StyleSheet,
  Text,
  View,
  StatusBar,
  TouchableOpacity,
} from "react-native";
import { Router, Stack, Scene } from "react-native-router-flux";
import Login from "../pages/login.js";
import Signup from "/Users/ayeshasiddiquebutt/elearning9thclassapp/sourcefiles/pages/signup.js";
import Profile from "../pages/profile.js";
class Routes extends React.Component {
  render() {
    return (
      <Router>
        <Scene>
          <Scene key="root" hideNavBar={true} initial={!this.props.isLoggedIn}>
            <Scene key="signup" component={Signup} title="Register" />
            <Scene key="login" component={Login} />
          </Scene>
          <Scene key="app" hideNavBar={true} initial={this.props.isLoggedIn}>
            <Scene key="profile" component={Profile} initial={true} />
          </Scene>
        </Scene>
      </Router>
    );
  }
}
export default Routes;

Main.js
import React from "react";
import {
  StyleSheet,
  Text,
  View,
  StatusBar,
  TouchableOpacity,
} from "react-native";
import { render } from "react-dom";
import { createUsers } from "/Users/ayeshasiddiquebutt/elearning9thclassapp/sourcefiles/reducers/auth.reducer.js";
import { connect } from "react-redux";

import Routes from "/Users/ayeshasiddiquebutt/elearning9thclassapp/sourcefiles/components/routes.js";
import { Actions } from "react-native-router-flux";

class Main extends React.Component {
  render() {
    const { createUsers } = this.props;
    console.log(this.props.createUsers.isLoggedIn);
    return (
      <View style={styles.container}>
        <StatusBar backgroundColor="#1c313a" barStyle="light-content" />
        <Routes isLoggedIn={this.props.createUsers.isLoggedIn} />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});

mapStateToProps = (state) => ({
  createUsers: state.authReducer.createUsers,
});`enter code here`

export default connect(mapStateToProps, null)(Main);


text:
Q: Working with hierarchy (tree) in R This is a general question about options of handling tree-like (hierarchy) data in R, as well as feasibility of igraph package for the task in hand.
Multiple hierarchies are stored in a relational table in a structure like:
Name ID PID Start Date  End Date
A    1      12/31/14
B    2  1   12/31/14
C    3  1   12/31/14    1/31/15
D    4  2   12/31/14
Z    5      6/30/14
Y    6  5   6/30/14     12/31/14
X    7  6   7/31/14      9/30/14
W    8  5   7/31/14

The structure of each hierarchy changes over time as indicated by "Start Date" and "End Date". In other words, the structure could potentially be different on any given day.
My objective at this point is to find an efficient and easy way of constructing an R-object from that data, and establish a framework for further manipulation/transformation of these hierarchies. The initial research tells me that the igraph package could be a good answer. One thing I'm not certain is the time dimension aspect (looks like the proper name is a "temporal graph").
Here are some of the common tasks I'm looking to do:

*

*Get composition of any hierarchy on any given day.

*Identify changes between two dates in any node (hierarchy delta).

*While each hierarchy is a tree with a single root (directed tree), there is a requirement to establish logic relationship between nodes of two hierarchies (a hierarchy pair).

*Assign attributes to nodes and search graph by them.

*Export hierarchy in a flat view like:

Date   Level1  Level2  Level3
12/31/14    A   B       D
12/31/14    A   C
12/31/14    Z   Y
12/31/14    Z   W
2/1/15      A   B       D
2/1/15      Z   W
I was able to create a graph object from the parent-child data (without time dimension), but could not figure out how to transform it into that flat structure.
Any suggestions and ideas are super welcome!


text:
Q: Why does nmap show every host is up? I've run a simple nmap search and every IP within my subnet are seen by nmap as being up but with the switches MAC address. eg:
Nmap scan report for 192.168.21.246
Host is up (0.0053s latency).
All 100 scanned ports on 192.168.21.246 are filtered
MAC Address: 00:00:0C:07:AC:0D (Cisco Systems)

Nmap scan report for 192.168.21.247
Host is up (0.0056s latency).
All 100 scanned ports on 192.168.21.247 are filtered
MAC Address: 00:00:0C:07:AC:0D (Cisco Systems)

Nmap scan report for 192.168.21.248
Host is up (0.0058s latency).
All 100 scanned ports on 192.168.21.248 are filtered
MAC Address: 00:00:0C:07:AC:0D (Cisco Systems)

Nmap scan report for 192.168.21.249
Host is up (0.0063s latency).
All 100 scanned ports on 192.168.21.249 are filtered
MAC Address: 00:00:0C:07:AC:0D (Cisco Systems)

This is a just a quick scan (nmap -T4 -F 192.168.21.1-254).
Is there some switch config that is spoofing the status of those IPs or is this the normal behaviour of nmap (it's been a while since I've last used nmap but I don't recall this behaviour before and unfortunately I don't have another safe network with a different stack of networking switches to test this on).
Lastly, those hosts do not respond to ping so I don't believe it is an issue with ICMP but this is where my networking knowledge gets a little fuzzy.
edit: for clarity, the hosts being reported as up are IPs with no host attached.
edit 2: After a little more research I've been able to determine that nmap is defaulting to ARP pings rather than ICMP echoes (what people often refer to as "ping"). Disabling ARP pings via the --disable-arp-ping flag now forces the ICMP echoes and I'm only seeing hosts being marked as "up" for IPs that literally do have a physical/virtual machine attached. So that is a step in the right direction.
HOWEVER some of our internal security monitoring tools exhibit the same problem as nmap (they possibly just use nmap in the background) I now need to research a way to configure our Cisco switches not to return an ARP entry for IPs without an endpoint. But that is a tangent from this StackExchange question :)


text:
Q: Button broken when using float left? I have two forms that need to be side by side. I can get them to float left but the button gets disabled when I use float left. I have tried display-inline and that doesnt work. I have tried span and that doesnt work. No idea why the button stops woeking. Here is a sample form

    <form method="post">

       Name

      <input class="form-control" id="name" name="name" type="text"/>

       <button class="btn btn-primary " name="submit" type="submit">
        Submit
       </button>

    </form>

    <form method="post">

       LastName

      <input class="form-control" id="name" name="name" type="text"/>

       <button class="btn btn-primary " name="submit" type="submit">
        Submit
       </button>

    </form>

A: Will this work as a start?
I changed this (which had a type, should be inline) style="display:incline;... to style="float:left;...

          <form method="post">

                Name

              <input class="form-control" id="name" name="name" type="text"/>

                <button class="btn btn-primary " name="submit" type="submit">
                  Submit
                </button>

          </form>

          <form method="post">

                LastName

              <input class="form-control" id="name" name="name" type="text"/>

                <button class="btn btn-primary " name="submit" type="submit">
                  Submit
                </button>

          </form>

but may I suggest to use style="display: inline-block;... on both your form containers, here using CSS styles (preferable) instead of inline style.

.formwrapper {
  display:inline-block;
  border:1px solid blue;
  width:200px;
}

          <form method="post">

                Name

              <input class="form-control" id="name" name="name" type="text"/>

                <button class="btn btn-primary " name="submit" type="submit">
                  Submit
                </button>

          </form>

          <form method="post">

                LastName

              <input class="form-control" id="name" name="name" type="text"/>

                <button class="btn btn-primary " name="submit" type="submit">
                  Submit
                </button>

          </form>


text:
Q: Datetime changes after input to SQL Server In my app I'm using node mssql module to input datetime into a SQL Server database. The problem is that in the database datetime is always changed and time is one hour less then the one that I input.
async function insertDate(date, logIO) {
try {
    var d = new Date(date)
    var name = 'zdzmar'
    const pool = await sql.connect(config)
    let result = await pool.request(pool)
    .input('date', TYPES.DateTime, d)
    .input('name', TYPES.VarChar, name)
    .input('logIO', TYPES.TinyInt, logIO)
    .query(`insert clock(date, name, logIO) values(@date, @name, @logIO)`)
} finally {
    sql.close();
}
}

Where is the problem?

A: It seems like a bug with the mssql package. I run into the same problem even when I formated the datetime into a string, the date still got converted into a different datetime, in my case 12:04pm got converted to 20:04pm, which is not directly related to timezone or UTC time.
A workaround to solve this problem is to use sql.VarChar instead of sql.DataTime.


text:
Q: Why startup-script runs multiple times in Google compute engine vm? I don't understand why my startup-script runs multiple times
at least, I think so because after I started the vm this morning at 6:00am
now I just logged into google cloud console, checked the logs and
saw that the startup script run multiple times
I thought it was meant to run just once :/
Nov 21 06:57:11 ubuntu startup-script: INFO startup-script: stuff...
Nov 21 06:57:11 ubuntu startup-script: INFO startup-script: stuff...
Nov 21 06:57:11 ubuntu startup-script: INFO startup-script: stuff...
Nov 21 07:12:17 ubuntu startup-script: INFO startup-script: stuff...
Nov 21 07:12:17 ubuntu startup-script: INFO startup-script: stuff...
Nov 21 07:12:17 ubuntu startup-script: INFO startup-script: stuff...
Nov 21 07:27:10 ubuntu startup-script: INFO startup-script: stuff...
Nov 21 07:27:10 ubuntu startup-script: INFO startup-script: stuff...
Nov 21 07:27:10 ubuntu startup-script: INFO startup-script: stuff...
Nov 21 07:42:13 ubuntu startup-script: INFO startup-script: stuff...
...

and more
any idea why the vm has that behaviour?
note that I added the startup-script in the instance Custom metadata:
#! /bin/bash
sudo -iu user2 Desktop/script.sh

A: I think you need to add checker on your script if you want one time running . for example :
if [[ -f /etc/startup_was_launched ]]; then exit 0; fi
…
touch /etc/startup_was_launched

or
if [ ! -f /etc/startup_was_launched ];then
...
sudo touch /etc/startup_was_launched
fi


text:
Q: data-pk attribute not showing in the x-editable CGridview I am using x-editable to use inline editing in CGridview. http://x-editable.demopage.ru/index.php I am using postgresql as the database. The problem is that I am using functions in postgres to write queries and I am calling those functions from yii. The data provider I am using is CSqlDataprovider. So while using the inline edit the data-pk attribute is not showing in the grid view. So the update is not working. Please help.

A: Try to set keyField of dataProvider to 'id'.
dataProvider->keyField ='id';

A: You can specify the PK has a param in your X-editable column:
$this->widget('editable.EditableField', array(
    'type'         => 'select',
    'model'        => $data,
    'attribute'    => 'user_status',
    'url'          => $this->createUrl('site/updateUser'),
    'pk'           => 'id',
    ));

?>

If you want more details, then provide us more information about your CgridView column and data that need to be saved.
Source


text:
Q: MongoDB: How to match on the elements of an array? I have two collections as follows:
db.qnames.find()
{ "_id" : ObjectId("5a4da53f97a9ca769a15d49e"), "domain" : "mail.google.com", "tldOne" : "google.com", "clients" : 10, "date" : "2016-12-30" }
{ "_id" : ObjectId("5a4da55497a9ca769a15d49f"), "domain" : "mail.google.com", "tldOne" : "google.com", "clients" : 9, "date" : "2017-01-30" }

and
db.dropped.find()
{ "_id" : ObjectId("5a4da4ac97a9ca769a15d49c"), "domain" : "google.com", "dropDate" : "2017-01-01", "regStatus" : 1 }

I would like to join the two collections and choose the documents for which 'dropDate' field (from dropped collection) is larger than the 'date' filed (from qnames field). So I used the following query:
 db.dropped.aggregate( [{$lookup:{ from:"qnames", localField:"domain",foreignField:"tldOne",as:"droppedTraffic"}},
     {$match: {"droppedTraffic":{$ne:[]}  }},
{$unwind: "$droppedTraffic" } ,
{$match: {dropDate:{$gt:"$droppedTraffic.date"}}} ])

but this query does not filter the records where dropDate < date. Anyone can give me a clue of why it happens?

A: You should use $redact to compare two fields of the same document. Following example should work:
db.dropped.aggregate( [
    {$lookup:{ from:"qnames", localField:"domain",foreignField:"tldOne",as:"droppedTraffic"}},
    {$match: {"droppedTraffic":{$ne:[]}  }},
    {$unwind: "$droppedTraffic" },
    {
        "$redact": {
            "$cond": [
                { "$lte": [ "$dropDate", "$droppedTraffic.date" ] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])

A: The reason why you are not getting the record is

Date is used as a String in your collections, to make use of the comparison operators to get the desired result modify your collection documents using new ISODate("your existing date in the collection")

Please note even after modifying both the collections you need to modify your aggregate query, since in the final $match query two values from the same document is been compared.
Sample query to get the desired documents
db.dropped.aggregate([
    {$lookup: {
       from:"qnames",
       localField:"domain",
       foreignField:"tldOne",
       as:"droppedTraffic"}
    },
    {$project: {
       _id:1, domain:1,
       regStatus:1,
       droppedTraffic: {
          $filter: {
             input: "$droppedTraffic",
             as:"droppedTraffic",
             cond:{ $gt: ["$$droppedTraffic.date", "$dropDate"]}
          }
       }
     }}
])

In this approach given above we have used $filter which avoids the $unwind operation


text:
Q: Wiredep не работает для css в Gulp Доброго времени суток!
Столкнулся с следующей проблемой, захотел вставить Wiredep в свою сборку Gulp, суть в том что я использую gulp-file-include и хотел что бы css библиотеки вставлялись в файл libs.css таким образом "@@include('path/to/libs')" а библиотеки js в файл  libs.js в каждом из файлов я прописал

// bower:js
// endbower

и

// bower:css
// endbower

в файл js все вставляется и работает без нареканий чего не могу скачать о файле css
Файл js после выполнения таска

// bower:js
@@include('src/app/libs/get-style-property/get-style-property.js')
@@include('src/app/libs/get-size/get-size.js')
@@include('src/app/libs/eventEmitter/EventEmitter.js')
@@include('src/app/libs/jquery/dist/jquery.js')
@@include('src/app/libs/bootstrap/dist/js/bootstrap.js')
// endbower

Файл css после выполнения таска

// bower:css
// endbower

Таски с gulpfile.js

gulp.task('bower-css', function () {
    gulp.src('app/libs.scss')
        .pipe(wiredep({
            directory: 'app/libs',
            fileTypes: {
                scss: {
                    replace: {
                        css:  '@@include("src/app/{{filePath}}")',
                        sass: '@@include("src/app/{{filePath}}")',
                        scss: '@@include("src/app/{{filePath}}")'
                    }
                }
            },
            ignorePath: /^(\.\.\/)+/
        }))
        .pipe(gulp.dest('app/'));
});
gulp.task('bower-js', function () {
    gulp.src('app/es6/libs.js')
        .pipe(wiredep({
            directory: 'app/libs',
            fileTypes: {
                js: {
                    replace: {
                        js: '@@include("src/app/{{filePath}}")'
                    }
                }
            },
            ignorePath: /^(\.\.\/)+/
        }))
        .pipe(gulp.dest('app/'));
});

Так почему с JS все работает а с CSS нет?


text:
Q: Malicious code vulnerability - Field should be package protected Sonar is giving me the message:

Malicious code vulnerability - Field should be package protected for
  static array FORMATS.

Why is this code considered malicious? I have a public class to store all the constants.
public class Constants
{
    /*
    all the public static final constants of primitive datatypes for which
    there is no sonar warning.
    */
    public static final String[] FORMATS = new String[] {
        "yyyy-MM-dd HH:mm:ss.S z",
        "yyyy-MM-dd HH:mm:ss.S"
}

A: Probably because another piece of code could execute:
Constants.FORMATS[0] = "SOME GARBAGE";

And break the rest of your code.
In other words your array is constant but not its content.
Examples of alternatives:

*

*you can store each format as a separate String constant

*you can use an immutable list instead: public static final List<String> FORMATS = Collections.unmodifiableList(Arrays.asList("yyyy-MM-dd HH:mm:ss.S z", "yyyy-MM-dd HH:mm:ss.S"));

*make it a method:
public static String[] formats() {
  return new String[] { "yyyy-MM-dd HH:mm:ss.S z", "yyyy-MM-dd HH:mm:ss.S" };
}

*ignore the warning if you are confident that (i) only your own code will access that class and (ii) there is no way you/your colleagues would even think of reassigning one of the values.


text:
Q: Проблемы с передачей переменных методом post Создал следующий файл post1.php, с такой формой для отправки:
<form action="post2.php" method="post" name="form1" target="_blank">

Введите ваше имя:
 <input name="name" type="text" size="20" />

Введите вашу фамилию:
 <input name="lastname" type="text" size="20" />

<input name="submit" type="submit" value="Отправить" />

</form>

в другом файле - post2.php прописал вывод:
<?php

echo $_POST[$name];
echo "$lastname";

?>

но при реализации кода, ничего не происходит. Страница пост2 открывается в новом окне, но ни имени, ни фамилии не отображает. Где моя ошибка, подскажите, пожалуйста.
A: $_POST['name']


text:
Q: Delete taking so long in mysql I am trying to Delete all the contents from a table. So using delete from M_Cast. But it seems to take infinitely long to get executed. The number of rows in the table are just 19. And this is happening only with this particular table M_Cast. What can be the problem..?
Picture of my terminal . I pressed enter and the cursor is still blinking

Even I faced this problem MySQL > Table doesn't exist. But it does (or it should) an hour back. I created a new DB as mentioned. But now even when I am trying to delete the DB it doesnt execute.
Why do such weird things happen in MySQL?

A: If a delete is taking so long on such a small table, then something is presumably locking the table.  Alternatively, you could have indexes or cascading deletes that affects a large number of rows in other tables.
One way of doing this is by using show open tables (see the documentation here).
As a note.  A faster way to delete all the rows in a table is to use truncate table.  This does the deletion without logging or executing delete triggers.


text:
Q: Integer gets automatically set to 0 C# I am doing an exercise on making a small console program which shows how fast a car is moving and a function to make it go either faster or slower.
So here is my class called car, it contains a constructor.
There is a get and set accessor for the private int speed.
There are 2 methods called accelerate and break.
class car
{
    private int speed;

    public car (int initialSpeed) //initializes car speed
    {
        Speed = initialSpeed;
    }

    public void accelerate() //increase Speed
    {
        Speed = Speed + 10;
    }

    public void brake() //decrease Speed
    {
        Speed = Speed - 10;
    }

    public int Speed //access private int speed
    {
        get { return speed; }
        set { speed = Speed; }
    }

}

Now here is the problem:
class program
{
    static void Main(string[] args)
    {
        var Car = new car(5);
        Console.WriteLine(Car.Speed);

    }
}

When I run the program the console just displays 0 even though initialized with 5. Why is this happening and what am I doing wrong?

A: Your Speed property is the problem. Here's the code:
public int Speed //access private int speed
{
    get { return speed; }
    set { speed = Speed; }
}

The getter is fine - it returns the value of the private variable.
The setter, however, sets the value of variable to the result of evaluating the getter - ignoring the value passed into the setter entirely (available via the value variable). It should be:
public int Speed
{
    get { return speed; }
    set { speed = value; }
}

Or better yet, use an automatically implemented property - remove the speed field, and just have:
public int Speed { get; set; }

At the same time, I'd suggest learning about compound assignment operators and .NET naming conventions. If you're using C# 6 you can also use expression-bodied members, leaving a really small amount of code:
class Car
{
    public int Speed { get; set; }

    public Car(int initialSpeed)
    {
        Speed = initialSpeed;
    }

    public void Accelerate() => Speed += 10;
    public void Brake() => Speed -= 10;
}

A: Change this code:
public int Speed //access private int speed
{
    get { return speed; }
    set { speed = Speed; }
}

to
public int Speed //access private int speed
{
    get { return speed; }
    set { speed = value; }
}

In C# properties, the setter uses the value keyword to set values to the underlying field.

A: Your set assessor should be
set { speed = value; }

So your property definition becomes
public int Speed //access private int speed
{
    get { return speed; }
    set { speed = value; }
}

A: The problem is in the set, change this
    set { speed = Speed; }

for this
    set { speed = value; }

Good luck!

A: @Jay is correct but the preferred syntax in this case is
public int Speed { get; set;}

and remove
private int speed;

Let the compiler handle the member details for you since you are not running any actual logic in the get/set properties


text:
Q: Handling two different functions with the same name in Doxygen I have a C project which contains two functions with the same name, but each is within a different group/module (@defgroup).
These functions each compile into a different binary, but I need the documentation to be closely cross-referenced, so I need to refer (@ref) to these functions (among other places) from each other's module.
When I do simple @ref name-of-the-function, it always links to the one which resides in file which is earlier in the file tree. How can I link to the other one?

A: As far as I can see: doxygen's autolinking does not support having multiple functions with the same name.
If there are multiple functions/methods with the same name, doxygen will simply link the first one it finds, as described in the question. The call graphs will also be incorrect. This seems to apply to all languages, not just to C.
This has been reported as a bug multiple times:

*

*#3676 bad links in source code browser for multiple functions of same name

*#5448 Different Static Functions With Same Name Confusion

*#979 Mismatched documentation for functions having same name

*#3724 \relates confused on multiple static functions with the same name
The section "Known problems" in doxygen's docs also describes a similar problem:

It is not possible to insert a non-member function f in a class A
  using the \relates or \relatesalso command, if class A already has a
  member with name f and the same argument list.

There is some hope; someone proposed a patch to better handle functions with the same name:  #4365 getDefs fails to resolve local function names if same global name exist.

This patch implements the following two strategies for resolving
  duplicated names. First, is the name is defined in current file, use
  the local name. Secondly try to match the names using the prototype
  definition.

This would partly solve the problem. Unfortunately, the ticket has seen no activity since 2012...

A: can this work for you?
The example is stripped down to the two files a.c and b.c, with only one function (the clashing) function.
file a.c
/**
 * \defgroup agroup Group A
 */

/**
 * the function in a,
 * see also \link b.c myfunc() \endlink the other one
 * \ingroup agroup
 */
void myfunc() {
    ;
}

file b.c
/**
 * \defgroup bgroup Group B
 */

/**
 * the function in b,
 * see also \link a.c myfunc() \endlink the other one
 * \ingroup bgroup
 */
void myfunc() {
    ;
}

as you see, myfunc() has a name clash. I placed a link to the other function in the documentation.
I prepended the function name by the filename.
I compiled it with doxygen and the links worked (they linked from each documentation of a function to the other function).

A: A solution that works for me in doxygen 1.8.13 is to provide an explicit link with the HTML  tag. For example, I have a function QF_run(), which is defined in three different files qv.c, qk.c and qxk.c. Here are three links to these three definitions:
QF_run()
QF_run()
QF_run()

These links are rendered in the HTML output the same way as the automatically generated links. The links are also stable as long as you don't change the name of the function.
To obtain the hash-value for your function, simply open its documentation in a browser and copy the link after the # sign.

A: No answer but same problem with C++ enums.
We're generally lazy and copy the main.cpp from one of our CLI tool to the next...
So they all contain:
enum class Command {
    USAGE,
    SOME_COMMAND,
}

Most of these tools are diagnostics, PoC, live test tools for libs, etc...
We build a single doc from all of our sources so the multiple declarations of this enum, even though they lie in different directories, will be found in the doc only once in the first file parsed and will contain ALL of the values declared in all the files... using clang parsing does not change anything there...
That is quite misleading. The call graphs are wrong too of course...


text:
Q: why am i getting none at the end of my output in the following code and how to avoid it? class A:
    def __init__(self, initialage):
        self.age= initialage
        print(self.age)
        print(initialage)
    def increaseby1(self):
        self.age += 1
        print(self.age)
a=A(5)
print(a.increaseby1())

A: Your function doesn't have a return value, meaning it implicitly returns None. To avoid that, either don't wrap the function call in a print statement or return the value you intended to print inside the function

A: Because your function doesn't return anything, it just prints age. And since you try to print it's returning value, which is None, it prints None
I suppose you want to print just the self.age, and you want to get rid of printing None.
The solution to this problem would be:
a.increaseby1() instead of print(a.increaseby1())
So you print the value you want in the function, and then just call it, instead of printing it's returning value, which is None
or
return self.age instead of print(self.age) in your increaseby1 function. This way your function will increment the value and the return it, so when you call your function in print statement it will print self.age


text:
Q: Assistance needed on the following error: "Invalid Next Control Variable Reference" I am currently writing code in VBA which will pull information from Oddschecker. Having inspected the relevant site, I can see the following:

         <tr data-bname="Competitor A", data-hcap-sort="1"

I am trying to capture Competitor A's name, as well as their ranking (as displayed under data-hcap-sort).
However, I am encountering the following error message:
Runtime error 13.Type Mismatch
I'm not sure if I am using the incorrect tags/variables, or, whether there is something basic I am overlooking.
Option Explicit

Sub ProcessHTMLPage(HTMLPage As MSHTML.HTMLDocument)

    Dim HTMLTable As MSHTML.IHTMLElement
    Dim HTMLTables As MSHTML.IHTMLElementCollection
    Dim HTMLRow As MSHTML.IHTMLElement
    Dim HTMLHCap As MSHTML.IHTMLElement

    Set HTMLTables = HTMLPage.getElementById("t1")

    For Each HTMLTable In HTMLTables
        Debug.Print HTMLTables

    For Each HTMLRow In HTMLTables.getElementsByTagName("data-bname")
        Debug.Print HTMLRow.innerText
    Next HTMLRow

    For Each HTMLHCap In HTMLTables.getElementsByTagName("data-hcap-sort")
        Debug.Print HTMLHCap.innerText
    Next HTMLHCap

 End Sub

Thank you in advance for any assistance in advance. A novice with VBA, so please excuse my ignorance.

A: The "Next Control Variable" is foo in this example:
For Each foo In bar
Next foo

When you specify an identifier after Next (it's optional), it must match exactly with the loop control variable's identifier.
For Each foo In Bar
Next zoo '<~ illegal

Just remove them all:
For Each foo In Bar
Next

As for the type mismatch error, I suspect it's this line:
Debug.Print HTMLTables

Trying to print/output an array will throw a type mismatch error 13 like you're getting. Looks like you mean that to be:
Debug.Print HTMLTable

...although, looking at your post's edit history, I'm not sure what your actual code is anymore.


text:
Q: Symfony 2.7 - multiple nested/embedded Forms I would really appreciate if someone could help me. I spend some hours with this problem and could not find a solution.
The code works fine (see below), as long as I don't need a second AddressType Class within PersonType Class. Something like this does not work:
// PersonType:
       $builder
            ->add('firstname', 'text')
            ->add('middlename', 'text')
            ->add('lastname', 'text')
            ->add('address', new AddressType())
            ->add('address', new AddressType());

Multiple FormTypes of the same Type will have the same HTML-IDs so Symfony does not render the second address. I have several questions on that topic:

*

*Do I need the CollectionType even if I need only two address or is there another way (I don't need the user to be able to add dynamically another address)?

*Let's assume I need the CollectionType. At the beginning a CollectionType is empty. But I need two addresses from the start. I found the following in the Symfony-Documentation to create some collection items from the start: Form Collections
// Controller:
$task = new Task();
// dummy code - this is here just so that the Task has some tags
// otherwise, this isn't an interesting example
$tag1 = new Tag();
$tag1->setName('tag1');
$task->getTags()->add($tag1);
$tag2 = new Tag();
$tag2->setName('tag2');
$task->getTags()->add($tag2);

Now, please look at my controller. I don't even create a entity. I only create the main FormType which has all other Formtypes embedded. How or where can I create the two addresses? Or even my whole Controller-Code is wrong?

*Is there a solution to tell symfony that the first address is not the same as the second address? How can I set the name/id of each AddressType? (This solution does not work anymore.)

*Is the form generation really ok in my controller? I don't pass a entity or an array to the form. It works, but I wonder why.... Otherwise I don't know how to pass all the entities I need to the form (contract, person, address, customer, payment, etc.).
Thanks in advance!
Controller:
class DefaultController extends Controller{
/**
 * @return array
 * @Route("/private")
 * @Template("DmmGenericFormBundle:Default:index.html.twig")
 */
public function indexAction(Request $request)
{
    // This formtype class has all other form type classes
    $privateRentDepositForm = new PrivateRentDepositType();

    $form = $this->createForm($privateRentDepositForm);

    $form->handleRequest($request);

    if($form->isValid()){

        $contract =          $form->get('contract')->getData();
        $privateContractDetails = $form->get('privateContractDetails')->getData();

        $customer =          $form->get('customer')->getData();
        $customerPerson =    $form->get('customer')->get('person')->getData();

        $privateRealEstate =          $form->get('privateRealEstate')->getData();
        $privateRealEstateAddress =   $form->get('privateRealEstate')->get('address')->getData();

        $landlord =          $form->get('privateRealEstate')->get('landlord')->getData();
        $landlordPerson =    $form->get('privateRealEstate')->get('landlord')->get('person')->getData();

        $caretakerPerson =   $form->get('privateRealEstate')->get('landlord')->get('caretaker')->get('person')->getData();

        $payment =           $form->get('payment')->getData();

        $contract->addPerson($customerPerson);
        $contract->addPerson($landlordPerson);
        $contract->addPerson($caretakerPerson);
        $contract->setPrivateContractDetails($privateContractDetails);

        $customer->setPayment($payment);

        $landlord->setPrivateRealEstate($privateRealEstate);

        $privateRealEstate->addCustomer($customer);
        $privateRealEstate->setLandlord($landlord);

        $em = $this->get('doctrine')->getManager();
        $em->persist($contract);
        $em->flush();
    }
    return array('form' => $form->createView());
}

Form Type Classes:
class PrivateRentDepositType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder
            ->add('contract', new ContractType())
            ->add('privateContractDetails', new PrivateContractDetailsType())
            ->add('customer', new CustomerType())
            ->add('privateRealEstate', new PrivateRealEstateType())
            ->add('payment', new PaymentType())
            ->add('save', 'submit');
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => null,
            'csrf_protection' => false
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'FormStep';
    }
}

Person Type Class:
class PersonType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstname', 'text')
            ->add('middlename', 'text')
            ->add('lastname', 'text')
            ->add('address', new AddressType());

    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            [
                'data_class' => 'Dmm\Bundle\GenericFormBundle\Entity\Person',
                'config' => null,
            ]
        );
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'dmm_bundle_genericformbundle_person';
    }
}

Address Type Class:
class AddressType extends AbstractType
{

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('street', 'text')
            ->add('housenumber', 'text')
            ->add('zip', 'text')
            ->add('city', 'text')
            ->add('extra', 'text')
            ->add('country', 'text')
            ->add('postOfficeBox', 'integer')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            [
                'data_class' => 'Dmm\Bundle\GenericFormBundle\Entity\Address',
                'config'     => null,
            ]
        );
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'dmm_bundle_genericformbundle_address';
    }
}

Customer Type Class:
class CustomerType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('person', new PersonType())
            ->add('birthplace', 'text')
            ->add('email', 'email')
            ->add('phone', 'text');

    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            [
                'data_class' => 'Dmm\Bundle\GenericFormBundle\Entity\Customer',
                'config'     => null,
            ]
        );
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'dmm_bundle_genericformbundle_customer';
    }
}

DB Associations
Contract:Person = 1:n (Owning Side: Person, ArrayCollection for Person in Contract)
Person:Address = 1:n (Owning Side: Address, ArrayCollection for Address in Person)
Person:Customer = 1:1 (Owning Side: Customer, Customer IS A Person)
Edit:
Code edit for Solution 2 by Cerad
Controller - create all objects
   $contract = new Contract();
   $contractDetails = new PrivateContractDetails();
   $contract->setPrivateContractDetails($contractDetails);

   $customer1Person = new Person();
   $customer1Address1 = new Address();
   $customer1Address1->setAddressType('someAddress');
   $customer1Address2 = new Address();
   $customer1Address2->setAddressType('someAddress');
   $customer1Person->addAddress($customer1Address1);
   $customer1Person->addAddress($customer1Address2);
   $contract->addPerson($customer1Person);
   $customer1 = new Customer();
   $customer1->setPerson($customer1Person);

   $customer2Person = new Person();
   $customer2Address1 = new Address();
   $customer2Address1->setAddressType('someAddress');
   $customer2Address2 = new Address();
   $customer2Address2->setAddressType('someAddress');
   $customer2Person->addAddress($customer2Address1);
   $customer2Person->addAddress($customer2Address2);
   $contract->addPerson($customer2Person);
   $customer2 = new Customer();
   $customer2->setPerson($customer2Person);

   $landlordPerson = new Person();
   $landlordPersonAddress = new Address();
   $landlordPersonAddress->setAddressType('someAddress');
   $landlordPerson->addAddress($landlordPersonAddress);
   $contract->addPerson($landlordPerson);
   $landlord = new Landlord();
   $landlord->setPerson($landlordPerson);

   $prEstate = new PrivateRealEstate();
   $prEstateAddress = new Address();
   $prEstateAddress->setAddressType('someAddress');
   $prEstate->setAddress($prEstateAddress);
   $landlord->setPrivateRealEstate($prEstate);
   $prEstate->addCustomer($customer1);
   $prEstate->addCustomer($customer2);

   $caretakerPerson = new Person();
   $caretakerAddress = new Address();
   $caretakerAddress->setAddressType('someAddress');
   $caretakerPerson->addAddress($caretakerAddress);
   $contract->addPerson($caretakerPerson);
   $caretaker = new Caretaker();
   $caretaker->addLandlord($landlord);
   $caretaker->setPerson($caretakerPerson);

   $payment = new Payment();
   $customer1->setPayment($payment);

    $privateRentDepositForm = new PrivateRentDepositType();

    $form = $this->createForm($privateRentDepositForm, $contract);

And I replaced
->add('address', new AddressType());

with
->add('address', 'collection', array(
    'type' => new AddressType()
))

Now I get the following exception:
The form's view data is expected to be of type scalar, array or an instance of \ArrayAccess, but is an instance of class Dmm\Bundle\GenericFormBundle\Entity\Contract. You can avoid this error by setting the "data_class" option to "Dmm\Bundle\GenericFormBundle\Entity\Contract" or by adding a view transformer that transforms an instance of class Dmm\Bundle\GenericFormBundle\Entity\Contract to scalar, array or an instance of \ArrayAccess.
In ContractType the data_class is set to the right class. Only in PrivateRentDepositType the data_class is set to null. But PrivateRentDepositType is a collection of diffrent types. I tried to set the data_class to 'Dmm\Bundle\GenericFormBundle\Entity\Contract' but that leads to another excepiton: Neither the property "contract" nor one of the methods "getContract()", "contract()", "isContract()", "hasContract()", "__get()" exist and have public access in class "Dmm\Bundle\GenericFormBundle\Entity\Contract".

A: There are two basic approaches you can use.
Given that each person needs two and only two addresses then the quickest approach would be to do:
   // Form type
   $builder
        ->add('firstname', 'text')
        ->add('middlename', 'text')
        ->add('lastname', 'text')
        ->add('address1', new AddressType(),
        ->add('address2', new AddressType());

Add address1/address2 getter/setters to your Person entity.  Internally, the Person can still store addresses in any array.  But as far as the form type goes, each is individually accessible.  Everything else should work.
The second approach is a bit more Symfonyish and basically involves creating and initializing a new contract and passing it to the form.  That would eliminate the need to do so much processing after the form is submitted.  So in your controller you would have:
$contract = new Contract();
$customerPerson = new CustomerPersion();
$contract->addPerson($customerPerson);
...
$privateContractDetails = new PrivateContractDetails()
...
$privateRentDeposit = [
    'contract' => $contract,
    'privateContractDetails' => new $privateContractDetails,
    ... rest of objects ...
];
...
$form = $this->createForm($privateRentDepositForm,$privateRentDeposit);
---
if ($form->isValid()) {
    $em->persist($contract);

There of course is a lot more to creating your contract (aka aggregate root) then what is shown but you should get the idea.  I would move it all into a createContract factory method somewhere.  This approach allows you to add two address to your person entities which in turn means you can use the form collection stuff out of the box.
One final note:  forms have changed significantly in S3.x.  new FormType() no longer works.  Consider updating to at least S2.8 (which has the new form stuff) otherwise you will be facing a major rewrite if you ever do move to S3+.


text:
Q: gamma adjustment is not working on ubuntu 21.04 I'm using dell with intel graphics I tried xgamma and xrandr for adjusting gamma values but both of them not working in 21.04, they are executing successfully but rgb value remains the same, it used to work fine in groovy. Is it happening cuz of the new update or some other reason? Is there any other alternative?

A: Switch to Ubuntu on Xorg and try again. To do so, logout → click on your username → click on the settings icon at the bottom right corner and select Ubuntu on Xorg.


text:
Q: Typescript covert to javascript How to write this typescript in javascript please help me...
I'm new to typescript
  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    setChecked(e.target.checked);
  };

A: Just remove the type information.
const handleChange = (e) => {
    setChecked(e.target.checked);
 };


text:
Q: How to work transactionally with spring-integration-smb I am new to the Spring Integration project. I am trying to process remote files (from an SMB2 share) transactionally with the spring-integration-smb project. With the help of this blog post I was able to process files transactionally (with Spring's PseudoTransactionManager) on the local filesystem. Now I've tried to adjust the sample to process files on a remote share (SMB), but I haven't found a solution to make to processing transactional. Have you any idea how I can implement such a transactional processing?

A: You still can use similar approach with a PseudoTransactionManager and TransactionSynchronizationFactory combination to track your transaction statuses.
For rollback-kinda operations you can use an SmbRemoteFileTemplate to call its rename(), remove() etc. operations. The failed message contains for you all necessary info in the headers:
messageBuilder.setHeader(FileHeaders.REMOTE_HOST_PORT, uri.getHost() + ':' + uri.getPort())
                    .setHeader(FileHeaders.REMOTE_DIRECTORY, uri.getPath())
                    .setHeader(FileHeaders.REMOTE_FILE, uri.getFragment());


text:
Q: Is there a JInterop replacement ? Beacause the JInterop follows GPL version 3, so we want to find anther one works just like it.
Inlcude commercial product. Is there anyone who can help me?

A: Maybe you try j-integra (commercial) or Jacob (LGPL).
PS: I only work with j-interop, so I could not say if one of them could really replace j-interop. Jacob I think works only on windows machines.


text:
Q: What context should I pass to SQLite What context should I pass when using SQLite?
I got error :  Fragment TimeTableFragment{f07e75e} not attached to a context.
My app works like :
DeleteDialog Ok button-> deleteColum ,
TimeTableFragment.sendData(Context context)  *sendData is draw data in layout
DeleteDialog.java

public class DeleteDialog extends android.support.v4.app.DialogFragment {

private Context mContext;
TimeTableFragment timeTableFragment;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable
ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.activity_delete_dialog, container, false);

    mContext=this.getActivity();

...

timeTableFragment = new TimeTableFragment();
    ok_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(editText.getText().toString().equals("")){
                Toast.makeText(getContext(), "과목명을 입력해 주세요", Toast.LENGTH_SHORT).show();

            }else{

                dbHelper = new DBHelper(mContext);
                db = dbHelper.getWritableDatabase();
                dbHelper.deleteColum(editText.getText().toString());
                timeTableFragment.sendData(mContext);
                getDialog().dismiss();
            }

        }
    });

TimeTableFragment.java
private Context mContext;

public void sendData(Context context) {

    //Log.d("tag", " 컨텍스트" + getContext()==null? "yes": "no");
    dbHelper = new DBHelper(context);
    db = dbHelper.getWritableDatabase();
    dbHelper.onCreate(db);
    String date = "", start = "", end = "", title = "", color = "";

    ArrayList<SubjectItem> timetable_data;
    timetable_data = dbHelper.getDataTimetable(); //get data from sql
    SimpleDateFormat sf = new SimpleDateFormat("HHmm");

    int resID = 0;
    int mok;
    Date a, b;
    long diff, min;
    View view = getView();

    for (int i = 0; i < timetable_data.size(); i++) {
        date = timetable_data.get(i).getSub_date();
        start = timetable_data.get(i).getSub_start();
        end = timetable_data.get(i).getSub_end();
        title = timetable_data.get(i).getSub_title();
        color = timetable_data.get(i).getSub_color();

        if (date.substring(0, 2).equals("Th")) {
            date = "h";
            Log.d("ㄹㄹ","목요일 : " +date);
        }
        date = date.toLowerCase().substring(0, 1);
        Log.d("ㄹㄹ","바깥의 데이터 : " +date);
        start = start.replace(":", "");
        end = end.replace(":", "");

        try {
            a = sf.parse(start);
            b = sf.parse(end);
            diff = b.getTime() - a.getTime();
            min = (diff / (1000 * 60));
            mok = (int) min / 30;

            Log.d(TAG,"title " +title + " start :  " + start +","+ a.getTime()+ " / end : " +  end+","+b.getTime() +   "   date : " + date);

            for (int k = 0; k < mok; k++) {

                if (mok != 1) {

                    if (end.substring(2, 4).equals("30")) {
                        end = Integer.toString(Integer.parseInt(end) - 30);
                        if (end.length() == 3) end = "0" + end;
                        Log.d(TAG, " 그리기 title :  " +title );
                        resID = getResources().getIdentifier(date + end, "id", mContext.getPackageName());
                        TextView textView = (TextView) view.findViewById(resID);
                        textView.setText(title);
                        paintTimetable(textView,color);

                    } else {
                        end = Integer.toString(Integer.parseInt(end) - 70);
                        if (end.length() == 3) end = "0" + end;
                        resID = getResources().getIdentifier(date + end, "id", mContext.getPackageName());
                        TextView textView = (TextView) view.findViewById(resID);
                        textView.setText(title);
                        paintTimetable(textView,color);
                        Log.d(TAG, " 그리기 title :  "  +title);
                    }
                } else {
                    resID = getResources().getIdentifier(date + start, "id", mContext.getPackageName());
                    TextView textView = (TextView) view.findViewById(resID);
                    textView.setText(title);
                    paintTimetable(textView,color);

                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    try {

        mContext=getContext();
    } catch (ClassCastException e) {
        Log.d(TAG, "Exception" + e.getMessage());
    }
}

My DBHelper.java
public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);

}

...

public void deleteColum(String name)
{
    String DELETE = "DELETE FROM " + TABLE_TIMETABLE + " WHERE " + KEY_TITLE + "='" + name + "'";

    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL(DELETE);
    Log.d("dd", "sql deleted  :  " + name);

}

and my logCat :
ragment TimeTableFragment{f07e75e} not attached to a context.
    at android.support.v4.app.Fragment.requireContext(Fragment.java:696)
    at android.support.v4.app.Fragment.getResources(Fragment.java:760)
    at com.example.a13.timetable4.TimeTableFragment.sendData(TimeTableFragment.java:138)
    at com.example.a13.timetable4.DeleteDialog$1.onClick(DeleteDialog.java:52)

A: Use this:
 mContext = this.getContext();

Instead of:
 mContext = this.getActivity();


text:
Q: How to tweet both URL and Hashtags Following this example on another thread, I am able to tweet either the URL:
String tweetUrl = "https://twitter.com/intent/tweet?text=PUT TEXT HERE &url="
                        + "https://www.google.com";
Uri uri = Uri.parse(tweetUrl);
startActivity(new Intent(Intent.ACTION_VIEW, uri));

which shows up as:

PUT TEXT HERE https://www.google.com

or the hashtags:
String tweetUrl = "https://twitter.com/intent/tweet?text=PUT TEXT HERE &url="
                        + "https://www.google.com &hashtags=android,twitter";
Uri uri = Uri.parse(tweetUrl);
startActivity(new Intent(Intent.ACTION_VIEW, uri));

which shows up as:

PUT TEXT HERE #android #twitter

But for some reason, I am unable to show both the URL and the hashtags in the twitter box.
What am I doing wrong?

A: Answering my own question: There shouldn't be a space before &hashtags. In other words, the above should be written:
String tweetUrl = "https://twitter.com/intent/tweet?text=PUT TEXT HERE &url="
                        + "https://www.google.com&hashtags=android,twitter";
Uri uri = Uri.parse(tweetUrl);
startActivity(new Intent(Intent.ACTION_VIEW, uri));

Hope this helps someone.


text:
Q: Putty's SSH->Remote Command does not work at all Every morning, and multiple times throughout the day, I need to open an ssh session to a VM that is behind a proxy-jump. Since putty doesn't have a native proxy-jump capability, I just log in to the jump server and ssh over. However, this is a bit cumbersome and prone to error if my attention slips between opening the jump-server and the ssh, which it will do in an office environment.
The most rated suggestions are to use Remote Commands, such as How to setup proxy jump with PuTTY and add the command I want to execute on connection. However, Remote Command does not work at all. It will not ssh (remote command = 'ssh {destination IP}'), nor will it even echo or cd or ls. The only thing that happens when I pass a Remote Command to the jump server is that it will not print the MoTD and leave me at prompt like normal. What can I do to troubleshoot this?
Attempting to use plink instead of Remote Command:
(Attempt #1)

*

*Created new session. Host Name (or IP address) = {ProxyJump IP} on port 22 (SSH).

*Connection -> Proxy. Proxy type = local. Proxy hostname = {ProxyJump IP}. Port = 22. Username = {username}. Password = {password}. Telnet command, or local proxy command = 'plink.exe %user@%proxyhost -nc %host:%port'

*Result: Blank screen where title = {ProxyJump IP}. No prompt. No Destination VM IP given, so wouldn't work in hindsight.

(Attempt #2)

*

*Created new session. Host Name (or IP address) = {Destination VM IP} on port 22 (SSH).

*Connection -> Proxy. Proxy type = local. Proxy hostname = {ProxyJump IP}. Port = 22. Username = {username}. Password = {password}. Telnet command, or local proxy command = 'plink.exe %user@%proxyhost -nc %host:%port'

*Result: Blank screen where title = {Destination VM IP}. No prompt.

(Attempt #3)
After seeing Putnik's comment on https://stackoverflow.com/questions/28926612/putty-configuration-equivalent-to-openssh-proxycommand, I added my path to my ssh key.

*

*Created new session. Host Name (or IP address) = {Destination VM IP} on port 22 (SSH).

*Connection -> Proxy. Proxy type = local. Proxy hostname = {ProxyJump IP}. Port = 22. Username = {username}. Password = {password}. Telnet command, or local proxy command = 'plink.exe %user@%proxyhost -ssh -i {path/to/key} -nc %host:%port'

*Result: Prompts for username. Once entered, logs me in as I would expect it to!

A: After trying multiple ways, the short answer is: No. Remote Command does not work this way.
An alternative, as suggested via, Martin Prikryl, is instead of using SSH: Remote Command, use the Connection->Proxy option with plink.exe.
I created a session pointing to my destination VM IP that exists behind the proxyJump. Then, in Connection->Proxy I set up a local proxy where the proxy host name is my ProxyJump server's IP, and for the 'local proxy command' I used "plink.exe %user@%proxyhost -ssh -i path\to\key.ppk -nc %host:%port"
I still have to enter my username even if I try adding it in the Username field, or if I replace the '%user' in the local command with my username, but this is good enough for what I want.


text:
Q: Jquery - Open a new window with content from the current page I'm trying to create a 'print' button to open a new window and display a PHP Variable in it.
The code below is looped through the PHP script as many times as there are tickets, however I can't seem to get the correct number to display when the window opens (the number that displays in the print link is correct - but when the new window is opened it's incorrect).

Print <?php echo $EM_Booking->get_spaces() ?>

<?php echo $EM_Booking->get_spaces() ?>

A: why not try something like this:
Print <?php echo $EM_Booking->get_spaces() ?>

        <?php echo $EM_Booking->get_spaces() ?>

But much better solution would be to give a button a unique ID, and onclick open an existing (php-generated) page from the server passing that ID, e.g. /getBooking.php?id=123 and that page would output whatever's needed.


text:
Q: Does the sandwich estimator in GEE protect against both correlation misspecification and heteroscedasticity? The relative merits of GEE with exchangeable correlation or GEE with independence and the sandwich estimate have been discussed, but I couldn't find a post specifically addressing my question.
I have analyzed longitudinal data using GEE with AR(1) correlation structure and the sandwich/robust estimates of the standard errors.
In the case of longitudinal data, the sandwich estimates are used to protect against miss-specifications of the correlation structure. The AR(1) was chosen based on the auto-correlation function of the data since it will produce a more efficient estimate than assuming independence. However, the univariate distrubitions of the outcomes are positively skewed and the residuals from the models exhibit some heteroscedasticity.
For GEE with longitudinal (or more generally, clustered) data, does the sandwich estimate protect against heteroscedasticity (what it was developed to do) in addition to its intended use to protect against miss-specificaiton of the correlation structure? Does reducing the heteroscedastcity with a log transformation of the outcome offer more efficiency for the estimate or some other benefit?
I would especially appreciate a reference to a journal article addressing this issue.

A: Yes. Sandwich estimator for $\mathrm{Cov}(\hat{\beta})$ is robust to the assumption of covariance, which include both the variances and correlations. A good reference of book is on page 359 of Applied Longitudinal Analysis.
Note that we sometimes call sandwich estimator as "semi-robust", since it is only robust to the misspecification of variance-covariance model, but is not robust to the mean model.
When doing exploratory analysis about the variance-covariance structure, I would suggest to remove the effects of covariates first, i.e., to examine the residuals. In this way, we can truely assess the variance-covariance structure of the error term without the influence of variability from the covariates.
Unlike mixed-effects models, we cannot rigorously test two nested variance-covariance models by likelihood ratio tests. GEE is based on quasi-likelihood, so no likelihood-based method is available to test variance models. On the other hand, if you are interested in the subject specific interpretation, mixed-effects models may help to take into account subject-level heterogeneity.
The transformation of the outcome may reduce the heterogeneity. But I would suggest you to transform the data based on the real relationship between the covariates and outcome, since sometimes the transformation makes the interpretation harder. If your response is count, you can use Poisson regression which adopts log link function.


text:
Q: How to generate dynamic form using JavaScript/JQuery? Suppose a form.php file, and there is "add" button, once it's clicked, a drop down list will show, to let you choose which type of input type you want. For example:
<select name="Type">
        <option value="Text">Text</option>
    <option value="MultipleChoice">MultipleChoice</option>
    <option value="Checkbox">Checkbox</option>
</select>

My question is, I don't know how to implement the function that, once the type is chosen, suppose checkbox, then a checkbox will shown, and could let you input the label of each checkbox, you can do this one by one.
Also I want to make this process could happen iteratively. I'm not sure if I explain clearly, it's a little bit like the google form function. Any ideas? If providing some codes would be better. Thanks!

A: Here is plain vanilla old school HTML/JS
<select name="Type" onchange="showformelement(this.value)">
    <option value="text">Text</option>
<option value="MultipleChoice">MultipleChoice</option>
<option value="Checkbox">Checkbox</option>
</select>
<script>
function showformelement(whichelement){
    //use whichelement to embedd element in DOM
}
</script>

If you can use jQuery or similar toolkit it may be a much simpler job

A: I know what are you looking for, just let you know that it isn't a simple script, it will have way too many functions and will be little hard to build.
Just to start, if you search on the web for PHP and jQuery based form builders and similar other things, you will find many ready to use scripts. Well, if you don't want to search for one, the principle logic will look like following:
PS: I will explain how to develop using jQuery.
<select id="options">
<option value="1"></option>
<option value="2"></option>
<option value="3"></option>
</select>

<script>
$(document).ready(function(){
$('#options').change(function(){
var optSelected = $('#options option:selected').val()
  if(optSelected == 1){
    // Shows up and div with Checkboex for edit
  }
  if(optSelected == 2){
    // Shows up and div with Combobox for edit
  }
  if(optSelected == 3){
    // Shows up and div with Textbox for edit
  }
  })
})
</script>

After doing that, you will need to build the options of each type...
There is too much work... look, I didn't write here your script, I just explained you how to build...
This is a huge system...you will need to know a bit of JavaScript to make one of these...

A: Even simpler, without needing to do any casing or conditioning, (uses jQuery).
Example: http://jsfiddle.net/SMAfA/
$(function() {
    $("#type").change(function() {
        type = $("option:selected", this).text();
        $("#target").append("<input type="+type+">");
    })
})


text:
Q: I Enabled my Google drive API, but still I got error code "Project has not enabled the API." As you can see in the image below Google drive API is enabled

And when I run my code I got error that tell me:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "Project has not enabled the API. Please use Google Developers Console to activate the API for your project.",
    "reason" : "forbidden"
  } ],
  "message" : "Project has not enabled the API. Please use Google Developers Console to activate the API for your project.",
  "status" : "PERMISSION_DENIED"

}
I used service account methodology, and I also try  OAuth2.0 client id, and i got the same error.
Is there something i missed for enabling driver api.
Note:

*

*Scope I am trying to use (DriveScopes.DRIVE "https://www.googleapis.com/auth/drive")

*

*I set all the info that need in Driver UI integration.

A: Thanks all for helping
I found the issue in my code, I used this line
Operation op = service.scripts().run(scriptId, request).execute();

where it required to have the following api also (Google Apps Script Execution API) where I have to enable it...

A: You are missing one you need Drive SDK as well.


text:
Q: Permissions.getAsync or Permissions.askAsync Not working in RealseAPK on Expo SDK33 Steps to Reproduce
Connect the actual device to the Android studio, start an extension, and then click the Run app button in the Android studio to install the app on the device. The permissions check is successful in this app.
However, after 'expo publish' build  => signed Bundle APK => select APK => click release=>   V1,V2 Check => APK on the device to run.
Pressing a button does not generate an alert for the privilege.
Expected Behavior
Shall be operated like a  simulator apk.
Actual Behavior
The actual APK does not notify you of any permissions.
Reproducible Demo
https://snack.expo.io/H1sswTuyS
import React, { Component } from "react";
import {
  Platform,
  StyleSheet,
  View,
  Text,
  Modal,
  TouchableOpacity,
  TouchableHighlight,
  Image,
  Alert,
  NativeModules
} from "react-native";
import * as Permissions from "expo-permissions";
import { Ionicons } from "@expo/vector-icons";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      alertVisibility: true
    };
  }

  static navigationOptions = ({ navigation }) => {
    return {
      headerLeft: (
        <TouchableOpacity style={{ paddingLeft: 25 }} onPress={() => {}}>
          <Ionicons
            name={"ios-arrow-back"}
            size={30}
            color={"#ffffff"}
          />
        </TouchableOpacity>
      ),

      headerRight: null
    };
  };

  showCustomAlert(visible) {
    this.setState({ alertVisibility: visible });
  }

  okButton = async () => {
    this.setState({
      buttonColor: "#ffd90d"
    });
    const permission = await Permissions.getAsync(Permissions.CAMERA_ROLL);
    if (permission.status !== "granted") {
      const newPermission = await Permissions.askAsync(Permissions.CAMERA_ROLL);

      if (newPermission.status === "granted") {
        const permission2 = await Permissions.getAsync(Permissions.CAMERA);
        if (permission2.status !== "granted") {
          const newPermission2 = await Permissions.askAsync(Permissions.CAMERA);
          if (newPermission2.status === "granted") {
            const permission3 = await Permissions.getAsync(
              Permissions.NOTIFICATIONS
            );
            if (permission3.status !== "granted") {
              const newPermission3 = await Permissions.askAsync(
                Permissions.NOTIFICATIONS
              );
              if (newPermission3.status === "granted") {
                const permission4 = await Permissions.getAsync(
                  Permissions.REMINDERS
                );
                if (permission4.status !== "granted") {
                  const newPermission4 = await Permissions.askAsync(
                    Permissions.REMINDERS
                  );
                  if (newPermission4.status === "granted") {
                    this.setState({ alertVisibility: false });
                    this.props.navigation.navigate("RegisterWalletIndex");
                  } else {
                    this.setState({ alertVisibility: false });
                    this.props.navigation.navigate("RegisterWalletIndex");
                  }
                }
                if (permission4.status === "granted") {
                  console.log(
                    "permission4.status not granted"
                  );
                } else {
                 console.log(
                    "permission4.status not granted"
                  );
                }
              } else {
                const permission4 = await Permissions.getAsync(
                  Permissions.REMINDERS
                );
                if (permission4.status !== "granted") {
                  const newPermission4 = await Permissions.askAsync(
                    Permissions.REMINDERS
                  );
                  if (newPermission4.status === "granted") {
                    this.setState({ alertVisibility: false });
                    this.props.navigation.navigate("RegisterWalletIndex");
                  } else {
                    this.setState({ alertVisibility: false });
                    this.props.navigation.navigate("RegisterWalletIndex");
                  }
                }
                if (permission4.status === "granted") {
                  console.log(
                    "permission4.status not granted"
                  );
                } else {
                  console.log(
                    "permission4.status not granted"
                  );
                }
              }
            }
            if (permission3.status === "granted") {
              console.log(
                    "permission4.status not granted"
                  );
            } else {
               console.log(
                    "permission4.status not granted"
                  );
            }
          } else {
            const permission3 = await Permissions.getAsync(
              Permissions.NOTIFICATIONS
            );
            if (permission3.status !== "granted") {
              const newPermission3 = await Permissions.askAsync(
                Permissions.NOTIFICATIONS
              );
              if (newPermission3.status === "granted") {
                const permission4 = await Permissions.getAsync(
                  Permissions.REMINDERS
                );
                if (permission4.status !== "granted") {
                  const newPermission4 = await Permissions.askAsync(
                    Permissions.REMINDERS
                  );
                  if (newPermission4.status === "granted") {
                    this.setState({ alertVisibility: false });
                    this.props.navigation.navigate("RegisterWalletIndex");
                  } else {
                    this.setState({ alertVisibility: false });
                    this.props.navigation.navigate("RegisterWalletIndex");
                  }
                }
                if (permission4.status === "granted") {
                  console.log(
                    "permission4.status not granted"
                  );
                } else {
                  console.log(
                    "permission4.status not granted"
                  );
                }
              } else {
                console.log(
                    "permission3.status not granted"
                  );
                const permission4 = await Permissions.getAsync(
                  Permissions.REMINDERS
                );
                if (permission4.status !== "granted") {
                  const newPermission4 = await Permissions.askAsync(
                    Permissions.REMINDERS
                  );
                  if (newPermission4.status === "granted") {
                    this.setState({ alertVisibility: false });
                    this.props.navigation.navigate("RegisterWalletIndex");
                  } else {
                    this.setState({ alertVisibility: false });
                    this.props.navigation.navigate("RegisterWalletIndex");
                  }
                }
                if (permission4.status === "granted") {
                  console.log(
                    "permission4.status not granted"
                  );
                } else {
                  console.log("permission4.status not granted");
                }
              }
            }
            if (permission3.status === "granted") {
              console.log(
                    "permission4.status not granted"
                  );
            }
          }
        }
        if (permission2.status === "granted") {
          console.log(
                    "permission4.status not granted"
                  );
        } else {
          console.log(
                    "permission4.status not granted"
                  );
        }
      } else {
        alert("close");
      }
    } else {
      if (permission.status === "granted") {
        console.log(
                    "permission4.status not granted"
                  );
      } else {
        console.log(
                    "permission4.status not granted"
                  );
      }
    }
  };

  androidButton = async () => {
    const permission = await Permissions.getAsync(Permissions.CAMERA_ROLL);
    if (permission.status !== "granted") {
      const newPermission = await Permissions.askAsync(Permissions.CAMERA_ROLL);
      if (newPermission.status === "granted") {
        const permission2 = await Permissions.getAsync(Permissions.CAMERA);
        if (permission2.status !== "granted") {
          const newPermission2 = await Permissions.askAsync(Permissions.CAMERA);
          if (newPermission2.status === "granted") {
            const permission3 = await Permissions.getAsync(
              Permissions.NOTIFICATIONS
            );
            if (permission3.status !== "granted") {
              const newPermission3 = await Permissions.askAsync(
                Permissions.NOTIFICATIONS
              );
              if (newPermission3.status === "granted") {
                this.setState({ alertVisibility: false });
                this.props.navigation.navigate("RegisterWalletIndex");
              }
            }
            if (permission3.status === "granted") {
              this.setState({ alertVisibility: false });
              this.props.navigation.navigate("RegisterWalletIndex");
            } else {
              console.log("permission3.status not granted");
            }
          } else {
            const permission3 = await Permissions.getAsync(
              Permissions.NOTIFICATIONS
            );
            if (permission3.status !== "granted") {
              const newPermission3 = await Permissions.askAsync(
                Permissions.NOTIFICATIONS
              );
              if (newPermission3.status === "granted") {
                this.setState({ alertVisibility: false });
                this.props.navigation.navigate("RegisterWalletIndex");
              } else {
                this.setState({ alertVisibility: false });
                this.props.navigation.navigate("RegisterWalletIndex");
              }
            }
            if (permission3.status === "granted") {
              this.setState({ alertVisibility: false });
              this.props.navigation.navigate("RegisterWalletIndex");
            }
          }
        }
        if (permission2.status === "granted") {
          this.setState({ alertVisibility: false });
          this.props.navigation.navigate("RegisterWalletIndex");
        }
      } else {
        Alert.alert(
          "info",
          `Text`,
          [
            {
              text: "ok",
              onPress: () => alert("close")
            }
          ],
          { cancelable: false }
        );
      }
    } else {
      const permission2 = await Permissions.getAsync(Permissions.CAMERA);
      if (permission2.status !== "granted") {
        const newPermission2 = await Permissions.askAsync(Permissions.CAMERA);
        if (newPermission2.status === "granted") {
          this.setState({ alertVisibility: false });
          this.props.navigation.navigate("RegisterWalletIndex");
        } else {
          this.setState({ alertVisibility: false });
          this.props.navigation.navigate("RegisterWalletIndex");
        }
      } else {
        this.setState({ alertVisibility: false });
        this.props.navigation.navigate("RegisterWalletIndex");
      }
    }
  };

  render() {
    return (
      <View style={styles.MainContainer}>
        <Modal
          visible={this.state.alertVisibility}
          transparent={true}
          animationType={"fade"}
          onRequestClose={() => {
            this.showCustomAlert(!this.state.alertVisibility);
          }}
        >
          <View
            style={{
              flex: 1,
              height: "100%",
              alignItems: "center",
              justifyContent: "center",
              backgroundColor: "rgba(0,0,0,.8)"
            }}
          >
            <View style={styles.alertmainview}>
              <Text style={styles.alerttitle}>Text</Text>

              <View
                style={{
                  width: "60%",
                  height: 1,
                  backgroundColor: "#fed80c",
                  marginLeft: 20
                }}
              />

              <Text style={styles.alertmessage}>
               Text
              </Text>
              <View>
                <Text style={styles.subtitle}>Text</Text>
                <View
                  style={{
                    flexDirection: "row",
                    backgroundColor: "#efefef",
                    alignItems: "center",
                    marginLeft: 20,
                    marginRight: 20,
                    borderRadius: 3,
                    marginBottom: 10
                  }}
                >
                  <Text style={styles.subtitletextstorage}>Text</Text>
                  <Text style={styles.subtitletext2}>Text</Text>
                </View>

                <Text style={styles.subtitle}>Text Text</Text>
                <View
                  style={{
                    flexDirection: "column",
                    backgroundColor: "#efefef",
                    marginLeft: 20,
                    marginRight: 20,
                    borderRadius: 3
                  }}
                >
                  <View style={{ flexDirection: "row", marginTop: 6 }}>
                    <Text style={styles.subtitletext}>Text</Text>
                    <Text style={styles.subtitletext2}>Text Text</Text>
                  </View>
                  <View
                    style={{
                      flexDirection: "row",
                      paddingTop: 8,
                      paddingBottom: 8
                    }}
                  >
                    <Text style={styles.subtitletext}>Text</Text>
                    <Text style={styles.subtitletext2}>
                      Text
                    </Text>
                  </View>
                </View>
              </View>
              <View
                style={{
                  width: "90%",
                  height: 1,
                  backgroundColor: "#fed80c",
                  marginLeft: 20,
                  marginRight: 20,
                  marginTop: 20
                }}
              />

              <View
                style={{
                  width: "100%",
                  alignItems: "flex-end",
                  paddingRight: 20,
                  paddingTop: 10
                }}
              >
                <TouchableHighlight
                  underlayColor="#ffd90d"
                  style={styles.buttonStyle}
                  onPress={() =>
                    Platform.OS === "ios"
                      ? this.okButton()
                      : this.androidButton()
                  }
                >
                  <Text style={styles.TextStyle}> ok </Text>
                </TouchableHighlight>
              </View>
            </View>
          </View>
        </Modal>
        <Image
          style={{ width: 180, height: 180 }}
          source={require("./assets/snack-icon.png")}
          resizeMode="contain"
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  MainContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    marginTop: Platform.OS == "ios" ? 20 : 0,
    backgroundColor: "rgba(0,0,0,.8)"
  },

  alertmainview: {
    width: "90%",
    borderRadius: 8,
    backgroundColor: "#fff"
  },

  alerttitle: {
    fontSize: 18,
    textAlign: "left",
    paddingLeft: 24,
    paddingTop: 30,
    marginBottom: 10
  },

  alertmessage: {
    fontSize: 14,
    padding: 20
  },
  subtitle: {
    fontWeight: "bold",
    marginLeft: 20,
    paddingTop: 12,
    fontSize: 12,
    paddingBottom: 8
  },
  subtitletext: {
    fontWeight: "bold",
    marginLeft: 10,
    fontSize: 14
  },
  subtitletextstorage: {
    fontWeight: "bold",
    marginLeft: 10,
    fontSize: 14,
    marginTop: 6,
    marginBottom: 6
  },
  subtitletext2: {
    marginLeft: 10,
    fontSize: 14,
    color: "#434343"
  },
  buttonStyle: {
    width: 60,
    height: 34,
    justifyContent: "center",
    borderRadius: 20,
    marginBottom: 18
  },

  TextStyle: {
    textAlign: "center",
    fontSize: 14,
    fontWeight: "bold"
  }
});

export default App;

Environment
Expo CLI 2.20.2 environment info:
    System:

*

*OS: macOS 10.14.5

*Shell: 3.2.57 - /bin/bash
Binaries:

*Node: 10.16.0 - ~/.nvm/versions/node/v10.16.0/bin/node

*Yarn: 1.15.2 - ~/.yarn/bin/yarn

*npm: 6.9.0 - ~/.nvm/versions/node/v10.16.0/bin/npm

*Watchman: 4.9.0 - /usr/local/bin/watchman
IDEs:

*Android Studio: 3.3 AI-182.5107.16.33.5314842

*Xcode: 10.2.1/10E1001 - /usr/bin/xcodebuild
npmGlobalPackages:

*expo-cli: 2.20.2

*"react-native":
"https://github.com/expo/react-native/archive/sdk-33.0.0.tar.gz",

*"expo": "^33.0.0",

*"expo-ads-admob": "~5.0.1",

*Android real device : LGM-V300S.

*Android Studio 3.3.2

*macOS 10.14.5

*Standalone App(ExpoKit)


text:
Q: Magento translating not working I am trying to translate a single line on a product page.
"Special Price" needs to be changed.
I found the Mage_Catalog.csv in the app/locale/[language] folder and changed the translation.
I used (translating to Dutch):

*

*"Special Price:","Aanbieding:"

*"Special Price","Aanbieding"

*"Special Price: %s","Aanbieding: %s"

*"Special Price %s","Aanbieding %s"

After saving & uploading, I cleared all caches:
Host cache, Magento cache & browser cache.
No result, it works on all other lines, save for this one.
So my next step was to change it on the generated product page, but I can't find the file I need.
Does any of you know?

A: price.phtml line 389 +/-
remove variable
$variable

and use
<?php echo $this->__('Special Price:') ?>

is bug magento, dont translate correct special price =(