text:
Q: Two Column A & B, Table Y (A, B) are referred to Table X (A, B). When A in Y is changed, how to make B in Y change to referred Table X value? I am working on a WPF program. In this program, I have two DataGrid, one is Quotation List and another is a Quotation Status List. Both the Quotation List's data and Quotation Status List's data are stored in the PostgreSQL database's table (quotation_list & quotation_status_list).
In quotation_list Table, there will be two columns named status and status_color. The status is used to present the status of the quotation and the status_color is used to control the the row's Foreground via Binding method in WPF TextBox Control.
<DataGridTemplateColumn SortMemberPath="status" CanUserSort="True" Header="Status" Width="100" >
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBox Name="Box_status" Foreground="{Binding status_color}" Text="{Binding status}" IsReadOnly="True" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

<DataGridTemplateColumn SortMemberPath="status_color" CanUserSort="True" Header="Color" Width="100" >
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBox Name="Box_status_color" Foreground="{Binding status_color}" Text="{Binding status_color}" IsReadOnly="True" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

What I want to achieve are:

*

*When user edit the status_color in quotation_status_list Table, all the status_color in the quotation_list with that status_color will be changed.

quotation_status_list
 id |  status  | status_color
----+----------+--------------
  1 |  Active  |     Red
  2 |  Firm    |     Blue

quotation_list
 id |  status  | status_color |  title
----+----------+--------------+--------
  1 |  Active  |     Red      |   abc
  2 |  Firm    |     Blue     |   def
  3 |  Active  |     Red      |   hij

After modify the status_color Red to Black, the status_color value in quotation_list will change automatically.
quotation_status_list
 id |  status  | status_color
----+----------+--------------
  1 |  Active  |     Black
  2 |  Firm    |     Blue

quotation_list
 id |  status  | status_color |  title
----+----------+--------------+--------
  1 |  Active  |     Black    |   abc
  2 |  Firm    |     Blue     |   def
  3 |  Active  |     Black    |   hij

*When user edit the status in quotation_list Table, its status_color value will be changed to status_color in quotation_status_list Table.

quotation_status_list
 id |  status  | status_color
----+----------+--------------
  1 |  Active  |     Red
  2 |  Firm    |     Blue

quotation_list
 id |  status  | status_color |  title
----+----------+--------------+--------
  1 |  Active  |     Red      |   abc
  2 |  Firm    |     Blue     |   def
  3 |  Active  |     Red      |   hij

After modify, the status of row 1 is changed to Firm, the status_color will be changed to Blue automatically.
quotation_status_list
 id |  status  | status_color
----+----------+--------------
  1 |  Active  |     Red
  2 |  Firm    |     Blue

quotation_list
 id |  status  | status_color |  title
----+----------+--------------+--------
  1 |  Firm    |     Blue     |   abc
  2 |  Firm    |     Blue     |   def
  3 |  Active  |     Red      |   hij

To achieve these two function, I try to create two Table by
quotation_status_list
CREATE TABLE IF NOT EXISTS quotation_status_list
(
    id SERIAL UNIQUE NOT NULL,
    status TEXT UNIQUE NOT NULL,
    status_color TEXT UNIQUE NOT NULL,
    PRIMARY KEY(id, status, status_color)
);

quotation_list
CREATE TABLE IF NOT EXISTS quotation_list
(
    id SERIAL UNIQUE NOT NULL,
    title TEXT NOT NULL,
    status TEXT NOT NULL,
    status_color TEXT NOT NULL,
    FOREIGN KEY(status, status_color)
    REFERENCES quotation_status_list(status, status_color)
    ON DELETE NO ACTION
    ON UPDATE CASCADE
) ;

I can create the quotation_status_list Table but I cannot create the quotation_list.
The error is
there is no unique constraint matching given keys for referenced table "quotation_status_list"

What will be the problem, the status, status_color in quotation_status_list should be UNIQUE and they are PRIMARY KEY.
Do I use wrong method? or Database cannot do this job?
Any suggestion are welcome.

A: You do not need a 3-column PK in quotation_status_list, the single column is sufficient. Then Do not repeat status and status_color quotation_list. Remove them and add the column containing the PK of quotation_status_list.
create table quotation_status_list(
       id           integer generated always as identity  primary key
     , status       text unique not null
     , status_color text unique not null
     );

create table if not exists quotation_list(
       id                  integer generated always as identity
     , title               text not null
     , quotation_status_id integer
                           references quotation_status_list(id)
                           on delete no action
     ) ;

Now to retrieve the status and status_color join the tables:
select ql.title
     , qs.status
     , gs.status_color
  from quotation_list        ql
  join quotation_status_list qs
    on (qs.id  = ql.quotation_status_id);

Now any change (except PK, which should never be changed) in quotation_status_list is automatically reflected in the select.

Note: I used the newer preferred generated as identity for the keys. If you have an older Postgres version which does not support (prior to v10?) serial accomplishes the same.


text:
Q: SQL: Union with subqueries My structure is like this
table1
key
value
date
table2
key
value
date
table3
key
value
date
I would like to have a sql query which returns distinct all keys
and the sum of all values for each key from all 3 tables.
My try has been

Select key=
  (select table1.key from table1 where date = '2017-05-30'
  union select table2.key from table2 where date = '2017-05-30' union select
  table3.key from table3 where date = '2017-05-30'), (select sum(value)
  from table1 where table1.key = key and date = '2017-05-30' ) + select
  (sum(value) from table2 where table2.key = key and date =
  '2017-05-30') + select (sum(value) from table3 where table3.key=key
  and date = '2017-05-30') from table1, table2, table3

A: You could combine the 3 tables into a temporary table and then do what you need to do on the temporary table:
CREATE TEMP TABLE temp1 AS
select key, value, date from table1
union all
select key, value, date from table2
union all
select key, value, date from table3

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find multiple occurrences of different URLs in a big string, where each URL is between two specific substrings using Python I have a file containing just one long string which has multiple URLs embedded in it. The URLs are all different but are always enclosed between two specific substrings. How can I extract all the URLs?
My File Contents look like the following:
data-starred-src="www.example.com" data-non-starred-src asdf asdf ghgh data-starred-src="www.someurl.com" data-non-starred-src gjsltg ajshssl ahssfh data-starred-src="www.anotherurl.com" data-non-starred-src

I want to extract URLs in the form
www.example.com
www.someurl.com
www.anotherurl.com

A: On the example, this one:
print re.findall(r'data-starred-src\s*=\s*"([^"]*)"', line)

Gives:
['www.example.com', 'www.someurl.com', 'www.anotherurl.com']

