text:
Q: Can i see the changes made in the files just `git add`'ed? When i do some work in working directory, i can use git diff to see what changes I have made.
Now i just ran git add for the files newly modified and created but not yet git commit, git diff doesn't show any thing. Is it still possible to see what changes have been made which were just git add'ed?
Thanks.

A: Use git diff --staged to look at the diff for staged files.  git diff only looks at unstaged files by default.


text:
Q: Serial port communications equipment file is working on Mac but not working on window This is the code which is not running in windows but running in mac
`
public ReadWithoutTimings() {
        super();
        num = 1;
        try {
            serialPort = (SerialPort) SearchPorts3P4P.selectedPortIdentifier.open("Read JSE3P4P", 2000);
            // serialPort = (SerialPort) portId.open("Read1", 2000);
        } catch (PortInUseException e) {
            System.out.println(e);
            JOptionPane.showMessageDialog(null, e);
        }

        try {
            serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

        } catch (UnsupportedCommOperationException e1) {
            System.out.println(e1);
        }
        try {
            in = serialPort.getInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        (new Thread(new SerialReader(in))).start();
    }

    public class SerialReader implements Runnable {

        public SerialReader(InputStream in) {
            inputStream = in;
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            br = new BufferedReader(new InputStreamReader(inputStream));
            try {
                bw = new BufferedWriter(new FileWriter(FILENAME));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void run() {
            String inputLine = null;
            try {
                long start = System.currentTimeMillis();
                long end = start + 120 * 1000;// 60 seconds * 1000 ms/sec
                while (System.currentTimeMillis() < end) {
                    if (in.available() > 0) {
                        while ((inputLine = br.readLine()) != null) {
                            // series.put(num, inputLine);
                            // num++;

                            bw.write(inputLine);
                            bw.newLine();
                            bw.flush();
                            System.out.println(inputLine);

                            if (inputLine.trim().startsWith("DATE") | inputLine.trim().startsWith("REMARK")
                                    | inputLine.trim().startsWith("TESTED BY")) {
                                serialPort.close();
                                inputStream.close();
                                br.close();
                                bw.close();
                                break;
                            }
                        }
                        end = System.currentTimeMillis();
                    } else if (System.currentTimeMillis() >= end) {
                        serialPort.close();
                        inputStream.close();
                        br.close();
                        bw.close();
                        PreviewJse3P4P.search.dispose();
                        JOptionPane.showMessageDialog(null, "Please reconnect again");
                        PreviewJse3P4P.frame.setVisible(true);
                    }
                }
                new CompareClass();
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }

    }

    public static void main(String[] args) {

        /*
         * portList = CommPortIdentifier.getPortIdentifiers(); //
         * System.out.println(System.getProperty("java.library.path")); while
         * (portList.hasMoreElements()) { portId = (CommPortIdentifier)
         * portList.nextElement(); if (portId.getPortType() ==
         * CommPortIdentifier.PORT_SERIAL) { if
         * (portId.getName().equals("/dev/cu.usbserial-FTCC026H")) { //
         * System.out.println("Connecting.....");
         *
         * new ReadWithoutTimings(); } } }
         */

    }
}
`This is the code which is running in windows and mac

     public static void main(String[] args) {
        portList = CommPortIdentifier.getPortIdentifiers();
        //System.out.println(System.getProperty("java.library.path"));
        while (portList.hasMoreElements()) {
            portId = (CommPortIdentifier) portList.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                 if (portId.getName().equals("/dev/cu.usbserial-FTCC026H")) {
                     System.out.println("Connecting.....");
            //                if (portId.getName().equals("/dev/term/a")) {
                    Read reader = new Read();
                }
            }
        }
    }
    public Read() {
        try {
            serialPort = (SerialPort) portId.open("Read", 2000);
        } catch (PortInUseException e) {System.out.println(e);}
        try {
            inputStream = serialPort.getInputStream();
        } catch (IOException e) {System.out.println(e);}
    try {
            serialPort.addEventListener(this);
    } catch (TooManyListenersException e) {System.out.println(e);}
        serialPort.notifyOnDataAvailable(true);
        try {
            serialPort.setSerialPortParams(9600,
                SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1,
                SerialPort.PARITY_NONE);
////////////////////////////////////put these lines to read line
            try {
                inputStream = serialPort.getInputStream();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            br = new BufferedReader(new InputStreamReader(inputStream));
 ////////////////////////////////////////////////////////////////////
        } catch (UnsupportedCommOperationException e) {System.out.println(e);}
        readThread = new Thread(this);
        readThread.start();
    }

    public void run() {
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {System.out.println(e);}
    }
    public void serialEvent(SerialPortEvent event) {
        switch(event.getEventType()) {
        case SerialPortEvent.BI:
        case SerialPortEvent.OE:
        case SerialPortEvent.FE:
        case SerialPortEvent.PE:
        case SerialPortEvent.CD:
        case SerialPortEvent.CTS:
        case SerialPortEvent.DSR:
        case SerialPortEvent.RI:
        case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
            break;
        case SerialPortEvent.DATA_AVAILABLE:
           byte[] readBuffer = new byte[1024];
           String num = "";String temp = "";

            try {
                //put these lines to read line
                String inputLine=br.readLine();
                System.out.println(inputLine);
                //////////////////////////////
            } catch (IOException e) {System.out.println(e);}
            break;
        }
    }

    }

I made a program that select port from the combo box and press connect button and than send data. It's perfectly working on Mac but not working on window. I have put Rxtx.jar and rxtxSerial.dll to respective folder n jre but still it's not working. May be dll and jar file is not proper. Anybody is having dll & jar file for serial port communication for window. What is the problem not working with window. Even it's showing serial com port it means Rxtx.jar is working ,problem is with dll. Please tell me the reason and how to rectify.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change parent's state using funciton in child component How to re render data using setState [child to parent] ? deleteItem function in FoodList should delete the selected data and re render it. Im not asking for delete code but on how will i re render the main component having a function inside child component which should deleteItem does the re rendering
I have a 3 components. Main, Food and FoodList.
Main Component - Holds the list of food in array via state and pass it as props to Food Component.

class Main extends Component{
    constructor(){
        super();
        this.state = {
            foods: []
        };
    }

    componentWillMount(){
        this.setState({
            foods: [
                {
                    id: uui.v4(),
                    name: "Chocolate Cake",
                    category: "dessert"
                },
                {
                    id: uui.v4(),
                    name: "Milkshake",
                    category: "beverage"
                }
            ]
        });
    }

    render(){
        return(<Food lists={this.state.foods}/>);
    }
}

Food Component - maps the recieved lists props of food and pass it to FoodList Component to render as lis

class Food extends Component{
    render(){
        let items;
        //check if object has value;
        if(this.props.lists)
        {
            items = this.props.lists.map(food => {
                //pass each food as props
                return <FoodList key={food.id} food_list={food} />;
            });
        }

        return(

Available Foods

            {items}

        );
    }
}

FoodList Component - recieves the mapped props and render as li

class FoodList extends Component {

    deleteItem(id)
    {
        console.log(id);
        //delete item using passed id and re rende food state in Main Component
    }

    render(){
        return
{this.props.food_list.name} - {this.props.food_list.category}
        Delete

    }
}

A: Add this to your Main component
deleteItem(id) {
  this.setState({
    foods: this.state.data.filter(food => food.id !== id)
  })
}

Pass it through your Components
<Food lists={this.state.foods} deleteItem={this.deleteItem.bind(this)}/>

-
items = this.props.lists.map((food, index) => {
  return <FoodList key={food.id} food_list={food} deleteItem={this.props.deleteItem}/>;
});

Invoke it onClick of your delete button
deleteItem(id) {
  this.props.deleteItem(id);
}

Delete

A: I think you can create a method on the parent component and pass it as a prop to the child component
example
class Main extends Component{
    constructor(){
        super();
        this.state = {
          foods: []
        };
    }

    deleteFood = (id) => {
      let foods = this.state.foods;
      let index = -1;
      for(let i = 0; i < foods.length; i++){
        if(foods[i].id == id){
          index = i;
          break;
        }
      }
      if(index == -1){
        return;
      }
      foods.splice(index, 1);
      this.setState({foods: foods});
    }

    componentWillMount(){
        this.setState({
            foods: [
            {
                id: uui.v4(),
                name: "Chocolate Cake",
                category: "dessert"
            },
            {
                id: uui.v4(),
                name: "Milkshake",
                category: "beverage"
            }
            ]
        });
    }

    render(){
        return(<Food deleteFood={this.deleteFood} lists={this.state.foods}/>);
    }
}

do the same for rendering FoodList in your Food component
<FoodList key={food.id} food_list={food} deleteFood={this.props.deleteFood} />

and finally use it in your foodlist component
deleteItem(id)
    {
        console.log(id);
        this.props.deleteFood(id);
        //delete item using passed id and re rende food state in Main Component
    }


text:
Q: Why VS build automation gets all solution files? I set a Visual Studio Build automation (on VS Team Services) for a team project containing several projects.
I need to create a build only for a wpf project instead the entire team project. So  I selected the specific project on the build configuration UI, like the following image.

However, when the build starts, I see that every single file in the entire team project is being GET.
Is it normal? My WPF project depends on another two projects, not the entire thing.
Is this a concern? How can I fix that?
Thanks

A: The build agent has no way to know that your project has only two references until it starts to build it.
You can narrow the number of file it will get by going to the tab "Repository" in the build definition and choose a mapping that is closer to the project. But don't forget to include all the dependencies


