text:
Q: Realtime Gifted Chat with Socket.io issues I'm trying to get Gifted Chat implemented in a realtime fashion with socket.io but I'm having issues. I'm able to get socket.io to connect, the message to be emitted, but it isn't showing up in real time when I have an android emulator and an iPhone simulator both running the app.
server.js
const express = require("express");
const http = require("http");
const app = express();
const server = http.createServer(app);
// Attempt at Socket.io implementation
const socket = require('socket.io')
const io = socket(server)

const bodyParser = require('body-parser');
const Message = require("./models/message");
const SportsMessage = require('./models/sportsMessage')
const GamerMessage = require('./models/gamerMessage')
const mongoose = require('mongoose');

// MongoDB connection
mongoose.connect(
  'mongodb+srv://yada:yada@cluster0.kt5oq.mongodb.net/Chatty?retryWrites=true&w=majority', {
    useNewUrlParser: true,
    useUnifiedTopology: true
  }).then(() => {
    console.log('Connected to the database!')
  }).catch(() => {
    console.log('Connection failed oh noooooo!')
});

// Parse the request body as JSON
app.use(bodyParser.json());

// GET messages, don't change these bro
app.get("/api/messages", (req, res) => {
  Message.find({}).exec((err, messages) => {
    if(err) {
       res.send(err).status(500);
    } else {
       res.send(messages).status(200);
    }
  });
});

app.get("/api/sportsMessages", (req, res) => {
  SportsMessage.find({}).exec((err, messages) => {
    if(err) {
       res.send(err).status(500);
    } else {
       res.send(messages).status(200);
    }
  });
});

app.get("/api/gamerMessages", (req, res) => {
  GamerMessage.find({}).exec((err, messages) => {
    if(err) {
       res.send(err).status(500);
    } else {
       res.send(messages).status(200);
    }
  });
});

// POST messages
app.post('/api/messages', (req, res) => {
  Message.create(req.body).then((message) => {
      res.send(message).status(200);
  }).catch((err) => {
      console.log(err);
      res.send(err).status(500);
  });
});

app.post('/api/sportsMessages', (req, res) => {
  SportsMessage.create(req.body).then((message) => {
      res.send(message).status(200);
  }).catch((err) => {
      console.log(err);
      res.send(err).status(500);
  });
});

app.post('/api/gamerMessages', (req, res) => {
  GamerMessage.create(req.body).then((message) => {
      res.send(message).status(200);
  }).catch((err) => {
      console.log(err);
      res.send(err).status(500);
  });
});

// Socket.io connection
io.on('connection', socket => {
  socket.emit('your id', socket.id)
  socket.on('send message', body => {
      console.log(body)
      io.emit('send message', body)
  })
  console.log("connected to dat socket boiii")
})

server.listen(8000, () => console.log("server is running on port 8000"));

Chat Screen
import React, { useState, useEffect, useContext, useRef } from 'react'
import { View, Text, Button, StyleSheet } from 'react-native'

import io from 'socket.io-client'

import useMessages from '../hooks/useMessages'
import { Context as UserContext } from '../context/UserContext'

import { GiftedChat as GChat } from 'react-native-gifted-chat'

const GeneralChat = () => {
  const [messages, ids, getMessages, randomId, setMessages] = useMessages()
  const { state: { username } } = useContext(UserContext)

  const socketRef = useRef()
  socketRef.current = io('{MyIP}')

  useEffect(() => {
    getMessages()
    randomId()
    const socket = io('{MyIP}')
    socket.on('your id', id => {
      console.log(id)
    })
  }, [])

  const onSend = (message) => {
    let userObject = message[0].user
    let txt = message[0].text
    console.log(message)
    setMessages(previousMessages => GChat.append(previousMessages, message))
    const messageObject = {
      text: txt,
      user: userObject
    }
    socketRef.current.emit('send message', messageObject)
    fetch("{MyIP}/api/messages", {
      method: "POST",
      headers: {
          "Content-Type": "application/json"
      },
      body: JSON.stringify(messageObject)
      }).then((res) => {
          return res.json();
      }).catch((err) => {
          console.log(err);
      });
  }

  return (
    <GChat
      // isLoadingEarlier
      scrollToBottom
      infiniteScroll
      loadEarlier
      alwaysShowSend
      renderUsernameOnMessage
      inverted={true}
      showUserAvatar
      messages={messages}
      onSend={message => onSend(message)}
      user={{
        _id: ids,
        name: username,
        avatar: 'https://placeimg.com/140/140/any'
      }}
    />
  )
}

GeneralChat.navigationOptions = () => {
  return {
    title: 'General Chat',
  }
}

const styles = StyleSheet.create({

})

export default GeneralChat


text:
Q: autocorrelation_plot and plot_acf giving different result/ Difference between autocorrelation_plot and plot_acf Please consider below code
%matplotlib inline
import pandas as pd
import numpy as np
sampleRng = pd.date_range(start='2017', periods=120, freq='MS')
sampleTs = pd.Series(np.random.randint(-10, 10, size=len(sampleRng)), sampleRng).cumsum()
sampleTs = pd.DataFrame(sampleTs,columns=['data'])
sampleTs.head()

from pandas.plotting import autocorrelation_plot
sampleTs["diff"] = sampleTs.diff() ## making data stationary

autocorrelation_plot(sampleTs["diff"])

Output is as below

Next lets use plot_acf from statsmodel
from statsmodels.graphics.tsaplots import plot_acf
import matplotlib.pyplot as plt
sampleTs["diff"].iloc[0] = 0
plot_acf(sampleTs["diff"], lags = 100)
plt.show()

output is as below

As we can notice there are clear difference between both figures. What could be the reason for this and how can we make both same.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to match Android Studio TODO comment patterns that include a colon in their regex I'm using Android Studio 2.2.1 .
I'm trying to create an Android Studio TODO pattern (Settings → Editor → TODO → Patterns) with regular expression that will match the word bug followed by : no matter where this combination written in the sentence.
The following sentences are ones that I want to match:

*

*bug: not working.

*BUG: whatever...

*this is a BUG: !

In contrast to the above, the following sentences are ones that I don't want to match:

*

*this is a bad bug.

*is it that buggy

*lots of bugs and no solution.

*:BUG doesn't work.

I currently have \bbug\b.* regular expression that works but he also works when : character is missing.
I've tried the following regular expressions without a success:

*

*\bbug:\b.*

*\bbug\\:\b.*
I would like to know how can I crate a regular expression pattern that consist of the word bug followed by : as a special character.

A: You just have to put the colon on the outside of the pattern, like so: \bbug\b:.*
This grabs bug:, BUG:, but not bug, BUG, or :BUG.


text:
Q: Integration of a differential equation I've got some problems with integrating a ODE, so maybe someone could add some words of advice.
Given the following equation:
$z''(x)-2\gamma z'(x) +p(x)z(x)=0$, $(1)$
and $\varphi(x)=z(x)e^{-\gamma x}$  $(2)$
, where $\gamma$ is a complex constant and $p(x),z(x),\varphi(x)$ are real funcions working on $\mathbb{R}$.
In addition it is assumed that $z'(x)\rightarrow 0 ; z(x)\rightarrow 1$ for $x\rightarrow \infty$. $(3)$
Now I want to show $z'(x)=\int_x^\infty e^{2\gamma(x-s)}p(s)z(s)ds$
I started rearranging $(1)$ to: $z''(x)=2\gamma z'(x)-p(x)z(x)$
Integrating both sides of $(1)$ from $x$ to $\infty$ yields
$\int_x^\infty z''(s)ds=z'(\infty)-z'(x)=0-z'(x)=\int_x^\infty 2\gamma z'(s)-p(s)z(s)ds$ because of $(3)$
But now I don't know how to go on, because I don't see how to reach with forming the integral on the right side, that there will be the $e^{\cdots}$ term. Even when I will use the assumption $(2)$ I'll some $\varphi(x)$ too. So I guess one have to integrate in a clever way or need something else to know. Maybe someone could point me in the right direction.
By the way: I've got also problems with $x$ in the integral and the $x$ in $e^{2\gamma(x-s)}$. I tried to derive both sides with respect to $x$ for getting an idea how to solve the problem why there is the $e$ term. But unfortunately  I'm quite unsure with deriving in these special situation.
Thanks!


text:
Q: how to add date-column to data frame I have a data frame with many different columns (each column has 10 rows/entries) and I want to add a date-column as the first column to this data frame. The date column should end today and starts today-9.
The following data frame is just a counterexample:
set.seed(123)
df <- data.frame(DE = rnorm(10, 2, 1), Wind = rnorm(10, 5, 2), Solar = rnorm(10, 2, 2))

So in this case the date-column should be c("2020-10-10", ..., "2020-10-19").
How can I add such an cate-column which depends on the current date, like today is the 19th Oct., so the date should start today()-9.

A: You can use the seq.Date function to generate such a list. Here we use the number of rows in the df but you could hard-code 10 if you prefer
date_vals <- rev(seq(Sys.Date(), by="-1 days", length.out=nrow(df)))

We start at 10, walk back a certain number of steps, and then reverse the list to get the oldest date first.
You could also specify both dates as well
date_vals <- seq(Sys.Date()-9, Sys.Date(), by="1 day")

Then, which ever way you create the values, you can add them as the first column of your data.frame with this
df <- data.frame(dates=date_vals, df)


text:
Q: Make IPython3 behave like Python3 for `type` Consider the following with IPython3:
Python 3.4.3+ (default, Jul 28 2015, 13:17:50)
Type "copyright", "credits" or "license" for more information.

