text:
Q: How can we find gaps in sequential numbering in MySQL? We have a database with a table whose values were imported from another system. There is an auto-increment column, and there aren't any duplicate values, but there are missing values. For example, running this query:
select count(id) from arrc_vouchers where id between 1 and 100

should return 100, but it returns 87 instead. Is there a query I can run that will return the values of the missing numbers? For example, the records may exist for id 1-70 and 83-100, but there aren't any records with id's of 71-82. I want to return 71, 72, 73, etc.
Is this possible?

A: An alternative solution that requires a query + some code doing some processing would be:
select l.id lValue, c.id cValue, r.id rValue
  from
  arrc_vouchers l
  right join arrc_vouchers c on l.id=IF(c.id > 0, c.id-1, null)
  left  join arrc_vouchers r on r.id=c.id+1
where 1=1
  and c.id > 0
  and (l.id is null or r.id is null)
order by c.id asc;

Note that the query does not contain any subselect that we know it's not handled performantly by MySQL's planner.
That will return one entry per centralValue (cValue) that does not have a smaller value (lValue) or a greater value (rValue), i.e.:
lValue |cValue|rValue
-------+------+-------
{null} | 2    | 3
8      | 9    | {null}
{null} | 22   | 23
23     | 24   | {null}
{null} | 29   | {null}
{null} | 33   | {null}

Without going into further details (we'll see them in next paragraphs) this output means that:

*

*No values between 0 and 2

*No values between 9 and 22

*No values between 24 and 29

*No values between 29 and 33

*No values between 33 and MAX VALUE

So the basic idea is to do a RIGHT and LEFT joins with the same table seeing if we have  adjacents values per value (i.e., if central value is '3' then we check for 3-1=2 at left and 3+1 at right), and when a ROW has a NULL value at RIGHT or LEFT then we know there is no adjacent value.
The complete raw output of my table is:
select * from arrc_vouchers order by id asc;

0
2
3
4
5
6
7
8
9
22
23
24
29
33

Some notes:

*

*The SQL IF statement in the join condition is needed if you define the 'id' field as UNSIGNED, therefore it will not allow you to decrease it under zero. This is not strictly necessary if you keep the c.value > 0 as it's stated in the next note, but I'm including it just as doc.

*I'm filtering the zero central value as we are not interested in any previous value and we can derive the post value from the next row.

A: If there is a sequence having gap of maximum one between two numbers (like
1,3,5,6) then the query that can be used is:
select s.id+1 from source1 s where s.id+1 not in(select id from source1) and s.id+1<(select max(id) from source1);

*

*table_name - source1

*column_name - id

A: I tried it in a different manner, and the best performance that I found was this simple query:
select a.id+1 gapIni
    ,(select x.id-1 from arrc_vouchers x where x.id>a.id+1 limit 1) gapEnd
    from arrc_vouchers a
    left join arrc_vouchers b on b.id=a.id+1
    where b.id is null
    order by 1
;

... one left join to check if the next id exists, only if next if is not found, then the subquery finds the next id that exists to find the end of gap. I did it because the query with equal (=) is better performance than the greater than (>) operator.
Using the sqlfiddle it does not show so a different performance compared to the other queries, but in a real database this query above results in 3 times faster than the others.
The schema:
CREATE TABLE arrc_vouchers (id int primary key)
;
INSERT INTO `arrc_vouchers` (`id`) VALUES (1),(4),(5),(7),(8),(9),(10),(11),(15),(16),(17),(18),(19),(20),(21),(22),(23),(24),(25),(26),(27),(28),(29)
;

Follow below all the queries that I made to compare the performance:
select a.id+1 gapIni
    ,(select x.id-1 from arrc_vouchers x where x.id>a.id+1 limit 1) gapEnd
    from arrc_vouchers a
    left join arrc_vouchers b on b.id=a.id+1
    where b.id is null
    order by 1
;
select *, (gapEnd-gapIni) qt
    from (
        select id+1 gapIni
        ,(select x.id from arrc_vouchers x where x.id>a.id limit 1) gapEnd
        from arrc_vouchers a
        order by id
    ) a where gapEnd <> gapIni
;
select id+1 gapIni
    ,(select x.id from arrc_vouchers x where x.id>a.id limit 1) gapEnd
    #,coalesce((select id from arrc_vouchers x where x.id=a.id+1),(select x.id from arrc_vouchers x where x.id>a.id limit 1)) gapEnd
    from arrc_vouchers a
    where id+1 <> (select x.id from arrc_vouchers x where x.id>a.id limit 1)
    order by id
;
select id+1 gapIni
    ,coalesce((select id from arrc_vouchers x where x.id=a.id+1),(select x.id from arrc_vouchers x where x.id>a.id limit 1)) gapEnd
    from arrc_vouchers a
    order by id
;
select id+1 gapIni
    ,coalesce((select id from arrc_vouchers x where x.id=a.id+1),concat('*** GAT *** ',(select x.id from arrc_vouchers x where x.id>a.id limit 1))) gapEnd
    from arrc_vouchers a
    order by id
;

You can see and test my query using this SQL Fiddle:
http://sqlfiddle.com/#!9/6bdca7/1

A: Create a temporary table with 100 rows and a single column containing the values 1-100.
Outer Join this table to your arrc_vouchers table and select the single column values where the arrc_vouchers id is null.
This should work:
select tempid from temptable
left join arrc_vouchers on temptable.tempid = arrc_vouchers.id
where arrc_vouchers.id is null

A: It is probably not relevant, but I was looking for something like this to list the gaps in a sequence of numbers and found this post that has multiple different solutions depending upon exactly what you are looking for.  I was looking for the first available gap in the sequence (i.e., next available number), and this seems to work fine.
SELECT MIN(l.number_sequence + 1) as nextavabile
from patients as l
LEFT OUTER JOIN patients as r on l.number_sequence + 1 = r.number_sequence
WHERE r.number_sequence is NULL

Several other scenarios and solutions discussed there, from 2005!
How to Find Missing Values in a Sequence With SQL

A: A better answer
JustPlainMJS provided a much better answer in terms of performance.
The (not as fast as possible) answer
Here's a version that works on a table of any size (not just on 100 rows):
SELECT (t1.id + 1) as gap_starts_at,
       (SELECT MIN(t3.id) -1 FROM arrc_vouchers t3 WHERE t3.id > t1.id) as gap_ends_at
FROM arrc_vouchers t1
WHERE NOT EXISTS (SELECT t2.id FROM arrc_vouchers t2 WHERE t2.id = t1.id + 1)
HAVING gap_ends_at IS NOT NULL

*

*gap_starts_at - first id in current gap

*gap_ends_at - last id in current gap

A: This just worked for me to find the gaps in a table with more than 80k rows:
SELECT
  CONCAT(z.expected, IF(z.got-1>z.expected, CONCAT(' thru ',z.got-1), '')) AS missing
FROM (
  SELECT
    @rownum:=@rownum+1 AS expected,
    IF(@rownum=YourCol, 0, @rownum:=YourCol) AS got
  FROM
    (SELECT @rownum:=0) AS a
    JOIN YourTable
    ORDER BY YourCol
  ) AS z
WHERE z.got!=0;

Result:
+------------------+
| missing          |
+------------------+
| 1 thru 99        |
| 666 thru 667     |
| 50000            |
| 66419 thru 66456 |
+------------------+
4 rows in set (0.06 sec)

Note that the order of columns expected and got is critical.
If you know that YourCol doesn't start at 1 and that doesn't matter, you can replace
(SELECT @rownum:=0) AS a

with
(SELECT @rownum:=(SELECT MIN(YourCol)-1 FROM YourTable)) AS a

New result:
+------------------+
| missing          |
+------------------+
| 666 thru 667     |
| 50000            |
| 66419 thru 66456 |
+------------------+
3 rows in set (0.06 sec)

If you need to perform some kind of shell script task on the missing IDs, you can also use this variant in order to directly produce an expression you can iterate over in Bash.
SELECT GROUP_CONCAT(IF(z.got-1>z.expected, CONCAT('$(',z.expected,' ',z.got-1,')'), z.expected) SEPARATOR " ") AS missing
FROM ( SELECT @rownum:=@rownum+1 AS expected, IF(@rownum=height, 0, @rownum:=height) AS got FROM (SELECT @rownum:=0) AS a JOIN block ORDER BY height ) AS z WHERE z.got!=0;

This produces an output like so
$(seq 1 99) $(seq 666 667) 50000 $(seq 66419 66456)

You can then copy and paste it into a for loop in a bash terminal to execute a command for every ID
for ID in $(seq 1 99) $(seq 666 667) 50000 $(seq 66419 66456); do
  echo $ID
  # Fill the gaps
done

It's the same thing as above, only that it's both readable and executable. By changing the "CONCAT" command above, syntax can be generated for other programming languages. Or maybe even SQL.

A: A quick-and-dirty query that should do the trick:
SELECT a AS id, b AS next_id, (b - a) -1 AS missing_inbetween
FROM
 (
SELECT a1.id AS a , MIN(a2.id) AS b
FROM arrc_vouchers  AS a1
LEFT JOIN arrc_vouchers AS a2 ON a2.id > a1.id
WHERE a1.id <= 100
GROUP BY a1.id
) AS tab

WHERE
b > a + 1

This will give you a table showing the id that has ids missing above it, and next_id that exists, and how many are missing between... E.g.,

id  next_id  missing_inbetween
 1        4                  2
68       70                  1
75       87                 11

A: If you are using a MariaDB database, you have a faster (800%) option using the sequence storage engine:
SELECT * FROM seq_1_to_50000 WHERE SEQ NOT IN (SELECT COL FROM TABLE);

A: Although these all seem to work, the result set returns in a very lengthy time when there are 50,000 records.
I used this, and it find the gap or the next available (last used + 1) with a much faster return from the query.
SELECT a.id as beforegap, a.id+1 as avail
FROM table_name a
where (select b.id from table_name b where b.id=a.id+1) is null
limit 1;

A: Based on the answer given by matt, this stored procedure allows you to specify the table and column names that you wish to test to find non-contiguous records - thus answering the original question and also demonstrating how one could use @var to represent tables &/or columns in a stored procedure.
create definer=`root`@`localhost` procedure `spfindnoncontiguous`(in `param_tbl` varchar(64), in `param_col` varchar(64))
language sql
not deterministic
contains sql
sql security definer
comment ''
begin
declare strsql varchar(1000);
declare tbl varchar(64);
declare col varchar(64);

set @tbl=cast(param_tbl as char character set utf8);
set @col=cast(param_col as char character set utf8);

set @strsql=concat("select
    ( t1.",@col," + 1 ) as starts_at,
  ( select min(t3.",@col,") -1 from ",@tbl," t3 where t3.",@col," > t1.",@col," ) as ends_at
    from ",@tbl," t1
        where not exists ( select t2.",@col," from ",@tbl," t2 where t2.",@col," = t1.",@col," + 1 )
        having ends_at is not null");

prepare stmt from @strsql;
execute stmt;
deallocate prepare stmt;
end

A: A simple, yet effective, solution to find the missing auto-increment values:
SELECT `id`+1
FROM `table_name`
WHERE `id`+1 NOT IN (SELECT id FROM table_name)

A: Another simple answer that identifies the gaps. We do a query selecting just the odd numbers and we right join it to a query with all the even numbers. As long as you're not missing id 1; this should give you a comprehensive list of where the gaps start.
You'll still have to take a look at that place in the database to figure out how many numbers the gap is. I found this way easier than the solution proposed and much easier to customize to unique situations.
SELECT *
FROM (SELECT * FROM MyTABLE WHERE MYFIELD % 2 > 0) AS A
RIGHT JOIN FROM (SELECT * FROM MyTABLE WHERE MYFIELD % 2 = 0) AS B
ON A.MYFIELD=(B.MYFIELD+1)
WHERE a.id IS NULL;

A: Starting from the comment posted by user933161,
select l.id + 1 as start from sequence as l inner join sequence as r on l.id + 1 = r.id where r.id is null;

is better in that it will not produce a false positive for the end of the list of records.  (I'm not sure why so many are using left outer joins.)
Also,
insert into sequence (id) values (#);

where # is the start value for a gap will fill that start value.  (If there are fields that cannot be null, you will have to add those with dummy values.)
You could alternate between querying for start values and filling in each start value until the query for start values returns an empty set.
Of course, this approach would only be helpful if you're working with a small enough data set that manually iterating like that is reasonable.  I don't know enough about things like phpMyAdmin to come up with ways to automate it for larger sets with more and larger gaps.

A: This works for me:
SELECT distinct(l.membership_no + 1) as nextavabile
from Tablename as l
LEFT OUTER JOIN Tablename as r on l.membership_no + 1 = r.membership_no
WHERE r.membership_no is NULL and l.membership_no is not null order by nextavabile asc;

A: CREATE TABLE arrc_vouchers (id int primary key);
INSERT INTO `arrc_vouchers` (`id`) VALUES (1),(4),(5),(7),(8),(9),(10),(11),(15),(16);

WITH RECURSIVE odd_num_cte (id) AS
(
    SELECT (select min(id) from arrc_vouchers)
    union all
    SELECT id+1 from odd_num_cte where id <(SELECT max(id) from arrc_vouchers)
)
SELECT cte.id
from arrc_vouchers ar right outer join odd_num_cte cte on ar.id=cte.id
where ar.id is null;


text:
Q: PostgreSQL - Failed to prepare query: ERROR: column "referenceno" does not exist This is probably a really obvious mistake, but I have been trying a number of things and I do not seem to be able to get the right answer.
From R, I try to execute the following DELETE SQL statement on a PostgreSQL database hosted by Digital Ocean.
sql <- "DELETE FROM tablename WHERE referenceNo IN (380,376,344,345)"
conn %>% dbExecute(sql)

I get the following error and I am unable to find the correct syntax.
Error: Failed to prepare query: ERROR:  column "referenceno" does not exist
LINE 1: DELETE FROM tablename WHERE referenceNo IN (380,37...
                                    ^
HINT:  Perhaps you meant to reference the column "tablename.referenceNo".

I have tried to follow the hint and tried SQL syntax like:
sql <- "DELETE FROM tablename WHERE tablename.referenceNo IN (380,376,344,345)"

Unfortunately, I get the same error message.

A: i already slove a problem like your's by using : "columns" and not columns,
DELETE FROM tablename WHERE "referenceNo" IN (380,376,344,345)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to correctly instantiate mContentView in RecyclerView's ViewHolder, to avoid Null Object Reference? When I attempt to set a string as the value of mContentView for my ViewHolder, Android studio says that I am creating a null object reference:
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    holder.mItem = mValues.get(position);
    holder.mContentView.setText(mValues.get(position).getName());

}

Error Message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.gatech.astroworld.spacetrader, PID: 10155
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
    at com.gatech.astroworld.spacetrader.views.market.Buy_Item_RecyclerAdapter.onBindViewHolder(Buy_Item_RecyclerAdapter.java:49)

Basically, my question is: How do I instantiate mContentView, so I can avoid the null object reference?
Here is ViewHolder class:
public class ViewHolder extends RecyclerView.ViewHolder {
    public View mView;
    public TextView mIdView;
    public TextView mContentView;
    public Store.MarketGood mItem;
    public int textCount = 0;

    public ViewHolder(View view) {
        super(view);
        mView = view;
        mIdView = view.findViewById(R.id.item_number);
        mContentView = view.findViewById(R.id.content);
        final TextView itemCountText = view.findViewById(R.id.countText);
        final TextView showName = view.findViewById(R.id.itemName);
        Button plusButton = mView.findViewById(R.id.plusButton);
        Button minusButton = mView.findViewById(R.id.minusButton);

        plusButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //showName.setText(mItem.getName());
                store.incrementCountBuy(mItem);
                itemCountText.setText(String.valueOf(mItem.getCount()));
            }
        });

        minusButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                store.decrementCountBuy(mItem);
                itemCountText.setText(String.valueOf(mItem.getCount()));
            }
        });
    }