text:
Q: A question about the measurability of convex sets. Let $E$ be a convex set of $\mathbb{R}^N$, symmetric respect to the origin and bounded. Is it true that there exists an $L^1$ function $l(\theta)$ defined on $S^{N-1}$ with values in $\mathbb{R}^{+}$ such that
$$ E=\{ t \cdot \theta : \, 0 \leq t \leq l(\theta) ,\, \theta \in S^{N-1} \}.$$
And what if I consider unbounded sets instead?
This fact was crucial for me to prove the following lemma.
Prove that an isoperimetric set $E$ of $\mathbb{R}^n$ which is symmetrical with respect to origin and convex is necessarily a ball.
The whole proof stands on proving that the function $l(\theta)$ that I introduced is constant. But I need to prove that $l(\theta)$ admits Lebesgue points first, so I need $l(\theta)$ to be in $L^1(S^{N-1})$ for the Lebesgue differentiation theorem to work, right?


text:
Q: Trying vs Just trying I've noticed you tend to say "just trying" when asked what you're doing. Would that work with 'just' omitted?
A: What are you doing, Tom?
B: Just trying to cook something.
A: What are you doing, Tom?
B: Trying to cook something.

A: Yes, it would still work if you omit "just".
It's strange, but "just" used here infers a casualness around the action.


text:
Q: Set build number for conda metadata inside Azure pipeline I am using the bash script to build the conda pakage in azure pipeline conda build . --output-folder $(Build.ArtifactStagingDirectory) And here is the issue, Conda build uses the build number in the meta.yml file(see here).
A solution of What I could think of is, first, copy all files to Build.ArtifactStagingDirectory and add the Azure pipeline's Build.BuildNumber into the meta.yml and build the package to Build.ArtifactStagingDirectory (within a sub-folder)
I am trying to avoid do it by writing shell script to manipulate the yaml file in Azure pipeline, because it might be error prone. Any one knows a better way? Would be nice to read a more elegant solution in the answers or comments.

A: I don't know much about Azure pipelines. But in general, if you want to control the build number without changing the contents of meta.yaml, you can use a jinja template variable within meta.yaml.
Choose a variable name, e.g. CUSTOM_BUILD_NUMBER and use it in meta.yaml:
package:
  name: foo
  version: 0.1

build:
  number: {{ CUSTOM_BUILD_NUMBER }}

To define that variable, you have two options:

*

*Use an environment variable:
export CUSTOM_BUILD_NUMBER=123
conda build foo-recipe

OR

*

*Define the variable in conda_build_config.yaml (docs), as follows
echo "CUSTOM_BUILD_NUMBER:" >> foo-recipe/conda_build_config.yaml
echo " - 123"               >> foo-recipe/conda_build_config.yaml

conda build foo-recipe

If you want, you can add an if statement so that the recipe still works even if CUSTOM_BUILD_NUMBER is not defined (using a default build number instead).
package:
  name: foo
  version: 0.1

build:
  {% if CUSTOM_BUILD_NUMBER is defined %}
    number: {{ CUSTOM_BUILD_NUMBER }}
  {% else %}
    number: 0
  {% endif %}


text:
Q: Google Geocoding API Licensing I'm building an application and I need to get the coordinates based on address, so I'm planning to use the Google Geocoding API. As I read in the Geocoding reference https://developers.google.com/maps/articles/geocodestrat I may store the data to avoid exceed the limit.
However, my application it's not a map based, I mean, has no map in my application and I just need the coordinates (latitude and longitude) to fulfill an own system that get some store information within a radius from coordinates.
Could I use the Google Geocoding API for this purpose? Is it allowed by licensing?

A:
10.1.1 (h) No Use of Content without a Google Map. You must not use or display the Content without a corresponding Google map, unless you are explicitly permitted to do so in the Maps APIs Documentation. In any event, you must not use or display the Content on or in conjunction with a non-Google map. For example, you must not use geocodes obtained through the Service in conjunction with a non-Google map. As another example, you must not display Street View imagery alongside a non-Google map, but you may display Street View imagery without a corresponding Google map because the Maps APIs Documentation explicitly permits you to do so.

https://developers.google.com/maps/terms

A: Though the general terms disallow use of content without a Google map, I think the specific terms for the Geocoding API permit it.

The following terms apply only to the Geocoding API:
3.1 Use without a Google Map. Customer may use Google Maps Content from the Geocoding API in Customer Applications without a corresponding Google Map.

Source: https://cloud.google.com/maps-platform/terms/maps-service-terms#3.-geocoding-api


text:
Q: BigQuery use_avro_logical_types ignored in Python script I'm trying to load AVRO files to BigQuery using a Python script. This process itself succeeds, but I'm having some trouble getting BigQuery to use AVRO's logical data types during table creation.
Using these logical types is documented by Google here and was added to the google-cloud-python libraries here.
I'm not a coder by profession but I'd expect below snippet to be correct... The use_avro_logical_types property however, seems to be ignored and timestamps are loaded as INT instead of TIMESTAMP.
...
with open(full_name, 'rb') as source_file:
           var_job_config = google.cloud.bigquery.job.LoadJobConfig()
           var_job_config.source_format = 'AVRO'
           var_job_config.use_avro_logical_types = True
           job = client.load_table_from_file(
               source_file, table_ref, job_config=var_job_config)
        job.result()  # Waits for job to complete
...

The AVRO schema is as follows:
{
    "type": "record",
    "name": "table_test",
    "fields": [{
        "name": "id_",
        "type": {
            "type": "bytes",
            "logicalType": "decimal",
            "precision": 29,
            "scale": 0
        }
    },
    {
        "name": "datetime_",
        "type": ["null",
        {
            "type": "long",
            "logicalType": "timestamp-micros"
        }]
    },
    {
        "name": "integer_",
        "type": ["null",
        {
            "type": "bytes",
            "logicalType": "decimal",
            "precision": 29,
            "scale": 0
        }]
    },
    {
        "name": "varchar_",
        "type": ["null",
        {
            "type": "string",
            "logicalType": "varchar",
            "maxLength": 60
        }]
    },
    {
        "name": "capture_time",
        "type": {
            "type": "long",
            "logicalType": "timestamp-millis"
        }
    },
    {
        "name": "op_type",
        "type": "int"
    },
    {
        "name": "seq_no",
        "type": {
            "type": "string",
            "logicalType": "varchar",
            "maxLength": 16
        }
    }]
}

Can anyone elaborate on this issue? Thanks!

A: Apparently my Python libs weren't as up-to-date as I thought.. updating my Google Cloud libs solved the issue. Thanks for your input shollyman

A: The code looks correct, and the logical type annotations look correct as well. I see that you have both milli and micro precisions, but I don't believe that will matter in this case.
One possibility:  Are you writing to an existing table?  As written, the code sample will use an APPEND write disposition as its the default for load jobs.  In this case, the load may be adapting the schema to what's defined (e.g. the table was initially created with the columns as INTEGER rather than TIMESTAMP).  You should be able to test by directing the load to a nonexistent table, or possibly using a truncate write disposition to allow overwriting the table.
var_job_config.write_disposition = bigquery.WriteDisposition.WRITE_TRUNCATE


text:
Q: Select an area to capture using the mouse I'm making a Java based screen shot application, and I want to make it so when you push a combination of keys on your keyboard something like this video happens where you select and area on your screen, and it takes a screen shot of the selected area.
How to select an area to capture using the mouse?

A: Start with something like this.

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;

/** Getting a Rectangle of interest on the screen.
Requires the MotivatedEndUser API - sold separately. */
public class ScreenCaptureRectangle {

    Rectangle captureRect;

    ScreenCaptureRectangle(final BufferedImage screen) {
        final BufferedImage screenCopy = new BufferedImage(
                screen.getWidth(),
                screen.getHeight(),
                screen.getType());
        final JLabel screenLabel = new JLabel(new ImageIcon(screenCopy));
        JScrollPane screenScroll = new JScrollPane(screenLabel);

        screenScroll.setPreferredSize(new Dimension(
                (int)(screen.getWidth()/3),
                (int)(screen.getHeight()/3)));

        JPanel panel = new JPanel(new BorderLayout());
        panel.add(screenScroll, BorderLayout.CENTER);

        final JLabel selectionLabel = new JLabel(
                "Drag a rectangle in the screen shot!");
        panel.add(selectionLabel, BorderLayout.SOUTH);

        repaint(screen, screenCopy);
        screenLabel.repaint();

        screenLabel.addMouseMotionListener(new MouseMotionAdapter() {

            Point start = new Point();

            @Override
            public void mouseMoved(MouseEvent me) {
                start = me.getPoint();
                repaint(screen, screenCopy);
                selectionLabel.setText("Start Point: " + start);
                screenLabel.repaint();
            }

            @Override
            public void mouseDragged(MouseEvent me) {
                Point end = me.getPoint();
                captureRect = new Rectangle(start,
                        new Dimension(end.x-start.x, end.y-start.y));
                repaint(screen, screenCopy);
                screenLabel.repaint();
                selectionLabel.setText("Rectangle: " + captureRect);
            }
        });

        JOptionPane.showMessageDialog(null, panel);

        System.out.println("Rectangle of interest: " + captureRect);
    }

    public void repaint(BufferedImage orig, BufferedImage copy) {
        Graphics2D g = copy.createGraphics();
        g.drawImage(orig,0,0, null);
        if (captureRect!=null) {
            g.setColor(Color.RED);
            g.draw(captureRect);
            g.setColor(new Color(255,255,255,150));
            g.fill(captureRect);
        }
        g.dispose();
    }

    public static void main(String[] args) throws Exception {
        Robot robot = new Robot();
        final Dimension screenSize = Toolkit.getDefaultToolkit().
                getScreenSize();
        final BufferedImage screen = robot.createScreenCapture(
                new Rectangle(screenSize));

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ScreenCaptureRectangle(screen);
            }
        });
    }
}

A: This is pretty simple to do:
http://www.javalobby.org/forums/thread.jspa?threadID=16400&tstart=0
http://www.javaworld.com/javaworld/jw-04-2006/jw-0424-funandgames.html


text:
Q: Get wordpress post in diffrent div but one by one I have 10 post in my wordpress blog and i want to something like that:
div class="something1"
post1
post5
post9
/div
div class="something2"
post2
post6
post10
/div
div class="something3"
post3
post7

post4
post8
/div
I have no idea, but i must need it, please help.

