text:
Q: How can i make a player stop moving when it touchs a collider? So i was wondering if there is a way to make a player move infinitely with just one click and just stop when colliding with another collider.

A: You can create a global property:
bool movePlayer = false;

In FixedUpdate method you can detect a mouse click and change movePlayer to true, and move the player if it values true:
void FixedUpdate() {
    if (Input.GetMouseButtonDown(0))
        movePlayer = true;

    if (movePlayer) {
        //move the player here, maybe with Translate method
    }
}

With OnTriggerEnter method you can detect the collision and change movePlayer to false:
void OnTriggerEnter(Collider other) {
    //you can check for some particular object or avoid this if
    if (other.gameObject.name == "SomeObject")
        movePlayer = false;
}


text:
Q: Fraction with longer line I'm trying to display some axioms and operational rules with LaTeX.
Those are basically . They work quite well when used with frac, but it's not really nice, I'd like the fraction line to be a bit longer.
I know that sounds a bit vague, so here is a picture of what I am trying to achieve. I'm pretty sure that document has been typeset in LaTeX, so it should be doable.

A: \newcommand\bigfrac[2]{%
  \begin{array}{c}
    #1 \\
    \hline
    #2
  \end{array}}

A: You should consider to use a dedicated package to write your axioms; the bussproofs package could be an option:
\documentclass{article}
\usepackage{bussproofs}
\usepackage{amsmath}