A: This should do it:
(?<=\")([^"]+\.[^"]+\.[^"]+)(?=\")

Working regex example:
http://regex101.com/r/sI2jL7
or another example:
http://regex101.com/r/sI2jL7

A: Try the following:
import re
r1 = re.compile('(?:AAA ")([^"]*)(?:" BBB)')
s = 'AAA "www.example.com" BBB asdf asdf ghgh AAA "www.someurl.com" BBB gjsltg ajshssl ahssfh AAA "www.anotherurl.com" BBB'
res = r1.findall(s)

You may also consider using finditer() if s is really long.
Updated re looks like this
r1 = re.compile('(?:data-starred-src=")([^"]*)(?:" data-non-starred-src)')

but I've simply replaced AAA and BBB with new delimiters so it's possible that the code won't work if it didn't work before.


text:
Q: How to decode base64 encoded image with JS/PHP? (previously encoded with Actionscript) I have an image encoded to base64, made with an ActionScript function:
private static const BASE64_CHARS:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

public static function encodeByteArray(_arg1:ByteArray):String {
   var _local3:Array;
   var _local5:uint;
   var _local6:uint;
   var _local7:uint;
   var _local2 = "";
   var _local4:Array = new Array(4);
   _arg1.position = 0;
   while (_arg1.bytesAvailable > 0) {
        _local3 = new Array();
        _local5 = 0;
        while ((((_local5 < 3)) && ((_arg1.bytesAvailable > 0)))) {
            _local3[_local5] = _arg1.readUnsignedByte();
            _local5++;
        };
        _local4[0] = ((_local3[0] & 252) >> 2);
        _local4[1] = (((_local3[0] & 3) << 4) | (_local3[1] >> 4));
        _local4[2] = (((_local3[1] & 15) << 2) | (_local3[2] >> 6));
        _local4[3] = (_local3[2] & 63);
        _local6 = _local3.length;
        while (_local6 < 3) {
            _local4[(_local6 + 1)] = 64;
            _local6++;
        };
        _local7 = 0;
        while (_local7 < _local4.length) {
            _local2 = (_local2 + BASE64_CHARS.charAt(_local4[_local7]));
            _local7++;
        };
    };
    return (_local2);
}

Now I'm trying to decode (with no success) the string in JS/PHP and have back the image.
Here is the Actionscript decoding function:
public static function decodeToByteArray(_arg1:String):ByteArray{
    var _local6:uint;
    var _local7:uint;
    var _local2:ByteArray = new ByteArray();
    var _local3:Array = new Array(4);
    var _local4:Array = new Array(3);
    var _local5:uint;
    while (_local5 < _arg1.length) {
        _local6 = 0;
        while ((((_local6 < 4)) && (((_local5 + _local6) < _arg1.length)))) {
            _local3[_local6] = BASE64_CHARS.indexOf(_arg1.charAt((_local5 + _local6)));
            _local6++;
        };
        _local4[0] = ((_local3[0] << 2) + ((_local3[1] & 48) >> 4));
        _local4[1] = (((_local3[1] & 15) << 4) + ((_local3[2] & 60) >> 2));
        _local4[2] = (((_local3[2] & 3) << 6) + _local3[3]);
        _local7 = 0;
        while (_local7 < _local4.length) {
            if (_local3[(_local7 + 1)] == 64){
                break;
            };
            _local2.writeByte(_local4[_local7]);
            _local7++;
        };
        _local5 = (_local5 + 4);
    };
    _local2.position = 0;
    return (_local2);
}

I tried to convert the decoding Aactionscript function to JS but I'm missing the new ByteArray(); I don't know how to manage that.
I need a way to decode the encoded image string back to an image.
Here a sample base64 string of an image, encoded with the "encodeByteArray" function:
sample base64 encoded string
thanks for the help.

A: To output your base64 image use this format:
<img src="data:image/png;base64,ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" />


text:
Q: Showing $\sqrt{z}$ is holomorphic on the upper half plane and its image is the first quadrant. Let
$$f(z)=\sqrt{z}$$
be defined on the upper half plane $D=\{z \in \Bbb{C} : \text{Im}z>0\}$. I need to show $f$ is holomorphic on $D$ and that $f(D)$ is the first quadrant. To show holomorphicity, I appeal to the C-R equations. I set
$$\sqrt{x+iy}=u+iv$$
and solve for $x$ and $y$. I obtain
$$x+iy = u^2-v^2 + 2iuv$$
Which implies $x=u^2-v^2$ and $y=2uv$.
Then $x_u=y_v$ and $x_v=-y_u$ and the C-R equations are satisfied.
I am stuck as I haven't used that the domain is the upper half plane but I got the C-R equations.
Also, how do I show $f(D)=\{z \in \Bbb{C} : \text{Re}z>0, \text{Im}z>0\}$?

A: Let $Q = \{ z | \operatorname{re} z >0, \operatorname{im} z >0 \}$ and
define $\phi: Q \to D$ by $\phi(z) = z^2$. Since $\phi(r e^{i\theta}) = r^2 e^{2 i\theta}$, it is straighforward to check that $\phi$ is a bijection. Note that $\phi$ is analytic on $Q$ and $\phi'(z) \neq 0$ for $ \in Q$, hence the inverse function theorem shows that $\phi$ has a local analytic inverse, and since $\phi$ is a bijection the inverse is analytic on $D$.


text:
Q: Ext JS 4 - how to add a time stamp to a text area form field? I have an form with a text area field.  I want to add some text (a date/time stamp) when the user clicks in to the form.  I am assuming I need to catch a click type event when the user clicks in to the field and then edit the field value and insert the text I want.   Is this the best approach?
Looking for suggestions based on using Ext JS 4 / MVC.

A: As mentioned by you - "I need to catch a click type event when the user clicks in to the field" - One way to achieve this and appending of timestamp to the value could be by using the focus event in following manner:
focus:function(){
    var value       =       this.getValue();
    value           +=      new Date().getTime();
    this.setValue(value);
}

Just that the date used here is the client's system date.
Hope this helps.


text:
Q: merging two data frames with different columns in R I have two tables that I want to merge:
Data.frame A:

DATUM
CP
MNOZSTVI
CLOSE

2021-07-30
USD
18
NA

2021-07-30
CZK
2991
NA

2021-07-30
EUR
0
NA

Data.frame B:

DATUM
CP
CLOSE

2021-07-30
USD
21,4

2021-07-30
CZK
1

2021-07-30
EUR
25

Desired data.frame:

DATUM
CP
MNOZSTVI
CLOSE

2021-07-30
USD
18
21,4

2021-07-30
CZK
2991
1

2021-07-30
EUR
0
25

I would like to do that using join function from dplyr. I tried it using full_join:
desired.data.frame<- A %>%
  full_join(B)

But it does not work as I want.
Thank you for your help guys.

A: You could use left_join and then select the columns:
library(dplyr)
df_A %>%
    left_join(df_B, by="CP") %>%
    select(DATUM = DATUM.x, CP, MNOZSTVI, CLOSE=CLOSE.y)

Or  thanks to akrun ,
df_A %>% select(-CLOSE) %>% left_join(df_B)

Output:
 DATUM      CP    MNOZSTVI CLOSE
  <chr>      <chr>    <dbl> <dbl>
1 2021-07-30 USD         18  21.4
2 2021-07-30 CZK       2991   1
3 2021-07-30 EUR          0  25

data:
df_A <- tribble(
~DATUM,     ~CP,    ~MNOZSTVI, ~CLOSE,
"2021-07-30",   "USD",  18, NA,
"2021-07-30",   "CZK",  2991, NA,
"2021-07-30",   "EUR",  0, NA)

df_B <- tribble(
    ~DATUM,     ~CP,    ~CLOSE,
    "2021-07-30",   "USD",  21.4,
    "2021-07-30",   "CZK",  1,
    "2021-07-30",   "EUR",  25)
df_A


text:
Q: Constructor vs static instance I am new to php and had to work with an existing code base. In this library there is a class which deals with the mysql database. However, they start to instantiate an object with a static getInstance function:
public static function get_instance() {
  if(null == self::$instance) {
    $c = __CLASS__;
    self::$instance = new $c();
  }
  return self::$instance;
}

I don't see the advantage of this static function in comparison to an usual constructor. How do I have to deal with my login credentials? Do I have to make them static, too?


text:
Q: Ext.Error: Unable to parse the JSON returned by the server: You're trying to decode an invalid JSON String I am working with ExtJs 4.0. I want to read json file in my chart but gettig following error
Ext.Error: Unable to parse the JSON returned by the server: You're trying to decode an invalid JSON String.
store n model:
 Ext.define('chartModel', {
    extend: 'Ext.data.Model',
    fields: [
            {name: 'year'},
            {name: 'comedy'},
            {name: 'action'},
            {name: 'drama'},
            {name: 'thriller'}
    ]
});

var myStore = Ext.create('Ext.data.Store', {
    model: chartModel,
    proxy: {
        type: 'ajax',
        url : '/data.json',
        reader: {
            type: 'json',
            root: 'data',
            method: "GET",
            messageProperty: 'jsonData'
        }
    },
    autoLoad: true
});

data.json file:
data: [{year: 2005, comedy: 34000000, action: 23890000, drama: 18450000, thriller: 20060000}]

A: JSON property names must be quoted to be considered valid. In addition, your data needs to be a property of an object, like {"data":[{"year":2005, "comedy":3400000....
EDIT: What Neil said is correct. Ext.decode does not require property names to be in quotes. However, the JSON standard does require them so you should definitely get in the habit of using them.


text:
Q: React img not immediately changing when src changes. How can I fix this? I have a basic  with a src.

If I change the src from say /1.jpg to /2.jpg and the new image takes 1 second to load, React will continue to show /1.jpg until the new image is loaded.
What I want is for the old image to be discarded while the new image is being loaded. (e.g. display: none)
Any idea how to accomplish this? Ideally without conditional rendering, because I still need to use onLoad and onError
EDIT: Here's some more code. It's a little more complicated than my question, but I'm just trying to add some loading and error state to the image.
I have a button that calls this onClick
this.props.history.push('/${page + 1}');

This is the image component, where src is based on the page from the URL.
import React, { Component } from 'react';
import CenteredLoading from 'components/loading/CenteredLoading';

type Props = { src: string };

type State = {
  status: 'LOADING' | 'LOADED' | 'FAILED',
};

class ImageWithLoader extends Component<Props, State> {
  state = {
    status: 'LOADING',
  };

  handleImageLoad = () => {
    this.setState({ status: 'LOADED' });
    console.error('image loaded');
  };

  handleImageError = () => {
    this.setState({ status: 'FAILED' });
    console.error('image error');
  };

  render() {
    const { src, ...otherProps } = this.props;
    const { status } = this.state;

    return (
      <React.Fragment>

        {status === 'LOADING' && <CenteredLoading />}
        {status === 'FAILED' &&
error
}
      </React.Fragment>
    );
  }
}

export default ImageWithLoader;

A: Made my own workaround.
I believe because react isn't mounting a new component (i.e. ), it's not going to update to the new image until it's finished loading.
What I did was check if the src changed in componentDidUpdate and change the status to LOADING. Then I set img style to display: none while its status was LOADING.
EDIT: Also, by manually setting my own key, I can force React to re-render the

A: Just add key attribute to your image tag and assign some unique value to key attribute like image source.


text:
Q: Simple Map/Reduce MongoVUE I am trying to get a simple map reduce working in MongoVUE, but it doesn't return any results, I just want to get it to output the count of each userID just so I can have a working example to build from.
function Map() {
emit( this.UpdatedBy.UserId, {"count": 1} );
}

function Reduce(key, values) {

var result = {count: 0};
  values.forEach(function(value) {
  result.count += value.count;
});
return result;
}

function Finalize(key, reduced) {
/*
reduced = Transform-to-Desired-Form(reduced);
*/
return reduced;
}

And the output is set to inline.
This is the tutorial I am working from, but I just want to apply a simple count to start off with http://www.mongovue.com/2010/11/03/yet-another-mongodb-map-reduce-tutorial/

A: function() {
    emit( this.UpdatedBy.UserId, 1 );
  };

  function(key, values) {
    var result =  0;

    values.forEach(function(value) {
      result += value;
    });
    return result;
  };

Here is how I got it to work for anyone who needs a simple example on how to group and count a user Id.

A: I just wrote a blog post and made two short screencasts showing exactly how to get an example MapReduce working in MongoVue


text:
Q: JSXGraph - Animation of one element pushing another element out of the way, JSX behavior not as expected I'm trying to create an animation which has a circle moving from left to right, and upon encountering a rod the rod is pushed out of the way by the circle.
I'm using an 'if else' and a nested 'if else' to achieve that.
https://jsfiddle.net/Cleonis/h9u5xjzb/
The large circle and the intersection point are auxillary elements, they will be set to invisible in the finished version.
The element 'rodB' is a line, hinging around a fixed coordinate [1.0, -0.5], the coordinates of the other end of the rod are dependent on a conditional.
The first transition happens as expected: when the moving circle reaches the rod it starts "pushing" the rod.
However, the second transition does not happen, and I cannot explain why.
(When the center of the pushing circle has reached x-coordinate 1.1 the rod should become static again, in a slanted position.)

Either there is an error in the way I declared the 'if else' statement, or the problem is due to a quirk of JSXGraph.
My expectation is that when a function calls a point element, then JSXGraph will return an array of the form [x,y]
I also tried a switch statement, but that had the same result; the first transition happens, but the second transition does not happen.

So:
Transition from static form to dynamic form works.
But then the element 'rodB' should go from dynamic form to static form again, and that does not happen.
Can the intention of the animation be achieved?
The function with the conditional statements
var pushPoint = function() {
  if (pos < (1.0 - or)) {return [1.0, 0.0]}
  else {
    if (pos < 1.1) {
      //return [function() {return intersection1B.X()}, function() {return intersection1B.Y()}];
      return intersection1B;
      //return [1.1, -0.2]
    }
    else {return [1.1, -0.2]}
  }
}

A: Defining the second point of the rod by a function which sometimes returns a point and sometimes coordinates does not work. The rod remains visible if the coordinates of the intersection point are returned:
var pushPoint = function() {
  if (pos < (1.0 - or)) {return [1.0, 0.0]}
  else {
    if (pos < 1.1) {
      return intersection1B.coords.usrCoords.slice(1);
    }
    else {return [1.1, -0.2]}
  }
}

// This line element calls the function 'pushPOint()' to obtain coordinate array
var rodB = board.create('line',
  [[1.0, -0.5], function() {return pushPoint()}],
  {straightFirst:false, straightLast:false}
);

See it live at https://jsfiddle.net/ohqpvz9x/1/.


text:
Q: React custom hook causes infinite loops any idea why this custom hook with SWR causes an infinite loop?
export const useOrganization = () => {
  const [data, setData] = useState<OrganizationModel | undefined>();
  const { organizationId } = useParams();
  const { data: dataSWR } = useSWRImmutable<
    AxiosResponse<Omit<OrganizationModel, 'id'>>
  >(`organizations/${organizationId}`, api);

  useEffect(() => {
    if (dataSWR?.data && organizationId) {
      setData({ id: organizationId, ...dataSWR.data });
      console.log({ id: organizationId, ...dataSWR.data });
    }
  });
  return data;
};

I need to fetch data from API and add missing id from URL param. If I use setData(dataSWR.data), everything is fine. The problem occurs when setData({...dataSWR.data}) is used -> loop.

A: You need to use useEffect based on the scenario. When dataSWR changed the useEffect call again with new data.
You can add the dataSWR as dependencies argument in useEffect hook.
useEffect(() => { do something... }, [dataSWR])

Example:
export const useOrganization = () => {
  const [data, setData] = useState<OrganizationModel | undefined>();
  const { organizationId } = useParams();
  const { data: dataSWR } = useSWRImmutable<AxiosResponse<Omit<OrganizationModel, 'id'>>>(`organizations/${organizationId}`, API);

  useEffect(() => {
   if (dataSWR?.data && organizationId) {
      setData({ id: organizationId, ...dataSWR.data });
      console.log({ id: organizationId, ...dataSWR.data });
    };
  },[dataSWR]);

  return data;
};

Usage of hook:
const data = useOrganization()

Dependencies argument of useEffect is useEffect(callback, dependencies)
Let's explore side effects and runs:
Not provided: the side-effect runs after every rendering.
import { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // Runs after EVERY rendering
  });
}

An empty array []: the side-effect runs once after the initial rendering.
import { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // Runs ONCE after initial rendering
  }, []);
}