A: In your loop you need to increment your div with php. I haven't tested this, but this should work:

<?php
    $myCustomClass = 0;
    $args = array
    (
        'posts_per_page' => 4,
        'orderby'     => 'name',
        'order'       => 'DEC',
        'post_type'   => 'post',
        'post_status' => 'publish'
    );
    $loop = new WP_Query( $args );

    while ( $loop->have_posts() ) : $loop->the_post(); ?>
        <?php $myCustomClass++ ?>

            <div class="myCustomClass-<?php echo $myCustomClass;?>">

                    <a href="<?php the_permalink();?>">
                        <?php the_title(); ?>

                    <?php the_content(); ?>

<? endwhile; ?>


text:
Q: Js - regular matching Array and String First post, so be gentle, please ;D
code:
var matchString;
var searchString = '';
var lastKey;
function keyDown(e) {
  if (!e)
    e = window.e;
    for (var i=0; i<asciiNum.length;i++){
        if (e.keyCode == asciiNum[i]){
            console.log('asciiLet: '+asciiLet[i]);
            lastKey = asciiLet[i];
            searchString +=lastKey;
        }else if(e.keyCode == "27"){
            searchString="";
            console.log(searchsrtring)
        }
    }
}

function keyUp(e) {
    console.log('left: '+searchString)
    for (var i=0; i<champArray.length; i++){
    }

}

The Array:
var nameArray = ["aatrox","ahri","akali","alistar","amumu","anivia","annie","ashe", "blitzcrank",   "brand",    "caitlyn",  "cassiopeia",   "cho'gath", "corki",    "darius",   "diana",    "draven",   "dr. mundo",    "elise",    "evelynn",  "ezreal",   "fiddlesticks", "fiora",    "fizz", "galio",    "gangplank",    "garen",    "gragas",   "graves",   "hecarim",  "heimerdinger", "irelia",   "janna",    "jarvan iv",    "jax",  "jayce",    "karma",    "karthus",  "kassadin", "katarina", "kayle",    "kennen",   "kha'zix",  "kog'maw",  "leblanc",  "lee sin",  "leona",    "lissandra",    "lucian",   "lulu", "lux",  "malphite", "malzahar", "maokai",   "master yi",    "m.fortune",    "mordekaiser",  "morgana",  "nami", "nasus",    "nautilus", "nidalee",  "nocturne", "nunu", "olaf", "orianna",  "pantheon", "poppy",    "quinn",    "rammus",   "renekton", "rengar",   "riven",    "rumble",   "ryze", "sejuani",  "shaco",    "shen", "shyvana",  "singed",   "sion", "sivir",    "skarner",  "sona", "soraka",   "swain",    "syndra",   "talon",    "taric",    "teemo",    "thresh",   "tristana", "trundle",  "tryndamere",   "twitch",   "twisted fate", "udyr", "urgot",    "varus",    "vayne",    "veigar",   "vi",   "viktor",   "vladimir", "volibear", "warwick",  "wukong",   "xerath",   "xin zhao", "yorick",   "zac",  "zed",  "ziggs",    "zilean",   "zyra", "jinx"];
    var asciiNum = ['27','65','66','67','68','69','70','71','72','73','74','75','76','77','78','79','80','81','82','83','84','85','86','87','88','89','90']
    var asciiLet=  ['Esc','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']

so, what do i want to do:
I want to match the content of searchstring with the nameArray in fact of every pressed key.
In the end every element who is not beginning with f.e. "A" should fadeOut.
Hope you all can understand my broken english and will take pity on me (:

A: You could do this

*

*Add the keyDown callback to the input (I assume it is an HTMLInputElement)

*In the keyDown callback delay the call to searchNameFromInput function so that the value of the input has already change when you check it.

*Filter elements in nameArray by creating a regex that checks for matches of names with your input value from the beginning (for instance: "an" would match "anivia" and "annie")
The code looks like this
var nameArray = ["aatrox","ahri","akali","alistar","amumu","anivia","annie","ashe", "blitzcrank",   "brand",    "caitlyn",  "cassiopeia",   "cho'gath", "corki",    "darius",   "diana",    "draven",   "dr. mundo",    "elise",    "evelynn",  "ezreal",   "fiddlesticks", "fiora",    "fizz", "galio",    "gangplank",    "garen",    "gragas",   "graves",   "hecarim",  "heimerdinger", "irelia",   "janna",    "jarvan iv",    "jax",  "jayce",    "karma",    "karthus",  "kassadin", "katarina", "kayle",    "kennen",   "kha'zix",  "kog'maw",  "leblanc",  "lee sin",  "leona",    "lissandra",    "lucian",   "lulu", "lux",  "malphite", "malzahar", "maokai",   "master yi",    "m.fortune",    "mordekaiser",  "morgana",  "nami", "nasus",    "nautilus", "nidalee",  "nocturne", "nunu", "olaf", "orianna",  "pantheon", "poppy",    "quinn",    "rammus",   "renekton", "rengar",   "riven",    "rumble",   "ryze", "sejuani",  "shaco",    "shen", "shyvana",  "singed",   "sion", "sivir",    "skarner",  "sona", "soraka",   "swain",    "syndra",   "talon",    "taric",    "teemo",    "thresh",   "tristana", "trundle",  "tryndamere",   "twitch",   "twisted fate", "udyr", "urgot",    "varus",    "vayne",    "veigar",   "vi",   "viktor",   "vladimir", "volibear", "warwick",  "wukong",   "xerath",   "xin zhao", "yorick",   "zac",  "zed",  "ziggs",    "zilean",   "zyra", "jinx"],
input = document.getElementById('foo');

// I also assume IE9+ for addEventListener
input.addEventListener('keydown', function keyDown(e) {
    e = e || window.event;
    // just bind the input element as a parameter
    // for the function searchNameFromInput
    setTimeout(searchNameFromInput.bind(null, e.target||e.srcElement), 80);
}, false);

function searchNameFromInput(input) {
    if (input.value.length) {
         console.log(
            nameArray.filter(function (name) {
                return new RegExp('^' + input.value).test(name);
            })
        );
    }
}


text:
Q: state loading issue (javascript loads before templateUrl) I am using angularJS to load forms and having 2 issues

*

*JS files loads before templateUrl

*When I move to new View then JavaScript functions in old views are also accessible.

Please have a look at attached code:

.state('index.categdashboard', {
            url: "/categdashboard",
            templateUrl: "views/categdashboard.html",
            data: { pageTitle: 'Category wise Headcount - Dashboard' },
   controller: 'getCategoryWiseSummary',
   resolve: {
                loadPlugin: function ($ocLazyLoad) {
                    return $ocLazyLoad.load([
                        {
                            files: [
                                 // Row 1
                                 'js/categdashboard/categdashboard.js',
                                 ],
                            cache: false
                        }
                    ]);
                }
            }
        })

I have tried

$(document).ready(function () {

but it also did not worked

A: I declared a new controller in my new view and called the JavaScript functions from it.

angular
 .controller('MainDashboardCtrl', MainDashboardCtrl)

function MainDashboardCtrl(){
 // Called functions here
}
<div ng-controller="MainDashboardCtrl as MDCtrl">
</div>


text:
Q: scrolling only parts of the page while making them cover the entire screen
What is the best way of achieving this?

css:
.body .head{margin:0; height:100%}
.container{height:100%}
.topbar{width:100%; height:30px}
.leftbar {width: 50px; height: 100%; overflow: auto; float: left}
.content-wrap{height: 100%; overflow: auto; float: left}
.content-header{height:30px}
.content{height:100%; overflow:auto}
.content-footer{height:35px}

I Want to cover the entire page...and only want left bar and content to scroll when required else cover the remaining space. All other things are fixed

A: jsBin demo
Pure old-school CSS: (no CSS3)

*{margin:0;}
html, body{
  height:100%;
}
#top{
  position:fixed;
  width:100%;
  height:50px; /* See #wrapper bottom value */
  background:#ddd;
}
#wrapper{
  position:absolute;
  width:100%;
  bottom:0;
  top:50px; /* compensate #top height */
}
#left{
  position:absolute;
  background: #3BB3C3;
  height:100%;
  width:150px;   /* See #right left value */
  overflow:auto; /* make scrollable if content overflows */
}
#right{
  position:absolute;
  right:0;
  left:150px; /* compensate #left width */
  bottom:0;
  height:100%;
  background:#EE9B69;
}
#header{
  position:fixed;
  width:100%;   /* (100% cause of fixed pos) */
  height:30px;  /* see #page top value */
  background:#F8C301;
}
#page{
  position:absolute;
  top:30px;    /* header height */
  bottom:30px; /* bottom height */
  width:100%;
  overflow-y:scroll;
}
#footer{
  background:#B8DC7C;
  position:fixed;
  width:100%; /* (100% cause of fixed) */
  bottom:0;
  height:30px; /* see #page bottom value */
}

/* DEMO ONLY */
p.long{
  height:1500px;
  border-left:5px dotted #000;
}

TOP

    LEFT
Long content
--END!

HEADER

      ARTICLE CONTENT
Long content test
--END!

FOOTER

A:

* {
  margin: 0;
  padding: 0;
}
html,
body,
.container {
  height: 100%;
}
.topbar {
  background: grey;
  height: 40px;
}
.leftbar {
  background: blue;
  width: 30%;
  overflow-y: scroll;
}
.content-wrap {
  background: red;
  width: 70%;
}
.leftbar,
.content-wrap {
  height: calc(100% - 40px);
  float: left;
}
.content-hearer {
  height: 40px;
  background: yellow;
}
.content-footer {
  height: 40px;
  background: green;
}
.content {
  height: calc(100% - 80px);
  background: orange;
  overflow-y: scroll;
}