IPython 4.0.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: type([1,2])
Out[1]: list

and the same piece of code with Python3:
Python 3.4.3+ (default, Jul 28 2015, 13:17:50)
[GCC 4.9.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> type([1,2])
<class 'list'>

How can I tweak IPython so that it shows the same output as "pure" Python3?

A: One needs to deactivate pretty printing:
%pprint


text:
Q: React - Dynamic AJAX loading HTML data not working in dangerouslySetInnerHTML I am not able to dynamically AJAX loaded HTML format data(as mentioned below) in dangerouslySetInnerHTML(ie., it is setting in DOM as the same string and not compiling). Please note that I am using axios plugin for AJAX API calls. When I try with the same HTML data giving statically in dangerouslySetInnerHTML, it is working perfectly. I don't know what is going there.
[{id: 1, image: "assets/img/news-sm.png", content: "
சிறுவனே!
"}]

My React Component code is
import React, { Component, PropTypes } from 'react';
import List from 'material-ui/List/List';
import ListItem from 'material-ui/List/ListItem';
import Divider from 'material-ui/Divider';
import { Media } from 'react-bootstrap';
import { map } from 'lodash';

class NewsList extends Component {
    constructor(props) {
        super(props);
    }

    handleListClick(d){
        console.log(d);
    }

    renderLoadingComponent() {
        return <ListItem style={{textAlign: 'center'}}>Loading...</ListItem>;
    }

    renderNothingFoundElement() {
        return <ListItem style={{textAlign: 'center'}}>Nothing found</ListItem>;
    }

    render() {
        const { data, loading } = this.props;

        return (
            <List className="list">
                {
                    map(data, (d, index) =>
                        React.Children.toArray([
                            <ListItem className="list-item">
                                <Media onClick={(ev) => this.handleListClick(d)} className="media-align">
                                    <Media.Left align="middle">

                                    </Media.Left>
                                    <Media.Body>
                                        {d.content &&

}
                                    </Media.Body>
                                </Media>
                            </ListItem>,
                            (index + 1) !== data.length ? <Divider /> : ''
                        ])
                    )
                }

                { loading ? this.renderLoadingComponent() : data.length === 0 ? this.renderNothingFoundElement() : '' }
            </List>
        )
    }
}

NewsList.propTypes = {
    data: React.PropTypes.array.isRequired
};

export default NewsList;

I am calling the above Component from another Component like this
import React, { Component, PropTypes } from 'react';
import NewsList from '../components/news-list';

class Home extends Component {
    constructor(props) {
        super(props);

        this.state = { ajaxData: [], ajaxLoading: false }
    }

    componentDidMount() {
        axios.get('/ajaxUrl')
            .then(response => this.setState({ajaxData: response.data}))
    }

    render() {
        return (
            <NewsList data={this.state.ajaxData} loading={this.state.ajaxLoading} />
        )
    }
}

Can someone please help me to solve this issue? Thanks.

A: Probably you have to specify The Component Lifecycle shouldComponentUpdate or forceUpdate or componentWillReceiveProps facebook.github.io
But you can also use a huck and set state in your Parent component to '' and on a callback set the NewList and pass props
this.setState({newList: ''},()=> this.setState({ newList: <NewList {...props}/>}))

Update The simple one
class Home extends Component {
constructor(props) {
    super(props);

    this.state = { ajaxData: [], ajaxLoading: false, newsList:'' }
}

componentDidMount() {
    axios.get('/ajaxUrl')
        .then(response => this.setState({ajaxData: response.data},
()=> this.setState({newsList: <NewsList data={this.state.ajaxData} loading={this.state.ajaxLoading} />})))
 }

render() {
    return (

 {this.state.newsList}

    )
}}

Also you can implement method for a life cycle
shouldComponentUpdate(nextProps, nextState) {
    return this.state.ajaxData != nextState.ajaxData;
  }


text:
Q: McEliece (FlexiProvider): How can i create KeyPair from byte array? I use Flexi Provider (for McEliece algorithm) to generate my public and private keys and then i saved it to file and now i need to load keypair from file, i can read file and get public key byte array and private key byte array but i don`t know how can i create KeyPair from it:
i use flexiprovider.de for McEliece Algorithm:
For Generating McEliece keys:
import de.flexiprovider.api.keys.KeySpec;
import de.flexiprovider.core.FlexiCoreProvider;
import de.flexiprovider.pqc.FlexiPQCProvider;
import de.flexiprovider.pqc.ecc.mceliece.McElieceKeyFactory;
import de.flexiprovider.pqc.ecc.mceliece.McElieceKeyPairGenerator;

public KeyPair generateKeyPair(){
    KeyPair kp = null;
    int KeySize = 256;
    Security.addProvider(new FlexiCoreProvider());
    Security.addProvider(new FlexiPQCProvider());

    try
    {

        McElieceKeyPairGenerator mcElieceKeyPairGenerator = new McElieceKeyPairGenerator();
        mcElieceKeyPairGenerator.initialize(KeySize, new SecureRandom());
        kp = mcElieceKeyPairGenerator.generateKeyPair();
    } catch (Exception e) {
        System.out.println(e.ToString());
    }
    return kp;
}

For Load KeyPair From Byte Array:
public KeyPair readKeyPair(byte[] privateKey, byte[] publicKey){
       //?? How can i create KeyPair
}

I try to use McElieceKeyFactory but i dont know how can i use it, It needs KeySpec (de.flexiprovider.api.keys.KeySpec) for generating Private Key and Public Key but de.flexiprovider.api.keys.KeySpec is abstract class and i can`t create new instance from it. so what should i do?
Edit 1:
Saved method:
public void writeFile(byte[] data, String fileName) throws IOException{
    FileOutputStream out = new FileOutputStream(fileName);
    out.write(data);
    out.close();
}

public void saveKeyPair(KeyPair keyPair){
    byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
    byte[] publicKeyBytes = keyPair.getPublic().getEncoded();

    writeFile(privateKeyBytes,"Private.key");
    writeFile(publicKeyBytes,"Public.key");
}

A: Please try the following code. Also notice that I don't directly use the key pair generator and key factory implemetations.
KeyPairGenerator mcElieceKeyPairGenerator = KeyPairGenerator.getInstance("McEliece");
mcElieceKeyPairGenerator.initialize(keysize, new SecureRandom());
kp = mcElieceKeyPairGenerator.generateKeyPair();

final byte[] publicKeyData = kp.getPublic().getEncoded();
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyData);
KeyFactory mcElieceKeyFactory = KeyFactory.getInstance("McEliece");
PublicKey regeneratedPublicKey = mcElieceKeyFactory.generatePublic(publicKeySpec);

final byte[] privateKeyData = kp.getPrivate().getEncoded();
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyData);
PrivateKey regeneratedPrivateKey = mcElieceKeyFactory.generatePrivate(privateKeySpec);


text:
Q: How to handle blog articles category labels not passing accessibility rules for labeling links that use the same text? Does anyone know how I should handle aria-labels on link labels that repeat dozens of time on a page? My website accessibility checker tool keeps flagging these elements as using the same link text for these labels and they require unique aria-labels. Problem is, all of the links go to the same generic pages and am not sure how to make the aria-labels specific enough.
Has anyone dealt with anything like this before and how did you handle it? I imagine I'd need a JS solution to inject aria-labels, but before I invest in a JS resource doing this for me does anyone know how I can make these specific enough to pass the checker but not confuse screen readers?
Screenshot of category labels for each article

A: There is no need for aria-labels and what you are doing is not an accessibility fail. You have to bear in mind the automated accessibility checkers are dumb (and in this case quite possibly wrong) and are only there to offer guidance on common accessibility fails.
The main reason you are seeing this is that the accessibility checker thinks that this is text like "read more" that is not descriptive of the end-point. It should pick up the fact that the end-point is the same but it obviously does not.
Using the same link text for links that go to the same page is encouraged:

It is a best practice for links with the same destination to have
consistent descriptions (and this is a requirement per Success
Criterion 3.2.4 for pages in a set). It is also a best practice for
links with different purposes and destinations to have different
descriptions.
Source: https://www.w3.org/TR/UNDERSTANDING-WCAG20/navigation-mechanisms-refs.html

Also one of the checks for success criterion 3.2.4 - Consistent Identification is:

Check that this associated text is identical for each user interface
component with the same function.
Source: https://www.w3.org/WAI/WCAG21/Techniques/general/G197.html

Assuming your articles are marked-up correctly a screen reader user could skip between headings (<h2>s for example) in order to not hear the same category links. This is one of the primary ways a screen reader user will navigate a page (via headings).
For this reason the categories should be AFTER the heading in the HTML so that they are read out after the heading.
You could place the heading visually after the tags using techniques similar to those in this answer I gave. This would be acceptable for "logical tab order" in my opinion so you wouldn't fail there.
Your only other option would be to use aria-hidden="true" and tabindex="-1" on your category links to hide them from screen reader users and take them out of the tab order. If you did this you would need to ensure a categories list is available at the side of the page.
Personally I would go with the first option as the categories information is useful to screen reader users, the fact the links repeat themselves over and over if I search by links would indicate they are categories to me when using a screen reader anyway.

A: In this case, it is correct to hide all duplicate links except for the first element that contains these labels
You force people with disabilities to navigate through all the same links using keyboard navigation, this is also bad for a screen reader
1.) Hide any duplicate labels from your screen reader
aria-hidden="true"

2.) Hide any duplicate labels from keyboard navigation
tabindex="-1"