Has props or state values [prop1, prop2, ..., state1, state2]: the side-effect runs only when any dependency value changes.
import { useEffect, useState } from 'react';

function MyComponent({ prop }) {
  const [state, setState] = useState('');
  useEffect(() => {
    // Runs ONCE after initial rendering
    // and after every rendering ONLY IF `prop` or `state` changes
  }, [prop, state]);
}

A: I found the solution - useMemo hook:
export const useOrganization = () => {
  const { organizationId } = useParams();
  const { data } = useSWRImmutable<
    AxiosResponse<Omit<OrganizationModel, 'id'>>
  >(`organizations/${organizationId}`, api);

  const result = useMemo(() => {
    if (data && organizationId) {
      return { id: organizationId, ...data.data };
    }
  }, [data, organizationId]);
  console.log('useOrganization');
  return result;
};


text:
Q: How to get public dns name from aws ec2 describe-instances I'm trying to make simple script which queries my ec2 instances and gets public dns name of instances which matches my filter. There is my first shot:
#!/bin/bash

aws ec2 describe-instances \
    --filters "Name=tag:app,Values=swarm-cluster" \
              "Name=tag:role,Values=manager" \
    --query "Reservations[*].Instances[*].PublicDnsName"

It almost works but I get something ugly:
[
    [
        ""
    ],
    [
        "ec2-xxx-xxx-xxx-xxx.venus-central-1.compute.amazonaws.com"
    ]
]

I want just list of FQDNs, one per line. How to format output?
I know, I can do it with tr, sed and so on but I'd like use more sophisticated way. :)

A: You can just append --output text to your CLI call to get a text output.
Ref - https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-output.html

A: By using jq you can parse the JSON response to get what you want.
Example:
#!/bin/bash

aws ec2 describe-instances \
    --filters "Name=tag:app,Values=swarm-cluster" \
              "Name=tag:role,Values=manager" \
    --query "Reservations[*].Instances[*].PublicDnsName" | jq ".[0][1]"

That will give you:
"ec2-xxx-xxx-xxx-xxx.venus-central-1.compute.amazonaws.com"

A: for i in `cat kafka_instance_names`
do
    aws ec2 describe-instances --filters "Name=tag:Name,Values=$i" --query "Reservations[*].Instances[*].PublicDnsName" | grep ec
done

  "ec2-54-166-168-168.compute-1.amazonaws.com"
  "ec2-52-72-30-88.compute-1.amazonaws.com"


text:
Q: Comparing an input to a database entry Ive been trying to make a simple mySQL program to just check if a key is in a databse. However, i am failing, any ideas? I have tried looping around the entire database to find the value, though no luck. If anyone could shed some light on this it would be very thankful. Also The database looks like this:
VALUE
wouehourhfwfrhg
rwihewoughwourh
fw8rhfouirhushr
wrohwroghwhrwhr
And the program just checks if the input in the box is in the database.

<?php
require_once ("config.php");
function isKeyValid($key){
  $query='SELECT `Value` FROM `InviteKeys` WHERE `Used`=0';
  $response = @mysqli_query($link,$query);
  if($response)
  {
    echo($key);
    while($row = mysqli_fetch_array($response))
    {
      echo $row . "
";
      if($key==$row)
        return 1;
    }
    return 0;
  }
}
if(isset($_POST['submit'])){
    $key = trim($_POST['keyInput']);
    if(isKeyValid($key))
    {
      echo("KYS");
    }
    else {
      echo("Kys less");
    }
}
?>

<form action='/keyTester.php' method="post">
  <input type="text" name="keyInput" size="30" placeholder = "Username" class = "inpoot">

  <input type="submit" name="submit" value="Submw">
</form>


text:
Q: has_many :through association - can't save record with a foreign id during create action I have a Rails 4 application and am having problems creating a new record for a has_many :through association.  A couple of observations that I made while debugging:

*

*Commenting out the checkboxes associated with the Features model, the application will create and save the venue object properly.

*The update action in the venues controller works fine for the feature checkboxes.

Can somebody tell me why my application is having problems saving the associated features object (an array) when creating a new venue?  Not sure if this is because the foreign key, venue_id, doesn't exist prior to the save...
Here's the code:
venues.rb
class Venue < ActiveRecord::Base
  has_many :venue_features, dependent: :destroy
  has_many :features, :through => :venue_features

venue_features.rb
class VenueFeature < ActiveRecord::Base
  belongs_to :venue
  belongs_to :feature

features.rb
class Feature < ActiveRecord::Base
  has_many :venue_features, dependent: :destroy
  has_many :venues, :through => :venue_features

venues\new.html.erb (Features are listed as checkboxes - use selects relevant checkboxes)
<%= hidden_field_tag "venue[feature_ids][]", nil %>
<% Feature.all.each do |feature| %>

      <%= check_box_tag "venue[feature_ids][]", feature.id, @venue.feature_ids.include?(feature.id) %>
      <%= feature.name %>

<% end %>

venues_controller.rb
class VenuesController < ApplicationController
  def create
    @venue = Venue.new(venue_params)

    if @venue.save(venue_params)
      flash[:success] = "Success!"
      redirect_to venues_path
    else
      flash[:error] = "Problem!"
      render 'new'
    end
  end

  def venue_params
    params.require(:venue).permit(:attribute_1, :attribute_2, :feature_type_ids => [])
  end
end

A: I'm sure there's a cleaner solution but what I ended up doing was to update a different set of strong parameters after a successful save.  The problem prob has something to do with 1) one of my parameters, :feature_type_ids, is actually an array and/or 2) :feature_type_ids is in a different model (not the venues.rb).  I thought that Rails would "automagically" handle saving to differnet models since venues.rb and features.rb have been set up through a :has_many :through relationship.  I'd be curious for a better solution but the following works:
class VenuesController < ApplicationController
  def create
    ...
    if @venue.save(venue_only_params)
      if @venue.update_attributes(venue_params)
      flash[:success] = "Success!"
      redirect_to venues_path
    else
      flash[:error] = "Problem!"
    render 'new'
    end
  end

  def venue_params
    params.require(:venue).permit(:attribute_1, :attribute_2, :feature_type_ids => [])
  end

  def venue_only_params
    params.require(:venue).permit(:attribute_1, :attribute_2)
  end

end


text:
Q: Nativescript RadSideDrawer gives symbol not available at run time error I am following nativescript RadSideDrawer doc at:
http://docs.telerik.com/devtools/nativescript-ui/Controls/Angular/SideDrawer/getting-started, but once I started the app in ios emulator, I am getting this error:
CONSOLE ERROR file:///app/tns_modules/@angular/core/./bundles/core.umd.js:1052:24: ERROR Error: Uncaught (in promise): ReferenceError: Metadata for "TelerikUI.TKSideDrawerView" found but symbol not available at runtime.

RadSideDrawer@file:///app/tns_modules/nativescript-telerik-ui/sidedrawer/sidedrawer.js:15:38

I tried several times and always got the same error.
What's wrong with this? Is the documentation having errors here?
Thanks

A: It looks like there may be inconsistency and incompatibility in the used dependencies in your package.json. You can take a look at the sdkAngular repository that showcases many scenarios for using the RadSideDrawer and the other components of the nativescript-telerik-ui-pro plugin here.
Other things that you can try is to clean the project, by deleting the platforms and node_modules folders and running tns run ios after that.


text:
Q: Concatenate two Excel spreadsheet data (side by side) I am trying to figure out how I can combine data from two spreadsheets side by side. I know how to write and save into a specific file name using Pandas, but am not sure how to combine them. E.g.:
Sheet 1:
avgdegf |  50 |
76      |  20 |
68      |  30 |
39      |  40 |

Sheet 2:
temp    |  32 |
26      |  20 |
28      |  32 |
32      |  41 |

Resulting in:
    avgdegf |  50 | temp| 32 |
    76      |  20 | 26  | 20 |
    68      |  30 | 28  | 32 |
    39      |  40 | 32  | 41 |

I know that you can save into another spreadsheet by using (general example):
writer = ExcelWriter('file name.xlsx')
df.to_excel(writer,'Sheet1',index=False)
writer.save()


text:
Q: Pandas Input/output error? I created a multiindex .h5 file and use HDFStore to store the data. However, when I try to read the dataframe from the file, it turns out that I can read some dataframes successfully but fail to read several others. The following is the error message I get:
HDF5-DIAG: Error detected in HDF5 (1.8.9) thread 0:
  #000: H5Dio.c line 174 in H5Dread(): can't read data
    major: Dataset
    minor: Read failed
#001: H5Dio.c line 449 in H5D_read(): can't read data
    major: Dataset
    minor: Read failed
#002: H5Dcontig.c line 560 in H5D_contig_read(): contiguous read failed
    major: Dataset
    minor: Read failed
#003: H5Dselect.c line 275 in H5D_select_read(): read error
    major: Dataspace
    minor: Read failed
#004: H5Dselect.c line 210 in H5D_select_io(): read error
    major: Dataspace
    minor: Read failed
#005: H5Dcontig.c line 890 in H5D_contig_readvv(): can't perform vectorized sieve buffer read
    major: Dataset
    minor: Can't operate on object
#006: H5V.c line 1457 in H5V_opvv(): can't perform operation
    major: Internal error (too specific to document in detail)
    minor: Can't operate on object
#007: H5Dcontig.c line 691 in H5D_contig_readvv_sieve_cb(): block read failed
    major: Dataset
    minor: Read failed
#008: H5Fio.c line 113 in H5F_block_read(): read through metadata accumulator failed
    major: Low-level I/O
    minor: Read failed
#009: H5Faccum.c line 254 in H5F_accum_read(): driver read request failed
    major: Low-level I/O
    minor: Read failed
#010: H5FDint.c line 142 in H5FD_read(): driver read request failed
    major: Virtual File Layer
    minor: Read failed
#011: H5FDsec2.c line 753 in H5FD_sec2_read(): file read failed: time = Wed Jul  3 14:07:31 2013
, filename = 'N.h5', file descriptor = 3, errno = 5, error message = 'Input/output error', buf = 0x7f8807fccb6c, size = 649492, offset = 185876480
major: Low-level I/O

minor: Read failed

Traceback (most recent call last):
File "", line 1, in
File "/usr/share/python27/lib/python2.7/site-packages/pandas/io/pytables.py", line 165, in getitem
return self.get(key)

File "/usr/share/python27/lib/python2.7/site-packages/pandas/io/pytables.py", line 261, in get
return self._read_group(group)

File "/usr/share/python27/lib/python2.7/site-packages/pandas/io/pytables.py", line 651, in _read_group
    return handler(group, where)
File "/usr/share/python27/lib/python2.7/site-packages/pandas/io/pytables.py", line 400, in _read_frame
    return DataFrame(self._read_block_manager(group))