Fusce pharetra convallis urna. Etiam rhoncus. Phasellus volutpat, metus eget egestas mollis, lacus lacus blandit dui, id egestas quam mauris ut lacus. Quisque libero metus, condimentum nec, tempor a, commodo mollis, magna. Aenean leo ligula, porttitor
    eu, consequat vitae, eleifend ac, enim. Suspendisse nisl elit, rhoncus eget, elementum ac, condimentum eget, diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed aliquam, nisi quis porttitor congue, elit
    erat euismod orci, ac placerat dolor lectus quis orci. Fusce a quam. Praesent nonummy mi in odio. Fusce egestas elit eget lorem. Fusce ac felis sit amet ligula pharetra condimentum. Pellentesque dapibus hendrerit tortor. Suspendisse pulvinar, augue
    ac venenatis condimentum, sem libero volutpat nibh, nec pellentesque velit pede quis nunc. Praesent porttitor, nulla vitae posuere iaculis, arcu nisl dignissim dolor, a pretium mi sem ut ipsum. Fusce convallis metus id felis luctus adipiscing. Vivamus
    elementum semper nisi. Nullam vel sem. Nullam sagittis. Vivamus laoreet. Aliquam erat volutpat.

Fusce pharetra convallis urna. Etiam rhoncus. Phasellus volutpat, metus eget egestas mollis, lacus lacus blandit dui, id egestas quam mauris ut lacus. Quisque libero metus, condimentum nec, tempor a, commodo mollis, magna. Aenean leo ligula, porttitor
      eu, consequat vitae, eleifend ac, enim. Suspendisse nisl elit, rhoncus eget, elementum ac, condimentum eget, diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed aliquam, nisi quis porttitor congue, elit
      erat euismod orci, ac placerat dolor lectus quis orci. Fusce a quam. Praesent nonummy mi in odio. Fusce egestas elit eget lorem. Fusce ac felis sit amet ligula pharetra condimentum. Pellentesque dapibus hendrerit tortor. Suspendisse pulvinar, augue
      ac venenatis condimentum, sem libero volutpat nibh, nec pellentesque velit pede quis nunc. Praesent porttitor, nulla vitae posuere iaculis, arcu nisl dignissim dolor, a pretium mi sem ut ipsum. Fusce convallis metus id felis luctus adipiscing. Vivamus
      elementum semper nisi. Nullam vel sem. Nullam sagittis. Vivamus laoreet. Aliquam erat volutpat.


text:
Q: Is it possible to customize Google / Yahoo Map? I'm absolute newbie as for Google Map / Yahoo Map. I would like to know if it is technically possible to ask to show any city in any country DYNAMICALLY (I mean by passing parameters) and then to show some pictures OVER the map near the city ?
Thanks.

A: There's a multitude of ways you could accomplish this, some prettier than others.

*

*You could use GInfoWindow to display a popup window with pictures in it at any location.

*You could use one of the handy libraries offered here http://code.google.com/p/gmaps-utility-library-dev/ to assist you in displaying those images.

*What I would recommend, however, is using http://econym.org.uk/gmap/ewindows.htm to create a window that is similar to GInfoWindow but that is styled by you. Just style the window so that it appears to simply be an overlaid picture.

*You could choose to fool around with z-index's and manual positioning with a JavaScript library like jQuery.

Also, to answer the beginning of your question yes you can refocus the map anywhere using GMap's .setCenter() method. Documentation of setCenter(), GInfoWindow and much more available at http://code.google.com/apis/maps/documentation/reference.html

A: I just started learning this myself.
Here is a good link to get started:
http://code.google.com/apis/maps/

A: On your second question,

show some pictures OVER the map near
  the city?

I like @andykram's response above, but I've implemented this previously using the Panoramio layer available for the Maps API. It can get a bit crowded but its an interface people are used to and because it is so simple to include it in a map, it just be the solution for you this time.
Just add the following to your map initialisation function.
var myLayer = new GLayer("com.panoramio.all");
map.addOverlay(myLayer);

As far as dynamically showing any city in the world in a Google Map, the solution is easily implemented - you need to geocode the name of the city. This can be done by triggering a function on an event like onclick.
function showAddress(address) {
  if (geocoder) {
    geocoder.getLatLng(
      address,
      function(point) {
        if (point) {
          map.setCenter(point, 13);
          var marker = new GMarker(point);
          map.addOverlay(marker);
          marker.openInfoWindowHtml(address);
        }
      }
    );
  }
}

If you hit a hurdle, try this first - http://econym.org.uk/gmap/ - possibly the best resource for the GMaps API on the web.

A: GeoExt is a nice framework if you work with maps in general. You can access other kinds of maps too (OSM, GeoServer).


text:
Q: Issues while Installing Caret All,
When I try to install the library(caret), I get the following error
library(caret)
Loading required package: ggplot2
Error: package or namespace load failed for 'ggplot2' in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]):
 there is no package called 'pkgconfig'
Error: package 'ggplot2' could not be loaded

When ggplot2 is installed separately, it says the following but still not able to load ggplot2
package 'ggplot2' successfully unpacked and MD5 sums checked

The downloaded binary packages are in
        C:\Users\b_umair\AppData\Local\Temp\Rtmpym8OBL\downloaded_packages

I am using R version 4.0.2 and have tried majority of the options listed on the internet
Any suggestions on how to resolve this issue??


text:
Q: How can I examine the query string generated by Spring Data Cassandra Mapper If I annotate a class with annotations from com.datastax.driver.mapping.annotations, I can write a test along the lines of:
MappingManager manager = new MappingManager(session);
Mapper<MyAnnotatedClass> mapper = manager.mapper(MyAnnotatedClass.class);

MyAnnotatedClass entity = ...;

RegularStatement saveQuery = (RegularStatement) mapper.saveQuery(entity);

assertEquals("...", saveQuery.getQueryString());

However I have entity classes annotated with org.springframework.data.cassandra.mapping annotations. I've been unable to find an Spring equivalent to Mapper's saveQuery(), getQuery() and deleteQuery().
How can I write (ideally lightweight at runtime) tests regarding the CQL generated from Spring Data Cassandra-annotated entity classes?

A: With Spring Data for Apache Cassandra 1.5, you can write the following code to create Statements:
CassandraTemplate template = …

Person person = …

CqlIdentifier tableName = template.getTableName(Person.class);

Insert insert = CassandraTemplate.createInsertQuery(tableName.toCql(), person,
                    new WriteOptions(), template.getConverter());

Delete delete = CassandraTemplate.createDeleteQuery(tableName.toCql(), person,
                    new WriteOptions(), template.getConverter());

Update update = CassandraTemplate.createUpdateQuery(tableName.toCql(), person,
                    new WriteOptions(), template.getConverter());

Note: Spring Data for Apache Cassandra 1.5 uses BATCH statements for inserts, that's going to change with the release 2.0.
CassandraTemplate and CassandraConverter are the key classes involved in query creation for version 1.5. In Spring Data 2.0, things are going to change a bit as 2.0 is going to ship with additional Query and Update types for partial entity updates. So query creation moves from CassandraTemplate.create…Query(…)to QueryUtils.create…Query(…).


text:
Q: Order of Execution during Sync Quote I am trying to find what happens when Sync Quote is clicked on the Quote. What is the order of execution (Opportunity updated prior to OpportunityLineItem or vice-versa)? The execution flow is important because one of our logic works fine if sync is on and Quote is edited but doesn't work when Sync Quote is turned on after quote is edited.
I tried going through the debug logs and didn't find any OpportunityLineItem triggers fired.

A: I have tried with an example that I have created a Quote and Quote comes with QuoteLineItem as same as OpportunityLineItem. I Press the (StartSync) button on Quote and checked the debug I found that trigger sequence below :

*

*Before/ After Update On Opportunity

*Before/ After Update On Quote

Also tried with Created a Quote and changed the Quantity of QuoteLineItem then Press the (StartSync) Button, Sequence was :

*

*Before/ After Update On Opportunity

*Before/ After Update On Quote

*Before/ After Update OpportunityLineItem

*Before/ After Update on Opportunity


text:
Q: How to change width ImageView to correct ratio? I have this XML file with a RelativeLayout. In this RelativeLayout I have got an ImageView and a LinearLayout with a lot of Views (not displayed in the code).
   <RelativeLayout
        android:layout_weight="1"

        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"

            android:id="@+id/imageViewDemo"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"

            android:layout_alignTop="@+id/imageViewDemo"
            android:layout_alignLeft="@+id/imageViewDemo"
            android:layout_alignRight="@+id/imageViewDemo"
            android:layout_alignBottom="@+id/imageViewDemo"
            android:gravity="center"

            android:orientation="vertical">

            <!-- A lot of stuff -->

        </LinearLayout>
   </RelativeLayout>

I want the ImageView have the same width/height ratio as the ratio of the phone/tablet screen size. The height should just match the parent view, but the width must be changed to match the correct ratio. The LinearLayout must be inside the ImageView. I can simply not find a working solution.

A:
I want the ImageView have the same width/height ratio as the ratio of the phone/tablet screen size.

First you should get the phone/tablet screen size in order to compute the width/height ratio.
This code get the ratio:
DisplayMetrics metrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
int width = metrics.widthPixels;
int height = metrics.heightPixels;
final float screenRatio = ((float)width/(float)height);

The height should just match the parent view, but the width must be changed to match the correct ratio.

For this purpose, you should change the ImageView's width in code, the height should be specified match_parent in your layout.
This code can help you change the width :
imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        imageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);

        int height = imageView.getHeight();
        int resultWidth = (int)(height * screenRatio);

        ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
        layoutParams.width = resultWidth;
        imageView.setLayoutParams(layoutParams);
    }
});

Hope this can help you.


text:
Q: new jQuery selectors I recently wrote the following selector with a little help from (possbily you) StackOverflow
$(':submit[name="Delete"][value="Delete"]').click(function() {
return window.confirm(this.title || 'Delete this record?');
});

Q: Now that 1.4 has been released, is there a more elegant way to write the selector?

A: jQuery 1.4 has no new selectors that will change that expression.
I would highly suggest you give the element(s) in question an ID (if there is one) or a class (if there are several) instead as they're much faster than attribute selectors.

