text:
Q: KerasTuner Custom Objective Function I am trying to use Keras Tuner for my hyper-parameter fine tuning. I would like to maximize auc. Can anyone help me with using kerastuner.Objective for a custom metric ?
EXECUTIONS_PER_TRIAL = 5

b_tuner = BayesianOptimization(
    tune_nn_model,
    objective='val_binary_accuracy',
    max_trials=MAX_TRIALS,
    executions_per_trial=EXECUTIONS_PER_TRIAL,
    directory='test_dir101897',
    project_name='b_tune_nn',
    seed=12347
)

I tried defining a custom function like :
from sklearn import metrics
from keras import backend as K

def auc(y_true, y_pred):
    auc = tf.metrics.auc(y_true, y_pred)[1]
    K.get_session().run(tf.local_variables_initializer())
    return auc

and plug it in
objective='val_auc'

But this does not work

A: Thanks to the GitHub page provided above by @Shiva I tried this to get the AUC for the validation data with the Keras tuner, and it worked. My model is an LSTM, and I have made the MyHyperModel class to be able to tune the batch_size as described here. You don't have to do this if you want to use a fixed batch_size. You can uncomment any of the other metrics and do the regularization based on them in the same way.
# make X_train, y_train, X_valid, y_valid
mask_value=-9999.99
epochs=200

class MyHyperModel(kt.HyperModel):
  def build(self, hp):
    hp_lstm_units = hp.Int('units', min_value=16, max_value=128, step=16)
    hp_dropout_rate = hp.Float('drop_out_rate', min_value=0, max_value=0.6)
    hp_recurrent_dropout_rate = hp.Float('recurrent_dropout_rate', min_value=0, max_value=0.6)
    hp_initial_learning_rate = hp.Float('initial_learning_rate',  min_value=1e-3, max_value=1e-1, sampling='log')
    hp_decay = hp.Int('decay', min_value=10, max_value=100, step=10 )

    # model
    model = tf.keras.Sequential()

    model.add(tf.keras.layers.Masking(mask_value=mask_value, input_shape = (X_train.shape[1], X_train.shape[2])))
    model.add(tf.keras.layers.LSTM(hp_lstm_units,
    dropout=hp_dropout_rate, recurrent_dropout=hp_recurrent_dropout_rate))
    model.add(tf.keras.layers.Dense(1, activation='sigmoid'))
    model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=False),
                  optimizer=keras.optimizers.SGD(learning_rate=hp_initial_learning_rate, decay=hp_decay),
                  metrics=[
                      # tf.keras.metrics.TruePositives(name='tp'),
                      # tf.keras.metrics.FalsePositives(name='fp'),
                      # tf.keras.metrics.TrueNegatives(name='tn'),
                      # tf.keras.metrics.FalseNegatives(name='fn'),
                      # tf.keras.metrics.BinaryAccuracy(name='accuracy'),
                      # tf.keras.metrics.Precision(name='precision'),
                      # tf.keras.metrics.Recall(name='recall'),
                      tf.keras.metrics.AUC(name='auc'),
                  ])
    return model

    def fit(self, hp):
      hp_batch_size = hp.Int('batch_size', min_value=8, max_value=128, step=8)
      return model.fit(
          *args,
          batch_size=hp_batch_size,
          **kwargs)

tuner = kt.BayesianOptimization(
    MyHyperModel(),
    objective=kt.Objective('val_auc', direction='max'),
    overwrite=True,
    max_trials=100,
    directory="MyDirectory",
    project_name="MyProject",
)

tuner.search(X_train, y_train, epochs=200, validation_data=(X_valid, y_valid))


text:
Q: DATE_FORMAT displays NULL SQL:
SELECT
    MAX(ansprechpartner.timestamp),
    MAX(gallery.timestamp),
    MAX(instrument.timestamp),
    MAX(kurs.timestamp),
    DATE_FORMAT('maxDate', '%d. %M %Y') as MaxDateFormat,
    CASE
        WHEN MAX(ansprechpartner.timestamp) > MAX(gallery.timestamp)
                AND MAX(ansprechpartner.timestamp) > MAX(instrument.timestamp)
                AND MAX(ansprechpartner.timestamp) > MAX(kurs.timestamp)
            THEN MAX(ansprechpartner.timestamp)
        WHEN MAX(gallery.timestamp) > MAX(ansprechpartner.timestamp)
                AND MAX(gallery.timestamp) > MAX(instrument.timestamp)
                AND MAX(gallery.timestamp) > MAX(kurs.timestamp)
            THEN MAX(gallery.timestamp)
        WHEN MAX(instrument.timestamp) > MAX(ansprechpartner.timestamp)
                AND MAX(instrument.timestamp) > MAX(gallery.timestamp)
                AND MAX(instrument.timestamp) > MAX(kurs.timestamp)
            THEN MAX(instrument.timestamp)
        ELSE MAX(kurs.timestamp)
    END AS maxDate
FROM ansprechpartner, gallery, instrument, kurs

The .timestamp columns have the type timestamp.
So the problem is, that I get a NULL value within my MaxDateFormat. Any idea what I might have missed here?

A: By quoting the column name 'maxDate', you a causing MySQL to treat it as a string literal, which can not be converted into a date, so the result is NULL.  Try it without quotes:
DATE_FORMAT(maxDate, '%d. %M %Y') as MaxDateFormat

A: You cannot access alias name maxDate in same SELECT list in which it is defined.
Although you are not geting error because you have written maxDate in qoutes making it a string literal which expectedly fails to be converted into dateformat and returns NULL.
Use a derived table expression like below
SELECT col1,col2,col3,DATE_FORMAT(maxDate, '%d. %M %Y') as MaxDateFormat,maxDate
FROM

(   SELECT
    MAX(ansprechpartner.timestamp) as col1,
    MAX(gallery.timestamp) as col2,
    MAX(instrument.timestamp) as col3,
    MAX(kurs.timestamp) col4,

    CASE
        WHEN MAX(ansprechpartner.timestamp) > MAX(gallery.timestamp)
                AND MAX(ansprechpartner.timestamp) > MAX(instrument.timestamp)
                AND MAX(ansprechpartner.timestamp) > MAX(kurs.timestamp)
            THEN MAX(ansprechpartner.timestamp)
        WHEN MAX(gallery.timestamp) > MAX(ansprechpartner.timestamp)
                AND MAX(gallery.timestamp) > MAX(instrument.timestamp)
                AND MAX(gallery.timestamp) > MAX(kurs.timestamp)
            THEN MAX(gallery.timestamp)
        WHEN MAX(instrument.timestamp) > MAX(ansprechpartner.timestamp)
                AND MAX(instrument.timestamp) > MAX(gallery.timestamp)
                AND MAX(instrument.timestamp) > MAX(kurs.timestamp)
            THEN MAX(instrument.timestamp)
        ELSE MAX(kurs.timestamp)
    END AS maxDate
FROM ansprechpartner, gallery, instrument, kurs
) as z

In above query, the inner query is used as as a derived table on which further processing is done by outemost SELECT list.
Giving a name as Z to the inner query makes it sort of table which allows for SELECT clause to work on it.

A: try this : -
select ansprechpartner_timestamp, gallery_timestamp, instrument_timestamp, kurs_timestamp, DATE_FORMAT(maxDate, '%d. %M %Y') as MaxDateFormat
from
(SELECT MAX(ansprechpartner.timestamp) as ansprechpartner_timestamp, MAX(gallery.timestamp) as gallery_timestamp, MAX(instrument.timestamp) as instrument_timestamp, MAX(kurs.timestamp) as kurs_timestamp,

CASE
WHEN MAX(ansprechpartner.timestamp) > MAX(gallery.timestamp) AND MAX(ansprechpartner.timestamp) > MAX(instrument.timestamp) AND MAX(ansprechpartner.timestamp) > MAX(kurs.timestamp) THEN MAX(ansprechpartner.timestamp)
WHEN MAX(gallery.timestamp) > MAX(ansprechpartner.timestamp) AND MAX(gallery.timestamp) > MAX(instrument.timestamp) AND MAX(gallery.timestamp) > MAX(kurs.timestamp) THEN MAX(gallery.timestamp)
WHEN MAX(instrument.timestamp) > MAX(ansprechpartner.timestamp) AND MAX(instrument.timestamp) > MAX(gallery.timestamp) AND MAX(instrument.timestamp) > MAX(kurs.timestamp) THEN MAX(instrument.timestamp)
ELSE MAX(kurs.timestamp)
END AS maxDate

FROM ansprechpartner, gallery, instrument, kurs ) as table1

redpajama_set_name: RedPajamaStackExchange


text:
Q: excel vba: Can someone help me understand how to use a cusom sort order? I've been working on a code to sort a block of data using Range.Sort using a custom sort order. I've tried to record macros and look online but came up more confused about this problem.

*

*For the key1:= argument; is it a single cell (e.g. Range("A1")) or a whole column?

*How exactly can I use a custom sort order in OrderCustom:=?

*In the case I'm going about this all wrong; the Range in Range.Sort can be anywhere as long as its in one continuous block, correct?

Here is the code I'm working with:
Sub Test()
    Dim quantity As Variant
        quantity = 2 + WorkshetFunction.Count(Range("A" & 3, "K" & 900))

    With Range("A" & 3, "K" & quantity)
        .Sort key1:=Range("A" & 3)
              Order:=xlAscending
              Header:=xlNo
              OrderCustom:="VALID, GOOD, DUE, OVERDUE, WAY OVERDUE, MISSING"
                '> This is the order in which I want the items on this list sorted by.
    End With
End Sub

The Range("A" & 3, "K" & quantity) refers to a block of data containing on "A" the "status" of some items determined by their calibration expiration dates, amongst other data which is irrelevant for this  purpose, and  I'm not in the liberty to share. All I'm asking is help understanding the inner workings of the .Sort method. Thanks!

A: Give'r
Sub SortItOut()
    Dim rng As Range, sh As Worksheet
    Set sh = Sheets("Sheet1")
    With sh
        Set rng = .Range("A3:K" & .Cells(.Rows.Count, "K").End(xlUp).Row)
        With rng
            sh.Sort.SortFields.Clear
            sh.Sort.SortFields.Add Key:=Range("A3") _
                                 , SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:= _
                                   "VALID,GOOD,DUE,OVERDUE,WAY OVERDUE,MISSING", DataOption:=xlSortNormal
        End With
        With .Sort
            .SetRange rng
            .Orientation = xlTopToBottom
            .Apply
        End With
    End With

End Sub


text:
Q: How to create an "external" 404 route in React router 4, when using nested routing? I'm trying to create a 404 route in React router 4. The thing is, that my main routing page renders a component i call "container", in which all standard views are rendered. Looks something like that:
const AppRouter = () => (
 <Router history={history}>

     <Switch>
       <Route path="/" component={Container}  />
       <Route component={NotFoundPage} />
     </Switch>

</Router>
);

Then the Container:
const Container = (props) => (

      <Switch>
          <Route path="/" component={DashboardPage} exact={true} />
          <Route path="/Test" component={Test} />
      </Switch>

 );

The idea is, to completely separate the 404 page from the container. With the current setup, the 404 page doesn't even get rendered. If i put this route within the switch of the container, it will be rendered in case of a 404, but it would be sitting inside the container of course.
What would be the way to completely separate it from the container?