File "/usr/share/python27/lib/python2.7/site-packages/pandas/io/pytables.py", line 426, in _read_block_manager
    ax = self._read_index(group, 'axis%d' % i)
File "/usr/share/python27/lib/python2.7/site-packages/pandas/io/pytables.py", line 487, in _read_index
    _, index = self._read_index_node(getattr(group, key))
File "/usr/share/python27/lib/python2.7/site-packages/pandas/io/pytables.py", line 532, in _read_index_node
    data = node[:]
File "/usr/share/python27/lib/python2.7/site-packages/tables/array.py", line 684, in getitem
    arr = self._readSlice(startl, stopl, stepl, shape)
File "/usr/share/python27/lib/python2.7/site-packages/tables/array.py", line 781, in _readSlice
    self._g_readSlice(startl, stopl, stepl, nparr)
File "hdf5Extension.pyx", line 1092, in tables.hdf5Extension.Array._g_readSlice (tables/hdf5Extension.c:9570)
tables.exceptions.HDF5ExtError: Problems reading the array data.
Can anyone help with this problem ? Thank you so much.

A: The HDF5 file is corrupt. You can get this to occur by doing a write, then interrupting it in the middle (ctrl-c). You will be unable to recover. HDF5 writes in chunks and if a chunk is interrupted I believe state is not consistent.
You will also get corruption if you are doing concurrent writes (either threads or processes). see this: http://pandas.pydata.org/pandas-docs/dev/io.html#notes-caveats

A: Hmm, it sounds like the HDF5 library may not be compiled with the thread-safe configure option enabled (--enable-threadsafe).  Also, if you are writing to the same file simultaneously from different processes, that is not going to work - you will need to close the file and re-open it from the other process.
See the HDF5 FAQ here:
http://www.hdfgroup.org/hdf5-quest.html#gconc


text:
Q: angular 2.0.0-rc.1 + karma: provide RouteSegment When a component is injected with RouteSegment, just providing the RouteSegment in the test is not enough:
component.ts:
export class ComponentToTest {
  private param: string;

  constructor(routeSegment: RouteSegment) {
    this.param = routeSegment.getParam('param');
    this.getData();
  }
}

component.spec.ts:
import {Router, RouteSegment} from '@angular/router';

import {it, inject, beforeEachProviders} from '@angular/core/testing';
import {ROUTER_FAKE_PROVIDERS} from '@angular/router/testing';

import {ComponentToTest} from './component';

describe('ComponentToTest', () => {
  beforeEachProviders(() => [
    ROUTER_FAKE_PROVIDERS,
    RouteSegment,
    ComponentToTest
  ]);

  it('should call getData() on contruct', inject([Router], (router) => {
    spyOn(ComponentToTest.prototype, 'getData');
    expect(ComponentToTest.prototype.getData).not.toHaveBeenCalled();
    let component = new ComponentToTest(router);
    expect(ComponentToTest.prototype.getData).toHaveBeenCalled();
  }));
});

Following error will occur:

Error: Cannot resolve all parameters for 'RouteSegment'(?, ?, ?, ?,
  ?). Make sure that all the parameters are decorated with Inject or
  have valid type annotations and that 'RouteSegment' is decorated with
  Injectable.

I have no idea on how to provide the RouteSegment parameters.

A: I had the same issue, I had to look at the angular router code and the specs they have in there repo. You should be able to provide the routeSegment like this:
import {RouteSegment, Router} from '@angular/router';
provide(RouteSegment, {useFactory: (r: any) => r.routeTree.root, deps: [Router]})

or you can just mock out a new RouteSegment similar to how you did with RouteParams:
provide(RouteParams, { useValue: new RouteParams({ page: 'terms-conditions' }) }),

Is now this:
provide(RouteSegment, { useValue: new RouteSegment([], { page: 'terms-conditions' }, null, null, null) }),

To create it you just have to pass it a couple of extra parameters.

A: Solution 1
See the answer of HomeBrew
Didn't work for me, still not sure why.
Solution 2
A mock implementation of RouteSegment:
class MockRouteSegment implements RouteSegment {
  urlSegments: any;
  parameters: any;
  outlet: string;
  _type: any;
  _componentFactory: any;
  type: any;
  stringifiedUrlSegments: string;
  constructor(parameters?: { [key: string]: any; }) {
    this.parameters = parameters
  }
  getParam(param: string) {
    return this.parameters[param];
  }
}

Provide it like this:
provide(RouteSegment, { useValue: new MockRouteSegment({ 'key': 'value' }) })


text:
Q: How do I get data from selected points in an offline plotly python jupyter notebook? Example code:
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot

import plotly.graph_objs as go

import numpy as np

N = 30
random_x = np.random.randn(N)
random_y = np.random.randn(N)

# Create a trace
trace = go.Scatter(
    x = random_x,
    y = random_y,
    mode = 'markers'
)

data = [trace]

# Plot and embed in ipython notebook!
iplot(data, filename='basic-scatter')

[]
How do I get a copy of the x,y data, or the indices from the selection?

A: So if you want to use javascript in Jupyter notebooks you have two options.
Using the display(HTML()) method for rendering html inside jupyter notebook, this method is demonstrated in the below sample code!
Another method is to use IPython Magic, read more here, the code will go something like this.

%%html
  %html [--isolated] Render the cell as a block of HTML
optional arguments:
  --isolated    Annotate the cell as 'isolated'. Isolated cells are rendered inside their own  tag

%%html
<span> naren</span>

You can also use this above method to render the HTML.
Please check the below code, where I have taken the code for select event from the plotly javascript events docs and made it work for jupyter!
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.graph_objs as go
from plotly import tools
import pandas as pd
import numpy as np
from datetime import datetime
init_notebook_mode(connected=True)
from IPython.core.display import display, HTML

N = 30
random_x = np.random.randn(N)
random_y = np.random.randn(N)

# Create a trace
trace = go.Scatter(
    x = random_x,
    y = random_y,
    mode = 'markers'
)

data = [trace]

# Plot and embed in ipython notebook!
plot = plot(data, filename='basic-scatter', include_plotlyjs=False, output_type='div')
divId=plot.split("id=\"",1)[1].split('"',1)[0]
plot = plot.replace("Plotly.newPlot", "var graph = Plotly.newPlot")
plot = plot.replace("</script>", """
var graph = document.getElementById('"""+divId+"""');
var color1 = '#7b3294';
var color1Light = '#c2a5cf';
var colorX = '#ffa7b5';
var colorY = '#fdae61';
;graph.on('plotly_selected', function(eventData) {
  var x = [];
  var y = [];

  var colors = [];
  for(var i = 0; i < N; i++) colors.push(color1Light);

  eventData.points.forEach(function(pt) {
    x.push(pt.x);
    y.push(pt.y);
    colors[pt.pointNumber] = color1;
  });

  Plotly.restyle(graph, 'marker.color', [colors], [0]);
});
""")
display(HTML(plot))


text:
Q: How to return an object using jQuery, not only the value I'm looking for a way of replacing .val(); in jQuery with something like .array or .object.  So instead of getting only the value of a drop down, i can return the full array for the selected value.
I have a drop down which allows a user to select multiple 'gameTypes', i'm outputting this to the screen and when the user clicks next the content of these 'gameTypes' should be sent as a JSON request.
The code i'm currently using is below however it only returns the 'gametype' name, so when i run the code i get 'RPG' in the console.  What i need is the full object, so RPG, publishers, games etc.
Ive looked at the API documentation in jQuery and can't find a way of doing it, is it possible with jQuery?
Js Code:
$("#nextbutton").click(function () {
         var datatosend = {
             gametypes: [],
             market: [] //This is populated using the same method however i don't need the whole object, just the name so this works
         };
             $("#comboGameType").find(":selected").each(function() {
             var str = $(this).val();
             datatosend.gametypes.push(str);
             console.log(str);
         });

});

JSON example:
{
"games": [{
    "gameType": "RPG",
    "publishers": [{
        "publisher": "Square",
        "titles": [{
            "title": "Final Fantasy",
            "gameReleases": [ 2006, 2008, 2010, 2012, 2013, 2014 ]
        }]
    }]
}]
}

The html is pretty standard, it's populated through js
<select id="comboGameType" class="selectpicker" multiple> </select>

JS to handle changes to drop down and display selections:
$('#comboGameType').change(function () {
     var values = $('#comboGameType').val();
     var parsedData = JSON.parse($myData);
     for (var i = 0; i < values.length; i += 1) {
         $('#output').append("<div>" + values[i] + "</div>")
     }
 });

Heres a fiddle to show as an example - when you view console see the value of the drop down is returned, however i'm trying to return the FULL object (so everything in RPG for example)  http://jsfiddle.net/2Ma7U/

A: You can use jQuery data to store the entire object and retrieve it later.
$(parsedData.genres).each(function (i) {
     $("#pubCombo").append($("<option/>", {
         val: this.genre,
         html: this.genre,
         data: this
     }));
 });

$("#next").click(function () {
         var datatosend = {
             gametypes: [],
             market: []
         };
             $("#pubCombo").find(":selected").each(function() {
             var obj = $(this).data();
             datatosend.gametypes.push(obj);
             console.log(obj);
         });

});

Updated fiddle http://jsfiddle.net/2Ma7U/1/


text:
Q: Unable to sort bars by value in ggplot I have tried everything to sort my bars in geom(bar) in ggplot by spending. This is my code:
I have tried manually ordering the data, forcats, changing as an aes in ggplot and can't get it to work.
#Load any packages
library(ggplot2)
library(dplyr)
library(readr)
library(janitor)
library(RColorBrewer)
library(forcats)

#Create data frame
MarketSize <- data.frame(Country = c("United States", "Japan", "Germany", "France", "Italy", "United Kingdom", "Spain", "Canada", "South Korea",
                                     "Australia", "China", "Brazil", "Russia", "India", "Other"),
                            Spending_2020 = c(528.7, 88.2, 54.9, 36.3, 33.3, 30.2, 25.7, 22.8, 16.2, 11.8, 134.4, 28.7, 17.5, 21.5, 15)
)

# Arrange by Spending outside ggplot
MarketSize$Country <- fct_rev(fct_infreq(MarketSize$Country))

#Create plot, labels etc.
MarketSize_2020 <- ggplot(MarketSize, aes(x = Country, y = Spending_2020)) +
  geom_col(fill="steelblue", width=0.75) +
  geom_text(aes(label=Spending_2020), vjust=0.5, hjust=-0.01, size=3.5) +
  coord_flip() +
  labs(title = "Market Spending on pharmaceuticals, 2020",
       x = "Country or region",
       y = "Total spending on pharmaceuticals (US $BN)") +
  theme_classic()

#View plot
MarketSize_2020

Can anyone help? Thanks in advance
I have tried ordering using forcats package and cannot get it to work!


text:
Q: Make a toast if a slidingDrawer is opening? Hi I would like to make a toast whenever a slidingDrawer is opening. I would like to know how i can listen if the slidingDrawer is opening and then make the toast if it is. I have looked everywhere but couldnt find a solution to the problem. Hope some of you can help :)
i found this on developer.android but could not figure out how to use it
    public void setOnDrawerCloseListener (SlidingDrawer.OnDrawerCloseListener onDrawerCloseListener)

A: drawer.setOnDrawerOpenListener(new OnDrawerOpenListener() {
    @Override
    public void onDrawerOpened() {
        Toast.makeText(context, text, duration).show();
    }
});