A: No, there are no new selectors, but if you find yourself doing something similar a lot you can create your own selector. Here is one with somewhat limited use:
$.expr[':'].delete_button = function(el) {
    return $(el).is(':submit') && el.name === 'Delete' && el.value === 'Delete';
};

You could then change your line to read:
$('input:delete_button').click(function() {
    return window.confirm(this.title || 'Delete this record?');
});

Here is a more functional one, that matches the string arbitrarily:
$.expr[':'].btn = function(el, i, parts) {
    return $(el).is(':submit') && el.name === parts[3] && el.value === parts[3];
};

It would be called like this:
$('input:btn(Delete)').click(function() {
    return window.confirm(this.title || 'Delete this record?');
});

But would also work if you used the same naming structure for other buttons:
$('input:btn(Save)').click(function() {
    return window.confirm(this.title || 'Save this record?');
});


text:
Q: Android Data Validation I am wondering what is the most effective form of data validation for android. So, when getting a value from an EditText how should the value given be validated before it is used? I currently check to make sure the string returned from getText().toString() is not null or empty using the guava library:
Strings.isNullOrEmpty(editText.getText().toString())
Then, depending on what type of data I am expecting, I create a method to see if the data can be parsed. So if I am expecting a double I will create a method like this:
private boolean isDouble(String string) {
    try {
        double stringDouble = Double.parseDouble(string);
        return true;
    } catch (Exception e)
    {
        return false;
    }
}

Is there a simpler way to do this without the need to create a separate method for each type of data I am expecting to receive?

A: I've used the edittext-validator the last time I needed a quick validation. Works like charm :)
https://github.com/vekexasia/android-edittext-validator

A: If you are using EditText you should know what purposes it serves. Usually you are expecting to have just a plain string to, for example, send it to server or store in SharedPreferences.
But, if you want a particular data to be filled in, you can use Pattern class for validation. In case of number values you are using android:inputType="number" and when converting it using Integer.valueOf(text)


text:
Q: Cronjobs made via cronjob not working I have the following in my cronjob -e:
00 17 * * 1-5 /home/jhvisser/bin/drive-at-five-record
00 18 * * 1-5 pkill rtmpdump
50 15 * * 1-5 /home/jhvisser/bin/z1035-no-commercial
55 16 * * 1-5 pkill rtmpdump

Looking at the cron log it seems like the scripts should have been run, however no files were created like the jobs would have done.
Log:
Sep 26 07:39:01 jhvisser CRON[27399]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
Sep 26 07:44:01 jhvisser CRON[27459]: (root) CMD (cd / && run-parts --report /etc/cron.hourly)
Sep 26 08:09:01 jhvisser CRON[27639]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
Sep 26 08:39:01 jhvisser CRON[28010]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
Sep 26 08:44:01 jhvisser CRON[28100]: (root) CMD (cd / && run-parts --report /etc/cron.hourly)
Sep 26 09:09:01 jhvisser CRON[28498]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
Sep 26 09:39:01 jhvisser CRON[28732]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
Sep 26 09:44:01 jhvisser CRON[28802]: (root) CMD (cd / && run-parts --report /etc/cron.hourly)
Sep 26 10:09:01 jhvisser CRON[29066]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
Sep 26 10:39:01 jhvisser CRON[29300]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
Sep 26 10:44:01 jhvisser CRON[29355]: (root) CMD (cd / && run-parts --report /etc/cron.hourly)
Sep 26 11:09:01 jhvisser CRON[29537]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
Sep 26 11:39:01 jhvisser CRON[29767]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
Sep 26 11:44:01 jhvisser CRON[29826]: (root) CMD (cd / && run-parts --report /etc/cron.hourly)
Sep 26 12:09:01 jhvisser CRON[30004]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
Sep 26 12:39:01 jhvisser CRON[30230]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
Sep 26 12:44:01 jhvisser CRON[30288]: (root) CMD (cd / && run-parts --report /etc/cron.hourly)
Sep 26 13:09:01 jhvisser CRON[30495]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
Sep 26 13:39:01 jhvisser CRON[30747]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
Sep 26 13:44:01 jhvisser CRON[30806]: (root) CMD (cd / && run-parts --report /etc/cron.hourly)
Sep 26 14:09:01 jhvisser CRON[30987]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
Sep 26 14:39:01 jhvisser CRON[31239]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
Sep 26 14:44:01 jhvisser CRON[31300]: (root) CMD (cd / && run-parts --report /etc/cron.hourly)
Sep 26 15:09:01 jhvisser CRON[31678]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
Sep 26 15:39:01 jhvisser CRON[31938]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
Sep 26 15:44:01 jhvisser CRON[31996]: (root) CMD (cd / && run-parts --report /etc/cron.hourly)
Sep 26 15:50:01 jhvisser CRON[32027]: (jhvisser) CMD (/home/jhvisser/bin/z1035-no-commercial)
Sep 26 16:09:01 jhvisser CRON[32179]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
Sep 26 16:39:01 jhvisser CRON[32413]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
Sep 26 16:44:01 jhvisser CRON[32447]: (root) CMD (cd / && run-parts --report /etc/cron.hourly)
Sep 26 16:59:01 jhvisser CRON[32571]: (jhvisser) CMD (pkill rtmpdump)
Sep 26 17:00:01 jhvisser CRON[32578]: (jhvisser) CMD (/home/jhvisser/bin/drive-at-five-record)
Sep 26 17:09:01 jhvisser CRON[32652]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
Sep 26 17:39:01 jhvisser CRON[720]: (root) CMD (  [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir fuser -s {} 2>/dev/null \; -delete)
Sep 26 17:44:01 jhvisser CRON[756]: (root) CMD (cd / && run-parts --report /etc/cron.hourly)
Sep 26 18:00:01 jhvisser CRON[910]: (jhvisser) CMD (pkill rtmpdump)

A: According to the logs, cron functioned correctly.  If your scripts should be creating files, please verify that your files are executable
ls -l /home/jhvisser/bin

If they are executable, verify that each script begins with
#!/bin/bash


text:
Q: RegEx to remove all \begin{gather}... \end{gather} I have a 6,200 hundred pages book with simple stuff like:
\begin{gather}
    A>B,A=B,A<B,A\leq B,A \geq B
\end{gather}

or a bit more complicates:
\begin{gather}
    \begin{aligned}
    (a+b)^0&=1\\
    (a+b)^1&=1a+1b\\
    (a+b)^2&=1a^2+2ab+1b^2\\
    (a+b)^3&=1a^3+3a^2b+3ab^2+1b^3\\
    \end{aligned}
\end{gather}

I'm trying to found the RegEx to remove all \begin{gather} \end{gather} environment (it's LaTeX). The best i have found by trial and error is:
(\\begin\{gather\}*\r?\n?.*)*\r?\n?.*(\r?\n?.*\\end\{gather\})

But it doesn't work :-(((
Any help would be appreciate.
Thx in advance

A: This works in Notepad++:
(?s)\\begin\{gather\}.*?\\end\{gather\}

Make sure you set the option (. matches newline)
Here is an example in Regex101 that uses the ungreedy option ".*?" and the "(?s)" s modifier: single line. Dot matches newline characters.
example


text:
Q: $f: \mathbb R^2 \to \mathbb R$ be $f(x,y) = x^{[y]}$. How can we define this function at $(0,0)$? For any $y \in \mathbb R$, let $[y]$ denotes the greatest integer less than or equal to $y$. Define $f: \mathbb R^2 \to \mathbb R$ be $f(x,y) = x^{[y]}$.
Then there are four options from which any number of option can be correct.
But my question is how can we define this function at $(0,0)$?
Can anyone give any suggestion?
Edit:**  I know the function is not defined on whole $R^2$ . But This question was asked in a National Level Exam in India. That's why I had doubt in myself.**

A: the problem should have included a value for $f(0,0)$. If $|y|<1$, then
$$
[y]=\begin{cases}\phantom{-}0 & \text{if }y\ge0,\\-1 &\text{if }y<0.\end{cases}
$$
Then, if $x\ne0$,
$$
x^{[y]}=\begin{cases}1 & \text{if }y\ge0,\\\dfrac{1}{x} &\text{if }y<0.\end{cases}
$$
$f$ cannot be defined at $(0,0)$ to make it continuous. However, answer 2 is correct.


text:
Q: Insert spaces in specific field How can I insert space between strings in field 3 only in a file.
I can use command  sed "s// /g" but this will do globally in a file. How can I do only for column 3.
Say input is as
A  seq      A1A2
B  comb   A1A2A3

I want output as
A  seq      A1 A2
B  comb   A1 A2 A3

A: With your shown samples, please try following. Written and tested with GNU awk.
awk '{gsub(/../,"& ",$3);sub(/ +$/,"",$3)} 1' Input_file

A: Assuming you want to insert a whitespace in the "gap" between digit and alphabet in the 3rd column, with GNU awk:
awk '{$3 = gensub("([[:digit:]])([[:alpha:]])", "\\1 \\2", "g", $3)} 1' file

A: If you know you have only three fields on all lines
awk '{printf($1 " " $2 " ");  n=split($3,a,""); for(i=1; i <= n; i++) printf(a[i] " "); printf("\n")}' file

if you have more than 3 fields and want to print remaining fields after splitting 3rd field, along with first 2 fields:
awk '{printf($1 " " $2 " ");  n=split($3,a,"");for(i=1; i <= n; i++) printf(a[i] " "); $1="";$2="";$3="";print($0); printf("\n")}' file


text:
Q: pandas merge dataframes on certain columns but exclude them in the result dataframe In pandas, I have to include certain columns that I want to merge two dataframes on,
result = df_a.merge(df_b[['A', 'B', 'C']], how='left', on=['A', 'B'])

so if I want to merge df_a and df_b on columns A and B, I have to also include A and B in the result dataframe, but what I really want is only column C. I am wondering if there a way to only include C in merge.
A sample result dataframe after merge,
year_x    code_x    year_y    code_y    id
2000      005       2000.00   005       1
2001      006       2001.00   006       2
2002      007       2002.00   007       3