\newcommand*\LArrow[1][a]{\xrightarrow{\phantom{a}#1\phantom{a}}}

\begin{document}

\begin{prooftree}
  \AxiomC{$x\LArrow x^\prime$}
  \UnaryInfC{$x+y\LArrow x^\prime$}
\end{prooftree}

\end{document}

To work with displayed math environments, a better option would be to use the proof package. A little example:
\documentclass{article}
\usepackage{proof}
\usepackage{amsmath}

\newcommand*\PA{\phantom{a}}
\newcommand*\LArrow[1][a]{\xrightarrow{\PA#1\PA}}

\begin{document}

\begin{equation}
  \infer{\PA x+y\LArrow x^\prime\PA}{x\LArrow x^\prime}
  \qquad
  \infer{\PA x+y\LArrow y^\prime\PA}{y\LArrow y^\prime}
  \qquad
  \infer{\PA x+y\, \downarrow\PA}{x\,\downarrow}
  \qquad
  \infer{\PA x+y\, \downarrow\PA}{y\,\downarrow}
\end{equation}

\end{document}

A: Here's an extended version of \frac, supporting an optional argument for a wider line:
\documentclass{article}
\DeclareRobustCommand{\frac}[3][0pt]{%
  {\begingroup\hspace{#1}#2\hspace{#1}\endgroup\over\hspace{#1}#3\hspace{#1}}}
\begin{document}
\[
  \frac{x}{y} \quad \frac[5pt]{x}{y}
\]
\end{document}

Of course you can define your own frac command similar instead of redefining the existing \frac, also with a default value bigger than 0pt.
The definition is similar to the definition in amsmath.sty, except that file is using \@@over.
Or, you could define your own macro using the original \frac:
\DeclareRobustCommand{\widefrac}[3][5pt]{%
  \frac{\hspace{#1}#2\hspace{#1}}{\hspace{#1}#3\hspace{#1}}}
...
\widefrac{x}{y} ... \widefrac[8pt]{x+y}{y}

A: In case you really want fractions with a longer line, you can just pad both numerator and denominator with spaces. (Padding the longer of the two would acually suffice.) \frac{\ a\ }{\ b\ } gives

For a longer line use, e.g., \quad instead of \ .

A: Another solution is to use the \phantom{} command, which renders the exact whitespace the exact same size as  its argument.
For example,
\documentclass{article}
\usepackage{proof}
\usepackage{amsmath}

\begin{align*}
\varphi &= 1+ \frac{1}{1 + \cfrac{1}{\varphi}}\\[.5cm]
%
%
\varphi &= 1+ \frac{ \phantom{\longrightarrow} 1 \phantom{\longrightarrow} }{1
+ \cfrac{1}{\varphi}}
\end{align*}

\end{document}

which returns

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I Run Dash app (Flask app) on a Drupal Apache Server? The title is basically my question. Below is some background info.
I am trying to create an interactive visualization dashboard consisting of multiple graphs. I have a MongoDB database, which is updated once a day automatically.
I am familiar with Python, HTML, CSS but I am not an expert in Drupal and PHP, so I'm trying to use Python to make the visualization. Specifically, I am using Dash Plotly with HTML  tag to paste it on the webpage. Right now the Dash app is deployed under my local computer's IP address running in the terminal.
Now I want to take this app live on the server so that I don't have to keep my computer on. Is it safe to deploy and run a Dash app (or a Flask app, they are basically the same) via Apache on my Drupal web server?
Drupal Info:
Drupal Version: 9.1.2
Web Server: Apache/2.4.41 (Ubuntu)
PHP Version: 7.4.3
Server Info:
Two CPUs: Intel(R) Xeon(R) CPU E5-2690 v4 @ 2.60GHz
RAM: 4GB
I don't have much server knowledge and I can't find an answer to this.

A: Resolved by simply deploying the dash app on Apache server, then using HTML iframe tag to embed to the specific webpage on drupal.


text:
Q: Why does a custom adapter require a resource? I'm more of a C++ developer and have just recently started Android development. While learning about Custom adapters for ListView one think struck me.
If you look at the constructors of ArrayAdapter, all of them require a resource which points to the layout. ArrayAdapter
I guess passing a layout is helpful when I'm using the default ArrayAdapter class.
But since I can @Override the getView method of ArrayAdapter in my own class, and manually inflate the view by passing the resource id, then why does the ArrayAdapter require a resource id on all its constructors?
@Override
public View getView(int position, View convertView, ViewGroup parent) {
  LayoutInflater inflater = (LayoutInflater) context
      .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    //In the below line I'm passing the resource id to the inflate method
    View rowView = inflater.inflate(R.layout.rowlayout, parent, false);

    return rowView;
}

A: If you directly extend the BaseAdapter you can handle the layout inflation by your own. However the ArrayAdapter needs the resources to get the items and to inflate the item layouts. What it exactly does depends a little on your actual code.
I would recommend that you take a look at the source code of the ArrayAdapter. That might help you.
A little off topic you should really recycle the views you can see how that is done also in the ArrayAdapters source code, if you don't you would create dozens of elements which are not required.


text:
Q: Troubles monitoring a zimbra installation with nagios I am trying to monitor my legacy zimbra installation (running on an outdated Ubuntu 8.x) from my nagios install (running on a more recent OpenBSD).
The problem is that when I run check_nrpe from the nagios server it complains:
nagios-server$ sudo su -m _nagios -c "/usr/local/libexec/nagios/check_nrpe -H ZIMBRA_HOST -c check_zimbra"
CHECK_NRPE: No output returned from daemon.

Note that the zimbra server's NRPE configuration runs:
command[check_zimbra]=/usr/lib/nagios/plugins/check_zimbra.pl

On the other hand, running the plugin locally on the zimbra server works fine from root:
zimbra-server# ./check_zimbra.pl
HOST : ZIMBRA_HOST, ldap : OK, logger : STOPPED and zmlogswatchctl down, mailbox : OK, mta : STOPPED and zmmtaconfigctl down and zmsaslauthdctl down, snmp : STOPPED, spell : OK, stats : OK

However, running it as nagios user on the zimbra server complains about the path:
zimbra-server# su -m nagios -c "./check_zimbra.pl"
Insecure $ENV{PATH} while running setuid at ./check_zimbra.pl line 32.

Line 32 recites:
7  $zimbra_status_command='/opt/zimbra/bin/zmcontrol status';
[snip]
32 open (ZMSTATUS, "$zimbra_status_command |");

I have a suspicion it might have something to do with suid perl. In fact, following this advice and adding this line to the check_zimbra.pl file,
delete @ENV{'PATH', 'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

I get the following:
zimbra-server# su -m nagios -c "./check_zimbra.pl"
Insecure dependency in piped open while running setuid at /opt/zimbra/bin/zmcontrol line 389.

Anyhow, on the zimbra server I have installed the check_zimbra.pl plugin, which is suid zimbra so I can run it from the nagios user:
zimbra-server# ls -la check_zimbra.pl
-rwsr-xr-x 1 zimbra root 2885 2010-01-11 21:14 check_zimbra.pl

I have modified /etc/sudoers so that the nagios user can run the appropriate zimbra monitoring tool:
%nagios ALL=(zimbra) NOPASSWD:/opt/zimbra/bin/zmcontrol

I am stuck.. is there any other way to run the check_zimbra.pl plugin as nagios user, being able to run the zmcontrol status command as zimbra user..?
Thanks,

A: perldoc perlsec states that should set @ENV{'PATH'} to a known value, not unset it !

Blockquote
  For "Insecure $ENV{PATH}" messages, you need to set $ENV{'PATH'} to a known value, and each directory in the path must be
         absolute and non-writable by others than its owner and group.  You may be surprised to get this message even if the pathname to
         your executable is fully qualified.  This is not generated because you didn't supply a full path to the program; instead, it's
         generated because you never set your PATH environment variable, or you didn't set it to something that was safe.  Because Perl
         can't guarantee that the executable in question isn't itself going to turn around and execute some other program that is
         dependent on your PATH, it makes sure you set the PATH.


text:
Q: How to write to a .txt file I need help trying to convert an ASCII list to a string list, I have already tried this:
ciphertext = str[Nintendo65]

However it keeps outputting this: TypeError: 'type' object is not subscriptable

A: str[x]

tries to access the xth element of str (which fails with the error you saw).
If you want to convert some object to a string, the correct syntax is
my_string = str(my_obj)

That gives you a string. If you want to convert that to a list containing each character of your string as one element, use
char_list = list(my_string)


text:
Q: function not being called, do I need a window.load? I am trying to change the css stylings of an item when it's clicked.
ryan.js
function ryanClicked(id){
    document.getElementById(id).style.color = "blue";
    alert("Asdsa");
}

product.html

 S

 M

 L

I assume I need a onReady or onLoad somewhere? I haven't done js in a while.
My page has Jquery included so I can use jquery for the ready event. I'm not sure if that would be better to do or not.

A: Try this, you don't need pass id to your function, instead you can pass this (refers to element that was clicked),

function ryanClicked(el) {
  el.style.color = "blue";
}

S

M

L

A: If you are using jQuery, you might prefer:

 S

 M

 L

and:
$(".sizeButton").on("click", function() {
    $(this).css("color", "blue")
})

https://jsfiddle.net/38ybvty8/

A: You can get desired result without passing id and onclick attribute in your element tag.

$(".sizeButton").click(function(){
   $(this).css({'color':'blue'});
});

S

M

L


text:
Q: iphone ansi c : pointer being freed was not allocated I am using a c lib in my iPhone application. The c lib is written by someone I do not have access to.
However I am getting the error that object 0xa6000d is being freed but not allocated. The debug variable screenshot is here.

struct GtsMsg is defined as,
struct msg {
    int offset;
    int dataLength;
    u8* data;
    cBool expandable;
    cBool owned;
    u8* mid2key;
};

#define GtsMsg struct msg

void freeMessageData(GtsMsg* msg) {
    if (msg == NULL) return;
    if (msg->owned) {
        if (msg->data != NULL) {
            free(msg->data);
        }
    }
    free(msg->mid2key);
    memset(msg, 0, sizeof(GtsMsg));
}

The breakpoint for malloc_error_break is the line free(msg->data).
I have added the checking if (msg->data != NULL), but it did not work. What are the ways to check if the memory for msg->data or for msg is allocated or not?
Do you think there is something fishy, at *data = (u8)'\0'?
thanks in advance!

A: Thanks to all to your suggestions.
Thanks hmjd for your tips.
I found the struct is used in a cpp class which destructor calls the freeMessageData. But I could not find that the struct is initialized. So, if I initialize the struct to NULL in the declaration, this avoid the free memory problem and do not crash.
Its something suggested by simonc. If he writes that as an answer not, comment, I could accept that.
From comments of hmjd,

The check for NULL is useless as free() will be a no-op if the pointer
  passed to it is NULL. Just because a pointer is not NULL does not mean
  it points a valid memory location (the memory may have already been
  freed or the pointer was never initialized to NULL). It is the
  responsibility of the programmer to ensure that the pointer is valid
  before attempting to free it.


text:
Q: Cant valid email textfield java My problem is that i want to check if email textfield contains char "@".How am i supposed to do it?I also want to check if other textfields such as name, username, password are empty.Thanks alot in advance for your help. This application blowed my mind!
   private JButton signupButton;
private JTextField name;
  private JTextField email;
  private JTextField username;
private JPasswordField pass;

private UserManager userManager;

public SignUpFrame (UserManager userManager){
super("Please fill in your Data");

userManager = new UserManager();

signupButton = new JButton("Sign Up!");
signupButton.addActionListener(new signupButtonListener());

 name = new JTextField(15);

 email = new JTextField(15);

 username = new JTextField(15);

pass = new JPasswordField(15);

 JPanel mainPanel = new JPanel();

  mainPanel.setLayout(new GridLayout(5,2));

     mainPanel.add(new JLabel("Name:"));
  mainPanel.add(name);
   mainPanel.add(new JLabel("Email:"));
     mainPanel.add(email);
    mainPanel.add(new JLabel("Username"));
      mainPanel.add(username);
    mainPanel.add(new JLabel("Password:"));
   mainPanel.add(pass);
    mainPanel.add(signupButton);

    this.setContentPane(mainPanel);
   this.pack();
      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);

   }

    class signupButtonListener implements ActionListener{

         public void actionPerformed(ActionEvent arg0) {

    String nam,emai,id,psw;

        nam = name.getText();
       emai= email.getText();
     id = username.getText();
 psw = pass.getText();

User u1 = new User(nam,emai,id,psw);

 UserManager.userList.add(u1);

}

A: To check if a TextField is empty you can use if statements like:
if(name.getText().length() > 0){ nam = name.getText(); }
...

And for checking if there a char @ in your email TextField you can use the .contains() method:
emai= email.getText();
if(emai.contains("@")){ ... }

I hope i was able to help you..

A: Try doing an if to test what the field hold ie
if(nam.equals("")){
//alert the user

}

You can do this with all the fields.
You could possible use regular expression for the email - something like
String emailreg = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$";

 Boolean result = emailAddress.matches(emailreg);
if(result == true){
//email is valid
}

Hope this helps.


text:
Q: React JS color picker inside form I've been struggling with this all day. Really new to react so apologies in advanced.
I'm trying to use react-jsonschema-form to create form from json with react-color.
This is what I have now:
import React, {Component} from "react";
import {ChromePicker} from 'react-color';
import Form from "react-jsonschema-form";

const ColorPicker = (props) => {
    return (
        <ChromePicker
            color={props.value || false}
            value={props.value}
            onChange={(event) => {
                props.onChange(event.color)
            }}
        />
    )
}
const schema = {
  "type": "object",
  "properties": {
    "base": {
      "type": "object",
      "title": "Global settings",
      "properties": {
        "line-height": {
          "title": "Body line height",
          "type": "number"
        },
        "background-color": {
          "title": "Body background color",
          "type": "string"
        },
        "font-color": {
          "title": "Body background color",
          "type": "string"
        }
      }
    }
  }
}
const uiSchema = {
    base:{
        "background-color":{
            'ui:widget':ColorPicker
        },
        "font-color":{
            'ui:widget':ColorPicker
        }

    }
}
export default class GeneratorForm extends Component {
    constructor(props) {
        super(props);
        this.handleChange = this.handleChange.bind(this);
    }
    handleChange(data) {
            console.log(data)
    }
    render() {
        return (
            <Form schema={schema}
                  uiSchema={uiSchema}
                  //onBlur={this.handleSubmit}
                  onChange={this.handleChange}
                  //onSubmit={this.handleSubmit}
                  onError={log("errors")}/>
        );
    }
}

Simple form with two colorpickers. And the colorpicker works great, except in the handleChange, formData for that field is empty. It's like the value isn't assigned. I've searched for similar topics, somethings similar with datepicker3 and that gave me an idea to make it simple (had some crazy code, custom class component and so on).
So the question is, how to pass a value from color picker to form value?
Thanks in advance.

A: You should take a look at the Docs for react-color. You aren't handling the onChange event correctly. It should be:
const ColorPicker = (props) => {
    return (
        <ChromePicker
            color={props.value || false}
            value={props.value}
            onChange={ color => {
                props.onChange(color)
            }}
        />
    )
}

event.color doesn't exist. The onChange handler will get two arguments, color and event.


text:
Q: Superfish menu Delay I'm using superfish menu for a Joomla website. The problem I have has to do with the menu time delay. here is the menu: http://jsfiddle.net/tBZPe/6/
 it is working fine here. But when I do the same styling on my website it looses all the jQuery functionality.
This is the jQuery I have used:
jQuery(document).ready(function () {
jQuery("#menu").superfish({
      delay: 5000,
      onHide: function () { jQuery("#HideThis").hide(); }
 });
jQuery("#Stuff").click(function () { jQuery("#HideThis").show() });

});

A: I figured out that the version of joomla was not compatible with the version of superfish menu I was using. so I upgraded my joomla from 1.7.1 to joomla 2.5.11
then I have installed superfish version 2 then problem solved


text:
Q: Issue in comparing files in eclipse As i am using Windows 7 64 bit, i installed SVN plugin version 1.8 from the site
http://subclipse.tigris.org/update_1.8.x
When i compare any file with latest from repository then the comparison is not shown properly. Please refer the screen shot and suggest if i am missing something. I faced this in eclipse indigo also.

A: I got the issue, Actually it was considering white-spaces during comparison by default for all files.
Open Window > Preferences from the menu bar
Select General > Compare/Patch in the left-side tree menu
Check "Ignore white space"
Press Apply, then OK

A: Do you mean the Syncrhonize Perspective?
Hit Ctrl+F8 and select it from the list.
If it isnot there, click that "window with a plus icon" next to MyEclipse Java ..., and select it from the appearing list.


text: Q: Local system windows service is throwing Webexception:"Unable to connect to remote server"? I am working on a windows service to upload data from database to a remote server in C# using visual studio 2012, when I am using a "Local system windows service", it is throwing a webexception:"Unable to connect to remote server". But when I am using "user service", it is sending the data to server successfully. But user service asks the username and password during installation, which I do not want. How can I create a local system service, which can upload data to server without throwing above webexception? I have checked the firewall settings also.


text:
Q: How do I make a header above my navigation bar? I'm trying to create a navigation bar with a header above it. I want it to be so that the navigation bar will stick once it reaches the top of the screen (which I've already worked out myself) but anything above it will not stick (will scroll off screen as normal). A VERY GOOD EXAMPLE OF WHAT I'M TRYING T DO IS Happy Cog. Go there and scroll down until the header disappears but the navigation bar stays visible and appears connected to the top of the browser window. That's what I want: the header to be placed ABOVE the navigation bar and disappear when scrolling but the navigation bar stay at the top of the browser. I want to make sure it scrolls and runs as smoothly as theirs as well--no jumping around or jumping to the top of the window. How do I put content above the navigation bar and make it where it won't stick when the navigation menu does?
I REALLY APPRECIATE ANY HELP YOU GUYS CAN BE! THANKS SO MUCH IN ADVANCE!
MY HTML:
<!DOCTYPE html>

<meta charset="utf-8">
<title>Testing</title>
<link href="style.css" rel="stylesheet" type="text/css" />

Atlas Land Office (text will change)

Keeping lands fresh.

Home

Land Surveying

Civil Engineering

Land Planning

Company

Careers

My CSS (that I have up to this point--no where near finished):
body {
height: 3000px;
top: 0;
position: relative;
}

#navbar {
position: relative;
width: 1329px;
height: 44px;
background: #CCC;
margin-left:-8px; /* Connects the navigation menu to the left "wall" */
margin-top:-8px;
top: 100px;
padding-left:10px;
padding-right:10px;
}

My jQuery:
$(window).scroll(function () {
if ($(window).scrollTop() > 100) {
$('#navbar').css('top', $(window).scrollTop());
}
}
);

A: I have Changed Your Code A bit and it's working fine Now. tested in Chrome
HTML

Atlas Land Office (text will change)

Keeping lands fresh.

Home

Land Surveying

Civil Engineering

Land Planning

Company

Careers

CSS
 body {
 height: 3000px;
 top: 0;
 position: relative;
   }
 #header-text{
  height:200px;
  border:2px solid;
 }
 #menu {
display:block;
  }
 #menu ul {
width:1000px;
background-color:#666;
border:1px solid;
height:30px;
 }
 #menu ul li{
float:left;
padding:5px;
list-style:none;
 }
 #menu ul li a{
color:white;
text-decoration:none
 }
 .fixnav{
position:fixed;
top:0;
z-index:1000;
 }

JQUERY
  $(window).scroll(function ()

    {
        if ( $(window).scrollTop() > 200)
        {
            $("#menu").addClass("fixnav");
        }
        else  if ($(window).scrollTop() < 200)
        {
            $("#menu").removeClass("fixnav");
        }
    });


text:
Q: Error: in points2grid(points, tolerance, round) : dimension 1: coordinate intervals are not constant I'm new working in programming languages at all, but here I'm using R language and I need some help, I'm trying to learn how to make a consensus in SDM. The idea is create a raster and then, use the stack() function. But when I try to apply this on a document, using the gridded() function on the presente.txt file, I got the following error:
in points2grid(points, tolerance, round) :  dimension 1 : coordinate intervals are not constant
The document in question is a .txt file that look like this:
presente.txt
What I'm not understanding is that: I have others .txt files on the code and they run just fine in the code: example .txt
My code: https://drive.google.com/file/d/17z5Kd8ahzNx0uIgBUGgbn_xIhfNBjmQd/view?usp=sharing
Hope it's reproducible, really need to solve this
Note: I realize now that the first file have 49.502 rows and the others 49.504, don't know if it's saying something
Thanks!!


text:
Q: SO_REUSEADDR and UDP behavior in Windows I'm aware that using SO_REUSEADDR with UDP in a *NIX environment, behaves like a multicast, where multiple clients bound to the same port can listen and receive broadcast datagrams simultaneously. Is this the behavior on Windows as well?

A: Multiple UDP sockets on Windows bound to the same port will all receive broadcast packets together.
Here's a demo program you can build for windows and Linux with GCC and test with Netcat as mentioned. In both systems, only one socket (either A or B) receives each datagram when a unicast address is used as the target. If a broadcast address is used then both sockets will receive the message.
/* Tested on linux and windows 7.
 * On windows use mingw-gcc:
 *    gcc -Wall -g -o udplisten udplisten.c -lws2_32
 * Test with:
 *    echo hello | netcat -u machinename 9898 (unicast)
 *    echo hello | netcat -u 172.16.255.255 9898 (broadcast)
 */
#ifdef WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define SOCKET int
#define INVALID_SOCKET -1
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#undef max
#define max(x,y) ((x) > (y) ? (x) : (y))

static void
die(const char *str)
{
    perror(str);
    exit(1);
}

static SOCKET
mksocket(struct sockaddr_in *addr)
{
    SOCKET sock = INVALID_SOCKET;
    int opt = 1;
    if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
        die("socket");
    if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char *)&opt, sizeof(opt)) < 0)
        die("setsockopt");
    if (bind(sock, (struct sockaddr *)addr, sizeof(struct sockaddr_in)) < 0)
        die("bind");
    return sock;
}

static void
process(SOCKET sock, const char *label)
{
    char buffer[8192];
    struct sockaddr_in caddr;
    socklen_t caddr_size = sizeof(caddr);
    memset(&caddr, 0, caddr_size);
    int count = recvfrom(sock, buffer, sizeof(buffer), 0,
                         (struct sockaddr *)&caddr, &caddr_size);
    if (count < 0) die(label);
    printf("%s %d '", label, count);
    fwrite(buffer, 1, count, stdout);
    printf("'\n");
}

int
main(int argc, char *argv[])
{
    struct sockaddr_in addr;
    SOCKET socka = INVALID_SOCKET, sockb = INVALID_SOCKET;
    fd_set read_set;
#ifdef WIN32
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2,2), &wsaData))
        return -1;