Fill in context, text and duration according to your needs. I would like to inform you though, that SlidingDrawer is deprecated since API 17: http://developer.android.com/reference/android/widget/SlidingDrawer.html

A: In your Activity where you have your SlidingDrawer, you simply attach the listener like this:
EDIT:
Added more code:
The layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<SlidingDrawer xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/slidingDrawer1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:content="@+id/content"
    android:handle="@+id/handle" >

    <Button
        android:id="@+id/handle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Handle" />

    <LinearLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </LinearLayout>

</SlidingDrawer>

The Activity onCreate method where you set the content view of the Activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout);

    SlidingDrawer mySlidingDrawer = (SlidingDrawer) findViewById(R.id.slidingDrawer1);
    mySlidingDrawer.setOnDrawerOpenListener(new OnDrawerOpenListener() {
        @Override
        public void onDrawerOpened() {
            Toast.makeText(getApplicationContext(), "SlidingDrawer opened!", Toast.LENGTH_SHORT).show();
        }
    });
}

Bear in mind, that the SlidingDrawer is actually deprecated in API 17 - it's discouraged to use it.


text:
Q: Matching filesystem paths but not URLs in Python I'm trying to write a regular expression that will match any filesystem path, but not any URL (I'm assuming URLs start with http). For instance, I'd like to match any path whose filename extension is svg unless is preceded by http, so that hei.svg matches but not http://hey.svg
My (probably) closest attempt is
'(?:(?!http))(\S+\.svg)'

and
re.findall('(?:(?!http))(\S+\.svg)', 'hey.svg')

['hey.svg']

but
re.findall('(?:(?!http))(\S+\.svg)', 'http://hey.svg')

['ttp://hey.svg']

Any help is appreciated.
Cheers.
EDIT:
I'm struggling to finetune the regex to also match a file whenever it is surrounded by newline's

blah blah \nfoo.svg\n blah blah

or html tags

foo.svg

I took a shot at the latter (which seemed easier), but I can't even get that one to work:
https://regex101.com/r/rHsdOx/1
I'd like the last two lines to also yield a match.
Any further clue?

A: If the path should not start with http and contain .svg
(?<!\S)(?!http)\S+\.svg(?!\S)

Explanation

*

*(?<!\S) Assert a whitespace boundary to the left

*(?!http) Assert not http directly to the right

*\S+\.svg Match 1+ non whitespace chars and .svg

*(?!\S) Assert a whitespace boundary

Regex demo
If the path should contain .svg you can change the (?!\S) to \S+
(?<!\S)(?!http)\S+\.svg\S*

Regex demo
Note that using \S assumes the path does not contain a whitespace char.


text:
Q: Memory management - How to show an already instantiated ViewController without creating a new instance I am having major memory management issues. After small use of the program it will crash running out of memory. I have finally found the cause, every time I create a new ViewController rather than accessing the instance, I am creating a new instance.
So app loads and instantiates the FirstViewController. You click a button which instantiates FilterViewController. From here when going back to FirstViewController I am creating a new instance of this as follows:
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName
        :@"MainStoryboard" bundle:nil];

    FirstViewController *fvc = [storyboard
        instantiateViewControllerWithIdentifier:@"FirstViewController"];

    fvc.modalTransitionStyle = UIModalTransitionStyleCoverVertical;

And repeat process. Any way of presenting the view controller without re-instantiating it? I am close to submitting the app (tomorrow hopefully) so I need to try get this sorted. Thanks!
Here is the presentation of the ViewController.
[self presentViewController:fvc animated:YES completion:nil];

Presenting FilterViewController from FirstViewController
- (IBAction)searchOptions:(id)sender {
    FilterViewController *ctrl = [[FilterViewController alloc] init];
    [UIView transitionFromView:self.view toView:ctrl.view duration:1 options:UIViewAnimationOptionTransitionCurlUp completion:nil];

    self.filterViewController = ctrl;

    [self.navigationController pushViewController:self.filterViewController animated:NO];

}

A: If you're using presentViewController, you get back to the previous view by calling [self dismissViewControllerAnimated:YES];. You would do that in the method where you're currently creating the new controller.
If you are pushing into a navigation controller you would pop from the navigation controller: [self.navigationController popViewControllerAnimated:YES];.

Based on your last update it seems like you don't have a navigation controller and you're just adding the view as a subview and storing the filter view controller. That makes life more complicated really and the correct way to remove it is to setup a delegate relationship so that the filter view controller calls back to the first view controller when it's done and the first controller then transitions the views and nil's the reference.
If you can, change to use a navigation controller properly. You already have half the code, but the first view controller seems to not be in a navigation controller. If you use a nav controller life will be easy...


text:
Q: how to decode predictions in tensorflow_serving of predictions I am using tensorflow serving to serve YOLO_V3 keras based model
Now ,everything is working but just prediction that Im getting  is a np array , how can I decode to a actual classes
This is the function that I'm using
import argparse
import json

import numpy as np
import requests
from keras.preprocessing import image

# Argument parser for giving input image_path from command line
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
                help="path of the image")
args = vars(ap.parse_args())

image_path = args['image']
# Preprocessing our input image
img = image.img_to_array(image.load_img(image_path, target_size=(224, 224))) / 255.

# this line is added because of a bug in tf_serving(1.10.0-dev)
img = img.astype('float16')

payload = {
    "instances": [{'input_image': img.tolist()}]
}

# sending post request to TensorFlow Serving server
r = requests.post('http://localhost:9000/v1/models/coco:predict', json=payload)
pred = json.loads(r.content.decode('utf-8'))
print(json.dumps(inception_v3.decode_predictions(np.array(pred['predictions']))[0]))

print(pred)
# Decoding the response

now this gives a big list of dictionaries
{6876, -4.81754398, -4.97275639, -4.97607, -4.67160654, -5.79011679, -5.50944614, -4.7312355, -4.77109718, -3.92586088, -4.7312994, -5.91286898, -4.75739, -5.51783752, -3.74576402, -3.78617764, -4.80710745, -3.40718174, -6.06222868, -6.37612915, -4.38785028, -4.47397232, -4.61613226, -3.94074273, -4.83034134, -5.37178898, -6.06883144, -6.90097952, -5.8203454, -5.86746645, -5.82842541, -6.18484926, -6.35572672, -5.26999807, -6.18502855, -5.94293404, -6.49861908, -5.93721819, -6.14823675, -5.90117025, -2.50677276, -2.75121665, -2.7598753, -3.41550899, -2.62428784, -4.74949789, -5.21396255, -3.80554819, -6.01200724, -5.17863417, -5.40073681, -6.22671843, -5.16459131, -5.0060482, -6.87409353, -4.7619772, -4.86423874, -3.08233714, -5.99755383, -5.63631535, -5.94745159, -4.65718126, -6.86422825, -6.06967211, -0.217412367, 0.0550900251, -0.707384586, 0.70622, -15.0436678, 1.10565865, -4.42187643, -2.98756099, -3.72572565, -3.26745987, -2.93719411, -4.07914925, -2.34109211, -3.39609504, -4.85195971, -3.63920546, -5.17407417, -5.62931442, -4.00350428, -5.02346706, -4.95578051, -4.48103857, -4.72352171, -6.18291044, -5.11228895, -4.26431751, -5.34162378, -5.54107809, -3.85009646, -4.6390605, -3.89385056, -4.55916357, -4.70904684, -4.15174866, -6.43089485, -4.33550072, -4.58510923, -5.21521187, -3.22094584, -5.75563383, -6.88566399, -4.80700207, -4.38226604, -5.49326801, -3.26696324, -4.9029026, -5.82695913, -6.17655087, -6.67043591, -5.67217445, -6.74844885, -5.9330287, -5.71555614, -6.11479235, -4.86581087, -5.67418, -5.19628048, -6.53483, -5.78065157, -5.86239386, -5.4403944, -3.27615428, -3.07651854, -2.16416335, -3.98195553, -4.52128935, -4.46353388, -4.64035559, -4.67165565, -6.01290417, -5.59658194, -5.59060287, -6.70377827, -6.25058842, -5.20660543, -6.53567076, -5.66916752, -3.13120627, -3.95540428, -5.51402569, -5.0683589, -6.33612585, -4.35945034, -6.52084446, -5.74546289]]]}]}

How do I decode it into classes ?
Doing this gives class mismatch error because its coco pre-trained model not imagenet
what will be a similar decoding function for this ?
print(json.dumps(inception_v3.decode_predictions(np.array(pred['predictions']))[0]))


text:
Q: Babel 'of' keyword (as in "Page x of y") I want to have "Page X of Y" in the footer, but I also want it to be flexible for other languages. I know I can do
\providecommand{\pagename}{Page}
\usepackage[german]{babel}
...
\pagename

which will display Seite instead of Page because of babel. What I want is something similar to of so that I can write:
\pagename \thepage{} of \pageref{LastPage}

with the appropriate macro instead of of so that when I switch to german (or any other language), the of will also switch to the appropriate language.
MWE:
\documentclass{article}
\usepackage{hyperref}
\usepackage{fancyhdr}
\usepackage{lastpage}
\providecommand{\pagename}{Page}
%\usepackage[german]{babel}

\fancypagestyle{custom}{%
    \fancyhf{}% clears the footer and header
    \fancyfoot[c]{\pagename \thepage{} of \pageref{LastPage}}
}%

\pagestyle{custom}

\begin{document}

foo baz baa, this is a document

\end{document}

A: With babel you have \setlocalecaption, which can be used to both redefine existing \...name captions and define new ones. The suffix name is added automatically.
\documentclass{article}

\usepackage[english,italian,ngerman]{babel}

\setlocalecaption{english}{of}{of}
\setlocalecaption{italian}{of}{di}
\setlocalecaption{ngerman}{of}{von}

\begin{document}

\pagename\ 1 \ofname\ 4.

\selectlanguage{english}

\pagename\ 1 \ofname\ 4.

\selectlanguage{italian}

\pagename\ 1 \ofname\ 4.

\end{document}

This prints:

Seite 1 von 4.
Page 1 of 4.
Pag. 1 di 4.

A: I defined a new macro that has this property: \of:
\ExplSyntaxOn
\prop_new:N\g_of_text_prop
\prop_gset_from_keyval:Nn \g_of_text_prop
 {
   english   = {of},
   spanish   = {de},
   german    = {von},
   italian   = {di},
   norsk     = {av},
   nynorsk   = {av},
   swedish   = {av},
   danish    = {af},
   french    = {de},
   esperanto = {el}
 }
\newcommand{\of}
 {
   \prop_get:NVNTF \g_of_text_prop \languagename \l_tmpa_tl
     { \l_tmpa_tl }
     { \prop_item:Nn \g_of_text_prop {english} }
 }

\ExplSyntaxOff

So now I can write:
\pagename \thepage{} \of\ \pageref{LastPage}

and when I use \usepackage[german]{babel}
I get: "Siete 1 von 1", as I wanted.