df_a and df_b all contain year and code, I only need id from df_b, but I have to merge on code and year.
originally year is of int64 dtype in both df_a and df_b, but after the merge year_y turned into float, which is also confusing.
If I drop code_y and year_y after the merge, I may have to rename code_x and year_x back to code and year, which is not convenient if I can eliminate the duplicate columns in the first place.

A: If you only need the one column in the result frame:
result = df_a.merge(df_b[['A', 'B', 'C']], how='left', on=['A', 'B'])['C']

As for your changing dtypes, it looks, at least in the sample data you provided, that your year_x and year_y are different types, one being int and one being float, which means the resulting column will be float.


text:
Q: Change background color of bootstrap dropdown link when clicked The bootstrap dropdown button has a default color that blinks up when the button is clicked.
HTML

  <button type="button" class="btn btn-danger">Action</button>
  <button type="button" class="btn btn-danger dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Toggle Dropdown
  </button>

    Action
    Another action
    Something else here

    Separated link

I have tried using .dropdown-item:active in css but it's not changing. How to do please. Thank you.

A: Try this code in your css!
.dropdown-item:active {
background-color: red !important; //Any color you want
}

In CSS, the !important means that "this is important", ignore all the subsequent rules, and apply !important rule and the !important keyword must be placed at the end of the line, immediately before the semicolon

.dropdown-item:active {
background-color: red !important; //Any color you want
}
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <title>Hello, world!</title>

  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown button
  </button>

    Action
    Another action
    Something else here


text:
Q: Does using ASCII/Latin Charset speed up the database? It would seem that using the ASCII charset for most fields and then specify utf8  only for the fields that need it would reduce the amount of I/O the database must perform by 100%.
Anyone know if this is true?
Update: The above was not really my question.  I should have said: use Latin for the default character set and then only specify utf8mb4 only for the fields that need it.  The thinking being that: using 1 byte vs 2 bytes should improve I/O by 100%.  Sorry for the confusion.

A: @RickJames is right, you should not worry about saving space by choosing ASCII or utf8 over utf8mb4.
utf8 and utf8mb4 are variable-length character encodings. This table from wikipedia illustrates how characters automatically take 1, 2, 3, or 4 bytes each, depending on the value encoded. If the high bit of a byte is set, then the character uses an additional byte, up to 4 bytes.

The wikipedia article explains it clearly:

The first 128 characters (US-ASCII) need one byte. The next 1,920 characters need two bytes to encode, which covers the remainder of almost all Latin-script alphabets, and also Greek, Cyrillic, Coptic, Armenian, Hebrew, Arabic, Syriac, Thaana and N'Ko alphabets, as well as Combining Diacritical Marks. Three bytes are needed for characters in the rest of the Basic Multilingual Plane, which contains virtually all characters in common use including most Chinese, Japanese and Korean characters. Four bytes are needed for characters in the other planes of Unicode, which include less common CJK characters, various historic scripts, mathematical symbols, and emoji (pictographic symbols).

You don't have to do anything to choose single-byte versus multi-byte mode. This is just the way the encoding works. Each character automatically uses the number of bytes it needs, and no more.
So there is no advantage to using utf8 over utf8mb4, and no advantage of using ASCII over either, unless you need to restrict the characters allowed in a string.
For what it's worth, the character set MySQL calls "utf8" is an alias for utf8mb3, an implementation of just the first three bytes of the UTF8 encoding. The MySQL server team blog (https://mysqlserverteam.com/mysql-8-0-when-to-use-utf8mb3-over-utf8mb4/) says that utf8mb4 is faster, at least given performance improvements in MySQL 8.0, and utf8mb3 should be considered deprecated. MySQL 8.0.11 release notes say that utf8 will be redefined as an alias for utf8mb4 in some future version of MySQL.

A: Short Answer: Not worth worrying about.
Long Answer:
Two issues:

*

*Speed:

Comparing two encodings with the corresponding _bin (ascii_bin or utf8_bin) COLLATION is as simple as comparing the bytes -- so no significant difference.  Other collations can differ, with ascii being faster.  But the difference is insignificant compared to the effort of fetching rows, etc.

*

*Space:

Ascii is a subset of utf8.  utf8 stores only 1 byte for each ascii character, just as ascii does.  So, no space difference.  (Accented letters in Western Europe need either 1-byte latin1 or 2-byte utf8; hence incompatible and different in size.)  Space leads to caching, which leads to a slight difference in performance.
For English text, 0% savings.  For European, latin1 would save only a few percent; For most the rest of the world, utf8 are the only viable solution.  For Chinese and Emoji, utf8mb4 is a must.

*

*Temp tables

In certain situations, the space consumed by a string expands to the potential max.  country_code CHAR(2) CHARACTER SET ... will take 2 bytes for ascii; 6 bytes for utf8.
Bottom Line:
Use ascii for country codes, hex, postal codes, uuids, md5s etc.  If you are going international, and/or need Emoji, then make your "strings" utf8mb4.  But do it because it is 'right', not because you will get magically marvelously much more speed; you won't.  And do it whenever you create a table; it's the pits to change it later.


text:
Q: query = query % db.literal(args) TypeError: not all arguments converted during string formatting I have a problem with MySQLdb that none of the previous questions have been able to help me with. I have a list called alltitles in python, I want to insert it into a table in MySQL. I have the following code in python:
for s in range(0,len(alltitles)):
    print alltitles[s]
    query = "INSERT INTO table (colname) VALUES ("+alltitles[s]+")"
    x=conn.cursor()
    x.execute(query, alltitles[s])
    row = x.fetchall()

It returns this error:
Traceback (most recent call last):
  File "<pyshell#180>", line 5, in <module>
    x.execute(query, alltitles[s])
  File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 159, in execute
    query = query % db.literal(args)
TypeError: not all arguments converted during string formatting

Would appreciate any suggestions, thank you.

A: You're putting the values both as literals in the string, and as the parameters to the query. You should only do it in one place, and that should be as the parameter.
(Also note in Python you should never iterate through a range with an index; iterate through the thing itself.)
x = conn.cursor()
for title in alltitles:
    print title
    query = "INSERT INTO table (colname) VALUES (%s)"
    x.execute(query, title)
    row = x.fetchall()

A: Also, try to use:
for title_index,title in enumerate(alltitles):
    print title_index, title
    ...

(alltitles[title_index] will also give you title)


text:
Q: VB 2D Array possibly not returning correct value/Need help counting number of booleans in a 2d array I am trying to write Conways game of life in visual basic but there seems to be a problem with the code that counts the number of living surrounding cells. The code is shown below:
Module Module1

Dim ScreenHeight As Integer = 30
Dim ScreenWidth As Integer = 30
Dim Field(ScreenWidth - 1, ScreenHeight - 1) As Boolean
Dim FieldBuffer(ScreenWidth - 1, ScreenHeight - 1) As Boolean

Sub Main()
    Console.SetWindowSize(ScreenWidth, ScreenHeight)
    Field(10, 9) = True
    Field(10, 10) = True
    Field(10, 11) = True

    While True

        Dim x = 0
        While (x < ScreenWidth)
            Dim y = 0
            While (y < ScreenHeight)
                Console.SetCursorPosition(x, y)

                If ((x <> 0 And x <> ScreenWidth - 1) And (y <> 0 And y <> ScreenWidth - 1)) Then

                    Dim count = Field(x + 1, y) + Field(x - 1, y) + Field(x, y + 1) + Field(x, y - 1) _
                        + Field(x + 1, y + 1) + Field(x - 1, y - 1) + Field(x - 1, y + 1) + Field(x + 1, y - 1)

                    count = count * -1
                    If (Field(x, y) = True) Then

                        If (count < 2) Then
                            FieldBuffer(x, y) = False
                        End If
                        If (count > 3) Then
                            FieldBuffer(x, y) = False
                        End If
                        If (count = 3 Or count = 2) Then
                            FieldBuffer(x, y) = True
                        End If

                        Console.BackgroundColor = ConsoleColor.Blue
                    Else

                        If (count = 3) Then
                            FieldBuffer(x, y) = True
                        End If

                        Console.BackgroundColor = ConsoleColor.Black
                    End If

                    Console.Write(count)
                Else
                    Console.BackgroundColor = ConsoleColor.Red
                    Console.Write("X")
                End If

                y += 1
            End While
            x += 1
        End While

        Console.ReadKey()
        Field = FieldBuffer
    End While

End Sub

End Module

The code that gets the values of the surrounding cells is:
Dim count = Field(x + 1, y) + Field(x - 1, y) + Field(x, y + 1) + Field(x, y - 1) _
+ Field(x + 1, y + 1) + Field(x - 1, y - 1) + Field(x - 1, y + 1) + Field(x + 1, y - 1)
count = count * -1

For the first iteration of the program, it returns the right values for the cell structure in the Field array.
But on the second iteration, after applying the rules, it doesn't return the correct values, which should be:
12321
11211
12321
The rules are being applied to the array correctly because after the first iteration the structure that is being displayed is correct. This bug has also appeared when having an 'If(Field(x,y) = true) then Count+=1' for every position surrounding the cell.
Any help would be appreciated as this bug has been driving me crazy for about 2 weeks now.

A: Your rules are wrong.
' Any live cell with two or three neighbours lives
' Any dead cell with exactly three live
If count = 3 Then ' If (count = 3 Or count = 2) Then
    FieldBuffer(x, y) = True
End If

You are also copying the reference. This mean, on the second pass, Field and FieldBuffer are the same.
Field = FieldBuffer

You need to copy each item. Use a loop, something like Array.Copy or other methods.