Note! don't forget to leave one unique link! You can also hide everything and add them to context under elements or above elements. When I say hide, I mean the above methods.

It's easy to check for accessibility, close your eyes and imagine you click on a tab and hear (in a screen reader) a re-link through every two elements! This is annoying isn't it?


text:
Q: Defining and replacing variable based on input I am attempting to replace the input variable with user submitted channel name from the form input each time a new value is entered. So far, this just seems to break and not displaying anything. Any advice is very appreciated!

<form id="form" onsubmit="channelChanger()">
Channel: <input id="a" type="text">
<button type="submit" value="Submit" >Submit</button>
</form>

**UPDATED - onclick typo fixed and changed second input to button did not change the result. Also, added return function. Still unresponsive.

A: There's a typo in your 'onClick' prop. I also would have expected the element with the typo to be a button rather than a second input.
If you change those two things, what happens?


text:
Q: How do you save wcfg waveform data in Xilinx ISim clock cycle resolution I have a simulation that takes 4 hours to run and don't want to repeat it when I have to measure timing. Is there a way to save the data so that I can review it on demand.

A: The simulation data is store in a waveform database (.wdb) file. The waveform configuration file (.wcfg) contains only the selected signals and its display settings like radix, color, position, grouping, ...
So don't delete the *.wdb file and load/open it on your next run. Don't overwrite it :).


text:
Q: Issue with highlighting of button's border only in chrome When I click on button in chrome border of button highlights, How can solve this problem? Once more question when i click on IE there is nice click effect, text inside button moves, how can I do this for all browsers ?
here is jsfiddle http://jsfiddle.net/qhTzT/

please look via ie and chrome

A: Set
outline: 0;

However, the border is a usability issue set by the browser.

A: To solve the issue with the blue border in Chrome use
button:focus {
    outline:none;
}

That the text moves in IE is a built-in function of IE, and I don't have any idea how you can solve this.


text:
Q: Is there a Java equivalent for .Net System.Data? Is there a Java package providing funcionality like the .Net System.Data namespace ?
Specificaly the DataSet and Adaptor classes ?

A: Use java.util for the collections.
java.sql for databases.

A: The equivalent to ADO.NET is JDBC. You can get the flavor of it here:
http://www.heimetli.ch/jdbc/JDBCQuery.html

A: ADO.NET is a framework with multiple uses, and DataSet is one of the main abstractions. Tell us more about what you want to achieve, and I'm sure somebody will find a Java framework for that purpose.
If you want a simple way to map Java objects to a data backend (like XML files), take a look at some of the POJO (Plain Old Java Object) frameworks.

A: Hibernate is a popular framework in the Java world.  Pretty simple mapping of objects to tables and lots more.


text:
Q: Heisenbug in IE9 Okay StackOverflow - this is a weird one.
The Problem
So I have a "button" (really just a div with a javascript onclick listener) that gets its text from a database via json on page load. (It makes sense given the application). We are not supporting IE < 9.
The problem is that the text inside the div does not show up in a fresh instance of IE9. HOWEVER, when I open up the developer console (to try to figure out what went wrong) and refresh the page, IE acts as though nothing ever went wrong and populates the button text correctly. It works in every other browser.
What.
The Code
So here's what I have in PHP:

    ▶

Javascript (using Jquery 1.8.0):
$('document').ready(refreshNotificationButtons('.notification-button'));
function refreshNotificationButtons(buttons){
    var buttons = typeof buttons != 'object' ? $('.notification-button') : buttons;
    var allNotifications = {};
    var buttonsCount = 0;
    buttons.each(function(){
        var button = $(this);
        if(typeof button.attr('id') == 'undefined') button.attr('id', 'notif-button-' + buttonsCount);
        buttonsCount ++;
        if(typeof allNotifications[button.attr('data-notification')] == 'undefined'){
            allNotifications[button.attr('data-notification')] = [button.attr('id')];
        } else {
            allNotifications[button.attr('data-notification')].push(button.attr('id'))
        }
    });
    $.get(
        '/notifications/get_notifications/' + $.map(allNotifications, function(x, abbr){return abbr}).join(','),
        '',
        function(data){
            $(data).each(function(){
                if (typeof allNotifications[this.Notification.NotificationAbbr] != 'undefined'){
                    console.log(this); //debug
                    buttonEl = $('#' + allNotifications[this.Notification.NotificationAbbr]);
                    if(this.Notifications_User.UserID != null) buttonEl.addClass('notification-button-remove');
                    buttonEl.attr('data-notification-id', this.Notification.Notifications_TableID);
                    buttonEl.append($('' + this.Notification.EnableText + '' + this.Notification.DisableText + ''));
                }
            });
        },
        'json'
    );

}
Images
Button before opening dev console:

Button after opening dev console and refreshing:

Conclusion
Any ideas? I'd be happy to post more code if you would like to see it! Thanks in advance.

A: As commented above, console.log() doesn't work so well in IE when there is no console open to write to.
You can either remove the calls to console, or add in this plugin (developed by Paul Irish)
http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/

A: IE only has a console object when the debugger is active.
So, when you try to do console.log() and there is no console object, it throws a javascript exception as it tries to reference the .log property of undefined and your code stops executing.
You can work around that by inserting this in your initialization code - somewhere before you use console.log().
var console = console || {};
if (!console.log) {
    console.log = function(data) {
        // do nothing
    }
}

This just makes it safe to always use console.log(), even in IE when the debugger isn't running.  I wouldn't recommend leaving console.log() statements in finished production code, but it might help you during development.


text:
Q: iis6 which app pool does each w3wp belong to? I have a run away worker process.
Which of the 10ish sites on this box is it thats going nuts?
How can I determine from the pid of the worker process which site he is?

A: run
>c:\windows\system32\cscript iisapp.vbs

it outputs the pids and the names of the app pools associated.


text:
Q: Probability of having ANY of (at least one of) $\{1,2,3\}$ in a random draw of $n$ numbers (without replacement) from $\{1,2,...,100\}$? As the questions says, what is his probability?
I need to sample $n$ numbers from ${1,2,...,100}$ and find the probability of this sample of $n$ numbers containing any of${1,2,3}$?
My work so far is that we have $\binom{100}{n}$ different combinations. The possible events are:
$99*98*...*(100-n)$ contain 1
$99*98*...*(100-n)$ contain 2
$99*98*...*(100-n)$ contain 3
But I'm having trouble with how to overcome the double counting when considering those that contain ${1,2}, {1,3}, {2,3}$ and ${1,2,3}$?
Thanks

A: P(At least one draw <= 3) = 1 - P(All Draws >3)
In order for all the draws to be greater than 3, you must have a number larger than 3 for your first pick, and a number larger than 3 for your second pic etc.
Since you have 100-3=97 numbers larger than 3, you have:
97*96*95*...*(97-(n-1)) ORDERED ways of doing this, just by choosing one of the 97 for the first draw, then one of the 96 for the second draw etc.
so P(All Draws > 3)= 97*96*95*...*(97-(n-1)) / 100Cn
And your answer follows


text:
Q: Why does Newton's Third Law not preclude any motion at all? When walking, if I apply a force of 2N on the earth, the earth applies a force of 2N back on my feet due to Newtons 3rd Law of Motion. These 2 forces are equal in magnitude but opposite in direction, so they negate each other and add up to zero. So how can we move then if the net force adds up to zero?

A: In a sense your question is entirely apropos. The critical distinction to be made, however, is that the two forces can only be summed to zero if we are talking about the two-body system. Each body, considered in isolation, experiences an unbalanced force and thus experiences accelerated motion. The system, however, only experiences mutually-canceling internal forces. That is to say, a pair of equal and opposite forces internal to a system cannot cause an acceleration of the center of mass of that system. Ergo, even though the individual bodies are free to move without limit, the center of mass of the system will not move so long as a net external force is absent.


text:
Q: Reading wav files in a folder with Python Here is my code :
for filename in glob.glob('*.wav') :
    for i in range(10) :
        sr[i],x[i]=scipy.io.wavfile.read(filename)

I want to read .wav files in a folder and save their values on x and also their sampling rates on sr. But my code gives error: "list assignment index out of range". How can I fix it? I am using python2.7 on ubuntu.

A: I could be wrong but I'm guessing it'll be the line:
sr[i],x[i] = scipy.io.wavfile.read(filename)

I don't think you'll be able to index the results like that as I dont think they're lists.
try this instead:
sr, x = scipy.io.wavfile.read(filename)

If you need a list of the sr and x values, try defining the lists before reading the files. Append the results individually to each of your lists. There is probably a clever way of writing this, but for clarity I'll just do it like this:
sr = []
x = []

for filename in glob.glob('*.wav'):
    for i in range(10):
        sr_value, x_value = scipy.io.wavfile.read(filename)
        sr.append(sr_value)
        x.append(x_value)

I'd also maybe recommend renaming your sr and x (particularly x) variables to something more meaningful. It might make your code a bit easier to read and it could save you a few naming conflicts later down the line.


text:
Q: Extracting data from a Solar Inverter, UDP Broadcast? First post here, so please let me know if any extra detail would be useful.
I am trying to extract data from a WiFi enabled Solar PV inverter (e.g. Power generation vs time,  Energy generated today, battery charge level etc).
There is an android app in the playstore called kstarmg which does some of this already but only works when connected to the local network, so not accessible via the Internet. I want to write something to run on a local machine (raspberry pi) that logs data from the inverter and updates a web page. My first thought is to use python.
I have managed to decompile the android app apk and so far as I can see it uses a UDP broadcast to communicate with the inverter. So far as I can see it sends some text "WIFIKIT-214028-READ" on port 48899. I have managed to see this text by listening with nc on the raspberry pi. I am struggling to work out how to read responses from the inverter. Can anyone point me towards how I can determine how to read data from the inverter?
I tried the following in python but got nothing back:
import socket
import struct