text:
Q: Modal UIViewController doesn't appear I'm attempting to load a Modal View Controller (1st) from a Modal View Controller (2nd). While it sounds complicated, it probably isn't.
The 1st controller is actually a UIWebView which is initialized in the loadView method of the .m file:
- (void)loadView {

    // Initialize webview and add as a subview to LandscapeController's view
    myWebView = [[[UIWebView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
    //CGRect forceframe = CGRectMake(0, 0, 480, 320);
    //myWebView = [[[UIWebView alloc] initWithFrame:forceframe] autorelease];
    myWebView.scalesPageToFit = YES;
    myWebView.autoresizesSubviews = YES;
    myWebView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
    myWebView.delegate = self;
    self.view = myWebView;
}

Then in viewDidLoad:
- (void)viewDidLoad {
    [super viewDidLoad];

    // Load HTML file as an NSURL request
    [self.myWebView loadHTMLString:updated_html baseURL:nil];

    // Invoke the covering modal view on condition
    if (some_condition) {
        landscapeCoverController = [[UIViewController alloc] initWithNibName:@"LandscapeCoverController" bundle:[NSBundle mainBundle]];

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

The intended 2nd Modal View Controller (landscapeCoverController) is initialized with a NIB that I set up in IB.
My intended objective, is to conditionally cover up the UIWebView with the "LandscapeCoverController" view, which will have some buttons and interactivity which will result in the 2nd Modal View being dismissed.
Why isn't my landscapeCoverController loading? Any thoughts greatly appreciated!
Also...the 1st Modal View controller (LandscapeViewController) .h looks like:
@class LandscapeCoverController;

@interface LandscapeViewController : UIViewController <UIWebViewDelegate> {
    UIWebView *myWebView;

    LandscapeViewController *landscapeCoverController;
}

@property (nonatomic, retain) UIWebView *myWebView;

@property (nonatomic, retain) LandscapeViewController *landscapeCoverController; // Modal view controller

and...the 2nd Modal View controller (landscapeCoverController) viewDidLoad does nothing:
// NIB initialized in LandscapeViewController.m viewDidLoad:
- (void)viewDidLoad {
    [super viewDidLoad];

}

as I think the
landscapeCoverController = [[UIViewController alloc] initWithNibName:@"LandscapeCoverController" bundle:[NSBundle mainBundle]];
[self presentModalViewController:landscapeCoverController animated:YES];
[landscapeCoverController release];

statement should handle initialization and loading of the controller...

A: You are declaring landscapeCoverController as an instance of LandscapeViewController, and allocating it as a UIViewController. This is most likely your problem (probably the first one, as you aren't calling any methods specific to LandscapeViewController). Also, since landscapeCoverController is an instance variable, you don't really need to release it after presentModalViewController. Try to pick more dissimilar class names. It will save you from confusion like this in the future.


text:
Q: save file to google cloud working directory Good morning. I am working in development with nodejs in local and I generate a .csv file
Once generated, I save it in the local system directory using library 'objects-to-csv';
Through the function:
     // New file csv
    const csv1 = new ObjectsToCsv(coordenadas);

    // Save to file:
    await csv1.toDisk('./coordenadas.csv');

  })()

If I deploy the application in google cloud, it works, however it reads the coordinates.csv file but does not rewrite it. There is some method without using storage?
Thank you

A: When you use serverless application (App Engine, CLoud Run, Cloud functions) your code is packaged into a container. Thus, you can't write in it, only read. In each product, you still have an "in-memory" file system in /tmp
So, use this directory to write the file and to serve it to your user. But, be careful, it's an in-memory file system. If you don't purge it (after the user download), you will reach the maximum allowed memory size and your instance will crash.


text:
Q: What happen in background memory point of view when we move one branch to another branch of same project in git...? What happen in background memory point of view when we move one branch to another branch of same project in git, Where the commit store???

A: When you move a branch to another, there's no new revision created. Only the pointer to the revision (aka, the branch, a file inside the .git directory, aka the repo) is renamed, but the content of the object (the file) does not change.


text:
Q: How to make custom Authentication filter like Iauthentication in dotnet core I am migrating asp.net mvc to dotnet 3.1, In older app we are using IAuthorization and IAuthentication filter  now in dotnet 3.1 we have IAuthorization filter but not the IAuthentication.
Kindly suggest the way to make custome Iauthentication filter in dotnet core 3.1.
We are using authentication method OnAuthentication.
public void OnAuthentication(AuthenticationContext filterContext)
        {
        if (System.Web.HttpContext.Current.Session.GetString("SUserID") == null && ConfigurationManager.AppSettings["Authentication"] == "Yes")
            {
                if(!(filterContext.ActionDescriptor.ActionName== "AuthRequest" || filterContext.ActionDescriptor.ActionName == "AuthResponse" || filterContext.ActionDescriptor.ActionName == "Sessiontimeout"))
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "AuthRequest", area = string.Empty }));
       }
}

A: You can implement the filter like this:
  public class CustomAuthorizeFilter : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            //check IsAjax request or not
            var ajax = context.HttpContext.Request.IsAjaxRequest();

            //IsAuthenticated
            var result = context.HttpContext.User.Identity.IsAuthenticated;

            //check user is in role
            var isInRole = context.HttpContext.User.IsInRole(YourRoleName);

            //get action and  controller Name
            var currentContext = context.Resource as AuthorizationFilterContext;
            var descriptor = currentContext?.ActionDescriptor as ControllerActionDescriptor;
            if (descriptor != null)
            {
                var actionName = descriptor.ActionName;
                var ctrlName = descriptor.ControllerName;
            }

            //and etc
        }
    }

you can Authorize your users in OnActionExecuting , and for reading session, you can use HttpContextAccessor. This is a good sample


text:
Q: How to listen all events in appdelegate I'm trying to get all callbacks from appdelegate with custom framework. But I couldn't figured out how can I do this ?
I'm trying to get all callbacks which is returned from appdelegate.

A: You can't have all the callback, Following is the list of UIApplication notifications you can register for.
@available(iOS 4.0, *)
public static let UIApplicationDidEnterBackground: NSNotification.Name

@available(iOS 4.0, *)
public static let UIApplicationWillEnterForeground: NSNotification.Name

public static let UIApplicationDidFinishLaunching: NSNotification.Name

public static let UIApplicationDidBecomeActive: NSNotification.Name

public static let UIApplicationWillResignActive: NSNotification.Name

public static let UIApplicationDidReceiveMemoryWarning: NSNotification.Name

public static let UIApplicationWillTerminate: NSNotification.Name

public static let UIApplicationSignificantTimeChange: NSNotification.Name

public static let UIApplicationWillChangeStatusBarOrientation: NSNotification.Name // userInfo contains NSNumber with new orientation

public static let UIApplicationDidChangeStatusBarOrientation: NSNotification.Name // userInfo contains NSNumber with old orientation

// userInfo dictionary key for status bar orientation
public static let UIApplicationWillChangeStatusBarFrame: NSNotification.Name // userInfo contains NSValue with new frame

public static let UIApplicationDidChangeStatusBarFrame: NSNotification.Name // userInfo contains NSValue with old frame

// userInfo dictionary key for status bar frame
@available(iOS 7.0, *)
public static let UIApplicationBackgroundRefreshStatusDidChange: NSNotification.Name

@available(iOS 4.0, *)
public static let UIApplicationProtectedDataWillBecomeUnavailable: NSNotification.Name

@available(iOS 4.0, *)
public static let UIApplicationProtectedDataDidBecomeAvailable: NSNotification.Name

// userInfo contains NSURL with launch URL
// userInfo contains NSString with launch app bundle ID
// userInfo contains NSDictionary with payload
// userInfo contains a UILocalNotification
// userInfo contains object with annotation property list
// app was launched in response to a CoreLocation event.
// userInfo contains an NSArray of NKAssetDownload identifiers
// userInfo contains an NSArray of CBCentralManager restore identifiers
// userInfo contains an NSArray of CBPeripheralManager restore identifiers
// userInfo contains the UIApplicationShortcutItem used to launch the app.

// Key in options dict passed to application:[will | did]FinishLaunchingWithOptions and info for UIApplicationDidFinishLaunchingNotification
// Sub-Dictionary present in launch options when user activity is present
// Key in user activity dictionary for the activity type
// The presence of this key indicates that the app was launched in order to handle a CloudKit sharing invitation. The value of this key is a CKShareMetadata object.

// userInfo contains NSURL with launch URL
// userInfo contains NSString with launch app bundle ID
// userInfo contains NSDictionary with payload
// userInfo contains a UILocalNotification
// userInfo contains object with annotation property list
// app was launched in response to a CoreLocation event.
// userInfo contains an NSArray of NKAssetDownload identifiers
// userInfo contains an NSArray of CBCentralManager restore identifiers
// userInfo contains an NSArray of CBPeripheralManager restore identifiers
// userInfo contains the UIApplicationShortcutItem used to launch the app.
// Key in options dict passed to application:[will | did]FinishLaunchingWithOptions and info for UIApplicationDidFinishLaunchingNotification
// Sub-Dictionary present in launch options when user activity is present
// Key in user activity dictionary for the activity type
// The presence of this key indicates that the app was launched in order to handle a CloudKit sharing invitation. The value of this key is a CKShareMetadata object.

// Keys for application:openURL:options:

// value is an NSString containing the bundle ID of the originating application
// value is a property-list typed object corresponding to what the originating application passed in UIDocumentInteractionController's annotation property
// value is a bool NSNumber, set to YES if the file needs to be copied before use

// value is an NSString containing the bundle ID of the originating application
// value is a property-list typed object corresponding to what the originating application passed in UIDocumentInteractionController's annotation property
// value is a bool NSNumber, set to YES if the file needs to be copied before use

// This notification is posted after the user takes a screenshot (for example by pressing both the home and lock screen buttons)
@available(iOS 7.0, *)
public static let UIApplicationUserDidTakeScreenshot: NSNotification.Name


text:
Q: How to chain 3 Promises with angular2 and typescript I have successfully chained promises, but I find the way I did it enough complicated: I'm wondering if there is not a more elegant way to do it.
I use Angular2, Typescript and signalR.
I have a service getIntervention that returns an object from the server by Id.
Before calling getIntervention, I want to check the client to be connected to the server, and before connecting to the server, I want the SignalR scripts to be loaded.
So I created a first promise scriptLoadedPromise that waits for the SignalR script to be loaded. When scriptLoadedPromise is resolved a new promise connectionPromise is created that waits for the connection to be established.
When connectionPromise  is resolved, call the service getIntervention.
For each promise I added callbacks named scriptLoaded  and connectionDetected  that call resolve().
Here is my code:
public loadIntervention( numFI : number ) : Promise<Intervention>
{

    let scriptLoadedPromise : Promise<Intervention> = new Promise( ( resolve, reject ) =>
    {
        // si le script est chargé alors la promesse est déjà tenue
        if ( this.isScriptLoaded )
            resolve();
        else
            this.scriptLoaded = ( () => { resolve(); } ) ;
    }).then
    ( () => {
        let connectionPromise : Promise<Intervention> = new Promise( (resolve, reject) =>
        {
            // si le serveur est connecté alors la promesse de connection est déjà tenue
            if ( this.Connected )
                resolve();
            else
                this.connectionDetected = ( () => { console.log("RECONNETED !!!!!"); resolve(); } );

        } )
        .then( ()  => { return this.proxy.server.getIntervention( numFI ); } );

        return connectionPromise;
    });

    return scriptLoadedPromise;
}

Is there a way to simplify that implementation where 3 promises are chained ?