text:
Q: Access VBA - Assigning a value to duplicate records? I have a table with products taken from an Excel spreadsheet and some have duplicate values in the 'Product ID' field. Where this happens I want to assign a value to differentiate between them in the 'Run No' field. So for example it would look like this...
Product ID|Run No|ProcessNo |Product Description
34        |  1   |71808013  |Product 1
34        |  2   |71807961  |Product 1
42        |  1   |71808011  |Product 2
42        |  2   |71807962  |Product 2
43        |  1   |71808012  |Product 3
41        |  1   |71807959  |Product 4
52        |  1   |71808010  |Product 5
52        |  2   |71807960  |Product 5

The products that will appear in this table will change every day and could have more than 2 runs. I've tried looking around for solutions but the closest thing was for Excel (http://www.ozgrid.com/forum/showthread.php?t=46060) and I don't really understand how I could implement that in Access. So far I've only managed to find the duplicates using a query but I'm a little lost after that.
Any help is appreciated! Thanks!

A: You can assign the run number with something like:
select t.*,
       (select count(*)
        from mytable as t2
        where t2.productid = t.productid and
              t2.processno <= t.processno
       ) as runno
from mytable as t;

This assumes that processno is distinct for any given product, which is the case for your sample data.


text:
Q: Eclipse PlugIn Project get existing Projects of the workspace I am totally confused with the plugin procedures.
To be more precise: I am struggling to access the classes/projects of my workspace. I wrote an Eclipse PlugIn Project that is supposed to access my workspace and to parse one of the projects. I actually took the code from here [Link]http://www.vogella.com/tutorials/EclipseJDT/article.html#using-the-ast!
My problem is that do not receive my projects on my workspace. With this code only the RemoteSystemsTempFiles are returned:
     public class SampleHandler  {

public Object execute(ExecutionEvent event) throws ExecutionException {
    // Get the root of the workspace
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IWorkspaceRoot root = workspace.getRoot();
    // Get all projects in the workspace
    IProject[] projects = root.getProjects();
    // Loop over all projects
    for (IProject project : projects) {
        System.out.println(project.getName());
    }
    return null;
}

Do I access the right workspace? I want to access the workspace of my plugIn project (c:/workspace) and not the workspace of the eclipse instance that is opening when I run the project.
I also tried
     IPath path = ResourcesPlugin.getWorkspace().getRoot().getLocation();

This returns C:/runtime-EclipseApplication
And
    File file = new File("C://workspace");
    URI location = file.toURI();
    IFile[] files=ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(location);

The files Array's length is 0.
How can I get all of my projects?


text:
Q: SAPUI5 VizFrame false data is picked I have a sapui5 project with a graph made by vizframe. The graph has two dimensions (Date and Condition) and one measure
(Rest Value). The Rest Value is taken from invoices. But on one Date there can be multiple invoices of course. When this happens the vizframe graph automatically picks the first value he can find for this date, I think. Example: Date is 01.01.2023, there are four invoices for this date with the Rest Values: 1, 2, 3, 4. Because my model I get from the backend via Odata is ordered descending for Rest Value, the first value for this date is 4. Problem is I really have to display the lowest value for every date so i want the 1 not the 4. I hope my problem is understandable.
My graph is of vizType "timeseries_line". The Date is of course on the uid timeAxis, Dimension is uid color, and Rest Value on valueAxis. The sapui5 version im using is 1.108.0. The Vizframe is created in a xml view but the data binding is done in the controller with a FlattenedDataset and feeds.
I have been reading the sapui5 API Reference and asking ChatGPT questions but didnt get any smarter.
I hope someone can help me, thanks very much.
I did a lot of research but I could not find anything similar.


text:
Q: How to compare two NSArrays of NSStrings, ignoing case and order I have two NSArrays, each containing NSStrings.
How do I check they are equivalent, ignoring case and order?
I've been playing around with NSSets and NSPredicates, but not having much luck.

A: Simple (case insensitive)
NSSet* one = [[NSCountedSet setWithArray:firstArray] valueForKey:@"lowercaseString"];
NSSet* two = [[NSCountedSet setWithArray:secondArray] valueForKey:@"lowercaseString"];

return [one isEqualToSet:two];

Complex (case and diacritic insensitive)
This solution is more complex, because it requires a special string comparison. You can either accomplish this by iterating sorted arrays using this method, or, if you wish to use valueForKey:, using the following code.
@interface LNComparisonHelper : NSObject

- (instancetype)initWithString:(NSString*)str;
@property (nonatomic, copy, readonly) string;

@end

@implementation LNComparisonHelper

- (instancetype)initWithString:(NSString*)str
{
    self = [super init];
    if(self) { _str = [str copy]; }
    return self;
}

- (BOOL)isEqual:(LNComparisonHelper*)other
{
    return [_str compare:other.string options:(DiacriticInsensitiveSearch | CaseInsensitiveSearch)] == OrderedSame;
}

@end

@interface NSString (ComparisonWrapper)

- (id) ln_casediacriticInsensitiveComparator;

@end

@implementation NSString (ComparisonWrapper)

- (id) ln_casediacriticInsensitiveComparator
{
    return [[LNComparisonHelper alloc] initWithString:self];
}

@end

NSSet* one = [[NSCountedSet setWithArray:firstArray] valueForKey:@"ln_casediacriticInsensitiveComparator"];
NSSet* two = [[NSCountedSet setWithArray:secondArray] valueForKey:@"ln_casediacriticInsensitiveComparator"];

return [one isEqualToSet:two];

A: *

*Compare array counts

*Copy into new NSMutableArrays

*Sort the arrays (sortUsingComparator: with NSCaseInsensitiveSearch and DiacriticInsensitiveSearch)

*By pairs in order compare strings (NSCaseInsensitiveSearch and DiacriticInsensitiveSearch)

As soon as there is a failure return NO
If no failure YES
Note: For reasonably sized arrays sorting has a low cost close to O(n).


text:
Q: Embed Plotly in html with responsive behavior: can I change legend position based on screen width? I am using Plotly to embed a plot on an HTML page. My website is responsive, but I am not satisfied with the legend of the plot that I have embedded. Here you can see two screenshots: on the left, we see the plot on a widescreen, and on the right with a narrow one.
 vs

As shown in the figure, the plot looks good on the widescreen (left). However, when the screen is narrow (right), the legend takes too much space and the plot is shrunk.
Moving the legend below when the screen is small would solve the issue (as depicted with the red drawing). Is it possible to embed such a responsive behavior in Plotly when adding the legend?
Thanks in advance! :)


text:
Q: Why does this program compile? public class Fir extends Test
{
    public static void main(String args[])
    {
        Fir fir = new Fir();
        System.out.println(fir);
    }

    public String toString(String x) throws RuntimeException
    {
        return "Fir";
    }
}

class Test
{
    protected String toString(String x) throws NullPointerException
    {
        return "Test";
    }
}

Both classes do not override the toString method appropriately.
Question: Are these methods overriden?
If yes, what about this rule: If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception. RuntimeException is parent of NullPointerException.

A: The rule you gave is correct, but it applies to checked exceptions, not to runtime exceptions. Any method is allowed to throw any runtime exception it wants, without declaring it. You may declare them, but it's purely for documentation purpose.
To answer your question, yes, the toString(String) method in Fir overrides the toString(String) method in Test. Add the @Override annotation to Fir.toString(), and the compiler will check that for you: you'll get a compilation error if Fir.toString(String) doesn't override any method.

A:
Question: Are these methods overriden?

No. these methods are overloaded
the original method looks like this:
public String toString()


text:
Q: Issue returning multiple values with a tuple for a function Hi I was just having a few issues with a function I made to return multiple values after looking around for ways to return two values from a function, however I still seem to be getting errors from this function.
I was using this website as a reference: https://en.cppreference.com/w/cpp/utility/tuple
and am running the default (latest version of c++17).
#include <tuple>
std::tuple<int, int> returnCoordinates()
{
  int xCoordinate = -2;
  int yCoordinate = 2;
  return {xCoordinate, yCoordinate}; //can only do in c++ 17
}

int main()
{
  int xCoordinate;
  int yCoordinate;
  auto[xCoordinate, yCoordinate] = returnCoordinates(); //only works c++17
  return 0;
}

The error I'm getting is "expression must have a constant value the value of xCoordinate cannot be declared as a constant" and I'm not exactly sure why. Edit: As suggested by a commenter I removed the declaration of xCoordinate and yCoordinate, but it now seems to be saying that xCoordinate and yCoordinate are undefined.
However, if I switch out this line of code:
auto[xCoordinate, yCoordinate] = returnCoordinates(); //only works c++17

with this:
std::tie(xCoordinate, yCoordinate) = returnCoordinates();

it seems to work, I'm just confused about why this is, apologies for any misunderstanding on my part.

A: Thanks to the commenters M.M and NathanOliver, I managed to figure out what was wrong.
First of all, I removed my initial declaration of:
int xCoordinate;
int yCoordinate;

as:
 auto[xCoordinate, yCoordinate] = returnCoordinates(); //only works c++17

declares new variables.
Also, I wasn't using the latest c++ compiler. To change that go to project-> properties -> C/C++ -> Language -> C++ Language Standard -> Preview - Features from the Latest C++ Working Draft(/std::c++latest)
The default setting for this means that an error will pop up for the following code:
However, otherwise this code now works:
#include <tuple>
std::tuple<int, int> returnCoordinates()
{
  int xCoordinate = -2;
  int yCoordinate = 2;
  return {xCoordinate, yCoordinate}; //can only do in c++ 17
}

int main()
{
  auto[xCoordinate, yCoordinate] = returnCoordinates(); //only works c++17
  return 0;
}


text:
Q: How to fix "Failed to load class org.slf4j.impl.StaticLoggerBinder" error on Maven? I  was trying to deploy a web app but I can't deploy my web app, I am working with:
Intellij IDEA 14.1.4
OS X YOSEMITE 10.10.4
Maven 3.2.5
Tomcat 7.0.63
In my pom.xml file. I wrote this:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>simple</groupId>
    <artifactId>simple</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.12</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.12</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <url>http://127.0.0.1:8080/manager/text/</url>
                    <server>TomcatServer</server>
                    <username>tomcatg</username>
                    <password>sg</password>
                    <path>/firstwebapp</path>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