import sys
message = 'WIFIKIT-214028-READ'
multicast_group = ('224.3.29.71', 48899)
# Create the datagram socket                                                                                sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Set a timeout so the socket does not block indefinitely when trying to receive data.
sock.settimeout(20)
# Set the time-to-live for messages to 1 so they do not go past the local network segment.                       ttl = struct.pack('b', 1)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
try:
    # Send data to the multicast group
    print >>sys.stderr, 'sending "%s"' % message                                                                     sent = sock.sendto(message, multicast_group)
    # Look for responses from all recipients                                                                         while True:
        print >>sys.stderr, 'waiting to receive'
        try:
            data, server = sock.recvfrom(16)
        except socket.timeout:
            print >>sys.stderr, 'timed out, no more responses'                                                               break
        else:
            print >>sys.stderr, 'received "%s" from %s' % (data, server)
finally:                                                                                print >>sys.stderr, 'closing socket'
    sock.close()

Some of the lines from the android apk that seem relevant are:
package com.kstar.common;

import android.util.Log;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public abstract class UdpBroadcast {
    private static final int BUFFER_SIZE = 100;
    private static final String TAG = "UdpBroadcast";
    private InetAddress inetAddress;
    private DatagramPacket packetToSend;
    private int port;
    private ReceiveData receiveData;
    private DatagramSocket socket;

    /* renamed from: com.kstar.common.UdpBroadcast.1 */
    class C00521 extends Thread {
        C00521() {
        }

        public void run() {
            DatagramPacket packet = new DatagramPacket(new byte[UdpBroadcast.BUFFER_SIZE], UdpBroadcast.BUFFER_SIZE);
            long time = System.currentTimeMillis();
            while (System.currentTimeMillis() - time < 300) {
                try {
                    UdpBroadcast.this.socket.receive(packet);
                } catch (Exception e) {
                }
            }
            try {
                Log.i(UdpBroadcast.TAG, "--UdpBroadcast Send:  ------------>" + new SimpleDateFormat("hh:mm:ss").format(new Date()));
                UdpBroadcast.this.socket.setSoTimeout(1000);
                UdpBroadcast.this.socket.send(UdpBroadcast.this.packetToSend);
            } catch (IOException e2) {
                e2.printStackTrace();
            }
            UdpBroadcast.this.receiveData = new ReceiveData(null);
            Log.i(UdpBroadcast.TAG, "--UdpBroadcast receiveData:  ------------>" + new SimpleDateFormat("hh:mm:ss").format(new Date()));
            UdpBroadcast.this.receiveData.start();
        }
    }

    private class ReceiveData implements Runnable {
        private List<DatagramPacket> packets;
        private boolean stop;
        private Thread thread;

        private ReceiveData() {
            this.thread = new Thread(this);
            this.packets = new ArrayList();
        }

        public void run() {
            this.stop = false;
            while (!this.stop) {
                try {
                    DatagramPacket packetToReceive = new DatagramPacket(new byte[UdpBroadcast.BUFFER_SIZE], UdpBroadcast.BUFFER_SIZE);
                    UdpBroadcast.this.socket.receive(packetToReceive);
                    this.packets.add(packetToReceive);
                } catch (SocketTimeoutException e) {
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
            if (!this.stop) {
                UdpBroadcast.this.onReceived(this.packets);
            }
            this.stop = true;
        }

        void start() {
            this.thread.start();
        }

        void stop() {
            this.stop = true;
        }

        boolean isStoped() {
            return this.stop;
        }
    }

    public abstract void onReceived(List<DatagramPacket> list);

    public void setPort(int port) {
        this.port = port;
    }

    public UdpBroadcast() {
        this.port = Constant.UDP_PORT;
        this.socket = null;
        try {
            this.inetAddress = InetAddress.getByName("255.255.255.255");
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    public void open() {
        try {
            if (this.socket == null) {
                this.socket = new DatagramSocket(this.port);
                this.socket.setBroadcast(true);
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    public void close() {
        stopReceive();
        if (this.socket != null) {
            this.socket.close();
            this.socket = null;
        }
    }

    public void send(String text) {
        if (this.socket != null && text != null) {
            text = text.trim();
            this.packetToSend = new DatagramPacket(text.getBytes(), text.getBytes().length, this.inetAddress, this.port);
            try {
                this.socket.setSoTimeout(500);
                stopReceive();
                new C00521().start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void stopReceive() {
        if (this.receiveData != null && !this.receiveData.isStoped()) {
            this.receiveData.stop();
        }
    }
}

I am struggling to work out what to do next to work out what is going on so any advice would be very gratefully received
Thanks
Graham

A: I managed to do it with PHP in order to change the timers on the inverter, maybe this will help.
First I installed a packet sniffer (I used HttpCanary) to find the command to change timers.
For example "AA55B07F02390B0701040E00173BFFF1FF7F064E" would set the 1st timer to 14:00.
And I used the following function, most of it picked from here
function send_socket(){
$server = '137.134.128.220';
$port = 13435;
$return="Not OK";
if(!($sock = socket_create(AF_INET, SOCK_DGRAM, 0))){
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    $return="Couldn't create socket: [$errorcode] $errormsg";
    return $return;
}
$return="Socket created";

$output = hex2bin("AA55B07F02390B0701040E00173BFFF1FF7F064E");//start at 2

//Send the message to the server
if( ! socket_sendto($sock, $output , strlen($output) , 0 , $server , $port)){
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    $return="Could not send data: [$errorcode] $errormsg";
    return $return;
}

//Now receive reply from server and print it
if(socket_recv ( $sock , $reply , 2045 , MSG_WAITALL ) === FALSE){
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    $return="Could not receive data: [$errorcode] $errormsg";
    return $return;
}

$return=bin2hex($reply);
echo "Reply: $return";
if ($return=="aa557fb002b9010602f0"){
    $return="Success";
}
return $return;
}


text:
Q: vsftpd настроил как советуют — не работает
*

*Сервер: ubuntu server 16.--, installed( apache2 php mysql-server phpmyadmin ubuntu-desktop mc vsftpd ).

*Ноутбук: windows 10.

*Роутер: TP-Link TL-WR741N, имеются следующие настройки:

*

*Переадресация/Виртуальные серверы:

*

*80/80 - 192.168.0.101,

*443/443 - 192.168.0.101;

*DHCP/Резервирование адресов:
**mac* - 192.168.0.101.
Проблема: Сделал вроде все по различным статьям которые нашел в сети (не буду перечислять потому как пробовал раз шесть), итог один: не зайти с ноутбука на сервер по FTP, что бы я там в конфигах не писал (в принципе во всех статьях одно и тоже за небольшими исключениями).
Не подключается ни через локальный IP, ни через внешний. Не подключение выражается, через браузер — «не удается получить доступ к сайту», через сетевое окружение — «не удается установить связь с сервером».
Как устроена сеть:

*

*К роутеру подключен компьютер с ubuntu server при помощи провода, за ним зарезервирован адрес 192.168.0.101.

*Ноутбук подключен через сеть вайфай к этому же роутеру, за ним закрепен адрес 192.168.0.102.
И вводя на ноуте ftp://192.168.0.101 ничего не происходит. Вводя на компе ftp://127.0.0.1 все нормально заходит.

A: NB: Связисты обычно рекомендуют не крутить сразу две ручки.
У вас может быть допущена не одна ошибка, а сразу несколько. Поэтому поиск неисправностей нужно вести последовательно и исключать проблемы одну за другой.
Раз у вас локально ftp виден - пробуем проверить, видно ли в локальной сети. И только потом уже будем проверять видимость извне, из интернета - правильно ли проброшено на роутере.
Я бы предложил отключить настройки роутера, но поскольку можно их неправильно отключить - то могу предложить самый простой вариант: соедините ноутбук с компьютером кроссоверным кабелем.
Это минимальная сеть на два IP-адреса, роутер не нужен.
Если удалось увидеть нормально -- значит, пора разбираться с тем, что понакрутили из настроек роутера.
Если не видится -- значить, надо разбираться с firewall. Иначе как это: апач видится, пинги идут - а ftp видится только локально.

A: Если nmap не видит FTP сервера, то скорее всего это означает что он закрыт файерволлом. Открыть можно, например, так:
iptables -I INPUT -p tcp -m tcp --dport ftp -j ACCEPT
iptables -I INPUT -p tcp -m tcp --dport ftp-data -j ACCEPT

Для более постоянного решения изучите настройку iptables в вашем дистрибутиве.


text:
Q: Pass list of one of two structures to the function New in Go, couldn't find any intuitive way of doing that.
I have such piece of code
tx = getTx()
for _, record := range tx.a {
    // do a lot with record.Important
}
for _, record := range tx.b {
    // do a lot with record.Important
}
for _, record := range tx.c {
    // do a lot with record.Important
}

And the following structs:
type Record1 struct {
    // fields of Record1
    Important string
}
type Record2 struct {
    // fields of Record1
    Important string
}
type TX struct {
    a []Record1
    b []Record1
    c []Record2
}

Now the logical is to extract every for logic into the function:
func helper(records) { // Here is the problem
   // do a lot with record.Important
}

Problem:
records is a []Record1 or []Record2 type. But it looks like Union types doesn't exists in Golang. So I thought I could pass []string into the helper, but cannot even find an elegant way to get something equivalent to map(lambda r: r.Important, tx.a). There is no high order map function, no list comprehesion. I am not convinced to use raw for loop to solve that.

A: One approach to do the loop across multiple types is to use interfaces together with generics. Have each Record type implement a getter method for the important field. Then declare an interface that includes that getter method in its method set. Then you can make your helper generic by declaring the interface as its type parameter.
func (r Record1) GetImportant() string { return r.Important }
func (r Record2) GetImportant() string { return r.Important }

type ImportantGetter interface {
     GetImporant() string
}

func helper[T ImportantGetter](s []T) {
    for _, v := range s {
        _ = v.GetImportant()
    }
}

A: Unless I'm misunderstanding your question, it seems like you want to extract all the values in column X from a set of records and then pass those values in as a slice to some function - I'm basing my assumption on your wish that go had something like map().
If what you're after is type-agnosticism, you could certainly use an interface approach like that suggested by mkopriva, but you aren't going to get out of using a for loop - iteration over list types is core to idiomatic go.  If you need a mapping function, you're going to have to write one that performs the mapping you want.
I'd note that you do not need generics to do what mkopriva suggests, you can just use an interface without muddying the waters with generics go playground:
package main

import "fmt"

type Record1 struct {
    Important string
}

type Record2 struct {
    Important string
}

func (r Record1) GetImportant() string { return r.Important }
func (r Record2) GetImportant() string { return r.Important }

type ImportantGetter interface {
    GetImportant() string
}

func helper(s []ImportantGetter) {
    for _, v := range s {
        fmt.Println(v.GetImportant())
    }
}

func main() {
    records := []ImportantGetter{Record1{Important: "foo"}, Record2{Important: "bar"}}

    helper(records)
}

Another approach to the type-agnosticism, and one that's a bit more (IMHO) idiomatic for "I expect all of these types to have a common property," is to use struct embedding and type assertions to build your own Map() function up go playground:
type CommonFields struct {
    Important string
}

type Record1 struct {
    CommonFields
    FieldSpecificToRecord1 string
}

type Record2 struct {
    CommonFields
    FieldSpecificToRecord2 int
}

func main() {
    r1 := Record1{
        CommonFields{Important: "I'm r1!"},
        "foo",
    }

    r2 := Record2{
        CommonFields{Important: "I'm r2!"},
        5,
    }

    records := []interface{}{r1, r2, "this is not a valid record type"}

    fmt.Println(Map(records))

}

func Map(source []interface{}) []string {
    destination := make([]string, len(source))
    for i, sourceRecord := range source {
        if rr, ok := sourceRecord.(Record1); ok {
            destination[i] = rr.Important
        } else if rr, ok := sourceRecord.(Record2); ok {
            destination[i] = rr.Important
        } else {
            destination[i] = "undefined"
        }
    }
    return destination
}

You'd likely want to make your implementation of Map() accept an argument specifying the field to extract to conform to what you have in other languages, or possibly even just pass in a helper function which does most of the type-specific value extraction.


text:
Q: Accessing and adding shared contacts Sharepoint server Today i am faced with a problem that the company i work for is going to try to centralize their global sales team`s contacts to a SharePoint server.
There are 2 parts to my question,
Firstly is there a web server or API i can use to programatically add contacts which i have stored on a local database to the sharepoint shared contacts list?
Secondly is there a web service which i can plug into to do the reverse? basically the plan is one the sales team have been using it for a while they would like a way in which we can use that contact information for analytics.
Thanks

A: SharePoint has numerous Web services. The Lists Web service will probably the one you need (2007, 2010). Start with the GetListItems and UpdateListItems methods.
Additionally, SharePoint 2010 supports a JavaScript client object model.


text:
Q: HorizontalPodAutoscaler: missing field "conditions" Friends, I am trying to implement a HPA following the hpa tutorial of k8s and I am having the following error:
ValidationError(HorizontalPodAutoscaler.status): missing required field "conditions" in io.k8s.api.autoscaling.v2beta2.HorizontalPodAutoscalerStatus.
I couldn't find anything about this field "conditions". Does someone have an idea what I may be doing wrong? Here its the YAML of my HPA:
apiVersion: autoscaling/v2beta2
kind: HorizontalPodAutoscaler
metadata:
  name: {{ .Values.name }}
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: {{ .Values.name}}
  minReplicas: {{ .Values.deployment.minReplicas }}
  maxReplicas: {{ .Values.deployment.maxReplicas }}
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 50
status:
  observedGeneration: 1
  lastScaleTime: <some-time>
  currentReplicas: 2
  desiredReplicas: 2
  currentMetrics:
  - type: Resource
    resource:
      name: cpu
      current:
        averageValue: 0

And here the manifest of my deployment:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ .Values.name }}
spec:
  replicas: {{ .Values.deployment.replicaCount }}
  selector:
    matchLabels:
      app: {{ .Values.labels}}
  template:
    metadata:
      annotations:
        checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}
      labels:
        app: {{ .Values.labels }}
    spec:
      initContainers:
      - name: check-rabbitmq
        image: {{ .Values.initContainers.image }}
        command: ['sh', '-c',
        'until wget http://$(RABBITMQ_DEFAULT_USER):$(RABBITMQ_DEFAULT_PASS)@rabbitmq:15672/api/aliveness-test/%2F;
        do echo waiting; sleep 2; done;']
        envFrom:
        - configMapRef:
            name: {{ .Values.name }}
      - name: check-mysql
        image: {{ .Values.initContainers.image }}
        command: ['sh', '-c', 'until nslookup mysql-primary.default.svc.cluster.local; do echo waiting for mysql; sleep 2; done;']
      containers:
      - name: {{ .Values.name }}
        image: {{ .Values.deployment.image }}
        ports:
        - containerPort: {{ .Values.ports.containerPort }}
        resources:
          limits:
            cpu: 500m
          requests:
            cpu: 200m
        envFrom:
        - configMapRef:
            name: {{ .Values.name }}

A: Background
Not sure, why you want to create HPA with status section. If you would remove this section it will create HPA without any issue.
In documentation Understanding Kubernetes Objects - Object Spec and Status you can find information:

Almost every Kubernetes object includes two nested object fields that govern the object's configuration: the object spec and the object status. For objects that have a spec, you have to set this when you create the object, providing a description of the characteristics you want the resource to have: its desired state.

The status describes the current state of the object, supplied and updated by the Kubernetes system and its components. The Kubernetes control plane continually and actively manages every object's actual state to match the desired state you supplied.

Your situation is partially described in Appendix: Horizontal Pod Autoscaler Status Conditions

When using the autoscaling/v2beta2 form of the HorizontalPodAutoscaler, you will be able to see status conditions set by Kubernetes on the HorizontalPodAutoscaler. These status conditions indicate whether or not the HorizontalPodAutoscaler is able to scale, and whether or not it is currently restricted in any way.

Example from my GKE test cluster
As I mention before, if you will remove status section, you will be able to create HPA.
$ kubectl apply -f - <<EOF
> apiVersion: autoscaling/v2beta2
> kind: HorizontalPodAutoscaler
> metadata:
>   name: hpa-apache
> spec:
>   scaleTargetRef:
>     apiVersion: apps/v1
>     kind: Deployment
>     name: php-apache
>   minReplicas: 1
>   maxReplicas: 3
>   metrics:
>   - type: Resource
>     resource:
>       name: cpu
>       target:
>         type: Utilization
>         averageUtilization: 50
> EOF
horizontalpodautoscaler.autoscaling/hpa-apache created

Following HPA documentation, I've created PHP Deployment.
$ kubectl apply -f https://k8s.io/examples/application/php-apache.yaml
deployment.apps/php-apache created
service/php-apache created

When you executed command kubectl autoscale you have created HPA for deployment php-apache
$ kubectl autoscale deployment php-apache --cpu-percent=50 --min=1 --max=10
horizontalpodautoscaler.autoscaling/php-apache autoscaled

Now you are able to see hpa resource using kubectl get hpa or kubectl get hpa.v2beta2.autoscaling. Output is the same.
First command will show all HPA objects with any apiVersion (v2beta2, v2beta1, etc), second command will show HPA only with apiVersion: hpa.v2beta2.autoscaling. My cluster as default is using v2beta2 so output of both commands is the same.
$ kubectl get hpa
NAME         REFERENCE               TARGETS   MINPODS   MAXPODS   REPLICAS   AGE
php-apache   Deployment/php-apache   0%/50%    1         10        1          76s
$ kubectl get hpa.v2beta2.autoscaling
NAME         REFERENCE               TARGETS   MINPODS   MAXPODS   REPLICAS   AGE
php-apache   Deployment/php-apache   0%/50%    1         10        1          84s

When execute command below, new file with hpa configuration will be created. This file is based on already created HPA from previous kubectl autoscale command.
$ kubectl get hpa.v2beta2.autoscaling -o yaml > hpa-v2.yaml
# If I would use command `kubectl get hpa hpa-apache > hpa-v2.yaml` file would look the same
$ cat hpa-v2.yaml
apiVersion: v1
items:
- apiVersion: autoscaling/v2beta2
  kind: HorizontalPodAutoscaler
  metadata:
...
status:
    conditions:
    - lastTransitionTime: "2020-12-11T10:44:43Z"
      message: recent recommendations were higher than current one, applying the highest
        recent recommendation
      reason: ScaleDownStabilized
      status: "True"
      type: AbleToScale
      ...
    currentMetrics:
    - resource:
        current:
          averageUtilization: 0
          averageValue: 1m

Conclusion
The status describes the current state of the object, supplied and updated by the Kubernetes system and it's components.
If you want to create resource based on YAML with status, you have to provide value in status.conditions, where condition require array value.
status:
  conditions:
  - lastTransitionTime: "2020-12-11T10:44:43Z"

Quick solution
Just remove status section, from your YAML.
Let me know if you still encounter any issue after removing status section from YAML manifest.


text:
Q: Skip kerberos sso authentication in keycloak In certain cases we need to skip automatic login through Kerberos.
According to the documentation this should be done through the parameter ?prompt=login:

prompt - Keycloak supports these settings:

*

*login - SSO will be ignored and the Keycloak login page will be always shown, even if the user is already authenticated

This works in most cases (we also use a NTLM waffle implementation) but with Kerberos the user is always signed in automatically.
Any hint or idea why? Are there alternative ways to force forwarding to the login page?
EDIT: The reason I need to skip the Kerberos authentication is because I need to login with an admin-account where I have to enter username+password.
EDIT2: We are using Keycloak.x version 14.0.0, also applies to version 15.0.2.

A: The parameter ?prompt=login will only skip the Cookie authenticator in your authentication flow. Execution of the Cookie authenticator will be marked as attempted but not as successful. So Keycloak will fallback to an alternative authenticator. I am assuming the Kerberos authenticator is configured as an alternative. If this is the case, you will be (automatically) authenticated by the Kerberos authenticator.
If you only need this behaviour for a particular client, you may want to create an additional authentication flow for that client without the Kerberos authenticator. Use Authentication flow overrides to configure the new flow for the client.

A: I just created a feature-request with a possible solution on the code side.
skip kerberos SSO authentication to use login-form
Might be able to override the default SpnegoAuthenticator with a custom one containing the login parameter handling.
I patched and tested it in a kerberos environment and it worked.
@Override
public void authenticate(AuthenticationFlowContext context) {
// +++ BEGIN CHANGE +++
    AuthenticationSessionModel session = context.getAuthenticationSession();
    Map<String, String> clientNotes = session.getClientNotes();

    if ("login".equals(clientNotes.get("prompt"))) {
        logger.info("skip SPNEGO authenticator because of client requests login prompt: " + clientNotes); //$NON-NLS-1$
        context.attempted();
        return;
    }
// +++ END CHANGE +++

    HttpRequest request = context.getHttpRequest();
    String authHeader = request.getHttpHeaders().getRequestHeaders().getFirst(HttpHeaders.AUTHORIZATION);
    if (authHeader == null) {
        Response challenge = challengeNegotiation(context, null);
        context.forceChallenge(challenge);
        return;
    }


text:
Q: Windows batch script to copy largest file and by pattern Can anyone tell me how to create a batch file to do the following:

*

*Create a folder in the following date format MMDDYYYY

*Search the current directory for the largest file and copy it into the folder that was created in step 1.

*Also search the current directory for a second file which matches the largest file which was found and copy it into the directory created in step 1.

For example:
file1test.txt (3kb)
file2test.txt (10 kb)
file1test.log (2kb)
file2test.log (2kb)

file2test.txt is selected and copied into the folder since it is the largest file and file2test.log is selected and copied into the same folder as well since it matches the pattern of the largest file.

A: as Andriy already pointed out, there are three questions on your post, and First and Second are already answered in SO.
To solve your latest problem, you need to iterate with FOR over the list of files and compare just the part of the filename you want to match.
To help you and get you started, see at the following sample code. I assume from your example that you want to just take the name part, without extension, and I am assuming for this example that the extensions you want are .log and .txt. You will have to complete with the folder part, change and extend it to fit your needs. And, as an added bonus, for this sample to be understendable, I had to solve your second problem too, sorry :)
@echo off
setlocal enabledelayedexpansion enableextensions
set destfolder=Folder01012001
set largest=
set largestname=
set /a largestsize=0
for %%a in (*.txt) do (
  if %%~za gtr !largestsize! (
    set largest=%%a
    set largestname=%%~na
    set /a largestsize=%%~za
  )
)
set match=
for %%a in (*.log) do (
  if %%~na==!largestname! (
    set match=%%a
  )
)
echo copy "!largest!" %destfolder%
echo copy "!match!" %destfolder%
endlocal


text:
Q: Azure Data Factory from On-Premises PostgreSQL I'm trying to create a Linked Service connection in ADF from an on-premises PostgreSQL to Azure DW.  I've selected the PostgreSQL connection type, but am unable to establish an ODBC connection -

"Connection refused.  Cannot connect to host"

which I think is expected considering the PostgreSQL server is on a different cloud network.
What steps do I need to take in order to create a connection between the two?  Can I create ADF Pipelines directly thereafter, or do I need to create an SSIS Runtime and work with SSIS packages only?

A: Since you want to transfer data from on-premises PostgreSQL to Azure DW, i think you need to create and configure a self-hosted integration runtime.As the statements you could find in this document:

A self-hosted IR is capable of running copy activity between a cloud
  data stores and a data store in private network.

Please follow the steps to create Self-hosted IR:https://learn.microsoft.com/en-us/azure/data-factory/create-self-hosted-integration-runtime#install-and-register-self-hosted-ir-from-the-download-center
BTW,according to this document,PostgreSQL only supports source link,not for sink, which is suitable for you.


text:
Q: hashmap being re-used by new objects I have an issue with a hashmap which is being reused by new objects and I can't seem to figure out how to give each new object its own hashmap. So essentially, when I generate a time table and I save it etc, when it comes to make the next time table, it uses the same roomList, i.e. the int[][] part of the hashmap for some rooms are already booked (which has been taken from the previous time table generated). What I want is an indiv object with a unique time table, unique list of rooms and the arr.
Below is my code:
The first is a class which generates a population of time tables.
public population(int size, boolean init, ArrayList<ListOfObj> arr, HashMap<Room, int[][]> roomList){
        listOfTables = new Tables[size];
        if(init){
            for(int i=0; i<listOfTables.length; i++){
                IndivTables indiv;
                CompleteTable[][][] table = new CompleteTable[5][9][];
                indiv = new IndivTables (arr,roomList,table);
                saveIndiv(i, indiv);
            }
        }
    }

The second is the actual class which creates the time tables.
    private CompleteTable[][][] timetable;
    private HashMap<Room, int[][]> roomList;
    private ArrayList<listOfObj> arr;

    public IndivTables (ArrayList<ListOfObj> arr, HashMap<Room, int[][]> roomList, CompleteTable[][][] table){
        this.arr = arr;
        table = generate(arr, roomList);
        this.timetable = table;
        this.roomList = roomList;
    }

Below is the function that creates the time table. This is in the same class as IndivTables.
    public static CompleteTable[][][] generate(ArrayList<ListOfObj> arr, HashMap<Room, int[][]> roomList){

        int rows = 5;
        int columns = 9;
        CompleteTable[][][] timeTable = new CompleteTable[rows][columns][];
        HashMap<Room, int[][]> roomListAll = new HashMap<Room, int[][]>(roomList);

        Random random = new Random();

        ListOfObj randomObj;

        Iterator<ListOfObj > iterator = arr.iterator();
        while(iterator.hasNext()){

            boolean clash = false;

            //Get random ListOfObj object
            randomObj= arr.get(random.nextInt(arr.size()));

            //Allocate room based on most efficient - doesn't do anything to hashmap
            Room room = allocateRoom(roomListAll, randomObj, row, column);
            if(room != null){
                CompleteTable comp = new CompleteTable(randomObj, room);

                if(timeTable[row][column] != null && timeTable[row][column].length>0){
                    if(!clash){
                    int[][] val = roomListAll.get(room);
                    val[row][column] = 1;
                    roomListAll.put(room, val);
                }
             }else{
                int[][] val = roomListAll.get(room);
                val[row][column] = 1;
                roomListAll.put(room, val);
                clash = false;
             }

             if(!clash){
               arr.remove(randomObj);
             }
          }
       }
    }
}
  }
 }
   return timeTable;
 }

Thanks in advance for any help!!

A: You are using same hashmap reference to create new IndivTables in the for loop iteration. Hence it's using same HashMap.
Change the following line new IndivTables (arr,roomList,table) to
new IndivTables (arr, new HashMap(), table);
However, if you want to retain the content of roomList, then do this
new IndivTables (arr, new HashMap(roomList), table);
Please note, this is shallow copy and not deep copy.


text:
Q: In correct answer from doc2vec I execte doc2vec model for text similarity
my code and not obtain reslt
it = LabeledLineSentence(datafiles, labels1)

model = gensim.models.Doc2Vec(vector_size=300, min_count=0, alpha=0.025, min_alpha=0.025)
model.build_vocab(it)

#training of model

for epoch in range(100):
    print ('iteration '+str(epoch+1))
    model.train(it,total_examples=model.corpus_count,
                epochs=model.epochs)

    model.alpha -= 0.002
    model.min_alpha = model.alpha

#saving the created model
model.save('doc2vec.model')
print ("model saved")

#loading the model
d2v_model = gensim.models.doc2vec.Doc2Vec.load('doc2vec.model')

#start testing
seed_text = "consider illegal immoral plagiarism do various"
tokens1 = seed_text.lower().split()
vector1 = d2v_model.infer_vector(tokens1)

#to get most similar document with similarity scores using document-index
most_similar = d2v_model.docvecs.most_similar(positive = [vector1] )

# output_sentences(most_similar)
print(u'%s %s: %s\n' % ("Most", most_similar[0][1], data[int(most_similar[0][0])]))

It output
Most 0.14691241085529327: M
why not print data bt only M what mean , what can i do to solve the problem
Regards

A: You're using a version of LabeledLineSentence that doesn't match the code that used to be in Gensim. Your version is taking an extra labels1 argument. So, it's non-standard and you should show its code or explain what online example you're basing your code on. Similarly, it's not clear what the values, or indirect contents, of datafiles and labels1 might be.
The M in the output is the result of your code data[int[most_similar[0][0])]. Your code doesn't show what data is, but perhaps it's a string, and the character M is in whatever position int(most_similar[0][0]) evaluates to.
(The value of most_similar[0][0] should be the document-tag that's most-similar to your inferred text-vector, which might be an int or string, depending on how you prepared your training data, in the unshown LabeledLineSentence code. There must have been a document in the trining set with that as a tag.)
The number 0.14691241085529327 is the amount of similarity. That's not very much, so your probe inferred text isn't very similar to any training document. (Perhaps that's indicative of some other problem.)
Your code also shows a few bad practices:

*

*calling train() more than once & using non-default min_alpha you're manipulating yourself - see answer My Doc2Vec code, after many loops of training, isn't giving good results. What might be wrong? for more details

*setting min_count=0 - almost always a bad idea, Doc2Vec & similar algorithms benefit from ignoring rare words

*using a large vector_size=300 - this would only be appropriate with some very large training corpus, the kind you'd most likely use a much-larger-than-default min_count on, and attempt only after gaining success with smaller experiments

I suggest you not trust or use whatever online article motivated this code, & instead start from examples inside the Gensim docs, gradually building them towards your need.
Other generic good steps:

*

*enable logging at the INFO level, watch the output: it may hint at steps that aren't behaving (via progress counts or timing) the way they should

*double-check your inputs, especially the it you've created.

For example, if you run:
first_item = next(iter(it))
print('tags: %s\nwords: %s' % (first_item.tags, first_item.words))

Does it print the 1st document you intended to use as training material, with the right words and tags? If not, you've got problems in your data source.


text:
Q: pug for loop - trying to dynamically create # of li items via a number passed in by mixin argument I'm trying to dynamically create a number of lis equals to the number passed in by a mixin. I tried using for loops, but nothing is being generated.
Here is what the mixin looks like:
mixin grid-content(liCount,itemTitle1, itemDescriptionTitle1, itemDescription1, itemTitle2, itemDescriptionTitle2, itemDescription2, itemTitle3, itemDescriptionTitle3, itemDescription3)
    - var count = liCount
    .grid-content
        .container
            .row
                ul.grid-content__list.grid-content__list--not-news
                    each val in count
                        li.grid-content__item
                            h1.item-title=itemTitle+count
                            .item-content
                                h3.item-description-title=itemDescriptionTitle+count
                                p.item-description=itemDescription+count

A: There are many things going on here. First, consider the following:
Say count = 3. One might think p= itemTitle+count is equivalent to p= itemTitle3, but it's not. Instead, it looks for a variable called itemTitle and tries to sum its value with a variable called count, which doesn't seem to be what you're trying to do.
If you're trying to create a mixin that can easily accept any number of grid items, consider passing an array of objects.
You might consider an approach like this:
// My Grid items

-
  var myGridItems = [
    {
      title: 'Item One Title',
      description: {
        title: 'Item One Description Title',
        contents: 'Item One Description Contents'
      }
    },
    {
      title: 'Item Two Title',
      description: {
        title: 'Item Two Description Title',
        contents: 'Item Two Description Contents'
      }
    },
    {
      title: 'Item Three Title',
      description: {
        title: 'Item Three Description Title',
        contents: 'Item Three Description Contents'
      }
    }
  ]

// My Mixin

mixin gridContent(items)

  .grid-content
    .container
      .row
        ul.grid-content__list.grid-content__list--not-news

          each item in items

            li.grid-content__item
              h1.item-title= item.title
              .item-content
                h3.item-description-title= item.description.title
                 p.item-description= item.description.contents

// Calling the Mixin

+gridContent(myGridItems)


text:
Q: Aligning markers for individual points in matplotlib and removing "double" legend for markers in matplotlib in Python I am trying to figure out the alignment of Markers in "ax.plot" . Apart from plotting 2 bar graphs, I also need to plot 2 points, one per bar graph.
Here's what I am looking for -:

*

*Centering/alignment of markers ('o' and '' here, in the center of each bar, rather than at the edge of the bar graph. "o" should come at the center of the 1st bar graph and "" should come at the center of the 2nd bar graph, their individual heights will differ though, as on the scale "Performance" -the "o" and "" are "Performance" objects (right hand side scale, as in the figure) - centering, thus means, overlay of the markers("o" and "" against its respective stacked graph.

*Removing the duplicate marker symbols, with 'o' and '*' in the legend on the upper right corner. And, understanding why that happens for par2.plot , but not for ax.bar object. Could I have done this without using ax.twinx(), which generates two scales (one for "#candidates"  and other for "Performance" - and if this double entry of legend is related to using the 2 scales ? (I hope not)
For (2), I also used plt.legend(numpoints=1) just before the last line, plt,show() according to the answer here, multiple markers in legend , but that didn't seem to remove the "duplicate markers" in this context.
Also attached is the graph, with (1) and (2) highlighted

Tip -: Ignore the looping constructs, they are a part of the larger piece, and did not want to change that while pasting, focus on this snippet of the entire code (IMO, this should narrow the problem?)
rects1 = ax.bar(ind, Current_Period, width, color=colors)
rects2 = ax.bar(ind+width, Next_Period, width, color='c')
lines_1=par1.plot(perform_1,linestyle='', marker='H', markerfacecolor ='k')
lines_2=par1.plot(perform_2,linestyle='', marker='*',markerfacecolor ='m')
ax.legend((rects1[0], rects2[0],lines_1[0],lines_2[0]), ('Current time period', 'Next time Period','Current Period Performance', 'Next Period Performance'),prop=dict(size=10) )

Here is the complete code that I used -:
#Final plotting file
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
#placing anchored text within the figure
from mpl_toolkits.axes_grid.anchored_artists import AnchoredText
rc('mathtext', default='regular')

history_P=[[1.4155322812819471, 4.9723842851306213, 3.6831354714462456, 3.0345047089322521, 5.3355879766963819], [2.3240101637275856, 4.7804345245879354, 7.0829471987293973, 6.1050663075245852, 3.6087166298399973], [3.5770722538162265, 3.4516290562530587, 4.4851829512197678, 5.1158026103364733, 3.7873662329909235], [4.7137003352158136, 5.0792119756378593, 4.4624078437179504, 3.1790266221827754, 4.8711126648436895], [4.8043291762010414, 5.6979872315568576, 3.4869780377350339, 3.892755123606721, 3.8142509389863095], [4.8072846135271492, 4.2055137431209033, 5.0441056822018417, 4.1014759291893306, 5.327936039526822]]
history_C=[[14000, 14000, 14000, 14000, 14000], [5373, 18874, 13981, 11519, 20253], [6806, 14001, 20744, 17880, 10569], [12264, 11834, 15377, 17540, 12985], [14793, 15940, 14004, 9977, 15286], [15500, 18384, 11250, 12559, 12307]]

N = 5
ind = np.arange(N)  # the x locations for the groups
width = 0.35

def make_patch_spines_invisible(ax):
    ax.set_frame_on(True)
    ax.patch.set_visible(False)
    for sp in ax.spines.itervalues():
        sp.set_visible(False)

def autolabel(rects):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height),ha='center', va='bottom')

alphab = ['M1', 'M2', 'M3', 'M4', 'M5', 'M6']

for k in range(0,5):
    colors=[]
    Current_Period=history_C[k]
    Next_Period = history_C[k+1]
    perform_1=history_P[k]
    perform_2=history_P[k+1]

    for i in range(0,5):
        if perform_1[i]==max(perform_1) :
            colors.append('g')
            best=i
        elif perform_1[i]==min(perform_1):
            colors.append('r')
            worst=i
        elif (perform_1[i] != min(perform_1) or perform_1[i] != max(perform_1)):
            colors.append('b')

    fig, ax = plt.subplots()
    fig.subplots_adjust(right=0.75)

    par1 = ax.twinx()
    make_patch_spines_invisible(par1)

    rects1 = ax.bar(ind, Current_Period, width, color=colors)
    rects2 = ax.bar(ind+width, Next_Period, width, color='c')
    lines_1=par1.plot(perform_1,linestyle='', marker='H', markerfacecolor ='k')
    lines_2=par1.plot(perform_2,linestyle='', marker='*',markerfacecolor ='m')
    ax.set_xlabel("Model #",style='italic',size='large')
    ax.set_ylabel("Candidate #",style='italic',size='large')
    par1.set_ylabel("Performance",style='italic',size='large')

    ax.set_title('Aggregated Performace Rolled out to candidates, per period',style='italic')
    #fontdict=dict('fontsize':rcParams['axes.titlesize'],'verticalalignment': 'baseline', 'horizontalalignment': loc)
    ax.set_xticks(ind+width)
    ax.set_xticklabels( ('M1', 'M2', 'M3', 'M4', 'M5') )
    ax.annotate('Worst Performer', xy=(worst,0),  xycoords='data',xytext=(-30, 30), textcoords='offset points',size=12, va="center", ha="center",arrowprops=dict(arrowstyle="simple", connectionstyle="arc3,rad=-0.2"))
    ax.annotate('Best Performer', xy=(best,0),  xycoords='data',xytext=(-30, 30), textcoords='offset points',size=12, va="center", ha="center",arrowprops=dict(arrowstyle="simple", connectionstyle="arc3,rad=-0.2"))
    ax.legend((rects1[0], rects2[0],lines_1[0],lines_2[0]), ('Current time period', 'Next time Period','Current Period Performance', 'Next Period Performance'),prop=dict(size=10) )
    #placing anchored text within the figure, per Period
    at = AnchoredText("Time Period :"+str(k+1),prop=dict(size=10), frameon=True,loc=2,)
    at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
    ax.add_artist(at)
    par1.set_ylim(0, 10)

    autolabel(rects1)
    autolabel(rects2)
    plt.show()

A: *

*You have to provide the plot method with x-coordinate arguments. If given only one list-like object, matplotlib will use this list as the y-coordinates and use x = np.arange(len(y)) (where y are the given y-coordinates).

*You should not call the legend method several times for each Axes; include the numpoints kwarg in your original legend call.
In other words, replace the lines
lines_1=par1.plot(perform_1,linestyle='', marker='H', markerfacecolor ='k')
lines_2=par1.plot(perform_2,linestyle='', marker='*',markerfacecolor ='m')
ax.legend((rects1[0], rects2[0],lines_1[0],lines_2[0]), ('Current time period', 'Next time Period','Current Period Performance', 'Next Period Performance'),prop=dict(size=10) )

with
lines_1=par1.plot(ind + 0.5*width, perform_1,linestyle='', marker='H', markerfacecolor ='k')
lines_2=par1.plot(ind + 1.5*width, perform_2,linestyle='', marker='*',markerfacecolor ='m')
ax.legend((rects1[0], rects2[0],lines_1[0],lines_2[0]), ('Current time period', 'Next time Period','Current Period Performance', 'Next Period Performance'),prop=dict(size=10), numpoints=1 )

This gives the desire output:

A: I think it is slightly better style to use bar(..., align='center'), as that is what you really want here:
    rects1 = ax.bar(ind, Current_Period, width, color=colors, align='center')
    rects2 = ax.bar(ind+width, Next_Period, width, color='c', align='center')
    lines_1=par1.plot(ind, perform_1,linestyle='', marker='H', markerfacecolor ='k')
    lines_2=par1.plot(ind+width, perform_2,linestyle='', marker='*',markerfacecolor ='m')
    ax.set_xticks(ind + width/2)
    ax.set_xticklabels( ('M1', 'M2', 'M3', 'M4', 'M5') )
    ax.legend((rects1[0], rects2[0],lines_1[0],lines_2[0]), ('Current time period', 'Next time Period','Current Period Performance', 'Next Period Performance'),prop=dict(size=10), numpoints=1 )

From a philosophical point of view, it it better to tell the plotting library to do what you want, than to contort your self (and inject details of how the plotting library does things internally) to accommodate the fact that you only are using part of the api.


text:
Q: Different View/Layout for Landscape Orientation I am building a calculator app and have it working in portrait mode. However, I want the user to have more options/functions when they switch to landscape mode. In other words, the entire layout would have to change as there will be more buttons in landscape mode compared to portrait mode.
I have managed to do this using the installed property under the attribute inspector. Here are the problems I am running into:

*

*When I run the app in portrait mode and rotate it to landscape, I will show the buttons but they are overlapped. Here is a demo(Just wait for the gif to restart):

*When I run the app in landscape mode, it displays all the buttons correctly, but as soon as I rotate it again to portrait and then back to landscape, the same problem as #1 happens. Here is a demo (Just wait for the gif to restart):

What am I doing wrong? How can I resolve this?

A: Here's what I've been doing since iOS9. Complete code, does not assume you are using IB (I actually think you should not) and should help you with how auto layout works. BEWARE, this does assume some knowledge of auto layout and Swift. This also deals with a very simple example of a UIButton.
First, declare two arrays of constraints, typically in the view controller:
var landscape = [NSLayoutConstraint]()
var portrait = [NSLayoutConstraint]()
var myButton = UIButton()

Next, set up your constant constraints and set the active:
myButton.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(myButton)
myButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
myButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
myButton.widthAnchor.constraint(equalToConstant: 200).isActive = true

So far, so good. You've created a button, added it to the VC view, declared it's size as 40x200. You've also declared it to be anchored to the parent's safeAreaLayoutGuide top anchor.
Now, it's time for the "magic". You wish to move this UIButton from the bottom to the right depending on orientation. (Please note, while certain overrides will work on iPhones, iPads, when full screen, will always have a "Regular" size class - in full screen - no matter the orientation!)
The first thing you need is to put the remaining constraints into the arrays you declared.
portrait.append(myButton.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 10))
landscape.append(myButton.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -10))

Now you have s single constraint to activate. It can be more, remember we are talking arrays. This is simple, just deactivate and activate as needed:
func changeConstraints() {
    if isInPortrait {
        NSLayoutConstraint.deactivate(landscape)
        NSLayoutConstraint.activate(portrait)
    } else {
        NSLayoutConstraint.deactivate(portrait)
        NSLayoutConstraint.activate(landscape)
    }
}

You can even animate things is you wish! Finally, let's tap into the VC life cycle. I'm very sure there are other (and better) ways, but keep in mind what I mentioned earlier - in full screen, an iPad will always have a Regular size class. So I prefer to dig just a bit deeper. I tend to use three variables - you probably need less.
var initialOrientation = true
var isInPortrait = false
var orientationDidChange = false

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()
    if initialOrientation {
        initialOrientation = false
        if view.frame.width > view.frame.height {
            isInPortrait = false
        } else {
            isInPortrait = true
        }
        changeConstraints()
    } else {
        if view.orientationHasChanged(&isInPortrait) {
            changeConstraints()
        }
    }
}

I also have an extension to UIView:
extension UIView {
    func orientationHasChanged(_ isInPortrait:inout Bool) -> Bool {
        if self.frame.width > self.frame.height {
            if isInPortrait {
                isInPortrait = false
                return true
            }
        } else {
            if !isInPortrait {
                isInPortrait = true
                return true
            }
        }
        return false
    }
}

I think this should describe most of my code. Basically, (a) do not use UIDevice nor (b) use viewWillTransition(toSize:) and check a size class when working with a iPad. (They will have a size class change - albeit differently on devices depending on size, but only when in split screen mode. At least for now!)
Pretty much, use (a) view willLayoutSubviews - you can use view DidLayoutSubviews but I prefer doing things at the earliest point possible - and then (b) check the actual screen size.


text:
Q: Login to a website using python I am trying to login to this page using Python.Here is my code
  from urllib2 import urlopen
  from bs4 import BeautifulSoup
  import requests
  import sys

  URL= 'http://coe2.annauniv.edu/result/index.php'
  soup = BeautifulSoup(urlopen(URL))

  for hit in soup.findAll(attrs={'class' : 's2'}):
  print hit.contents[0].strip()

  RegisterNumber = raw_input("enter the register number")
  DateofBirth = raw_input("enter the date of birth [DD-MM-YYYY]")
  login_input = raw_input("enter the what is()?")

 def main():
    # Start a session so we can have persistant cookies
     session = requests.session()

# This is the form data that the page sends when logging in
login_data = {
    'register_no':'RegisterNumber',
    'dob':'DateofBirth',
    'security_code_student' :'login_input',
    'gos': 'Login',
}

# Authenticate
r = session.post(URL, data=login_data)

# Try accessing a page that requires you to be logged in
r = session.get('http://coe2.annauniv.edu/result/students_corner.php')

 if __name__ == '__main__':
      main()

i tried using requests .but the above code  can't accessed the page that requires to be login.
What am I doing wrong?

A: You are incorrectly using string values instead of the intended variables inside login_data.
from urllib2 import urlopen
from bs4 import BeautifulSoup
import requests
import sys

URL= 'http://coe2.annauniv.edu/result/index.php'
soup = BeautifulSoup(urlopen(URL))
#print soup.prettify()

for hit in soup.findAll(attrs={'class' : 's2'}):
    print hit.contents[0].strip()

RegisterNumber = raw_input("Enter the registration number: ")
DateofBirth = raw_input("Enter the date of birth [DD-MM-YYYY]: ")
login_input = raw_input("Enter the what is()? ")

def main():
    # Start a session so we can have persistant cookies

    # Session() >> http://docs.python-requests.org/en/latest/api/#request-sessions
    session = requests.Session()

    # This is the form data that the page sends when logging in

    # You are wrongly using string values instead of the intended variables here that is RegisterNumber and not 'RegisterNumber'
    login_data = {
    'register_no': RegisterNumber,
    'dob': DateofBirth,
    'security_code_student': login_input,
    'gos': 'Login',
    }
    print login_data

    # Authenticate
    r = session.post(URL, data = login_data)
    # Try accessing a page that requires you to be logged in
    r = session.get('http://coe2.annauniv.edu/result/students_corner.php')
    print r

if __name__ == '__main__':
    main()

P.S.: Get back if you are looking for something else, but post what you wished and what you got elaborately!


text:
Q: vuejs component template files I'm looking to build a simple SPA with Vue.js. I'd like to load different templates and animate a transition between them like this:
http://codepen.io/michaeljcalkins/pen/BNqREZ
The example is great, but I'd like to load each component's template from a separate file.
Something like:
var Foo = Vue.extend({
    template: '/foo.html'

I went through the documentation but I can't seem to find anything. How would I go about achieving something like this?
Thank you!

A: As mentioned by Björn above, it  doesn't look like it's possible to use Template URL's in Vue. Thanks Björn!