A: If these promises depend on each other, it's similar to what you created already. You could enhance the code-style of that, by putting the logic into separate methods like e.g.
private firstAction():Promise<any> {
  return new Promise<any>(
    (resolve, reject) => { ... }
  );
}
private secondAction():Promise<any> {
  return new Promise<any>(
    (resolve, reject) => { ... }
  );
}
execute() {
  this.firstAction().then(
    (firstResult:any) => this.secondAction().then(
      (secondResult:any) => { ... }
    );
  )
}

If it's allowed that the promises are executed in parallel, you can make use of Promise.all(), like e.g.
execute() {
  let promises:Promise<any>[] = [];
  promises.push(this.firstAction());
  promises.push(this.secondAction());

  Promise.all(promises).then(
    () => { ... }
  );
}


text:
Q: An app that can give me the amount of time using an app? I need an app that tracks automatically every time I use Final Cut X or another app and gives me the total usage time. Any ideas?

A: I use RescueTime. It's quite cool + for free you get a lot of features

A: Option A
Option A is to create an alias:
alias timeon='ps -ax -o etime,command -c | grep'

then you can run:
timeon Safari

Option B
If you're comfortable with the shell you can use:
ps -ax -o etime,command -c

and attempt to locate the app. For me, Safari looks like:
   01:57:18 Safari

You an also pipe it through grep:
ps -ax -o etime,command -c | grep "Safari$"


text:
Q: reducer case set value delayed response When I dispatch "REMOVE_TODO" on button click it does what I want it to do, the problem I'm having is that when it executes. It doesn't return the correct current array length.

Now when I click an item, it will dispatch "TOGGLE_TODO" which will change the font color and put a line-through the text.

Now while toggled and I click the "Clear Completed" button, it toggles "REMOVE_TODO" and works fine. It removes the items toggled. The problem I'm having is that The number doesn't reflex the current amount of items left in the list when I click the button once..

However if I click the button once more (or however many more times) the number updates to the correct total

This is my app code
import React, { useState, useReducer } from 'react';
import { Reducer } from './reducers/reducer';
import './App.css';

function App() {
  const [{ todos, todoCount }, dispatch] = useReducer(Reducer, {
    todos: [],
    todoCount: 0,
    completedCount: 0
  });
  const [text, setText] = useState("");

  return (

ToDo List [ { todoCount } ]

          { todos.map((todo, index) => (

 dispatch(
                { type: "TOGGLE_TODO", index }
              )}
              style={{
                fontFamily: 'Tahoma',
                fontSize: '1.5rem',
                textDecoration: todo.completed ? 'line-through' : "",
                color: todo.completed ? '#61dafb' : 'dimgray',
                cursor: 'pointer'
              }}
              >
                { todo.text }

            ))
          }
          <form
            onSubmit={e => {
              e.preventDefault();
              text.length === 0 ? alert("No Task To Add!") : dispatch({ type: "ADD_TODO", text });
              setText("");
            }}
          >
            <input
              type="text"
              name="input"
              value={ text }
              onChange={e => setText(e.target.value)}
            />

            <button>
              Add
            </button>
          </form>
          <button onClick={() => {dispatch({ type: "REMOVE_TODO" })}}>
            Clear Completed
          </button>

  );
}

export default App;

and this is my reducer code
export const Reducer = (state, action) => {
    switch (action.type) {
        case 'ADD_TODO':
            return {
                todos: [...state.todos, { text: action.text, completed: false, id: Date.now() }],
                todoCount: state.todoCount + 1,
                completedCount: 0
            };
        case 'TOGGLE_TODO':
            return {
                todos: state.todos.map((todo, index) => index === action.index ? { ...todo, completed: !todo.completed } : todo),
                todoCount: state.todoCount,
                completedCount: 0
            };
        case 'REMOVE_TODO':
            return {
                todos: state.todos.filter(t => !t.completed),
                todoCount: state.todos.length
                }
        default:
            return state;
    };
 };

Does anyone have any idea what I'm doing wrong, or what I'm not doing? Thanks in advance!

A: Remove "todoCount" from reducer, then derive count using "todos":

      ToDo List [{" "}

        {todos.filter((todo) => !todo.completed).length}
      {" "}
      ]

View in CodeSandbox here


text:
Q: How to send json schema validation for mutual dependency field to ajv npm module? Thanks! I tried many ways to resolve it but I am unable to resolve it.
Here is the sample payload except for caseId every field is an optional field :
{
"CaseId": "xxxxxxxx",
"OpsrampStatus":"New",
"Reference": [
  {
    "Type": "GDDC Incident Number",
    "ReferenceNumber": "INC-xxx"
  },
  {
    "Type": "Opsramp Incident Number",
    "ReferenceNumber": "INC-xxx"
  }
]  }

so here OpsrampStatus is Mandatary field when the Reference array contains Type field as Opsramp Incident Number
Pass Case:
1.
{
"CaseId": "xxxxxxxx",
"Reference": [
  {
    "Type": "GDDC Incident Number",
    "ReferenceNumber": "INC-xxx"
  },

]}

*

`{
    "CaseId": "xxxxxxxx",
    "OpsrampStatus":"New",
    "Reference": [
      {
        "Type": "Opsramp Incident Number",
        "ReferenceNumber": "INC-xxx"
      }
    ]  }
`

Failed Case:
1.
`
{
    "CaseId": "xxxxxxxx",
    "Reference": [
      {
        "Type": "Opsramp Incident Number",
        "ReferenceNumber": "INC-xxx"
      }
    ]  }

`
2.
`{
    "CaseId": "xxxxxxxx",
    "OpsrampStatus":"New",
   }
`

Here is the schema I tried


text:
Q: Kubernetes Ingress www.example.com gives 404 while https://example.com works Does anyone know what could be the problem that i'm getting a 404 when trying to access the website via www.example.com while https://example.com works without any issues.
Here is the example of my ingress:
# Ingress
apiVersion: networking.k8s.io/v1
# make a new cert
kind: Ingress
metadata:
  name: ${APP_NAME}
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/ssl-redirect: 'true'
    nginx.ingress.kubernetes.io/from-to-www-redirect: 'true'
spec:
  defaultBackend:
    service:
      name: ${APP_NAME}
      port:
        number: 80
  tls:
  - secretName: ${APP_NAME}
    hosts:
    - ${URL}
    - www.${URL}

Also I tried to run
kubectl describe ingress

it returns:
host: example.com
Is there an issue with the configuration or why does the www. not redirect properly?

A: You don't specify the hosts. They need to be specified in spec.rules, for example:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: name-virtual-host-ingress-no-third-host
spec:
  rules:
  - host: first.bar.com
    http:
      paths:
      - pathType: Prefix
        path: "/"
        backend:
          service:
            name: service1
            port:
              number: 80
  - host: second.bar.com
    http:
      paths:
      - pathType: Prefix
        path: "/"
        backend:
          service:
            name: service2
            port:
              number: 80

Note: Keep in mind that TLS will not work on the default rule because the certificates would have to be issued for all the possible sub-domains. Therefore, hosts in the tls section need to explicitly match the host in the rules section.

Source


text:
Q: Run code with a different outcome every 30 seconds I have 2 variables called var1, and var2:
var var1 = 'foo';
var var2 = 'bar';

I'd like to be able to log one of these variables to the console every 30 seconds, with the variables alternating being logged (here's some pseudo-code):
Log var1 to console
Wait 30 seconds
Log var2 to console
Wait 30 seconds
Repeat
Any way to do this? I believe I should be doing something related with setInterval, but my solution:
setInterval(function() {
    console.log(var1);
    setTimeout(() => {
        console.log(var2);
    }, 30000);
}, 60000);

Doesn't seem to be the best solution. Is there a more efficient way to do this?

A: Just keep counter that enables you to alternate.

var counter = 0;
var var1 = "ONE!";
var var2 = "TWO!";
var frequency = 1000; //1000 is for illustration for the example

setInterval(function() {
   if( counter++ % 2 == 0 ) {
     console.log(var1);
   } else {
     console.log(var2);
   }
}, frequency );

A: You want to use setInterval so that the interval is consistent and there is no execution time involved in establishing the time for the next async call.
You can pass in an object reference to control scope and also track the boolean and flip it:

 setInterval(function(a){
        a.bool = !a.bool
        if(!a.bool){
            console.log( a.var1)
            return
         }
         console.log(a.var2)
    }, 3000, {
    bool : true,
    var1 : 'value',
    var2 : 'other value'
    })

A: You could use setTimeout with two functions that call each other:

var var1 = 'foo';
var var2 = 'bar';

const log1 = () => {
  console.log(var1);
  setTimeout(log2, 30000)
}

const log2 = () => {
  console.log(var2);
  setTimeout(log1, 30000)
}

log1();

A: Here's a more generic approach: For a given list of values - it'll print the provided values in a cycle forever, and will wait for intervalMs between every print
/**
 *
 * @param {Array} values - collection of values to log
 * @param {Number} intervalMs - the log interval
 */
function logValuesCyclicForever(values, intervalMs = 30000) {
  let index = 0;
  return setInterval(() => {
    console.log(values[index]);
    index = (index + 1) % values.length; // sets the location back to 0 when the last element is printed.
  }, intervalMs);
}

var var1 = 'foo';
var var2 = 'bar';

logValuesCyclicForever([var1, var2]); // for your use case


text:
Q: How to Store a stylesheet reference defined in a XAML in a separate Class to be used in any XAML Window? I have a XAML MyXamlStyleSheet.xaml where I define the style of a Button and Various other Controls.
I also have a C# class MyButtonClass : Button that I defined to intercept the basic Button class and declare any custom functionality that I want to give it.
In the XAML Window where I want to use  I have declared a xmlns:lc with the source pointing to the C# class MyButtonClass.
What I want to do is that when I declare this custom button
<lc:MyButtonClass .../>

I have a Reference to the Style defined in MyXamlStyleSheet that is stored in MyButtonClass so that I can access it from the XAML Window.
What would I write in the class and in the xaml declaration?
<lc:MyButtonClass Style="{StaticResource ???"..../>

Until now I have used MergedDictionaries to reference the XAML style sheet directly. However I want to do it using this different path.

A: Found the answer. It´s the same as Merging a Dictionary to your XAML Window int the Window.Resources section. From your class you instantiate a ResourceDictionary with the correct path and Merge that dictionary to the Dictionary of the Button class.
namespace YourNamespace
{

    public class MyCustomButton : Button
    {

        public MyCostumButton()
        {

            ResourceDictionary res = Application.LoadComponent(new Uri("/Directory/StyleDirectory.xaml", UriKind.RelativeOrAbsolute)) as ResourceDictionary;
            if (res == null)
                return;
            Resources.MergedDictionaries.Add(res);
            Style = (Style)FindResource("Name of the x:Key your gave your style");
        }
    }
}

This let´s you write an entire library of standarized controls in a Folder, where each control has a C# class assigned to it. So if you have many implementations of the same control you can always define the most basic behaviour and look in the XAML file that the class is referencing.


text:
Q: Editing Docker container FS using Atom/Sublime-Text? I'm running OSX and Docker with the help of boot2docker.
From my understanding boot2docker is a lightweight linux distro that is running the docker containers. I have some Ubuntu containers that I use to run and test projects that should specifically run well on Linux.
However every small code change from my host text editor of choice, requires me to re-build image and re-run the container. Run the  app and confirm that the change I made didn't break something.
Is there a way for me to open a Docker container FS folder in a text editor from my host machine? (a.k.a Remote edit?)
Have any of you guys done this? Any ideas will be awesome. I think about setuping SFTP or SSHD on the Docker container, but I would want your opinion?