A: See my adapter as an example:
public class AdapterAssetList extends RecyclerView.Adapter<AdapterAssetList.ViewHolderAssets> {
private final LayoutInflater layoutInflater;
OnItemClickListener itemClickListener;

Context context;
private ImageLoader imageLoader;

public AdapterAssetList(Context mContext, ArrayList<Asset> assetList) {
    this.context = mContext;
    this.assetList = assetList;
    layoutInflater = LayoutInflater.from(context);
}

@NonNull
@Override
public ViewHolderAssets onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view = layoutInflater.inflate(R.layout.dashboard_asset_childs, viewGroup, false);
    ViewHolderAssets viewHolderAssets = new ViewHolderAssets(view);
    return viewHolderAssets;
}

@Override
public void onBindViewHolder(@NonNull final ViewHolderAssets holder, int position) {
    imageLoader = VolleySingleton.getInstance(context).getImageLoader();
    holder.assetName.setText(assetList.get(position).getName());
    holder.assetValue.setText(withSuffix((long) assetList.get(position).getValue()));
}

@Override
public int getItemCount() {
    if (assetList == null)
        assetList = new ArrayList<>();
    return assetList.size();
}

public void SetOnItemClickListener(final OnItemClickListener mItemClickListener) {
    this.itemClickListener = mItemClickListener;
}

public void removeAt(int position) {
    //subsPlanList.remove(position);
    notifyItemRemoved(position);
    //notifyItemRangeChanged(position, subsPlanList.size());
}

public interface OnItemClickListener {
    public void onItemClick(View view, int position, String id);
}

public class ViewHolderAssets extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView assetName;
    TextView assetValue;

    public ViewHolderAssets(@NonNull View itemView) {
        super(itemView);
        assetName = itemView.findViewById(R.id.txt_asset_name);
        assetValue = itemView.findViewById(R.id.txt_asset_value);

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        itemClickListener.onItemClick(v, getAdapterPosition(), "copyright");
    }
}

}

Note: your ViewHOlder should be inner class of your adapter.

A: You can create an inner class for your viewHolder and extend RecyclerView.ViewHolder. Then a add a method like bindData in your new viewHolder class and add user implementation. Once this is complete, call the bindData from the onBindViewHolder method.
Eg: https://github.com/Kartikkumargujarati/Android-RR/blob/b6baa006477377aeef6e614f4291760fff324dfb/Networking/app/src/main/java/com/kartik/networking/ui/GitHubListAdapter.kt#L26


text:
Q: Concatenating cells in Excel ignoring blank cells I've searched through the site but can't seem to see anything that fits my problem.
I have 7 columns
User ID
Session1
session2
session3
session4
session5
session6
Within the sessions 1-6, there will be a P or A to represent whether the user was "present" or "Absent".
Based on this master data, I have created a further 6 columns to the right of this will the same headings and input IF statements to say =IF(B2="P","",B$1) so that it will show the Session ID if the user was absent from that session.
I then need to have all the users absent sessions within one column and that needs to be sepearated by commas.
What I can't work out is how to get this without have duplicate commas where the cells are blank.
Any ideas?
Thanks
James

A: Pick up the StringConcat UDF given at the link C Pearson Concatenation page. Copy the code starting from Function StringConcat(Sep As String, ParamArray Args()) As Variant upto the end, and paste it in a general module in VBA. If you don't know how to do this, refer this link which explains it all.
This UDF will ignore blanks, and concatenate any given range with a separator/delimiter of your choice.
Your solution then simply becomes
=StringConcat(", ",H2:M2)
Let me know if something isn't clear.
Alternate Solution :
Alternatively, modify your formulae as follows.
In cell H2, instead of =IF(B2="P","",B$1) , enter the following formula
=IF(B2="A",B$1&", ","")

Copy this formula upto M2, and down as many rows as you want.
Now, in cell N2, put the following formula:
=IF(LEN(H2&I2&J2&K2&L2&M2)>2,LEFT(H2&I2&J2&K2&L2&M2,LEN(H2&I2&J2&K2&L2&M2)-2),"")

Hope this helps.


text:
Q: applescript find default application for a file type This is my first time using applescript, I'm trying to open a file from a website in the default application for that file type and am not sure how to do it.
For example:
The file http://test.com/1234.docx should open in OpenOffice if they have that installed.
I can only get it to open in Safari, which I don't want because we use WebDav so the file is editable.
Is there any way to find the default text editor and open a url with that program?

A: You can use Finder's open command to open a file in the default application:
tell application "Finder"
    open POSIX file "/Library/Desktop Pictures/Abstract.jpg"
end tell

default application of (info for) gets the default application:
tell application "Finder"
    default application of (info for POSIX file "/Library/Desktop Pictures/Abstract.jpg")
end tell

You can use perl to get the default application for a URL scheme:
VERSIONER_PERL_PREFER_32_BIT=1 perl -MMac::InternetConfig -le 'print +(GetICHelper "mailto")[1]'


text:
Q: Newtons Third Law. How is jumping from a pier different to jumping from a boat? This is the absolute basic of a physics and yet 2 hours of googling fails to find an answer ! So ignoring all vertical movement and just concentrating on the horizontal movement:-

*

*A man who weighs 75 kg jumps off a pier (steps off horizontally) with a force of 150N. Ignoring gravity he accelerates by 2 meters per sec per sec.

*A man who weighs 75kg jumps off (steps off horizontally) a boat that weighs 75 kg with a force of 150N. Ignoring gravity he accelerates by 2 meters per sec per sec. So does the boat (it accelerates by same amount), but in the opposite direction.

*What is wrong here? Im sure the boat and the man would end up at half the speed in each direction compared to example 1. Example 2 sounds like free energy compared to example one. What am I missing, apart from a working version of google, and an easy way to format this text?

*p.s.  I think one of my key confusions is in example 2,  is the acceleration relative to a point in space or is the acceleration relative to the other body. I.e. do they accelerate away from each other at 2m per sec^2 or 4m per sec^2? I guess my other confusion is if they are accelerating away at twice the rate then I appear to be doing twice the amount of work for the same amount of force applied which seems odd, and feels like free energy.