#endif
    addr.sin_family = AF_INET;
    addr.sin_port = htons(9898);
    addr.sin_addr.s_addr = INADDR_ANY;

    socka = mksocket(&addr);
    sockb = mksocket(&addr);

    for (;;) {
        FD_ZERO(&read_set);
        FD_SET(socka, &read_set);
        FD_SET(sockb, &read_set);
        if (select(max(socka,sockb)+1, &read_set, NULL, NULL, NULL) < 0)
            die("select");
        if (FD_ISSET(socka, &read_set))
            process(socka, "A");
        if (FD_ISSET(sockb, &read_set))
            process(sockb, "B");
    }
    return 0;
}


text:
Q: Почему не сохраняются картинки в heroku (Rails)? Здравствуйте, вопрос по сути уже задан. Добавляю изображение на сайт, через некоторое время захожу, а его уже нету.

A: Heroku так устроен, что ваш сервер включается только когда к нему идут обращения. Если обращений к сайту нет, ваш инстанс выключается и вся сохраненная на нем в ходе работы информация обнуляется. При использовании Heroku лучше отправлять изображения в какое-нибудь долговременное облачное хранилище (Swift, S3). Тем более они почти все допускают привязку доменного имени, в результате чего вы сможете отдавать изображения с поддомена вашего сайта img.yoursite.com.


text:
Q: Why does my SSL verification libCUrl code work on my local machine but not on the server? I have the following code snippet which is sample code generated by postman for the most part.
main.cpp:
#include <stdio.h>
#include <string.h>
#include <curl/curl.h>
int main(int argc, char *argv[]){
  CURL *curl;
  CURLcode res;
  curl = curl_easy_init();

  struct curl_slist *host = NULL;

  if(curl) {
    host = curl_slist_append(NULL, "example.com:443:xxx.xxx.xxx.xxx");
    curl_easy_setopt(curl, CURLOPT_RESOLVE, host);
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
    curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/auth/vx/getToken");
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
    curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
    curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
    curl_easy_setopt(curl, CURLOPT_CAINFO,  "key_file.pem");
    struct curl_slist *headers = NULL;
    headers = curl_slist_append(headers, "Content-Type: application/x-www-form-urlencoded");
    headers = curl_slist_append(headers, "Accept: */*");
    headers = curl_slist_append(headers, "Authorization: Basic <some_auth_data>");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");
    const char *data = "<some_data>";
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
    res = curl_easy_perform(curl);
    printf("Response code= %d %s", res, curl_easy_strerror(res));
  }
  curl_easy_cleanup(curl);
  return (int)res;
}

When I run this on a local AMD64 machine I get the token back with a 0 CUrl code. When I cross compile and run this on the ARM64 server I get no token and an error CUrl code of 60 with the message:
Response code= 60 SSL peer certificate or SSH remote key was not OK

I have looked at other questions/answers which point out that it is usually a file path error, but the key_file.pem is located in the same directory as the executing binary main, both on the AMD64 (local) machine and the ARM64 (server) machine.
My question is, what else could give the error code 60? Is there a few possible SSL system configurations that may be blocking me here?


text:
Q: Progressbar overlapping at smaller displays (responsive design issue ) Hi people when i use a device with a smaller display. The progressbar would overlap the main area (like in the picture below). Please help me. I am a absolute beginner.
Progressbar overlapping at small displays

       <--- image above progressbar

     <----- Progressbar

        <----- this is the main area

Greetings from austria. Thanks !

A: For the progress bar which is overlapping, give it a style attribute, left: 20%.
Dont use left/right px. It will give the element fixed position


text:
Q: How to exclude IPs from VPN routing? I want to prevent certain IP connections to go through my default VPN.
Is that possible at all to set a specific IP or range that should go the normal way, instead of going through a connected VPN?
ifconfig shows a wlp147s0 and a vpn0. I'm not having 2 ethernet cards.
How can I now prevent some ips from going through vpn0?

A: The following command worked to route the range of 192.0.64.0/18 (simplenote.com) through my local router, instead of the vpn0:
sudo ip route add 192.0.64.0/18 via 192.168.178.1 dev wlp147s0


text:
Q: Build jar issue but manual compilation works fine I have a issue on building the jar at place.
It is not generating all .class files.
But if i manually complite the .java files i am able to generate all the .class files without any issue.
What could be the issue?

A: you should compile the .java files before generating the jar file,
(I hope I have understand your question right)


text:
Q: How do I use egrep to list words that match a regular expression? I need to use egrep to count words that contain strings which match a regular expression. For instance, I need to do something like "Count the number of words containing three consecutive vowels" (not exactly that, but that's the gist of it).
I've figured out how to do it to count lines which contain these words, but when I add the -w tag I get an egrep: illegal option -- w error.
Here's the regular expression I'd use to count lines in the scenario above, which seems to work:
egrep -i -c '[aeiou][aeiou][aeiou]' full.html

Using the -w tag with this command causes the error I listed above, even if I add \b tags around the regex expression. e.g.:
egrep -i -c -w '\b.*[aeiou][aeiou][aeiou].*\b' full.html

What am I doing wrong?
EDIT: I'm running this on Solaris 10 out of the terminal.

A: use this way also to find the count of the words that contains strings
grep --color -Eow '[aeiou][aeiou][aeiou]' filename | wc -l
or
egrep -ow '[aeiou][aeiou][aeiou]' filename | wc -l
o for Print only the matched.
w for word.
finally, it will display the count of the word.

A: You'll have to consult your solaris man-pages to know if your egrep supports any/all/some of the GNU like extensions.
Does your system have /usr/xpg4/bin ? If yes, make sure your MANPATH includes /usr/xpg4/man. That dir used to have the newest versions, short of having something like /opt/gnu install added.
In any case, your regexp '\b.*[aeiou][aeiou][aeiou].*\b' reads to my eye as ...
1 word-boundary
followed by any number of any chars (including blanks and vowels)
followed by three vowels,
followed by any number of any chars (including blanks and vowels),
followed by 1 word-boundary.

Probably not what your really want.
To meet your need of words with 3 vowels in a row and using old/square reg-ex long hand, try
 egrep -i -c '[a-z]*[aeiou][aeiou][aeiou][a-z]*' full.html

This says, match chars [a-z] any number (including none), before 3 vowels, followed by any number of chars [a-z] (including none). So space chars won't match [a-z]. YOu're using -i to ignore case, so you don't have to use [A-Za-z]. Obviously, if you find other chars that you want to consider as word chars, maybe the '_' char?, add that to both sides.
Sorry, but I'm going from memory here, I don't work in a Solaris shop, and can't test it there.
edit
Also note that the man page on my current system for grep says
  -c, --count
          Suppress normal output; instead print a count of matching  lines
          for  each  input  file.  With the -v, --invert-match option (see
          below), count non-matching lines.

Note it's the number of matching lines, not the number of matches.
Might be easier to use
  awk '{for (i=1;i<=NF;i++){if ($i ~ /.*[aeiou][aeiou][aeiou].*/) cnt++};}; END{print "count="cnt}'file

IHTH

A: I believe that egrep does not support \b for word boundaries. Try \< for beginning of word boundary and \> for end of word boundary.
EDIT
Hmm... never mind. According to the man page \b is supported.
Actually, I think the answer is that only grep supports the "-w" option. I don't think egrep does.
http://ss64.com/bash/egrep.html

A: Which platform and which version of egrep?
The -w option works for me (CentOS and Mac with GNU egrep) - see below.  Also, \b works as expected - see below.
Also, I used a different regex - see below.
$ grep --version
grep (GNU grep) 2.5.1

$ cat test.txt
this and that iou and eai
not this aaih
not this haai

$ egrep -i -w '[aeiou]{3}' test.txt
this and that iou and eai

# with no -w
egrep -i '\b[aeiou]{3}\b' test.txt
this and that iou and eai

# with neither -w nor {3}
$ egrep -i '\b[aeiou][aeiou][aeiou]\b' /tmp/test.txt
this and that iou and eai

# using '\<' and '\>' works as well for word boundaries
$ egrep -i '\<[aeiou][aeiou][aeiou]\>' /tmp/test.txt
this and that iou and eai


text:
Q: Pinch zoom to view all icons of GridView in android I have implemented a launcher application based on grid view with flipper to show all the application icons successfully. Using flipper I am able to view all pages one by one.
I want to implement pinch zoom (multi touch) to view all the pages in single page (Refer default launcher in android). And by clicking a mini page in that, it should open the respective page.
Please guide me for the above problem.
Thanks,
Biplab


text:
Q: PHP foreach returning last row in multidimentional array I am trying get user value from multidimensional array as
$array = array();

$array["id"] = "1";
$array["name"] = "name1";
$array["country"] = "country1";

$array["id"] = "2";
$array["name"] = "name2";
$array["country"] = "country2";

$array["id"] = "3";
$array["name"] = "name3";
$array["country"] = "country3";

$array["id"] = "4";
$array["name"] = "name4";
$array["country"] = "country4";

foreach($array as $e){
    print_r($e);
}

It return me 4name4country4 only
I need to fetch rows like
foreach($array as $e){
    $id=$e['id'];
    $name=$e['name'];
    $country=$e['country'];
    echo $id.'/'.$name.'/'.$country.'
';
}

but this gives me error as Illegal string offset 'id'
from what I understood about array this should return all values, Please see why this simple array is not working and suggest any way to do it

A: Currently you are overwriting the keys. Need to add the keys properly. You have to build the array like -
$array[0]["id"] = "1";
$array[0]["name"] = "name1";
$array[0]["country"] = "country1";

$array[1]["id"] = "2";
$array[1]["name"] = "name2";
$array[1]["country"] = "country2";

OR
$array = array(
   0 => array('id' => 1, 'name' => 'name1', 'country' => 'country1'),
   1 => array('id' => 2, 'name' => 'name2', 'country' => 'country2'),
);

A: Instead, do it like so you won't have to give array keys manually
$array = array();

$array[] = array("id" => 123,  "name" => "Your name",  "country" =>  "UK");
$array[] = array("id" => 1342,  "name" => "Your name 2 ",  "country" =>  "UK");

then in foreach do this
foreach($array as $key => $val){

echo $key. ":     ".$val['id']. " " . $val['name'];
}

A: You have to create the multidimensional array like this, right now you're overwriting the array multiple times.
$arrays = [
  [0]=>
    ["id"] => "1",
    ["name"] => "name1",
    ["country"] => "country1"
  ],
  [1]=>[
     ...
  ]
];
foreach($arrays as $array){
    $id=$array['id'];
    $name=$array['name'];
    $country=$array['country'];
    echo $id.'/'.$name.'/'.'$country'.'
';
}