I select tomcat7:deploy and press Run Maven Build button and the result is:
[INFO] Deploying war to http://127.0.0.1:8080/firstwebapp
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details

I reviewed the web page www.slf4j.org but I don't know how to place slf4-simple.jar on the classpath and I reviewed some solutions here but I can't fix this issue.
Can anyone help me?


text:
Q: useRef is null when it's rendered without browser refresh So unfortunately i have problem with my component. So let's explain a little more.
I have div container with some content in there.
This container has height: 100% and overflow-auto style.
When the user go to the the corresponding component, it will scroll automatically to the bottom of the container.
So what's the problem then?
So the problem is when user goes to that component via <Link> or <Redirect> useRef is returning null.
I tried with useEffect with ref.current dep but still work only on page refresh and not work with Link and etc.
Stop talking, here's some of my code:
import React, {useState, useEffect, useRef} from "react";
import {useTranslation} from "react-multi-lang";
import UserLayout from "../../containers/UserLayout";
import HomeLayout from "../../containers/HomeLayout";
import {useParams} from "react-router";
import {connect} from "react-redux";

const TicketAnswers = props => {
    const t = useTranslation();
    const [reply, setReply] = useState("");
    const [ticket, setTicket] = useState([]);

    const user = props.user.data
    const {id} = useParams();
    const messageDivBox = useRef(null);

    useEffect(() => {
        if (!props.userAltData.loading) {
            setTicket(props.userAltData.data.tickets.filter(t => t.id === parseInt(id))[0])
        }

        // Scroll into the last reply
        if (messageDivBox.current !== null) {
            messageDivBox.current.scrollTop = messageDivBox.current.scrollHeight;
        }
    }, [props.userAltData.loading, messageDivBox.current]);

    const _handleSubmit = e => {
        e.preventDefault();
    }

    return (
        <HomeLayout>

            <UserLayout>

                            {t('user.ticket-answers')}: {ticket.name}

                        {/*HERE IS MY DIV WITH ref*/}

                            {(ticket.answers === undefined || ticket.answers.length === 0) ? (t("user.no-ticket-replies")) : ticket.answers.map((ans, key) => (

                                                    {ans.content}

                                                <img className="w-10 h-10 rounded-full mr-4"
                                                     src={`https://www.gravatar.com/avatar/${user.email}`}
                                                     alt={`Avatar of ${user.name}`}/>

{user.id === ans.user_id ? user.name : ans.user.name}

{ans.created_at}

                            ))}

                            <textarea className="w-full text-black" onChange={e => setReply(e.target.value)}/>

            </UserLayout>
        </HomeLayout>
    )

}

const mapStateToProps = state => {
    return {
        user: state.user,
        userAltData: state.userAltData
    }
}

export default connect(mapStateToProps)(TicketAnswers);

So what i do wrongh. Please give me some suggestions or tips. Thanks in advice guys!
EDIT 1:
I make a function with the same logic as in useEffect()
and then added onLoad event on my
 to run that custom function and it works. If you know some other ways please let me see
Example:
const scrollToBottom = () => {
    // Scroll into the last reply
    if (messageDivBox.current !== null) {
        messageDivBox.current.scrollTop = messageDivBox.current.scrollHeight;
    }
    return true;
}

return (
...content
);


text:
Q: Is there a way to find the values of x for a graph in a given area? Sorry for my wording, I'm not sure what the proper term for this is. I want to find the sections of x for which the graph of some function, f(x), is in a given area. For an example of what I'm describing, I want to know how to find the thick black bars in the picture below.

A: Use Reduce to get the region as inequalities:
f[x_] := Sin[4 x] + x;
Reduce[-1 <= f[x] <= 1, x, Reals]

(* Root[{1 + Sin[4 #1] + #1 &, -1.45320652256538767403}] <= x <=
  Root[{1 + Sin[4 #1] + #1 &, -0.71249223361378546370}] ||
 Root[{1 + Sin[4 #1] + #1 &, -0.222621770186095002502}] <= x <=
  Root[{-1 + Sin[4 #1] + #1 &, 0.222621770186095002502}] ||
 Root[{-1 + Sin[4 #1] + #1 &, 0.71249223361378546370}] <= x <=
  Root[{-1 + Sin[4 #1] + #1 &, 1.45320652256538767403}] *)

With recently introduced NumberLinePlot it can also be visualized easily. Most of the code below is really styling for aesthetics...
Module[{f},
 f[x_] := Sin[4 x] + x;
 Show[{Plot[{f[x], -1, 1}, {x, -2, 2},
    PlotStyle -> {Automatic, Gray, Gray}, Filling -> {2 -> {3}}],
   NumberLinePlot[Reduce[-1 <= f[x] <= 1, x, Reals], x, Spacings -> 0,
     PlotStyle -> Thickness[0.008]]}]]

EDIT: If you're looking only for the visualization, it's actually possible to skip Reduce entirely inside NumberLinePlot and pass the specification (-1 <= f[x] <= 1) directly to it. Extra Reduce doesn't hurt, though...


text:
Q: Redirecting after a successful (or otherwise) login in Rails I'm relatively new to Rails, so I've been following Railscasts to get up to speed, and have successfully created a Login function. The code is as follows:
def create

    user = User.find_by_email(params[:email])
      if user && user.authenticate(params[:password])
        if params[:remember_me]
          cookies.permanent[:auth_token] = user.auth_token
        else
          cookies[:auth_token] = user.auth_token
        end
        redirect_to root_url, :notice => "Logged in!"

      else
        flash.now.alert = "Invalid email or password"
        render "new"
      end

  end

However, as the code shows, the user is always redirected to the home page, as indicated by root_url.
What I'd like to achieve is something along the following lines:

*

*The user is on the "About", "Contact" or whatever page

*The user clicks the "Login" link and is taken to the login form page

*After successfully (or unsuccessfully) logging in, the user is
returned to the "About", "Contact" page or whatever.

However, I cannot seem to work out what I should replace root_url with. I tried request.referer, but this obviously took me back to the login form (or, rather, a message stating I was already logged in) rather than the page that the user originally accessed the login form from.
I suppose I could do some sort of switch/case, where I store the referring page in a string or whatever, and redirect back to that, but this sounds a bit clunky and (as with most things Rails) I'm sure there's an easier way that I'm missing!
Thanks!

A: you can store return_to in session you can refer here,here


text:
Q: .NET: Return a list of strings given a list of whole words to match I need to split a string into substrings by a set of whole words.
Input:
word wo wordword
Output (split by word):
str1: word
str2: [space]wo wordword
Output (split by wo):
str1: word[space]
str2: wo
str3: [space]wordword
The method signature for the desired method should look like this:
public List<string> GetPhrases(string text, List<string> splitters);

Considerations:

*

*whole word matches only

*whitespaces should be preserved

*splitters list contains distinct words only

*a splitter does not contain whitespace

*matches should be case insensitive
With this method, I'll be able to highlight whole word matches in a UI window with the ability to match multiple words with different highlights, but I can't wrap my head around using regex.
Currently, I have a non-regex solution, but it's not great:
var words = Regex.Split(text, @"\s+").Where(s => s != string.Empty).ToList();
var str = "";
var list = new List<string>();

foreach (var word in words)
{
    if (!splitters.Contains(word))
    {
        if(words.IndexOf(word) != words.Count - 1)
            str += word + " ";
        else
            str += word;
    }
    else
    {
        if(!string.IsNullOrWhitespace(str))
           list.Add(str);

        list.Add(word);
        str = "";
    }
}

if(!string.IsNullOrWhitespace(str))
   list.Add(str);

The problem is I'm not maintaining any whitespace like newlines and instead replacing them with a space.

A: If your splitter words are just streaks of alphanumeric or underscore chars, you may use
var results = Regex.Split(s, $@"\b({string.Join("|", splitters)})\b")
                   .Where(s => !string.IsNullOrEmpty(s))

Here, \b(word1|word2)\b pattern will match splitter words as whole words, and Regex.Split will split the string into the matching and non-matching chunks because of the capturing group ((...)) around the splitter words in the pattern.
The .Where(s => !string.IsNullOrEmpty(s)) will filter out empty strings that usually appear when the match happens be a consecutive match or at the start/end of the string.
See the regex demo:


text:
Q: Split the decimal number in half I have this algorithm, and it's not working. This should split the number in half:
#include<iostream>

#include<math.h>

using namespace std;

int main()
{
    int n, m = 0, k = 0, p = 0, i = 0, y, r = 0, s = 0, j = 0;

    cin >> y;

    n = y;

    while (n != 0)
    {
        n = n / 10;
        k++;
    }

    if (k % 2 == 0){
        m = k / 2;
        p = k / 2;
    }
    else {
        m = k / 2;
        p = (k / 2) + 1;
    }

    n = y;

    while (r < p){
        i = n % 10 * pow(10, r) + i;
        r++;
        n = n / 10;
    }

    while (s < m){
        j = n % 10 * pow(10, s) + j;
        s++;
        n = n / 10;
    }

    cout << j << " " << i;
}

Algorithm: y is the number you read, n is where I save y because it can be lost in the loop, k is a variable where I number how many digits does the number has.
For number 13584, it is working:

But for number 123456789, it isn't.

A: Everything is working. Here is your code changed.
#include<iostream>

#include<math.h>

using namespace std;

int main()

{
    int n, m = 0, k = 0, p = 0, i = 0, y, r = 0, s = 0, j = 0;

    cout << "Enter number to split ";
    cin >> y;

    n = y;

    while (n != 0)
    {
        n = n / 10;
        k++;
    }

    if (k % 2 == 0)
    {
        p = m = k / 2;

    }

    else {
        p=m = k / 2;
        p++;
    }

    n = y;

    while (r < p) {
        i = n % 10 * pow(10, r) + i;
        r++;
        n = n / 10;
    }

    while (s < m) { j = n % 10 * pow(10, s) + j; s++; n = n / 10; }

    cout << j << " " << i;

}