A: Good question, though you have stated it a little imprecisely I think. So first I will state the question more precisely.
Scenario 1. Man leaps from pier, such that the force between himself and the ground, in the horizontal direction, reaches 150 N (for some length of time to be discussed).
Scenario 2. Man leaps from a boat having the same mass as the man, such that the force between himself and the boat, in the horizontal direction, reaches 150 N (for some length of time to be discussed).
You are correct to suppose that in both cases the acceleration of the man, relative to some convenient frame of reference such as planet Earth, reaches the same value in the two scenarios at the moment when the force reaches 150 N. But in the second scenario the man will find it harder to get the force to reach that value, because the boat is being pushed away as his legs get straighter. He could do it, but he would find that he had to expend more energy.
To find the final velocity of the man in the two cases, you can use either energy or momentum. In terms of momentum, what you need to know is the length of time for which any give force is applied. Leaping from a pier, a man can get to some given force pretty quickly, before his body has moved very much, and then maintain that force for, let's say, half a second. So he gets the momentum approximately 75 kg m/s. Leaping from a boat, the force will rise from zero more slowly, so will take longer to get to 150 N. So he will only manage to apply 150 N for some shorter time. His final momentum will therefore be lower than in first case.
Next let's think about energy. Now we have to consider the distance over which the centre of mass of the man moved while the force applied to the centre of mass was 150 N. Leaping from the pier, this distance is approximately the distance by which his legs extended from the crouch to the leap. Leaping from the boat, since the boat moves away, his centre of mass moves by about the half the distance of the first case. Therefore the energy delivered to the man in the second case is about half that of the first case. On this estimate the man does the same work in the two cases, but when leaping from the boat half of the work goes to kinetic energy of the boat, and half to the man, whereas in the first case the man gets all the kinetic energy (the change in motion of the pier being negligible).