text:
Q: Триггер MySQL AFTER UPDATE срабатывает при вставке записи в таблицу Почему AFTER UPDATE триггер срабатывает при вставке новой записи в таблицу?
DELIMITER $$
CREATE TRIGGER `afterStatusChanged` AFTER UPDATE ON `orders` FOR EACH ROW BEGIN
DECLARE notify_status INT;
SELECT user.notify_status INTO notify_status FROM user WHERE user.user_id = NEW.user_id AND user.notify = '1';
IF notify_status > 0 THEN
BEGIN
   INSERT INTO notifications (notify_dateDelivered, notify_title, notify_body, notify_userID) VALUES (NOW(), '', CONCAT('Ваш статус: ', NEW.order_status), NEW.user_id);
  END;
  END IF;
END
$$
DELIMITER ;

Запрос:
INSERT INTO orders (user_id, order_date, order_status, order_subj, order_cost) VALUES ('$user_id', NOW(), 'В обработке', '$order_subj', '$order_cost')


text:
Q: how to add bunch of data into linked list Basically, I just tried to learn linked lists but I can't seem to understand how to insert a bunch of data from different variables into it. Does it work as an array/ ArrayList? Before we end the loop we are supposed to store the data right, but how??
Let say I have variables ( name, age, phonenum).
'''
    char stop='Y';

    while(stop!='N'){

    System.out.println("\nEnter your name : ");
    int name= input.nextLine();
    System.out.println("\nEnter your age: ");
    int age= input.nextInt();
    System.out.println("\nEnter your phone number: ");
    int phonenum= input.nextLine();

    System.out.println("Enter 'Y' to continue, 'N' to Stop: ");
    stop = sc.nextLine().charAt(0);

}
'''

A: First, change your code to use appropriate types. Name and phone should be of type String, not int.
Define a class to hold your fields. Records are an easy way to do that.
record Person ( String name , int age , String phone ) {}

Declare your list to hold objects of that class.
List< Person > list = new LinkedList<>() ;

Instantiate some Person objects, and add to list.
list.add( New Person( "Alice" , 29 , "477.555.1234" ) ) ;

In the line above, I hard-coded some example data. In your own code, you will be passing to the constructor the variables you populated by interacting with the user.
list.add( New Person( name , age , phonenum ) ) ;

A: Try this
Possibility : 1
import java.util.*;

public class Naddy {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        char stop = 'Y';

        LinkedList<Object> list = new LinkedList<Object>();

        while (stop != 'N') {

            System.out.println("\nEnter your name : ");
            String name = input.nextLine();
            System.out.println("\nEnter your age: ");
            int age = input.nextInt();
            System.out.println("\nEnter your phone number: ");
            long phonenum = input.nextLong();

            list.add(name);
            list.add(age);
            list.add(phonenum);
            System.out.println("Enter 'Y' to continue, 'N' to Stop: ");
            input.nextLine();
            stop = input.nextLine().charAt(0);
        }

        System.out.println(list);
    }
}

possibility : 2
import java.util.*;

public class Naddy {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        char stop = 'Y';

        LinkedList<User> list = new LinkedList<User>();

        while (stop != 'N') {

            System.out.println("\nEnter your name : ");
            String name = input.nextLine();
            System.out.println("\nEnter your age: ");
            int age = input.nextInt();
            System.out.println("\nEnter your phone number: ");
            long phonenum = input.nextLong();

            list.add(new User(name, age, phonenum));
            System.out.println("Enter 'Y' to continue, 'N' to Stop: ");
            input.nextLine();
            stop = input.nextLine().charAt(0);
        }

        System.out.println(list);
    }
}

class User {
    private String name;
    private int age;
    private long phonenum;

    public User() {
    }

    public User(String name, int age, long phonenum) {
        this.name = name;
        this.age = age;
        this.phonenum = phonenum;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public long getPhonenum() {
        return phonenum;
    }

    public void setPhonenum(long phonenum) {
        this.phonenum = phonenum;
    }

    @Override
    public String toString() {
        return "User [age=" + age + ", name=" + name + ", phonenum=" + phonenum + "]";
    }

}

A: You can create an object which has name, age and phenomenon then create an insert method which you call in your while loop.
In psuedo code it would look something like this:
public class Data {
    String name;
    int age;
    int phenomenon;
    //constructor
    //getters & setters
}

This class above will hold contain the user input. You can gather all the user input and store it in an array and perform the insert with array of data instead of inserting one object at a time
public void InsertData(LinkedList<Data> list, Arraylist<Data> input) {
  for(Data d: input){
   list.add(d);
  }
}

You can read up on linkedlists a bit more here to understand how exactly linkedlists work and implement your own from scratch: https://www.geeksforgeeks.org/implementing-a-linked-list-in-java-using-class/


text:
Q: Stability of a dipole magnet undergoing eddy current braking in a cylindrical tube Consider a cylindrical dipole magnet with strength $B$ undergoing eddy current braking in a conductive cylindrical tube with the axis of the magnet aligned with the axis of the tube.
The magnet feels a retarding force $F_{eddy} =\mathcal{V}vB^2σ$
The arrangement is in equilibrium (by symmetry) in all directions apart from along the axis. But is it a stable equilibrium in the off-axis directions?
That is, if you knock the magnet sideways by a small amount, is there a restoring force? If you turn the magnet slightly off the axis, is there a restoring couple?
Bonus question: could it be made stable by mechanically attaching some other magnets to the moving magnet?  (the goal is to make it stable without significantly reducing the braking force)


text:
Q: Heroku development environment + git pain I've read the docs on Heroku and managing multiple environments and I have a staging environment, and production environment on heroku.
However what's jamming me up is every time I want to deploy my code to my Heroku staging server, it makes a new commit.
Now my git repo is a mess. 'Typo' is the last 20 commit messages.
Is there a better workflow to reduce the amount of git commits? How have others kept their repos clean?

A: If you have a local repo, you can commit to THAT (which you should be doing). Only once you're done editing files on your LOCAL REPO, then you can PUSH to your staging repo.
Your staging repo will also have the same commits as your local repo.
From your staging repo, you can then either PUSH to your production, or from your production, PULL from your staging.
Please let me know if I've misunderstood your question, however.

A: If you're constantly committing typos all in a row and not actual features, you can simply amend the previous commit so you they are fewer/sparse. The only caveat is that you'll have to force push to heroku as changing the commit history can be destructive.
git commit --amend
git push -f heroku master


text:
Q: Why is DefaultOverloadAttribute required in WinRT? I recently had a WinRT class definition with methods like this:
public void Foo(string x){}
public void Foo(CustomClass x){}

The compiler threw an error though that

The 1-parameter overloads of Earlz.FooBar must have exactly one method specified as the default overload by decorating it with Windows.Foundation.Metadata.DefaultOverloadAttribute.

What kind of implications does this attribtue have? I'm unfamiliar with how WinRT projections work, but what I'm writing will eventually be a publicly usable API. So, I want to make sure that I'm not doing something that will cause pain to people who use the API. Should I rename my Foo method to FooCustom or some such, or is using DefaultOverload on the more commonly used function the way to go?
Also, I tried looking up what this attribute does and why it's required, but MSDN was short on details as usual and just gave single sentence description "Indicates that a method is the default overload method"
I assume the primary reason for this attribute is because Javascript only supports overloading on parameter count, not parameter type. However, how would a Javascript app access the non-default WinRT methods with type overloads?

A: As Jesse Jiang described in this thread:

JavaScript has limited ability to differentiate overloaded methods. Therefore, you need to change the function name, or setting the Windows::Foundation::Metadata::DefaultOverloadAttribute to set the default overload function.


text:
Q: Degree of composition Supose that $X\stackrel{f}{\to} Y \stackrel{g}{\to} Z$ are given, $f,g$ smooth and $X,Y,Z$ compact, oriented manifolds. Prove that $$\textrm{deg}(f\circ g) = \textrm{deg}(f)\textrm{deg}(g)$$
where $\textrm{deg}(f)=I(f,{z})$ for any $y\in Y$.
I say this on the answer by @Jared at The degree of antipodal map. and this is in fact an exercise of Guillemin-Pollack (chap.3 sec.3  number 10). I have no idea where start from. Any thoughts?

A: Let $z\in Z$ a regular value of the composite. Then
$$\deg(g\circ f)=\sum_{x \in (g\circ f)^{-1}(z)}\pm 1$$
according whit the orientatión of the derivative $T_xX→T_zZ$. Let's write
$$\deg(g\circ f)=\sum_{x \in (g\circ f)^{-1}(z)}\pm 1=\sum_{y \in g^{-1}(z)}\sum_{x \in f^{-1}(y)}\pm 1=\sum_{y \in g^{-1}(z)}\pm 1\sum_{x \in f^{-1}(y)}\pm 1=\deg(g)\deg(f).$$


text:
Q: Show lowercase url in .htaccess with uppercase file names In my .htaccess file, I have this code:
RewriteMap tolowercase int:tolower
RewriteRule ^(.*)$ ${tolowercase:$1} [R=301,L]

From: htaccess Uppercase URL to lowercase
This change the url from uppercase to lowercase and works fine for me.
All I want now is that I can keep my filenames in uppercase, but my server opens the files (with capitals in the names) and shows a url without capitals.
I searched for a solution via the internet and this platform, among others, but I ended up on pages that explain how you can convert a url to a url without capital letters. Now I want this too, but he has to open the files with capital letters in the file name.

A: So basically you want to open URL without capital letters and so it would work with capital letter filenames? Logically it's impossible. File names in most of operating systems are case sensitive. When you ask for text.txt, it could refer to Text.txt or TEXT.txt or TEXT.TXT or text.TXT or different combinations... how the server would decide which one? Logically the thing that you are trying to do doesn't make any sense and won't work. URL rewriting is not only about what is being shown in URL bar, it affects the request itself.
The solution would be to change the URL in address bar with JavaScript (after processing the request by server), but then imagine that a person would want to refresh the site - would wrap up to the same problem as above.


text:
Q: Graphql using redux state as well as Apollo I have a server side rendered app and want data to be accessible on the first render. If a user navigates to the next page, I want to use the graphQL library Apollo to fetch the new content.
When a page is requested, the server sets the initialState key curPage with the data of the page that is requested. For example a user requests http://example.com/about. I get the page data for /about from my DB, set the initialState key curPage to that data from the DB.
So my initialState might look something like this:
{
  "curPage": {
    "id": 5,
    "title": "About",
    "slug": "about",
    "path": "/about",
    "template": "about",
    "published": "2017-07-10 02:02:30",
    "image": null,
    "seo": {
      "title": null,
      "description": null,
      "image": null,
      "fbAdmins": null,
      "gtm": null,
      "schema": ""
    },
    "sections": [
      {
        "type": "masthead",
        "mh_title": "",
        "video": false,
        "image": [

        ],
        "showCta": false,
        "cta": [

        ]
      },
      {
        "type": "text_image",
        "alignment": "left",
        "text_image": [
          {
            "type": "text",
            "title": "",
            "content": "",
            "call_to_action": false,
            "cta": [

            ]
          }
        ]
      }
    ]
  },
}

So if that curPage data is available, I want to use that, otherwise I want to fetch from graphQL.
My page component currently only fetches from graphQL and doesn't check if the data is available in initialState.
import React, { Component } from 'react'
import { graphql, gql } from 'react-apollo';

import './about.css'

class About extends Component {
  render() {
    return (

About Page

    )
  }
}

const mapQueryToProps = ({data: { findResource }, ownProps}) =>
  ({ curPage: findResource ? findResource[0] : null })

const MY_QUERY = gql`
  query {
    findResource(filter: {resource: "pages", slug: "about"}) {
        id
        title
        slug
        path
        sections
    }
  }`