text:
Q: How can I solve $z^{-i} = 1+i$ Basically I need to solve  $z^{-i} = 1+i$
But the $-i$ is throwing me off.
As well, talking about differential equations how can I get the fundamental system of solutions of $y'''-3iy=0 $. I know it is a homogenous equation but the $i$ following the $y$ is throwing me off.
Thanks in advance.

A: $$-i\ln z=\ln(1+i)=\ln(\sqrt2e^{i\pi/4})=\dfrac{\ln2}2+i\left(2n\pi+\dfrac\pi4\right)$$
$$\ln z=i\cdot\dfrac{\ln2}2-\left(2n\pi+\dfrac\pi4\right)$$
$$z=e^{i\cdot\dfrac{\ln2}2-\left(2n\pi+\dfrac\pi4\right)}=e^{-\left(2n\pi+\dfrac\pi4\right)}\cdot e^{i\cdot\dfrac{\ln2}2}$$
Use Intuition behind euler's formula

A: By $z=re^{i\theta}$ we have
$$z^{-i}=1+i \implies r^{-i}e^{\theta}=\sqrt 2\cdot e^{i(\frac{\pi}4+2k\pi)}$$
that is

*

*$e^{\theta}=\sqrt 2$

*$r=e^{-(\frac{\pi}4+2k\pi)}$


text:
Q: Build SDK in Flutter/Dart and use it from Java / Web We are building an application in Flutter, which is composed of an SDK (no UI Code) and a Flutter UI, using the SDK.We have now the requirement to provide the SDK for other, native target platforms (iOS, Android, Web, JVM) and use it in existing applications. As far as we have understood this is possible for iOS and Android. But is this also possible (or planned) for Web and JVM? We simply want to minimise the effort to build the similar SDK in various platform specific technologies.
Thank you!

A: You can build your Flutter app targeting web https://docs.flutter.dev/development/platform-integration/web/faq#is-the-web-version-of-flutter-ready-for-production
If you want to target the Desktop then check https://docs.flutter.dev/development/platform-integration/desktop to see if it meets your requirements.


text:
Q: Read html from current UIWebview I have a UIWebview that shows some links. When I clic on a link, it sends me some JSON. In order to display the data that is sent to me, I need :
1) detect when a link is called
2) get the json
For 2), I've tried  [webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"]; that returns me :

{some JSON}

and [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName(\"pre\")"]; returns me an empty object. What other way do I have to get my JSON ?
And for 1) is there a UIWebView delegate methode to detect when a link is called ?

A: I have same problem. I solved by this code
    NSString *jsonString = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName(\"pre\")[0].innerHTML"];

A: The iOS Developer Library is your best friend. Turns out that UIWebView does have a protocol that you can subscribe to.
Here's the link to the delegate callbacks: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIWebViewDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intf/UIWebViewDelegate
The one you want is
    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

Implement this protocol method and you can introspect the NSURLRequest object for it's NSURL and then the rest is up to you...
Edit:
For completeness, I should mention the - (NSData *)HTTPBody instance method on NSURLRequest objects. You'll most likely find the JSON within that piece of NSData.
There is an NSJSONSerialization class in the Foundation framework that you can use to create NSObject's out of JSON data.
Here's what you have so far...
// UIWebView delegate method
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
  NSData *jsonData = request.HTTPBody;
  id jsonObj = [NSJSONSerialization JSONObjectWithData: jsonData options: NSJSONReadingMutableContainers error: nil];
  // do stuff with the object...
  ...
  // the webview shouldn't load the request since it's going to be raw json data (or is it)
  return NO;
}

In theory, this code should work but only if the JSON data that you receive is pure JSON. From your question, it seems like there's a bit of HTML attached to the JSON data so you will have to implement a method to strip the data of it's HTML parts. Be wary that there is alot of fine print when it comes to converting data structures in this manner. Check out the NSJSONSerialization documentation to get more specific information:
http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html
Happy coding!


text:
Q: get element id jquery on drop I've found a tutorial on w3schols, that helped me with drag and drop, but I have a noob question:
How can I get ev.target.id from drag(ev) function?

A: DRAG:
You can send the element itself as parameter:

And in the JS:
function drag(ev, obj)
{
    alert(obj.id);
}

DROP:

and JS:
function allowDrop(ev, obj)
{
    alert(obj.id);
}


text:
Q: Select statement scope In Go, I know that every new enclosing braces declare a new scope, this is true of all control flow statements. Today while writing a program, I stumbled in a scenario where I needed to use the select statement like below
select {
case <-ctx.Done():
    <-ch
    return ctx.Err()
case resp := <-ch:
    var b bytes.Buffer
    if _, err := io.Copy(&b, resp.Body); err != nil {
        return err
    }
}

From the above code, I would like to access the b variable after select statement is closed. Will that be possible?
I know I can move the logic that uses b inside the select, but I would rather not go that route because select is much complicated already on its own and want to keep it slim for easy understanding in future.

A: It's absolutely fine to declare a var outside the select if it's intended to be used after the select:
var b bytes.Buffer
select {
case <-ctx.Done():
    <-ch
    return ctx.Err()
case resp := <-ch:
    if _, err := io.Copy(&b, resp.Body); err != nil {
        return err
    }
}
... // use b here

There is no shadowing involved here, and you can't shadow unless you have another b declared in an inner scope. An assignment b = <something> inside the select here will just assign to the right b.


text:
Q: How to mock persisting and Entity with Mockito and jUnit I'm trying to find a way to test my entity using Mockito;
This is the simple test method:
@Mock
private EntityManager em;

@Test
public void persistArticleWithValidArticleSetsArticleId() {
    Article article = new Article();
    em.persist(article);
    assertThat(article.getId(), is(not(0L)));
}

How do I best mock the behaviour that the EntityManager changes the Id from 0L to i.e. 1L? Possibly with the least obstructions in readability.
Edit:
Some extra information; Outside test-scope the EntityManager is produced by an application-container

A: public class AssignIdToArticleAnswer implements Answer<Void> {

    private final Long id;

    public AssignIdToArticleAnswer(Long id) {
        this.id = id;
    }

    @Override
    public Void answer(InvocationOnMock invocation) throws Throwable {
        Article article = (Article) invocation.getArguments()[0];
        article.setId(id);
        return null;
    }
}

And then
doAnswer(new AssignIdToArticleAnswer(1L)).when(em).persist(any(Article.class));

A: similar answer as above, but with lambdas
   doAnswer((InvocationOnMock invocation) -> {
        Article article = (Article) invocation.getArguments()[0];
        article.setId(1L);
        return null;
    }).when(em).persist(any(Article.class));

A: You could use a Mockito Answer for this.
doAnswer(new Answer<Object>(){
     @Override
     public Object answer(InvocationOnMock invocation){
        Article article = (Article) invocation.getArguments()[0];
        article.setId(1L);
        return null;
     }
  }).when(em).persist(any(Article.class));

This tells Mockito that when the persist method is called, the first argument should have its setId method invoked.
But if you do this, I don't understand what the purpose of the test would be.  You'd really just be testing that the Mockito Answer mechanism works, not that the code of Article or of EntityManager works correctly.


text:
Q: How can I implement a zoomable draggable interface the same as seatgeek? Seatgeek has a zoomable draggable tiled interface.
An example is here:
http://seatgeek.com/sf-bulls-yankees-tickets/3-2-2012-tampa-george-steinbrenner-field/mlb/785875/#
I want to implement a scrollable draggable interface like this but I cannot use Google's code for google maps.
Also I need the tile system like google maps where it pulls tiles from the server for rendering the map.
Need to implement in javascript. What library can I use? How can I do it?
How does seatgeek do it?

I de-compiled their javascript http://pastebin.com/PVjahhnH

A: *

*Map Client

*

*OpenLayers

*OpenLayers Examples

*Map Data

*

*OpenStreetMap

A: This kind of interface seems complex to implement, but it is just some math tricks. If you decide to implement your own algorithm, try this out:

*

*Take the full image and create tiles in different scales and consequently with different depth.

*The user start looking at the scene in real scale, composed by 16 tiles created from the original scene.
If the user drags, all tiles moves equaly. If the user zoom in, all tiles are scaled up.

*If the user zoom more than X, you change the 16 tiles by their 16 child tiles! Got it? Higher the zoom, higher the detail. To avoid having 36000 tiles at the same time, generate with different depth and switch them on the fly.

You just need to load and move the tiles. Multiply tile x, y, width, height by the zoom. Keep the focus of the scene in the mouse position. Take a look at this example. It does exactly the steps above, but with a lot of microscope images. It is the same idea of google maps.

A: CloudMade map tile  is one of the server based map tile service. Please read this page server http://cloudmade.com/documentation/map-tiles or contact with alex@cloudmade.com for more information.


text:
Q: TeamCity: use multiple values for environment variable I'd like to run a build with different values for a specific environment variable.
I know that Jenkins alows this with its "matrix" builds, where you define a set of env variables and it builds the project with all the combinations of these variables:
2 variables:
TARGET = X86, X64
DEBUG  = 0,   1

Will produce 4 builds:
        | X86 | X64 |
DEBUG 0 |  X  |  X  |
DEBUG 1 |  X  |  X  |

I didn't find the option in TC, apart from copy/paste a build conf and modify by hand the environment variable.
Is this possible in teamcity?

A: There is no existing option for that in TeamCity (as of TeamCity 8.0.1).
Your options here are:

*

*create a base build configuration template and 4 build configurations which inherit from this template with different setting for environment variables

*use a manual triggering of the builds, but alter the value of the environment variable on build start (use Run custom build dialog for this)

*write a custom TeamCity plugin which would allow to run a bunch of builds with appropriate variables set
Regards,
KIR


text:
Q: How to copy some columns from a table and put into a word file
Here is an example of a table. I want to be able to put the product name, sale price, qty sold and total profit of each item into a table on a word document, if the qty has a value. No idea how to start.
Would it also be possible to add this to the end of an existing word file?

A: This might not be the best solution but it's definitely simple:
Activate filters, unselect "Blanks" from the Qty Sold column. Copy and paste the whole table into Word then right click to delete the columns you don't need.
Alternatively, if you already have the table worked up in Word, then you can select the individual columns you need and copy/paste only those.


text:
Q: Consuming multiple kafka topics in the same consumer class I have a spring boot project and I am spring-kafka to connect to the underlying kafka event hub.
I have to listen to 2 different topics in the same consumer class. I have two approaches to do so.
One is to have two kafka listeners like this:
 @KafkaListener(topics = "topic1")
public void consumeTopic1(String message) throws Exception {
   //do something
  }

 @KafkaListener(topics = "topic2")
public void consumeTopic2(String message) throws Exception {
   //do something
  }

Another approach is to have 2 topics in the same kafkaListener like this
 @KafkaListener(topics = {"topic1", "topic2"})
public void consumeTopics(String message) throws Exception {
   //do something
  }

Since I am new to kafka, I am not sure what is the difference between the two approaches. Which one is performant  and resource effective.
One thing I am wondering about is that would it listen to both the topics on a single thread in both approaches or it would spawn a thread each to listen to these topics.
Using approach 1, I have had troubles with the consumer where I see some delays in the consumption of the topics.
Please suggest me based on your experience as I am pretty new to kafka
===============EDIT========
Kafka properties are in application.yml as follows:
 kafka:
    properties:
      topics:
        topic1: topic1
        topic2: topic2
    bootstrap-servers: server1,server2
    producer:
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
      retries: 4
    consumer:
      group-id: mygroupid
      auto-offset-reset: latest
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: org.apache.kafka.common.serialization.StringDeserializer

A: *

*The purpose of creating multiple topics is to spread the data, and
subsequently, the processing of data, across multiple
cores/processes/threads.

*Even then, you can start with a single    consumer for multiple
topics until a delay is observed in processing    events in queue.
Then you can separate them out.


text:
Q: unique_ptr vs shared_ptr - design I'm writing a card game. I have the following classes: Card, Deck, Player, Board, GameLogic.
Deck holds a vector of unique_ptr Cards. Then a card is drawn from the deck and passed to a player. Then player picks a card and puts... Here I have a design problem. Because up to now it's totally fine to have a unique_ptr. But then I want to pass a card to both Board and GameLogic.
Currently I converted a unique_ptr to shared_ptr. But I find it either ugly and not logical.
I believe that proper usage of pointers is very important and should tell you about the lifetime of a variable. I'm doing something wrong but don't know what...
Do you have some suggestion about how to solve it?

A: Following your own words:

Deck holds a vector of unique_ptr Cards. Then a card is drawn from the
  deck and passed to a player. Then player picks a card and puts... Here
  I have a design problem. Because up to now it's totally fine to have a
  unique_ptr. But then I want to pass a card to both Board and
  GameLogic.

Probably you create each card in the constructor. Though it is perfectly feasible, I don't see the point. Provided there are always the same, fixed, number of cards. I mean, you don't create new cards of each type or whatever.
I would just create the deck of cards as a simple array, and pass average pointers to players and so on. The cards will be just destroyed when the deck is destroyed.
class Deck {
public:
    const static int NumCards = ...;
...
private:
    Card cards[NumCards];
};

class Player {
public:
    void dealt(Card*[] cards);
};

One of the advantages of C++ is that lets you choose between storing objects in the heap or the stack. While the former is more flexible (when the number of available cards changes over time, for example), the latter is much more efficient, provided you know the number of items beforehand, as apparently you do in this case.
Hope this helps.

A: To use objects with specific life spans:

*

*Prefer values over pointers.  Copy the values or pass references as needed, but don't store the references as the referenced value can be removed.

*When pointers are needed, prefer unique_pointer if you can identify one owner. Pass references as needed, but don't store them.

*Use shared_pointer when there are multiple owners or when "references" need to be stored. Pass weak_pointers, which can be stored and locked as needed.

Remark that you could also give some id as reference so later on, you could access objects that could have been removed.  If your Card is nothing more than an id (queen of hearts), just pass a copy of it.

A: While I agree with the sentiment in the other answers that pointers aren't strictly necessary here, the simplest way to go if you do use pointers is to employ references:
class Deck
{
private:
    std::vector<unique_ptr<Card>> cards;
public:
    const Card& get_card(unsigned index); // returns cards[index]
}

A const reference allows you to reference it without having to convert it to shared_ptr (and without the risk of other parts of the code modifying it).

A: if you are not satisfied with both shared pointer and unique pointer, there is no better option than normal pointer. Use observer pattern which is helpful when one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.


text:
Q: Getting error UserSession.OnActionExecuting(ActionExecutingContext): no suitable method found to override in mvc 5? I have created one demo in mvc 5 and now I need to create one custom filter in my demo. I have used mvc 5.
I need to check every time what method is execute like is a ajax call or action method call in mvc.
Here I have write like this code in my class.
 public class UserSession
 : System.Web.Http.Filters.ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var session = filterContext.HttpContext.Session;
        if (ApplicationSession.IsSessionAlive)
            return;

        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            var ajaxRedirectTarget = new RouteValueDictionary { { "action", "FailAuthenticationAjax" }, { "controller", "Home" } };
            filterContext.Result = new RedirectToRouteResult(ajaxRedirectTarget);
        }
        else
        {
            var redirectTarget = new RouteValueDictionary { { "action", "Login" }, { "controller", "Account" } };
            filterContext.Result = new RedirectToRouteResult(redirectTarget);
        }
    }
}

but I got error like this UserSession.OnActionExecuting(ActionExecutingContext): no suitable method found to override
After I have put this class on my controller like this.
[UserSession]
public class DashboardController
{

}

any one know how to fixed this issue in mvc 5?


text:
Q: How to change directory in "Publish over SSH plugin" in Jenkins I'm using Jenkins' Publish Over SSH plugin to deploy my builds to a windows machine which has SSH server running. Issue is that I need to deploy the build into E Drive of the target system, but when I try to give E drive location in the "Remote Directory" box of the plugin, it throws Exception as "Unable to change" directory.
Jenkins Error

A: Finally got a solution:
To use a directory name with : in it use this notation:
like "E:\Test"  use this
/E=/Test/
Update: after comments from @"Brian Ogden"
/E:Test/


text:
Q: Send Query String in RedirectToAction MVC I've two action method in the following controller-
public class VisitMasterController
{
    public ActionResult StartBrVisit()
    {
        string id=(Request.QueryString["id"].ToString(); //value=null here
    }

    public ActionResult BrNotPresent()
    {
         return RedirectToAction("StartBrVisit","VisitMaster" , new { id = "id", name = "name" });
    }
{

After Redirect, Request.QueryString["id"] returns null.
My default route config is-
         context.MapRoute(
         "BR_default",
         "BR/{controller}/{action}/{id}",
         new { action = "Index", id = UrlParameter.Optional },
         new[] { "OpinionLeader.Areas.BR.Controllers" } //add this line
     );

Any help?

A: You have defined a route with a parameter named id so when you use new { id = "id" }, the RedirectToAction() method finds a match and adds the value as a route value, not a query string value (in the case of name, there is no match, so its value is added as a query string value). You could access it using
string id = (string)Request.RequestContext.RouteData.Values["id"]

However, it would be far easier to add a parameter to your method
public ActionResult StartBrVisit(string id)


text:
Q: Convert Int16 to String Swift 4 I am trying to convert an Int16 value to String but it gives value with Optional, won't allow me to forced unwrap it.
String(describing:intValue)

Result : Optional(intValue)

A: Unwrap intValue first, then pass it to the string initializer: String(unwrappedIntValue)
Here are some ways of handling the optional. I've added explicit string# variables with type annotations, to make it clear what types are involved
let optionalInt: Int? = 1

// Example 1
// some case: print the value within `optionalInt` as a String
// nil case:  "optionalInt was nil"

if let int = optionalInt {
    let string1: String = String(int)
    print(string1)
}
else {
    print("optionalInt was nil")
}

// Example 2, use the nil-coalescing operator (??) to provide a default value
// some case: print the value within `optionalInt` as a String
// nil case:  print the default value, 123

let string2: String = String(optionalInt ?? 123)
print(string2)

// Example 3, use Optional.map to convert optionalInt to a String only when there is a value
// some case: print the value within `optionalInt` as a String
// nil case:  print `nil`

let string3: String? = optionalInt.map(String.init)
print(string3 as Any)

// Optionally, combine it with the nil-coalescing operator (??) to provide a default string value
// for when the map function encounters nil:
// some case: print the value within `optionalInt` as a String
// nil case:  print the default string value "optionalInt was nil"

let string4: String = optionalInt.map(String.init) ?? "optionalInt was nil"
print(string4)

A: You can convert a number to a String with string interpolation:
let stringValue = "\(intValue)"

Or you can use a standard String initializer:
let stringValue = String(intValue)

If the number is an Optional, just unwrap it first:
let optionalNumber: Int? = 15

if let unwrappedNumber = optionalNumber {
  let stringValue = "\(unwrappedNumber)"
}

Or
if let unwrappedNumber = optionalNumber {
  let stringValue = String(unwrappedNumber)
}


text:
Q: Angular/material ui - programatically select mat-selection-list I have a mat-selection-list that I need to programmatically check specific items when the component loads. The items I need to check will be selected based on the [value] of the mat-list-option. I can't find any documentation on this. The html is pretty simple:
<mat-selection-list color="primary" #suretyList formControlName="AgentAgencyAndSureties">
    <mat-list-option *ngFor="let surety of suretyNames" [value]="surety.Id">
        {{surety.SuretyName}}
    </mat-list-option>
</mat-selection-list>

I just want to check items with a specific surety.Id in the value. It doesn't seem like this should be too hard to do but like I said, I can't find any examples or good documentation on this.
I am using Angular 10 for both the core and material UI

A: try mat-list-option selected input.
<mat-list-option  [selected]="condition">....

A: tmsbrndz pointed me in the right direction. I created the following function:
  isChecked(id): boolean {
        const exists = this.agentModel.AgentAgencyAndSureties.some(x => x.AgencyAndSuretyId == id);
        return exists;
  }

then added the selected attribute using the function:
<mat-selection-list color="primary" #suretyList formControlName="AgentAgencyAndSureties">
    <mat-list-option *ngFor="let surety of suretyNames" [value]="surety.Id" [selected]="isChecked(surety.Id)">
    {{surety.Id + " " + surety.SuretyName}}
    </mat-list-option>
</mat-selection-list>

A: You should use [selected] attribute, because there's no information about form control support in this component (https://material.angular.io/components/list/api#MatSelectionList)


text:
Q: Change training parameters in the config file after training for a certain number of steps using the Tensorflow Object Detection API I have trained an Inception Resnet v2 model on a dataset for 61000 steps so far with the following values in the configuration file of the model:
adam_optimizer: {
      learning_rate: {
        manual_step_learning_rate {
          initial_learning_rate: 0.0003
          schedule {
            step: 150000
            learning_rate: .0001
          }

Now, If I want to reduce the learning rate of my model from now on, will making the below change:
adam_optimizer: {
      learning_rate: {
        manual_step_learning_rate {
          initial_learning_rate: 0.0003
          schedule {
            step: 60000
            learning_rate: .0001
          }

And restarting from the checkpoint actually reduces the learning rate of my model from 0.0003 to 0.0001 since the number of steps that it has already trained for so far is greater than 60000?
If not, is there any other way to achieve this?

A: One possible way is to use the already trained 61000 steps model file as the fine-tune checkpoint and then you can modify the lr as you like. In this case, you are essentially training from step 1.

A: goto to your config file and search this node then add the bold line train_config: { num_steps: 5000


text:
Q: Decrypting AES/CBC/PKCS5Padding in iOS I have a file that has been encrypted on Android using this code:
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESUtils {
    private static final String IV_STRING = "123456789876543";
    private String key = "mysecretkey12345";

    public static byte[] encryptData(String key, byte[] byteContent) {
        byte[] encryptedBytes = null;
        try {
            byte[] enCodeFormat = key.getBytes();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
            byte[] initParam = IV_STRING.getBytes();
            IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
            encryptedBytes = cipher.doFinal(byteContent);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptedBytes;
    }
    public static byte[] decryptData(String key, byte[] encryptedBytes) {
        byte[] result = null ;
        try {
            byte[] sEnCodeFormat = key.getBytes();
            SecretKeySpec secretKey = new SecretKeySpec(sEnCodeFormat, "AES");
            byte[] initParam = IV_STRING.getBytes();
            IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
            result = cipher.doFinal(encryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

I tried to reverse engineer the decryption in Swift using CommonCrypto like this:
import CommonCrypto

let keyStr:String = "mysecretkey12345"
let ivStr:String = "123456789876543"

func aesDecrypt(data:NSData) -> Data? {
        let k:NSData = keyStr.data(using: .utf8)! as NSData
        let dbytes = data.bytes
        let kbytes=k.bytes

        if let keyData = keyStr.data(using: .utf8),
           let cryptData    = NSMutableData(length: Int((data.length)) + kCCBlockSizeAES128) {

                let keyLength              = size_t(kCCKeySizeAES128)
                let operation: CCOperation = UInt32(kCCDecrypt)
                let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
                let options:   CCOptions   = UInt32(kCCOptionPKCS7Padding)

                var numBytesEncrypted :size_t = 0

                let cryptStatus = CCCrypt(operation,
                    algoritm,
                    options,
                    kbytes, keyLength,
                    ivStr,
                    dbytes, data.length,
                    cryptData.mutableBytes, cryptData.length,
                    &numBytesEncrypted)

                if UInt32(cryptStatus) == UInt32(kCCSuccess) {
                    cryptData.length = Int(numBytesEncrypted)
                    return (cryptData.copy() as! Data)
                }
                else {
                    return nil
                }
        }
        return nil
    }

I am quite new to encryption, but from my research I found that CC uses CBC by default and PKCS7Padding is basically identical to PKCS5Padding. However, the decryption does not deliver the results that I expect!
The swift code was frankensteined together from various sources, including many solutions suggested here on stackoverflow. Main problem is that most examples use key and iv as Data, whereas I have strings - not sure my conversion causes problems. Secondly, many simply convert string messages, whereas I convert data (from files) directly - should not affect it too much, actually makes the code simpler avoiding data->string conversion.
But since it doesn't work, what did I miss?

A: Okay, I think I figured the problem. Obviously, there is a problem with NSData.bytes and one should work withUnsafeBytes. Furthermore, my issue may was that the IV was not part of the data, as many examples assumed, so I missed 16 bytes when decrypting. The following code works for me, hope it will help someone!
func decrypt(data: Data) -> Data {
    let key: Data = keyStr.data(using: .utf8) ?? Data()
    let iv: Data = ivStr.data(using: .utf8) ?? Data()

    if(keyStr.count == kCCKeySizeAES128){print("Key OKAY")} else {print("Key NOT okay")}
    if(ivStr.count == kCCBlockSizeAES128){print("IV OKAY")} else {print("IV NOT okay")}

    var buffer = Data(count: data.count)

    var numberBytesDecrypted: Int = 0

    let cryptStatus: CCCryptorStatus = key.withUnsafeBytes {keyBytes in
        data.withUnsafeBytes {dataBytes in
            buffer.withUnsafeMutableBytes {bufferBytes in iv.withUnsafeBytes {ivBytes in
                CCCrypt(         // Stateless, one-shot encrypt operation
                    CCOperation(kCCDecrypt),                        // op: CCOperation
                    CCAlgorithm(kCCAlgorithmAES128),                // alg: CCAlgorithm
                    CCOptions(kCCOptionPKCS7Padding),                                        // options: CCOptions
                    keyBytes.baseAddress,                           // key: the "password"
                    key.count,                                      // keyLength: the "password" size
                    ivBytes.baseAddress,                          // iv: Initialization Vector
                    dataBytes.baseAddress!,    // dataIn: Data to decrypt bytes
                    data.count,                                     // dataInLength: Data to decrypt size
                    bufferBytes.baseAddress,                        // dataOut: decrypted Data buffer
                    data.count,                                     // dataOutAvailable: decrypted Data buffer size
                    &numberBytesDecrypted                           // dataOutMoved: the number of bytes written
                )}
            }
        }
    }

    if(cryptStatus == CCCryptorStatus(kCCSuccess)){
        return buffer[..<numberBytesDecrypted]
    } else {
        print("Decryption failed")
        return data
    }
}

A: Okay, turned out one of my test files was corrupted and my decryption worked all along. Here is a simpler version without withUnsafeBytes:
func decrypt(data: Data)  -> Data {
    let key:Data = keyStr.data(using: .utf8)!
    let iv:Data = ivStr.data(using: .utf8)!

    var buffer = [UInt8](repeating: 0, count: data.count + kCCBlockSizeAES128)
    var bufferLen: Int = 0

    let status = CCCrypt(
        CCOperation(kCCDecrypt),
        CCAlgorithm(kCCAlgorithmAES128),
        CCOptions(kCCOptionPKCS7Padding),
        [UInt8](key),
        kCCBlockSizeAES128,
        [UInt8](iv),
        [UInt8](data),
        data.count,
        &buffer,
        buffer.count,
        &bufferLen
    )

    if(status == kCCSuccess) {
        return Data(bytes: buffer, count: bufferLen)}
    else {
        print("Decryption failed")
        return data
    }
}


text:
Q: Tokbox Video not working in iOS, Macbook Recently implemented Tokbox in a project, I recognized there are some issues with iOS and OSX.

*

*Regarding iOS(iPad was used for testing), the Tokbox popped up with a message stating incompatibility.

*In OSX, the video comes for five seconds and disappears.

These are the following issues faced with Tokbox, well it worked well in Ubuntu, Windows. WebRTC is still not supported in iOS browser. Is there anything possible way to support WebRTC in iOS browsers? Did anyone face the similar problem as I faced with Macbook?
It is Macbook Air with OS X Yosemite version 10.10.5.

A: Up to my knowledge, there is no support for WebRTC on iOS browsers. If you want to use WebRTC on iOS you will need a native application.


text:
Q: Redux saga failed in production I've been trying to tackle this problem more than 2 weeks now. Everything works fine in development mode. But not in production mode. The example below are shown using Redux Saga environment (I'm still new in redux saga). But I've tried re-do it using Context API. Unfortunately the problem still persists. (below are the images showing successful process in development mode & unsuccessful process in production mode)

*

*successful in development mode

*unsuccessful in production mode

My guess it could be something to do with status code 304 Not Modified. Since the data I tried to fetch not changing, thus it will use cached data in browser. But I don't know how to setup my server so that I can handle this issue. I have read a bunch of online threads. But none were able to resolve my issue.
You may have a look at my code right now. Bear in mind that everything works just fine in development mode. From the images above you can see that I don't have problem logging in. Just fetching & getting data to be displayed in dashboard got error.

*

*client/src/redux/actions/Dashboard.js (Action)

import { SET_ISDASHBOARD, SET_LOADING, SET_ERROR } from '../sagas/types'

// Set Loading
export const setLoading = (status) => ({
  type: SET_LOADING,
  payload: status
})

// Set Error
export const setError = (error) => ({
  type: SET_ERROR,
  payload: { error: error.status, message: error.message }
})

// Dashboard
export const isDashboard = () => ({
  type: SET_ISDASHBOARD
})

*

*client/src/redux/reducers/Dashboard.jd (Reducer)

import { SET_ERROR, SET_LOADING, SET_ISDASHBOARD, SET_DASHBOARD } from '../sagas/types'

const initialState = {
  user: {
    id: '',
    name: '',
    email: ''
  },
  loading: false,
  error: false,
  message: ''
}

const reducer = (state = initialState, action) => {
  switch(action.type) {
    case SET_ISDASHBOARD:
      return {
        ...state,
        loading: true
      }
    case SET_DASHBOARD:
      return {
        ...state,
        user: {
          ...state.user,
          id: action.payload.id,
          email: action.payload.email,
          name: action.payload.name
        }
      }
    case SET_ERROR:
      return {
        ...state,
        error: action.payload.status,
        message: action.payload.message
      }
    case SET_LOADING:
      return {
        ...state,
        loading: action.payload
      }
    default:
      return state
  }
}

export default reducer

*

*client/src/redux/sagas/handlers/dashboard.js (Saga handlers)

import { call, put } from 'redux-saga/effects'
import { requestGetDashboard } from '../requests/dashboard'
import { SET_LOADING, SET_ERROR, SET_DASHBOARD } from '../types'

export function* handleGetDashboard(action) {
  try {
    const response = yield call(requestGetDashboard)
    const result = response.data.data
    console.log(response); console.log(result)
    // dispatch set dashboard
    yield put({ type: SET_DASHBOARD, payload: { id: result.id, email: result.email, name: result.name } })
  } catch(error) {
    // console.log(error); console.log(error.response)
    const result = error.response.data
    const payload = {
      status: true,
      message: result.error
    }

    // dispatch setError
    yield put({ type: SET_ERROR, payload: payload })
  }

  // loading to false
  yield put({ type: SET_LOADING, payload: false })
}

*

*client/src/redux/sagas/requests/dashboard.js (Saga requests)

import axios from 'axios'

/** get dashboard */
export const requestGetDashboard = () => {
  return axios.get(
    '/api/v1/dashboard',
    {
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${localStorage.getItem('uid')}`
      }
    }
  )
}

*

*client/src/redux/sagas/rootSaga.js (Root Saga)

import {
  SET_ISLOGIN, SET_ISLOGOUT, SET_ISAUTH,
  SET_ISDASHBOARD,
} from './types'
import { takeLatest } from 'redux-saga/effects'
import { handleClientAuth, handlePostLogin, handlePostLogout } from './handlers/auth'
import { handleGetDashboard } from './handlers/dashboard'

export function* watcherSaga() {
  // auth
  yield takeLatest(SET_ISLOGIN, handlePostLogin)
  yield takeLatest(SET_ISLOGOUT, handlePostLogout)
  yield takeLatest(SET_ISAUTH, handleClientAuth)
  // dashboard
  yield takeLatest(SET_ISDASHBOARD, handleGetDashboard)
}

*

*client/src/redux/sagas/types.js (Types)

/** for AUTH */
export const SET_ISLOGIN = 'SET_ISLOGIN'
export const SET_ISLOGOUT = 'SET_ISLOGOUT'
export const SET_ISAUTH = 'SET_ISAUTH'
export const SET_AUTH = 'SET_AUTH'
export const SET_LOADING = 'SET_LOADING'
export const SET_ERROR = 'SET_ERROR'

/** for DASHBOARD */
export const SET_ISDASHBOARD = 'SET_ISDASHBOARD'
export const SET_DASHBOARD = 'SET_DASHBOARD'

Please point me to any directions that could help get closer insight to this problem.


text:
Q: Is there any problems with putting a lambda in a concept? Take this concept for example - all classes that have a member named func should satisfy this concept.
template<class T>
concept has_func =
requires(T) {
   { [](T& t, auto&&... args){
         t.func(args...);
      }
   };
};

struct STemplateFunc {
    template<class T>
    void func(T){};
};

template<has_func E>
void FuncFunc(E a) {}

int main() {
   FuncFunc(STemplateFunc{});
}

Are there any problems with this trick - Putting a lambda in the concept or with putting generic lambda or variadic lambda?
gcc 10.2 accepts it: godbolt

A: Going the route of using type traits seems more idiomatic and also works with all the big 3 compilers.
template<class T>
concept has_func = std::is_member_function_pointer_v<decltype(&T::func)>;

Godbolt

A: The lambda in your suggestion is ill-formed, no diagnostic required, if a T is substituted which does not have such a member func, because no valid instantiation exists of its function call operator template (and it can never be instantiated; [temp.res]/8.1).  This is the same restriction as with SFINAE.


text:
Q: AOT build error with BrowserAnimationsModule in platform-browser I'm currently working with Angular 4 and also apply Ahead-of-time compilation to reduce the amount of the boostrap time to my application. Everything is working fine but there is only one trouble when I try to apply some transition animation between states to the application.
I follow this solution.
When I try to build AOT by the command:
"ngc -p tsconfig-aot.json && rollup -c rollup-config.js"

It always ends up with this error :

"Unexpected value 'BrowserAnimationsModule in
  /home/alex/Documents/htdocs/music_performance/assets/node_modules/@angular/platform-browser/animations/index.d.ts'
  imported by the module 'AppModule in
  /home/alex/Documents/htdocs/music_performance/assets/app/app.module.ts'.
  Please add a @NgModule annotation."

Here is my app.module.ts file:
import {APP_BASE_HREF} from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

//SOME_COMPONENTS_IMPORT

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routing,
    BrowserAnimationsModule
  ],
  providers: [Globals],
  entryComponents: [ ... ],
  bootstrap: [AppComponent],
})
export class AppModule { }

Other configurations for AOT and roll-up, I do exactly same as this documentation:
https://angular.io/docs/ts/latest/cookbook/aot-compiler.html
Thank for your help.


text:
Q: Print a UIView, but NOT by rendering as a bitmap image Say you have a simple UIView with only text (ie, UILabel) and maybe some black lines.

Here's exactly how you can print that UIView...
render it as a UIImage, and print that...
- (IBAction)printB:(id)sender
    {
    // we want to print a normal view ... some UILabels, maybe a black line

    // in this technique, depressingly we CREATE AN IMAGE of the view...

    // step 1. make a UIImage, of the whole view.

    UIGraphicsBeginImageContextWithOptions(self.printMe.bounds.size, NO, 0.0);

    // [self.printMe.layer renderInContext:UIGraphicsGetCurrentContext()];
    // UIImage *asAnImage = UIGraphicsGetImageFromCurrentImageContext();
    // .... or, more futuristically.....
    [self.printMe drawViewHierarchyInRect:self.printMe.bounds
        afterScreenUpdates:NO];
    UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    // step 2. choose grayscale, etc

    UIPrintInfo *info = [UIPrintInfo printInfo];
    info.orientation = UIPrintInfoOrientationPortrait;
    info.outputType = UIPrintInfoOutputGrayscale;

    // step 3, print that UIImage

    UIPrintInteractionController *pic =
       [UIPrintInteractionController sharedPrintController];
    pic.delegate = self;
    //pic.printingItem = asAnImage;
    pic.printingItem = snapshotImage;
    pic.printInfo = info;

    UIPrintInteractionCompletionHandler completionHandler =
    ^(UIPrintInteractionController *pic, BOOL completed, NSError *error)
        {
        if (error)
            NSLog(@"failed... %@ %ld", error.domain, (long)error.code);
        if (completed)
            NSLog(@"completed yes");
        else
            NSLog(@"completed no");
        };

    [pic presentAnimated:YES completionHandler:completionHandler];
    }

But this gives you crap results. It's a ridiculous way to print typography. It should be being sent as postscript, or something.
on iPad screen...

when printed ..

Note that, of course, if you use a retina ipad it's a bit better, but that's not the point.  it's ridiculous to print text information, black lines, as an image.
Now, you'd think you could print a UIView something like this ...
pic.printFormatter = [someUIView viewPrintFormatter];

but I can't get that to work no matter what I try.
Does anyone have anything on this?  Thanks!
PS - note that in iOS, we've recently changed from using renderInContext to using the snapshot call. It makes absolutely no difference to the issue here, cheers.

A: As Apple Doc states,  viewPrintFormatter attribute of UIView is defined in a UIView category but it's available only for instances of type: UITextView, MKMapView and UIWebView.
So you can either:

*

*print UIView using it's layer attribute and flattening all its content

*initialize a UIWebView with the content to print and giving its viewPrintFormatter attribute to a pageRenderer and render each page


text:
Q: How do I trace SQL Server Failure Audit events? I recently took over management of a Windows 2003 server. The application log is being filled up with messages like these:
Event Type: Failure Audit
Event Source: MSSQLSERVER
Event Category: (4)
Event ID: 18456
Date:  3/5/2010
Time:  4:00:30 PM
User:  N/A
Computer: FAIROAKS1
Description:
Login failed for user 'administrator'. [CLIENT: <local machine>]
Data:
0000: 18 48 00 00 0e 00 00 00   .H......
0008: 0a 00 00 00 46 00 41 00   ....F.A.
0010: 49 00 52 00 4f 00 41 00   I.R.O.A.
0018: 4b 00 53 00 31 00 00 00   K.S.1...
0020: 07 00 00 00 6d 00 61 00   ....m.a.
0028: 73 00 74 00 65 00 72 00   s.t.e.r.
0030: 00 00                     ..

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

I'd like to figure out what program is causing these. Is there a way to trace and find out which process is causing these errors?

A: This is caused by some account not being able to log to the SQL Server instance installed on that server.
The message above means there is a SQL login (not Windows Auth) called "administrator" that is not set up in sys.server_principals or the password used is incorrect.
Now, if you run SQL profiler then you should be able to trap the connection attempt including HostName and Application name. Audit Login Failed Event Class is a good starting point.
Potentially, this is a serious issue: it could be an attack, of a failed monitor attempt. But it's nice you can shut-down your SQL Server instance and no-one notices ... :-)


text:
Q: Android Webview não retorna conteúdo do site Tento executar a aplicação abaixo sem sucesso. O erro retornado informa que o site não responde, o que pode ser?
MainActivity.java e logcat. Agradeço antecipadamente pela sua atenção.
package com.mycompany.TesteWebView;

import android.app.*;
import android.os.*;
import android.webkit.*;

public class MainActivity extends Activity
{
@Override
   protected void onCreate(Bundle         savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

WebView myWebView = (WebView)      findViewById(R.id.webview);
  WebSettings webSettings =      myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
 myWebView.loadUrl("http://www.google.com.uk");
             }
    }

log:
Late-enabling -Xcheck:jni
04-02 21:13:16.682 23877 23877 W        System                                       ClassLoader      referenced unknown path:      /data/app/com.mycompany.TesteWebView-2/lib/arm
 04-02 21:13:25.541 23877 23877 I   WebViewFactory                               Loading com.google.android.webview version 56.0.2924.87 (code 292408700)
 04-02 21:13:25.696 23877 23877 I   art                                          Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.TokenBindingManagerAdapter>
 04-02 21:13:25.697 23877 23877 I   art                                          Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.TokenBindingManagerAdapter>
04-02 21:13:25.704 23877 23877 I   art                                          Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.ServiceWorkerControllerAdapter>
04-02 21:13:25.705 23877 23877 I   art                                          Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.ServiceWorkerControllerAdapter>
04-02 21:13:25.718 23877 23877 I   cr_LibraryLoader                             Time to load native libraries: 2 ms (timestamps 2997-2999)
04-02 21:13:25.718 23877 23877 I   cr_LibraryLoader                             Expected native library version number "56.0.2924.87", actual native library version number "56.0.2924.87"
 04-02 21:13:25.760 23877 23877 I   cr_LibraryLoader                             Expected native library version number "56.0.2924.87", actual native library version number "56.0.2924.87"
 04-02 21:13:25.763 23877 23877 I   chromium                                     [INFO:library_loader_hooks.cc(163)] Chromium logging enabled: level = 0, default verbosity = 0
04-02 21:13:25.779 23877 23877 I   cr_BrowserStartup                            Initializing chromium process, singleProcess=true
04-02 21:13:25.814 23877 23877 I   Adreno-EGL                                   <qeglDrvAPI_eglInitialize:379>: QUALCOMM Build: 10/09/15, 6cbbf7d, I3193f6e94a
 04-02 21:13:26.183 23877 23877 I   cr_Ime                                       ImeThread is enabled.
04-02 21:13:26.202 23877 24117 W   cr_media                                     Requires BLUETOOTH permission
04-02 21:13:26.255 23877 24122 D   OpenGLRenderer                               Use EGL_SWAP_BEHAVIOR_PRESERVED: true
 04-02 21:13:26.367 23877 24122 I   OpenGLRenderer                               Initialized EGL, version 1.4
 04-02 21:13:26.750 23877 24142 E   libEGL                                       validate_display:255 error 3008 (EGL_BAD_DISPLAY)
 04-02 21:13:26.875 23877 24142 W   VideoCapabilities                            Unrecognized profile 2130706433 for video/avc
 04-02 21:13:26.902 23877 24142 W   VideoCapabilities                            Unrecognized profile/level 0/3 for video/mpeg2
 04-02 21:13:26.952 23877 24142 I   VideoCapabilities                            Unsupported profile 4 for video/mp4v-es
04-02 21:13:27.023 23877 23877 W   cr_BindingManager                            Cannot call determinedVisibility() - never saw a connection for the pid: 23877
04-02 21:13:27.036 23877 23877 W   cr_BindingManager                            Cannot call determinedVisibility() - never saw a connection for the pid: 23877
04-02 21:13:33.536 23877 24122 E   Surface                                      getSlotFromBufferLocked: unknown buffer: 0xb8f77c70

(https://i.stack.imgur.com/qObvb.png)

A: Verifique os seguintes itens:

*

*Permissão de Internet no AndroidManifest.xml (<uses-permission android:name="android.permission.INTERNET" />)

*Site existe realmente.

Fiz um teste com o site que você está tentando acessar: www.google.com.uk, porém ele não está acessível nem no browser. Faça um teste com o www.google.com.


text:
Q: Removing pages in a pdf file conditioning on something using Python I have a PDF file that has around 1000 pages and want to remove some of the pages conditioning on not finding a specific word. For instance, the code would search for a specific word such as "STACKOVER", if it cannot find that word on the page, remove the page and continue to the following page, and at the end saves the file.

A: The way to do this is: First, define the search words you are looking for (in my case I tested it on a medical journal and searched for searchwords=['unclear risk for poorly']). Second, find all pages containing the word or string and store the page numbers in a list (pages_to_delete). For safe keeping, I put them i a csv file giving the page in which a specific searchword is found. Third, open to original pdf, delete the pages contained in the list and save to a new pdf.
import PyPDF2
import re
from PyPDF2 import PdfFileWriter, PdfFileReader

pdfFileObj=open(r'C:\Users\s-degossondevarennes\......\dddtest.pdf',mode='rb')
pdfReader=PyPDF2.PdfFileReader(pdfFileObj)
number_of_pages=pdfReader.numPages

pages_text=[]
words_start_pos={}
words={}

searchwords=['unclear risk for poorly']

pages_to_delete = []

with open('Pages.csv', 'w') as f:
    f.write('{0},{1}\n'.format("Sheet Number", "Search Word"))
    for word in searchwords:
        for page in range(number_of_pages):
            print(page)
            pages_text.append(pdfReader.getPage(page).extractText())
            words_start_pos[page]=[dwg.start() for dwg in re.finditer(word, pages_text[page].lower())]
            words[page]=[pages_text[page][value:value+len(word)] for value in words_start_pos[page]]
        for page in words:
            for i in range(0,len(words[page])):
                if str(words[page][i]) != 'nan':
                    f.write('{0},{1}\n'.format(page+1, words[page][i]))
                    pages_to_delete.append(page)

infile = PdfFileReader(r'C:\Users\s-degossondevarennes\.......\dddtest.pdf', 'rb')
output = PdfFileWriter()

for i in range(infile.getNumPages()):
    if i not in pages_to_delete:
        p = infile.getPage(i)
        output.addPage(p)

with open('Newdddtest.pdf', 'wb') as f:
    output.write(f)

Update
If you want to disregard whether the text is bold or not replace
words_start_pos[page]=[dwg.start() for dwg in re.finditer(word, pages_text[page].lower())]

with
words_start_pos[page]=[dwg.start() for dwg in re.finditer(word, pages_text[page])]


text:
Q: Why tweepy.Cursor is returning empty file when it should not I'm trying to crawl down tweets from Netherlands through twitter api, but it returns an empty file and does not show any bug. I know people in Netherlands speak English and use twitter so it does not make sense. Here is my code:
The set up part (should be fine):
import tweepy
import csv
import json
import pandas as pd
from pprint import pprint

key_file = 'keys.json'
# Loading your keys from keys.json (which you should have filled
# in in question 1):
with open(key_file) as f:
    keys = json.load(f)
# if you print or view the contents of keys be sure to delete the cell!
consumer_key = keys["consumer_key"]
consumer_secret = keys["consumer_secret"]
access_token = keys["access_token"]
access_token_secret = keys["access_token_secret"]
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True)

Here is the function I wrote to get data:
def tweet_obtainer(file_name,key_word = None, language = None,  tweet_since, tweet_until
               , geo = None, place = None, tweet_mode = 'extended', retweet = 'false', number_of_tweet = 100):

    ds_tweets_save_path = file_name + '.json'
    example_tweets = [t._json for t in tweepy.Cursor(api.search, q= key_word,
        lang= language,
        since= tweet_since,
        until= tweet_until,
        geocode = geo,
        place= place,
        tweet_mode= tweet_mode,
        retweet = retweet#-filter:nativeretweets
    ).items(number_of_tweet)]#number of tweets

    with open(ds_tweets_save_path, "w") as f:
        json.dump(example_tweets, f)
    with open(ds_tweets_save_path, "r") as f:
        example_tweets = json.load(f)

    return None

Here is the line where I implement it on the Netherlands and then I get an empty file which is blizzard:
tweet_obtainer("data_netherlands", ["is"],"en","2018-06-01",
    "2018-06-14",geo = "52.1326, 5.2913, 131km"
)

Any English tweet should contain "is" so It should not return empty file!

A: I figured it out! It is because my geocode string has space in it. There should be no space but only comma between lat, long and radius.


text:
Q: Compactness of the resolvent I want to prove the following proposition:
owning to the $ H^2_{loc}(\mathbb{R}^n)$ regularity when solving $\Delta^{(0)}_Vu=f\in L^2$, the compactness of the resolvent of $\Delta^{(0)}_V$ is a consequence of $\forall$ $u\in C^\infty _0(\mathbb{R}^n)$
$\|R(x)u\|^2=<u,R(x)^2>\le c[<u,\Delta^{(0)}_V u> +\|u\|^2]$ with       $\lim_{x\mapsto \infty} R(x)=+\infty$
This is what I tried to do :
we suppose that $\Delta^{(0)}_V$ has not a compact resolent hence since it is a self adjoint operator thre existe an orthonormal sequence $u_k$ such that $<u_k,\Delta^{(0)}_V u_k>$ is bounded hence the RHS is bounded but since  $\lim_{x\mapsto \infty} R(x)=+\infty$ we have $\lim_{x\mapsto \infty}\|R(x)u_k\|^2=+\infty$ thus the LHS goes to $+\infty$ contradiction
I want to know if my answer is true. Thanks in advance.


text:
Q: How to put a banner ad between post 1 and post 2 on homepage only Wordpress Swift Theme is installed on my My site http://tech-ticks.info
From last few days, I am trying to find a solution to put an ad banner on homepage only between post1 and post 2. I have already tried on worpress support forum.
Can anyone here help me out as i don't have much knowledge about PHP.
Your help will be highly appreciated.

A: Register a widget, and call it on the front-page when the the_post action is called second time:
add_action( 'wp_loaded', 'wpse_80202_register_banner_widget' );
function wpse_80202_register_banner_widget()
{
    // used on the first page of main loop only
    register_sidebar(
        array (
            'name'          => 'Banner front-page ',
            'id'            => 'frontpage_banner',
            'before_widget' => '
',
            'after_widget'  => '
'
        )
    );
}

add_action( 'loop_start', 'wpse_80202_show_banner_widget' );

function wpse_80202_show_banner_widget()
{
    static $count = 0;
    if ( ! is_front_page() )
        return;

    if ( 'loop_start' === current_filter() )
    {
        add_action( 'the_post', __FUNCTION__ );
        return;
    }

    $count += 1;

    if ( 2 === $count )
    {
        dynamic_sidebar( 'frontpage_banner' );
        remove_action( 'the_post', __FUNCTION__ );
    }
}

I would use the Text widget for that:

Another variant of this code here: Add Adsense code in index.php


text:
Q: CloudWatch Alarm via PowerShell - issue with InstanceName I want to create CloudWatch alarms automatically on instance launch (via AutoScaling, CLI or whatever).
My instances are running Windows, so I created task in Task Scheduler which executes PowerShell script.
This script uses Write-CWMetricAlarm cmdlet to create CloudWatch Alarms - http://prntscr.com/e6xptj
It works good for custom Metrics like Windows/Default , but for AWS/EC2 InstanceName is required as well - http://prntscr.com/e6xq18
But there's no Dimension for InstanceName - http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ec2-metricscollected.html
.. as well as no suitable parameter for Write-CWMetricAlarm Cmdlet   - http://docs.aws.amazon.com/powershell/latest/reference/Index.html
So any ideas about how this issue can be solved?
Thanks in advance!

A: Instance names are actually just tags (with key "Name") and the console gives them special treatment to make them appear as a first-class item. They also do not need to be unique, so using 'name' wouldn't enable CloudWatch to distinguish between different instances, making things confusing from an alarm perspective.
I think therefore that you need to be using the instance id value. In your script I notice you're using Invoke-Restmethod to obtain it - you might be interested to know you can also get this value using a cmdlet:
Get-EC2InstanceMetadata -Category InstanceId


text:
Q: How to fix Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0? I am trying to print from my mutable list but keep getting out of bounds. I added the members to the menu at the bottom, then every time I try to print something from a member of a list, I get an error. These members are objects of the class being stored as a list. I am thinking it has to do with the way I wrote the list but I can't figure it out.
I tried adding the members to the list in different ways but it results in the same error.
class membership ()
      {
        var number: Int? = null
        var name: String? = null
        var address: String? = null
        var zip: String? = null
        var phone: String? = null
        var memberSince: String? = null
        var memberType: Char? = null

    }

fun main(args: Array<String>) {

var Members: MutableList<membership> = mutableListOf()

    var member1 = membership()
    member1.number = 1
    member1.name = "George Jetson"
    member1.address ="123 Main St."
    member1.zip = "99207"
    member1.memberSince = "12/01/1997"
    member1.memberType = 'L'

Members[0] = member1

    println(Members[0].name)
}

// I have more members.

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
 at java.util.ArrayList.rangeCheck (ArrayList.java:653)
 at java.util.ArrayList.set (ArrayList.java:444)
 at FileKt.main (File.kt:45)

A: I would say you can not assign item 0, if it has not been set before. The member1 needs to be added with
Members.add(member1)


text:
Q: How to control volume on Windows from Android device remotely? I'm wondering is there a way to control volume from Android 9 on Windows PC (Windows 10) remotely via Wi-Fi?
Actually all I need is to lauch nircmd.exe on remote machine somehow.
It's not about using full remote access like RDP or VNC, it's about how to lauch any Windows script from Android device via one tap on it.
Thanks.


text:
Q: how to submit form on click of checkbox in Codeigniter i have a form like this in Codeigniter :
<form id="myform" action="">

<?php echo $approv['title'];?>

           <input type="checkbox" value="1" name="appro">
          </form>

I want to submit this on click of a checkbox. i m new to Codeigniter.please help.

A: Try using javascript function on click :
 <form id="myform" action="">

<?php echo $approv['title'];?>

<input type="checkbox" id="appro" value="1" name="appro">
 </form>