text:
Q: 1st Person Game Three.js - Controls - Moving the camera I want to create a 1st person 3D game with Three.JS. The controls are W A S D. I have the keys assigned to move forward (W), move backward (S), turn left (A) and turn right (D).
In this code I explain the logic behind the controls. The deltas' porpuse is to inform what direction the camera is looking, so that when it moves forward or backward it moves in that direction. That is what I'm having problems with.
//variables
 var pi = Math.PI; //just because I use PI a lot
 //controls
 var moveForward = false;
 var turnLeft = false;
 var moveBackward = false;
 var turnRight = false;

 //direção
 var deltaZ = pi;
 var deltaX = 0;
 var increaseDeltaX = true;
 var increaseDeltaZ = false;

/*code adding the camera, the scene and eventListener for the keys. When the keys mentioned are clicked the corresponded var turns true*/

function animate() {

//clicking W
if (moveForward) {
    camera.position.z += deltaZ/pi;
    camera.position.x -= deltaX/pi;
    //I used delta/pi because if delta=pi camera.position.z will increase 1
}

//clicking S
if (moveBackward) {
    camera.position.z -= deltaZ/pi;
    camera.position.x += deltaX/pi;
}

//clicking D
if (turnRight) {
    camera.rotation.y += pi/300; //clicking 300 times will spin 180 degrees

    //deltaZ starts in pi and decreasing, it varies between pi and -pi
    if (increaseDeltaZ) {
        deltaZ += pi / 150; //150= 300/2; pi= 90 degrees = 180/2
    } else {
        deltaZ -= pi / 150
    }

    if (deltaZ >= pi) {
        increaseDeltaZ = false;
    } else if (deltaZ <= -pi) {
        increaseDeltaZ = true;
    }

    //deltaX starts in 0 and increasing, it varies between pi and -pi
    if (increaseDeltaX) {
        deltaX += pi / 150;
    } else {
        deltaX -= pi / 150;
    }

    if (deltaX >= pi) {
        increaseDeltaX = false;
    } else if (deltaX <= -pi) {
        increaseDeltaX = true;
    }

}

This code works well. When I turn right and then move forward, the camera moves in the right direction. The problem is when I turn the camera left. I tried to just reverse the calculations but the values just get messed up and the deltas go over pi and the directions become incorrect.
What do I put in the  if (left)?


text:
Q: What are the techniques one can used for rule based plane generation? I've asked the question here at gamedev SE, but the response wasn't too encouraging. So I try to reask again, from a slightly difference perspective.
I have a terrain, which is defined by mesh. And there are a lot of other polygonal faces scattered throughout the terrain, they can be located above, or below or cutting through the terrain. You can think of those faces as platforms.
A screenshot below should clarify what I mean. Despite looking smooth, all the mesh are actually consist of small elements ($\text{number}> 10k$) combined together, giving the false appearance of smoothness. The obvious disconnected area are platforms.

My question is, how can I generate the planes that connect between the platforms and other platforms/ terrain? Here are the rules to generate the series of sloped planes:

*

*They could go up or down, depending on which direction will make them hit the terrain/neighbouring platform first.

*The plane generation rule is that, the plane will start at the edge of a platform, and moving $45^o$ upward/downward with respect to z axis for a certain length, then it will move 0 degree with respect to z axis for another certain length, and repeat. So it will be a series of piecemeal planes until at some points of the planes, obstacles are hit.

These slope planes are needed so that I can compute the volume difference between the slopes and the terrains, it's not just for visualization purpose.
My question is, are the available techniques that I can use to attack this problem? I'm pretty sure this is a well-established problem for computer graphics and whatnot, so there must be existing solution out there.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Focus to a particular div on window onload I have recently made a horizontal and vertical scrolling site using jquery.scrollTo
On the website, i have an enter page. Once you enter, fixed navigation appears and depending upon the links , site moves here and there. This navigation remains invisible using ('#my div').hide();
I show it once the user enter the site.
But the prob is that if u reload the site(which ppl will do in case they get their internet disconneted), it remains at the same place where it was last time.. So, i am lying at an arbit position place on every reload without the navigation buttons..
So, i am searching for some alternatives so that i can make sure that the page always starts with enter page irrespective of where he was initially...
Please help....

A: If I understood you well, this would work:
$(document).ready(function(){
   window.scrollTo(0, 0);
});

This code will take to the top of the page everytime the window loads.
Hope this helps. Cheers


text:
Q: When creating models.py ,the row size too large issue is found ,how to solve this problem How to solve this issue:

raise errorclass(errno, errval) django.db.utils.InternalError: (1118,
  u'Row size too large. The maximum row size for the used table type,
  not counting BLOBs, is 65535. This includes storage overhead, check
  the manual. You have to change some columns to TEXT or BLOBs')

can please help to solve this problem, here is the model code:
from django.db import models

class Newsdeatils(models.Model):
    news_provider_id = models.CharField(max_length=5000)
    news_title =  models.CharField(max_length=5000)
    news_details = models.CharField(max_length=5000)
    news_image = models.CharField(max_length=5000)
    news_page_url = models.CharField(max_length=5000)
    next_page = models.CharField(max_length=5000)
    news_des = models.CharField(max_length=5000)

A: Just use TextField for such length requirements.
Usually, TextFields are not really limited to a specific length w.r.t. to implementation limits (regarding filesystems or the general database system used). TextFields behave very similar to CharFieldsin usage.
You can read about the differences here.
Your code would change to something like that:
from django.db import models

class Newsdeatils(models.Model):
    news_provider_id = models.TextField(max_length=5000)
    news_title =  models.TextField(max_length=5000)
    news_details = models.TextField(max_length=5000)
    news_image = models.TextField(max_length=5000)
    news_page_url = models.TextField(max_length=5000)
    next_page = models.TextField(max_length=5000)
    news_des = models.TextField(max_length=5000)

Please note that setting the max_length attribute on TextFieldis not required (it is when using CharField). this max_length attribute is also not enforced on the db-level but only used for form validation.
Other things to consider in your model:
Why is the news_provider_id a CharField? should that not be a ForeignKey?
Same goes for things like the news_image field. This should probably be a BinaryField.


text:
Q: Howto organize Vim buffers, windows and tabs when working with many files I used VIM whole my life but recently I am a bit tired of it because I am lost in buffers, windows, and tabs when working simultaneously with 20 files or so in a big project (with 500k LOC, and hundreds files).
Whenever i do :make, :grep, etc, new buffers are jumping out in the current window.
The same happens for the tags. At some point this starts to be very confusing because I really have to focus where things are in a VIM.
What are a proven and easy ways to control this behavior?

A: *

*Use :hide to get rid of all windows unless you really need them open.

*I'm not sure why tags are creating a new window for you, CTRL+] should re-use the current window.

*nnoremap + 4<C-W>+ and nnoremap - 4<C-W>- make it much easier to resize windows, along with the standard <C-W>_ and <C-W>|.

*Get a 22" monitor (minimum) and use :vsplit to show files side by side. I find this is even more important than having two smaller monitors.

*Use <C-W>L, <C-W>H etc to move windows around. Don't forget :tab sp to open the current file (or a new one) in a new tab.

*:map <LEFT> <C-W>h and :map <RIGHT> <C-W>l, etc make it much easier to move between windows. :map <C-LEFT> :tabprev<CR> and :map <C-RIGHT> :tabnext<CR> make it much easier to move between tabs.
And finally, if you need to have 20 files open regularly, this could be a sign that your code is poorly organized. If possible, features should be contained within a single file, then you just need to focus work on one feature at a time.

A: I tested out Eclim http://eclim.org/ a while ago for a friend. Basically, it lets you run Eclipse in a headless mode while using vim for editing and so on. With the extension, it allows Vim to draw on all the strengths of both worlds, adding for instance Eclipse's project tree to your favourite editor!
Installation was a bit daunting back then, but once I had it up and running, it was really smooth and quite a brilliant solution. Try it out, I'm pretty sure you won't be disappointed. And the installation is probably easier now. :)
Oh, I should also mention that there are several Eclim-setups. You can have headless Eclipse with vim as your primary interface (as I first mentioned), you can have a headed Eclipse and Vim, so that you can easily switch back and forth (in the same project no less), or you can have Vim integrated into Eclipse itself.

A: Run multiple vims.  I use "konsole" on my Linux machine.  It allows me to open many tabbed linux terminal sessions in one window.  I can double click the tabs to name them, e.g. "models", "views", "controllers", etc.  In each of these tabbed linux terminals, I'll have a vim process running that has usually 2 or 3 files open at a time.
Another option is to find and IDE that has Vim mode, so you can still use most of your key commands.

A: As a longtime vim user, it pains me to say it, but--it might be time for you to graduate to a full-fledged IDE. You can still use vim as your editor in most cases, but the IDE will handle file management and navigation for you, and probably will simplify your make and grep workflows (e.g., structural search beats the pants off of grep). What language are you working on?

A: Vim-CtrlSpace lets you organize Tabs, Buffers, Sessions (workspaces) + fuzzy search.
It is quite suitable to work on large projects. That's how I actually come up with it.
Before, I used 'jlanzarotta/bufexplorer.git' and 'xolox/vim-session'
You can check the demo on YouTube.


text:
Q: React context is undefined This is my first time using Reactjs with Laravel. I'm trying to send data among components but the context returns as undefined. I want to send data from Product_Detail.js to Cart.js
globalContext.js
import React from "react";

export const MContext = React.createContext(); //exporting context object

export class MyProvider extends React.Component {
  constructor() {
    this.state = {
      message: ""
    };
  }
  render() {
    return (
      <MContext.Provider value={{ message: "kkk" }}>
        <Cart />
        <Product_Detail />
        {this.props.children} //this indicates that all the child tags with
        MyProvider as Parent can access the global store.
      </MContext.Provider>
    );
  }
}

export const MyConsumer = MContext.Consumer;

Cart.js
import { MyConsumer } from "./globalContext";

<MyConsumer>{context => <p>{console.log("CCC", context)}</p>}</MyConsumer>;

export default Cart;

if (document.getElementById("shoppingCart")) {
  ReactDOM.render(<Cart />, document.getElementById("shoppingCart"));
}

Product_Detail.js
import { MyConsumer } from "./globalContext";

<MyConsumer>
  {context => (
    <button
      className="flex-c-m sizefull bg1 bo-rad-23 hov1 s-text1 trans-0-4"
      onClick={() => {
        console.log("kkkk", context);
      }}
    >
      Add to Cart
    </button>
  )}
</MyConsumer>;
export default Product_Detail;

if (document.getElementById("product_detail")) {
  ReactDOM.render(
    <Product_Detail />,
    document.getElementById("product_detail")
  );
}

App.js
import Cart from "./components/Website/Cart";
import Product_Detail from "./components/Website/Product_Detail";
import { MyProvider } from "./components/Website/globalContext";

A: It's not entirely clear what you're rendering inside your app component, but I think what is going wrong is that your components are not correctly wrapped by your Provider.
Your App component should look something like this:
import React from "react";
import Cart from "./components/Website/Cart";
import Product_Detail from "./components/Website/Product_Detail";
import { MyProvider } from "./components/Website/globalContext";

const App = () => {
  return (
    <MyProvider>
      <Cart />
      <Product_Detail />
    </MyProvider>
  );
};

export default App;

And your globalContext like this:
import React from "react";

export const MContext = React.createContext(); //exporting context object

export class MyProvider extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      message: ""
    };
  }
  render() {
    return (
      <MContext.Provider value={{ message: "kkk" }}>
        {this.props.children}
      </MContext.Provider>
    );
  }
}