 export default graphql(MY_QUERY, { props: mapQueryToProps })(About)

Is there a way through Apollo graphQL that I can do something like react-redux's connect() does but if it isn't available then fetch from graphQL?
I'm guessing I need to use connect() but then in my componentDidMount() check if the data is set and if it's not retrieve it?

A: You need to transform the curData into the Apollo graphql format and use it to initialize the Apollo section of the store.
You can read about the specific here: http://dev.apollodata.com/react/server-side-rendering.html#store-rehydration
Note that Apollo actually supports server side rendering, so if you use Apollo Graphql on the server, it will actually generate the state that you need to send to the client to use to initialize the client-side Redux store


text:
Q: How to nest each statement to get objects ab.c.click = function() {};
ab.c.focus = function() {};
ab.d.c = function() {};
ab.g.d = function() {};

data.c = $('.element');
data.g = $('.element');

I want to do an each statement that does the following:
do a for each on the ab
EXAMPLE: get the first part (c) and the second part (click)
using the (c) get the corresponding element from data (data.c)
$(document).on( (click), (elementfromdata), function() {});

I tried this but it did not work:
     $.each(ab, function(x){
             $.each(x, function(g){
             var final = x + g;
         });
      });

please ask if more info needed.

A: Is something like this what you're looking for?
for(coll in ab){ //coll corresponds to "c","d" etcetera
    if(ab.hasOwnProperty(coll)){

        for(handler in ab[coll]){ //handler corresponds to "click","focus" etcetera
            if(ab[coll].hasOwnProperty(handler)){

                $(document).on(handler, data[coll], ab[coll][handler]);

            }
        }

    }
}

A: You need to use the magical this variable.
$('.element').each(function() {
    console.log($(this).text());
});


text:
Q: Check if token works with endpoint - Node/Express Unsure how to go about checking the auth token and how it has been set up. First, I'm calling a token endpoint on login on the front end - api/token - the response I get back is the token I use on the rest of the endpoints for this app as a header on the front end. The call - api/token - is making a call to another server side project in a different language. Anyways, I get back the token from this call. How do I check if the token is correct on the node side on each call?
Here's simple middleware I've added but it's not checking to see if the token that was given is the correct one. Is that normal to even check if the token is correct? Or just to check if a token is present?
app.use((req, res, next) => {
        if(!req.headers.authorization){
            return res.status(403).json({ error: 'No credentials sent!'});
        }
        next();
    })

Thanks!

A:
Is that normal to even check if the token is correct? Or just to check if a token is present?

You need to check for both the "presence" and "validity" of the token
If you check only for the presence, you might allow invalid tokens that you haven't issued from the
server
app.use((req, res, next) => {
  if (!req.headers.authorization) {
    // this will allow if the authorizaton is set to '1' or 'some random string'
    return res.status(403).json({
      error: 'No credentials sent!'
    });
  }

  next();
});

app.get('/', (req, res) => {
  return res.status(200).send({
    result: 'hello world'
  });
});

Here, clearly 123 is an invalid token. But still the application allows it

curl -H 'Authorization:123' http://localhost:3000

Response

{"result":"hello world"}

We can fix this by validating the token received using a jwt-simple or any similar packages
app.use((req, res, next) => {
  let jwt = require('jwt-simple');
  if (!req.headers.authorization) {
    return res.status(403).json({
      error: 'No credentials sent!'
    });
  }

  try {
    let token = req.headers.authorization.split(' ')[1]
    var decoded = jwt.decode(token, 'your secret here');
  } catch (err) {
    console.log('err ', err.stack);
    return res.status(403).json({
      error: 'invalid token'
    });
  }

  next();
});

app.get('/', (req, res) => {
  return res.status(200).send({
    result: 'hello world'
  });
});

Response

{"error":"invalid token"}


text:
Q: What is phantom reference in java There are four type of references in Java: Strong, Soft, Weak, and phantom. Kindly elaborate where and how Java exactly use phantom reference.
EDIT :
I did read the javaDoc, as assylias posted below. the section says an object is phantom rechable if it has been finalized and some phantom refernce refers to it. I dint quite get that statement.
What is the use of phantom and in which cases shall we use it?

A: How each type of reference works is described in the java.lang.ref package javadoc:

Going from strongest to weakest, the different levels of reachability reflect the life cycle of an object. They are operationally defined as follows:

*

*An object is strongly reachable if it can be reached by some thread without traversing any reference objects. A newly-created object is strongly reachable by the thread that created it.

*An object is softly reachable if it is not strongly reachable but can be reached by traversing a soft reference.

*An object is weakly reachable if it is neither strongly nor softly reachable but can be reached by traversing a weak reference. When the weak references to a weakly-reachable object are cleared, the object becomes eligible for finalization.

*An object is phantom reachable if it is neither strongly, softly, nor weakly reachable, it has been finalized, and some phantom reference refers to it.

*Finally, an object is unreachable, and therefore eligible for reclamation, when it is not reachable in any of the above ways.

There are a few posts on Stack OVerflow that give examples of how and when you might need a PhantomReference:

*

*Have you ever used Phantom reference in any project?

*When to use phantom references in Java?


text:
Q: Windows Workflow Foundation or IoC container + Dependency Injection? I am trying to figure out the internals of the windows workflow foundation. So, we have some software components and we intertwine them in the form of a workflow be it a condition based sequential workflow or a state machine workflow. Now, I am thinking (I may be wrong here) that doesnt the same apply to IoC + Dependency Injection (via Unity or Spring.net). When to use what?? Am I even thinking right??

A: Not quite sure I understand the question but I will give it a try anyway.
WF doesn't use an IOC container. It uses the ServiceLocator pattern where you add dependencies to the workflow runtime, the service locator, and workflow activities and retrieve these services from the workflow runtime.
A ServiceLocator and IOC pattern are similar and have the same purpose in decoupling dependencies. The apporach is different though in an IOC container pushing dependencies in while a ServiceLocator is used to pull dependencies out.
Hope this answers your question and if not I would try and rephrase the original question.

A: I was grappling with how to use components provided and serviced by my IOC container from workflows, too.  As the other answer states, workflow instances want to use service-locator to pull services from the runtime instead of having the dependencies injected.
An easy way to bridge the gap is to take the dependencies out of your IOC container at the time you are setting up the WF runtime, and then use AddService to put them into the runtime.  Your workflows can override OnActivityExecutionContextLoad, and use the GetService method on the service provider to fish them back out of the runtime and plop them into [NonSerialized] public properties on the workflow.  You then have access to the services from code activities, etc.
You might also be able to rig up a runtime service that injects dependencies when the workflow instances are activiated.


text:
Q: Want to redirect URL and change slug to url parameter I am stuck with a mod rewriting on Apache htaccess.
my URL looks like this :
http://localhost/Ac5GRnXW

I want it to redirect like this:
http://localhost/redirect.php?id=Ac5GRnXW

I am using the following code :
Options +FollowSymLinks
RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^(\w+)$ ./redirect.php?id=$1

Please help


text:
Q: Convert matrix to row/data pairs I have a table of transactional data, with item numbers in each cell. For each non-missing entry, I would like to output an (ID, ITEM) pair, where ID is the row number and ITEM is the data. For instance, consider the following input table:
(dat <- matrix(c(25, 39, 35, 39, 15, 26, 7, 227, 52, 120, 249, 422, 229, 104, 185, 390, 164, 124, 674, 449, 262, 143, 214, NA, 240, 205, 712, 704, 283, 320, 350, NA, 274, 401, 733, 825, 294, 569, 529, NA, 328, 581, 759, 857, 352, 620, 658, NA, 368, 704, 854, 895, 381, 798, 682, NA, 448, 814, 950, 937, 708, NA, 782, NA, 538, 825, NA, 954, 738, NA, 809, NA, 561, 834, NA, 964, 766, NA, 849, NA), nrow=8))
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,]   25   52  164  240  274  328  368  448  538   561
# [2,]   39  120  124  205  401  581  704  814  825   834
# [3,]   35  249  674  712  733  759  854  950   NA    NA
# [4,]   39  422  449  704  825  857  895  937  954   964
# [5,]   15  229  262  283  294  352  381  708  738   766
# [6,]   26  104  143  320  569  620  798   NA   NA    NA
# [7,]    7  185  214  350  529  658  682  782  809   849
# [8,]  227  390   NA   NA   NA   NA   NA   NA   NA    NA

The eighth row would be converted to the following:
data.frame(ID=c(8, 8), ITEM=c(227, 390))
#   ID ITEM
# 1  8  227
# 2  8  390

I would like each row to be converted in this way.

A: You could generate a table of all pairs (including the pairs with missing item numbers) and then use complete.cases to limit to just the pairs with non-missing data:
out <- data.frame(ID=c(row(dat)), ITEM=c(dat))
out <- out[complete.cases(out),]
head(out)
#   ID ITEM
# 1  1   25
# 2  2   39
# 3  3   35
# 4  4   39
# 5  5   15
# 6  6   26

c(row(dat)) returns a vector indicating the row number of each piece of data in your input matrix, while c(dat) is a vector with the matrix data.


text:
Q: Bulma - How to put image and text inline I want text on right and image on left and vice-versa with vertically centered both.
It should look like as follows

Image

A: Structure

In total
(Change CSS according to your needs)

.myBg {
  background-color: #273238;
  color: white;
  border: 1px solid white;
}

.myHero .hr {
  display: inline-block;
  width: 100px;
  height: 15px;
  background: white;
  border-radius: 20px;
  margin-bottom: 15px;
}

.myHero h1 {
  font-size: 50px
}

.myHero.hero-right {
  padding-right: 100px;
  text-align: right;
}

.myHero.hero-left {
  padding-left: 100px;
}