A: What I often do is, in development, mount the source code of the application to its usual place in a volume. Then, I set the command (or entrypoint) of the container to a script that launches it in "development mode" (for example, by using nodemon for a node.js application, setting RAILS_ENV=development in Rails, and so on).
Volumes do work on Mac OS X (and I assume Windows) under boot2docker or docker-machine, with the caveat that you need to be working somewhere beneath your home directory.
For a concrete example, here's a repository that I set this up in. The ingredients:

*

*script/dev is my "dev-mode" entrypoint. It launches the main application under nodemon.

*When I launch the container, I mount the source directory into the container as a volume and set script/dev as the command. (I'm using docker-compose here to launch and link in an upstream dependency, so I can do everything in one command.)

With those two things in place, I can run docker-compose up, make a source change in whatever editor I choose on my host, save the file, and the service within the container auto-reloads to bring my changes into effect. Presto!


text:
Q: Python switch case, multiple value How to execute multiple value in python dictionary?
def func1():
    pass
def func2():
    pass
def func3():
    pass
def func4():

def main_menu():
    os.system('clear')
    print("\nWelcome, \n\n")
    print("1. First Question")
    print("2. Second Question")
    print("\n\n Type 'q' for Quit\n")
    choice = input(" >>  ").lower()
    if choice == '':
        main_menu()
    else:
        try:
            main_menus[choice]()
        except KeyError:
            print("Invalid selection, Please try again.\n")
            main_menu()
    return

main_menus = {
    '1' : func1,
    '2' : func2,
}

i want main_menus key have two value, like this for example
main_menus = {
    '1' : func1, func4
    '2' : func2, func3
}

so, if user input '1', it will execute func1 first, after finish, it will execute func4..
i can't call func4 from func1 like this:
def func1():
    return func4()

because func1, maybe will be use by another main_menus key, and will be pair with func3..
anyone have solution for this, if can, better not use for loop.
Thank you

A: Option 1 Using Eval
main_menus = {
    '1' : "func1(), func2()",
    '2' : "func2(), func3(),func4()"
}

try:
    eval(main_menus[choice])

Overall Code becomes:
import os

def func1():
  pass

def func2():
  pass

def func3():
  pass

def func4():
  pass

def main_menu():
  choice = ''
  while True:
    os.system('clear')
    print("\nWelcome, \n\n")
    print("1. First Question")
    print("2. Second Question")
    print("\n\n Type 'q' for Quit\n")

    choice = input(" >>  ").lower()
    if choice != 'q':
      try:
        eval(main_menus[choice])
      except KeyError:
          print("Invalid selection, Please try again.\n")
    else:
      break

  return

main_menus = {
    '1' : "func1(), func2()",
    '2' : "func2(), func3(),func4()"
}

main_menu()

Option 2 -- Use For Loop
Replace main_menus and try are in overall code above with:
main_menus = {
    '1' : [func1, func2],
    '2' : [func2, func3, func4]
}

try:
    for f in main_menus[choice]:
        f()

A: Just define a function that calls both of them.
def func12():
    func1()
    func2()
def func34():
    func3()
    func4()

main_menus = {
    '1': func12,
    '2': func34
}


text:
Q: What is the running time of two sorting algorithms if one is merge sort and one is insertion sort If I have to sort one list and merge it with another already sorted one. Then what will the running time be if I use merge sort and insertion sort?
Merge sort is: n logn
Insertion sort is: n^2
But together they are?
EDIT: Oh, so what I actually meant was that I had to sort one of the lists and merge them together.
I have made the pseudocode for the insertion sort, but I don't know what the running time of the two algorithms will be.
http://gyazo.com/0010f053f0fe64a82dad1dd383740a3f

A: The complexity of merging two sorted lists with lengths n1 and n2 is O(n1 + n2); that should be enough to work out the big-Oh of the entire algorithm


text:
Q: Why table header is also sorting with table data in jade?
Here is my code sample that is working perfect but the only problem is that when i click on table header its sort the data but also it include the table header itself.(Table header also sorted)

.Container.feedPageComponent.feedPageHome
 script(src='/dashboard/bootstrap/js/tablesort.js')
 script.
  var something = function(text) {
    console.log('something', text);
    var value = text;
    window.location.href="#{baseUrl}/feed/searchData/"+value
  }
  function init() {
   new Tablesort(document.getElementById('myTable'));
    }
  window.onload = init;
 div.input
            input(type="text",id="demo" name="title", placeholder="Search Your Articles",onchange="something(this.value)")
  div
    table#myTable.table.table-striped
      tr
         th Date
         th Time
         th Title
         th Type
         th Delete
         th User
         th Share
      - for item in data.rows.feedArray
        tr
          - var a = new Date(item.publishDate)
          if a == "Invalid Date"
            td N/A
            td
          else
            td #{a.toDateString()}
            td

A: The table header elements need to be in thead to be recognised as a table head. Then the rest goes into the tbody.
See also https://github.com/Mottie/tablesorter/issues/397 :

  ...
  table.table.tablesorter.table-bordered
    thead
      tr
        th Name
        th Label
        th Created
        th Expires
        th Type
        th Status
        th.last
    tbody
      each tape in tapes
  ...


text:
Q: Polars: how to add a column in front? What would be the most idiomatic (and efficient) way to add a column in front of a polars data frame? Same thing like .with_column but add it at index 0?

A: You can select in the order you want your new DataFrame.
df = pl.DataFrame({
    "a": [1, 2, 3],
    "b": [True, None, False]
})

df.select([
    pl.lit("foo").alias("z"),
    pl.all()
])

shape: (3, 3)
┌─────┬─────┬───────┐
│ z   ┆ a   ┆ b     │
│ --- ┆ --- ┆ ---   │
│ str ┆ i64 ┆ bool  │
╞═════╪═════╪═══════╡
│ foo ┆ 1   ┆ true  │
├╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ foo ┆ 2   ┆ null  │
├╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ foo ┆ 3   ┆ false │
└─────┴─────┴───────┘


text:
Q: Why does Wunderlist not load in private Firefox? If I login to Wunderlist from a private tab in Firefox, it keeps reloading https://www.wunderlist.com/webapp# over and over. In Chrome, I have no such problem; I can access it from private tab.
Now the first step of the answer to the popular question "why won't Wunderlist load in Firefox?" in Wunderlist's FAQ seems to impy it is by design.

1. Ensure that you are not using Wunderlist in Private Browsing mode

My question is two-fold:

*

*Why was Wunderlist designed to not work in private browsing mode in Firefox?

*Is there a known workaround for this, by tweaking the settings for instance?
(Other than using a different browser).


text:
Q: Chrome --user-data-dir not working properly? So i wanted to pin different chrome instances to my taskbar. I've found this cmd line argument and I tried executing it:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir="C:\Users\username\AppData\Local\Google\Chrome\User Data"
And It opened chrome with the default profile. I have another local profile for developing with different extensions etc. Its path is ..\Profile 1
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir="C:\Users\username\AppData\Local\Google\Chrome\User Data\Profile 1"
Weird thing, it opened a somewhat guest profile, with no ability to switch to other profiles. What's wrong?

A: The User Data folder is the profile.
Copy the existing C:\Users\username\AppData\Local\Google\Chrome\User Data folder to something like C:\Users\username\ChromeProfiles\User Data (anywhere else on C:\ might cause Admin access issues).
Now make a new (or copy existing) taskbar shortcut and point its Target (including quotations) to "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir="C:\Users\username\ChromeProfiles\User Data
I use this trick to move my profile to a RAM drive on bootup (obviously w/ different path structure) and it works like a charm.

A: Instead of using  --user-data-dir run Chrome with this parameter:

chrome.exe --profile-directory="Profile 1"

A: As another answer explained, your User Data folder in its entirety needs to be copied.
Hence you cannot just reference "Profile 1" within a User Data Folder but have to reference an entire User Data folder.
What you can do is
1. Copy your current User Data folder (with said guest profile) to a NEW DIRECTORY
2. Point chrome shortcut to the NEW DIRECTORY using the --user-data-dir parameter
3. After launch, notice that the profile is exactly as the original. Now modify this chrome instance, removing profiles and things you don't need.

A: If you are attempting to run this from IIS and the application pool is not set to load a profile, you'll need to set both the --profile-directory and --user-data-dir, such as:
chrome.exe --profile-directory="C:\temp\profile" --user-data-dir="C:\temp\profile\userdata"


text:
Q: Operator precedence in C++ For the following function

int search(int n) {
    return arr[n] == n ? n : arr[n] = search(arr[n]);
}

Not very sure exactly what it's supposed to do. According to what I understand about operator precedence, my guess is that above is equivalent to
int search(int n) {
    if (arr[n] == n) {
        return n;
    } else {
        return arr[n] = search(arr[n]);
    }
}

but then it doesn't really make sense to me that the function is returning an assignment? Or am I interpreting it wrong entirely?

A: Your expansion of the expression looks correct to me.
I think what you're missing is that assignment expressions can be evaluated as a value. The value returned is the value of the left operand after assignment.
So arr[n] = search(arr[n]) effectively returns arr[n] after it was assigned the return value of search(arr[n]).
This SO answer covers the part of the standard that allows this and answers a similar question.

After testing some different initial arrays and arguments with that function, I should warn you that it can throw a StackOverflow exception!
For Example: arr[2] = {1,0}; and search(1);.


text:
Q: How to hide widget from UI without taking up any space in GridView
I need to hide a widget in a GridView. I searched and tried many ways to hide this widget but it still have space. so this is what I used to solve it
1- I used Visibility
2- I used Offset
3- I used If case but the widget still have place in GridView and ListView ,
I need it to be removed and don't take any space in my Ui.
I give it red color to show .
GridView.builder(
                          dragStartBehavior: DragStartBehavior.start,
                          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 4
                          ),
                          scrollDirection: Axis.vertical,
                          physics: ScrollPhysics(),
                          shrinkWrap: true,
                          itemBuilder: (BuildContext context, int index) {
                            var data = val[index];
                            bool visible = data['isView'] && data['url'] != '';

                            return !visible?Padding(
                              padding: const EdgeInsets.all(5),
                              child: Container(
                                  color:Colors.red),
                            ): Container(
                                decoration: BoxDecoration(
                                    borderRadius:
                                        BorderRadius.circular(15),
                                    color: data['IsDirectOn']
                                        ? mCD
                                        : Colors.white,
                                    boxShadow: [
                                      BoxShadow(
                                          color: mCL,
                                          offset: Offset(3, 3),
                                          blurRadius: 3,
                                          spreadRadius: -3),
                                    ]),
                                child: Expanded(
                                  child: Container(
                                    child: SocialBox(
                                        color: Colors.green,
                                        width: width,
                                        height: height,
                                        image: data['image'],
                                        category: data['label']),
                                  ),
                                ),

                            );
                          },
                          itemCount: snapshot.data.documents.length,
                        );

A:
The data comes from Firebase, and I don't know how to remove index from Firebase list

After getting data from Firebase, you can filter it with your conditions.
  _DataList = AllDataList.where((i) => i['isView'] && i['url'] != '').toList();