A: To avoid getting sidetracked into questions of how muscles work, let's replace the man with a sack of potatoes with a mass of $75$ kg and let's suppose the force is provided by a compressed spring which produces an initial force of $150$ N when it is released.
If the sack of potatoes is on a pier (or on the ground) then the spring exerts a force of $150$ N on the sack and (by Newton's third law) on the pier. The man has a mass of $75$ kg and so initially accelerates at $2$ metres per second per second. The pier has (effectively) the mass of the whole Earth, so its acceleration is negligible. If the sack travels a small distance $d$ (small enough so that the force exerted by the spring does not change) the work done by the spring is $150d$ Joules. This energy was originally potentially energy in the compressed spring, and becomes the kinetic energy of the sack. Note that the pier does not move (or, to be precise, its movement is negligible) so the spring does no work on the pier, and the kinetic energy of the pier is negligible.
If the sack of potatoes is on a boat (or on a trolley) which has a mass of $75$ kg then the spring exerts a force of $150$ N on the sack and on the boat. Again, the man has a mass of $75$ kg and so initially accelerates at $2$ metres per second per second. But this time the boat has a mass of $75$ kg so its acceleration is $2$ metres per second per second in the opposite direction. This time, when the sack travels a small distance $d$ (small enough so that the force exerted by the spring does not change) then the boat also travels the same distance $d$ in the opposite direction, so the total work done by the spring is now $300d$ Joules. So both the sack and the boat accelerate and gain kinetic energy, but the work done by the spring is twice what it was in the first case.

A: As @anna_v has addressed several times in the comments, your confusion is caused by acceleration not being a conserved quantity. That it, the sum of accelerations is not necessary the same at different times. The total momentum and energy is, however, conserved at all times. As a small exercise, it might be fruitful for you to compute the total momentum of the system and check that it vanishes at all times.

A: In the first case the man does a force in the pier and the pier does a force in the man. Both of 150 N. Of course only during the leg's impulse.
In the second case, the man does a force in the boat and the boat does a force in the man. Both of 150 N.
No difference concerning the third law.
And third law is conservation of momentum:
$$F_{12} = -F_{21} => \frac{\partial \mathbf p_2}{\partial t} = -\frac{\partial \mathbf p_1}{\partial t} $$
About conservation of momentum, the second case is easy because the objects have the same mass. In the first one, the pier is attached to the Earth, so all the Earth is accelerated backwards by the force. But as its mass is so big, the acceleration is negligible.


text:
Q: PHP : get data from 2 bracket I want to get data from bracket in array
$x = ['1(data1(data2))','2(data3(data4))'];

I want x to show :
$x = ['data1(data2))','data3(data4)']

When i use
explode("(",rtrim($x,")"));

It show me
$x = ['data1','data3']

I am beginner of php
$x = ['1(data1(data2))','2(data3(data4))'];`

Thanks a lot.

A: If all your array-elements start with a number followed by a '(' and end with a ')' you could use following code:
$x = ['1(data1(data2))','2(data3(data4))'];

function cutSomeData($elem){
    $data = substr($elem, strpos($elem, '(')+1);
    $data = substr($data, 0, strrpos($data, ')'));
    return $data;
}
$x = array_map('cutSomeData', $x);

If not, let me know.
I'll try to help you out


text:
Q: python calculate distance closest xy points so i have a list of points
["9.5 7.5", "10.2 19.1", "9.7 10.2", "2.5 3.6", "5.5 6.5", "7.8 9.8"]

with a starting point of
["2.2 4.6"]

now what i am trying to do it is get the closest point to my starting point, then the closest point to that point and so on.
So i get to calculate distance
def dist(p1,p2):
    return math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)

but again, i'm trying to get the closest to my starting point, then the closest point to that one and so on.
ok, because you are complaing i didn't show enough code?
fList = ["2.5 3.6", "9.5 7.5", "10.2 19.1", "9.7 10.2",  "5.5 6.5", "7.8 9.8"]
def distance(points):
    p0, p1 = points
    return math.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2)

min_pair = min(itertools.combinations(fList, 2), key=distance)
min_distance = distance(min_pair)

print min_pair
print min_distance

so i get passing my starting point I get
([2.2, 4.6], [2.5, 3.6])

So now i need to use 2.5, 3.6 as my starting point and find the next closest and so on
Has anyone done anything similar?

A: A possibility is to use a breadth-first search to scan all elements, and find the closest point for each element popped off the queue:
import re, collections
import math

s = ["9.5 7.5", "10.2 19.1", "9.7 10.2", "2.5 3.6", "5.5 6.5", "7.8 9.8"]
def cast_data(f):
   def wrapper(*args, **kwargs):
     data, [start] = args
     return list(map(lambda x:' '.join(map(str, x)), f(list(map(lambda x:list(map(float, re.findall('[\d\.]+', x))), data)), list(map(float, re.findall('[\d\.]+', start))))))
   return wrapper

@cast_data
def bfs(data, start, results=[]):
   queue = collections.deque([start])
   while queue and data:
     result = queue.popleft()
     possible = min(data, key=lambda x:math.hypot(*[c-d for c, d in zip(result, x)]))
     if possible not in results:
       results.append(possible)
       queue.append(possible)
       data = list(filter(lambda x:x != possible, data))
   return results

print(bfs(s, ["2.2 4.6"]))

Output:
['2.5 3.6', '5.5 6.5', '7.8 9.8', '9.7 10.2', '9.5 7.5', '10.2 19.1']

The result is the listing of closest points, as determined by using math.hypot.

A: You can try the following code. Much simpler and short. Uses a comparator to sort the list depending on the distance from the starting point (2.2,4.6)
import math
data = ["9.5 7.5", "10.2 19.1", "9.7 10.2", "2.5 3.6", "5.5 6.5", "7.8 9.8"]
data.sort(key=lambda x: math.sqrt((float(x.split(" ")[0]) - 2.2)**2 +
                                  (float(x.split(" ")[1]) -4.6)**2))
print(data)

# output ['2.5 3.6', '5.5 6.5', '7.8 9.8', '9.5 7.5', '9.7 10.2', '10.2 19.1']

A: You can simply sort a list by a key you define as you wish - f.e. by your distance function:
import math

def splitFloat(x):
    """Split each element of x on space and convert into float-sublists"""
    return list(map(float,x.split()))

def dist(p1, p2):
    # you could remove the sqrt for computation benefits, its a symetric func
    # that does not change the relative ordering of distances
    return math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)

p = ["9.5 7.5", "10.2 19.1", "9.7 10.2", "2.5 3.6", "5.5 6.5", "7.8 9.8"]

s = splitFloat("2.2 4.6")       # your start point
p = [splitFloat(x) for x in p]  # your list of points

# sort by distance between each individual x and s
p.sort(key = lambda x:dist(x,s))

d = [ (dist(x,s),x) for x in p]  # create tuples with distance for funsies
print(p)
print(d)

Output:
 [[2.5, 3.6], [5.5, 6.5], [7.8, 9.8], [9.5, 7.5], [9.7, 10.2], [10.2, 19.1]]

[(1.0440306508910546, [2.5, 3.6]), (3.8078865529319543, [5.5, 6.5]),
 (7.64198926981712, [7.8, 9.8]), (7.854934754662192, [9.5, 7.5]),
 (9.360021367496977, [9.7, 10.2]), (16.560495161679196, [10.2, 19.1])]


text:
Q: PHP Warning: mysqli::query(): Couldn't fetch mysqli Here's my current code:
<?php
$key = $_REQUEST['key'];
$url = $_REQUEST['url'];

include_once '../../dbconnect.php';

$query = $conn->query("SELECT * FROM members WHERE apikey='$key' && status='Active'");
$userRow=$query->fetch_array();
$conn->close();

/// Verify the URL starts with http:// or https://
if (0 === strpos($url, 'http://') || 0 === strpos($url, 'https://')) {
$url = $url;
} else {
$url = "http://$url";
}

/// Verify the key is 32 characters
if (!preg_match('/[^A-Za-z0-9]/', $key) && (strlen($key) == 32)) {

/// Verify the URL isn't malicious
if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) {
    die('Error:  Invalid URL');
} else {

if ($userRow['status'] === 'Active') {

function generateRandomString($length = 8) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

$redirect = generateRandomString();

$addshort = $conn->query("INSERT INTO short_".$redirect[0]." (redirect, apikey, url) VALUES ('".$redirect."','".$key."','".$url."')");

if ($conn->query($addshort) === TRUE) {
echo "added correctly";
} else {
echo "there was an error";
}

$conn->close();

} else {
echo "Error:  Account Not Active";
}

}

} else {
die('Error:  Invalid API Key');
}
?>

Here's the error_log:
[18-Oct-2016 12:21:31 America/New_York] PHP Warning:  mysqli::query(): Couldn't fetch mysqli in /home/username/public_html/subdomains/url/index.php on line 40
[18-Oct-2016 12:21:31 America/New_York] PHP Warning:  mysqli::query(): Empty query in /home/username/public_html/subdomains/url/index.php on line 42
[18-Oct-2016 12:21:31 America/New_York] PHP Warning:  mysqli::close(): Couldn't fetch mysqli in /home/username/public_html/subdomains/url/index.php on line 48

You can see on the 7th line where I connect to the database for the first time:
$query = $conn->query("SELECT * FROM members WHERE apikey='$key' && status='Active'");

And that line is working.  However, the second time I'm connecting to do an INSERT, I'm getting the above errors:
$addshort = $conn->query("INSERT INTO short_".$redirect[0]." (redirect, apikey, url) VALUES ('".$redirect."','".$key."','".$url."')");

Is there something I'm missing from just staring at this code for too long?

A: Your connection has been closed, after execution of first SELECT Statement, it means connection closed to early:
$conn->close();

You need to use close() after your all queries or re build connection. ist one is the better option.
You are getting user input $_REQUEST['key'], it means your query is open for SQL injection, this will help you to understand how can you prevent your code with SQL injection: How can I prevent SQL injection in PHP?

A: This:
$addshort = $conn->query("INSERT ...')");
^^^^^^^
if ($conn->query($addshort) === TRUE) {
                   ^^^^^

$addshort is your query result/handle/object, which you then try to EXECUTE AGAIN, which doesn't work. query() expects an SQL string, and you're passing in an object.
And on top of that, you're vulnerable to sql injection attacks.


text:
Q: Youtube Iframe video not autoplay on IOS and some android devices browsers I integrate youtube video on my website through an iframe. It works good start playing(autoplay) when page load on browsers.
But it shows issues when I run it on browsers of IOS and some android devices.
Either IOS does not allow autoplay video or is there any other issue?
Here is link to iframe.


text:
Q: how to write a true default method to avoid code duplication I want to write two classes implement interface with default method with parameter - function name and use it in both classes, but don know how to put method name as a parameter. It necessary to avoid duplication.
interface C {
        default public StatusEntry getServiceStatus(){????}
}

class A implements C {

    private StatucBType getSatusA(){...}

    @Override
    public StatusEntry getServiceStatus() throws Exception {
        StatusEntry result = new StatusEntry();
        ServiceStatus status;
        try {
            status = **getSatusA()**/*need make as a parametr*/.getStatus();
        } catch (Exception e) {
        }
        result.Status(status);
        return result;
    }
}

class B implements C {
    private StatucBType getSatusB(){...}

    @Override
    public StatusEntry getServiceStatus() throws Exception {
        StatusEntry result = new StatusEntry();
        ServiceStatus status;
        try {
            status = **getSatusB()**/*need make as a parametr*/.getStatus();
        } catch (Exception e) {
        }
        result.Status(status);
        return result;
    }
}

A: Maybe you are looking for the template method pattern.
Your interface should have just a getStatus method,
StatucBType getStatus();

and the getServiceStatus method will be default and implemented like this:
default StatusEntry getServiceStatus() throws Exception {
    StatusEntry result = new StatusEntry();
    ServiceStatus status;
    try {
        status = getStatus().getStatus();
    } catch (Exception e) {
    }
    result.Status(status);
    return result;
}

Now you need to implement getStatus in A and B:
// in A
public StatucBType getStatus { /*put the implementation of getStatusA here*/}
// in B
public StatucBType getStatus { /*put the implementation of getStatusB here*/}

A: If you add a parameter to the method getServiceStatus in your interface, the concrete implementations must also add this parameter, and - more important - the callers of that method must know what argument to provide.
So first of all, don't add a parameter to that interface (at least, it's not necessary in this little scenario)!
For avoiding code duplication, you can add an intermediate abstract class hosting the code:
abstract class Z {

    final StatusEntry getServiceStatus(Supplier<StatucBType> statusProvider) throws Exception {
        StatusEntry result = new StatusEntry();
        ServiceStatus status;
        try {
            status = statusProvider.get().getStatus();
        } catch (Exception e) {
        }
        result.Status(status);
        return result;
    }

}

Then use it as following:
class A implements C extends Z {

    private StatucBType getSatusA() {...}

    @Override
    public StatusEntry getServiceStatus() throws Exception {
        return getServiceStatus(this::getStatusA);
    }

}


text:
Q: Is there a way to list all services historically used on AWS account (excluding cloud trail) I'm trying to find a way to list all services used on AWS account, having 1000s of accounts, I can't use cloud trail. Config only provides data on infrastructure like EC2, lambdas, RDSs, which is a fraction of what I need.
Is there an API or a way to make call preferably using an aggregator of some sort?
I would be interested in simple output like account, what services, when first consumed. Any suggestions?
Why do I need it? We let our app teams to consume number of services and they are gradually whitelisted to consume, we would like to understand how quick these are being utilized since whitelsited.

A: Have you had a look at your AWS bill?  That would be a nice source of all the information as to what services were active on an account.
AWS provides the AWS Cost Explorer API which would permit you to do this programatically.


text:
Q: Combining products of like terms in a division I was seeing an example on a book which says that:
$$\frac{t}{t(x+t+1)} = \frac{1}{x+t+1}$$
The instructions read: "combine products of like terms"
What exactly is that? Why does it work and why didn't he just cut out the $t$ on the numerator and the one multiplying the denominator? He could do that, right?

A: If $t \neq 0$ you could just divide the denominator and numerator by $t$, if not you need to distinguish a special case where $t=0$. By the edits I see I will edit this too. Because we take the limit $t\rightarrow 0$, $t$ will never be $0$ but we can take it as close to zero as we like, so we can divide the numerator and the denominator by $t$, or factor out in the fashion as suggested.

A: Yes; I would describe this just cancelling $t$ in the numerator and denominator.  I have no idea why the writer would consider this as "combining like terms".
(If $t = 0$, then of course you can't cancel $t$.  But in that case, the left-hand fraction is undefined in any case.)


text:
Q: How to run a program without an operating system? How do you run a program all by itself without an operating system running?
Can you create assembly programs that the computer can load and run at startup, e.g. boot the computer from a flash drive and it runs the program that is on the CPU?

A: Runnable examples
Let's create and run some minuscule bare metal hello world programs that run without an OS on:

*

*an x86 Lenovo Thinkpad T430 laptop with UEFI BIOS 1.16 firmware

*an ARM-based Raspberry Pi 3
We will also try them out on the QEMU emulator as much as possible, as that is safer and more convenient for development. The QEMU tests have been on an Ubuntu 18.04 host with the pre-packaged QEMU 2.11.1.
The code of all x86 examples below and more is present on this GitHub repo.
How to run the examples on x86 real hardware
Remember that running examples on real hardware can be dangerous, e.g. you could wipe your disk or brick the hardware by mistake: only do this on old machines that don't contain critical data! Or even better, use cheap semi-disposable devboards such as the Raspberry Pi, see the ARM example below.
For a typical x86 laptop, you have to do something like:

*

*Burn the image to an USB stick (will destroy your data!):
sudo dd if=main.img of=/dev/sdX

*plug the USB on a computer

*turn it on

*tell it to boot from the USB.
This means making the firmware pick USB before hard disk.
If that is not the default behavior of your machine, keep hitting Enter, F12, ESC or other such weird keys after power-on until you get a boot menu where you can select to boot from the USB.
It is often possible to configure the search order in those menus.
For example, on my T430  I see the following.
After turning on, this is when I have to press Enter to enter the boot menu:

Then, here I have to press F12 to select the USB as the boot device:

From there, I can select the USB as the boot device like this:

Alternatively, to change the boot order and choose the USB to have higher precedence so I don't have to manually select it every time, I would hit F1 on the "Startup Interrupt Menu" screen, and then navigate to:

Boot sector
On x86, the simplest and lowest level thing you can do is to create a Master Boot Sector (MBR), which is a type of boot sector, and then install it to a disk.
Here we create one with a single printf call:
printf '\364%509s\125\252' > main.img
sudo apt-get install qemu-system-x86
qemu-system-x86_64 -hda main.img

Outcome:

Note that even without doing anything, a few characters are already printed on the screen. Those are printed by the firmware, and serve to identify the system.
And on the T430 we just get a blank screen with a blinking cursor:

main.img contains the following:

*

*\364 in octal == 0xf4 in hex: the encoding for a hlt instruction, which tells the CPU to stop working.
Therefore our program will not do anything: only start and stop.
We use octal because \x hex numbers are not specified by POSIX.
We could obtain this encoding easily with:
echo hlt > a.S
as -o a.o a.S
objdump -S a.o

which outputs:
a.o:     file format elf64-x86-64

Disassembly of section .text:

0000000000000000 <.text>:
   0:   f4                      hlt

but it is also documented in the Intel manual of course.

*%509s produce 509 spaces. Needed to fill in the file until byte 510.

*\125\252 in octal == 0x55 followed by 0xaa.
These are 2 required magic bytes which must be bytes 511 and 512.
The BIOS goes through all our disks looking for bootable ones, and it only considers bootable those that have those two magic bytes.
If not present, the hardware will not treat this as a bootable disk.
If you are not a printf master, you can confirm the contents of main.img with:
hd main.img

which shows the expected:
00000000  f4 20 20 20 20 20 20 20  20 20 20 20 20 20 20 20  |.               |
00000010  20 20 20 20 20 20 20 20  20 20 20 20 20 20 20 20  |                |
*
000001f0  20 20 20 20 20 20 20 20  20 20 20 20 20 20 55 aa  |              U.|
00000200

where 20 is a space in ASCII.
The BIOS firmware reads those 512 bytes from the disk, puts them into memory, and sets the PC to the first byte to start executing them.
Hello world boot sector
Now that we have made a minimal program, let's move to a hello world.
The obvious question is: how to do IO? A few options:

*

*ask the firmware, e.g. BIOS or UEFI, to do it for us

*VGA: special memory region that gets printed to the screen if written to. Can be used in Protected Mode.

*write a driver and talk directly to the display hardware. This is the "proper" way to do it: more powerful, but more complex.

*serial port. This is a very simple standardized protocol that sends and receives characters from a host terminal.
On desktops, it looks like this:

Source.
It is unfortunately not exposed on most modern laptops, but is the common way to go for development boards, see the ARM examples below.
This is really a shame, since such interfaces are really useful to debug the Linux kernel for example.

*use debug features of chips. ARM calls theirs semihosting for example. On real hardware, it requires some extra hardware and software support, but on emulators it can be a free convenient option. Example.
Here we will do a BIOS example as it is simpler on x86. But note that it is not the most robust method.
main.S
.code16
    mov $msg, %si
    mov $0x0e, %ah
loop:
    lodsb
    or %al, %al
    jz halt
    int $0x10
    jmp loop
halt:
    hlt
msg:
    .asciz "hello world"

GitHub upstream.
link.ld
SECTIONS
{
    /* The BIOS loads the code from the disk to this location.
     * We must tell that to the linker so that it can properly
     * calculate the addresses of symbols we might jump to.
     */
    . = 0x7c00;
    .text :
    {
        __start = .;
        *(.text)
        /* Place the magic boot bytes at the end of the first 512 sector. */
        . = 0x1FE;
        SHORT(0xAA55)
    }
}

Assemble and link with:
as -g -o main.o main.S
ld --oformat binary -o main.img -T link.ld main.o
qemu-system-x86_64 -hda main.img

Outcome:

And on the T430:

Tested on: Lenovo Thinkpad T430, UEFI BIOS 1.16. Disk generated on an Ubuntu 18.04 host.
Besides the standard userland assembly instructions, we have:

*

*.code16: tells GAS to output 16-bit code

*cli: disable software interrupts. Those could make the processor start running again after the hlt

*int $0x10: does a BIOS call. This is what prints the characters one by one.
The important link flags are:

*

*--oformat binary: output raw binary assembly code, don't wrap it inside an ELF file as is the case for regular userland executables.

To better understand the linker script part, familiarize yourself with the relocation step of linking: What do linkers do?
Cooler x86 bare metal programs
Here are a few more complex bare metal setups that I've achieved:

*

*multicore: What does multicore assembly language look like?

*paging: How does x86 paging work?
Use C instead of assembly
Summary: use GRUB multiboot, which will solve a lot of annoying problems you never thought about. See the section below.
The main difficulty on x86 is that the BIOS only loads 512 bytes from the disk to memory, and you are likely to blow up those 512 bytes when using C!
To solve that, we can use a two-stage bootloader. This makes further BIOS calls, which load more bytes from the disk into memory. Here is a minimal stage 2 assembly example from scratch using the int 0x13 BIOS calls:
Alternatively:

*

*if you only need it to work in QEMU but not real hardware, use the -kernel option, which loads an entire ELF file into memory. Here is an ARM example I've created with that method.

*for the Raspberry Pi, the default firmware takes care of the image loading for us from an ELF file named kernel7.img, much like QEMU -kernel does.

For educational purposes only, here is a one stage minimal C example:
main.c
void main(void) {
    int i;
    char s[] = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
    for (i = 0; i < sizeof(s); ++i) {
        __asm__ (
            "int $0x10" : : "a" ((0x0e << 8) | s[i])
        );
    }
    while (1) {
        __asm__ ("hlt");
    };
}

entry.S
.code16
.text
.global mystart
mystart:
    ljmp $0, $.setcs
.setcs:
    xor %ax, %ax
    mov %ax, %ds
    mov %ax, %es
    mov %ax, %ss
    mov $__stack_top, %esp
    cld
    call main

linker.ld
ENTRY(mystart)
SECTIONS
{
  . = 0x7c00;
  .text : {
    entry.o(.text)
    *(.text)
    *(.data)
    *(.rodata)
    __bss_start = .;
    /* COMMON vs BSS: https://stackoverflow.com/questions/16835716/bss-vs-common-what-goes-where */
    *(.bss)
    *(COMMON)
    __bss_end = .;
  }
  /* https://stackoverflow.com/questions/53584666/why-does-gnu-ld-include-a-section-that-does-not-appear-in-the-linker-script */
  .sig : AT(ADDR(.text) + 512 - 2)
  {
      SHORT(0xaa55);
  }
  /DISCARD/ : {
    *(.eh_frame)
  }
  __stack_bottom = .;
  . = . + 0x1000;
  __stack_top = .;
}

run
set -eux
as -ggdb3 --32 -o entry.o entry.S
gcc -c -ggdb3 -m16 -ffreestanding -fno-PIE -nostartfiles -nostdlib -o main.o -std=c99 main.c
ld -m elf_i386 -o main.elf -T linker.ld entry.o main.o
objcopy -O binary main.elf main.img
qemu-system-x86_64 -drive file=main.img,format=raw

C standard library
Things get more fun if you also want to use the C standard library however, since we don't have the Linux kernel, which implements much of the C standard library functionality through POSIX.
A few possibilities, without going to a full-blown OS like Linux, include:

*

*Write your own. It's just a bunch of headers and C files in the end, right? Right??

*Newlib
Detailed example at: https://electronics.stackexchange.com/questions/223929/c-standard-libraries-on-bare-metal/223931
Newlib implements all the boring non-OS specific things for you, e.g. memcmp, memcpy, etc.
Then, it provides some stubs for you to implement the syscalls that you need yourself.
For example, we can implement exit() on ARM through semihosting with:
void _exit(int status) {
    __asm__ __volatile__ ("mov r0, #0x18; ldr r1, =#0x20026; svc 0x00123456");
}

as shown at in this example.
For example, you could redirect printf to the UART or ARM systems, or implement exit() with semihosting.

*embedded operating systems like FreeRTOS and Zephyr.
Such operating systems typically allow you to turn off pre-emptive scheduling, therefore giving you full control over the runtime of the program.
They can be seen as a sort of pre-implemented Newlib.
GNU GRUB Multiboot
Boot sectors are simple, but they are not very convenient:

*

*you can only have one OS per disk

*the load code has to be really small and fit into 512 bytes

*you have to do a lot of startup yourself, like moving into protected mode

It is for those reasons that GNU GRUB created a more convenient file format called multiboot.
Minimal working example: https://github.com/cirosantilli/x86-bare-metal-examples/tree/d217b180be4220a0b4a453f31275d38e697a99e0/multiboot/hello-world
I also use it on my GitHub examples repo to be able to easily run all examples on real hardware without burning the USB a million times.
QEMU outcome:

T430:

If you prepare your OS as a multiboot file, GRUB is then able to find it inside a regular filesystem.
This is what most distros do, putting OS images under /boot.
Multiboot files are basically an ELF file with a special header. They are specified by GRUB at: https://www.gnu.org/software/grub/manual/multiboot/multiboot.html
You can turn a multiboot file into a bootable disk with grub-mkrescue.
Firmware
In truth, your boot sector is not the first software that runs on the system's CPU.
What actually runs first is the so-called firmware, which is a software:

*

*made by the hardware manufacturers

*typically closed source but likely C-based

*stored in read-only memory, and therefore harder / impossible to modify without the vendor's consent.

Well known firmwares include:

*

*BIOS: old all-present x86 firmware. SeaBIOS is the default open source implementation used by QEMU.

*UEFI: BIOS successor, better standardized, but more capable, and incredibly bloated.

*Coreboot: the noble cross arch open source attempt

The firmware does things like:

*

*loop over each hard disk, USB, network, etc. until you find something bootable.
When we run QEMU, -hda says that main.img is a hard disk connected to the hardware, and hda is the first one to be tried, and it is used.

*load the first 512 bytes to RAM memory address 0x7c00, put the CPU's RIP there, and let it run

*show things like the boot menu or BIOS print calls on the display
Firmware offers OS-like functionality on which most OS-es depend. E.g. a Python subset has been ported to run on BIOS / UEFI: https://www.youtube.com/watch?v=bYQ_lq5dcvM
It can be argued that firmwares are indistinguishable from OSes, and that firmware is the only "true" bare metal programming one can do.
As this CoreOS dev puts it:

The hard part
When you power up a PC, the chips that make up the chipset (northbridge, southbridge and SuperIO) are not yet initialized properly. Even though the BIOS ROM is as far removed from the CPU as it could be, this is accessible by the CPU, because it has to be, otherwise the CPU would have no instructions to execute. This does not mean that BIOS ROM is completely mapped, usually not. But just enough is mapped to get the boot process going. Any other devices, just forget it.
When you run Coreboot under QEMU, you can experiment with the higher layers of Coreboot and with payloads, but QEMU offers little opportunity to experiment with the low level startup code. For one thing, RAM just works right from the start.

Post BIOS initial state
Like many things in hardware, standardization is weak, and one of the things you should not rely on is the initial state of registers when your code starts running after BIOS.
So do yourself a favor and use some initialization code like the following: https://stackoverflow.com/a/32509555/895245
Registers like %ds and %es have important side effects, so you should zero them out even if you are not using them explicitly.
Note that some emulators are nicer than real hardware and give you a nice initial state. Then when you go run on real hardware, everything breaks.
El Torito
Format that can be burnt to CDs: https://en.wikipedia.org/wiki/El_Torito_%28CD-ROM_standard%29
It is also possible to produce a hybrid image that works on either ISO or USB. This is can be done with grub-mkrescue (example), and is also done by the Linux kernel on make isoimage using isohybrid.
ARM
In ARM, the general ideas are the same.
There is no widely available semi-standardized pre-installed firmware like BIOS for us to use for the IO, so the two simplest types of IO that we can do are:

*

*serial, which is widely available on devboards

*blink the LED

I have uploaded:

*

*a few simple QEMU C + Newlib and raw assembly examples here on GitHub.
The prompt.c example for example takes input from your host terminal and gives back output all through the simulated UART:
enter a character
got: a
new alloc of 1 bytes at address 0x0x4000a1c0
enter a character
got: b
new alloc of 2 bytes at address 0x0x4000a1c0
enter a character

See also: How to make bare metal ARM programs and run them on QEMU?

*a fully automated Raspberry Pi blinker setup at: https://github.com/cirosantilli/raspberry-pi-bare-metal-blinker

See also: How to run a C program with no OS on the Raspberry Pi?
To "see" the LEDs on QEMU you have to compile QEMU from source with a debug flag: https://raspberrypi.stackexchange.com/questions/56373/is-it-possible-to-get-the-state-of-the-leds-and-gpios-in-a-qemu-emulation-like-t
Next, you should try a UART hello world. You can start from the blinker example, and replace the kernel with this one: https://github.com/dwelch67/raspberrypi/tree/bce377230c2cdd8ff1e40919fdedbc2533ef5a00/uart01
First get the UART working with Raspbian as I've explained at: https://raspberrypi.stackexchange.com/questions/38/prepare-for-ssh-without-a-screen/54394#54394 It will look something like this:

Make sure to use the right pins, or else you can burn your UART to USB converter, I've done it twice already by short circuiting ground and 5V...
Finally connect to the serial from the host with:
screen /dev/ttyUSB0 115200

For the Raspberry Pi, we use a Micro SD card instead of an USB stick to contain our executable, for which you normally need an adapter to connect to your computer:

Don't forget to unlock the SD adapter as shown at: https://askubuntu.com/questions/213889/microsd-card-is-set-to-read-only-state-how-can-i-write-data-on-it/814585#814585
https://github.com/dwelch67/raspberrypi looks like the most popular bare metal Raspberry Pi tutorial available today.
Some differences from x86 include:

*

*IO is done by writing to magic addresses directly, there is no in and out instructions.
This is called memory mapped IO.

*for some real hardware, like the Raspberry Pi, you can add the firmware (BIOS) yourself to the disk image.
That is a good thing, as it makes updating that firmware more transparent.
Resources

*

*http://wiki.osdev.org is a great source for those matters.

*https://github.com/scanlime/metalkit is a more automated / general bare metal compilation system, that provides a tiny custom API

A:
How do you run a program all by itself without an operating system running?

You place your binary code to a place where processor looks for after rebooting (e.g. address 0 on ARM).

Can you create assembly programs that the computer can load and run at startup ( e.g. boot the computer from a flash drive and it runs the program that is on the drive)?

General answer to the question: it can be done.
It's often referred to as "bare metal programming".
To read from flash drive, you want to know what's USB, and you want to have some driver to work with this USB. The program on this drive would also have to be in some particular format, on some particular filesystem... This is something that boot loaders usually do, but your program could include its own bootloader so it's self-contained, if the firmware will only load a small block of code.
Many ARM boards let you do some of those things. Some have boot loaders to help you with basic setup.
Here you may find a great tutorial on how to do a basic operating system on a Raspberry Pi.
Edit:
This article, and the whole wiki.osdev.org will anwer most of your questions
http://wiki.osdev.org/Introduction
Also, if you don't want to experiment directly on hardware, you can run it as a virtual machine using hypervisors like qemu. See how to run "hello world" directly on virtualized ARM hardware here.

A: Operating System as the inspiration
The operating system is also a program, so we can also create our own program by creating from scratch or changing (limiting or adding) features of one of the small operating systems, and then run it during the boot process (using an ISO image).
For example, this page can be used as a starting point:
How to write a simple operating system
Here, the entire Operating System fit entirely in a 512-byte boot sector (MBR)!
Such or similar simple OS can be used to create a simple framework that will allow us:

make the bootloader load subsequent sectors on the disk into RAM, and jump to that point to continue execution. Or you could read up on FAT12, the filesystem used on floppy drives, and implement that.

There are many possibilities, however. For for example to see a bigger x86 assembly language OS we can explore the MykeOS, x86 operating system which is a learning tool to show the simple 16-bit, real-mode OSes work, with well-commented code and extensive documentation.
Boot Loader as the inspiration
Other common type of programs that run without the operating system are also Boot Loaders. We can create a program inspired by such a concept for example using this site:
How to develop your own Boot Loader
The above article presents also the basic architecture of such a programs:

*

*Correct loading to the memory by 0000:7C00 address.

*Calling the BootMain function that is developed in the high-level language.

*Show ""Hello, world…", from low-level" message on the display.

As we can see, this architecture is very flexible and allows us to implement any program, not necessarily a boot loader.
In particular, it shows how to use the "mixed code" technique thanks to which it is possible to combine high-level constructions (from C or C++) with low-level commands (from Assembler). This is a very useful method, but we have to remember that:

to build the program and obtain executable file you will need the compiler and linker of Assembler for 16-bit mode. For C/C++ you will need only the compiler that can create object files for 16-bit mode.

The article shows also how to see the created program in action and how to perform its testing and debug.
UEFI applications as the inspiration
The above examples used the fact of loading the sector MBR on the data medium. However, we can go deeper into the depths by plaing for example with the UEFI applications:

Beyond loading an OS, UEFI can run UEFI applications, which reside as files on the EFI System Partition. They can be executed from the UEFI command shell, by the firmware's boot manager, or by other UEFI applications. UEFI applications can be developed and installed independently of the system manufacturer.
A type of UEFI application is an OS loader such as GRUB, rEFInd, Gummiboot, and Windows Boot Manager; which loads an OS file into memory and executes it. Also, an OS loader can provide a user interface to allow the selection of another UEFI application to run. Utilities like the UEFI shell are also UEFI applications.

If we would like to start creating such programs, we can, for example, start with these websites:
Programming for EFI: Creating a "Hello, World" Program / UEFI Programming - First Steps
Exploring security issues as the inspiration
It is well known that there is a whole group of malicious software (which are programs) that are running before the operating system starts.
A huge group of them operate on the MBR sector or UEFI applications, just like the all above solutions, but there are also those that use another entry point such as the Volume Boot Record (VBR) or the BIOS:

There are at least four known BIOS attack viruses, two of which were for demonstration purposes.

or perhaps another one too.
Attacks before system startup

Bootkits have evolved from Proof-of-Concept development to mass distribution and have now effectively become open-source software.

Different ways to boot
I also think that in this context it is also worth mentioning that there are various forms of booting the operating system (or the executable program intended for this). There are many, but I would like to pay attention to loading the code from the network using Network Boot option (PXE), which allows us to run the program on the computer regardless of its operating system and even regardless of any storage medium that is directly connected to the computer:
What Is Network Booting (PXE) and How Can You Use It?

A: I wrote a c++ program based on Win32 to write an assembly to the boot sector of a pen-drive. When the computer is booted from the pen-drive it executes the code successfully - have a look here C++ Program to write to the boot sector of a USB Pendrive
This program is a few lines that should be compiled on a compiler with windows compilation configured - such as a visual studio compiler - any available version.


text:
Q: Pre-fill fields with content from outside when creating a new post I'd like to find a way to fill some of the fields from the /wp-admin/post-new.php page from an external source.
It works for the title: loading /wp-admin/post-new.php?post_title=title1 fills the title input with title1.
You get the idea, what would be great is something like /wp-admin/post-new.php?post_title=title1&content=content1&tags=tag1,tag2&cat=cat1,cat2... so that when I arrive on the post-new.php with most fields already filled from an outside script.
I would need to fill in custom fields as well.
How can I do that? What's the best option? A full external script that connects to the base my himself and run insert queries? A plugin? If so, do you have some suggestions?

A: If this is to add end-users then maybe the easiest thing to do is to create a jQuery script to assign the values.  Here's how to parse the URL:

*

*Get QueryString values with jQuery
And here's how to add Javascript in WordPress:

*

*What is the best way to add custom javascript files to the site?
Finally, just view source in the WordPress edit screen to see the names of the input fields and then this shows how to use jQuery to assign values:

*

*How to get and set form element values with jQuery

A: An empty post is created by get_default_post_to_edit(). This function reads the post_title, content and excerpt values in the $_REQUEST array, and also filters them through default_title, default_content and default_excerpt.
By default this function only returns a "fake" $post object, but if the $create_in_db parameter is set to true, it is actually saved in the database with the post_status set to auto-draft.
This parameter is set in post-new.php, which means you can hook into wp_insert_post and save extra stuff, like tags, from the $_REQUEST array or from an external source. A very simple example:
add_action( 'load-post-new.php', 'wpse8650_post_new' );
function wpse8650_post_new()
{
    add_action( 'wp_insert_post', 'wpse8650_wp_insert_post_default' );
}

function wpse8650_wp_insert_post_default( $post_id )
{
    add_post_meta( $post_id, 'wpse8650_meta_key', $_REQUEST['meta_value'] );
    wp_set_post_tags( $post_id, $_REQUEST['tags']) );
}

This works because the custom fields and post tags are read again from the database (or the cache) when building the page, and we do this before these metaboxes are displayed.

A: In addition to Mike's answer, you can also use WordPress' XML-RPC server to do external posting. It depends on what you're trying to do.


text:
Q: Need desired format of .wav In Recoder.js I am using recorder.js to record audio. When I download .wav file it is 48KHz but I want in 16KHz, mono channel.
function init(config) {
            sampleRate = config.sampleRate; //to 16000
            numChannels = config.numChannels; //to 1
            initBuffers();
        }

It changes the recorded voice (like a voice of the robot).
Help me to get a voice in 16KHz, mono .wav file in a normal voice. (Thanx in Advance)
My Code Is Here


text:
Q: Timeout on a Python function call inside timeit I have a function, let's call it my_function(*args, **kwargs), that depending on the arguments passed to it takes anywhere from 30 seconds to many many hours (days). I have a list of different arguments and I want to know how long the functions will take given the arguments.
I am still very new to using timeit, but I have learn enough to do this part; however, this wouldn't be the very efficient for my purposes.  Any set of arguments that take longer than 4 hours to complete are consider intractable, despite all of them being able to be solved in "finite" time. As some (possibly most) of the arguments will results in run times that will take upwards of 20+ hours, I am looking for a way to terminate a test after 4 hours so that I don't have to waste time after figuring out that it is intractable.
I have looked at Timeout on a Python function call and Stop code after time period, and this might be close enough of a question to be a duplicate, but I am having trouble integrating those answers with timeit so that times less that 4 hours are recorded like they should be while long runs return some valid time greater than 4 hours.
What would be the best way to go about doing this?
EDIT : One of the problems that I have had with it is that the answers that I've seen have take in func(*args,**kwargs) while the timeit functions looks like this:
timeit.Timer('my_function(*args, **kwargs)', setup=setup).timeit(1)

I don't know how to handle this form.
EDIT :  The original answer that I provided below using threads doesn't actually terminate the threads. This can easily be shown by running it with the following function.
def foo(x):
    for i in xrange(1, x + 1):
        sleep(1)
        print i
    return x

Using a code that involves multiprocessing.Pool, which actually has a terminate(), allow for this.

A: Based on the answer found  in Timeout function using threading in python does not work. If you try it out on foo(x) it does indeed stop counting unlike the my previous answer.
import multiprocessing as mp
import timeit

def timeout(func, args=(), kwargs=None, TIMEOUT=10, default=None, err=.05):

    if hasattr(args, "__iter__") and not isinstance(args, basestring):
        args = args
    else:
        args = [args]
    kwargs = {} if kwargs is None else kwargs

    pool = mp.Pool(processes = 1)

    try:
        result = pool.apply_async(func, args=args, kwds=kwargs)
        val = result.get(timeout = TIMEOUT * (1 + err))
    except mp.TimeoutError:
        pool.terminate()
        return default
    else:
        pool.close()
        pool.join()
        return val

def Timeit(command, setup=''):
    return timeit.Timer(command, setup=setup).timeit(1)

def timeit_timeout(command, setup='', TIMEOUT=10, default=None, err=.05):
    return timeout(Timeit, args=command, kwargs={'setup':setup},
                   TIMEOUT=TIMEOUT, default=default, err=err)

A: After some more fiddling I have a initial answer based on Timeout function using threading. I would still love to hear from anyone who has better ideas as I am still new to this.
def timeout(func, args=None, kwargs=None, TIMEOUT=10, default=None, err=.05):
    if args is None:
        args = []
    elif hasattr(args, "__iter__") and not isinstance(args, basestring):
        args = args
    else:
        args = [args]

    kwargs = {} if kwargs is None else kwargs

    import threading
    class InterruptableThread(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
            self.result = None

        def run(self):
            try:
                self.result = func(*args, **kwargs)
            except:
                self.result = default

    it = InterruptableThread()
    it.start()
    it.join(TIMEOUT* (1 + err))
    if it.isAlive():
        return default
    else:
        return it.result

def timeit_timeout(command, setup='', TIMEOUT=10, default=None, err=.05):
    import timeit
    f = lambda: timeit.Timer(command, setup=setup).timeit(1)
    return timeout(f,TIMEOUT=TIMEOUT, default=default, err=err)

if __name__ == '__main__':
    from time import sleep
    setup = 'gc.enable()\nfrom time import sleep'
    for n in range(1,15):
        command = 'sleep({})'.format(n)
        print timeit_timeout(command, setup=setup, default=float('Inf'))


text:
Q: Mouse hover moving image position I am trying to move an image when my mouse is over it.
Here's an exemple. When moving hover pictures, the text is smoothly following your mouse and this is what I'm looking for.
Do you have any idea ?
The problem with what I tried is that the image keeps moving when I get out of the violet box. (I would prefer to avoid having to create a box and recognize when I am over the image).

$("#containerScaled").on('mousemove', '.box', function (e) {
    $("#followC").css("top", e.clientY)
        .css("left", e.clientX);
});

test

A: I think you should begin with altering your position based on where your mose is positioned inside your rectangel like so:
  if (e.clientX > width/2){
    addX = 20;
  }
  if(e.clientX < width/2){
    addX = -20;
  }
  if(e.clientY > height/2){
    addY = 20;
  }
  if(e.clientY < height/2){
    addY = -20;
  }

This is the first step, that actually makes something "follow" your mouse.
I think you could do some optimization, so that the animation is more crispy, but basically thats the way to go.
I also added
    $("#containerScaled").on('mouseleave', '.box', function(e) {

      $("#followC").css("top", "50%").css("left", "50%");

    });

so that your element will get back to its original position once you leave the :hover area
Because of this I also made you hover area transparent, any lay over the moving element, so that when you hover over the moving element, you wont leave the hover area, and trigger mouseleave
.box{
  background-color: transparent;
}

.boxcolored{
  position: absolute;
  height: 100px;
  width: 100px;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%);
  background-color: green;
}

$("#containerScaled").on('mousemove', '.box', function(e) {

      var left = parseFloat($(".box").css("left"));
      var right = parseFloat($(".box").css("top"));
      var width = parseFloat($(".box").css("widht"));
      var height = parseFloat($(".box").css("height"));

      var addX = 0;
      var addY = 0;

      if (e.clientX > width/2){
        addX = 20;
      }
      if(e.clientX < width/2){
        addX = -20;
      }
      if(e.clientY > height/2){
        addY = 20;
      }
      if(e.clientY < height/2){
        addY = -20;
      }
              $("#followC").css("top", e.clientY + addY)
        .css("left", e.clientX + addX);
      });

    $("#containerScaled").on('mouseleave', '.box', function(e) {

      $("#followC").css("top", "50%").css("left", "50%");

    });
#containerScaled {
  position: absolute;
  top: 0;
  left: 0;
  width: 200px;
  height: 200px;
  background-color: red;
}

#followC {
  transition: all 0.9s ease-out;
  transform-origin: center;
}

.box {
  position: absolute;
  height: 100px;
  width: 100px;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%);
  background-color: transparent;
}
.boxcolored{
  position: absolute;
  height: 100px;
  width: 100px;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%);
  background-color: green;
}

.mouseFollow {
  position: relative;
  height: 20px;
  width: 75px;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%);
  background-color: yellow;
}

HALLO

mouse me

A: The box outlined in a red dashed line is the hover area. The yellow box is the visual area which is the approximation of the limits to which the letters can move within.
There is a lag and an offset. The lag is due to transition: 0.9s and the offset is left and top. The lag can be decreased but at the cost of the smooth movement, There are four letters at varying transition times for comparison. Notice that they all stop at the same position (when the mouse is no longer moving within the dashed box), it just that the slower the transition the more movement occurs after the mouse has left the dashed box.
The offset is tougher since there is only two positions that will work: x: right or left and y: top or bottom. If keeping the letters within a box is a concern, then keep the hover area border and background to none and show the offset (visual area) instead.
Note: Do not review this demo in compact mode, view it in full page mode (normal dimensions)

$(".target").on('mousemove', function(e) {
  $(".text").css({
    "top": e.clientY,
    "left": e.clientX
  });
});
main {
  position:relative;
  font: 400 16px/1.2 Arial;
}

.zone {
  position: absolute;
  z-index: 1;
  height: 120px;
  width: 110px;
  margin: 90px 0 0 90px;
  background: gold;
  color:white;
  text-align:right;
}

.target {
  position: absolute;
  z-index: 2;
  height: 100px;
  width: 100px;
  margin: 75px;
  outline: 3px dashed red;
  color:red
}

.text {
  position: absolute;
  z-index: 3;
  top: 90px;
  left: 90px;
  font-size: 32px;
  color:black
}

.A {
  transition: all 0.9s ease-out;
}

.B {
  transition: all 0.6s ease-out;
}

.C {
  transition: all 0.3s ease-out;
}

Hover Area

    A
    B
    C
    D

Visual Area


text:
Q: Replace one or more sub-strings from multiple file names in a folder I have a list of files for which I would like to replace a substring within their name. The glob.glob(path) returns:
'./path\\2016_Joe_Black_tall_blond',
etc.

where Joe_Black should become Joe-Black.
I would have to do the same for other names, e.g. Tim_Blue becomes Tim-Blue etc.
(can I gather all those into names=[Joe_Black, Tim_Blue ...] ?)
I have found multiple approaches online, but what would be the best to do it?

A: You can use list comprehension for this purpose. In this example, I simply replace _ by -. Note basename is used to extract the name of the file and not its full path.
import glob
import os

path = "./data/"
# Make list of paths
names = glob.glob(os.path.join(path, "*"))
# Returning a list of file names (without path) where a character is replaced
names = [os.path.basename(name).replace('_', '-') for name in names]


text:
Q: Lower bound for denominator of $\displaystyle \frac {a_1}{b_1} + \frac {a_2}{b_2}$ in terms of $b_1$ and $b_2$. Let $a_1, a_2, b_1, b_2$ be positive integers such that $\gcd(a_1, b_1) = \gcd(a_2, b_2) = 1$.
It appears to me based on some intuition and numerical evidence that the (reduced) denominator of $\displaystyle \frac{a_1}{b_1} + \frac{a_2}{b_2} = \frac{a_1b_2 + a_2b_1}{b_1b_2}$ is bounded below by $\displaystyle\frac{\operatorname{lcm}(b_1,b_2)}{\gcd(b_1,b_2)}$. I reckon that there's a simple way to prove this, but I don't see it immediately.

The bound on the other side is clear to me: the (reduced) denominator of $\displaystyle \frac{a_1}{b_1} + \frac{a_2}{b_2} = \frac{a_1b_2 + a_2b_1}{b_1b_2}$ is bounded above by $\operatorname{lcm}(b_1,b_2)$, because

*

*$b_1b_2 = \operatorname{lcm}(b_1,b_2)\gcd(b_1,b_2)$, and

*$\gcd(b_1,b_2)$ divides $a_1b_2 + a_2b_1$ since it divides both $b_1$ and $b_2$,

so $$
  \frac{a_1b_2 + a_2b_1}{b_1b_2} =   \frac{a_1b_2 + a_2b_1}{\operatorname{lcm}(b_1,b_2)\gcd(b_1,b_2)} =   \frac{a_1b'_2 + a_2b'_1}{\operatorname{lcm}(b_1,b_2)},
$$ where $b'_1 = \frac{b_1}{\gcd(b_1,b_2)}$ and $b'_2 = \frac{b_2}{\gcd(b_1,b_2)}$.


text:
Q: is there any method available in django models, so that i can access its fieldname using string? i want to update fields using ajax:
models.py
class EmployerInfo(models.Model):
    employer = models.ForeignKey(Employer, unique=True)
    address=models.CharField(max_length=100, blank=True)
    city=models.CharField(max_length=40, blank=True)

contactinfo.html
<form id="ajax-form">
    <fieldset>
        <legend>Contact Information</legend>
        Address:
        <input type="text" id="address" value="{{ empinfo.address }}" />
        City:
        <input type="text" id="city" value="{{ empinfo.city }}" />
    </fieldset>
</form>


text:
Q: How to make a field auto increment in ActiveAndroid ORM How can I make an integer or long field to be auto-incremented using annotation.

A: As we can read in a documentation:

One important thing to note is that ActiveAndroid creates an id field
  for your tables. This field is an auto-incrementing primary key.

Maybe accessing auto-generated primary key will be enough for you?
Moreover, if you would like to create custom primary key in you model, you can check solution mentioned in GitHub issue connected with ActiveAndroid, which looks like this:
@Table(name = "Items", id = "clientId")
public class Item extends Model {
    @Column(name = "id")
    private long id;
}

Then, id field is custom primary key, which will be auto-incremented.

A: In case of ActiveAndroid ORM you do not need to write id column in model, It will automatic generate auto incremented value and you can simply use it.
I am giving a sample model below-
@Table(name="Items")
public class Item extends Model{
    @Column(name="name")
    public String name;
}

Instead of
@Table(name="Items")
public class Item extends Model{
    @Column(name="Id")
    public long id;
    @Column(name="name")
    public String name;
}

If item is an object of Item then you can simply get id by using
item.getId();

So, the correct model is first one. For reference you can click here.


text: Q: Use area name to get pincode/postalcode in android? In my app,getting address from user,after user enter the area name how to display the pin code/postal code automatically in edit text field.using map any one know please share with me.


text:
Q: How to display dots view on image slide android studio said that it's not use for future app i.e. Html.fromHtml("&#8226") so i use this code but it's not work for me why is there any missing or...
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    dots[i].setText(Html.fromHtml("•",1));
    dots[i].setTextSize(35);
    dots[i].setTextColor(colorInactive[position]);
    dotslayout.addView(dots[i]);
}


text:
Q: How to make a selectable image in a NSTextView? I am working on an application which performs some mathematical calculations and sends the results ( including texts and graphs) into a NSTextView.
This code works fine in making the output but this is the problem: I want that user can select/copy-pate and drag-drop the produced images into other text editors ( like Pages or Text Edit). When user drags an image from my textview, it is dragged but nothing is pasted to the destination:
- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];

    NSBezierPath* aPath=[NSBezierPath bezierPath];

    NSImage* anImage = [[NSImage alloc] initWithSize:NSMakeSize(200.0, 200.0)];
    [anImage lockFocus];
    //some drawings:
    NSColor* blue= [NSColor blueColor];
    [blue setStroke];
    aPath=[NSBezierPath bezierPath];
    [aPath setLineWidth:20];
    [aPath moveToPoint:NSMakePoint(20.0, 20.0)];
    [aPath lineToPoint:NSMakePoint(100.0, 100.0)];
    [aPath stroke];
    [anImage unlockFocus];
    //re-capture and change it to a bitmap

    NSSize size = [anImage size];
    [anImage lockFocus];
    NSBitmapImageRep* rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0,0,size.width,size.height)];
    [anImage unlockFocus];
    NSData* jpgData = [rep representationUsingType:   NSJPEGFileType properties:nil ];

    NSImage* newImage= [[NSImage alloc]initWithData:jpgData];

    //append attrited string only once.   BOOL isDrownYet in header
    if (!isDrownYet) {
        NSTextAttachmentCell *attachmentCell1 = [[NSTextAttachmentCell alloc]   initImageCell:newImage];
        NSTextAttachment *attachment1 = [[NSTextAttachment alloc] init];
        [attachment1 setAttachmentCell: attachmentCell1];
        NSMutableAttributedString *attributedString1 = (NSMutableAttributedString*)[ NSMutableAttributedString attributedStringWithAttachment: attachment1];
        [self.textStorage appendAttributedString:attributedString1];
        isDrownYet=YES;
    }
 }


text:
Q: LinkedCaseInsensitive map casting issue with HashMaps with Spring higher version The LinkedCaseInsensitiveMap is part of the Spring Framework and extends the LinkedHashMap
The hierarchy goes like this:
java.lang.Object
java.util.AbstractMap
java.util.HashMap
java.util.LinkedHashMap
org.springframework.util.LinkedCaseInsensitiveMap
For information refer : https://docs.spring.io/spring/docs/3.2.4.RELEASE_to_4.0.0.M3/Spring%20Framework%203.2.4.RELEASE/org/springframework/util/LinkedCaseInsensitiveMap.html
Now I have this code :
List<HashMap<String, String>> l_lstResult = (List<HashMap<String, String>>)service.fetchRowwiseMultipleRecords(p_iQueryName, l_hmParams, userDetails);

                l_lstCityTownList = new ArrayList<String>(l_lstResult.size());

                for (int i = 0; i < l_lstResult.size(); i++) {
                    HashMap<String, String> l_hmColmnData = l_lstResult.get(i);
                    String l_sValue = l_hmColmnData.get(p_sColumnName);
                    l_lstCityTownList.add(l_sValue);
                }

The l_lstResult returns a LinkedCaseInsensitiveMap and i get the error in the line  HashMap l_hmColmnData = l_lstResult.get(i);

java.lang.ClassCastException:
  org.springframework.util.LinkedCaseInsensitiveMap cannot be cast to
  java.util.HashMap

The thing is i get this error with Spring version 4.3.14.RELEASE and no error in 3.2.3.RELEASE. Where is the specification in 3.2.3.RELEASE that allows this casting.
Any suggestions,examples would help me a lot .
Thanks a lot !

A: Since Spring 4.3.6.RELEASE, LinkedCaseInsensitiveMap doesn't extend anymore LinkedHashMap and HashMap, but only implements Map interface.
API reference.
When you cast service.fetchRowwiseMultipleRecords(p_iQueryName, l_hmParams, userDetails) to List<HashMap<String, String>> you're just telling the compiler to trust you. But then, when it comes to get the first element of the list, it fails because it's not a HashMap but a LinkedCaseInsensitiveMap (not extending HashMap).
This will solve your issue
List<LinkedCaseInsensitiveMap<String>> l_lstResult = service.fetchRowwiseMultipleRecords(p_iQueryName, l_hmParams, userDetails);

l_lstCityTownList = new ArrayList<String>(l_lstResult.size());

for (int i = 0; i < l_lstResult.size(); i++) {
    LinkedCaseInsensitiveMap<String> l_hmColmnData = l_lstResult.get(i);
    String l_sValue = l_hmColmnData.get(p_sColumnName);
    l_lstCityTownList.add(l_sValue);
}


text:
Q: Excel: date range with non-unique entries. Only return values of adjacent cell if date is lowest non-unique entry In column A, I have a list of non-unique dates. In column B, I have a list of numbers. I am attempting to put together a formula that I can copy down column C that will only return the value in column B if either the date in column A is unique, or where the date is non-unique, the non-unique date sits in the lowest row. Sorry I'm struggling to articulate this better. Hope this and the table below will be enough to help resolve my query.
Column A     Column B  Column C
04/05/2001   0.05      0.05
05/06/1996   0.01      0.01
13/11/1991   0.00963   n.a.
13/11/1991   0.004815  0.004815

Thanks in advance


text:
Q: How to export Quick Help Documentation for User Defined Function in Xcode 8 to HTML I know how to add the documentation in Xcode but I am unable to find , how to export that documentation to HTML.

A: There are 2 major apps/command line tools that can do what you want

*

*Headerdoc

*doxygen
Headerdoc
Is an open source documentation to html script/command line tool from Apple, Inc.
Headerdoc is provided by default in all versions of OS X/macOS just open Terminal and use the following to figure out what you have:

which headerdoc2html

and then read the man page using something like this:

man headerdoc2html

Doxygen
Supports many languages and has a few tag/format differences from Headerdoc

Which one you will want to use will be based on what language you are using, Headerdoc may not support the language you want and doxygen might not either, your mileage may vary. Read the documentation and supported languages to make your choice. I hope this helps :)


text:
Q: Programmatically generate thumbnail CAP for small video How can python make a simple cap for a video.
Ideia: take 9 snapshots for 9 even placed (on the timeline) times, and displace then in a JGP
How should I do this?
Is PIL the only way? (it's not going to be easy to do what I want, right?)
Aren't there any module (python seens to have GREAT modeles for almoust anything, or am I out of luck)
Example:
Movie lenght = 10 min
T1= snapshot of 1 min
T2= snapshot of 2 min
......
T9= snapshot of 9 min
   |   |
 T1| T2| T3
---+---+---
 T4| T5| T6
---+---+---
 T7| T8| T9
   |   |

A: This is a quick change to something I've done some time ago, using ffmpeg for frame extraction and PIL to create the full thumbs image.
import os, sys
from PIL import Image

# Use "ffmpeg -i <videofile>" to get total length by parsing the error message
chout, chin, cherr = os.popen3("ffmpeg -i %s" % sys.argv[1])
out = cherr.read()
dp = out.index("Duration: ")
duration = out[dp+10:dp+out[dp:].index(",")]
hh, mm, ss = map(float, duration.split(":"))
total = (hh*60 + mm)*60 + ss

# Use "ffmpeg -i <videofile> -ss <start> frame<nn>.png" to extract 9 frames
for i in xrange(9):
    t = (i + 1) * total / 10
    os.system("ffmpeg -i %s -ss %0.3fs frame%i.png" % (sys.argv[1], t, i))

# Make a full 3x3 image by pasting the snapshots
full = None
for y in xrange(3):
    for x in xrange(3):
        img = Image.open("frame%i.png" % (y*3+x))
        w, h = img.size
        if full is None:
            full = Image.new("RGB", (w*3, h*3))
        full.paste(img, (x*w, y*h))

# Save result
full.save("thumbs.png")


text:
Q: how to find the difference b/w to dates stored in a variable in shell script ( KSH shell ) In hp-ux as there is no GNU date available, i.e the -d and -s options of the date command are not available. How do I find the difference between two given dates in days (as we do in Solaris or bash shell)?

A: There are actually many solutions to be found via Google, but here is one that I just stumbled across and like for its brevity. You would use its ansi_dn function on both dates and calculate the difference.
diff_dates.sh:
#!/bin/ksh

. ./ansi_dn.sh

date_to="$1"
date_from="$2"

echo $((
      $(ansi_dn \
        $(echo "${date_to}"   | cut -d/ -f3) \
        $(echo "${date_to}"   | cut -d/ -f2) \
        $(echo "${date_to}"   | cut -d/ -f1) \
      )
    - $(ansi_dn \
        $(echo "${date_from}" | cut -d/ -f3) \
        $(echo "${date_from}" | cut -d/ -f2) \
        $(echo "${date_from}" | cut -d/ -f1) \
      )
))

(If you have the years, months and days of both dates in separate variables already the cut nightmare is not needed, obviously.)
Example:
$ ./diff_dates.sh 08/05/2013 01/01/1939
27156

Let's verify correctness with GNU date:
$ echo $(( ( $(date -d 2013-05-08 +%s) - $(date -d 1939-01-01 +%s) + 43200 ) / 86400))
27156


text:
Q: How to get the Cell Position of a TableLayoutPanel for a radioButton Here is my code, it is returning (-1, -1) as the coordinates of the cell position. Which I assume means the control was not found in the table. My radio buttons are sitting inside a panel within the table cell. However, radio.Container returns null.
private void radio_CheckedChanged(object sender, EventArgs e)
{
    var radio = sender as RadioButton;
    var coord = tblPanel.GetPositionFromControl(radio);//returns (-1, -1)
}

I would like to get the row number from the sender object by any means necessary. Thanks for any help you can provide.
Daniel

A: Turns out what I needed was the parent property which in this case was the panel. Container was always null.
private void radio_CheckedChanged(object sender, EventArgs e)
{
        var radio = sender as RadioButton;
        var row = tblPanel.GetRow(radio.Parent);
}


text:
Q: How to check the available VM Sizes in an Azure Region using Azure sdk for go I'm trying to get a list of the available vm sizes in a particular region using azure sdk for go. But as of yet I haven't been able to find how i'd do it with the sdk.
Any help would be appreciated.
Thanks


text:
Q: SQL Server : Query Missing FROM clause with IIf I need to run a T-SQL query via the Microsoft Query interface, using an IIf statement.
When I run the query, I get the error Missing FROM clause. This is odd, because the FROM clause is there. It fails because of the IIf but I have no idea why.
The code:
SELECT
    TABLE1.NUMBER,
    TABLE1.TEXT,
    TABLE1.INT,
    IIf(
        (
            (
                ((TABLE2.INT1-TABLE2.INT2) -TABLE2.INT3) -TABLE2.INT4
            ) > 0
        ),
        (
            1
        ),  0)
        as NEWCOL
FROM
    DB.TABLEX TABLE1,
    DB.TABLEY TABLE2
WHERE
    TABLE2.NUMBER = TABLE1.NUMBER
    AND TABLE1.NUMBER='991208000192'

The database is not mine, so I have to work with what I can. Does anyone have an idea what may cause the problem?

A: the SQLBase reference in http://enos.itcollege.ee/~priit/(I216)%20Ab-de%20administreerimine/SQLBase%20admin%20juhendid/LANG.PDF (Courtesy @twoleggedhorse) does not have function IIF in SQLBase. It has a function IF with similar syntax as your IIF.
Try using @IF(CONDITION, TRUE_VAL, FALSE_VAL) in your SQL.


text:
Q: How to unsbscribe from the FirebaseMsgService to stop getting notifications I have created a MyFirebaseMsgService to receive Push notification from my Azure notification Hub following the various blogs to get everything working. my resultant service looks as below:
[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
public class MyFirebaseMessagingService : FirebaseMessagingService
{
    const string TAG = "MyFirebaseMsgService";
    NotificationHub hub;
    //override on
    public override void OnNewToken(string token)
    {
        Log.Debug(TAG, "FCM token: " + token);
        SendRegistrationToServer(token);
    }

    void SendRegistrationToServer(string token)
    {
        // Register with Notification Hubs
        hub = new NotificationHub(Constants.NotificationHubName, Constants.NotificationHubListenConnectionString, this);

        var tags = new List<string>() { };
        var regID = hub.Register(token, tags.ToArray()).RegistrationId;

        Log.Debug(TAG, $"Successful registration of ID {regID}");
    }
    public async override void OnMessageReceived(RemoteMessage message)
    {

so far so good, its all working fine, but now the challange I have is, I want the user to have control over stopping / starting the notification subscription.
right now once the subscription is created, I think its somehow running in the background and this class is out of reach from my application to do anything with the NotificationHub instance there. I don't see OnNewToken being ever called after the 1st time no matter howmany times I restart the app on the phone.
can some one please suggest me how I can enable/disable the subscription to the messages from the server. almost all the resources on net talsk about using Firebase.Messaging.FirebaseMessaging.Instance.UnsubscribeFromTopic() which is not helping me.
I am only targeting on Android, if that makes any difference.

A: Well let me brief it to you, Firebase recommends that you use data push rather than notification push if you want to have complete control over push notifications.
When you check their official documents it says:

Use notifications when you want FCM to handle displaying a notification on your client app's behalf. Use data messages when you want your app to handle the display or process the messages on your Android client app...

So what this basically means is change the body of your notifications to something like
{
 "data": {
   "type" : "mytype",
   "title": "My Title",
   "body": "My Notification Message"
  },
 "to": "/topics/all"
}

Once you do that it will always call your OnMessageReceived method where you can handle whether or not the notification needs to be shown to the user.


text:
Q: Converting a Matrix Class into IplImage* I do have a class of Matrix and I access to it with two loops and have stored in it all the values I wanted to have in it.
Matrix MatriceJ(width, height);
for (int i=0;i<width;i++)
{
    for (int j=0;j<height;j++)
    {
        MatriceJ.at(i,j)=....
    }
}

But now, I would like to store the MatriceJ in an IplImage* for that I can multiply its different elements, one by one, with the other IplImages.
Can you help me with that?

A: This should get you started. I assume the data to be unsigned char and one channel, please adjust accordingly.
// Create the image
int depth = IPL_DEPTH_8U; // please adjust
int channels = 1;         // please adjust
IplImage* img = cvCreateImage(cvSize(width,height), depth, channels);

// Now assume there is a matrix MatriceJ
// Copy the data to our newly created IplImage*
for (int i=0;i<height;i++)
{
    uchar* ptr = (uchar*)(img->imageData + i*img->widthStep);
    for (int j=0;j<width;j++)
    {
        ptr[j] = MatriceJ(i,j);
    }
}


text:
Q: Removing a framework support from a big project I need to remove a framework(vertx, to be specific) from a project(lib) which is the base for other projects as well.
What would be the best approach to remove all dependencies on the framework from the project. I am new to this and I do not have enough understanding of the project yet.
They are thinking to replace it with Spring Cloud.

A: Per the comments, and with a few assumptions I would take the following approach.
First, Make sure the current framework (vertx) is as decoupled as possible. This will make replacing whole or parts of the framework easier in the long run.
Second, Option 1: You can do this in one giant change, as suggested in the comments remove all libs and wait fr compile errors. Then start to fix it.
Second, Option 2: If you are a little more hesitant about the change, refactor one part (or module) of the application, test it, repeat.
Whatever you choose, make sure you have amazing tests that pass before the changes and after the changes. This will save you from feature regressions.


text:
Q: Pause Scheduled tasks in SCDF Hi I'm running batch jobs via SCDF in openshift environment. All the jobs have been scheduled through the scheduling option in SCDF. Is there way to pause or Hold those jobs from executing instead of destroying the schedules ? Since the number of jobs are more, everytime we have to recreated the schedules for all of them.
Thanks.

A: We have an open issue: spring-cloud/spring-cloud-dataflow#3276 to add support for it.
Feel free to update the issue with your use-case requirements and the acceptance criteria. Better yet, it'd be great if you can contribute adding support for it in a PR; we would love to collaborate and release it.