@media(max-width: 768px) {
  .myHero {
    padding: 100px 50px !important;
    //text-align: left !important;
  }
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.1/css/bulma.min.css">

BOOST

This is the cooles thing.

I am gonna do in my entire life. Awesome!

Achievements are good as heaven. I want it soon.

BOOST

This is the cooles thing.

I am gonna do in my entire life. Awesome!

Achievements are good as heaven. I want it soon.


text:
Q: Any way to host PHP locally inside a .net executable file I'd like to basically turn a php website with database into a .net executable file. I'd like everything to be internal. Is this possible or will I have to rewrite the entire project into C#?

A: You have to (should) rewrite the project in C#.
Of course, it is technically possible to integrate everything you need into one executable .NET file, but this solution will make use of lots of unsupported stuff, temp files or PInvoke calls, which you do not want to have in a managed environment.


text:
Q: Force python installation into virtualenv I've got large python module that is particularly complex in terms of dependencies and on the Raspberry Pi it now conflicts with several core modules (pillow, pyserial, and a few others) which can't easily be overwritten. In general, installing into a virtualenv would be the best thing. But I've found that's a little beyond some users and as most users will simply use the CLI command that gets installed instead of the module API, I'd like to make things automatic. Is it possible, in any way, with setuptools to do the following?

*

*Automatically install virtualenv if not available

*Install module into virtualenv

*Install require dependencies into virtualenv

*Setup CLI command to run automatically from that virtualenv without first activating it

A: For this I've created two scripts where are in a script directory.
Create venv:
#!/bin/bash
cd ..
virtualenv -p python3 --no-site-packages venv
cd script
sh updateEnv.sh

Update venv (based on a requirements.txt file):
#!/bin/bash
cd ..
echo "activating env"
. venv/bin/activate
pip install --upgrade -r requirements/requirements.txt

You just need to add a check if the venv folder is already created.
All you need is to install virtualenv.


text:
Q: Extracting data from csv files using powershell sort and group My goal is to output each Group object individually but in order of Start_Order. From Count you can see that there are multiple objects under the same Server_Name.
My code right now is packaging everything together.
Output should be :
Server_Name             Service_Name
USOHCLIENT901             DISP01   #organized by Start_Order, Start_Order =1
                          DISP03   #Start_Order =2
                          DISP05   #Start_Order =3

$Sourcefile = "C:\Users\StartF.csv"

$StartProperties  = (Import-Csv $Sourcefile)  | select Ava_Zone,Environment,Server_Name,
                                                Purpose,Service_Name, Start_Order, Start_Flag,
                                                Start_Wait
# $StartProperties

$StartProperties | Group-Object -Property Server_Name | Sort-Object -Property {$_Start_Order}

Count Name                      Group
----- ----                      -----
    1 USOHCLIENT901             {@{Ava_Zone=us-east-2a; Environment=DEV; Ser...
   13 DEFRCLIENT801             {@{Ava_Zone=de-central-1a; Environment=TEST;...
   12 APSGCOGAPP803             {@{Ava_Zone=ap-southeast-1a; Environment=TES...
   12 APSGCOGAPP802             {@{Ava_Zone=ap-southeast-1b; Environment=TES...
   12 APSGCOGAPP801             {@{Ava_Zone=ap-southeast-1a; Environment=TES...
    1 APSGCLIENT801             {@{Ava_Zone=ap-southeast-1a; Environment=TES...
   12 USOHCOGAPP803             {@{Ava_Zone=us-east-2a; Environment=TEST; Se...
   12 USOHCOGAPP802             {@{Ava_Zone=us-east-2a; Environment=TEST; Se...
   12 USOHCOGAPP801             {@{Ava_Zone=us-east-2a; Environment=TEST; Se...
    1 USOHCLIENT801             {@{Ava_Zone=us-east-2a; Environment=TEST; Se...
    1                           {@{Ava_Zone=--; Environment=; Server_Name=; ...
   12 DEFRCLIENT903             {@{Ava_Zone=de-central-1a; Environment=DEV; ...
   12 DEFRCOGAPP902             {@{Ava_Zone=de-central-1b; Environment=DEV; ...
   11 DEFRCOGAPP901             {@{Ava_Zone=de-central-1a; Environment=DEV; ...
    2 DEFRCLIENT901             {@{Ava_Zone=de-central-1a; Environment=DEV; ...
   12 APSGCOGAPP903             {@{Ava_Zone=ap-southeast-1a; Environment=DEV...
   12 APSGCOGAPP902             {@{Ava_Zone=ap-southeast-1b; Environment=DEV...
   12 APSGCOGAPP901             {@{Ava_Zone=ap-southeast-1a; Environment=DEV...
    1 APSGCLIENT901             {@{Ava_Zone=ap-southeast-1a; Environment=DEV...
   12 USOHCOGAPP903             {@{Ava_Zone=us-east-2a; Environment=DEV; Ser...
   12 USOHCOGAPP902             {@{Ava_Zone=us-east-2a; Environment=DEV; Ser...
   12 USOHCOGAPP901             {@{Ava_Zone=us-east-2a; Environment=DEV; Ser...
   12 DEFRCOGAPP802             {@{Ava_Zone=de-central-1b; Environment=TEST;...
   12 DEFRCOGAPP803             {@{Ava_Zone=de-central-1a; Environment=TEST;...

PowerShell Output

A: Take a look at the code below. It will do what you are looking for but for all the running processes. After Group-Object you could directly select your needed properties with Select-Object and a custom created property @{Name = 'Id'; Expression = {($_.Group.Id | Sort-Object) -join "rn"}} that will collect the data from the Group-Object group and sort it.
$Processes = Get-Process
$Processes | Group-Object -Property 'ProcessName' | Select-Object -Property 'Name', @{Name = 'Id'; Expression = {($_.Group.Id | Sort-Object) -join "`r`n"}} | Format-List


text:
Q: How to get this recursive async/await issue right? I have a recursive method that visits every node in a tree hierarchy and triggers a callback for every node, like (code below is not tested and an example):
void Visit(Node node, Func<Node, int> callback, CancellationToken ct)
{
  if(ct.IsCancellationRequested)
  {
    return;
  }

  var processedNode = DoSomeProcessing(node);

  int result = callback(processedNode);

  // Do something important with the returned int.
  ...

  // Recursion.
  foreach(var childNode in node.Children)
  {
    Visit(childNode, callback);
  }
}

The method above is called from an async method that passes the callback on. As it is long running, I wrap the call into a Task.Run():
async Task ProcessAsync(Func<Node, int> callback)
{
  var rootNode = await someWebService.GetNodes();
  await Task.Run( () => Visit(rootNode, callback) );
}

Now here's the issue: some async code is awaiting ProcessAsync():
...
await ProcessAsync( node => {
  return DoSomethingWithTheNode();
});
...

This works. However, no we're refactoring and DoSomethingWithTheNode becomes async: DoSomethingWithTheNodeAsync. The result won't build because the delegate types don't match. I would have to return Task<int> instead of int:
...

    await ProcessAsync( async node => {
      return await DoSomethingWithTheNodeAsync();
    });
    ...

If I change the delegate's signature to Func<Node, Task<int>> I will have to make my Visit method async which is somehow weird - it is already running as a Task and I don't feel very good about using a recursive async method that gets an async callback passed in. Can't explain, but it looks wrong.
Question:

*

*Is the approach just not suitable for an async world?

*How to get this done right?

*I originally did not want to use a callback method but an IEnumerable<Node>. However this seems to be impossible with async methods.

*Is this question maybe more adequate for codereview.stackexchange.com?

A: After re-factoring, your new async Visit might look like this:
async Task Visit(Node node, Func<Node, Task<int>> callback, CancellationToken ct)
{
  if(ct.IsCancellationRequested)
  {
    return;
  }

  var processedNode = DoSomeProcessing(node);

  int result = await callback(processedNode).ConfigureAwait(false);

  // Do something important with the returned int.
  ...

  // Recursion.
  foreach(var childNode in node.Children)
  {
    await Visit(childNode, callback, token);
  }
}

Then ProcessAsync would look like this:
async Task ProcessAsync(Func<Node, Task<int>> callback, token)
{
  var rootNode = await someWebService.GetNodes();
  await Visit(rootNode, callback, token);
}

And it can simply be called like this:
await ProcessAsync(DoSomethingWithTheNodeAsync, token);

Because you are introducing asynchrony into your callback, most likely you no longer need to offload ProcessAsync to a separate thread. Below I'll try to explain why.
Let's consider for a minute your DoSomethingWithTheNodeAsync looks like this:
async Task<int> DoSomethingWithTheNodeAsync(Node node)
{
    Debug.Print(node.ToString());
    await Task.Delay(10); // simulate an IO-bound operation
    return 42;
}

Inside Visit, the execution after await callback(processedNode).ConfigureAwait(false) will continue on a random pool thread (the thread which happened to serve the completion of the asynchronous Task.Delay operation). So, the UI thread will no longer be blocked.
The same is true for any other pure asynchronous API which you may be using inside DoSomethingWithTheNodeAsync (and which was the original reason for re-factoring, I believe).
Now, my only concern would be this:
var processedNode = DoSomeProcessing(node);

Once you've called ProcessAsync(DoSomethingWithTheNodeAsync), the very first invocation of the above DoSomeProcessing will happen on the same thread as the original call. If that's a UI thread, DoSomeProcessing might block the UI for one time, for as as long as the processing goes inside it.
If that's a problem, then wherever you invoke ProcessAsync from the UI thread, wrap it with Task.Run, e.g:
void async button_click(object s, EventArgs e)
{
    await Task.Run(() => ProcessAsync(DoSomethingWithTheNodeAsync));
}

Note, we still don't use Task.Run anywhere inside ProcessAsync, so there will be no redundant thread switching during the recursive traversal of the tree.
Also note, you do not need to add another async/await to the lambda like below:
await Task.Run(async () => await ProcessAsync(DoSomethingWithTheNodeAsync));

That would add some redundant compiler-generated state machine code. Task.Run has an override to deal with a lambda returning Task<T> or Task, which unwraps the nested task with Task.Unwrap. More about this here.
Finally, if something inside DoSomeProcessing or DoSomethingWithTheNodeAsync updates the UI, it has to been done on the UI thread. With Monotouch, it can be done via SynchronizationContext.Post/Send of the UI thread's SynchronizationContext.

A: If you want to use async to unblock the calling thread, the entire call tree becomes infected up to the point where you need to release the thread. This is the nature of async, and it is a major reason why you should carefully think whether you want to bring it into a codebase or not.
In that sense, Visit should be async because something it calls is async. Don't fall into the trap of implementing the well-known async-over-sync anti-pattern (or sync-over-async).
Especially, this is likely to be wrong:
await Task.Run(() => Visit(rootNode, callback) );

This is async-over-sync. Make Visit async and treat Task.Run suspiciously.
Regarding your sub-question about IEnumerable<Node>: I'm unclear on what exactly you want to accomplish. Depending on that, you could use a Task<IEnumerable<Node>> or an IAsyncEnumerable<Node>. Depends on the use case.

... I will have to make my Visit method async which is somehow weird - it is already running as a Task and I don't feel very good about using a recursive async method that gets an async callback passed in.

You should feel bad about using Task.Run. That's the mistake, not making Visit async.


text:
Q: Separating std::threads by condtions Program to invoke threads on the priority basis
I am trying to run threads as priority 1 and other priority threads(except 1),
In here thread t2 is of priority 2  the 3 threads t1,t2, and t3 are in wait . and thread t4 goes and calls signals with priority 2. //- I want it to invoke only threads with priority other than 1
The output of this program is
single notifyall
both notifyall
cv.wait(master);
priority1
cv1.wait(master);
priority2
cv.wait(master);
priority1
which is what I expected , I am looking for the eplanation of this behavious as I am of a view that notify_all() will notify all threads so all threads should get notify no the priority 1 threads or the other priority threads
#include <condition_variable>
#include <thread>
#include <chrono>
using namespace std;
std::condition_variable cv;
std::condition_variable cv1;
std::mutex cv_m;

void waits(int priority)
{
    std::unique_lock<std::mutex> master(cv_m);
        if(priority == 1){

            cv.wait(master);
            std::cout<<"cv.wait(master);"<<std::endl;
        }
        else {
         cv1.wait(master);
         std::cout<<"cv1.wait(master);"<<std::endl;
        }
        std::cout<<"priority"<<priority<<std::endl;
        master.unlock();
}

void signals(int priority)
{
    switch (priority){
            case 1:
                std::cout<<"both notifyall"<<std::endl;
                cv.notify_all();
                cv1.notify_all();
                break;

            case 2:
                std::cout<<"single notifyall"<<std::endl;
                cv1.notify_all();
                break;
        }
}

int main()
{
    std::thread t1(waits,1), t2(waits,2), t3(waits,1), t4(signals,2),t5(signals,1);
    t1.join();
    t2.join();
    t3.join();
    t4.join();
    t5.join();

}```


text:
Q: Spring boot micro services with pre-Authenticated filter using CSRF protection I am using SSO and preAuthenticated Filter in my micro services. Micro services are built using spring boot and are stateless in nature. How can I apply CSRF protection across all micro services using spring security. Please let me know if any solution is available to implement CSRF for this scenario.

A: You are probably looking for a proxy server. Take a look at Zuul and its security filters:
https://github.com/spring-cloud/spring-cloud-netflix/issues/796
https://github.com/spring-cloud/spring-cloud-security/issues/88


text:
Q: auto-login user when reopening app in Backand I have a simple Backand and Ionic app where I want users to log in once and no more from that point on, just like the Facebook app for example.
So once the user is logged in, I receive a token from Backand. From what I know, I assume I have to save that token in localStorage (which I'm doing, and works). But from that point on, I don't understand what I need to do to log the user back in when he revisits.
I have tried in my angular "run" method to look for an existing token in the localstorage, and if one exists, I paste it in my http headers. (the following function exists in the authentication service and is being called in the "run" method).
self.checkExistingUser = function() {
  if ($localStorage.user_token) {
    $http.defaults.headers.common.Authorization = $localStorage.user_token;
    Backand.user.getUserDetails()
        .then(function (response) {
            // Do stuff
        }
    console.log('Token found, logging in user');
  }
};

I assumed that the "getUserDetails()" call would interpret the Authorization header I had just added. But that's what I misunderstood; that's not how it works.
So my question is: how do I automatically log in the returning (existing) user with that token? I can't seem to find any function for that purpose in the Backand docs.
Thanks in advance!

A: Using Backend Vanilla SDK, this code:
backand.user.getUserDetails(false)
  .then(res => {
    console.log(res.data);
  })
  .catch(err => {
    console.log(err);
  });

will get the user details if he is authenticated, or null if not.
So you do not need to login the user again. The false makes sure that it checks it internally without contacting Backend. You should structure your app around it.

A: Your comment made me find the answer to my question, Kornatzky.
The problem was that I had included my appName, anonymousToken and signUpToken into the initialization (BackandProvider.init). Removing the anonymousToken and adding useAnonymousTokenByDefault:false solved the problem.
getUserDetails now returns my currently logged-in user instead of a Guest object. Thanks for your help!


text:
Q: An alternative to getElementsByTagName and pass information I've been looking to find an alternative to getElementsByTagName for something that requires a valid HTML format. I don't really want to use a form to pass the information. Any help is greatly appreciated.

<my-widget myId="3053" myOtherId="hello"></my-widget>


text:
Q: Excel VBA code to fetch data from website I've developed the code below in order to get some information from a webpage (Internal IT support) into excel including: ticket ID, description, content, person assigned, first reply and all the information possible in order to report them according to our KPIs, now i don't know much about coding especially VBA, the code below fetch one piece of information in every run so i couldn't get a list of all the tickets and their information.
Please help me with a method or code to get this done.
Cheers :)
Private sub report_data_click ()
Dim IE as InternetExplorer
Dim HTML as variant
set IE = createobject("internetexplorer.application")
IE.visible = false
ie.navigate "https://forum.fortinet.com"
while IE.busy
 do events
wend
while ie.readystate < 4
do events
wend
set HTML = ie.document
set elements as variant
set elements2 as variant
set elements3 as variant
set elements4 as variant
set elements = html.getelementsbyclassname ("contentlink")
for i=0 to elements.length - 1
sheet1.range ("A" & (9+1)) =elements(i).innertext
next i

set elements2 = html.getelementsbyclassname ("authorlink")
for i=0 to elements2.length - 1
sheet1.range ("A" & (9+1)) =elements2(i).innertext
next i

set elements3 = html.getelementsbyclassname ("performdateformat")
for i=0 to elements3.length - 1
sheet1.range ("A" & (9+1)) =elements3(i).innertext
next i

set elements4 = html.getelementsbyclassname ("Messagelink newpost")
for i=0 to elements4.length - 1
sheet1.range ("A" & (9+1)) =elements4(i).innertext
next i
IE.quit
set IE = Nothing
End sub

A: It seems you are from different language like vb.net because the way you have written the above script reminds me something of that sort. You just can't declare everything (specially Objects) as variant and Set them the way you have written. Try the below approach to get the data from every containter under class name newActiveList-item. I tried to create the script which should parse the three fields (mentioned in your script) from each container. If anything you wanna add, I think you can manage following the logic implemented below.
Private Sub ReportData()
    Const url As String = "https://forum.fortinet.com/"
    Dim IE As New InternetExplorer, HTML As HTMLDocument
    Dim post As Object, R&

    With IE
        .Visible = True
        .navigate url
        While .Busy = True Or .readyState < 4: DoEvents: Wend
        Set HTML = .document
    End With

    For Each post In HTML.getElementsByClassName("newActiveList-item")
        With post.getElementsByClassName("authorlink")
            If .Length Then R = R + 1: Cells(R, 1) = .Item(0).getAttribute("href")
        End With
        With post.getElementsByClassName("performdateformat")
            If .Length Then Cells(R, 2) = .Item(0).innerText
        End With
        With post.getElementsByClassName("messagelink")
            If .Length Then Cells(R, 3) = .Item(0).innerText
        End With
    Next post
    IE.Quit
End Sub

Reference to add to the library in order to execute the above script:
Microsoft Internet Controls
Microsoft HTML Object Library


text:
Q: Google Analytics real-time - keep alive i have a realtime platform when users are staying on pages for a long duration, i found that after 5 minutes (more or less) the GA realtime stop show them so i created timer that each 4 minutes send pageview and this way all users remain "connected" to GA.
I wonder if it's a good approach or it's can may produce un-accurate data on the reports later.
Is anyone experienced that?

A: Your terminology seems a little off - users do not become "disconnected" from Google Analytics, the difference between realtime reports and data from the reporting api is that the former shows only a subset of ad hoc computed dimensions and metrics whereas the reporting api shows, after some processing latency, the full set of metrics and dimensions, including stuff that required more processing time like session- and user scoped data.
Other than that your approach is fine. There is a limit on the number of API calls you are allowed to make - the documentation has an example on how to calculate your calls to stay within the limits, and Google suggests to implement some sort of serverside caching if you do need a lot of realtime dashboards.
But this is not going to affect the data quality of reports in any way. Realtime API is a read-only API, the worst thing that can happen is that you exceed your quota and get blocked for the rest of the day. So there is no way this would create "un-accurate data on the reports later".


text:
Q: Find Next Lower number based on other field in Access I have a table that has data like this:
MainID, MainNumber, MainType
1       250         Hours
2       500         Hours
3       1000        Hours
4       5000        Miles
5       20000       Miles

When I put the values in for the MainNumber and the MainType, I need to pull the next lower MainNumber for that MainType.
This is the code that I have:
SQL = "SELECT T2.MainID, Max([t2.MainNumber]) AS PreviousCycle"
SQL = SQL & " FROM tblMainType AS T1 LEFT JOIN tblMainType as T2 on T1.MainNumber > T2.MainNumber"
SQL = SQL & " WHERE T1.mainType = '" & mType & "' AND T1.MainNumber = " & MainNumber
SQL = SQL & " Group By T2.MainID;"

Oddly it works for hours but not miles? What is wrong with my code?

A: To find the next highest number I would take the sort the field in descending order and take TOP 1 value.
Sql = "SELECT TOP 1 tblMainType.MainID, tblMainType.MainNumber " & _
      "FROM tblMainType " & _
      "WHERE (((tblMainType.MainNumber)< " & mType & ") AND ((tblMainType.MainType)='" & MainNumber & "')) " & _
      "ORDER BY tblMainType.MainNumber DESC;"

A: I would expect a query like this:
SELECT TOP 1 MainID, MainNumber
FROM tblMainType
WHERE MainType = @MainType AND
      MainNumber >= @MainNumber
ORDER BY MainNumber DESC, MainId;

The @MainType and @MainNumber are the values you are inputting.


text:
Q: how get Count of array inside other array I want to get the count of second array by count() metod ,
if Apply count method to external array i got 2,
  But ie count($get_comment),i want internal array count ,
outer array has count 2
array (size=2)   0 =>
     array (size=2)
       0 =>
         object(stdClass)[12]
          public 'comment_ID' => string '23' (length=2)
        public 'comment_post_ID' => string '22' (length=2)
          public 'comment_author_IP' => string '::1' (length=3)

       1 =>
         object(stdClass)[13]
          public 'comment_ID' => string '20' (length=2)
          public 'comment_post_ID' => string '22' (length=2)
          public 'comment_author_IP' => string '::1' (length=3)

  1 =>
     array (size=2)
       0 =>
        object(stdClass)[11]
           public 'comment_ID' => string '22' (length=2)
           public 'comment_post_ID' => string '23' (length=2)
           public 'comment_author_IP' => string '::1' (length=3)

      1 =>
        object(stdClass)[15]
          public 'comment_ID' => string '21' (length=2)
          public 'comment_post_ID' => string '23' (length=2)
          public 'comment_author_IP' => string '::1' (length=3)

A: Something along theese lines should work
foreach($array as $key -> $getComment){
 echo count($getComment);
}

This loops over the parent array where $array is the outer level, and echo's the count of each item inside the array (The internal array).
If you want to save this count somewhere you could push the count onto another array.
$arrayCounter = array();
foreach($array as $key -> $getComment){
   $arrayCounter[] = count($getComment);
}


text:
Q: angular - access the element from ng-disabled I want to pass this (the element) - a button to my controller by ng-disable.
here is my HTML:

<button type ="button" class = "btn btn-default" ng-click= "open()" ng-disabled = "checkRowId(this)">
</button>

And my controller :
$scope.checkRowId = function(btn){
   console.log(btn); //undefined
}

The log shoes undefined, is there a way to pass a element like a button via ng-disabled?

A: There is no direct way to pass element via ng-disabled. You can create one directive say "disabled-ele" and put your element disabling logic there.
Example Code:
.directive('disabledEle', function() {
                    return {
                        restrict: 'EA',
                        link: function(scope, element, attrs) {
                            if(attrs.disabledEle.toLowerCase() === 'true') {
                                element.attr('disabled', 'disabled');
                            } else {
                                element.removeAttr('disabled');
                            }
                        }
                    }
                });

<button type ="button" value="Click" class = "btn btn-default" disabled-ele="false">Click
                    </button>


text:
Q: UIWebView won't hide keyboard I need to hide the keyboard as soon as a page starts loading. I've tried all commonly suggested approaches discussed e.g. here
Following approaches have no effect on the keyboard
[webView endEditing:YES];
[webView stringByEvaluatingJavaScriptFromString:@"document.activeElement.blur();"];
[webView stringByEvaluatingJavaScriptFromString:@"window.blur();"];

I invoke them in -webView:shouldStartLoadWithRequest:navigationType:
What am I doing wrong? Any suggestions?

A: Thanks for your answer. i write this methods
- (BOOL)disablesAutomaticKeyboardDismissal {
  return NO;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [webView endEditing:YES];
}

works for me

A: The problem was that UIViewController's returned YES here for UIModalPresentationFormSheet.
- (BOOL)disablesAutomaticKeyboardDismissal {
  return NO;
}

Have a look at that answer.

A: try
webView.delegate = self;

and inside the -webViewDidFinishLoad: delegate method
[webView resignFirstResponder];


text:
Q: type object argument after ** must be a mapping, not str I wanna get json from the site and change it into python object.
I wrote this code but it shows me this error:
    ----- line 25, in <module>
    meme_list.append(meme(**u))
TypeError: type object argument after ** must be a mapping, not str

here is my code:
import requests
import json

url = 'https://api.imgflip.com/get_memes'
headers = {'Accept': 'application/json'}
response = requests.get(url, headers=headers)
with open('meme_imgflip.json', 'wb') as outf:
    outf.write(response.content)

class meme:
    def __init__(self, name, url, id):
        self.name = name
        self.url = url
        self.id = id
    @staticmethod
    def from_json(meme_string):
        return meme(**json_dict)
    def __repr__(self):
        return f'<meme {self.id}>'

meme_list = []
with open('meme_imgflip.json', 'r') as json_file:
    meme_data = json.loads(json_file.read())
    for u in meme_data:
        meme_list.append(meme(**u))
print (meme_list)

A: The API you're calling returns a dictionary, not a list. The list of memes is in meme_data['data']['memes']. So the loop should be:
for u in meme_data['data']['memes']:
    meme_list.append(meme(**u))

A: meme_data contains a dict, so u gets assigned the keys to that dict, which are strings.  It isn't clear what you want instead.


text:
Q: How to create a service (windows) from a java application WITHOUT a wrapper? I've seen a lot of people asking how to make a java application a service and the answer is always a wrapper (i.e. JSW).
I'd like to know what makes a java application turn into a service and how to implement it without the wrapper.
I don't mean to re-invent the wheel, it just makes me feel "weaker" to not handle the concepts behind this issue.

A: Windows is not Lunix. Linux service is just a shell script that implements options like start, stop, restart. Windows service is a native component that implements well defined interface. JVM does not implement such interface, so you need something that does it and runs java.
There are several such components. I know JavaService and Apache Daemon and suggest you to use them. I do not believe that there is something "weaker" and I do not think that mentioned solutions are too heavy. JavaService is just a small DLL.

A: Take a look at https://en.wikipedia.org/wiki/Service_wrapper:

"Java itself doesn't support creating system services"

A: Java does not compile to native executables (.exe files for !indows or Linux elf executables). The only way that Java classes are executed are inside a Java Virtual Machine which is why you type java -cp Main when starting the Java application. This is also why Java binaries can be executed on multiple platforms, no matter which platform created the class and jar files.
Services are just executables that are started by the operating system at some point in time (at startup for instance). Creating such services are completely separate from Java, since they are an operating system concern. If you want to know more about services, I suggest looking up the creation of 'services' (or whatever the platform you are working on calls them) on the relevant websites. You could even look at the source code for an existing wrapper library for details, but you will inevitably have to use a language other than Java to implement services for your OS.
There is no weakness in using existing wrapper libraries to avoid native coding n other languages at least. As you said, do not reinvent the wheel.

A: If you want to know why these wrappers are needed, you can look at their source code (some of them are open source).
The executables normally used to run applications (java.exe and javaw.exe) have nothing to handle the signals required to run a service. In particular, while it's easy to start an application, notifying a service application that it needs to stop and restart is another matter. You need something to catch those notifications while the application is running, and it's certainly better if this is not an abrupt process termination.
Besides the registration aspects of the service, service wrappers also implement some JNI functions, to make your application aware that it's a service. (The also tend to use the JVM DLL instead of the executable as far as I'm aware.)
Have a look at the Winrun4J code for example. It has native sections and Java sections.
In addition, services also need to be aware of certain tricks. For example, if you don't use -Xrs, your service will be shut down when the user logs off.


text:
Q: UPDATE ANOTHER COLUMN IN AFTER UPDATE TRIGGER I have a table with three columns: id, date and dateDekete
I try to execute an update on the column dateDelete after an update on another column (column date) using a AFTER UPDATE TRIGGER.
The code that I use to create my trigger is the following:
CREATE OR REPLACE FUNCTION update_delete_date_allocation()
  RETURNS trigger LANGUAGE plpgsql AS  $body$
    BEGIN
        NEW."dateDelete" := NEW.date + 1;
        RETURN NEW;
      END;
 $body$;

CREATE TRIGGER delete_date_allocation_trg
    AFTER INSERT OR UPDATE ON client.client_portfolio_allocation
    FOR EACH ROW
    EXECUTE PROCEDURE update_delete_date_allocation();

Although the code executes fine with no error message, the latter column that I try to update does not change.
I was wondering if it's possible to do this. AND if so, what should I change in my code?
I am using Postgres 11.5.

A: you can't change the new record in an AFTER trigger, you need to declare your trigger as a BEFORE trigger:
CREATE TRIGGER delete_date_allocation_trg
    BEFORE INSERT OR UPDATE ON client.client_portfolio_allocation
    FOR EACH ROW
    EXECUTE PROCEDURE update_delete_date_allocation();


text:
Q: Using IFNULL in sqlalchemy core I'm trying to use sqlalchemy core select rows from a mysql table using IFNULL.
Given a table like so:
id    int1    string1   other
1      7        NULL    other stuff
2      NULL     bar     more stuff

The sql would be something like:
SELECT IFNULL(int1, 0) AS int1, IFNULL(string1, '') AS string1 FROM table

Is this possible using the core? What would be great would be something like
s = select(ifnull(table.c.int1, 0), ifnull(table.c.string1, ''))

A: You should be able to use func from sqlalchemy.sql like this for arbitrary database functions (I think ifnull is db dependent, I use coalesce for postgresql):
from sqlalchemy.sql import select, func
# assuming you have imported table from somewhere!!

s = select([func.ifnull(table.c.int1, 0), func.ifnull(table.c.string1, '')])

A: PostgreSQL doesn't support if null
instead of ifnull() you can use func.coalesce()
Syntax -
  func.coalesce(Table.field, default_value)

Example -
 func.coalesce(Order.price, 0)

 func.coalesce(Student.name, ' ')


text:
Q: tmux copy does not work I'm trying to become more proficient with tmux, but I ran into ( what seems to me ), a weird issue. Here's my tmux.conf:
  1 TERM=screen-256color
  2 set-option -g default-terminal $TERM
  3
  4 TMUX_COLOUR_BORDER="colour237"
  5 TMUX_COLOUR_ACTIVE="colour231"
  6 TMUX_COLOUR_INACTIVE="colour16"
  7
  8 set-window-option -g window-status-activity-bg $TMUX_COLOUR_BORDER
  9 set-window-option -g window-status-activity-fg $TMUX_COLOUR_ACTIVE
 10 set-window-option -g window-status-current-format "#[fg=$TMUX_COLOUR_ACTIVE]#I:#W#F"
 11 set-window-option -g window-status-format "#[fg=$TMUX_COLOUR_INACTIVE]#I:#W#F"
 12
 13
 14 set -g prefix C-a
 15
 16 bind-key o split-window -v
 17 bind-key e split-window -h
 18
 19 bind-key w kill-pane

I'm trying to copy paste between two panes. So, I hit Ctrl-a-[ , and then Ctrl-space. The thing is, I don't see a visual selection of the block, and alt-w also does not work ( since I guess it's not even entering copy mode ). Is there an obvious error in my tmux.conf? Can you spot what I'm doing wrong?

A: tmux has an option, mode-keys, you can find it in man page.
default is emacs, but if your $EDITOR is vim/vi, tmux will use vi.
So the key binding will be in vi mode.
E.g. your Alt-w won't work, it is emacs binding. you can see a table of key-binds in tmux man page.
some related to your question:
Function                     vi              emacs
Copy selection               Enter           M-w
Start selection              Space           C-Space

so you should go with the vi-mode keys.
I used vim mode too, and did a little customization (to make it same as vim) in my tmux.conf, maybe you could give it a try:
bind-key -t vi-copy 'v' begin-selection     # Begin selection in copy mode.
bind-key -t vi-copy 'C-v' rectangle-toggle  # Begin selection in copy mode.
bind-key -t vi-copy 'y' copy-selection      # Yank selection in copy mode.

A: In case it helps, I had a correct tmux configuration (with vi like settings for selection & copy/paste) but needed to set these two environment variables in my .zshrc file (using Zsh & Neovim):
export EDITOR='nvim'
export VISUAL='nvim'


text:
Q: Create KML from MXD that contains map service layers like feature layers How can I create a KML (tools suggestion), provided that I have a map (.mxd) file which layers are service layers of hosted services and not local data coming from a geodatabase.
I know that the map to kml tool works only for local data and not with data coming from services.
Any ideas ?

A: Since ArcGIS Server 10.1, the ability to include a hosted service inside a map service has been disabled.
You should get the following error if you try to publish an mxd containing one:
ArcGIS for Server error description
Perhaps you could scrape the data from the hosted service and recreate the service.


text:
Q: Object properties does not seem change in Parallel processing using joblib in python I have the following code that works well with one process but doesn't work with more than one. No error messages but class properties doesn't not seem to save and I have no clue why or how to fix it. I am running the code under windows
class T:
  a = 0
  b = 0
  c = 0
  def do_something(self):
    self.a = 10
    self.b = 5
    self.c = 1
    return 'ok'

def call_T(a):
  return a.do_something()

if __name__ == '__main__':
  B = T()
  print(B.a)
  B.do_something()
  print(B.a)
  C = [T() for i in range(20)]
  print(C[14].c)
  F = Parallel(n_jobs=2)(delayed(call_T)(C[i]) for i in range(20))
  print(F)
  print(C[14].b)

results are
0
10
0
['ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok']
0

now for the same code only change n_jobs=1 and it will give me the correct expected resuls
0
10
0
['ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok']
5

I am clueless as what is wrong. Any help is appreciated

A: I found a simple answer
it turns out that joblib only passes results from returned method but not the memory
using threading, however will pass both
class T:
  a = 0
  b = 0
  c = 0
  def do_something(self):
    self.a = 10
    self.b = 5
    self.c = 1
    return 'ok'

def call_T(a):
  return a.do_something()

if __name__ == '__main__':
  B = T()
  print(B.a)
  B.do_something()
  print(B.a)
  C = [T() for i in range(20)]
  print(C[14].c)
  F = Parallel(n_jobs=3,backend="threading")(delayed(call_T)(C[i]) for i in range(20))
  print(F)
  print(C[14].b)

results
0
10
0
['ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok', 'ok']
5


text:
Q: How can I make redux dispatch an action as well as return a promise? Here is my function in songAction.js
export function createSong(title, url, token) {

    axios.defaults.headers.common['Authorization'] = token

    return function (dispatch) {
        axios.post('http://localhost:8080/api/song/create', {
            title,
            link: url

        })
        .then((response) => {
            console.log('the response was', response)
            if(response.data.success){
                dispatch({type: "CREATE_SONG_FULFILLED", payload: response.data.song})
            } else {
                dispatch({type: "CREATE_SONG_REJECTED", payload: response.data})

            }
        })
        .catch((err) => {
            dispatch({type: "CREATE_SONG_REJECTED", payload: err})
        })
    }
}

I want to be able to return a promise after dispatching so I can use the function like this inside a component -
 createSong(title, url, token)
   .then((result) =>{
        // do stuff with result
     })

I know I can pass in a callback to make this work async.. but I want to use ES6 features of promises. And I'm a little confused how I can do this.

A: If you want to go full ES6 you should use the async/await syntax. This eliminates the need to deal with promises at all.
export function createSong (title, url, token) {
  axios.defaults.headers.common['Authorization'] = token
  return async (dispatch) => {
    try {
      const response = await axios.post('http://localhost:8080/api/song/create', {
        title,
        link: url
      })
      console.log('the response was', response)
      if (response.data.success) {
        dispatch({type: 'CREATE_SONG_FULFILLED', payload: response.data.song})
      } else {
        dispatch({type: 'CREATE_SONG_REJECTED', payload: response.data})
      }
    } catch (err) {
      dispatch({type: 'CREATE_SONG_REJECTED', payload: err})
    }
  }
}

The anonymous function returned by createSong is marked with the new async keyword. This means that the anonymous function will now return an implicit Promise.
The async keyword also allows you to use await in the body of the function so you can await the async call to axios.post and so treat it as if it were a synchronous call.
Another advantage is that you can go back to using normal try / catch blocks. These are actually resolving and rejecting the implicit promise behind the scenes but they act in the normal way.
Because the anonymous function is actually returning a Promise, higher up the call chain, wherever you call the createSong(...) function, you can also use the async / await syntax ... and so on. No more callbacks, and no more explicit Promise handling.

A: First of all, you need to return the axios call.
...
return function (dispatch) {
  return axios.post('http://localhost:8080/api/song/create', {
    title,
    link: url
  })
...

Your createSong function is returning another function (so it's a curried function).
Therefore,
createSong(title, url, token)(dispatch)
.then(()=>{
  // something
})

looks to me pretty valid.

A: I think that it isn't very 'React' way to use return values of dispatched actions.
There is a better way how to solve 'complex' situations like this using Redux Saga, example here.
Although, I used returned values by dispatched actions in this way in the past:
export const updatePage = (id, batch) => {
  return dispatch => {
    dispatch({
      type: 'UPDATE_PAGE',
      payload: {
        id
      }
    })

    // Make an API call
    return requestUpdatePages(
      id, batch
    ).then(data => {
      // When API call is successful
      return dispatch({
        type: 'UPDATE_PAGE_SUCCESS',
        payload: {
          id,
          data
      })
    })
    .catch(error => {
      // When API call fails
      return dispatch({
        type: 'UPDATE_PAGE_FAIL',
        payload: {
          error,
          id
        },
        error: true
      })
    })
  }
}

// After dispatch is bound to action creators
// you can use it like this

handleClick(id) {
  const { updatePage } = this.props
  updatePage(id).then(action => {
    if(action.type === 'UPDATE_PAGE_SUCCESS') {
      console.log('Whee, page has been updated!', action.payload.data)
    } else {
      console.error('Something went wrong :-( ', action.payload.error)
    }
  })
}


text:
Q: struggling to change grid for certain media query I want the second column that take the entire two rows on full screen, to drop down so the grid only contains one column with 4 rows(1st row being the title of the section, second being the description, and the third and fourth rows the skills) I tried a lot of different stuff but yet non of them make the grid actually drop to 1 column when i resize.

        My Journey So Far

Java

UI

CSS

UX

HTML

GIT

LINUX

ADOBE

          Always up for a challenge, I have worked for lean start-ups and was a
          member of the first New Zealand start-up to attend Y Combinator, the
          largest start-up accelerator in the world. From there, I worked my way
          up to Art Director and Team Lead at Appster where I oversaw the design
          of 30+ mobile and desktop apps. Currently, I lead UI/UX design at SaaS
          start-up VideoMyJob.

.heading {
  font-size: 2.75rem;
  font-weight: 500;
}

.grid-container {
  display: grid;
  grid-template-columns: 50% 20%;
  grid-row-gap: 1rem;
  grid-column-gap: 3rem;
  margin-left: 5%;
  margin-bottom: 8rem;
}

@media only screen and (max-width: 768px) {
  .grid-container {
    display: grid;
    grid-template-columns: 50%;
    grid-template-rows: 1ft 1fr 1fr 1fr;
  }
  .skill-col-container {
    grid-column-start: 1;
    grid-row-start: 4;
  }
}

.skill-col-container {
  grid-row-start: 1;
  grid-row-end: 3;
  grid-column: 2;
}

.skill-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-row-gap: 20px;
}

.skills {
  text-transform: uppercase;
  display: inline-block;
  border: solid;
  border-radius: 1px;
  border-color: black;
  width: 5rem;
  display: flex;
  justify-content: center;
  border-radius: 3.75rem;
  background-color: #ec9b3b;
}

.p-3 {
  grid-column: 1;
}

A: Just put your @media at the end of your file. Media queries add no specificity to the selectors they contain, but source order still matters.
You can also refer here: Why does the order of media queries matters in CSS
.heading {
  font-size: 2.75rem;
  font-weight: 500;
}

.grid-container {
  display: grid;
  grid-template-columns: 50% 20%;
  grid-row-gap: 1rem;
  grid-column-gap: 3rem;
  margin-left: 5%;
  margin-bottom: 8rem;
}

.skill-col-container {
  grid-row-start: 1;
  grid-row-end: 3;
  grid-column: 2;
}

.skill-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-row-gap: 20px;
}

.skills {
  text-transform: uppercase;
  display: inline-block;
  border: solid;
  border-radius: 1px;
  border-color: black;
  width: 5rem;
  display: flex;
  justify-content: center;
  border-radius: 3.75rem;
  background-color: #ec9b3b;
}

.p-3 {
  grid-column: 1;
}

@media only screen and (max-width: 768px) {
  .grid-container {
    display: grid;
    grid-template-columns: 50%;
    grid-template-rows: 1ft 1fr 1fr 1fr;
  }

  .skill-col-container {
    grid-column-start: 1;
    grid-row-start: 4;
  }
}


text:
Q: Setting a buttons image using another button - Swift I am trying to change a buttons image using another button. The idea being this button resets the buttons to their original state to allow the user to play again.
@IBAction func playAgainButton(_ sender: Any) {
    grid = ["0", "3", "4", "5", "6", "7", "8", "9", "a"]
    let btnCheckMarkImage = UIImage(cgImage: "Image-1" as! CGImage)
    gridSpace0.setImage(btnCheckMarkImage, forState: UIControlState.Normal)
    gameResultLabel.isHidden = true
    //let image = UIImage(named: "blankSpace")
}

@IBAction func gridSpace0(_ sender: Any) {
    let button = sender as! UIButton
    checkIfFree(gridSpace: 0, sender: button)
}

func checkIfFree(gridSpace: Int, sender: UIButton) {
    if(player % 2 != 0)
    {
        player = playerone
        currentPlayerName = playerOneName
    }
    else
    {
        player = playertwo
        currentPlayerName = playerTwoName
    }
    if(grid[gridSpace] != "1" && grid[gridSpace] != "2")
    {
        if(player == playerone)
        {
            let image = UIImage(named: "TicTacToeX")
            grid[gridSpace] = String(player)
            sender.setBackgroundImage(image, for: UIControlState.normal)
            player = player + 1;
        }
        else
        {
            let image = UIImage(named: "TicTacToeO")
            grid[gridSpace] = String(player)
            sender.setBackgroundImage(image, for: UIControlState.normal)
            player = player + 1;
        }

So each time a button is pressed by the user, the space is checked to see if it is free, if so it changes the image of the button.
Like I said, I want the play again button to change the image of gridSpace0 button but when I use the code above I get this error:
I need to user the sender part for the button to identify which button is being pressed, so how can I change it's background?
Thanks

A: Your gridSpace0 is a function so you cannot set image like that.
@IBAction func gridSpace0(_ sender: Any) {
    let button = sender as! UIButton
    checkIfFree(gridSpace: 0, sender: button)
}

You need to first link your button to your view controller, and then set button like this


text:
Q: blow up $\mathbb C^{n}$ at $0$ Let $D$ be the open unit ball of $\mathbb{C}^{n}$, and $\tilde D$ be the submanifold of $D \times \mathbb CP^{n - 1}$ given by $\{(z, l) \in U \times \mathbb CP^{n - 1} | z^{i}l^{j} = z^{j} l^{i}\}$ where $[l_1: \ldots l_n]$ are the homogeneous coordinates on $\mathbb CP^{n - 1}$. Denote the projection $(z, l) \to z$ by $\pi$. We can cover $\tilde D$ by $\tilde D_{i} = \{ l^{i} \neq 0\}$ with local coodinates $\tilde z(i)^{j} = \frac{l^{j}}{l^{i}} = \frac{z^{j}}{z^{i}}$ for $j \neq i$ and $\tilde z(i)^{i} = z^{i}$. Denote $E := \pi^{-1}(0)$. The claims is that $E$ on $\tilde D_{i}$ is given by $\tilde z(i)^{i} = 0$.
Basically, $E \cap \tilde D_{i} = \{(0, l) \in D \times \mathbb CP^{n - 1} | l_{i} \neq 0\}$, but $\tilde z(i)^{i} = 1$ by definition. How would $\tilde D_{i}$ ever be given by $\tilde z(i)^{i} = 0$?


text:
Q: Unable to start wildfly 10.1.0.Final in cluster mode when enabling IPv6 Currently we use wildfly 10.1.0.Final with OpenJDK 7. When I set java.net.preferIPv4Stack=false to support IpV6 as new requirement from customers. But I see this problem below in cluster mode only
What should we do now? If I set java.net.preferIPv4Stack=true, it is working properly, but this means that IPv6 is not supported.
Thank you!
java -version
java version "1.7.0_79"
OpenJDK Runtime Environment (rhel-2.5.5.4.el6-x86_64 u79-b14)
OpenJDK 64-Bit Server VM (build 24.79-b02, mixed mode)
Exception:

2017-10-06 10:35:51,667 ERROR [ServerService Thread Pool --
  3]-[org.jboss.modcluster] MODCLUSTER000034: Failed to start advertise
  listener: java.net.SocketException: bad argument for IP_MULTICAST_IF:
  address not bound to any interface
at java.net.PlainDatagramSocketImpl.socketSetOption(Native Method)

at java.net.AbstractPlainDatagramSocketImpl.setOption(AbstractPlainDatagramSocketImpl.java:310)

at java.net.MulticastSocket.setInterface(MulticastSocket.java:471)

at org.jboss.modcluster.advertise.impl.AdvertiseListenerImpl.init(AdvertiseListenerImpl.java:151)

at org.jboss.modcluster.advertise.impl.AdvertiseListenerImpl.start(AdvertiseListenerImpl.java:165)

at org.jboss.modcluster.ModClusterService.init(ModClusterService.java:178)

at org.wildfly.mod_cluster.undertow.UndertowEventHandlerAdapter.start(UndertowEventHandlerAdapter.java:100)

at org.wildfly.clustering.service.AsynchronousServiceBuilder$1.run(AsynchronousServiceBuilder.java:102)

at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)

at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)

at java.lang.Thread.run(Thread.java:745)

at org.jboss.threads.JBossThread.run(JBossThread.java:320)

2017-10-06 10:35:51,797 INFO  [MSC service thread
  1-7]-[org.jboss.as.remoting] WFLYRMT0001: Listening on [::]:9999
2017-10-06 10:35:52,014 INFO  [MSC service thread
  1-5]-[org.jboss.as.remoting] WFLYRMT0001: Listening on [::]:4447

A: Thank you!
mutiple cast: 225.1.2.5
ifconfig -a
eth0      Link encap:Ethernet  HWaddr 00:50:56:9C:DD:DC
          inet addr:192.168.92.204  Bcast:192.168.92.255  Mask:255.255.255.0
          inet6 addr: fe80::250:56ff:fe9c:dddc/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:971537495 errors:0 dropped:0 overruns:0 frame:0
          TX packets:666680550 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:468632879172 (436.4 GiB)  TX bytes:548433354959 (510.7 GiB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:838757022 errors:0 dropped:0 overruns:0 frame:0
          TX packets:838757022 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:280155497754 (260.9 GiB)  TX bytes:280155497754 (260.9 GiB)

jboss.bind.address = 0.0.0.0
I see similar issue here, but not anwsered yet
https://developer.jboss.org/thread/233410


text:
Q: angularjs adding a form to a page Take the following code example:
app.config( function($stateProvider, $urlRouterProvider, RestangularProvider){
     $stateProvider
        .state('route1', {

            url: "/ID/:slug",
            templateUrl: "/static/html/main-view.html",
            controller: "CampaignCtrl"
        })

etc...

The template main-view.html just shows a list of items. I now want to add simple sign-up form to the page, but what is the correct approach (an example would be good too).
1) just stick it in the main-view.html, downside is I cannot use it on its own
2) somehow attach another controller no idea how.
3) create a custom directive that accepts prarms to create a form if thats possible.
4) something else?


text:
Q: Minimum Spanning tree different from another Assume we are given
an undirected  graph g where every node i,1 <= i < n is connected to all j,i < j <=n
and a source s.
We want to find the total costs (defined as the sum of all edges' weights) of the cheapest minimum spanning tree that differs from the minimum distance tree of s (i.e. from the MST obtained by running prim/dijkstra on s) by at least one edge.
What would be the best way to tackle this? Because currently, I can only think of some kind of fixed-point iteration

*

*run dijkstra on (g,s) to obtain reference graph r that we need to differ from

*costs := sum(edge_weights_of(r))

*change := 0

*for each vertex u in r, run a bfs and note for each reached vertex v the longest edge on the path from u to v.

*iterate through all edges e = (a,b) in g: and find e'=(a',b') that is NOT in r and minimizes newchange := weight(e') - weight(longest_edge(a',b'))

*if(first_time_here OR newchange < 0) then change += newchange

*if(newchange < 0) goto 4

*result := costs + change
That seems to waste a lot of time... It relies on the fact that adding an edge to a spanning tree creates a cycle from which we can remove the longest edge.
I also thought about using Kruskal to get an overall minimum spanning tree and only using the above algorithm to replace a single edge when the trees from both, prim and kruskal, happen to be the same, but that doesn't seem to work as the result would be highly dependent on the edges selected during a run of kruskal.
Any suggestions/hints?

A: You can do it using Prim`s algorithm
Prim's algorithm:
let T be a single vertex x
while (T has fewer than n vertices)
{
    1.find the smallest edge connecting T to G-T
    2.add it to T
}

Now lets modify it.
Let you have one minimum spanning tree. Say Tree(E,V)
Using this algorithm
Prim's algorithm (Modified):
let T be a single vertex
let isOther = false
while (T has fewer than n vertices)
{
    1.find the smallest edge (say e) connecting T to G-T
    2.If more than one edge is found, {
        check which one you have in E(Tree)
        choose one different from this
        add it to T
        set isOther = true
      }
      else if one vertex is found {
        add it to T
        If E(Tree) doesn`t contain this edge, set isOther = true
        Else don`t touch isOther ( keep value ).
      }
}
If isOther = true, it means you have found another tree different from Tree(E,V) and it is T,
Else graph have single minimum spanning tree


text:
Q: Schema type one of a set of types I have the following schema:
const x = new mongoose.Schema({
   y: {
      type: // here
   }
})

I want the type of y to be string or array or number, how to do that?, is there something like:
const x = new mongoose.Schema({
   y: {
      type: String | Array | Number
   }
})

P.S: I don't want to allow all the types on earth, I only want to allow String, Number and Array.
If the user provided an object, for example, it should throw a validation error. How?


text:
Q: How to fill by colour a grid cell i need to fill a whole cell with background colour, but im getting this:
I used a "match_parent" everywhere and it's gave nothing, please help
code:
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<GridLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/gucciBlack"
    android:padding="3dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/gucciRed"
        android:text="@string/days" />

    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_column="1"
        android:layout_row="0"
        android:background="@color/gucciRed"
        android:text="mon" />

    <CheckBox
        android:id="@+id/checkBox2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_column="0"
        android:layout_row="1"
        android:background="@color/gucciLazur"
        android:text="tue" />

 ... other checkboxes (same code) ...
</android.support.v7.widget.CardView>

A: This is happening because your TextView width and height are set as "wrap_content". Try changing them to "match_parent", as it follows:
   <TextView
         android:id="@+id/textView"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:layout_column="0"
         android:layout_row="0"
         android:background="@color/gucciRed"
         android:text="@string/days" />

A: In TextView, Instead of background you should be using textColor,
<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@color/gucciRed"
    android:text="@string/days" />


text:
Q: C compilation warning: passing argument 1 of 'insert' from incompatible pointer type [enabled by default] /*Implementation of Binary Tree*/

#include <stdio.h>
#include <ncurses.h>
#include <malloc.h>
#include <stdlib.h>

struct bin_tree
{
    int INFO;
    struct node *LEFT, *RIGHT;
};

typedef struct bin_tree node;

node *insert(node *,int); /*Function prototype for insering a new node*/
void display(node *); /*Function prototype fpr displaying the tree nodes*/

int count=1; /*counter for ascertaining left or right position for the new node*/

int main()
{
    struct node *root = NULL;
    int element, choice;

    clear();

    /*Displaying a menu of choices*/
    while(1)
    {
        clear();
        printf("\n Select an option\n");
        printf("\n1 - Insert");
        printf("\n2 - Display");
        printf("\n3 - Exit");

        printf("\n\nEnter your choice: ");
        scanf("%d",&choice);

        switch(choice)
        {
            case 1:
            {
                printf("\n\n Enter the node value: ");
                scanf("%d", &element);
                root = insert(root, element); /*calling the insert function for    inserting a new element into the tree*/
                getch();
                break;
            }

            case 2:
            {
                display(root); /*calling the display function for printing the node values*/
                getch();
                break;
            }

            case 3:
            {
                exit(1);
                break;
            }

            default:
            {
                printf("\n incorrect choice.Please try again.");
                getch();
                break;
            }
         }
    }
}

node *insert(node *r, int n)
{
    if(r==NULL)
    {
        r=(node*)malloc(sizeof(node));
        r->LEFT = r->RIGHT = NULL;
        r->INFO = n;
        count = count+1;
    }
    else
    {
        if(count%2==0)
        r->LEFT = insert(r->LEFT,n);
        else
        r->RIGHT = insert(r->RIGHT,n);
    }
    return(r);
}

void display(node *r)
{
    if(r->LEFT!=NULL)
    display(r->LEFT);
    printf("%d\n",r->INFO);
    if(r->RIGHT!=NULL)
    display(r->RIGHT);
}

gcc -Wall -c "BinaryTree.c" (in directory: /home/dere/IGNOUPROGRAMS/C)

BinaryTree.c: In function 'main':
BinaryTree.c:46:5: warning: passing argument 1 of 'insert' from incompatible pointer type [enabled by default]
BinaryTree.c:16:7: note: expected 'struct node *' but argument is of type 'struct node *'
BinaryTree.c:46:10: warning: assignment from incompatible pointer type [enabled by default]
BinaryTree.c:53:5: warning: passing argument 1 of 'display' from incompatible pointer type [enabled by default]
BinaryTree.c:17:6: note: expected 'struct node *' but argument is of type 'struct node *'
BinaryTree.c: In function 'insert':
BinaryTree.c:86:3: warning: passing argument 1 of 'insert' from incompatible pointer type [enabled by default]
BinaryTree.c:74:7: note: expected 'struct node *' but argument is of type 'struct node *'
BinaryTree.c:86:11: warning: assignment from incompatible pointer type [enabled by default]
BinaryTree.c:88:3: warning: passing argument 1 of 'insert' from incompatible pointer type [enabled by default]
BinaryTree.c:74:7: note: expected 'struct node *' but argument is of type 'struct node *'
BinaryTree.c:88:12: warning: assignment from incompatible pointer type [enabled by default]
BinaryTree.c: In function 'display':
BinaryTree.c:96:2: warning: passing argument 1 of 'display' from incompatible pointer type [enabled by default]
BinaryTree.c:93:6: note: expected 'struct node *' but argument is of type 'struct node *'
BinaryTree.c:99:2: warning: passing argument 1 of 'display' from incompatible pointer type [enabled by default]
BinaryTree.c:93:6: note: expected 'struct node *' but argument is of type 'struct node *'
Compilation finished successfully.

Would appreciate any help on this error.

A: Declare root as type of node * itself in main() function. No need to declare as struct node *.
node *root = NULL;

As root is typedef for struct bin_tree.
Warning is due to the declaration mismatch. As insert() function is defined as node *insert(node *,int); but root variable is defined as struct node * and its passed as argument to insert() function.

A: seems your code is wrong,probably try like this.you need to pass the adress of root to insert function pointer like below:
root = insert(&root, element);

node *insert(node **r, int n)
{

    struct node* temp = NULL;

    struct node *q = NULL;

    q = *r;

    if(q==NULL)
    {
        temp=(node*)malloc(sizeof(node));
        temp->LEFT = temp->RIGHT = NULL;
        temp->INFO = n;
        count = count+1;
    }
    else
    {
       if(count%2==0)
        temp->LEFT = insert(temp->LEFT,n);
       else
        temp->RIGHT = insert(temp->RIGHT,n);
    }
    return(temp);
}