export const MyConsumer = MContext.Consumer;

This way the value you passed to your provider get's logged out when Cart is rendered and when you click on the button rendered by Product_Detail.
Also I'm assuming that you're importing React inside the Cart and Product_Detail components and that you're correctly defining these components.


text:
Q: Shapeless HList Containing a Sequence I have a String representation as below that I would like to represent as a HList. Here is it:
123456,/02/2017,0,0,0,0,0,0,170.153

So the type that I'm interested in is:
Int :: DateTime :: Seq[Double]

I was able to manage one-to-one mapping done, but how could I convert my representation above to the Shapeless type that I would want to? Any suggestions?

A: I'm not sure where's your trouble. Why can't you just do something like:
def hlistFromString(s: String): Int :: Date :: Seq[Double] :: HNil = {
  val ss = s.split(',')
  ss(0).toInt :: new Date(ss(1)) :: ss.toSeq.drop(2).map(_.toDouble) :: HNil
}

val s = "123456,01/02/2017,0,0,0,0,0,0,170.153"
println(hlistFromString(s))

Output is

123456 :: Mon Jan 02 00:00:00 2017 :: ArrayBuffer(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 170.153) :: HNil

The only guess I have is that you missed that any HList type should end with HNil


text:
Q: Concave envelope: equivalent definitions Let $f: X\to \mathbb{R}$ be bounded. Consider the following definitions:
Definition 1: $f^{*}(x)=\inf\{h(x): h\in \mathbb{R}^{X} \;\;\text{affine and}\;\; h\ge f\}$.
Definition 2: $f^{**}(x)=\inf\{h(x): h\in \mathbb{R}^{X} \;\;\text{affine, continuous and}\;\; h\ge f\}$.
Definition 3: $f^{***}(x)=\min\{h(x): h\in \mathbb{R}^{X} \;\;\text{concave and}\;\; h\ge f\}$.
All were extracted from different textbooks or articles. They refer to the concave envelope of $f$.
Are they all equivalent?
I can see how they are related, but, for instance, for $g$ strictly concave with $g(x)\ge f^{***}(x)$, $f^{***}(x)=g(x)$ but what about $f^{*}(x)$? Why is continuity required in definition 2?

A: Posed as it is posed, for general $X$ (hence possibly infinite dimensional) it is clear that there may exist linear unbounded functions, making the two definitions nonequivalent.
Note also that for general $X$ we may not even be sure the $\min$ exists in definition $3$.
Knowing what is $X$ (a generic set, a set endowed with a preference relation and maybe an order topology, a finite dimensional space,...) is fundamental for the question, since in total generality it is false.


text:
Q: XML has multiple value nodes Updated: I can only step down to the first value node in my XML.
The code below gets to the first value node and shows data, but how would I select another node? I only need 3 values at the moment from each item node.The Tax Year, Bill number, and appl_amt, along with the image path are the only values I am working on retrieving. The Xml added is only a portion. The section added repeats several times until the BatchCompiler/Batch/transactions/transaction tags close the groupings.
   <?xml version="1.0"?>
 <BatchCompiler>
<batch>
   <batchid>95531</batchid>
   <transactions>
        <transaction>
            <items>
              <item>
                <values>
                  <value>
                     <name>doc_type</name>
                     <data>1</data>
                  </value>
                  <value>
                    <name>doc_id</name>
                    <data>10</data>
                 </value>
                   <value>
                    <name>Bill Base Number</name>
                    <data>0007956700</data>
                 </value>
                 <value>
                    <name>Tax Year</name>
                    <data>2015</data>
                </value>
                 <value>
                    <name>Year For</name>
                    <data>2015</data>
               </value>
                <value>
                   <name>Listing Type</name>
                   <data>0000</data>
              </value>
               <value>
                  <name>Postmark Date</name>
                   <data>08212015</data>
             </value>
            <value>
                   <name>appl_amt</name>
                   <data>18.12</data>
            </value>
            <value>
                    <name>tran_num</name>
                    <data>1</data>
           </value>
           <value>
                   <name>tran_seq</name>
                   <data>1</data>
           </value>
          </values>
          <image>..\images\95531_1_S_1.tif</image>
     </item>

 namespace GETZIP2
 {
 class Program
 {
    static void Main(string[] args)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("\\example\\index.xml);
        MessageBox.Show(doc.SelectSingleNode("BatchCompiler/batch/transactions/transaction/items/item/values/value").InnerText);

    }

    }

 }

A: LINQ to XML is a much better API than the old XmlDocument DOM, and LINQ to XML's query methods a lot nicer than messing around with XPath.
Something like this would probably work, though it would help if you showed some XML and were a little more specific about which values you actually want.
var doc = XDocument.Load(@"\example\index.xml");

foreach (var value in doc.Descendants("value"))
{
    var name = (string)value.Element("name");
    var data = (string)value.Element("data");

    // do something with these
}

If you wanted to query for a specific key/value pair, you could do something like:
var taxYear = doc.Descendants("value")
    .Where(e => (string)e.Element("name") == "Tax Year")
    .Select(e => (string)e.Element("data")
    .Single();

You might even consider creating a dictionary of all key/value pairs:
var keyValues = doc.Descendants("value")
    .ToDictionary(e => (string)e.Element("name"), e => (string)e.Element("data"));

var taxYear = keyValues["TaxYear"];
var billNumber = keyValues["Bill Base Number"];

A: Besides Linq to XML, you can also use XmlReader class. It offers functions like ReadToNextSibling which help you move through siblings.
Other functions such as ReadToDescendant and MoveToNextAttribute might come in handy.
XmlReader reader = XmlReader.Create(@"\example\index.xml");

// Move to the desired element.
reader.MoveToContent();
reader.ReadToDescendant("value");


text:
Q: PHP protected classes and properties, protected from whom? I'm just getting started with OOP PHP with PHP Object-Oriented Solutions by David Powers, and am a little curious about the notion of protection in OOP.
The author clearly explains how protection works, but the bit about not wanting others to be able to change properties falls a bit flat. I'm having a hard time imagining a situation where it is ever possible to prevent others from altering your classes, since they could just open up your class.php and manually tweak whatever they pleased seeing as how PHP is always in plain text.
Caution: all of the above written by a beginner with a beginner's understanding of programming.

A: Protected is not really protecting from anyone to change the source code, but is just a class method visibility in PHP OOP

Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

A: They mean they are protected in different ways...

*

*Private variables are not visible to anywhere except from within the class.

*Protected variables are not visible to the instantiated object, but are visible to classes which inherit from that class, as well as the class itself.

Nothing stops another programmer from opening a class file and changing the access modifiers.
The hiding of data is a good thing because the less you expose, the more you can control and less bugs you can potentially introduce.

A: From yourself!
You use various levels of protection to indicate how you want a class to be used. If a class member is protected or private, it can only be accessed by the class itself. There's no chance you can screw up the value of that member accidentally from "external" code (code outside the class).
Say you have a class member that is only supposed to contain numbers. You make it protected and add a setter which checks that its value can only be numeric:
class Foo {

    protected $num = 0;

    public function setNum($num) {
        if (!is_int($num)) {
            throw new Exception('Not a number!!!');
        }
        $this->num = $num;
    }
}

Now you can be sure that Foo::$num will always contain a number when you want to work with it. You can skip a lot of extra error checking code whenever you want to use it. Any time you try to assign anything but a number to it, you'll get a very loud error message, which makes it very easy to find bugs.
It's a restriction you put on yourself to ease your own work. Because programmers make mistakes. Especially dynamically typed languages like PHP let you silently make a lot of mistakes without you noticing, which turn into very hard to debug, very serious errors later on.
By its very nature, software is very soft and easily degrades into an unmaintainable Rube Goldberg logic machine. OOP, encapsulation, visibility modifiers, type hinting etc are tools PHP gives you to make your code "harder", to express your intent of what you want certain pieces of your code to be and enable PHP to enforce this intent for you.


text:
Q: JPanel clock and button merge I'm having a problem with in merging time and button together...
I can't get the button show in the JPanel.
This is my code:
import java.awt.Color;
import java.awt.Font;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public final class Date_Time extends JFrame{
    private static final long serialVersionUID = 1L;
    private JPanel show_date_time = new JPanel();
    private JLabel time = new JLabel("Time:");
    private JLabel show_time = new JLabel("Show Time");

    DateFormat dateFormat2 = new SimpleDateFormat("h:mm:ss a");
    java.util.Date date2;
    private JLabel label;
    private JPanel panel;

     public Date_Time(){
        this.setSize(300, 300);
        this.setResizable(false);
        getContentPane().add(Show_Time_date());
     }
     private JButton button1 = new JButton();
     private JFrame frame1 = new JFrame();
    public JPanel Show_Time_date(){
        frame1.add(show_date_time);
        show_date_time.setBackground(Color.ORANGE);
        frame1.add(button1);
        getShow_date_time().setLayout(null);
        Font f;
        f = new Font("SansSerif", Font.PLAIN, 15);
        getTime().setBounds(0,250,400,30);
        getTime().setFont(f);
        getShow_date_time().add(getTime());
        setShow_time(new JLabel(""));
        updateDateTime();
        getShow_time().setBounds(37,250,400,30);
        getShow_time().setFont(f);
        getShow_date_time().add(getShow_time());
        return getShow_date_time();

    }

    public static void main(String[] args) {
        Date_Time Main_win=new Date_Time();
        Main_win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Main_win.setVisible(true);
    }

    public void updateDateTime()
    {
    Thread th = new Thread(new Runnable()
        {
            @Override
        public void run()
            {
            while(true)
                {
                date2 = new java.util.Date();
                String dateTime = dateFormat2.format(date2);
                    getShow_time().setText(dateTime);
                    getShow_time().updateUI();

                }
            }
        });
    th.start();
    }

    /**
     * @return the show_time
     */
    public JLabel getShow_time() {

        return show_time;
    }

    /**
     * @param show_time the show_time to set
     */
    public void setShow_time(JLabel show_time) {
        this.show_time = show_time;
    }

    /**
     * @return the time
     */
    public JLabel getTime() {
        return time;
    }

    /**
     * @param time the time to set
     */
    public void setTime(JLabel time) {
        this.time = time;
    }

    /**
     * @return the show_date_time
     */
    public JPanel getShow_date_time() {
        return show_date_time;
    }

    /**
     * @param show_date_time the show_date_time to set
     */
    public void setShow_date_time(JPanel show_date_time) {
        this.show_date_time = show_date_time;
    }

    /**
     * @return the label1
     */

    /**
     * @param label1 the label1 to set
     */

    /**
     * @return the label
     */
    public JLabel getLabel() {

        return label;
    }

    /**
     * @param label the label to set
     */
    public void setLabel(JLabel label) {
        this.label = label;
    }

    /**
     * @return the panel
     */
    public JPanel getPanel() {
        return panel;
    }

    /**
     * @param panel the panel to set
     */
    public void setPanel(JPanel panel) {
        this.panel = panel;
    }
}

A: Here have a look at this modified code :
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public final class Date_Time extends JFrame{

    private static final long serialVersionUID = 1L;
    private JPanel show_date_time = new JPanel();
    private JLabel time = new JLabel("Time:");
    private JLabel show_time = new JLabel("Show Time");

    private DateFormat dateFormat2 =
                new SimpleDateFormat("h:mm:ss a");
    private JButton button1 = new JButton("USELESS");
    private java.util.Date date2;
    private JLabel label;
    private JPanel panel;

    public Date_Time(){

        //this.setResizable(false);
        getContentPane().add(show_Time_date());
    }

    public JPanel show_Time_date(){

        getShow_date_time().setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
        /*
         * Always set this Opaque property of the
         * said JComponent to true, before
         * you change the Background Colour
         * of the said component in question.
         * In some Look And Feels it's set to
         * false by default, so you won't
         * see any colour, in such situations.
         */
        getShow_date_time().setOpaque(true);
        getShow_date_time().setBackground(Color.ORANGE);

        Font f;
        f = new Font("SansSerif", Font.PLAIN, 15);

        getTime().setFont(f);
        getShow_date_time().add(getTime());
        setShow_time(new JLabel(""));

        updateDateTime();

        getShow_time().setFont(f);
        getShow_date_time().add(getShow_time());
        getShow_date_time().add(button1);

        return getShow_date_time();
    }

    public static void main(String[] args) {

        /*
         * Calls like pack()/setSize()/setVisible()
         * must be done from inside the Event Dispatch Thread
         * or the EDT in short. And not from your
         * Main Thread. Please read Concurrency in Swing
         * in detail from this link :
         * http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html
         */
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                Date_Time main_win=new Date_Time();
                main_win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                main_win.setSize(250, 75);
                main_win.setVisible(true);
            }
        });
    }

    public void updateDateTime()
    {
        Thread th = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                while(true)
                {
                    date2 = new java.util.Date();
                    final String dateTime = dateFormat2.format(date2);
                    /*
                     * Any updates to the GUI, must also be done
                     * on the EDT - Event Dispatch Thread.
                     */
                    SwingUtilities.invokeLater(new Runnable()
                    {
                        public void run()
                        {
                            getShow_time().setText(dateTime);
                        }
                    });
                }
            }
        });
        th.start();
    }

    /**
     * @return the show_time
     */
    public JLabel getShow_time() {

        return show_time;
    }

    /**
     * @param show_time the show_time to set
     */
    public void setShow_time(JLabel show_time) {
        this.show_time = show_time;
    }

    /**
     * @return the time
     */
    public JLabel getTime() {
        return time;
    }

    /**
     * @param time the time to set
     */
    public void setTime(JLabel time) {
        this.time = time;
    }

    /**
     * @return the show_date_time
     */
    public JPanel getShow_date_time() {
        return show_date_time;
    }

    /**
     * @param show_date_time the show_date_time to set
     */
    public void setShow_date_time(JPanel show_date_time) {
        this.show_date_time = show_date_time;
    }

    /**
     * @return the label1
     */

    /**
     * @param label1 the label1 to set
     */

    /**
     * @return the label
     */
    public JLabel getLabel() {

        return label;
    }

    /**
     * @param label the label to set
     */
    public void setLabel(JLabel label) {
        this.label = label;
    }

    /**
     * @return the panel
     */
    public JPanel getPanel() {
        return panel;
    }

    /**
     * @param panel the panel to set
     */
    public void setPanel(JPanel panel) {
        this.panel = panel;
    }
}

