text:
Q: Helping to Understand Web Services and REST I've been longing to ask this question, but only found the time to do so now.
Anyways, there has been much of a discussion on Web Services (yeah, those traditional SOAP-XML response services) and RESTful services (which a lot of devs are into right now).
I feel that although I understand the concepts of REST in general, I need to learn more. I think one best way to totally embrace it is to show that it really is better (emphasis on ** as better is a subjective word) as what was being done currently.
Consider the following simple traditional codes: (This one is copied from an enterprise app with Oracle as backend. The database pretty much I think won't matter as you could readily switch between SQL Server or Oracle or any DB for that matter).
myWebService.asmx.cs
namespace MyApplication
{
    public class myWebService : System.Web.Services.WebService
    {
        private classEmployee _emp = new classEmployee();

        [WebMethod]
        public string GetEmployees()
        {
            string EmployeeData = string.Empty;
            EmployeeData = _emp.GetEmployees();
            return EmployeeData;
        }
    }
}

classEmployee.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Data.OracleClient;

namespace MyApplication.App_Code
{
    public class classEmployee
    {
        private DataAccess _da;

        public string GetEmployees()
        {
            string employeeData = string.Empty;
            string cmd = string.Empty;
            OracleCommand oraCmd = new OracleCommand();
            DataSet ds = new DataSet();

            try
            {
                 cmd = "SELECT * FROM Employees";

                oraCmd.CommandType = CommandType.Text;
                oraCmd.CommandText = cmd;
                ds = (DataSet)_da.ExecSQLQueryCmd(oraCmd, DataAccess.ResultType.DataSet);
                employeeData = ds.GetXml
                ds.Dispose();
            }
            catch (Exception ex)
            {
                employeeData = "Error: " + "Getting Employees [GetEmployees]" + Environment.NewLine + "Details: " + Environment.NewLine + ex.Message;
            }

            return employeeData;
        }
    }
}

DataAccess.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.OracleClient;

namespace MyApplication.App_Code
{
    public class DataAccess
    {
        private OracleConnection oraConn;
        private String connString;

        public enum ResultType
        {
            DataReader = 0,
            DataSet = 1,
            DataTable = 2
        }

        public DataAccess()
        {
            connString = System.Configuration.ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString;
        }

        public object ExecuteSQLCommand(OracleCommand oraCommand, ResultType ReturnType, string TableName = "")
        {
            OracleDataAdapter oraDataAdapter = new OracleDataAdapter(oraCommand);
            oraConn = new OracleConnection(sConnectionString);

            try
            {
                oraConn.Open();
                oraCmd.Connection = oraConn;
                oraCmd.CommandType = CommandType.Text;

                switch (ReturnType)
                {
                    case ResultType.DataReader:
                        OracleDataReader oraDataReader = null;
                        oraDataReader = oraCmd.ExecuteReader();
                        return oraDataReader;

                    case ResultType.DataSet:
                        DataSet ds = new DataSet();
                        oDataAdapter.Fill(ds);
                        oraConn.Close();
                        oraConn.Dispose();
                        return ds;

                    case ResultType.DataTable:
                        DataTable dt = new DataTable();

                        if (!string.IsNullOrEmpty(TableName))
                            dt.TableName = TableName;
                        oDataAdapter.Fill(dt);
                        oraConn.Close();
                        oraConn.Dispose();
                        return dt;
                }
            }
            catch (OracleException oException)
            {
                throw oException;
            }
            finally
            {
                oDataAdapter.Dispose();
                oDataAdapter = null;
                oraCmd.Dispose();
            }

            return null;
        }

        public int ExecuteSQLNonQueryCommand(OracleCommand oraCommand)
        {
            // This will execute any NON-QUERY command.
            //Trimmed for Brevity purposes..
        }
    }
}

The above code is quite self explanatory. Invoke the web service and the get the resulting data in XML format. To execute non-query commands, simply replace the command string passed in the command object and call the necessary method in the DataAccess.cs class.
I am overwhelmed already with the different opinions on why the above should at least be avoided and instead go for RESTful service type calls. But I have not seen anything that at least helps convert this code to somewhat at least embrace the RESTful architecture.
I am pretty sure that a lot of people use this (mind you, I still use a lot of this currently) based on the reason that:

*

*It works.

*Easy to implement, maintain and manage.

*People doing database driven development are so much into SQL commands that being able to use those SQL chops that we use in the SQL editor easily into the application is a big sigh of relief. Why would you use an ORM when you can simply implement all your multiple queries (including Stored Procedures) using the above example.

*Most code examples available for data related apps show the same pattern as above (Dataset being populated from an Command object, and returned as DataSet or XML, etc..).

For one to accept what people terms as "Best Practice" in this area of coding, one should show why it is better, and how it is far easier to do such thing over the one that has been tried and tested to work.
If I may ask our fellow expert devs here to show me how to convert it, and some explanation on why the conversion to REST would be better (through the code), then I would be more than grateful for that.
Appreciate your inputs. Thanks.
Additional:
I just want to point out that, although this is correct, I started to have some doubts whether this approach is the best after reading this article:
http://www.codeproject.com/Feature/WeirdAndWonderful.aspx?msg=4324770#xx4324770xx
The article above, as one commented on said - "Found this in a web service I'm upgrading. It's hard to find anything NOT wrong with this."
I am trying to establish as well what REALLY is wrong with this as I am in a bind.
Let me give you some situations:

*

*Client/Customer asks that you provide an app that queries the information stored on the database.

*You come up with the solution using the above method. Requirements asked by the customer is provided. The solution is reliable, fast and maintainable.

So in essence, the other question which I long to ask, is that, WHAT's really wrong with the code above?

A: To convert it, though this is off the top of my head, it would look something like this.
namespace MyApplication
{
    public class myWebService : System.Web.Services.WebService
    {
        private classEmployee _emp = new classEmployee();

        [HttpGet]
        public string GetEmployees()
        {
            string EmployeeData = string.Empty;
            EmployeeData = _emp.GetEmployees();
            return EmployeeData;
        }
    }
}

And you could return that string in anything that is easily convertable by the consumer. If it's JavaScript then I would recommend JSON since it's native.
Let's talk about ReST for a minute. The part I find the most amusing about ReST is that the old fashioned ASMX services were ReSTful. But, since the IT industry has a problem with accepting the fact that an older technology may have been more correct all along they had to name it something fresh and new.
They did this with the term Client/Server as well. IBM was doing Client/Server operations years before Microsoft came around and said hey, we need to bring everything down to the PC. Well, when that started becoming less popular because deployment was a nightmare they realized, oh man, we need to go back to doing what IBM has been doing all along. Big servers, dumb clients, and simple deployments. But, they couldn't call it that because the industry wouldn't have accepted that and Microsoft didn't want that, so they called it The Cloud (insert bum, bum, bum music here).
So, fast-forward to SOAP. People wanted to be able to transfer complex objects over the wire and not have to deserialize them and they wanted flexibility of protocol. Well, SOAP gave you both, Microsoft generates the client representation and deserialization and the WCF layer allows real flexibility of protocol, whereas ReST can only be transmitted over HTTP because it uses the standard verbs.
So, the real answer to your question is, what do you need?

*

*SOAP is heavier and often less performant on very large data sets than ReST because it's not a native operation for the browser and the envelope is large. But then again, how much data should you really be transferring to the client?!?

*Do you want the one click generation of the client-side model? Then use SOAP.

*Do you want to make the API more accessable to other programming paradigms? Then use ReST.

*Do you want to go down the way of the rest of the industry at the moment? Then use ReST.

There is so much more discussion to be had but that should get you started. ReST is not better than SOAP, it's different, and it solves a different set of problems. Do not let yourself, or others talk you into, Law of the instrument.


text: Q: maven read property file from jar I have a property file in a jar file. How do i read that file using Maven. I have tried using properties-maven-plugin but looks like you have to specify the location of the file. Its a standalone application so I don't see the jar files in the target folder either.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SVN Repository Structure - Why is this better? I've been told that most development shops have the following structure or at least close to this:

*

*Main Repository

*

*Project folders underneath

*Each Project folder has a trunk, branches, and tags folder

so:
ReponsitoryMain
    Project1
        branches
        trunk
        tags
    Project2
        ...

So why is this better or best?  What happens or what heartaches have you come across if you did it another way?

A: The repository structure depends on your needs. If your projects are fully separated (no dependencies between them) then this "simple" repository structure is fine.
If you have dependencies in your project (eg some global "tool-libraries", shared code) you should use a different structure like:
trunk
   prj_a
   prj_b
tags
   <YOUR_TAGNAME>
       prj_a
       prj_b
branches
   <YOUR_BRANCHNAME>
     prj_a
     prj_b

or anything else which makes more sense to your process.
In the simple structure with local trunk/tags/branches it is not possible (at least in a clean way) to tag multiple projects, if you have dependencies between them.
Also the often proposed "Multi-repository" approach will not fill this gap as then you are doomed with multiple revisions or tags in multiple repositories.
The main problem is that SVN has NO support for shared ressources and tagging/branching them.
If you think about your Repository structure, you should ask yourself in what process you want to share your code libraries.

A: Ok, I'm going to be a little more preachy and come down firmly on the side of having a trunk,tags & branches for each project.
The main alternative is to have a single trunk,tags & branches with all projects underneath.
However, this leads to a number of problems, one of which is significant and I'll detail here:
Primarily it paves the way to the untouchable library, where everyone's scared to touch a particular library because any change may break something subtle in some random project. The cause of this is that because there's no separation between projects, anyone can effectively change the code in your project without you being able to either detect or control it.
What happens is that one day you check out your project and it builds, the next day you check it out and it fails, but you've made no changes to your project. What's happened is that someone has changed a library that you depended on. In a large structure with many dependencies, it's unrealistic for a developer to test their library changes against every project, especially if they have to make breaking changes. What you need in your project is a reference to a specific version of the library. That way, the library only gets updated when you change the reference to the latest version.
This kind of reference has 3 effects: 1 your project is isolated from random intermediate development changes to the library. 2 you get a revision in your project that tells you that "I'm now using this version of the library". 3. You get to control when you make the changes to your project to account for any breaking changes in the library.
There are other issues which I can go through if this isn't enough.

A: We keep a separate repository for each project.
While this doesn't allow you to copy and keep the version history files from one project to another, it enables you to archive a whole repository when a project is over.

A: That's what we have.
It works and that's good enough for now (because we never know what the future will bring)
We don't have any compelling reasons to spend some valuable time (and money) to find a possibly more optimal structure.
M.

A: At my shop, we have something like this:
RepositoryMain
  Trunk
    proj 1
    proj 2
    ..
  Dev
    Team1
      proj 1
      proj 2
    Team2
      proj 1
      proj 2
    ...

I don't know how this stacks up to most places but it seems to work pretty good
All the development teams can work separately on their own projects, merging from trunk to their project when they are beginning development/enhancement, and then merging back to trunk once they are finished.

A: Most people do this because it's recommended by the Subversion book.
Here's a good explanation from the director of the CollabNet Subversion project:
http://blogs.collab.net/subversion/2007/04/subversion_repo/

A: This way of organizing the repository:
ReponsitoryMain
    Project1
        branches
        trunk
        tags
    Project2
    ...

is best when your projects aren't that connected/dependent on each other. The other way around makes it easier to version your entire project suite. So if you often release/package Project1 and Project2 together, it's best to have them share the same branch.
If, on the other hand, your project are very decoupled and have totally different teams working on them, then you wouldn't need to check them all out together most of the time, and so you could use the above method.

A: Trunk branches and tags are all act the same way.  How you use them is up to you.
I've been using this structure for years and have yet to find a time that the structure didn't adapt to what I needed to do.

A: In systems like CVS, you didn't keep separate "directories". You just tagged and branched.
However, SVN is modelled more on the idea of snapshots, and therefore "copies" of stuff are done very efficiently. Rather than tagging or otherwise marking special (or alternate) versions of a project, it's easier (and more efficient) to make a named copy of it.

A: Thanks for the Discussion here, I went through this
and project-structure-for-product-with-different-versions
link2
link3
link4
I could see terminologies are confusing.
Projects, Applications, to correctly correlate
Would like to repeat the above things with somewhat clear exp
Lets say we do solution for a customer ABC
Solution is TIcket/HelpDesk Application for ABC's Clients Queries
Lets say applicationName is OneDeskApplication. This Application consists
of
WebUI,Shared Libraries, Build Tools
can we design the SVN like this
XSoftware.com/ABC - Repository
/
trunk/
   OneDeskWebUI
   OneDeskService
   OneDeskDBScript
   OneDeskBatchApp
branches/
   Branch_Product_Support_1_0_0_0/
      OneDeskWebUI
      OneDeskService
      OneDeskDBScript
      OneDeskBatchApp
tags/
OneDeskDocs
OneDeskMasterBuild


text:
Q: data from api will show in console.log, but will not render in react app I am making a call to my API in a react component. I am using the useState hook. I can make my API call and set my state. When I console.log my state after setting it, it is coming back undefined. My code is below:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { API } from '../../config';
import Layout from '../../components/Layout';

const PendingUser = () => {
  const [pendingUser, setPendingUser] = useState({
    firstName: '',
    lastName: '',
    email: '',
    leAgency: ''
  });

  useEffect(() => {
    getPendingUsers();
  }, []);

  const getPendingUsers = async () => {
    const { data } = await axios.get(`${API}/admin/pendinguser`);
    const pendingUsers = data;
    setPendingUser({
      firstName: pendingUsers.firstName,
      lastName: pendingUsers.lastName,
      email: pendingUsers.email,
      leAgency: pendingUsers.leAgency
    });
    console.log(pendingUser);
  };

  return (

          First Name

          {pendingUser.firstName}

  );
};

export default PendingUser;

A: The setPendingUser call is done asynchronously. This is why right after you make the call you don't immediately get the value inside pendingUser.
If you want to know what's in the state each render, I suggest putting the console.log just before the return:
  console.log(pendingUser);
  return (


text:
Q: Why can't "Simple" partitions be read in Ubuntu? I've been slowly transitioning over to Ubuntu and the Linux community as I can see so many improvements linux has over Windows. I didn't have a problem with these as I used crouton and I liked the functions it had.
Now, I want to use another HDD as my /home partition. I made some free space on the Windows end and when I went to see the partition in GNOME Disks or gnome-disk-utility and to my expense, it says it is a "Microsoft LDM data" partition of a 1 TB. I've been checking about this and nothing has shown that can help me. It's a "simple partition" and it dosen't work for some reason.
I would love some help. Thanks.
Edit: I want to keep my files in that partition.

A: Why can't your Dynamic disk partition be read by Ubuntu Linux? Because the nonstandard LDM partitioning method created by Microsoft is proprietary, and does not play well with others.
There are multiple methods to convert your drives back to the standard partitioning method, such as the first one (only) here, this, alternative, or this one. You'll need to do that before Linux can see the drive.
However, ensure to make a complete backup of what's on that drive first, and verify the backup, before you start to make changes. Disk partition changes are the easiest way to lose all the programs and data on a drive.


text:
Q: Is there a name for this 3D printing effect? I'm relatively new to 3D printing, but I've taken to it with much gusto. I wish I'd done this years ago.
Trying to solve a printing problem, and I've been stymied by not knowing the name for the effect I'm seeing - there is zero chance I'm the first one to discover this.
A minimum reproducible example is a triplet of vertical cylinders on a raft, it's clear that the tool path starts at one spot, runs a full circle around to end in that same spot, and it lingers long enough to extrude just a tiny bit more material that builds up in a vertical line.

This matches exactly the tool path shown in the slicer and this effect is repeatable no matter how many parameters I changed. I've done many dozens of test prints and am not getting anywhere.
These are 16mm across and are used as inserts into a tray holding vials to shim a narrower diameter tube, and the bump is enough to matter.  I have to make thousands of these and am hoping not to have to file them all down by hand.
If it matters, I'm using a Sindoh 3DWOX 2D and a 3DWOX 1 with PLA filament.

*

*Is there a name for this effect?

*Are there mitigations?

I'm starting to rethink this whole approach...

A: I was happy to find my own answer elsewhere.
First, that effect is known as a "seam", and one mitigation is known as "vase mode" (known in some slicers as "Spiralise Outer Contour"), which builds the cylinder in a continuous spiral from the bottom up with no seam. It can create really nice aesthetically-pleasing prints.
However, vase mode only works for a single model because stopping (and possibly retracting) to print a second model breaks the whole continuous-spiral thing.
So, if I had only a few of these to print, I'd do them one at a time, but given that I need thousands of them, I've found other approaches to solving the problem.

A: As you already identified it's the z-seam you're seeing, you can choose to align your seam into different locations but it looks to me that your seam is bulging more than what I'd consider normal.
You could try ensuring that retraction is turned on and pick up the speed a little to reduce the time spent in that area.


text:
Q: Reproducible: after upgrade Gradle i.c.m. Android8.0 -- cannot re-install App - error INSTALL_FAILED_NO_MATCHING_ABIS (Binder.java:682/674) This post is different than other posts because due to upgrading Gradle and running the app on Android 8.0 the application cannot be re-installed.
After upgrading 1 of my 1 year old app to Gradle 4.4, I tried to re-install my app for the 101st time to my Samsung S7 Android 8 device. I got this error:

Installation failed with message INSTALL_FAILED_NO_MATCHING_ABIS:
  Failed to extract native libraries, res=-113.

Re-installing on a Android 7 emulator or Android 7 mobile works like charm. Installing on a Android 8.0 (Nexus5) emulator gave the SAME error!
I have installed the application a number of times on Android 8. Now it was silently removed by/from Android 8 a couple of days ago. Not because of the anti-virus, but to some feature of Android 8.
After clicking on [OK] for uninstall I got this error:

$ adb shell pm uninstall nl.deholtmans.categorychecklist Unknown
  failure (at android.os.Binder.execTransact(Binder.java:674)) Error
  while Installing APK

A: Thanks to sweisgerber.dev:
Replace this:
implementation 'org.apache.directory.studio:org.apache.commons.io:2.4'

By:
implementation group: 'commons-io', name: 'commons-io', version: '2.5'

A: Does the app install correctly when using Emulators?
If yes, maybe uninstall Avast and try again.


text:
Q: Test if numbers are divisible by 4, up to 100 digits Simply enough, I practice programming via an online judge. This is a rather stupid problem, really easy. However, The judge keeps saying I have a wrong answer. I'm just going to paste the code which is just a few lines, and a link  to the problem.
#include <iostream>
#include <string>

using namespace std;

int main() {

    int cases = 0;
    string solution = "";
    cin >> cases;

    if (cases > 100)
        return(0);

    for (int i = 0; i < cases; i++) {
        int temp = 0;
        cin >> temp;
        if ((temp % 4) == 0)
            solution +="Y";
        else
            solution +="N";
    }

    for (int j = 0; j < cases; j++) {
        if (solution[j] == 'Y')
            cout << "YES";
        else
            cout << "NO";
        cout << endl;
    }
}

The problem is simply to output YES or NO for each number that is input that is divisible by 4, YES for if it is, NO if its not. The problem and every minute detail can be found: http://coj.uci.cu/24h/problem.xhtml?abb=1306
This is rather silly, but I'm going bonkers here trying to figure out what I'm doing WRONG!

A: As I said in a comment, the problem is that you cannot read a 100 digit number into an int directly.  I don't want to give you the solution to the algorithm, but a hint that should help: How many digits would you need to know if the number was divisible by 2 or by 5?  And how could you extend that to 4?

A: A number is divisible by 4 if its two last decimal digits are divisible by 4.
The end.
P.S. Sometimes it makes sense to stop thinking as a programmer and remember algebra/arithmetics.

A: If you express a number X as Y + d  where d = X%100 and Y = X -d we can see that Y will always be divisible by 100, for example for the number X = 343535, Y would be 343500 and d would be 35. Since Y is divisible by 100, implies that is divisible by 4, so you can determinate if X is divisible by 4, checking if d is divisible by 4, i.e the last two digits of X.

Formally it would be:
Y = 4*Z
Y = 100*X +d
Y = 4*Z = 4*25*X +d
d = 4*(Z - 25*X)
i.e if Y is multiple of 4, d is multiple of 4

You have to apply this principle to solve your problem.
Simply read a raw string and check if the number represented by the last two characters are divisible by four.

A: As tempting as might be, you don't need a BitInteger to figure out whether a 100 digit number, of 1 million digit number is divisible by 4. That's just simple math, that you should be able to figure by yourself in a minute, if you don't know the rule.

A: Perhaps the problem is this if (cases > 100). because of this -1 would be a valid option.
Change to if (cases > 100 && cases < 1) to fix it

A: I wouldn't even read the whole number. I would just read the last 2 digits before the EOF char (end of file).
string inputString;
while(getline(cin,inputString)
{
    //code for finding x %4==0 and output
}

then all you need to do is convert the last 2 chars into a int and then do your mod 4 code. (you'll need a catch value for numbers < 10, but that shouldn't be hard)


text:
Q: Cannot set spatial index to geometry type - #1464 I use MySQL version 5.5.49. They type of the column is geometry and the engine of the table is InnoDB.
I try something like
ALTER TABLE geom ADD SPATIAL INDEX(field);

or
ALTER TABLE geom ADD SPATIAL INDEX table (field);

or
CREATE SPATIAL INDEX sp_index ON table(field);

and I get the error

#1464 - The used table type doesn't support SPATIAL indexes

Does this has to do with the engine of the table, the version of MySQL or am I missing something?
I read The used table type doesn't support SPATIAL indexes that is the engine that causes the problem. Do I really have to change the engine? InnoDB is more suitable for my needs.


text:
Q: Check if not null Bluej (Java) not working I have researched this extensively and found answers for checking if Strings are not null, but not for when checking if a class I've instantiated is null. This is a class instantiated by the another class that keeps a list of all Rooms, just like the Cave Adventure game. Here is the code:
public class Room
{
    private String description;
    private Room northExit;
    private Room southExit;
    private Room eastExit;
    private Room westExit;

    /**
     * Create a room described "description". Initially, it has
     * no exits. "description" is something like "a kitchen" or
     * "an open court yard".
     * @param description The room's description.
     */
    public Room(String description)
    {
        this.description = description;
    }

    /**
     * Define the exits of this room.  Every direction either leads
     * to another room or is null (no exit there).
     * @param north The north exit.
     * @param east The east east.
     * @param south The south exit.
     * @param west The west exit.
     */
    public void setExits(Room north, Room east, Room south, Room west)
    {
        if(north != null)
            northExit = north;
        if(east != null)
            eastExit = east;
        if(south != null)
            southExit = south;
        if(west != null)
            westExit = west;
    }

    /**
     * @return The description of the room.
     */
    public String getDescription()
    {
        return description;
    }

    public Room getExit(String direction)
    {
        if(direction.equals("north")) {
            return northExit;
        }
        if(direction.equals("east")) {
            return eastExit;
        }
        if(direction.equals("south")) {
            return southExit;
        }
        if(direction.equals("west")) {
            return westExit;
        }
            return null;
    }

    public String getExitString() {
        if (!northExit.equals(null) && !northExit.equals(""))
            return "north ";

        if (!eastExit.equals(null)  && !eastExit.equals(""))
            return "east ";

        if (!southExit.equals(null)  && !southExit.equals(""))
            return "south ";

        if (!westExit.equals(null)  && !westExit.equals(""))
            return "west ";

       else {
           System.out.println("There are no doors!");
           return null;
        }

    }
}

I end up getting a NullPointerException when it reaches the getExitString() method.
I've been working on this for many many hours and I'm at the limit of my frustrations currently, any help will be GREATLY appreciated.

A: The expression northExit.equals(null) (as one example) will not work as you think it will.
Think of it this way: the northExit. bit implies a dereferencing of the northExit reference to find what exactly it points to. Such a dereference attempt when it's null will give you the exception you're seeing.
The correct way to check if a value is null is to use reference equality(a),along the lines of:
if ((northExit != null) && (! northExit.equals(""))) ...

(a) When teaching, I've often found borrowing a couple of five dollar notes from students and explain it thus.
In terms of reference equality ==, they're different since they're actually distinct physical items. In terms of content or value equality .equals(), they are identical.
Then I pocket the ten bucks and hope they forget about it by the end of the lesson, a nice little supplement to my earnings :-)


text:
Q: C - Unable to read from a file that has no trailing new line in it I am working on a program in C that has to read a line from a file descriptor.
It has to return 1, 0 or -1 if there was an error but the line is read from main using the address of a pointer.
The program fails to output anything when I want to read from a file that I have created like this:
echo -n "test test" > filetest1 (-n do not output the trailing newline)
I use an array in which I store the new line until I find \n and then I allocate memory for a pointer and store that line in it.
The program copies "test test" in the pointer but it does not output anything when I compile. And I don't understand why.

*

*j = return 1,0 or -1.

*buf = array in which I store a line until I find \n

*str = store the line that I have initially put in buf

I am not allowed to :

*

*change the get_next_line prototype

*use realloc, only malloc

*use any other functions to read from a file
descriptor other than open and read.
   #include <fcntl.h>
   #include <stdio.h>

   static char     *ft_read_line(int fd, char *buffer, int *j)
   {
           char    c;
           int     i;
           char    *str;

          str = NULL;
          i = 0;

          while ((*j = read(fd, &c, 1)) != 0)
          {
                  if (c == '\n')
                          break;
                  buffer[i++] = c;
          }

          if (str != NULL)
                  free(str);

          if (!(str = (char *)malloc(sizeof(str) * (i + 1))))
                  return (NULL);

          strcpy(str, buffer);
          bzero((char*)buffer, 10000000);

          return (str);
  }

  int     get_next_line(int const fd, char **line)
  {
          static char     buf[10000000];
          int     j;

          j = 0;
          *line = ft_read_line(fd, buf, &j);

          if (j < 0)
                  return (-1);

          return (j);
  }

  int     main(void)
  {
          int     fd;
          char    *line;

          fd = open("filetest1", O_RDONLY);

          while (get_next_line(fd, &line) >0)
          {
                  printf("%s\n", line);
          }

          close(fd);
          return (0);
  }

A: There is no need to use an intermediate buffer. Assuming the return value must be -1, 0, +1, the function prototype
int get_next_line(int fd, char **lineptr);

is deficient, because it means you cannot read content with embedded nul bytes ('\0'), and reusing the same dynamically allocated line is not really feasible. (Sure, you can use strlen() to guess how long the previous line might be, but it's just a guess.)
A much better prototype would be
int get_next_line(int fd, char **lineptr, size_t *sizeptr, size_t *lenptr);

where the amount of memory allocated for *lineptr would be available in *sizeptr, and the length of the actual line (not including the end-of-string \0 byte) in *lenptr. When called, if *lineptr != NULL, *sizeptr would tell how much memory is already dynamically allocated for *lineptr.
In any case, the key to implementation is to one variable to track the number of bytes stored in the new line, and another to track the number of bytes allocated to the line, and reallocate whenever necessary.
Lets assume you are required to use the first prototype shown, and that the caller is responsible for free()ing it, i.e. that the contents of *lineptr are ignored, and a new line is always allocated.
Start the function with the necessary variable declarations and checks:
int get_next_line(int fd, char **lineptr)
{
    char   *line = NULL;
    size_t  size = 0;    /* Allocated for line, remember '\0' at end */
    size_t  used = 0;    /* Number of chars stored in line */

    ssize_t n;           /* Result from read() */

    /* Just to make error handling easier, we clear *lineptr to NULL initially. */
    if (lineptr)
        *lineptr = NULL;

    /* fd must be a valid descriptor, and lineptr a valid pointer. */
    if (fd == -1 || !lineptr)
        return -1;

In the read loop, you can use n = read(fd, line + used, 1); to read the next char into the buffer, but you must obviously first ensure the buffer has sufficient room for it. So, at the beginning of the loop body, before reading the next char, you ensure the line has room for at least one char, and also for the \0 to terminate the string:
        if (used + 2 > size) {
            char *new_line;

            /* Better allocation policy! */
            size = used + 2;

            new_line = realloc(line, size);
            if (!new_line) {
                free(line);
                return -1;
            }
            line = new_line;
        }

The comment about allocation policy means that you don't really want to grow the line buffer every other character read: you'll want to grow it in larger chunks, so that reallocation is not needed so often.
What constitutes a good reallocation policy, then? It is a matter of discussion. It really depends on what the typical data is like. If the policy allocates in chunks of a megabyte or so, each line might waste a lot of memory, even if trimmed to correct size later on. (This is because many C libraries use a technique called memory mapping for large allocations -- say, 256kiB or more, but it varies from implementation to implementation -- and those have their own granularity, typically page size (which is typically a power of two, between 4kiB (4096) and 2MiB (2097152)), so on average, you have at least half a such page of wastage per line we can do nothing about.)
In practice, I recommend a policy that allocates for a typical length of line, then doubles the allocation for longer lines, up to some limit (like a megabyte or so), and allocating in multiples of that limit. For example:
            /* Suggested allocation policy, much better */
            if (used < 126)
                size = 128;
            else
            if (used < 1048574)
                size = 2 * used;
            else
                size = used + 1048576;

The exact numbers above aren't critical, as long as you keep in mind that size must grow to at least used + 2. It can grow larger, but if it does not grow to at least used + 2, we are in trouble (our program won't work right).
If read() returns 0, it means you encountered the end of file. In this case, there is nothing stored to line, and you should not increment used.
If read() returns negative, an error occurred. (Normally, read() should be able to return only -1, and in that case, errno is set to indicate the error. However, a bug in the kernel or C library is always possible -- actually, I do know of one Linux kernel bug that can cause read() to return negative, but it only occurs when trying to write larger than 2GiB chunks.)
In other words, I'd recommend something like
            n = read(fd, line + used, 1);
            if (n == 0)
                break; /* Break out of the loop; no error */
            else
            if (n < 0) {
                /* Read error of some sort;
                   errno set if n == -1 */
                free(line);
                return -1;
            }

            if (line[used] == '\n') {
                /* Keep newline character */
                used++;
                break;
            }

            /* Skip/omit embedded NUL bytes */
            if (line[used] != '\0')
                used++;

After the loop, used == 0 if nothing was read. Note that if you do not keep the newline (add the \n into the buffer), you won't be able to tell whether you read an empty line (only a \n) or if you are at the end of the line. You can avoid that by adding a flag variable, say newline_seen, that is initially zero, but you set to one. Then, only if both used and newline_seen are zero after the loop, are you at the end of input without anything to read.
After the loop, you need to append the '\0' to terminate the line properly. Also, you might wish to optimize the memory allocated to the line to the exact length:
    char *new_line;

    new_line = realloc(line, used + 1);
    if (!new_line) {
        free(line);
        return -1;
    }
    line = new_line;

    line[used] = '\0';

Finally, store the dynamically allocated line to the pointer supplied by the caller, and return. (Note that you might need to check used whether you return with 0 or 1, depending on the requirements.)
    *lineptr = line;

The above is definitely not the only way to solve this problem. For example, when you wish to omit the newline from the end of the line, you could add the terminating \0 within the loops, before the break; statements. Then, in the n == 0 case, you could check if used == 0: if it is zero, it means you are at the end of input, without anything to read, and you can free line and return (with a value indicating end of file, nothing to read).
If you compare to OP's implementation, the most important point is avoiding the secondary buffer, and using realloc() to grow the line buffer as needed.
Note that when size is a positive number (nonzero), malloc(size) and realloc(NULL, size) are equivalent. (The zero case is a bit ambiguous anyway, because some implementations return NULL, and others return a pointer that you cannot use to store other data to.)
Also, free(NULL) is safe, and does nothing. Therefore, if you initialize your pointer to NULL, use realloc() to grow it when necessary, you can always call free(pointer) to discard it, regardless of whether it is still NULL or has some memory allocated to it. In my own programs, I rarely use malloc() at all, because realloc() and free() suffice.
Finally, I am not suggesting you to copy the above code. It is important for your learning process, your learning curve, to do stuff your own way, at your own pace; otherwise, you risk dropping onto nothing. Always keep your footing secure, by fully understanding your own programs, because everything else will build upon it. Knowledge is built, not heaped. Learning by rote -- copying without understanding -- is worth nothing at this level. We stand on the shoulders of giants, and so on.

The requirement of using only malloc() is utterly silly, because realloc() is the function that is ordinarily used, and in many ways just as easy to understand.
Anyway, let's take a look at OP's implementation, and what actually happens at a get_next_line() call:

*

*ft_read_line(fd, buf, &j) is called. fd is the correct file descriptor, buf is a local array of 10,000,000 chars, and j is an int cleared to zero.

*ft_read_line() initializes str pointer to NULL.

*A while loop tries to read from the file descriptor fd into a char variable named c, as long as read() does not report an end of input. (That is, even if an error occurs.) If a newline \n is read, the code breaks out of the loop, otherwise c is appended to the buffer specified as a parameter.

*If str is not NULL, it is freed. This if clause is doubly useless: first, because str must be NULL here. Second, because there is no need to check if str == NULL to call free(str); free(NULL) is perfectly safe, and does nothing. (In other words, free() itself will check if its parameter is NULL, and does nothing if it is.)

*i is the number of characters saved into the buffer passed as a parameter. str is allocated enough memory for i+1 pointers to char. If the allocation fails, the function returns NULL.

*At this point, the buffer contents are treated as a string. However, no end-of-string NUL byte (\0) has been appended to the buffer, so it is not a string yet. In other words, strcpy(str, buffer) is likely to try to copy much more than i characters from buffer to str, because it looks for that NUL byte in buffer to mark the end. This is a fatal bug, and may crash the program right here.

*An obsolete function, bzero(), is used to clear 10,000,000 bytes in buffer to zero.

*The pointer str is returned to get_next_line(). Note that in get_next_line(), j will reflect the last return value from read() (that is, 1 if a character was read but was '\0', or 0 if no more input. (All other values are impossible, because those are the only two values with which the code can break out of the while loop.)

*The returned pointer is saved to the pointer pointed by the second parameter to get_next_line().

*The get_next_line() checks if j == -1. This is an useless check, because j cannot be -1 here.

*get_next_line() returns 0 if an end of input occurred, 1 otherwise.
As you can see, the intermediate buffer is useless. However, there are more serious issues. First is that the input data is treated as a string, without making the char array a string by appending the string-terminating NUL byte, \0. The second is that read errors are ignored, in a way that makes the while loop repeat until it tries to overwrite memory it cannot, at which point the program crashes.

How to implement the int get_next_line(int const fd, char **line) function, then, if you are only allowed to use open(), read(), malloc(), and memmove()?
The logic you need to implement is actually quite straightforward:

*

*Begin (infinite) loop:

*Ensure your dynamically allocated line has room for at least two chars.

*Try read() one character from the file descriptor to the next unused index in your dynamically allocated line.
If read() returns

*

*> 0, you have a new character. If it is a newline (\n), terminate the string by appending a NUL byte, \0. If you want your get_next_line() to remove the newline at end of each line, replace the newline read with the NUL byte. Break out of the loop.
Note that in some cases, the file or input may contain "embedded NUL bytes", or \0 in the data itself. I personally would check for these just like newlines, except that instead of breaking out of the loop, I'd just not save them in the dynamically allocated buffer.

*0, no data was read, and there is no more input. If the buffer index is still zero, the end of input occurred before anything was read; so, free the dynamically allocated buffer, and return a value that indicates end-of-input (and make sure the line pointer is NULL).
If the buffer index is not zero, it means the final line in the file did not end with a newline. Such files occasionally happen. Append '\0' to the dynamically allocated buffer, and break out of the loop.

*< 0, an error occurred. If read() returned -1, then the exact cause is in errno; otherwise, it was a read error (same as errno == EIO). I recommend you free the dynamically allocated line (and set the line pointer to NULL) and return a value that indicates an error.
You could, if you want, add the terminating NUL byte \0 to the current line read, set the line pointer to point to it, and return an error value; so that the caller will get a partial line even when an error occurs.
However, in my opinion, returning a partial line when an error occurs is not sane: there is nothing safe/reliable that can be done with said line -- except possibly show it to the user, but even then, it might be garbage. Most likely, the user is only interested in knowing that an error occurred, and will throw all of the partial data away, and try something else. That's what I do (and have done).

*Optionally, reallocate the line to the number of chars saved in it, plus one for the (already appended) string-terminating NUL byte \0.

*Save the pointer to the dynamically allocated buffer (to *line), and return with a value indicating a line was successfully read.

Now, how do you ensure a dynamically allocated buffer has enough room?
Typically, we use a pointer to point to the buffer, the number of data characters in the buffer (its length), and the size allocated for the buffer (i.e. the number of characters we can store in the buffer):
char  *buffer = NULL;
size_t length = 0;
size_t allocated = 0;

When we detect that length >= allocated -- or, length + 2 > allocated, since we want to be able to add at least two chars (one data and one \0), above --, we need to reallocate a larger buffer. With realloc(), and variables initialized as above, it is as simple as
char *temp;

allocated = length + 2; /* Or, say, 2*length + 2 */
temp = realloc(buffer, allocated);
if (!temp) {
    /* Out of memory; exit program! */
}
buffer = temp;

The idea with realloc() is simple. It takes two parameters: a pointer, and the desired size.
If the pointer is NULL, then realloc() allocates memory, sufficient to store the size number of chars, and returns it.
If the pointer already points to dynamically allocated memory, realloc() grows or shrinks the amount to the desired size. If larger, all the old data is kept. If smaller, only the data up to the new size is kept. In both cases, realloc() may return a different pointer; but even so, the same data will be there.
If the pointer points anywhere else, like a local variable or array, the program will likely crash. Even if it does not crash, realloc() does not work in this case at all.
If realloc() cannot do the reallocation, it will return NULL with errno == ENOMEM. If it was trying to grow or shrink already dynamically allocated memory, that allocation and memory will still be valid. (And this is why you shouldn't use buffer = realloc(buffer, new_size): if it fails, you've lost the still-valid previous buffer. As you can see above, I use a temporary variable for the result, and only assign back to buffer if it is non-NULL.)
We can write our own analog of realloc() using malloc() and memmove(), though. We just need to know both the old and new sizes:
void *our_realloc(void *old_data, const size_t old_size, const size_t new_size)
{
    void *new_data;

    /* Reallocation to zero size is special. We always free and return NULL. */
    if (new_size < 1) {
        free(old_data);
        return NULL;
    }

    /* Allocate memory for the new buffer. */
    new_data = malloc(new_size);
    if (!new_data)
        return NULL; /* Failed! */

    /* Copy old data, if any. */
    if (old_size > 0) {
        if (old_size < new_size)
            memmove(new_data, old_data, old_size);
        else
            memmove(new_data, old_data, new_size);
    }

    free(old_data);

    return new_data;
}

The real realloc() is superior, because it does not need to know the old size (the C library remembers it internally!), and it can usually grow/shrink the allocation in place, without temporarily needing additional memory like we do above.

I fear the lecturer or course designer is either a genius or a functional idiot, and instead thought that you should write the get_next_line() along the following lines:

*

*Allocate a dynamic buffer you think is large enough.

*In a loop:

*read() one character. If read() returns:

*

*> 0, you read an additional character.
If that character is \n, append it to the buffer (if you wish to keep the newlines), and make the buffer contents into a string by appending the string-terminating NUL byte \0, too. Save the buffer pointer and return (value indicating a new line was read).
If that character is anything other than \0, append it to the dynamic buffer. (Since \0 terminates a string, we skip them if we read them from the file.)

*== 0, there is nothing more to read. If the dynamically allocated buffer does not have any data in it yet, we got end-of-input before any data, and can discard the buffer, and return "nothing; end of input".

*< 0, an error occurred. Discard the dynamically allocated buffer, and return read error.
Note that in the above case, you can use an infinite loop. For example, while (1) { ... } or for (;;) { ... }. You can break out of them, but here, you can also just return from the entire function at the above cases.
If they use this exercise to show how malloc() alone leads to arbitrary magic constants and buffer sizes, and how important realloc() is, and how relatively easily you can fix this to work for any-length lines (with realloc()`, they are a genius. Because real-world code has to deal with such stuff, and it might actually be a working approach to teaching dynamic memory management.
If they think this kind of code is acceptable in any other case, they are a functional idiot. The amount of time and resources lost due to badly-written software (for example, the kind that has secret limits that cause it to crash without any explanation if you happen to exceed those) is astronomical, and adding to that body is like teaching students how to mix papercuts hand household chemicals for maximum pain, and use it to gain sympathy. Functional, but idiotic.


text:
Q: Have dependengy jar automatically add to STS project when added as dependency in build.gradle I created a Spring Boot application at https://start.spring.io.
The dependencies I added at the time all exist. Now that I'm developing the app in STS I have to add dependencies to build.gradle from time to time. How can I get the relevant jars to be added to the project without manually downloading them and adding them through Configure Build Path...?

A: The component in Eclipse that supports Gradle is called Buildship. To add an new dependency you should modify your build.gradle file and add the dependency in the dependencies {} block. You can then right-click the project and select Gradle -> Refresh Gradle Project as described here. This will download the dependency (and all of its dependencies) and then update the classpath of the project.


text:
Q: Function to convert an arbitrary string for use inside JavaScript I need to write a VBScript function that can convert arbitrary strings into a string that I can safely use inside JavaScript. Something like this:
"Hello World"
-- becomes --
"Hello World"

"Hello
World"
-- becomes --
"Hello\nWorld"

"Hello
    World"
-- becomes --
"Hello\n\tWorld"

"Hello'World"
-- becomes --
"Hello\'World"

I need to use the function like this:
var foo = '
<%= thatfunction( Recordset( "TextField" ) ) %>
';

I hope you got the point. The function does not have to be bullet-proof but close.

A: @Salman A: Here's a Classic ASP function you could use
Function thatfunction(ByRef input_string)
    If NOT IsNull(input_string) AND input_string <> "" Then
        Dim working_string
        working_string = input_string
        working_string = Replace(working_string, vbNewLine, "\n")
        working_string = Replace(working_string, vbTab, "\t")
        working_string = Replace(working_string, "'", "\'")
        ' .. other escape values/strings you may wish to add

        thatfunction = working_string
    End If
End Function

A: You can use JavaScriptSerializer
Dim serializer as New JavaScriptSerializer()
Dim jsString as String = serializer.Serialize(your_string_here);

... but your example shows the text being embedded in an HTML element--not in a Javascript string.  Maybe you're looking for HttpUtility.HtmlEncode().  Your example might then look like this:

<%= HttpUtility.HtmlEncode( Recordset( "TextField" ) ) %>


text:
Q: Monitoring changes in web page through mobile app I am trying to develop a mobile app that monitors a web page(remote and not administered by me), such that whenever the content(body tag) of that page changes, my app come to know of that change and notifies the user.
I want to develop this mobile app using phonegap, jquery/javascript but can't use any server side language. After a lot of research, i thought of using YQL(Yahoo query language). It takes the url of the web page and returns its html in json format. I then stringify the json and calculate its unique hashcode using javascript and save the hashcode. I keep repeating these steps after every 5 minutes and keep comparing the hashcodes. If there is any change in hashcode, i get to know that the content of the web page is changed.
Although it is working good, but I was wondering if there is any alternative way of doing it because it seems very inefficient to grab entire page to a mobile and then store its hashcode? Any way which is more efficient?
Thanks

A: Depends on the webpage but in practice you can make a HEAD request instead of a GET request then check the Last-Modified header if present. Though, then you'd have to make a normal GET request to get the body contents if the Last-Modified date has changed


text:
Q: Show banner AdView below transparent toolbar I have a the below layout: A customVideoView that displays a video,a transparent toolbar is positioned on top and a banner addview. I want the banner addview to appear below the transparent toolbar. However it currently shows under the toolbar, its visible but not clickable.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clipChildren="false"
android:id="@+id/frame"
tools:context="com.kelele.movies.Kelele_Home" >

<com.kelele.movies.util.CustomVideoView
    android:id="@+id/video"
    android:clickable="false"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fitsSystemWindows="true"   />

<com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    ads:adSize="BANNER"
    ads:adUnitId="@string/banner_ad_unit_id"
    android:layout_gravity="center_horizontal" />

<include
    android:id="@+id/transparent_toolbar"
    layout="@layout/toolbar" />

<ImageView
    android:id="@+id/video_play_btn"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:visibility="gone"
    android:src="@drawable/play"
    android:layout_gravity="center" />

A: you can use WindowsManager.addView().
it probably look like this:
WindowManager.LayoutParams params=new WindowManager.LayoutParams();
params.type = WindowManager.LayoutParams.TYPE_PHONE;
            params.format = PixelFormat.RGBA_8888;
            params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                    | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
                    | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                    | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
            params.width = WindowManager.LayoutParams.FILL_PARENT;
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
windowManager= (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
windowManager.addview(new Banner(),params);


text:
Q: open file fail(-1) with different flag settings I have a question about using open() with different flags in Native android.
Because i want to open a file and ignore the cache& buffer, in oder to access the hardware(SD card) directly.
If the flag setting is
O_CREAT | O_RDWR | O_NDELAY, S_IRUSR | S_IWUSR| O_DIRECT | O_SYNC
. I can got a positive file descriptor(fd).
But if I change the setting to
 O_CREAT | O_RDWR | S_IRUSR | S_IWUSR| O_DIRECT | O_SYNC
the result is fail(-1).

A:
If the flag setting is O_CREAT | O_RDWR | O_NDELAY, S_IRUSR | S_IWUSR| O_DIRECT | O_SYNC . I can got a positive file descriptor(fd).

That is not quite correct usage of the form
int open(const char *pathname, int flags, mode_t mode);

But if I change the setting to O_CREAT | O_RDWR | S_IRUSR | S_IWUSR| O_DIRECT | O_SYNC the result is fail(-1).

What you call "setting" is an invalid mixture of flags and mode symbols.  Also, since O_CREAT has been specified in flags, the mode argument must be supplied and it is not.
Try separating the modes from the flags:
open(pathname, O_CREAT | O_RDWR | O_DIRECT | O_SYNC, S_IRUSR | S_IWUSR);


text:
Q: Iterating over a list and defining the range accordingly I have the following list,
l = {{"a", "b"}, {"a", "b"}, {"c", "d"}, {"e", "f"}, {"e", "f"},
     {"x", "y", "z"}, {"m", "n", "o"}, {"p", "q", "s"}};

for each sublist I want to count them and make a polynomial out of it, for example for {"a", "b"} I have
Total[x^-2 x^Map[Length, Select[l, ContainsAll[{"a", "b"}]]]]

Note that the x^-2 terms is important to be there for my later calculations. Now if I want to do this for {"x","y","z"} I shall do
Total[x^-3 x^Map[Length, Select[l, ContainsAll[{"x", "y","z"}]]]]

So as you see the power of first term is now x^-3, now if I want to do this on a table I can write,
AssociationThread[
 l -> Table[
   Total[x^-i x^Map[Length, Select[l, ContainsAll[l[[i]]]]]], {i,
    Length[l]}]]

My question is how to iterate the x^-i such that it works correspondingly? meaning for entries of length 2 the power should be x^-2, for entries of length 3 the power should be x^-3 and generalisable to higher length in similar manner.


text:
Q: Responsive Drop down menu with horizontal sub nav I have created a drop down menu with horizontal sub menu. This is a project I am working on from a client and I am working from a design from a Graphic Designer.
Here is the HTML...

Home

    Accommodation

        Subnav Link
        Subnav Link
        Subnav Link
        Subnav Link
        Subnav Link
        Subnav Link

Hindelinis

In House Spa

Own A Lodge

Book Online

Here is the css
.main-nav {
  background-color:#1e1e1e;
  height: 53px;
}
#topnav {
position: relative;
    float: left;
    margin: 0;
    padding: 0;
    width: 100%;
    list-style: none;
}
#topnav li {
 float: left;
 margin: 0;
 padding: 0;
}
#topnav li a {
    display: block;
    padding: 0 15px;
    height:53px;
    color: #fff;
    line-height:53px;
    text-decoration: none;
}
#topnav li:nth-child(3) {
   display:block;
   width:83px;
   height:53px;
   margin:15px;
   background-image:url('images/hindelinis.png');
   background-repeat:no-repeat;
   text-indent: 9999px;
   overflow:hidden;
 }
#topnav li:hover a {color:#f6f6f6;}
.book-online {
    background-color:#406340;
    color:#fff;
    margin-left:30px;
}
#topnav li span {
    display: none; /*--Hide by default--*/
    float: left;
    position: absolute;
    left: 0;
    top:53px;
    min-width: 900px;
    height:100px;
    color: #000;
}
#topnav li:hover span { display: block; } /*--Show subnav on hover--*/
#topnav li span a { color:#000!important;display: inline; }
.current-menu-item {display:block!important;}

I have put the link to the codepen so you can see what I have so far. It is here Codepen
I am running into a few issues with this style of navigation. I am hoping you guys here can help.

*

*I want to push this navigation across to the right, without it affecting the sub menu below.

I also believe there is a better way to code this to give me more flexibility, particularly when trying to make it responsive.
Because of some of the width declarations in there I am finding it difficult to make it responsive without completely changing the CSS.
If anybody could help, or suggest, or guide that would be so helpful for me.
At the minute it feels too hacky for my liking and I would like it to work much cleaner and be more flexible responsively.
Any help would be great
Thanks
Dan

A: give .main-nav class a float: right; property.


text:
Q: Exporting highlights from Kindle Personal Documents to a TXT file There are two main categories in Kindle App for iPad:

*

*Books - contains books purchased from Amazon; highlights are available at https://kindle.amazon.com/your_highlights — it works fine for me.

*Personal Documents - contains all other books; highlights are not available online.

So, I have book purchased at different source than Amazon and I would like to be able to export my highlights and notes to a text file (or any other common format). My approaches so far:

*

*As far as I know, https://kindle.amazon.com/your_highlights is available for Books category and thus, for Amazon-purchased books only. There are no entries from "Personal Documents"

*I cannot move my book from Personal Document to Books - there is no such option in Kindle App. There is no such option on Amazon's "Manage Your Kindle" site too.

*There is no option to export all highlights. Kindle app has option to share a highlight via Facebook or Twitter, but there is no option for copy or export it.

I synced my book with Kindle Touch and highlights are synced successfully. But:

*

*There is no export option in Kindle Touch too.

*I am unable to read highlights content on my cpu. The file with highlights has extension .azw3r and contains relative references, for example: annotation.personal.highlight 283390 283606.

*There are no entries in My Clippings text file (there are entries there but for non-synced books).

The question is: How can I export my highlights and notes from iPad Kindle App to a TXT or any other common file?
Note I'm using Windows but I put this question to Apple.SE since the root problem comes from iPad.

A: You can use Bookcision.Hope this helps.

A: This solution works previous to iOS 8.3, wish I knew what to do on 8.4 though! :

*

* Download & install an app such as iFunBox Classic (free). This app allows you to explore your iPhone files with no jailbreak required.

* Plug your iPhone/iPad into PC via USB and start iFunBox Classic.

* In iFunBox, navigate to "User Applications/Kindle/Library".

* Copy the file "AnnotationStorage" to your computer.

AnnotationStorage is an SQL database and can be read with a free app such as SQLiteBrowser.


text:
Q: React composition: expose higher-order methods Since I've seen React team have discouraged developers to use inheritance, I'm trying to use composition instead.
export class Page extends React.PureComponent {

    shouldComponentUpdate(nextProps, nextState) {
        return !isEqual(nextProps, this.props) || !isEqual(nextState, this.state);
    }

    render() {
        return this.props.children;
    }
}

const mapStateToProps = (state, ownProps) => {
    return {}
};

const mapDispatchToProps = (dispatch) => {
    return {
        onNextClick: () => dispatch(customAction())
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(Page);

export class FirstPage extends React.PureComponent {

    render() {
        return (
            <Page>

Title

                    <Button onClick={this.props.onNextClick}>Next</Button>

            </Page>
        );
    }
}

const mapStateToProps = (state, ownProps) => {
    return {}
};

const mapDispatchToProps = (dispatch) => {
    return {
        onNextClick: () => dispatch(customAction())
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(FirstPage);

In this case, several components will use Page as container and will have a next button. I'd like to expose a generic handler for the next button click in the Page component to avoid repeating the dispatch(customAction()).
I would easily achieve this with inheritance but I'm stuck with the composition pattern.
Any ideas?

A: You can use ref to refer to the Page element.

class Page extends React.Component {
  nextHandler(){
    console.log("I am in the parent.");
  }

  render(){
    return this.props.children;
  }
}

class FirstPage extends React.Component {
  render(){
    return (
      <Page ref={ page => this.page = page }>

Title

          <button onClick={ () => this.page.nextHandler() }>Next</button>

      </Page>
    )
  }
}

ReactDOM.render(<FirstPage />, document.getElementById("root"));

A: I suggest you to provide additional prop for Page children:
export class Page extends React.PureComponent {

    shouldComponentUpdate(nextProps, nextState) {
        return !isEqual(nextProps, this.props) || !isEqual(nextState, this.state);
    }

    render() {
        const {onNextClick} = this.props;
        return React.cloneElement(this.props.children, {onNextClick});
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        onNextClick: () => dispatch(customAction())
    }
};

export default connect(null, mapDispatchToProps)(Page);

export class FirstPage extends React.PureComponent {
    render() {
        return (

Title

                <Button onClick={this.props.onNextClick}>Next</Button>

        );
    }
}

export class App extends React.PureComponent {
    render() {
        return (
            <Page>
                <FirstPage />
            </Page>
        );
    }
}


text:
Q: Do PostSharp and .net demon play well together? I got the .Net Demon trial from RedGate and it seemed to be working great, but I just realized a PostSharp aspect I'm using is being ignored and I'm not sure why... wondering if it has to do with the fact that they both do stuff with the build system.
Is anyone else using them together successfuly?  I'd like to buy .Net Demon, but not if my PostSharp stuff won't work, of course.  Not sure if it's related or not yet though.

A: We (SharpCrafters) do not officially support .NET Demon. Since Demon is an incremental compiler and PostSharp does not support incremental compilation (it compiles the whole assembly every time), I doubt it could work and, if it worked, I doubt it would have any effect on performance. Since the build time is typically dominated by PostSharp, reducing the time of the C# compiler would not significantly reduce your complete build time.

A: .NET Demon compiles the whole assembly each time it compiles, including any post-build steps that are in the .csproj. I don't see why it shouldn't work. Look in the build output to see whether any logging normally produced by PostSharp is there.


text:
Q: How to get coordinate from fixed marker at center of google maps in android In my application I'm trying to get coordinate from fixed marker at center of google maps. When i scroll map, i want to get coordinate and set it on the text view.
Here is my Kotlin code:
class ActivityMapsDSPBng : AppCompatActivity(), OnMapReadyCallback, GoogleMap.OnMarkerClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
        com.google.android.gms.location.LocationListener {

    ...

    private val TAG = "ActivityMapsDSPBng"
    private lateinit var mGoogleApiClient: GoogleApiClient
    private var mLocationManager: LocationManager? = null
    lateinit var mLocation: Location
    private var mLocationRequest: LocationRequest? = null
    private val listener: com.google.android.gms.location.LocationListener? = null
    private val UPDATE_INTERVAL = (2 * 1000).toLong()
    private val FASTEST_INTERVAL: Long = 2000

    lateinit var locationManager: LocationManager

    override fun onStart() {
        ...
    }

    override fun onStop() {
        ...
    }

    override fun onConnectionSuspended(p0: Int) {
        ...
    }

    override fun onConnectionFailed(connectionResult: ConnectionResult) {
        Log.i(TAG, "Connection failed. Error: " + connectionResult.errorCode)
    }

    override fun onLocationChanged(location: Location) {
        var msg = "Update Location: Latitude " + location.latitude.toString() + " Longitude " + location.longitude.toString()
        tv_dspbg_lat.setText("" + location.latitude)
        tv_dspbg_long.setText("" + location.longitude)
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }

    override fun onConnected(p0: Bundle?) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return
        }

        startLocationUpdates()

        var fusedLocationProviderClient: FusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
        fusedLocationProviderClient.lastLocation
                .addOnSuccessListener(this, OnSuccessListener<Location> { location ->
                    if (location != null){
                        mLocation = location
                        tv_dspbg_lat.setText("" + mLocation.latitude)
                        tv_dspbg_long.setText("" + mLocation.longitude)
                    }
                })
    }

    protected fun startLocationUpdates(){
        // Create location request
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(UPDATE_INTERVAL)
                .setFastestInterval(FASTEST_INTERVAL)

        // Request location updates
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            return
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        ...

        val mapsDSPBNGfragment = supportFragmentManager
                .findFragmentById(R.id.maps_dspbg) as SupportMapFragment
        mapsDSPBNGfragment.getMapAsync(this)

        fusedLPCBg = LocationServices.getFusedLocationProviderClient(this)

        mGoogleApiClient = GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build()
        mLocationManager = this.getSystemService(Context.LOCATION_SERVICE) as LocationManager

        checkLocation()
    }

    private fun checkLocation(): Boolean{
        ...
    }

    private fun isLocationEnabled(): Boolean{
        ...
    }

    private fun showAlert(){
        val dialog = AlertDialog.Builder(this)
        dialog.setTitle("Enable Location")
                .setMessage("Your location setting is set to 'Off'. \nPlease enable location to " + "use this app")
                .setPositiveButton("Location Settings", DialogInterface.OnClickListener { paramDialogInterface, paramInt ->
                    val myIntent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                    startActivity(myIntent)
                })
                .setNegativeButton("Cancel", DialogInterface.OnClickListener { paramDialogInterface, paramInt ->  })
        dialog.show()
    }

}

I build code from https://androidteachers.com/kotlin-for-android/get-location-in-android-with-kotlin/
When I scrool maps, coordinates do not change according to the fixed maker.

A: Check my Java code. The fixed marker you are talking about is like an overlay View from your layout code. But if it's right at the center of the map, you can use the center of the camera:
mGoogleMap.setOnCameraIdleListener(new OnCameraIdleListener() {
    @Override
    public void onCameraIdle() {
            // Get the center coordinate of the map, if the overlay view is center too
            CameraPosition cameraPosition = mGoogleMap.getCameraPosition();
            LatLng currentCenter = cameraPosition.target;

            // Or get any coordinate if overlay view is not at the centered
            // int[] location = new int[2];
            // mOverlayView.getLocationInWindow(location);

            // Point viewPosition = new Point(location[0], location[1]);
            // LatLng currentCenter = mGoogleMap.getProjection().fromScreenLocation(viewPosition);
    }
}

A: To get the center location of google map
LatLng centerLatLang = mMap.getProjection().getVisibleRegion().latLngBounds.getCenter();


text:
Q: Is there a suitable name for spaces where quasi-components are singletons? I am familiar with totally disconnected spaces. All components are singletons there.
Is there some terminology for spaces that satisfy the (stronger) condition of having only quasi-components that are singletons?
I thought of a name myself (totally separated) but maybe this is in use already for something else.
Also I am willing to subject to what is already there.
Thank you.

A: I believe "totally separated" actually is the standard term already - see e.g. here or here. Note that the latter source defines "totally separated" as "for all distinct points $p,q$, there is a partition of the space into open sets $U,V$ with $p\in U$ and $q\in V$," but that's clearly equivalent to all quasicomponents being singletons.


text:
Q: Компиляция через gcc Как мне при компиляции .dll через gcc в выходных файлах скомпилировать .lib файл? Если я компилирую через clang, тогда он мне выдает как .dll, так и .lib
build.bat:
REM Build script for engine
@ECHO OFF
SetLocal EnableDelayedExpansion

REM Get a list of all the .c files.
SET cFilenames=
FOR /R %%f in (*.cpp) do (
    SET cFilenames=!cFilenames! %%f
)

REM echo "Files:" %cFilenames%

SET assembly=engine
SET compilerFlags=-g -Wvarargs -Wall -Werror
REM -Wall -Werror
SET includeFlags=-Isrc
SET linkerFlags=-luser32
SET defines=-D_DEBUG  -D_CRT_SECURE_NO_WARNINGS

ECHO "Building %assembly%%..."
g++ %cFilenames% %compilerFlags% -o ../bin/%assembly%.dll %defines% %includeFlags% %linkerFlags%

A: GCC использует для статических библиотек расширение .a, а не .lib.
Что вам выдает Clang - вообще неважно. Он может работать как в режиме совместимости с GCC, так и с MSVC - смотря как настроите.
Чтобы собрать статическую библиотеку, делаете:

*

*g++ 1.cpp -c - получаете 1.o

*ar -rcs lib1.a 1.o - получаете lib1.a - саму библиотеку.
До этого возможно стоит стереть старый файл, потому что иначе ar дописывает объектники в уже существующий файл. (Добавляет новые и перезаписывает старые, но ничего не удаляет - вроде так.)
Префикс lib... в имени файла очень рекомендуется, потому что потом, когда будете подключать либу через флаг -l??, этот префикс будет добавлен к имени автоматически...
Чтобы собрать динамическую библиотеку, делаете:

*

*g++ 1.cpp -c - получаете 1.o

*g++ 1.o -shared -o lib1.dll - получаете lib1.dll.
Современный MinGW умеет линковаться напрямую с .dll. Если у вас какая-то старая версия, то к последней команде надо добавить -Wl,--out-implib=lib1.dll.a, чтобы потом, при линковке с библиотекой указывать этот свежесозданный lib1.dll.a, а не .dll (тоже флагом -l1, lib??.dll.a дописывается автоматически).
Еще, батники - сомнительный выбор. Уж лучше потратьте время на изучение Make или CMake, тогда будет (относительно) кросс-платформенно.
И вот это в мусор: -D_DEBUG -D_CRT_SECURE_NO_WARNINGS. Это имеет только смысл для стандартной библиотеки MSVC, у GCC она своя.


text:
Q: How to make Firefox extension auto install in nav bar? I'm working on a Firefox extension. I'd like to make it auto-install in the far right position on the nav bar when a user installs it. As it stands, a user has to go to View > Toolbars > Customize... and drag the extension to the nav bar once it's installed. I'd like to eliminate this step.
The extension is here: http://madan.org/tickertool
The XUL for my extension looks basically like this and it overlays browser.xul:
<overlay id="my-ext-overlay" ... >
    <toolbarpalette id="BrowserToolbarPalette">
        <toolbaritem id="my-ext-container" ... >
            <toolbarbutton id="my-ext-customize-image" ... />
            <textbox id="my-ext-textbox" ... />
            <hbox id="my-ext-buttons">
                <image id="my-ext-button1" ... />
                <image id="my-ext-button2" ... />
                <image id="my-ext-button3" ... />
            </hbox>
        </toolbaritem>
    </toolbarpalette>
</overlay>

I've seen code here ( https://developer.mozilla.org/en/Code_snippets/Toolbar ) that supposedly does what I'm looking for, but this code is if your extension is just a single button and I can't get it to work for me. The answer to my question is likely some modification of this code, but I haven't figured it out.

A: I think I got it. It's basically spelled out in the link I mentioned in the original post. I'm not sure why I thought there was more to it than that.


text:
Q: How to remove event listener if callback is a parameterised arrow function I have a scenario where I want to remove the event listener.
    export const addEventToDropDown = (callback) => {
        document.addEventListener("keydown", (event) => {
            if (event.key === "Backspace" && document.activeElement.type === "select-one") {
                event.target.value = "";
                callback(event);
            }
        }, true);

    }

    export const removeEventListner = () => {
        //document.removeEventListener("keydown");
    }

A: You can only remove an event listener if you have a reference to it.
Since you passed an arrow function to addEventListener directly (and didn't, for example, store it in a variable and then use that variable in the call to addEventListener) you don't have a reference to it.
Therefore: You can't.

A: You can create a handler dynamically and store a reference to it in a closure.
In this way it will be possible to deregister the handler using removeEventListener
const createKeydownHandler = callback => event => {
    if (event.key === "Backspace" && document.activeElement.type === "select-one") {
        event.target.value = "";
        callback(event);
    }
};

let keydownHandler;

export const addEventToDropDown = (callback) => {
    keydownHandler = createKeydownHandler(callback);
    document.addEventListener("keydown", keydownHandler, true);
}

export const removeEventListner = () => {
    document.removeEventListener("keydown", keydownHandler)
}


text:
Q: Finding Marginal Density function of a joint density function $$f(y_1,y2) = (1/2)y_1 + (1/4)y_2,\\ 0 \le y_1 \le 1, \\0 \le y_2 \le 2
\\ 0\text{ elsewhere.} $$
How would I find the marginal density function for $Y_1$, and $Y_2$?
To find $Y_1$ you would do $f_1(y1) = \int_0^1 f(y_1,y_2)dy_2$ and for $Y_2$ you do $f1(y1) = \int_0^2 f(y_1,y_2)dy_1$.
For some strange reason when I do it out, it does not match the solutions that I have. I believe I might be doing the integration wrong. Could someone walk through it so I could see the process that you do?
Thanks

A: As mentionned,$$f_1(y_1)=
\int_0^2 f(y_1,y_2) dy_2= \int_0^2 \frac 12 y_1dy_2
 + \frac 14 \int_0^2 y_2 dy_2
= y_1 +  \frac 12
\\
f_2(y_2) = \int_0^1  f(y_1,y_2) dy_1
=\frac 12 \int_0^1 y_1dy_1 + \frac 14y_2
= \frac 14 + \frac 14y_2
$$


text:
Q: JQuery - Cycle a class with timer I've a list wit below structure

 a

 b

 c

 d

 e

I need to change the class 'active' of li's in a cycling manner
Here is the script I'm working with. issue is it either adds the class active to all li's or removes the class active from all li's
      toggleSlide = function(){
          $("#slider ul li").each(function(index) {
            if($(this).hasClass('active')){

              $("#slider ul li").removeClass('active');
              $(this).next().addClass('active'));
              //lis = $("#slider ul li")
              //$(lis[(index+1)%lis.length]).addClass('active');
            }
          });
        }
   setInterval(toggleSlide, 5000);

A: This should work a bit better:
toggleSlide = function() {
    var $active = $('#slider ul li.active');
    if($active.length == 0) {
        $active = $('#slider ul li:first');
    }
    $active.removeClass('active');
    if($active.next('li').length > 0) {
        $active.next('li').addClass('active');
    } else {
        $('#slider ul li:first').addClass('active');
    }
}
setInterval(toggleSlide, 5000);

You don't need the .each() loop and that's what was causing your issues. You only need to work on the current active element.
Live example:

http://jsfiddle.net/MS5DV/

A: I'd go for something far simpler
toggleSlide = function() {
    var active = $("#slider ul li.active");
    var next   = active.next();
    if (next.length === 0) {
        next = $('#slider ul li:first');
    }

    active.removeClass('active');
    next.addClass('active');
}
setInterval(toggleSlide, 1000);

http://jsfiddle.net/HyRYC/1/
Basically, find the active item and save it to a local var.  Then find the item after it and save that too.  Now if the last one is active, then next() will return a jQuery object with no matches, meaning it has a length of zero.  In that case, find the first item to be our next.
No we simply remove the active class from the current active item, and add it to our next one.

A: You can greatly simplify this with .add() and .last() since elements from .add() are turned in document order, it would look like this:
var toggleSlide = function(){
  $("#slider li.active").removeClass()
   .next().add("#slider li:first").last().addClass("active");
}
setInterval(toggleSlide, 5000);

You can test it here (1000ms duration for the demo)
How this works is it takes the next
 if there is one, then adds the first one as well, by using .last() (since they're in document order) we'll get the .next() one if it's there, otherwise the set only contains one element, the :first
, and we're back to the beginning.


text:
Q: Docker: Is it possible to mount a path from a different image into a docker container we have the situation, that there are files in a docker image (yes, not volume!)
and we want it to mount them in a container. The f6c1a62a47a2 is the "Image ID".
docker run -it --rm  -v f6c1a62a47a2:/target/path busybox

This command throws no errors but the content of the image is not mounted to  /target/path
in the resulting container. The mount can be readonly. We do not want to change something.
Is this possible or only with volumes?
Thanks in advance!


text:
Q: How to check android project dependencies from gradle panel?
I wan't to check the dependencies of my project and all modules. I run the script in gradle panel, but didn't find any out put after it finished.
Where can i found the output?


text:
Q: Understanding a proof about the Broccard problem I was reading the paper by Berndt and Galway,"The Brocard–Ramanujan diophantine equation $n!=m^2$. And I got stuck in the part when it says:
(1)$$n!+1=m^2$$
(2)$$\left ( \frac{n!+1}{p} \right)=1 \text{ or }0$$
Let us say that we have a "solution" if (2) holds for each of the first 40 primes
p after 10^9. Computations were performed modulo p: Except for the known cases
n = 4;5;7; we found no further "solutions" of (2). It follows that (1) also has
no further solutions up to 10^9

Why do they know that they have a "solution" if it holds for each of the first $40$ primes after $10^9?$ It is not detailed anywhere and I would like to know it, any help on understanding this is greatly appreciated.

A: By the symbol $\left( \dfrac{a}{p} \right)$, they mean the Legendre symbol, which is $1$ if $a$ is a square $\mod p$, $-1$ if $a$ is not a square $\mod p$, and $0$ if $p$ divides $a$ (we don't call $0$ a square).
Any square number will always be a square mod any prime $p$, unless that prime happens to divide that square (in which case, the Legendre symbol evaluates to $0$). So saying that $\left( \dfrac{n! + 1}{p} \right) = 1 \text{ or } 0$ for many primes is saying that $n! + 1$ behaves essentially like a square. They chose the number $40$ out of a hat (or perhaps $39$ was insufficient, which I highly doubt). I suppose they think that they think that being a square mod 40 large primes is very unlikely, unless you are actually a square. I do not know if there is an established expectation of the likelihood that a not-actual-square is a quadratic residue mod many consecutive primes - that seems like an interesting question to me.
But this doesn't matter in this case. Their 'solutions' might pick up false positive (i.e. not-squares that look like squares) but won't pick up any false negatives. And they don't find any 'solutions' except the known ones. Note that they only have to check a finite number of cases, since they're checking the value of the Legendre symbol up to approximately $10^9$ 40 times. Since they found no 'solution,' there cannot be an actual solution either.


text:
Q: If I use $_POST value directly in bindParam (mysqli) will there be a security issue? I have been reading about using $_POST values being used directly in isert statements and understand that this is an invitation for trouble. What is not clear in any of the posts I read was -
Say my form is sending 7 items to my mysqli insertion script and I use the posted values like this:
    $stmt = $mysqli->prepare("INSERT INTO `advertisements` (`from`, `r_u_res`, `email`, `blockname`, `floorno`, `doorno`, `content`) VALUES (?, ?, ?, ?, ?,?,?)");
    $stmt->bind_param('sssssss', $_POST['from'], $_POST['rures'], $_POST['email'], $_POST['blockname'], $_POST['floorno'], $_POST['doorno'], $_POST['content']);

    $stmt->execute();
    $stmt->close();

Would that be the correct way to do it? Or should I first store the posted values in a new variable and use that variable while binding? - like this :
    $postedfrom = $_POST['from'];
    $postedrures = $_POST['rures'];
    $postedemail = $_POST['email'];
    $postedblockname = $_POST['blockname'];
    $postedfloorno = $_POST['floorno'];
    $posteddoorno = $_POST['doorno'];
    $postedcontent = $_POST['content'];

    $stmt = $mysqli->prepare("INSERT INTO `advertisements` (`from`, `r_u_res`, `email`, `blockname`, `floorno`, `doorno`, `content`) VALUES (?, ?, ?, ?, ?,?,?)");
    $stmt->bind_param('sssssss', $postedfrom, $postedrures, $postedemail, $postedblockname, $postedfloorno, $posteddoorno, $postedcontent);

    $stmt->execute();
    $stmt->close();

I saw a post OO mysqli prepared statements help please where the answer does seem to be like the code above but I want to know whether doing it like the first code poses security issues...

A: both forms are equivalent from a security perspective as php first resolves the values to be passed in the method call to $stmt->bind_param, thus that function sees the exact same values in both cases.
ps: both snippets look ok to me.


text:
Q: Pandas / pyplot histogram: can plot df but not subset df is an enormous dataframe.  I only need the subset where Zcoord > 1.
df = pandas.DataFrame(first)
df.columns = ['Xcoord', 'Ycoord', 'Zcoord', 'Angle']
df0 = df[df.Zcoord>1]

The very same code that will draw a histogram of df will not work for df0.
plot1 = plt.figure(1)
plt.hist(df0.Zcoord, bins=100, normed=False)
plt.show()

Ipython spits out KeyError:0.
python 2.7.9 anaconda, ipython 2.2.0, OS 10.9.4
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-42-71643df3888f> in <module>()
      1 plot1 = plt.figure(1)
----> 2 plt.hist(df0.Zcoord, bins=100, normed=False)
      3
      4 plt.show()
      5 from matplotlib.backends.backend_pdf import PdfPages

/Users/Kit/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.pyc in hist(x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, hold, **kwargs)
   2888                       histtype=histtype, align=align, orientation=orientation,
   2889                       rwidth=rwidth, log=log, color=color, label=label,
-> 2890                       stacked=stacked, **kwargs)
   2891         draw_if_interactive()
   2892     finally:

/Users/Kit/anaconda/lib/python2.7/site-packages/matplotlib/axes/_axes.pyc in hist(self, x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, **kwargs)
   5560         # Massage 'x' for processing.
   5561         # NOTE: Be sure any changes here is also done below to 'weights'
-> 5562         if isinstance(x, np.ndarray) or not iterable(x[0]):
   5563             # TODO: support masked arrays;
   5564             x = np.asarray(x)

/Users/Kit/anaconda/lib/python2.7/site-packages/pandas/core/series.pyc in __getitem__(self, key)
    482     def __getitem__(self, key):
    483         try:
--> 484             result = self.index.get_value(self, key)
    485
    486             if not np.isscalar(result):

/Users/Kit/anaconda/lib/python2.7/site-packages/pandas/core/index.pyc in get_value(self, series, key)
   1194
   1195         try:
-> 1196             return self._engine.get_value(s, k)
   1197         except KeyError as e1:
   1198             if len(self) > 0 and self.inferred_type in ['integer','boolean']:

/Users/Kit/anaconda/lib/python2.7/site-packages/pandas/index.so in pandas.index.IndexEngine.get_value (pandas/index.c:2993)()

/Users/Kit/anaconda/lib/python2.7/site-packages/pandas/index.so in pandas.index.IndexEngine.get_value (pandas/index.c:2808)()

/Users/Kit/anaconda/lib/python2.7/site-packages/pandas/index.so in pandas.index.IndexEngine.get_loc (pandas/index.c:3440)()

KeyError: 0

A: You are passing a pandas.Series to matplotlib (df0.Zcoord).  However, at the moment, matplotlib is a bit indecisive about whether or not it likes being fed pandas datatypes (as opposed to numpy ndarray's).
At some point in the bowels of the matplotlib source, the histogram function is probably trying to get the "first item I've been asked to deal with", and it probably does that with a call to input[0] where input is whatever it was asked to chew on.  If input is a numpy.ndarray then everything works great.  However, if input is a pandas.Series or (even worse) a pandas.DataFrame, the expression input[0] will have a very different meaning.  In that case, depending on the structure of the data you fed to plt.hist, there could well be a KeyError when trying to index into your input.
In your particular case, this is probably working fine on df as a whole because df likely has an integer index ([0, 1, 2, ..., len(df)-1]), which is the default row index in a DataFrame.  However, when you select within df to make df0, the result keeps winds up with an index that is a subset of the index of df (maybe it winds up [3, 6, 9, 12, ...]).  So everything works fine on df (where the index contains 0), but blows chunks on df0 (where, ironically, given its name, 0 does not appear in the index).
Quick fix...instead of
plt.hist(df0.Zcoord, bins=100, normed=False)

run this
plt.hist(df0.Zcoord.values, bins=100, normed=False)

and my guess is everything will be good.


text:
Q: Creating a data frame with mean, standard deviation, standard error and confidence error I am trying to create a new data frame with each variable's mean, standard deviation(sd), standard error(se) and confidence interval(ci) with this data frame.
pct.df <- structure(list(group = c("a", "a", "a", "b", "b", "b"), gender = c("male",
"female", "male", "female", "male", "female"), var_a = c(33.3333333333333,
16.6666666666667, 50, 50, 50, 33.3333333333333), var_b = c(50,
75, 50, 75, 75, 75), var_c = c(50, 75, 75, 100, 75, 75), var_d = c(50,
25, 0, 25, 50, 50), var_e = c(25, 0, 50, 0, 50, 25), var_f = c(25,
25, 0, 50, 50, 25), var_g = c(25, 25, 0, 50, 50, 25), var_h = c(25,
25, 0, 50, 50, 25), avg = c(35.4166666666667, 33.3333333333333,
28.125, 50, 56.25, 41.6666666666667)), class = "data.frame", row.names = c(NA,
-6L))

I would like to compare group A and group B's mean for each variable (i.e. val_a to val_h and avg).
I currently know how to calculate the mean.
sum.df <- pct.df %>%
  group_by(group) %>%
  summarise_if(is.numeric, mean) %>%
  pivot_longer(cols = -group, names_to = "Variable")

However, I am also trying to get the sd,se and ci of each var_ in the same data frame.
I tried my hand in using something like this from https://www.r-graph-gallery.com/4-barplot-with-error-bar.html to get what I want.
my_sum <- data %>%
  group_by(Species) %>%
  summarise(
    n=n(),
    mean=mean(Sepal.Length),
    sd=sd(Sepal.Length)
  ) %>%
  mutate( se=sd/sqrt(n))  %>%
  mutate( ic=se * qt((1-0.05)/2 + .5, n-1))

but I cant quite get it to work (due to the lack of understanding in how I should approach it with multiple variables). I am new to R and I would appreciate any advice or alternative methods I should look into.
Note- Ideally to an output that looks something like this?
    group Variables mean sd se  ci
1      a     var_a   38 16 22  54
2      a     var_b   69 24 45  93
3      a     var_c   75 20 55  95
4      a     var_d   44 12 32  56
5      a     var_e   31 24  7  55
6      a     var_f   38 14 24  52
7      a     var_g   38 14 24  52
8      a     var_h   38 14 24  52
9      a       AVG   46 14 32  60
10     b     var_a   58 29 29  87
11     b     var_b   81 12 69  93
12     b     var_c   88 14 74 102
13     b     var_d   56 31 25  87
14     b     var_e   56 31 25  87
15     b     var_f   56 31 25  87
16     b     var_g   56 31 25  87
17     b     var_h   56 31 25  87
18     b       AVG   64 25 39  89

A: Based on your comments and updated post, this solution will work:
library(tidyverse)
pct.df <- structure(list(group = c("a", "a", "a", "b", "b", "b"), gender = c("male",
                                                                             "female", "male", "female", "male", "female"), var_a = c(33.3333333333333,
                                                                                16.6666666666667, 50, 50, 50, 33.3333333333333), var_b = c(50,
                                                                                75, 50, 75, 75, 75), var_c = c(50, 75, 75, 100, 75, 75), var_d = c(50,
                                                                                25, 0, 25, 50, 50), var_e = c(25, 0, 50, 0, 50, 25), var_f = c(25,
                                                                                25, 0, 50, 50, 25), var_g = c(25, 25, 0, 50, 50, 25), var_h = c(25,
                                                                                25, 0, 50, 50, 25), avg = c(35.4166666666667, 33.3333333333333,
                                                                                28.125, 50, 56.25, 41.6666666666667)), class = "data.frame", row.names = c(NA,
                                                                                -6L))
pct.df %>%
  pivot_longer(-c(group, gender, avg), names_to = "variable") %>%
  group_by(group, variable) %>%
  summarise(n = n(),
            mean = mean(value),
            sd = sd(value),
            se = sd/sqrt(n),
            ic = se * qt((1-0.05)/2 + .5, n-1)) %>%
  select(-n) %>%
  bind_rows(summarise(., across(everything(),
                                ~if(is.numeric(.)) mean(.) else "AVG"))) %>%
  arrange(group)
#> `summarise()` has grouped output by 'group'. You can override using the `.groups` argument.
#> # A tibble: 18 x 6
#> # Groups:   group [2]
#>    group variable  mean    sd    se    ic
#>    <chr> <chr>    <dbl> <dbl> <dbl> <dbl>
#>  1 a     var_a     33.3 16.7   9.62  41.4
#>  2 a     var_b     58.3 14.4   8.33  35.9
#>  3 a     var_c     66.7 14.4   8.33  35.9
#>  4 a     var_d     25   25    14.4   62.1
#>  5 a     var_e     25   25    14.4   62.1
#>  6 a     var_f     16.7 14.4   8.33  35.9
#>  7 a     var_g     16.7 14.4   8.33  35.9
#>  8 a     var_h     16.7 14.4   8.33  35.9
#>  9 a     AVG       32.3 17.4  10.0   43.1
#> 10 b     var_a     44.4  9.62  5.56  23.9
#> 11 b     var_b     75    0     0      0
#> 12 b     var_c     83.3 14.4   8.33  35.9
#> 13 b     var_d     41.7 14.4   8.33  35.9
#> 14 b     var_e     25   25    14.4   62.1
#> 15 b     var_f     41.7 14.4   8.33  35.9
#> 16 b     var_g     41.7 14.4   8.33  35.9
#> 17 b     var_h     41.7 14.4   8.33  35.9
#> 18 b     AVG       49.3 13.3   7.71  33.2

Created on 2021-07-10 by the reprex package (v2.0.0)

A: Here is a similar method without pivoting the data.
this method relies on the fact that summarise can also return a vector of summarys.
pct.df %>%
  group_by(group) %>%
  summarise(
    val = c("mean", "sd", "n", "se", "ic"),
    across(
      where(is.numeric),
      ~c(mean(.x), sd(.x),length(.x), sd(.x) / length(.x),
         sd(.x) / length(.x) * qt((1-0.05)/2 + .5, length(.x) - 1))
    ), .groups = "drop"
  )

# A tibble: 10 x 11
   group val   var_a var_b var_c var_d var_e var_f var_g var_h   avg
   <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1 a     mean  33.3  58.3  66.7  25    25    16.7  16.7  16.7  32.3
 2 a     sd    16.7  14.4  14.4  25    25    14.4  14.4  14.4   3.76
 3 a     n      3     3     3     3     3     3     3     3     3
 4 a     se     5.56  4.81  4.81  8.33  8.33  4.81  4.81  4.81  1.25
 5 a     ic    23.9  20.7  20.7  35.9  35.9  20.7  20.7  20.7   5.39
 6 b     mean  44.4  75    83.3  41.7  25    41.7  41.7  41.7  49.3
 7 b     sd     9.62  0    14.4  14.4  25    14.4  14.4  14.4   7.32
 8 b     n      3     3     3     3     3     3     3     3     3
 9 b     se     3.21  0     4.81  4.81  8.33  4.81  4.81  4.81  2.44
10 b     ic    13.8   0    20.7  20.7  35.9  20.7  20.7  20.7  10.5