A: As @nIcE cOw notes, your thread is incorrectly synchronized, and invokeLater() is a correct solution. Unfortunately, your thread also runs continuously, hampering performance. You should consider these alternatives:

*

*Poor: Yield the processor in the loop:
Thread.yield(); // prevent thread from starving

*Better: Add a suitable delay after invokeLater() and catch InterruptedException:
try {
    Thread.sleep(500);
} catch (InterruptedException ex) {
    Logger.getLogger(Date_Time.class.getName()).log(Level.SEVERE, null, ex);
}

*Best: Use javax.swing.Timer, as shown here.


text:
Q: How to use onCall with aws-sdk-mock? I would like let the mock method enable different responses for consecutive calls to the same method.
I found that Sinon has onCall, it allowed I can stub method like below,
        let stubCall = sandbox.stub(Math, 'random');
        stubCall.onCall(0).returns(Promise.resolve(0));
        stubCall.onCall(1).returns(Promise.resolve(-1));

but I don't know how to let this work on AWS mock framework like this.
        AWS.mock('CloudFormation', 'describeStacks', Promise.resolve(stackResponse));

I tried
AWS.mock('CloudFormation', 'describeStacks', Promise.resolve(stackResponse)).onCall(0).returns(Promise.resolve(res));

and
let mockCall = AWS.mock('CloudFormation', 'describeStacks', Promise.resolve(res));
mockCall.onCall(0).returns(Promise.resolve(res));

both of them didn't work.
I found people discuss this issue , mentioned since this aws-mock use sinon, it should able to use onCall. Is anyone use it successfully?
Since I use promise, I don't know what else I can do to return the different response for the same method has been called several times.

A: First, set the AWS SDK instance to be mocked
const sinon = require('sinon');
const AWS_Mock = require('aws-sdk-mock');
const AWS_SDK = require('aws-sdk');

AWSMock.setSDKInstance(AWS_SDK);

Configure stub that will be called
const stub = sinon.stub();
stub.onCall(0).returns(1);
stub.onCall(1).returns(2);

Mock Service method
Make sure that you're mocking the exact signature of the method.
AWSMock.mock('CloudFormation', 'describeStacks', function(params, cb) {
  cb(null, stub());
});

Our Mocked method in action
const cf = new AWS_SDK.CloudFormation();

cf.describeStacks({}, (err, data) => {
  if(err) {
    console.err(err);
  }
  console.log(data); // 1
});

cf.describeStacks({}, (err, data) => {
  if (err) {
    console.err(err);
  }
  console.log(data); // 2
});


text:
Q: How to ensure redundancy of a polling process I need to poll a database table (DB2) using Python. The table gets updated quite frequently so I am not particularly worried about empty pings. I wanted to get some tips around how to ensure redundancy for such a polling process. If I have only one process (let's call it A) then there is no backup in case A fails. If I create two processes A&B then how do I ensure that only one process is polling the database at a time and the other process kicks in only if the first one fails.
I understand this question is too broad, however, I would appreciate any pointers about the latest design patterns or frameworks that will help me achieve redundancy. I can use Java instead of Python if it will work better.

A: You will need to keep the state/result of the ping and make it available to both processes.  This could be kept in a cache, a file, etc.  Have one process ping and write a last-updated timestamp to the file/cache/etc.  The other process only runs if the file/cache/etc isn't updated.
This sort of process is encapsulated in distributed lock handlers and cluster managers like Apache Zookeeper.


text:
Q: How to read one .CAP file with C? My code in C/C++, shoud read some data from a .CAP file, (by the TCPDUMP). One good example could be by WireShark, but I need realy less data.
This .CAP  seems to be writen in HEXA and, when I try to read it, the variables are coming "codified" ?!?!
Well, I just a newbee and I have to learn this, I think I am not able to make the correct question... soo, I count on friends good wills  to figure it out..
Another Issue is I am totaly lost in an ocean of links in the net... and I just get more confuses...
Explain:
in this link you can get the .CAP, That can be easyli open by WireShark.
Following, my code below... pop ups "strange caracters".
like:
==> revision: �ò�*
OR
==> header_pad: ò�
where "revision", for exemple shound be 12 HEXA  or converted 18 decimal

*

*Wel,  I tryed to coment the code and, this soppouse to run in linux terminal.

.
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
// #include <curses.h>

// テスト用フラグ => Test for the flag
int LOOP_ONCE = 1;

// WiFi取得情報構造体 => get information structure

// Radiotap Header
// 18bytes固定長(と思われる)=> fixed length (seems to be)
typedef struct WF_HEADER
{
    char header_revision[1];
  char header_pad[1];
  unsigned short int header_length;
  char present_flags[4];
  char flags[1];
  char data_rate[1];
  char channel_frequency[2];
  char channel_flags[2];
  char ssi_signal[1];
  char antenna[1];
  char rx_flags[2];
} wf_header_t;

// IEEE802.11 Probe Request (前半部分)=>  (first half)
// 24bytes固定長  =>  fixed length
typedef struct WF_PROBE1
{
  char frame_control_field[4];
  char receiver_address[6];
  char transmitter_address[6];
  char bbs_id[6];
  char numbers[2];
} wf_probe1_t;

// IEEE802.11 Probe Request(後半部分)=>  (the latter part)
// 4bytes固定長 => fixed length
typedef struct WF_PROBE2
{
  char frame_check_sequence[4];
} wf_probe2_t;

// IEEE802.11 wireless LAN management frame(繰り返しヘッダー) => (repeat header)
// 2bytes
typedef struct WF_MANAGE_HEADER
{
  char tag_number[1];
  char tag_length[1];
} wf_manage_header_t;

int main(int argc, char *argv[]){
  char read_fname[30]; //読み込みファイル名                => read file name
  int read_fb;         //読み込みファイルバンドル           => read file bundle
  wf_header_t *wfh;    //WiFiデータ読み込み構造体のポインタ  => pointer of WiFi data read structure
  int read_size;       //読み込みファイルサイズ             => read file size
  int wfh_size;        // Wifiデータ構造体のサイズ          => Wifi data structure; int wfh_size

  /* WiFiデータ読み込み構造体の領域確保      =>   Area of WiFi data read structure ensure */
  wfh_size = sizeof(wf_header_t);
  wfh = calloc(1, wfh_size);

  /* ループ実行 */
  /* Loop execution */
  while (1) {
    /* ファイルの存在を監視する         =>  To monitor the presence of the file */
    /* 読み込みファイル名取得      =>  Read file name acquisition */
    if (1) {

        system("clear");

        // テスト用プログラム            =>  Test program
      fprintf(stdout, "読み込みファイル名を入力してください。\n"); // Please enter the reading file name
      scanf("%s", read_fname);
      fprintf(stdout, "ファイル名:%s\n", read_fname);         //file name:
    } else {
      // 次のファイル名を取得するような仕組み   =>  Like to get the following file name mechanism

    }
    /* ファイルオープン処理     =>  Seek to the data top position */
    read_fb = open(read_fname, O_RDONLY);
    if (read_fb == -1) {
      fprintf(stderr, "ファイルオープンに失敗しました。\n"); //Failed to open file
      fprintf(stderr, "ファイル名:%s\n", read_fname);    //file name
      return -1;
    }

    /* データ先頭位置までシークする                           =>  Seek to the data top position * /
    /* 前ファイルの続きである場合は、そのまま残サイズを読み込む    => Case is a continuation of the previous file, as it is read in the remaining size */

    read_size = read(read_fb, wfh, wfh_size);
    if (read_size == -1) {
      /* ファイル読み込み失敗       =>     File read failure */
      free(wfh);
      fprintf(stderr, "ファイル読み込みに失敗しました。\n");  //failed to file read
      fprintf(stderr, "ファイル名:%s\n", read_fname);    //file name
      return -1;
    } else if (read_size == wfh_size) {
      fprintf(stdout, "====================================\n");
      fprintf(stdout, "revision: %s \n", wfh->header_revision);
      fprintf(stdout, "header_pad: %s \n", wfh->header_pad);
      fprintf(stdout, "present_flags: %s \n", wfh->present_flags);
      fprintf(stdout, "flags: %s \n", wfh->flags);
      fprintf(stdout, "data_rate: %s \n", wfh->data_rate);
      fprintf(stdout, "channel_frequency: %s \n", wfh->channel_frequency);
      fprintf(stdout, "channel_flags: %s \n", wfh->channel_flags);
      fprintf(stdout, "ssi_signal: %s \n", wfh->ssi_signal);
      fprintf(stdout, "antenna: %s \n", wfh->antenna);
      fprintf(stdout, "rx_flags: %s \n", wfh->rx_flags);
      fprintf(stdout, "====================================\n");

    } else {
      /* 残りサイズを読み込み、次のファイルへ進む    => Read the remaining size, advance to the next file */

    }

    /* 終了処理   End processing */
    if (close(read_fb) != -1) {
      // ファイルクローズに成功したので、バックアップフォルダへ移動させる
      // Since successful file close, move to the backup folder

    } else {
      free(wfh);
      fprintf(stderr, "ファイルクローズに失敗しました。\n"); // file close failed
      fprintf(stderr, "ファイル名:%s\n", read_fname);    // file name
      return -1;
    }
    /* ループ終了判定    =>    Loop termination determination */
    if (LOOP_ONCE == 1) {
      free(wfh);
      fprintf(stdout, "終了しました。\n"); // was completed
      return 0;
    }
  }
}

Thanks for all tips an help ! !

A: You do know that in C a string is a sequence of characters terminated by the special character '\0'?
If you print a single character as a string, the printf function will loop printing characters until it finds the terminator character, and that will be beyond the limits of your one-character arrays. That leads to undefined behavior.
The simple solution is to not use arrays for structure members that are not really arrays (I mean all those one-element arrays). And then to use the proper printf format conversion specifier to print the characters. The correct specifier is either "%c" if you want to print it as a character, or "%hhd" if you want to print it as a small integer number.
For more information about the printf format specifiers, please read e.g. this printf (and family) reference.

A: To read .cap files, you use one of available libraries which will parse the file into individual packets. Do not call read() on the file directly.


text:
Q: Merge different columns Values - Pandas I have Nine columns 'instlevel1','instlevel2','instlevel3', 'instlevel4', 'instlevel5','instlevel6','instlevel7','instlevel8','instlevel9'
the values on this column are populated as follow : if instlevel1 value is 1, all others values for are 0, if instlevel2 value is 1, all others values for all others columns (including instlevel1) is 0.
I want to "pivot" this on one column. I got the desired results. but I wonder if there is a most efficient way to do this. because this case is very repetitive. here is the code for what I had done.
nivelEducacion = test[['instlevel1','instlevel2','instlevel3', 'instlevel4', 'instlevel5','instlevel6','instlevel7','instlevel8','instlevel9']].idxmax(axis=1)

test['nivelEducacion'] = nivelEducacion
test['nivelEducacion'] = test['nivelEducacion'].replace(['instlevel1'], '1')
test['nivelEducacion'] = test['nivelEducacion'].replace(['instlevel2'], '2')
test['nivelEducacion'] = test['nivelEducacion'].replace(['instlevel3'], '3')
test['nivelEducacion'] = test['nivelEducacion'].replace(['instlevel4'], '4')
test['nivelEducacion'] = test['nivelEducacion'].replace(['instlevel5'], '5')
test['nivelEducacion'] = test['nivelEducacion'].replace(['instlevel6'], '6')
test['nivelEducacion'] = test['nivelEducacion'].replace(['instlevel7'], '7')
test['nivelEducacion'] = test['nivelEducacion'].replace(['instlevel8'], '8')
test['nivelEducacion'] = test['nivelEducacion'].replace(['instlevel9'], '9')
test['nivelEducacion'] = test.nivelEducacion.astype('category')
test = test.drop(['instlevel1', 'instlevel2','instlevel3','instlevel4','instlevel5','instlevel6','instlevel7','instlevel8','instlevel9'], axis=1)

A: You can use melt's function from pandas. It's not maybe the best solution but it do the job:
s = pd.Series(list('aaabbbccddefgh')).astype('category') # generate fake dataset
df = pd.get_dummies(s) # fake df like you have (One Hot Encoded)

df2 = pd.melt(df, value_vars=["a", "b", "c", "d", "e", "f", "g", "h"])
df2 = df2[df2.value == 1]  # to keep only existing categories
df2.drop("value", axis=1, inplace=True)

Another solution I found is this one
x = df.stack()  # in that case you have to restrict only to your columns
df2 = pd.Series(pd.Categorical(x[x!=0].index.get_level_values(1))).to_frame()

I hope it helps,
Nicolas


text:
Q: simple attempt to sort inline returns None, don't know why To make a sorted list of values that appear in set a, This works:
a = [1,1,7,3,2,9,2]
b = list(set(a))
b.sort()
print b

but putting the two lines together, it returns None:
a = [1,1,7,3,2,9,2]
b = list(set(a)).sort()
print b

Even though these are true:
 type(list(set(a))) is list
 len(list(set(a)))  > 0

My question is, why doesn't the second method just return a sorted list - why do I have to put them on separate lines (as in the first method)?

A: sort() doesn't return a value, it just modifies the original object you pass in.

A: sort() sorts the list but doesn't return any result. You just end up with a nice sorted list. So you should do this:
b = list(set(a))
b.sort()
print(b)

A: sort is an in place method, meaning it does not return a value. It simply performs a method of the given object, almost like a void method from other languages. If you'd like a single line, try:
b = sorted(list(set(a)))


text:
Q: How to create interface to two class and mark methods, which I can use? class Rifle {
    void shoot() {
        System.out.println("rifle shoot");
    }

    void reload() {
        System.out.println("rifle reload");
    }

    void onlyRifle() {
        System.out.println("rifle!");
    }
}

class Shotgun {

    void shoot() {
        System.out.println("shotgun shoot");
    }

    void reload() {
        System.out.println("shotgun reload");
    }

    void onlyShotgun() {
        System.out.println("shotgun!");
    }
}

I need class Weapon, which will be use method shoot() from Rifle and method reload() from Shotgun
How can I do that using interface?
Imagine, that I CAN'T MODIFY class Rifle and class Shotgun
My bad realisation is
class Weapon {
    Rifle myRifle;
    Shotgun myShotgun;

    Weapon() {
        myRifle = new Rifle();
        myShotgun = new Shotgun();
    }

    void shoot() {
        myRifle.shoot();
    }

    void reload() {
        myShotgun.reload();
    }

    void onlyShotgun() {
        myShotgun.onlyShotgun();
    }

    void onlyRifle() {
        myRifle.onlyRifle();
    }
}

...main(){
    Weapon myWeapon = new Weapon();
    myWeapon.shoot();
    myWeapon.reload();
    myWeapon.onlyRifle();
    myWeapon.onlyShotgun();
}

That work that I want, but how can I do that more simply using interfaces?

A: Weapon should be an interface:
interface Weapon
{
     void shoot();
     void reload();
}

Then in your concrete instances, you implement that interface:
class Rifle implements Weapon
{
    /*ToDo - implement shoot and reload*/

    void onlyRifle() {
        /*ToDo - specific code here*/
    }
}

Then, say if you have r which is an instance of Rifle, you can add r to a collection of Weapon. It's unlikely you'll ever need onlyRifle: Rifle-specific stuff will only need to be passed on construction.

A: Try same like you used composition and using interface like:
interface Weapon {
 void shoot();
 void reload();
}

class ModifiedRifle implements Weapon {
     Rifle myRifle;
     Shotgun myShotgun;
     public ModifiedRifle (Rifle rifle, Shotgun shotgun) {
          this.myRifle = rifle();
          this.myShotgun = shotgun;
     }

     public void shoot() {
         myRifle.shoot();
     }

     public void reload() {
         myShotgun.reload();
     }
}

A: One way is to have the Interface Weapon defined and have 2 new classes, lets call them MyRifle which extends Rifle and implements Weapon and MySHotgun which extends Shotgun and implements Weapon
Asking you to extend the existing class since you mention that you cannot modify the existing ones
so
interface Weapon
{
     void shoot();
     void reload();
}

And
class MyRifle extends Rifle implements Weapon{
// actual implementations of your methods
}

A: You have a super class Weapon, which takes a WeaponType. Your WeaponType is an interface which has the shoot and reload methods.
public class Weapon {

WeaponType weaponType;

    public Weapon(WeaponType weaponType) {

        this.weaponType = weaponType;
    }

    public void shoot() {

        this.weaponType.shoot();
    }
    public void reload() {

        this.weaponType.reload();
    }
}

Your interface:
public interface WeaponType {

    public void shoot();
    public void reload();
}

Your shotgun class:
    public class Shotgun implements WeaponType {

    @Override
    public void shoot() {

        System.out.println("Shotgun shoot!");
    }

    @Override
    public void reload() {

        System.out.println("Shotgun reload!");
    }
}

Example usage:
Weapon myShotgun = new Weapon(new Shotgun());
myShotgun.shoot();
myShotgun.reload();


text:
Q: Http failure response Spring Boot Angular i  ran into the problem while making the crud application. i can add the records and view the records and delete the records while i update the records records not updated i got the problem on  ** Failed to load resource: net::ERR_FAILED** ** 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.**
what i tried so i attached below.on the update part of the application
CustomerController
`@RestController
@CrossOrigin("http://localhost:4200/")

@RequestMapping("api/v1/customer")
public class CustomerController
{
    @Autowired
    private CustomerService customerService;

@PostMapping(path = "/update")
public String updateCustomer(@RequestBody CustomerUpdateDTO customerUpdateDTO)
{
    String id = customerService.updateCustomers(customerUpdateDTO);
    return id;
}

}}`

CustomerService
String updateCustomers(CustomerUpdateDTO customerUpdateDTO);
`
CustomerServiceIMPL
`@Override
public String updateCustomers(CustomerUpdateDTO customerUpdateDTO)
{
    if (customerRepo.existsById(customerUpdateDTO.getCustomerid())) {
        Customer customer = customerRepo.getById(customerUpdateDTO.getCustomerid());

        customer.setCustomername(customerUpdateDTO.getCustomername());
        customer.setCustomeraddress(customerUpdateDTO.getCustomeraddress());
        customer.setMobile(customerUpdateDTO.getMobile());
        customerRepo.save(customer);
    }
        else
        {
            System.out.println("Customer ID do not Exist");
        }

            return null;
    }

CustomerRepo
`@EnableJpaRepositories
@Repository
public interface CustomerRepo extends JpaRepository<Customer,Integer> {
}

Customer
``@Entity
@Table(name = "customer")
public class Customer {
    @Id
    @Column(name = "customer_id", length = 50)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int customerid;

    @Column(name = "customer_name", length = 50)
    private String customername;

    @Column(name = "customer_address", length = 60)
    private String customeraddress;

    @Column(name = "mobile", length = 12)
    private int mobile;

    public Customer(int customerid, String customername, String customeraddress, int mobile) {
        this.customerid = customerid;
        this.customername = customername;
        this.customeraddress = customeraddress;
        this.mobile = mobile;
    }

    public Customer() {
    }

    public Customer(String customername, String customeraddress, int mobile) {
        this.customername = customername;
        this.customeraddress = customeraddress;
        this.mobile = mobile;
    }

    public int getCustomerid() {
        return customerid;
    }

    public void setCustomerid(int customerid) {
        this.customerid = customerid;
    }

    public String getCustomername() {
        return customername;
    }

    public void setCustomername(String customername) {
        this.customername = customername;
    }

    public String getCustomeraddress() {
        return customeraddress;
    }

    public void setCustomeraddress(String customeraddress) {
        this.customeraddress = customeraddress;
    }

    public int getMobile() {
        return mobile;
    }

    public void setMobile(int mobile) {
        this.mobile = mobile;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "customerid=" + customerid +
                ", customername='" + customername + '\'' +
                ", customeraddress='" + customeraddress + '\'' +
                ", mobile=" + mobile +
                '}';
    }

CustomerUpdateDTO
``package com.Project.SpringAngular.DTO;

public class CustomerUpdateDTO {
    private int customerid;
    private String customername;
    private String customeraddress;
    private int mobile;

    public CustomerUpdateDTO(int customerid, String customername, String customeraddress, int mobile) {
        this.customerid = customerid;
        this.customername = customername;
        this.customeraddress = customeraddress;
        this.mobile = mobile;
    }

    public CustomerUpdateDTO() {
    }

    public int getCustomerid() {
        return customerid;
    }

    public void setCustomerid(int customerid) {
        this.customerid = customerid;
    }

    public String getCustomername() {
        return customername;
    }

    public void setCustomername(String customername) {
        this.customername = customername;
    }

    public String getCustomeraddress() {
        return customeraddress;
    }

    public void setCustomeraddress(String customeraddress) {
        this.customeraddress = customeraddress;
    }

    public int getMobile() {
        return mobile;
    }

    public void setMobile(int mobile) {
        this.mobile = mobile;
    }

    @Override
    public String toString() {
        return "CustomerDTO{" +
                "customerid=" + customerid +
                ", customername='" + customername + '\'' +
                ", customeraddress='" + customeraddress + '\'' +
                ", mobile=" + mobile +
                '}';
    }
}`
`

Angular
setUpdate(data: any)
  {
   this.customername = data.customername;
   this.customeraddress = data.customeraddress;
   this.mobile = data.mobile;
   this.currentCustomerID = data.customerid;
  }

  UpdateRecords()
  {
    let bodyData = {
      "customername" : this.customername,
      "customeraddress" : this.customeraddress,
      "mobile" : this.mobile
    };

    this.http.post("http://localhost:8084/api/v1/customer/update"+ "/"+ this.currentCustomerID,bodyData,{responseType: 'text'}).subscribe((resultData: any)=>
    {
        console.log(resultData);
        alert("Employee Registered Updateddd")
        this.getAllCustomer();
        this.customername = '';
        this.customeraddress = '';
        this.mobile  = 0;

    });
  }


text:
Q: no matching versions for query "latest" with a local package go version go1.15.2 darwin/amd64

within my folder I have two files: main.go and user.go along with other files such as go.mod, go.sum etc.
when trying to import the package from user.go I get the error in my imports:

no matching versions for query "latest"

user.go
package user

import (
    "os"
    "os/user"
    "path/filepath"
)

main.go
import (
    "fmt"
    "bufio"
    "github.com/ctfrancia/go-dot/user" // <--- error here
    // ...
)

I tried following some suggestions such as go clean -modcache as suggested in a git hub issue
I'm using gomods so I don't want to disable it. Thanks

A: so my mistake was that the folder in the directory is the package name... well best practice:
so: goApplication/pkg/hello all the subsequent .go files should have package hello at the top

A: Your files user.go and main.go are in same directory, in golang if you want to work with custom packages you have to create directories with the same name as your package name in your case your directory structure will be something like:
goApplication/rootDir
- main.go
- user
-- user.go

Note: You can also use pkg/user directory but it is not mandatory for small projects and community has positive as well as negative remarks for this layout structure.


text:
Q: SQL Server - Select Rows in Derived Table that have count > 1 of value in one column Help please. I have the following Select query and want to select only the rows where the column A.Name repeats more than 1 time:
SELECT
    A.Payer,
    A.PaymentDate,
    A.Name
FROM
    (SELECT
         T.InstitutionRoleXrefLongName AS 'Payer',
         T.PaymentDate AS 'PaymentDate',
         T.FullName AS 'Name'
     FROM
         Transfer T
     UNION ALL
     SELECT
         T.InstitutionRoleXrefLongName AS 'Payer',
         T.PaymentDate AS 'PaymentDate',
         T.FullName AS 'Name'
     FROM
         TransferClosed T) A
WHERE
    PaymentDate BETWEEN '20180101' AND '20180331 23:59:59'

A: using CTE and  self join to get the count which greater than 1.
You can try this.
 ;with CTE AS (
    SELECT
        A.Payer,
        A.PaymentDate,
        A.Name
    FROM (
        SELECT
            T.InstitutionRoleXrefLongName AS 'Payer',
            T.PaymentDate AS 'PaymentDate',
            T.FullName AS 'Name'
        FROM Transfer T
    UNION ALL
        SELECT
            T.InstitutionRoleXrefLongName AS 'Payer',
            T.PaymentDate AS 'PaymentDate',
            T.FullName AS 'Name'
        FROM TransferClosed T
    ) A
    WHERE PaymentDate Between '20180101' AND '20180331 23:59:59'
)
select t2.*
from (
    SELECT name,count(1) totle
    FROM CTE
    GROUP BY Name
) t1 inner join CTE t2
ON t1.totle > 1 and t1.Name = t2.Name

The sqlfiddle CTE mock your result set
sqlfiddle:http://sqlfiddle.com/#!18/cc68f/9

A: WITH Payments AS (
    SELECT
        A.Payer, A.PaymentDate, A.Name,
        COUNT(*) OVER (PARTITION BY A.Name) AS NameCount
    FROM (
        SELECT
            T.InstitutionRoleXrefLongName AS Payer,
            T.PaymentDate AS PaymentDate,
            T.FullName AS Name
        FROM Transfer T
        UNION ALL
        SELECT
            T.InstitutionRoleXrefLongName AS Payer,
            T.PaymentDate AS PaymentDate,
            T.FullName AS Name
        FROM TransferClosed T
    ) A
    WHERE PaymentDate Between '20180101' AND '20180331 23:59:59'
)
SELECT * FROM Payments WHERE Name_Count > 1;

You might find that the query performs better by duplicating that date filter in both sides of the union. Just a thought.


text:
Q: Blob datatype issue with log file I am getting continuously below error message in mysqld.log
[ERROR] InnoDB: The total blob data length (10152274) is greater than 10% of the redo log file size (3072). Please increase innodb_log_file_size.
The size of tables which are having blob datatype is 690 MB.
The size of each ib_logfile is 48MB
As per the error message should I increase my ib_logfiles to more than 69MB. If so, when again if data of blob tables increases to 10GB, should I increase my log files to 1 GB.
Please suggest me how to resolve this, and how are these dependent to each other.
OS is Linux
MySQL version is 5.6.21
Later, I had changed all the columns whose datatype from BLOB to TEXT. Now there are BLOB datatype tables only in 'mysql' schema. Even after converting the datatype, I am observing the above error message.


text:
Q: Canvas alignment issue I'd like to generate a field that displays NxNsquares. (In the example it displays 2x2 red squares) in the center of the canvas. The field where the squares are located in should be horizontally & vertically centered in the canvas. (Also after changing rowCount for sure)
Moreover fieldSize declares the size of the calculated area where the red squares are aligned in. Changing the factor will change the fields Size. (1 == canvas Size, 0.5 = 1/2 canvas Size)

My question:
In the example below (it is hard to see) the red boxes aren't really centered but I'd like them to be. Have a look at this image:

let canvas = document.getElementById("canvas")

/* edit these values */
let rowCount = 2
let fieldSize = canvas.width * 0.8
/********************/

let ctx = canvas.getContext("2d")

for (let y = 0; y < rowCount; y++) {
  for (let x = 0; x < rowCount; x++) {

    let squareSize = (fieldSize / rowCount) * 0.7

    let positionX = (fieldSize / rowCount) * (x) + (canvas.width - fieldSize) * 0.5
    let positionY = (fieldSize / rowCount) * (y) + (canvas.width - fieldSize) * 0.5

    ctx.rect(positionX, positionY, squareSize, squareSize);
    ctx.fillStyle = "red"
    ctx.fill()
  }

}
<canvas style="background: green" id="canvas" width="300" height="300" id="codeCanvas"></canvas>

A: You can do that way (it works for any amount of rows) :
(canvas.width - fieldSize) / 2)

is for the padding of the field
x * (fieldSize / rowCount)

is for the relative position of each square
(fieldSize / rowCount - squareSize) / 2

is for the padding of each square and that is missing in your code

/* edit these values */
let rowCount = 2
let fieldSize = canvas.width * 0.8
let squareSize = (fieldSize / rowCount) * 0.8
/********************/

let ctx = canvas.getContext("2d")

for (let y = 0; y < rowCount; y++) {
    for (let x = 0; x < rowCount; x++) {

        let positionX = (canvas.width - fieldSize) / 2 + x * (fieldSize / rowCount) + (fieldSize / rowCount - squareSize) / 2
        let positionY = (canvas.width - fieldSize) / 2 + y * (fieldSize / rowCount) + (fieldSize / rowCount - squareSize) / 2

        ctx.rect(positionX, positionY, squareSize, squareSize);
        ctx.fillStyle = "red"
        ctx.fill()
    }
}
<canvas style="background: green" id="canvas" width="300" height="300" id="codeCanvas"></canvas>

A: Take the "inner space" without padding and spread your squares on that.
Due to rounding issues, you are not free to use all combinations of padding/spacing. To produce a prefect grid, you will have to use discrete square sizes to prevent aliasing or blurring effects.

function tiled(canvas, rowCount) {
  const ctx = canvas.getContext("2d");
  const spacing = 10;
  const padding = 30;
  const cellSize = (canvas.width - 2 * padding + spacing) / rowCount;
  const squareSize = cellSize - spacing;

  let positionX = padding;
  let positionY = padding;

  for (let y = 0; y < rowCount; y++) {
    positionX = padding;
    for (let x = 0; x < rowCount; x++) {
      ctx.rect(positionX, positionY, squareSize, squareSize);
      ctx.fillStyle = "red"
      ctx.fill();
      positionX += cellSize;
    }
    positionY += cellSize;
  }
}

tiled(document.getElementById("canvas"), 2);
tiled(document.getElementById("canvas2"), 3);
tiled(document.getElementById("canvas3"), 4);
tiled(document.getElementById("canvas4"), 5);
<canvas style="background: green" id="canvas" width="300" height="300"></canvas>
<canvas style="background: green" id="canvas2" width="300" height="300"></canvas>
<canvas style="background: green" id="canvas3" width="300" height="300"></canvas>
<canvas style="background: green" id="canvas4" width="300" height="300"></canvas>

A: This might help !

let canvas = document.getElementById("canvas")

/* edit these values */
let rowCount = 2
let fieldSize = canvas.width * 0.8
/********************/

let ctx = canvas.getContext("2d")

let width = canvas.width;
let height = canvas.height;

let dist = canvas.width/(rowCount + 1)

for(let i=1;i<=rowCount;i++){
  for(let j=1;j<=rowCount;j++){
  let w = (fieldSize / rowCount) * 0.8
    let posx = dist*i - w/2;
    let posy = dist*j - w/2;
    ctx.rect(posx,posy,w,w);
    ctx.fillStyle = "blue"
    ctx.fill();
  }
}
<canvas style="background: green" id="canvas" width="300" height="300" id="codeCanvas"></canvas>


text:
Q: How to fix : Error: Authentication failed I'm trying to connect remotely on a mongodb server throw my local machine, but i'm having some issues.
On the remote server i modified the 'mongod.cfg' file and i changed the bindIp from 127.0.0.1 to 0.0.0.0 to allow access. In the same file i changed the security by adding Authentication: 'enabled'.
I created an admin user:
> use admin
> db.createUser({user: "root", pwd: "root", roles:["root"]})

I started mongodb with --auth flag
> mongod --auth --port 27017

Once the server was up, i connect to it as administrator
mongo 127.0.0.1:27017 -u "root" -p "root" --authenticationDatabase "admin"

Once i was connected, i created a normal user
> use base
> db.createUser({user: "base", pwd: "base", roles:["dbOwner"]})

Then i disconnected from mongo shell and reconnected with new user credentials
> mongo <127.0.0.1:27017>/base -u "base" -p "base"

It worked properly on the remote server.
On the local machine i tried the same command on my local machine and it failed
> mongo 127.0.0.1:27017/base -u "base" -p "base"
[js] Error: Authentication failed. :
connect@src/mongo/shell/mongo.js:344:17
@(connect):2:6
exception: connect failed

A: 127.0.0.1 is making reference to the localhost of the host machine, you need to set the user in both machines if you are going to use one, if you want to use a db that share the data in the cloud you can use Mlab or if both ip are in the same network you can make reference from one to another by the ip address
mongo <ip_address>:27017/base -u "base" -p "base"


text:
Q: Remove element from heapq I am trying to implement the AStar search algorithm and I'm having trouble removing elements from the fringe (open list). I push my Cells in like this:
heapq.heappush(myHeap, (priority, cell)

My cell class looks like this:
class Cell(object):
    def __init__(self, x, y):
        self.X = int(x)
        self.Y = int(y)
        self.G = float("inf")
        self.parent = None

    def __lt__(self, other):
        return (self.X, self.Y) < (other.X, other.Y)

    def __eq__(self, other):
        return int(self.X) == int(other.X) and int(self.Y) == int(other.Y)

Is there a way I can just do heapq.remove(cell) or heapq.heappop(cell) to remove the entry from the heap and then reheapify it?
Currently, I'm doing it like this but I don't think it's working correctly as I get an infinite loop sometimes:
def remove(self, item):
    index = 0

    for i in range(len(myHeap)):
        if(myHeap[i][1] == item):
            index = i

    # Move slot to be removed to top of heap
    while index > 0:
        up = int((index + 1) / 2 - 1)
        self.heap[index] = self.heap[up]
        index = up

    # Remove top of heap and restore heap property
    heapq.heappop(myHeap)

Any help would be appreciated.

A: You can use the regular list methods also on your list myHeap. So first remove some particular element from the list, then heapify and push an element with new priority:
myHeap.remove((priority, cell))
heapq.heapify(myHeap)
heapq.heappush(myHeap, (new_priority, cell))


text:
Q: Python runtime type check that function passed to a decorator has correct signature I have a python decorator that expects the signature of the passed function to be a User and a Point, and it returns a function with the same signature:
@dataclass
class User:
    name: str

@dataclass
class Point:
    x: float
    y: float
    z: float

def logging_decorator(f: Callable[[User, Point], bool]) -> Callable[[User, Point], bool]:
    print('decorating function...')
    def decorated(a: User, b: Point) -> bool:
        print(f'User {a.name} calling with points {b.x},{b.y},{b.z}')
        ret = f(a, b)
        print(f'returned {ret}')
        return ret
    return decorated

At the point it prints decorating function..., I want it to check that the function which has been passed in has the correct signature, and give a sensible error message if it does not.
Here is an example of decorating two functions, one with the correct signature, and one with an incorrect one:
@logging_decorator
def good_f(a: User, b: Point) -> bool:
    return True

@logging_decorator
def bad_f(a: str, b: str) -> str:
    return "Hello"

How can I add checks to the logging_decorator so it checks that the function being decorated has the correct argument types?
I have tried using the typing_inspect and typeguard packages, but cannot find the functionality I need.
I am using Python 3.8.3

A: Use the inspect module in the standard library. With inspect.signature, you can write function-validation code like this:
import inspect

def validate_func(func):
    def good_func(a: User, b: Point) -> bool: ...
    good_func_signature = inspect.signature(good_func)
    received_signature = inspect.signature(func)
    if received_signature != good_func_signature:
        raise TypeError(
            f'Invalid function signature: '
            f'expected "{good_func_signature}", '
            f'got "{received_signature}"'
        )

(You can put this logic inside the decorator for your use case; I only wrote it as a separate function to keep it separate from your code.)
In usage:
>>> validate_func(good_f)
>>> validate_func(lambda a, b: a)
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "<string>", line 6, in validate_func
TypeError: Invalid function signature: expected "(a:__main__.User, b:__main__.Point) -> bool", got "(a, b)"
>>> validate_func(bad_f)
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "<string>", line 6, in validate_func
TypeError: Invalid function signature: expected "(a:__main__.User, b:__main__.Point) -> bool", got "(a:str, b:str) -> str"

If you want to, you can do far more detailed and fine-grained comparisons between signatures than just a simple equality check. You can use the return value from inspect.signature to compare:

*

*The number of parameters

*The names of the parameters

*The kinds of the parameters (positional-only, positional-or-keyword, or keyword-only)

*Whether the parameters have annotations

*What the annotations of the parameters are

*Whether the  parameters have default values

*What the default values of the parameters are

*Whether the function has a return annotation

*What the return annotation of the function is

You can find the documentation for inspect.signature here.


text:
Q: ASP.NET Resource resx String tooltip display help I have a string, Mini-move.Help, stored in a resource file that I would like displayed whenever user clicks on the help image that is displayed.
NOTE: the help image is displayed dynamically when you add the .HELP to your resource string.
I want to style this display in such a way that when user clicks on the image button generated as a result of storing the resx file, a popup/tooltip like popup shows up instead.
Every Few Minutes - MM:

Every Hour - H;

Every Day - D;Su,Mo,Tu,We,Th,Fr,Sa;

How do I accomplish this please?
thanks in advance

A: <img src="[path]"  title="" onclick="this.setAttribute('title', '<%$ Resources:SiteResources,Mini-move.Help %>');" />

This will set title on image when click event occures


text:
Q: $.post() doesn't send data as json but as x-www-form-urlencoded instead This one is really weird. I have multiple $.post() in the code, but there is one don't know why sends the json parameters as x-www-form-urlencoded instead and therefore doesn't work.
Here's the code:
$.post("/Route/SaveTransportProperties", { properties: JSON.stringify(propArray), currTravelBox: JSON.stringify(travelBoxObj), accessToken: getAccessToken()}, function(data)
    {
        //DO STUFF
    });

The XHR looks like this in Firefox:

Any ideas why is this happening? I also enforced the type as 'json' but doesn't work either.

A: Because $.post() is for sending form-like requests. $.ajax is for sending whatever you want to. See contentType in $.ajax page for more information.
Quote:

When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded", which is fine for most cases. If you explicitly pass in a content-type to $.ajax() then it'll always be sent to the server (even if no data is sent). Data will always be transmitted to the server using UTF-8 charset; you must decode this appropriately on the server side.

A: this also works for me
$.ajax({
  url: "mydomain.com/url",
  type: "POST",
  dataType: "xml/html/script/json", // expected format for response
  contentType: "application/json", // send as JSON
  data: JSON.stringify(data),

  complete: function() {
    //called when complete
  },

  success: function() {
    //called when successful
 },

  error: function() {
    //called when there is an error
  },
});

A: If you want to send the data as json then use the $.ajax function
You can specify type post and dataType json.
$.ajax({
  url: "mydomain.com/url",
  type: "POST",
  dataType: "xml/html/script/json", // expected format for response
  contentType: "application/json", // send as JSON
  data: $.param( $("Element or Expression") ),

  complete: function() {
    //called when complete
  },

  success: function() {
    //called when successful
 },

  error: function() {
    //called when there is an error
  },
});

Taken from ajax documentation
http://api.jquery.com/jQuery.ajax/
contentTypeString
Default: 'application/x-www-form-urlencoded; charset=UTF-8'

A: you can also force your data to be a json in the success function:
data = JSON.parse(data);


text:
Q: Create 100 X 100 frame around camera screen I am working on a camera based app. It is related to histogram. When I open up the app it should start the camera and it should make frame of 100 x 100 in the center of the screen.
The camera starts showing the images on screen but I don't know how to make frame around the center of the screen.
Please guide me.

A: If you want a 100x100 frame on top of the camera image then just create a 100x100 frame in a png image with transparent background. Create a UIImageView with your 100x100 frame.png and add that view to your camera view


text:
Q: Is there a standard way to denote a matrix with a single column (or single row) deleted? I would like to list the rows of sub matrix $M(i|j)$, which is the sub matrix of $M$ where the $i$-th row and $j$-th column have been deleted. So I have said that $M'$ is the matrix $M$ with the $j$-th column deleted, and $M'_k$ is the $k$-th column of $M'$, so that $$M(i|j) = \begin{bmatrix} M'_1 \\ \vdots \\ \widehat{M'}_i \\ \vdots \\ M'_n \end{bmatrix},$$
where $\widehat{M'}_i$ indicates that the row $M'_i$ should not be included in $M(i|j)$.
I am not too satisfied with my invented $M'$ notation. I am looking at proofwiki which provides several standard ways of denoting submatrices. But none seems convenient for writing a matrix where only a single column (or row) has been deleted. Is there a standard (or at least common) way to denote such a thing?


text:
Q: How do I turn the return value of a Perl sub into an arrayref? I try the code like this:
my @rows = getRows($sth);
$self->stash(rows => \@rows);

The getRows is a sub function name, and the code works in template.
The $rows is a Array.
I write code like this:
$self->stash(rows => \getRows($sth));

The $rows is a REF, It's wrong.
If write code like this:
$self->stash(rows => getRows($sth));

The $rows is a HASH, It's wrong.
Is there any way to write the two line code in one?

A: Yes.  You can write
$self->stash(rows => [getRows($sth)]);

The square brackets [] serve to create the desired reference.


text:
Q: Email address has a wrong format error, on paypal express checkout Magento 2.3.2 Paypal Express checkout not working, it says "Exception message: We can't save the address:
Email has a wrong format". However payments are being successful but Magento order isn't creating.
Anyone?
Exception message: We can't save the address:
Email has a wrong format
Trace: <pre>#1 Magento\Framework\Model\ResourceModel\Db\AbstractDb->save() called at [vendor/magento/framework/Model/AbstractModel.php:655]

I checked in this file vendor/magento/module-sales/Model/Order/Address/Validator.php
and $address->getEmail() is coming NULL/empty.

A: Issue resolved with this patch https://nimb.ws/gFA06i

Here is the code in non-image format:
    /* set customer email if email is found empty (bug) */
    if ($this->_quote->getCustomerEmail() === null && $this->_quote->getBillingAddress()->getEmail() !== null) {
        $this->_quote->setCustomerEmail($this->_quote->getBillingAddress()->getEmail());
    }


text:
Q: What path can I use to specify content in beamer theme styles? The author of this neat theme posted the source on github, but as the commits state, the background image was thrown in later and not referenced in the style files.
I added a global background template to the main style file, but using ./ as the relative path doesn't work. Is there a relative path for CURRENT_THEME that I can use to specify it? Neither the Beamer manual nor any existing questions/answers I found go into path issues about this.


text:
Q: mosquitto MQTT broker set up - getting Connecting with MQTT server failed (NotAuthorized) i'm trying to set up a broker on windows machine with Eclipse Mosquitto,
i followed all the steps based on this :
https://delightnet.nl/index.php/mqtt/12-mqtt-broker-installation

i have a listener i build in c# and i'm able to connect with it to another broker,
but when trying to connect to the broker i created, i'm getting
"MqttConnectingFailedException: Connecting with MQTT server failed (NotAuthorized)."
I Opened port 1883 in my firewall inbound and outbound.
Added this port in mosquitto.conf
my listener (working fine with another broker)
Console.WriteLine("Starting Subscriber....");
                //create subscriber client
                var factory = new MqttFactory();
                _client = factory.CreateMqttClient();

                //configure options
                _options = new MqttClientOptionsBuilder()
                    .WithClientId("sOc/BB:93:16:DE:E3:CA/s")
                    .WithTcpServer("63.250.63.219", 1883).WithCredentials("myBroker", "myBrokerpass")
                    //.WithTcpServer("39.108.54.186", 1883).WithCredentials("gateways", "admin")
                    .WithCleanSession()
                    .Build();

                //Handlers
                _client.UseConnectedHandler(e =>
                {
                    Console.WriteLine("Connected successfully with MQTT Brokers.");

                //Subscribe to topic
                _client.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("sOc/BB:93:16:DE:E3:CA/s").Build()).Wait();
                });
                _client.UseDisconnectedHandler(e =>
                {
                    Console.WriteLine("Disconnected from MQTT Brokers.");
                });

A: If you want to set up a broker, just go to https://mosquitto.org/download/ and install the package accordingly. No need coding.
If you want to test with the installed broker, you can use mosquitto_pub and mosquitto_sub. You can also use many client libraries for your client side coding.

A: Solved.
changed allow anonymous from false to true in the mosquitto.conf


text:
Q: How to prove that a language is non-regular by using Pumping lemma with length? I was given the following question:
Use the Pumping Lemma with length to prove that the following language is non-regular:
$L = \{b^na^{100}b^{2n}, \text{where n} = 1, 2, 3,...\}$
Use the prompts below to complete the proof
Assume
Then there exists
We choose any word w =
Thus we can write w =
The according to the pumping lemma with length,
There is/are __ possible choice(s) for y
If y is pumped in each of the above case(s),
Now, my answer, actually how far I came, is as follow:
Assume L is a regular language.
Then there exists an FA with, say k states that accepts L.
We choose any word w = $b^na^{100}b^2n$ in L.
Thus we can write w = $b^ka^{100}b^{2k}$
The according to the pumping lemma with length, w may be written as w = xyz such that |x| + |y| <= k and |y| > 0
Then I don't know further. I do know that y is 1 b or more. y is also at most k b's.
I would appreciate it if you will correct my mistakes and also finish the answer.
Thank you

A: You've filled in the first two blanks correctly, but after that you've gone a bit astray, I think because you're not seeing how the contradiction is going to arise.
It's true that you can start with any word in $L$, so $w$ could be $b^na^{100}b^{2n}$ for any $n\in\Bbb Z^+$, and the pumping lemma would say something about other members of $L$, but if we want to make matters easy for ourselves, we'll take $w=b^ka^{100}b^{2k}$. Then the pumping lemma says that we can write $w=xyz$, where $|y|\ge 1$, $|xy|\le k$, and $xy^nz\in L$ for each $n\ge 0$. So what can $y$ be? We know that $xy$ is the first $|xy|$ characters of $w$, and $|xy|\le k$, so $xy$ is contained in the first $k$ characters of $w$. And $w$ begins with $k$ $b$s, so $xy$ is a string of $b$s, say $xy=b^\ell$. What are the possible choices for $\ell$? It has to be at least $1$: $x$ can be the empty string, but we know that $|y|\ge 1$. And it can be at most $k$, since we know that $|xy|\le k$. Thus, $1\le\ell\le k$, and there are therefore $k$ possible choices for $y$, from $b^1$ through $b^k$.
Suppose that we pump $y$ in any of these cases: if we pump $y$ up to $y^2$, we change $y=b^\ell$ to $y^2=b^{2\ell}$, adding $\ell$ $b$s, and we get the word $b^{k+\ell}a^{100}b^{2k}$. And this is our contradiction: on the one hand the pumping lemma says that this must be in $L$, but on the other hand it clearly is not in $L$, since $2k\ne 2(k+\ell)$ (because $\ell\ne 0$). Thus, the initial assumption that $L$ is regular must have been false.
It is possible to use other initial words to get a contradiction, but this is the simplest.


text:
Q: Why is $\lim\limits_{x \space \to \infty}\space{\arctan(x)} = \frac{\pi}{2}$? As part of this problem, after substitution I need to calculate the new limits.
However, I do not understand why this is so:
$$\lim_{x  \to \infty}\space{\arctan(x)} = \frac{\pi}{2}$$
I tried drawing the unit circle to see what happens with $\arctan$ when $x \to \infty$ but I don't know how to draw $\arctan$. It is the inverse of $\tan$ but do you even draw $\tan$?
I would appreciate any help.

A: If you wanted to do it geometrically, your proof is the easiest. If you wanted to do it analytically, you can use the fact that $\mathrm{\tan} : (-\pi/2,\pi/2) \to \mathbb R$ is an increasing continuous bijection (even an homeomorphism), thus
$$
\lim_{x \to \infty} \mathrm{arctan}(x) = \lim_{y \to \pi/2} \mathrm{arctan}(\mathrm{tan}(y)) = \lim_{y \to \pi/2} y = \pi/2.
$$
In other words you just do the change of variables.
Hope that helps,

A: Here's a slightly different way of seeing that $\lim\limits_{\theta\rightarrow {\infty}}\arctan\theta={\pi\over2}$.
Thinking of the unit circle, $\tan \theta ={y\over x}$, where $(x,y)$ are the coordinates of the point on the unit circle with reference angle $\theta$, what happens as $\theta\rightarrow\pi/2$? In particular, what happens to $\tan\theta$ as $\theta\nearrow{\pi\over2}$?
Well, the $x$ coordinate heads towards 0 and the $y$ coordinate heads towards 1.
So in the quotient
$$
y\over x,
$$
the numerator heads to 1 and the denominator becomes arbitrarily small; so the quotient heads to infinity.
Thus, $\lim\limits_{\theta\rightarrow {\pi\over2}}\tan\theta=\infty$ and consequently
$\lim\limits_{\theta\rightarrow {\infty}}\arctan\theta={\pi\over2}$.

A: I finally solved it with help of this picture.

*

*$\sin x = BC$

*$\cos x = OB$

*$\tan x = AD$

*$\cot x = EF$

*$\sec x = OD$

*$\csc x = OF$

Note that, our nomenclature of $\tan x$ is not really arbitrary. $AD$ is really the tangent to the unit circle at A. Now it is clearly visible that when $\tan{(x)} = AD \to \infty$ then $\arctan{(AD)} = x = \frac{\pi}{2}$.

A: Since you mentioned the picture of $y =\arctan x$, have you looked it up in Wikipedia?


text:
Q: How to retrieve a reference from a boost ptr_vector? I have two classes: an Object class, and an ObjectManager class. The ObjectManager class stores "Objects" via a ptr_vector container. There are some instances where I need to retrieve references to these stored pointers to perform individual actions on them. How would I go about doing so?
Compilable Pseudo Code:
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/shared_ptr.hpp>

class Object
{
public:
  int m_Id;
  Object(int id) : m_Id(id) { }
};

class ObjectManager
{
private:
  typedef boost::shared_ptr<Object> ObjectPtr;
  typedef boost::ptr_vector<Object> ObjectVectorPtr;
  typedef ObjectVectorPtr::iterator ObjectIt;

  ObjectVectorPtr vector_;

  void AddObject(Object *obj) {
    vector_.push_back(obj);
  }

  ObjectPtr FindObject(int id) {
    for (ObjectIt it = vector_.begin(); it != vector_.end(); it++) {
      if (it->m_Id == id) {
        // Found the object...How to return a shared_ptr reference to it?
        // The line below is invalid, obviously:
        // cannot convert parameter 1 from 'Object' to 'const boost::shared_ptr<T> &'
        return *it;
      }
    }

    // We could not find anything.
    return ObjectPtr();
  }
};

Basically I want the ObjectManager to retain ownership, but I also want other classes to be able to get a reference to the object, use call methods on that object depending on what's going on, and move on.

A: Convert your container to use shared_ptr as the member:
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/shared_ptr.hpp>
#include <vector>

class Object
{
public:
  int m_Id;
  Object(int id) : m_Id(id) { }
};

class ObjectManager
{
private:
  typedef boost::shared_ptr<Object> ObjectPtr;
  typedef std::vector<ObjectPtr> ObjectVectorPtr;
  typedef ObjectVectorPtr::iterator ObjectIt;

  ObjectVectorPtr vector_;

  void AddObject(ObjectPtr& obj) {
    vector_.push_back(obj);
  }

  ObjectPtr FindObject(int id) {
    for (ObjectIt it = vector_.begin(); it != vector_.end(); ++it) {
      if (it->get()->m_Id == id) {
        // Found the object - return a shared_ptr reference to it
        return ObjectPtr(*it);
      }
    }

    // We could not find anything.
    return ObjectPtr();
  }
};

btw - prefer ++it vs it++ to avoid extra construction, and don't use matching like this if the container gets large - switch to std::map<int, ObjectPtr> with m_id as the key, or std::set with suitably-defined less function.
If I was being super-pedantic I would suggest replacing your find loop with a call to std::find_if, with a predicate that matches on Object::m_id...

A: You can't return a shared_ptr because the object wasn't created as a shared object initially - what would the reference count even be?
You can, however, return an Object* quite easily:
Object* FindObject(int id) {
    for (ObjectIt it = vector_.begin(); it != vector_.end(); it++) {
      if (it->m_Id == id) {
        // Found the object...How to return a shared_ptr reference to it?
        // The line below is invalid, obviously:
        // cannot convert parameter 1 from 'Object' to 'const boost::shared_ptr<T> &'
        return &*it;
      }
    }


text:
Q: Naming ArrayLists from user input After much research, I can't find anything on this,
Is it even possible to generate an Array list entirely from user input,
populating the list is easy, but I want to name the Array from user input also,
List<String> jTextfield.getText = new ArrayList<>();

Now i know this won't work, but is something to this effect even possible?


text:
Q: Exporting HTML Table to Excel for IE and Chrome I am trying to create a JavaScript function that will export a HTML table to Excel. The code below works in Chrome, but in IE, I receive a popup saying "No apps are installed to open this type of link (data)." I need the export to happen on the client and using ActiveXObject is not an option. Any help on making this work in both IE and Chrome would be greatly appreciated.
var uri = "data:application/vnd.ms-excel;base64,"
var template = "<!DOCTYPE html> " +
                   " " +
                   "   <meta http-equiv=Content-Type content='text/html;charset=windows-1252'><meta name=Generator content='Microsoft Excel 11'> " +
                   "   <meta name=ProgId content=Excel.Sheet> <meta name=Generator content='Microsoft Excel 11'> " +
                   "" +
                   " " +
                   "" +
                   "<form method='POST' action='PRJEdetail-ClientExportTest.asp' name='frmExcel'></form>" +
                   tableHTML +
                   "" +
               ""
var base64 = function (s) { return   window.btoa(unescape(encodeURIComponent(s))) }
window.location.href = uri + base64(template)


text:
Q: get_categories returning an empty array when it shouldn't I'm writing a file management plugin that uses the category system to create a mock filesystem hierarchy and I'm running into some issues with some code that is responsible for recursively deleting the 'folders' (actually categories). Instead of the code returning all of the child categories of the category to be deleted, it returns an empty array. Any ideas why?
    //get all child categories
    $wk_child_categories = get_categories(array('child_of' => $_POST['wk_ID'], 'orderby' => 'term_group'));
    echo " Got the child categories. They are:";
   print_r($wk_child_categories);

A: One thing that I can see that might be causing the issue is the lack of the post parameter. By default if you don't have a post parameter it will fallback to the standard Wordpress "post" type. If you are using a custom post type it would return an empty array because the query is looking in the wrong spot.
There is also the possibility that the categories are empty. In the arguments for get_categories() there is a hide_empty argument that will default to not return empty categories, try setting that to 0


text:
Q: IEnumerable as return value, deferred execution and N-tier applications First, I do not consider this question be the dup of these SO questions:
Should I always return IEnumerable<T> instead of IList<T>?
and IEnumerable<T> as return type
As we all know ont of the main purposes of introducing several tiers is to decrease coupling.
We must define some interface for data access and our BL should not care about the details of DAL implementation. If mentioned interface returnes IEnumerable<T> BL does not know whether it is just a static IEnumerable or something that has deferred execution. At the same time this particular detail can affect perfromance considerably and requires different coding depending on the implementation.
Well, it is possible to call .ToList() for each IEnumerable in situations when we are going to iterate collection several times. But this decreases perfromance for static collections because of unnecessary new list instantiation.
So I'm trying to understand which approach is better.
More universal and potentially less performant vs More coupled-more performant.
I guess, there's no silver bullet but it could be other approaches I've missed.

A:
So I'm trying to understand which approach is better: more universal and less performant vs more coupled and more performant.

First, though that is an interesting tradeoff, in this case I would think that the relevant tradeoff is actually correct vs incorrect, which surely trumps any question of performance. A deferred-execution query usually has the property that it gives you the most up to date results of the query, whereas calling ToList gives you a snapshot of a past version of the query results. There are surely cases where one is correct and the other is incorrect.
Second, assuming that you have dealt with the correctness issue and really do have a performance tradeoff to make, the tradeoff you actually want to make is: more universal and unacceptable performance vs more coupled and acceptable performance, at which is becomes clear that you have to choose the one with acceptable performance.
If both have acceptable performance and one is a few nanoseconds slower than the other, or consumes a few bytes more memory than the other, and both are correct, then who cares which one you choose? Spend your valuable time thinking about something else. And if neither have acceptable performance then you have a bigger problem to solve.

A: If it's important, conceptually, for the caller to know that the return type of the method is a List and not an IEnumerable (for example, to know that there will be no negative consequences for iterating it multiple times), then you should return a List.  The point of returning the interface instead is a way of saying, "It doesn't matter what the implementation is."  If the implementation does matter, then don't use the interface (in that specific situation).

A: I found good solution: All return types (the in interfaces) in DAL can't be IEnumerable<> (or can't be interface type). But it possible to use in BL. It can be architector's decision.


text:
Q: Monitor ssh connection and get login user information from authorized_keys is there any way to use .ssh/authorized_keys to get the corresponding login user's email when the linux system is connected through id_rsa.pub?
I try to use the content in /var/log/auth.log while I can't find the direct relationship between the records and .ssh/authorized_keys.
Thanks in advance.

A: May be someone needs it. Next command prints information about the ssh key that was used for a current session. The key is taken from a standard comment block from ~/.ssh/authorized_keys.
For instance, somebody@test.com will be printed for a key that looks this way: cyb5OrLRv0VR6gZev8...KdECf7Q== somebody@test.com
Command:
export CURRENT_SSH_USER=$(grep $(grep $(grep '@'$(who -m | awk '{print $2}') <(ps -ef) | head -1 | awk '{print $3}')']: Accepted publickey for' /var/log/auth.log | head -1 | awk '{print $16}') <(cat ~/.ssh/authorized_keys | xargs -n1 -I% bash -c 'ssh-keygen -l -f /dev/stdin <<<"%"') | tail -1 | awk '{print $3}')

The command above does these steps:

*

*who -m Only hostname and user associated with stdin.

*Taking pseudo terminal slave e.g. pts/2 for a current user from the prev. command.

*Searching for pts/2 in a list of processes ps -ef and extracting its pid.

*Looking for the pid, e.g. 21996 in /var/log/auth.log in lines like this one:
Jul 22 01:50:39 whatever-i-12345 sshd[21996]: Accepted publickey for ubuntu from 10.10.10.10 port 40411 ssh2: RSA SHA256:V4DD10NklAAAAAHNgxaurm1qaq/TOTejNjXMQABABAB. Be sure you have proper logging enabled.

*Once fingerprint SHA256:V4DD10NklAAAAAHNgxaurm1qaq/TOTejNjXMQABABAB is found, it matches it with the line from /.ssh/authorized_keys retrieves info about a name from a comment block.
Notes:
Tested only on Ubuntu 16.04.2 LTS (GNU/Linux 4.4.0-62-generic x86_64)

A: The last column of ssh public key is just a comment field and it is not present in the private key used to log in nor in the public key send to the server during the authentication attempt.
The comment in the server authorized keys can be completely different than the comment in the clients public key.
You can find the connection between the keys in authorized_keys and in the logs, but you need to convert the keys to fingerprints first using
ssh-keygen -lf ~/.ssh/authorized_keys


text:
Q: JavaScript drag drop swap div on mobile devices I'm currently working on a mobile app/game. I am having a difficult time getting an inventory system working properly on a phone. the drag and drop work perfectly fine with a mouse on the pc, but will not work on phone.
JavaScript code:

document.addEventListener("DOMContentLoaded", function(event) {
  $(document).ready(function(){
    var videoPath = "videos/lg/";
    var draggedItem = null;
    $('.segmentListItem').each(function(index){
      $(this).on("dragstart", handleDragStart);
      $(this).on("drop", handleDrop);
      $(this).on("dragover", handleDragOver);
    });
    function handleDragStart(e){
      //console.log('start');
      draggedItem=this;
      e.originalEvent.dataTransfer.effectAllowed = 'move';
      //e.dataTransfer.dropEffect = 'move'; //MH - do we need both of these?
      e.originalEvent.dataTransfer.setData('text/html', this.innerHTML);
    }

    function handleDragOver(e) {
      if (e.preventDefault) {
        e.preventDefault(); // Necessary. Allows us to drop.
      }
      e.originalEvent.dataTransfer.dropEffect = 'move';  // See the section on the DataTransfer object.
      return false;
    }

    function handleDrop(e){
      if (e.stopPropagation) {
        e.stopPropagation(); // Stops some browsers from redirecting.
      }

      if (draggedItem != this) { //MH - swap if we're not dragging the item onto itself
        var copy=$(this).clone(true,true);
        var slot1 = $(this).attr("id");
        var slot1Temp = slot1 + "temp";
        var slot2 = $(draggedItem).attr("id");
        $(this).replaceWith($(draggedItem).clone(true,true));
        $(draggedItem).replaceWith($(copy).clone(true,true));
        slotID = "slotID-" + slot1;
        document.getElementById(slot1).id = slot1Temp;
        document.getElementById(slot2).id = slot1;
        document.getElementById(slot1Temp).id = slot2;

        $.ajax({
          type: "GET",
          url: '/inventorySwap.php',
          data: {'slot1': slot1,'slot2': slot2},
          success: function(data) {
            alert(data);
          }
        });
      }
      return false;
    }
  });
});

HTML/PHP code:

slot_id ."'>
  slot_id ." src='{$itemImage}' />

Sorry if this question is set up a bit weird, I generally research and learn on my own. I don't like asking questions, I'm just completely stumped on this one.
What I need (and works perfect with mouse/on pc)
Drag element from 1 div to another. In code posted, it also changed the id of swapped elements to match their div inventory slot number. this is to prevent errors when updating database to swap within slot record.
thank you for any and all help given.

A: After a few hours of playing around with everything I managed to get what I needed.
outer div is for drop events,
middle div is for drag events, has to have width/height to fill outer div
inner div HAS to have position as absolute and z index less than the middle div.
this way no matter what, you click on middle div, and not it's inner contents.
the JS code saves both slot ids as a variable
then stores the id's innerhtml as another variable.
then it changes innerhtml of stored variable id1 with html of id2
contents as a var, then replaces each one to

function dragStart(event) {
    event.dataTransfer.setData("Text", event.target.id);
    id1 = event.target.id;
    id1Html = document.getElementById(id1).innerHTML;
}

function dragging(event) {

}

function allowDrop(event) {
    event.preventDefault();
}

function drop(event) {
    event.preventDefault();
    var data = event.dataTransfer.getData("Text");
    id2 = event.target.id;
    id2Html = document.getElementById(id2).innerHTML;
    document.getElementById(id1).innerHTML = id2Html;
    document.getElementById(id2).innerHTML = id1Html;
    alert(id1);
    alert(id2);
}
.inventorySlot1{position: absolute;top: 22%;left: 45%;width: 9%;height: 1px;height: 7%;overflow:hidden;background-color:green;opacity:0.5;}
.inventorySlot2{position: absolute;top: 22%;left: 54.5%;width: 9%;min-height: 1px;height: 7%;overflow:hidden;background-color:red;opacity:0.5;}
.inventorySlot6{position: absolute;top: 29.5%;left: 45%;width: 9%;height: 1px;height: 7%;overflow:hidden;background-color:green;opacity:0.5;}
.inventorySlot7{position: absolute;top: 29.5%;left: 54.5%;width: 9%;min-height: 1px;height: 7%;overflow:hidden;background-color:red;opacity:0.5;}