text:
Q: What is the difference between secondary/grammar/primary/grade/etc. school? There are some minor differences between primary, grade and elementary school, but let's forget them. The same goes for secondary, grammar and middle school.
The question is about different school names for the same grades and which one is preferred in American or British English.
I'm not sure if grammar school term exists at all, but that's what I got from a translator.

A: Primary school and elementary school are the same. The only difference is that elementary school is the preferred term in American and Canadian English.
Education in United States consists of three stages:

*

*elementary school

*middle school

*high school
Middle schools usually offer classes for students in sixth, seventh and eighth grades (some of them offer classes for ninth grade too) and prepares students for high school.
Education in United Kingdom consists of two phases:

*

*primary school

*secondary school
Secondary schools refer to high schools and prep schools.

A: In Britain.
Ages 4-11 are Primary school
Ages 11-18 is Secondary School (with education compulsory to age 16)
In British English "Primary" is preferred to "Elementary".  Middle Schools have been phased out in most places, but would have covered ages 9-14. "Secondary" is prefered to "High" school.
Grammar Schools are secondary schools that are selective. They take the top attaining 25% of students.  In most areas, state grammar schools have been phased out.  Comprehensive schools are secondary schools that do not select on ability.
Private and Independent schools are schools that are not run by the state. Public schools are a type of traditional Independent school, this differs from American use where "Public School" means the same as "State School". The term "public school" comes from a time when the Government didn't have schools. Either you had a private education at home with a parent or tutor, or a public education at a school.
So the main differences are:

*

*"Primary" not "Elementary",

*"Secondary" not "Middle" or "High",

*"State" not "Public".


text:
Q: Problem with Poker packages I want to display playing cards in my document, but none of the poker packages I've tried are working (\usepackage{poker} nor \usepackage{pst-poker}). I am, in fact, able to compile (using XeLaTeX) and get an output (in both cases), but the output is not correct: In both cases, the cards never have a box around them. So they're not displayed correctly.
The documents explaining these packages are pretty poor, so I'm not sure how to proceed.
Here is my MWE (for the case when I use the poker package):
\documentclass[12pt]{article}
\usepackage{amssymb}

\usepackage{poker}
\setkeys{poker}{inline=symbol}

\title{Poker}

\begin{document}

\maketitle

Conclusion:

\As\tenh\sevd\sevc\Qd

\end{document}

Again, I do get output, but not the the correct one.
The correct one is displayed immediately under Section 3.1 in http://web.mit.edu/foley/games/Arcadia/sr/poker/poker-doc.pdf Indeed, these cards have a box around them. And my problem is that I do not have any box around my cards, nor can I get it so.

A: \setkeys{poker}{inline=symbol} is not the style used under 3.1 in the pdf. That uses \setkeys{poker}{inline=card} if I'm not mistaken.
(Or actually, \setkeys{poker}{inline=card,colorset=4c}, since all four colors are used there.)
Since the frames use pstricks, you'll either need to compile with LaTeX > dvips > ps2pdf (the last with -dALLOWPSTRANSPARENCY), or if you use xelatex, you might need to use xelatex -output-driver="xdvipdfmx -i dvipdfmx-unsafe.cfg -q -E" to allow for Ghostscript transparency (see here) (or as egreg suggests, xelatex-safe with TeXLive 2022), depending on how your xdvipdfmx is configured.

With colorset=4c:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Usage of LU decomposition over UL decomposition What are some advantages of using LU decomposition over UL decomposition? From what I see, they can both be used equally well to solve $MX=V$ through forward and backward substitution, and since the determinant is commutative for triangular matricies, they can both be used. Some googling returns nothing on the UL decomposition, leading me to believe that LU has some advantages over UL. So why is LU decomposition preferred?
Source: Linear Algebra by Cherney, Denton, Waldron

A: In an otherwise banded matrix, sparseness is preserved by:
(1) LU decomposition when there are full rows at the bottom and/or
columns on the right;
(2) UL decomposition when there are full rows at the top and/or columns on
the left.


text:
Q: Zoomable flickable (map-like) in QML I am trying to make component, which allows me to move with Flickable and zoom it, similiar to QML component Map, except there will be border for user (which Flickable has by default).
Currently, I have this
Flickable {
    id: flickArea
    width: parent.width
    height: parent.height
    contentWidth: inner.width *  slider.value
    contentHeight: inner.height * slider.value
    Image {
        transform: Scale {
            origin.x: parent.width /2
            origin.y: parent.height/2
            xScale:  slider.value
            yScale: slider.value
        }

        id: inner
        width: parent.contentWidth
        anchors.centerIn: parent
        source: "file:/home/username/imgs/test"
    }
}

but it doesn't work as expected (there is white border around, and zoom isn't centered).
What am I doing wrong? Should I use Flickable, or is there any more suitable component?

A: Your source code is not complete and doesn't allow to understand exactly the problem.
So, I'm going to assume that:

*

*the white borders mentioned are the white surface displayed when the surface is dragged beyond the Flickable's boundaries.

*the slider id refers to a Slider item.
The following code could help:
import QtQuick 2.9
import QtQuick.Controls 1.4

Item {
    width: 1280
    height: 720

    Flickable {
        id: flickArea
        anchors.fill: parent
        focus: true
        contentWidth: Math.max(inner.width * slider.value, width)
        contentHeight: Math.max(inner.height  * slider.value, height)
        anchors.centerIn: parent
        boundsBehavior: Flickable.StopAtBounds
        contentX: contentWidth === width ? 0 : inner.width * slider.value / 2 - flickArea.width / 2
        contentY: contentHeight === height ? 0 : inner.height * slider.value / 2 - flickArea.height / 2

        Image {
            id: inner
            scale: slider.value
            transformOrigin: Item.Center
            anchors.centerIn: parent
            source: "Ba_b_do8mag_c6_big.png"
        }
    }

    Slider {
        id: slider
        value: 2
        orientation: Qt.Vertical
        anchors {
            bottom: parent.bottom
            right: parent.right
            margins: 50
        }
    }
}

Here, the white borders are not displayed anymore thanks to the boundsBehavior: Flickable.StopAtBounds.
In my example, when the slider is used, the zoom is always centered. The user can flick the surface as soon as the rendered image is bigger than the size of the window.
However, even if the user moves in the area, the zoom will always be centered. The movement is not saved.
The image used is downloadable here: https://commons.wikimedia.org/wiki/File:Ba_b_do8mag_c6_big.png_


text:
Q: What encryption is used by default SecureSocial for SecureSocialPasswordHasher? I've got a passwords on a datastore that were hashed using the method SecureSocialPasswordHasher.passwordHash from the package securesocial.utils.SecureSocialPasswordHasher of SecureSocial, and I have to validate them through Python.
Therefore, the use of SecureSocial (or the whole Play Framework) is out of the question. The question is: What does it use for hashing when calling that method? From the documentation it seems it is Bcrypt, but it wasn't clear enough for me to be sure.
---------EDIT---------
I've been told on SecureSocial forums that indeed it uses Bcrypt with work factor 10 default. However it doens't reflect what I see on the datastore.
There are 2 columns there, one for salt, and another one fro the hashed password. Neither of them have the Bcrypt header (such as $2a$10$). Also, the salt size is only 11 characters long, and the hashed password is only 22 characters long (and no signs of having the salt inside the string).

A: Found out the default for hashing passwords on SecureSocial is indeed Bcrypt.
The default implementation for it's hash method is:
  def hash(plainPassword: String): PasswordInfo = {
        PasswordInfo(id, BCrypt.hashpw(plainPassword, BCrypt.gensalt(logRounds)))
  }

This applies to the latest version of SecureSocial.
On my specific problem, the main issue was that I was not communicated that the code I was dealing with was using an older version of SecureSocial, and that the has method was overriden.


text:
Q: In Unix, how to display welcome message if user has logged in from a particular IP (or host)? I want to display one message if user XYZ has logged in from any IP (or host).

A: Check to see if you have environment variables such as SSH_CLIENT and SSH_CONNECTION set. If so, you can access these from scripts (perl, bash, etc...) to dynamically generate a welcome message. Below, is a simple perl script to extract the IP address from env var SSH_CLIENT and output a welcome message.
#!/usr/bin/env perl
use strict; use warnings;
my $ip = (split / /, $ENV{SSH_CLIENT})[0];
if ($ip eq 'xxx.xxx.xxx.xxx') {
  print "Hello XXXX\n";
}
else {
  print "Hello from unknown IP\n";
}

Then you need to execute this script at login time. You can do this by calling the script from the end of /etc/profile.

A: Also This can be done using shell script as
 REMOTE_IP=`echo $SSH_CONNECTION | cut -f1 -d " "`
if [ $REMOTE_IP == 'XXX.XXX.XXX.X' ] ;
      then echo "Hi XXX" ;
else echo "Hi, stranger...";
fi

And then run this script from /etc/profile


text:
Q: repeat ggplot using different data without typing out the whole code Is a way to re-plot something but using a subsetted dataset without writing the entire code out again?
maybe something like last_plot() but allow one to specific the data.frame to use?

A: Although I feel that Csgillespie's answer is complete. I'd like to add a secondary method that I personally use quite frequently, but rarely see out in the wild. It's great for applying corporate/personal themes and avoiding retyping one's work.
You can save ggplot2 elements as a list, just as though you were writing them with ... + ... +
default.point <- list(geom_point(),
coord_flip(),
theme(
axis.text.x=element_text(size=12
)))

ggplot(diamonds,aes(carat, price, colour=cut)) + default.point

A: You can use the %+% operator:
##Two data sets:
R> dd = data.frame(x = runif(10), y=runif(10))
R> dd_new = data.frame(x = runif(10), y=runif(10))

R> g = ggplot(dd, aes(x,y)) + geom_point()
R> g
R> g %+% dd_new


text:
Q: Can I combine groupby data? I have two columns home and away. So one row will be England vs Brazil and the next row will be Brazil England. How can I count occurrences of when Brazil faces England or England vs Brazil in one count?
Based on previous solutions, I have tried
results.groupby(["home_team", "away_team"]).size()
results.groupby(["away_team", "home_team"]).size()

however this does not give me the outcome that I am looking for.
Undesired output:
home_team    away_team
England  Brazil       1
away_team    home_team
Brazil  England       1
I would like to see:
England Brazil 2

A: May be you need  below:
df = pd.DataFrame({
    'home':['England', 'Brazil', 'Spain'],
    'away':['Brazil', 'England', 'Germany']
})

pd.Series('-'.join(sorted(tup)) for tup in zip(df['home'], df['away'])).value_counts()

Output:
Brazil-England    2
Germany-Spain     1
dtype: int64

PS: If you do not like the - between team names, you can use:
pd.Series(' '.join(sorted(tup)) for tup in zip(df['home'], df['away'])).value_counts()

A: You can sort values by numpy.sort, create DataFrame and use your original solution:
df1 = (pd.DataFrame(np.sort(df[['home','away']], axis=1), columns=['home','away'])
        .groupby(["home", "away"])
        .size())

A: Option 1
You can use numpy.sort to sort the values of the dataframe
However, as that sorts in place, maybe it is better to create a copy of the dataframe.
dfTeams = pd.DataFrame(data=df.values.copy(), columns=['team1','team2'])
dfTeams.values.sort()

(I changed the column names, because with the sorting you are changing their meaning)
After having done this, you can use your groupby.
results.groupby(['team1', 'team2']).size()

Option 2
Since a more general title for your question would be something like how can I count combination of values in multiple columns on a dataframe, independently of their order, you could use a set.

A set object is an unordered collection of distinct hashable objects.

More precisely, create a Series of frozen sets, and then count values.
pd.Series(map(lambda home, away: frozenset({home, away}),
              df['home'],
              df['away'])).value_counts()

Note: I use the dataframe in @Harv Ipan's answer.


text:
Q: In Perl, how do I pipe the output of one command to the input of another? In Perl, how can pipe the output of one command to the input of another?
I want to do it the way the shell does it, but without using the shell.
I know that I can do this using the shell and escaping the arguments to the command, but I don't want to use the shell.  I would also prefer using modules that are distributed with Perl, as opposed to ones on CPAN.
I could use fork and exec manually, but that doesn't work on Windows.

A: This is easy using IPC::Run.
run \@cmd1, '|', \@cmd2;

For example,
prog0:
#!/usr/bin/perl
use IPC::Run qw( run );
print("The parent's PID is $$\n");
run([ 'prog1' ], '|', [ 'prog2' ]);

prog1:
#!/usr/bin/perl
print("cmd1's parent's PID is ".getppid()."\n");

prog2:
#!/usr/bin/perl
while (<>) {
   chomp;
   print("Got <<$_>>\n");
}
print("cmd2's parent's PID is ".getppid()."\n");

Output from prog0:
The parent's PID is 6619
Got <<cmd1's parent's PID is 6619>>
cmd2's parent's PID is 6619

A: Using exec:
perl -e 'exec(bash => (-o => "pipefail", -c => "find . -type f|xargs ls -l"));'

or
perl -e 'exec("bash", "-o",  "pipefail", "-c", " find . -type f|xargs ls -l");


text:
Q: JSON with '-' in key reading in angular js I have this JSON
{
"data":{
  "string-x": "21",
  "string-y": "110"
}
}

the string x and y is coordinates
I just want to call the coodinates by
data.string-x and data.string-y but I got this error
ReferenceError: x is not defined
what am I missing? it seems javascript treat data.string-x like equation not regular node call.
could anyone help me.

A: data.string-x is treated as subtraction expression, equal to data.string - x
so change your code to data["string-x"]


text:
Q: How can I extract the part that is after @ in an email using php? For example, if an email is Hello@domain.com
I want to get "domain.com"
I want to do that for several emails that are in a table using php.
and I want to calculate how many emails have a certain domain and display it as a percentage.
For instance : Domain1.com : 50%
               Domain2.com : 50%

<html >
    <head>
         <meta charset="utf-8" />
    </head>
    <body>

 <?php
     $emails=array("email1@domain1.com","email2@domain2.fr","email3@domain3.com",
        "email4@domain4.com");
        $domain = explode('@', $emails)[4];
 ?>

    </body>
 </html>

I want to get :
domain1 : 25%
domain2 : 25%
domain3 : 25%
domain4 : 25%

A: I believe you want code like this
$emails=array("email1@domain1.com","email2@domain2.fr","email3@domain3.com", "email4@domain4.com",  "email233@domain4.com");
$results = array();

foreach($emails as $email){
    $domain = substr($email, strpos($email, "@") + 1);
    $result[$domain]  = isset($result[$domain]) ? $result[$domain] + 1 : 1;
}

foreach($result as $key=>$val){
    echo $key.": " . 100/array_sum($result)*$val . "<br>";
}


text:
Q: Add foreign key to AspNetUser table I've created an ASP.NET Core Razor Pages application with user identities.
The created project includes a migration that adds all the user tables, such as AspNetUser and AspNetRoles. However, it doesn't create any code models for these tables.
Now I've created my own entity models and I would like some of them to have foreign keys to the AspNetUser table.
How can I do this? Does the platform expose these as classes anyplace? Do I need to manually create models and try to get them to exactly match the tables? Or for that matter, how do I access all of a user's details?

A: The default identity uses IdentityUser, it is not exposed to the project code but you can create a new user model (e.g. AppUser) that is derived from IdentityUser, then add the foreign keys to the new user model:
public class AppUser : IdentityUser
{
    public int AddressId { get; set; }
    public UserAddress Address { get; set; }
}

public class UserAddress
{
    public int Id { get; set; }

    // ...

    public string UserId { get; set; }
    public AppUser User { get; set; }
}

Then replace IdentityUser in startup with AppUser :
services.AddDefaultIdentity<AppUser>();

Then create new migrations to create the new user table.


text:
Q: What does this loop do? What does the following loop do?
k = 0
while(b!=0):
   a = a^b
   b = (a & b) << 1
   k = k + 1

where a, b and k integers.
Initially a = 2779 and b = 262  then what will be the value of k after the termination of the loop?
I'd be happy if you people try solving the problem manually rather than programmatically.
EDIT : Dropping the tags c and c++. How can I solve the problem manually?

A: After this chunk is executed:
a = a^b ;
b = (a & b) << 1;

b will take on the integer representation of whatever bits were both set in b and not set in a. Assuming that the input numbers will be of the form 2x, a will become a + b, and b will be itself multiplied by 2 (due to shifting). This means that the loop will terminate when the MSB of a and b are the same (which will be 780th bit in this example). Since b starts off at the 63th bit, there will eventually be 718 iterations: 780 - 63 + 1 (the last iteration) = 718.
You can see this when you step through this with a = 21 and b = 20:
a = 10
b = 01
k = 0

a = 11
b = 10
k = 1

a = 01 (a + b no longer holds here, but it is irrelevant as this is the termination case)
b = 00
k = 2

A:
What does the following loop do?

It computes [power of a] - [power of b] + 1
If you look at the bit-patterns it becomes quite clear. For initial values of a = 210 and b = 25 it looks like this:
k =  0, a = 10000000000, b =       100000
k =  1, a = 10000100000, b =      1000000
k =  2, a = 10001100000, b =     10000000
k =  3, a = 10011100000, b =    100000000
k =  4, a = 10111100000, b =   1000000000
k =  5, a = 11111100000, b =  10000000000

Here is an ideone.com demo.
For the values you mention in your post I get k = 718.

A: In a language that supports numbers this big, the answer is 718, and the question is not at all interesting either way.

A: It looks like the loop is performing a series of bitwise operations while incrementing k by 1 at each iteration.
There's a decent-looking tutorial about bitwise operators here.
Hope that helps.

A: Since you have mentioned that a qnd b is an integer, i think the value 2779 is too big for a integer variable to accommodate this is same for the variable b 262 as well. So both will have there minimum value I think , so after executing  a = a^b ;
b = (a & b) << 1; these statements the value of a and be will be 0. and k's value will be equal to 1. Since b is 0 , the while loop's condition will be false and it will exit the loop.
EDIT : The answer is applicable for a programming language like C/C++ or C#

A: It's not really C syntax.. If we consider that the code is sequential, I am agree with @Paul. But, considering that
a + b == (a^b) + ((a&b) << 1)

where a^b is the sum without applying carry from each bit, and (a&b)<<1 is carry from each bit, we could say that it performs a sum, IFF C code would be
int k = 0;
while(b){
   int old_a = a;
   a = a^b;
   b = (old_a & b) << 1; // note that the need the original value of a here
   k++;  // number of recursion levels for carry
};

The difference in code could be because of "paralel" way of execution in  the original code (or language).


text:
Q: How to show Feature Importance on Random Forest in Text Classifcation? After we use TfidfVectorizer or CountVectorizer to convert the corpus and throw that into RandomForest, how we can get back the Gini Importance with the corresponding word and index?
vectorizer = TfidfVectorizer()
X_train_vectorizer = vectorizer.fit_transform(X_train)
X_test_vectorizer = vectorizer.transform(X_test)

clf = RandomForestClassifier()
clf.fit(X_train_tvectorizer, y_train)
to_predict = rclf.predict(X_test_vectorizer)

I tried, but I have no clue how to do that
plt.barh(X_train_vectorizer, rclf.feature_importances_)

A: Using features = vectorizer.get_feature_names(), you can get the feature names. Using fi = clf.feature_importances_, you can get feature importances from random forest.
They can be made into a dataframe and it can be sorted based on fi.
importance = [(features[i], fi[i]) for i in range(0,2000)]
df.columns = ['feature', 'importance']
df = pd.DataFrame(importance)


text:
Q: Safe label-based selection in DataFrame How can I safely select rows in pandas by a list of labels?
I want to get and Error when list contains any non-existing label.
Method loc doesn't raise a KeyError if at least 1 of the labels for which you ask is in the index. But this is not sufficient.
For example:
df = pd.DataFrame(index=list('abcde'), data={'A': np.arange(5) + 10})

df
    A
a  10
b  11
c  12
d  13
e  14

# here I would like to get an Error as 'xx' and 'yy' are not in the index
df.loc[['b', 'xx', 'yy']]

       A
b   11.0
xx   NaN
yy   NaN

Do pandas provide such a method that would raise a KeyError instead of returning me a bunch of NaNs for non-existing labels?

A: It's bit a hack, but one can do this like this:
def my_loc(df, idx):
    assert len(df.index[df.index.isin(idx)]) == len(idx), 'KeyError:the labels [{}] are not in the [index]'.format(idx)
    return df.loc[idx]

In [243]: my_loc(df, idx)
...
skipped
...
AssertionError: KeyError:the labels [['b', 'xx', 'yy']] are not in the [index]

In [245]: my_loc(df, ['a','c','e'])
Out[245]:
    A
a  10
c  12
e  14

A: I think you get NaN because loc or ix return same output as reindex. See reindex versus ix.
Solution for 'safe' selecting from open issue 10695:
list_of_values = ['b', 'xx', 'yy']
print (df.ix[df.reset_index()['index'].isin(list_of_values).values])
    A
b  11

One solution for return error if values are not in index is use drop:
df.drop(list_of_values)
print (df.loc[list_of_values])

ValueError: labels ['xx' 'yy'] not contained in axis

A: .loc[] won't let you set values if the index in the list is not part of the initial df
so you could do something like:
df = pd.DataFrame(index=['a','b','c','d', 'e'], data={'A':range(5)})
index_list = ['a', 'b']
df.loc[index_list] = df.loc[index_list]
df.loc[index_list]
Out[288]:
   A
a  0
b  1

now let's test for a dummy index:
index_list = ['aa', 'b']
df.loc[index_list] = df.loc[index_list]

you will get this error
   Traceback (most recent call last):
      File "C:\Anaconda2\lib\site-packages\IPython\core\interactiveshell.py", line 2885, in run_code
        exec(code_obj, self.user_global_ns, self.user_ns)
      File "<ipython-input-289-d6aac5dac03d>", line 2, in <module>
        df.loc[index_list] = df.loc[index_list]
      File "C:\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 139, in __setitem__
        indexer = self._get_setitem_indexer(key)
      File "C:\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 126, in _get_setitem_indexer
        return self._convert_to_indexer(key, is_setter=True)
      File "C:\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 1229, in _convert_to_indexer
        raise KeyError('%s not in index' % objarr[mask])
    KeyError: "['aa'] not in index"


text:
Q: How to improve quality after putting two videos side by side vertically? I am putting two videos side by side vertically with ffmpeg.
Both of the videos are in high quality.
There is a loss of quality and the output looks very bad after this command:
 ffmpeg -i input1t.avi -i input2 -filter_complex vstack output.avi

You can see an screen capture of the output movie here:

Any idea why? How to solve it?

A: FFmpeg will reencode your video, without additional parameters it will use default value resulting in a poor quality. Here's an example with a more modern format and codec:
ffmpeg -i input1.avi -i input2 -filter_complex vstack -c:v libx264 -preset slow -crf 20 -c:a aac -movflags +faststart output.mp4

If you need better quality, lower the -crf value.


text:
Q: cppcheck can't find include files cppcheck can't find even standard headers such as iostream. Any ideas?
I am using Ubuntu 11.04 and cppcheck from the repository.

A: cppcheck is really bad at finding standard include headers, on Mac and Linux. Fortunately, you can suppress this check, and only scan your custom header files:
cppcheck --enable=all --suppress=missingIncludeSystem .

A: It isn't recommended to provide the paths to the standard C/C++
headers - Cppcheck has internal knowledge about ANSI C/C++ and it
isn't recommended that this known functionality is redefined. But feel
free to try it.
-I [dir]

Give include path. Give several -I parameters to give several paths.
First given path is checked first. If paths are relative to source
files, this is not needed.


text:
Q: Android Background activity start I'm aware of the Restrictions on starting activities from the background starting from Android API 29, but I'm challenged by some app which is able to present an Activity despite the restrictions. The app does not use the SYSTEM_ALERT_WINDOW permission to draw over other apps. It just presents an activity while having only foreground service running.
The app listens to package added (ACTION_PACKAGE_ADDED) and removed (ACTION_PACKAGE_REMOVED) broadcasts and starts an activity styled as a dialog.
Normally, when I register the receiver (either in manifest or runtime in foreground service) and want to start an activity I get the next log from ActivityTaskManager:
2022-12-25 11:29:57.188   511-855   ActivityTaskManager     pid-511                              I  START u0 {flg=0x10000000 cmp=com.jasperapps.testpackageremoveintent/.TargetActivity} from uid 10146
2022-12-25 11:29:57.190   511-855   ActivityTaskManager     pid-511                              W  Background activity start [callingPackage: com.jasperapps.testpackageremoveintent; callingUid: 10146; appSwitchAllowed: false; isCallingUidForeground: false; callingUidHasAnyVisibleWindow: false; callingUidProcState: FOREGROUND_SERVICE; isCallingUidPersistentSystemProcess: false; realCallingUid: 10146; isRealCallingUidForeground: false; realCallingUidHasAnyVisibleWindow: false; realCallingUidProcState: FOREGROUND_SERVICE; isRealCallingUidPersistentSystemProcess: false; originatingPendingIntent: null; allowBackgroundActivityStart: false; intent: Intent { flg=0x10000000 cmp=com.jasperapps.testpackageremoveintent/.TargetActivity }; callerApp: ProcessRecord{5224fb8 12583:com.jasperapps.testpackageremoveintent:remote/u0a146}; inVisibleTask: false]
2022-12-25 11:29:57.191   511-855   ActivityTaskManager     pid-511                              E  Abort background activity starts from 10146

Where Abort background activity starts from 10146 means that I'm violating the background restrictions, which is expected.
Instead, when I examined the logcat for ActivityTaskManager for the app which workarounds this I found next:
2022-12-25 11:34:59.196   511-4063  ActivityTaskManager     pid-511                              I  START u0 {cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras)} from uid 10148
2022-12-25 11:34:59.198   511-4063  ActivityTaskManager     pid-511                              W  Background activity start [callingPackage: com.bingo.cleaner; callingUid: 10148; appSwitchAllowed: false; isCallingUidForeground: false; callingUidHasAnyVisibleWindow: false; callingUidProcState: FOREGROUND_SERVICE; isCallingUidPersistentSystemProcess: false; realCallingUid: 10148; isRealCallingUidForeground: false; realCallingUidHasAnyVisibleWindow: false; realCallingUidProcState: FOREGROUND_SERVICE; isRealCallingUidPersistentSystemProcess: false; originatingPendingIntent: PendingIntentRecord{921ede4 com.bingo.cleaner startActivity}; allowBackgroundActivityStart: false; intent: Intent { cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras) }; callerApp: ProcessRecord{c06f774 13034:com.bingo.cleaner/u0a148}; inVisibleTask: false]
2022-12-25 11:34:59.199   511-4063  ActivityTaskManager     pid-511                              W  startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { flg=0x800000 cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras) }
2022-12-25 11:34:59.200   511-4063  ActivityTaskManager     pid-511                              E  Abort background activity starts from 10148

2022-12-25 11:34:59.209   511-857   ActivityTaskManager     pid-511                              I  START u0 {flg=0x10000000 cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras)} from uid 10148
2022-12-25 11:34:59.210   511-857   ActivityTaskManager     pid-511                              W  Background activity start [callingPackage: com.bingo.cleaner; callingUid: 10148; appSwitchAllowed: false; isCallingUidForeground: false; callingUidHasAnyVisibleWindow: false; callingUidProcState: FOREGROUND_SERVICE; isCallingUidPersistentSystemProcess: false; realCallingUid: 10148; isRealCallingUidForeground: false; realCallingUidHasAnyVisibleWindow: false; realCallingUidProcState: FOREGROUND_SERVICE; isRealCallingUidPersistentSystemProcess: false; originatingPendingIntent: null; allowBackgroundActivityStart: false; intent: Intent { flg=0x10000000 cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras) }; callerApp: ProcessRecord{c06f774 13034:com.bingo.cleaner/u0a148}; inVisibleTask: false]
2022-12-25 11:34:59.210   511-857   ActivityTaskManager     pid-511                              E  Abort background activity starts from 10148

2022-12-25 11:34:59.285   511-857   ActivityTaskManager     pid-511                              I  START u0 {cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras)} from uid 10148
2022-12-25 11:34:59.287   511-857   ActivityTaskManager     pid-511                              W  Background activity start [callingPackage: com.bingo.cleaner; callingUid: 10148; appSwitchAllowed: false; isCallingUidForeground: false; callingUidHasAnyVisibleWindow: false; callingUidProcState: FOREGROUND_SERVICE; isCallingUidPersistentSystemProcess: false; realCallingUid: 10148; isRealCallingUidForeground: false; realCallingUidHasAnyVisibleWindow: false; realCallingUidProcState: FOREGROUND_SERVICE; isRealCallingUidPersistentSystemProcess: false; originatingPendingIntent: PendingIntentRecord{921ede4 com.bingo.cleaner startActivity (allowlist: d43f3f6:+30s0ms/0/NOTIFICATION_SERVICE/NotificationManagerService)}; allowBackgroundActivityStart: false; intent: Intent { cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras) }; callerApp: ProcessRecord{c06f774 13034:com.bingo.cleaner/u0a148}; inVisibleTask: false]
2022-12-25 11:34:59.287   511-857   ActivityTaskManager     pid-511                              W  startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { flg=0x800000 cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras) }
2022-12-25 11:34:59.288   511-857   ActivityTaskManager     pid-511                              E  Abort background activity starts from 10148

2022-12-25 11:34:59.288   511-857   ActivityTaskManager     pid-511                              I  START u0 {flg=0x10000000 cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras)} from uid 10148
2022-12-25 11:34:59.288   511-857   ActivityTaskManager     pid-511                              W  Background activity start [callingPackage: com.bingo.cleaner; callingUid: 10148; appSwitchAllowed: false; isCallingUidForeground: false; callingUidHasAnyVisibleWindow: false; callingUidProcState: FOREGROUND_SERVICE; isCallingUidPersistentSystemProcess: false; realCallingUid: 10148; isRealCallingUidForeground: false; realCallingUidHasAnyVisibleWindow: false; realCallingUidProcState: FOREGROUND_SERVICE; isRealCallingUidPersistentSystemProcess: false; originatingPendingIntent: null; allowBackgroundActivityStart: false; intent: Intent { flg=0x10000000 cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras) }; callerApp: ProcessRecord{c06f774 13034:com.bingo.cleaner/u0a148}; inVisibleTask: false]
2022-12-25 11:34:59.289   511-857   ActivityTaskManager     pid-511                              E  Abort background activity starts from 10148

2022-12-25 11:34:59.522   511-543   ActivityTaskManager     pid-511                              I  START u0 {cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras)} from uid 10148
2022-12-25 11:34:59.522   511-543   ActivityTaskManager     pid-511                              W  startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { flg=0x800000 cmp=com.bingo.cleaner/.modules.scene.fork.ForkActivityC (has extras) }
2022-12-25 11:34:59.527   511-543   ActivityTaskManager     pid-511                              W  Can't find TaskDisplayArea to determine support for multi window. Task id=27 attached=false
2022-12-25 11:34:59.606   511-852   ActivityTaskManager     pid-511                              W  Tried to set launchTime (0) < mLastActivityLaunchTime (556847)
2022-12-25 11:34:59.914   511-546   ActivityTaskManager     pid-511                              I  Displayed com.bingo.cleaner/.modules.scene.fork.ForkActivityC: +325ms

Note, I intentionally added blank lines to the logcat to make it clearer.
So the app tries to launch an activity 3 times and gets rejected by the system. However on the 4th time it somehow succeeds!
Please take a look on the video of my screen recording: https://yura-misc.s3.eu-central-1.amazonaws.com/activity_from_bakcground.mov
P.S.
What I have tried (from onReceive of the runtime-registered broadcast receiver):

*

*starting the activity in a loop up to 10 times (to replicate what the sample app is doing)

*showing a notification along with starting the activity (I thought the notification could increase priority of my app)

*starting another foreground service and launching the activity from it (I thought it  could increase priority of my app too)

*sending a Pending Intent instead of regular intent to start the activity

I suppose this must be some kind of a hack, which is potentially android system vulnerability.
Do you please have any ideas of what could it be or in what direction would I want to look?

A: I am also facing a similar issue. I have a database where phone number saves time by time, and my application has to call those number even my app is in the background. But when I tried it on the android 12 emulator it works well. works in the background but the call cut on start.. and when I tried it on android 10. it didn't work in the background but works well in the foreground.
I also have a notification on that app, so the process not finish.
I don't know, what to do now!
you can see here.
you have to get the SYSTEM_ALERT_WINDOW permission by the user.
also, here are given multiple conditions. .check, and if yours is solved, please write here. My problem isn't solved.
https://developer.android.com/guide/components/activities/background-starts


text:
Q: Dark Theme not applying in some recyclerview items I have an app with multiple activities and fragments, and inside them there are recycler views. On one of my fragments, the recycler view items change to dark theme automatically, just like they should. But when using the exact same adapter class and exact same item layout on a different activity, it not longer applies the dark theme.
Item Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">

        <androidx.cardview.widget.CardView
            android:id="@+id/crv_anime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:foreground="?android:attr/selectableItemBackground"
            android:clipToPadding="false"
            android:layout_marginBottom="14dp"
            app:cardCornerRadius="10dp"
            android:layout_marginTop="28dp"
            app:cardElevation="10dp"
            android:layout_centerHorizontal="true">

            <RelativeLayout
                android:layout_width="550px"
                android:layout_height="wrap_content">

                <ImageView
                    android:id="@+id/img_anime_cover"
                    android:layout_width="550px"
                    android:layout_height="777px"
                    android:layout_centerHorizontal="true"/>

                <TextView
                    android:id="@+id/lbl_anime_title"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/img_anime_cover"
                    android:layout_marginBottom="10dp"
                    android:layout_marginTop="10dp"
                    android:textAlignment="center"
                    android:fontFamily="@font/segoeb"
                    android:paddingLeft="5dp"
                    android:paddingRight="5dp"
                    android:textSize="16sp"/>

            </RelativeLayout>
        </androidx.cardview.widget.CardView>
</RelativeLayout>

Adapter Class:
package com.animewatcher.animewatcher;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;

public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.ViewHolder> {

    List<anime_class> mAnime;
    Context mContext;
    LayoutInflater inflater;

    public RecycleAdapter(Context context, List<anime_class> anime){
        this.mAnime = anime;
        this.inflater = LayoutInflater.from(context);
        this.mContext = context;
    }

    @NonNull
    @Override
    public RecycleAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.grid_layout, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecycleAdapter.ViewHolder holder, int position) {
            holder.title.setText(capitalizeLetters(mAnime.get(position).getmNameEN()));
            Glide.with(mContext).load(mAnime.get(position).getmThumbnail()).into(holder.thumbnail);

            holder.crv_.setOnClickListener(
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent i = new Intent(mContext, anime_page.class);
                            i.putExtra("mNameEN", mAnime.get(position).getmNameEN());
                            i.putExtra("mThumbnail", mAnime.get(position).getmThumbnail());
                            mContext.startActivity(i);
                        }
                    }
            );
    }

    @Override
    public int getItemCount() {
        return mAnime.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder{
        TextView title;
        ImageView thumbnail;
        CardView crv_;

        public ViewHolder(@NonNull View itemView){
            super(itemView);
            title = itemView.findViewById(R.id.lbl_anime_title);
            thumbnail = itemView.findViewById(R.id.img_anime_cover);
            crv_ = itemView.findViewById(R.id.crv_anime);
        }
    }

    private String capitalizeLetters(String str)
    {
        String[] strArray = str.split(" ");
        StringBuilder builder = new StringBuilder();
        for (String s : strArray) {
            String cap = s.substring(0, 1).toUpperCase() + s.substring(1);
            builder.append(cap + " ");
        }

        return builder.toString();
    }
}

Fragment code (where the dark theme is working):
if (getActivity()!=null) {
                        if(getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
                            adapter = new RecycleAdapter(getActivity(), animes);
                            GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3, GridLayoutManager.VERTICAL, false);
                            animeList.setLayoutManager(gridLayoutManager);
                            animeList.setAdapter(adapter);
                        }
                        else
                        {
                            adapter = new RecycleAdapter(getActivity(), animes);
                            GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2, GridLayoutManager.VERTICAL, false);
                            animeList.setLayoutManager(gridLayoutManager);
                            animeList.setAdapter(adapter);
                        }
                    }

Activity code (where dark theme is not working):
if (getApplication()!=null) {
                            if(getApplicationContext().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
                                adapter = new RecycleAdapter(getApplicationContext(), animes);
                                GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(), 3, GridLayoutManager.VERTICAL, false);
                                animeList.setLayoutManager(gridLayoutManager);
                                animeList.setAdapter(adapter);
                            }
                            else
                            {
                                adapter = new RecycleAdapter(getApplicationContext(), animes);
                                GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(), 2, GridLayoutManager.VERTICAL, false);
                                animeList.setLayoutManager(gridLayoutManager);
                                animeList.setAdapter(adapter);
                            }
                        }

Image of the dark theme correctly applied
Image of the item not applying dark theme

A: I think I've got your problem. On the second code provided (Dark theme not applied), you've used getApplicationContext() which is not ActivityContext aware, and so theme not applied properly. Use Activity context instead (getActivity() if inside fragment or Activity.this if inside Activity) like the first code.
adapter = new RecycleAdapter(getActivity(), animes);
GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3, GridLayoutManager.VERTICAL, false);

A: possible solutions:
1- check theme applied to that activity which is not showing items in dark mode.
2- check if you set background color to white in that activity main layout or recyclerview.
Your code seems fine.


text:
Q: how to include or require a view into another view MVC I want to create a page that will act as a sidebar on all pages. This sidebar shows some widgets which should get records from the database. I don't want to have to copy and paste this sidebar code into every single other view but rather want to require or include it.
I am not sure how to go about this but what I tried was:

*

*Created a folder in the views folder called "widgets" and put an
index.php file in it.

*Created a Widgets.php file in the controllers folder

*Created a Widget.php file in the models folder

*Send the data from the model to the controller and sent to the view.

If I go directly to the index.php file in the widgets view, it works fine and the database records are displayed as I want.
However, if I try and include this index file in another view somewhere else, I get an "undefined index" and "invalid argument supplied foreach()".
So, what is the proper way to achieve this?
PS.I am not using a framework and this is my controller:
public function index()
    {

        $widgets = $this->widgetModel->getWidgets();

        $data = [

        'widgets' => $widgets

        ];

        $this->view('widgets/index', $data);
    }


text:
Q: Move item to bottom of listView on click I'm having a hard time figuring this one out, I need to be able to click on an item of a listview, and move that item to the bottom of the list with some background color change to make a difference, then if clicked back return it to the original position in the list.
I've tried with list.addFooterView() but I can't make it work that way, it just attach an empty item to the footer, I couldn't make it go back to it's original position.
Here is my code so far. Any ideas on how to tackle this are appreciated.
ActivityProductsBuy.java
package com.roneskinder;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.roneskinder.model.DataProducts;
import com.roneskinder.utils.DatabaseHandler;
import com.roneskinder.x111.R;

public class ActivityProductsBuy extends Activity {

    protected Context mContext;

    protected DatabaseHandler db;
    private SQLiteDatabase newDB;
    private String tableProducts = DatabaseHandler.TABLE_PRODUCTS;

    protected ListView lvProducts;
    protected String title, idProduct, idGroceryList, ProductCode, ProductName;
    protected int totalItems, itemsInCart = 0;
    protected Button btn_itemsInCart;
    protected TextView tv_percentText;

    /** The data used for products */
    private List<DataProducts> info;

    /** The Adapter holds the listview. */
    private ProductsItemAdapter adapter1;

    private static final int ZBAR_SCANNER_REQUEST = 0;

    protected SharedPreferences preferences;

    protected String TAG = ActivityProductsBuy.class.getName();

    ImageView imgHolder;
    Paint paint;
    EditText edtPercentage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_products_buy);

        mContext = getApplicationContext();

        // Get Database values for User
        db = new DatabaseHandler(mContext);

        preferences = PreferenceManager.getDefaultSharedPreferences(this);

        // remove and add products to DB
        //db.removeAllProducts();
        // this.addProducts();

        // get intent Extras (the title, list id)
        //title = getIntent().getExtras().getString("title");
        idGroceryList = getIntent().getExtras().getString("idGroceryList");

        lvProducts = (ListView) findViewById(R.id.lvProducts);

        info = new ArrayList<DataProducts>();
        imgHolder = (ImageView) findViewById(R.id.coringImage);
        btn_itemsInCart = (Button) findViewById(R.id.btn_itemsInCart);
        tv_percentText = (TextView) findViewById(R.id.percentText);
        tv_percentText.setText("0%");

        paint = new Paint();

        adapter1 = new ProductsItemAdapter(this, info);

        // load all database products into listview
        lvProducts.setAdapter(adapter1);
        loadProducts();
        totalItems = adapter1.getCount();

        lvProducts.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                itemsInCart++;
                if(itemsInCart <= totalItems){
                    btn_itemsInCart.setText("(" + itemsInCart + "/"+ totalItems +")");
                    // Fill percentage of image
                    float percentage = ((float)itemsInCart/(float)totalItems)*100;
                    Log.d(TAG, "percentage: " + percentage);
                    imgHolder.setImageResource(R.drawable.cart_default);

                    if (percentage > 0 && percentage <= 100) {
                        imgHolder.setImageBitmap(doBottomToTopOperation(Math.round(percentage)));
                        tv_percentText.setText((int)percentage + "%");
                    }
                }
            }
        });
    }

    public void loadProducts() {
        info.clear();
        ((BaseAdapter) lvProducts.getAdapter()).notifyDataSetChanged();
        Cursor cur = null;
        try {
            newDB = db.getWritableDatabase();
            cur = newDB.rawQuery(
                    "SELECT idProduct, ProductCode, name FROM "
                            + tableProducts + " WHERE idGroceryList = " + idGroceryList, null);

            Log.d(TAG, DatabaseUtils.dumpCursorToString(cur));

            if (cur != null) {
                // tvNoProducts.setVisibility(View.GONE);
                if (cur.moveToFirst()) {
                    do {
                        idProduct = cur.getString(cur.getColumnIndex("idProduct"));
                        ProductCode = cur.getString(cur.getColumnIndex("ProductCode"));
                        ProductName = cur.getString(cur.getColumnIndex("name"));

                        info.add(new DataProducts(ProductName, ProductCode,idProduct, "Vegetales", "0", idGroceryList));
                    } while (cur.moveToNext());
                }
            } else {
                // tvNoProducts.setVisibility(View.VISIBLE);
            }
        } catch (SQLiteException se) {
            Log.e(getClass().getSimpleName(),
                    "Could not create or Open the database");
        }

    }

    /**
     * The Class ProductsItemAdapter.
     */
    private class ProductsItemAdapter extends BaseAdapter {

        /** The context. */
        private Context context;

        /** The list. */
        private List<DataProducts> list;

        /** The inflater. */
        private LayoutInflater inflater;

        /**
         * Instantiates a new deal item adapter.
         *
         * @param context
         *            the context
         * @param list
         *            the list
         */
        public ProductsItemAdapter(Context context, List<DataProducts> list) {
            this.context = context;
            this.list = list;
        }

        /*
         * (non-Javadoc)
         *
         * @see android.widget.Adapter#getCount()
         */
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }

        /*
         * (non-Javadoc)
         *
         * @see android.widget.Adapter#getItem(int)
         */
        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

        /*
         * (non-Javadoc)
         *
         * @see android.widget.Adapter#getItemId(int)
         */
        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        /*
         * (non-Javadoc)
         *
         * @see android.widget.Adapter#getView(int, android.view.View,
         * android.view.ViewGroup)
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                inflater = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.adapter_products, null);
            }
            TextView txt1 = (TextView) convertView
                    .findViewById(R.id.tvProductName);
            TextView txt2 = (TextView) convertView
                    .findViewById(R.id.tvProductCode);
            TextView tv1 = (TextView) convertView
                    .findViewById(R.id.tvProductPrice);
            TextView tv2 = (TextView) convertView
                    .findViewById(R.id.tvProductCategory);

            final DataProducts dInfo = list.get(position);
            txt1.setText(dInfo.getProductName());
            txt2.setText(dInfo.getProductCode());

            tv1.setText(dInfo.getProductPrice());
            // tv1.setPaintFlags(tv1.getPaintFlags() |
            // Paint.STRIKE_THRU_TEXT_FLAG);

            tv2.setText(dInfo.getProductCategory());
            return convertView;
        }

    }

    public Bitmap doBottomToTopOperation(int percentage) {
        Bitmap bitmapOriginal = ((BitmapDrawable) imgHolder.getDrawable()).getBitmap();

        Bitmap bitmapTarget = BitmapFactory.decodeResource(getResources(), R.drawable.cart_filled);

        int heightToCrop = bitmapTarget.getHeight() * (100 - percentage) / 100;

        Bitmap croppedBitmap = Bitmap.createBitmap(bitmapTarget, 0, heightToCrop, bitmapTarget.getWidth(), bitmapTarget.getHeight() - heightToCrop);

        Bitmap bmOverlay = Bitmap.createBitmap(bitmapOriginal.getWidth(),
                bitmapOriginal.getHeight(), bitmapOriginal.getConfig());
        Canvas canvas = new Canvas(bmOverlay);
        canvas.drawBitmap(bitmapOriginal, new Matrix(), null);
        canvas.drawBitmap(croppedBitmap,
                canvas.getWidth() - croppedBitmap.getWidth(),
                canvas.getHeight() - croppedBitmap.getHeight(), null);

        return bmOverlay;
    }

}

activity_products_buy.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <com.sothree.slidinguppanel.SlidingUpPanelLayout
        xmlns:sothree="http://schemas.android.com/apk/res-auto"
        android:id="@+id/sliding_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="bottom"
        sothree:umanoPanelHeight="68dp"
        sothree:umanoShadowHeight="4dp" >

        <!-- MAIN LAYOUT -->

        <ListView
            android:id="@+id/lvProducts"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/myFilter" >
        </ListView>

        <!-- SLIDING LAYOUT -->

        <LinearLayout
            android:id="@+id/dragView"
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:background="#ffffff"
            android:clickable="true"
            android:focusable="false"
            android:orientation="vertical" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="68dp"
                android:background="#f0f0f0"
                android:orientation="horizontal" >

                <TextView
                    android:id="@+id/name"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:gravity="center_vertical"
                    android:paddingLeft="10dp"
                    android:text="Total de Productos en el carrito"
                    android:textColor="#000"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/btn_itemsInCart"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:gravity="center_vertical|right"
                    android:paddingLeft="10dp"
                    android:paddingRight="10dp"
                    android:text="(0)"
                    android:textColor="#000"
                    android:textSize="14sp" />
            </LinearLayout>

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

                <ImageView
                    android:id="@+id/coringImage"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:src="@drawable/cart_default" />

                <TextView
                    android:id="@+id/percentText"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignBottom="@+id/coringImage"
                    android:layout_alignLeft="@+id/coringImage"
                    android:layout_alignRight="@+id/coringImage"
                    android:layout_alignTop="@+id/coringImage"
                    android:layout_margin="1dp"
                    android:gravity="center"
                    android:text="0%"
                    android:textColor="#ffffff" />
            </RelativeLayout>
        </LinearLayout>
    </com.sothree.slidinguppanel.SlidingUpPanelLayout>

</RelativeLayout>

adapter_products.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/top"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:paddingLeft="@dimen/pad_10dp"
    android:paddingRight="@dimen/pad_10dp"
    android:paddingTop="@dimen/pad_15dp" >

    <LinearLayout
        android:id="@+id/left_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/item_img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="@dimen/pad_10dp"
            android:src="@drawable/icon_mypurchase1" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingLeft="@dimen/pad_10dp" >

        <LinearLayout
            android:id="@+id/right_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/tvProductName"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Nombre del Producto" />

                <TextView
                    android:id="@+id/tvProductCode"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingTop="@dimen/pad_2.5dp"
                    android:text="Codigo" />
            </LinearLayout>

            <View
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="right"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/tvProductPrice"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/$45"
                    android:textColor="@color/red_main"
                    android:textSize="@dimen/txt_18sp" />

                <TextView
                    android:id="@+id/tvProductCategory"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Categoria"
                    android:textSize="@dimen/txt_12sp" />
            </LinearLayout>
        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="@dimen/pad_15dp"
            android:background="@color/my_purchase_list_sap" />
    </LinearLayout>

</LinearLayout>

A: Just change index of the item in your data source, and then notifyDataSetChanged()
DataProducts item = info.get(<index>);
info.remove(<index>);
info.add(item);
adapter1.notifyDataSetChanged();

Set background for the bottom item in getView,
if (position==getCount()-1){
    convertView.setBackground(<backgroud>);
}

If you want move it back,
DataProducts item = info.get(info.size()-1);
info.remove(info.size()-1);
info.add(<original_index>,item);
adapter1.notifyDataSetChanged();


text:
Q: InfluxDB and relational metadata? I am currently working on a project with InfluxDB, where I have to track and store several measurements. My issue: For all my measurement I also need to store some additional relational metadata (for reporting), which only change once or twice a week. Moreover I have some config data, for my applications..
So my question: Do you have any suggestions or experience with storing time-series and relational data like that? Should I try to store everything (even the relational data) within the InfluxDB or should I use an external relational DB for that?
Looking forward to your help!
Marko


text:
Q: Storing multiple object types in a List I have following homework about computer store:

*

*There are several class include: Monitor, Case, Mouse, Keyboard.

*All the classes have common fields: id, name, price, quantity.

*Each class has some unique fields.
All most features are: add, update, delete, find, show list, save, load file
-So, first I will create a class named Product have 4 common fields. Above classes will extends from Product.
-Then, I think I maybe create a ComputerStore class which have a field is items type ArrayList. items stores all objects which are instance of 4 above classes  But I'm not sure.
Whether it is reasonable? I need some ideas
Before , I always use ArrayList store for only one class like
List <String> list = new ArrayList<String>();

Now they are multi type. I think it's generic in Java, right??
In case, I want to update for 1 items. I must think about how to change information for them. Ex: mouse for some code, keyboard for another code. Anyway, thank for everybody!

A: Your approach is 100% reasonable.
You are completely on the right track with "generics". First, check out the official enter link description here.
Next, just think about your data in real world terms, like you are already doing: Monitor, case, mouse, and keyboard are products. Your computer store's inventory is a list of products.
Hint: A list of products.
Put that together with what you learn about generics through that tutorial, and you'll be good to go.

A: You could use java generic.First create a java collection (ex: List) with supper class type, Product. Now you could add any sub classes (Monitor , Keyboard etc) in your collection (List) that extends of class Product.
public class Product{

}
public class Monitor extends Product{

}

public class Keyboard extends Product{

}

List<Product> products = new ArrayList<Product>();
products.add(new Monitor());
products.add(new Keyboard());

A: Since you have a superclass (Product), you can have the list's type as Product, i.e.
List<Product> list = new ArrayList<Product>();
list.add(new Mouse());
list.add(new Keyboard());

It will allow you to iterate them and list their name and price without caring for the class, but if you intend to take an item out of the list you'll need to check its actual type (depending on what you do with it).

A: You can do like below
import java.util.List;
import java.util.ArrayList;

class Test{
public static void main(String... args){
    List<MultiObj> multiObjs = new ArrayList();

    MultiObj ob = new MultiObj(); multiObjs.add(ob);
    ResX xOb = new ResX(); multiObjs.add(xOb);
    ResY yOb = new ResY(); multiObjs.add(yOb);
    ResZ zOb = new ResZ(); multiObjs.add(zOb);

    for (int i = 0; i < multiObjs.size(); i++ ) {
        System.out.println(multiObjs.get(i).getV());
    }
    System.out.println("Waoo its working");
 }
}
class MultiObj{
public String greet(){
    return "Hello World";
}
public String getV(){
    return "Hello World";
 }
}
class ResX extends MultiObj{
String x = "ResX";
public String getX(){
    return x;
}
public String getV(){
    return x;
 }
}
class ResY extends MultiObj{
String y = "ResY";
public String getY(){
    return y;
}
public String getV(){
    return y;
 }
}
class ResZ extends MultiObj{
String z = "ResZ";
public String getZ(){
    return z;
}
public String getV(){
    return z;
 }
}

A: You could do this:
public class Item {

public Item(int id, string name, float price, int amount, int ArrayID) {
if (ArrayID == 1) {
ID1 = id;
name1 = name;
price1 = price;
amount1 = amount;
}
if (ArrayID == 2) {
ID2 = id;
name2 = name;
price2 = price;
amount2 = amount;
}
if (ArrayID == 3) {
ID3 = id;
name3 = name;
price3 = price;
amount3 = amount;
}
if (ArrayID == 4) {
ID4 = id;
name4 = name;
price4 = price;
amount4 = amount;
}

}

//ArrayID #1
public static int ID1;
public static String name1;
public static float price1;
public static int amount1;

//ArrayID #2
public static int ID2;
public static String name2;
public static float price2;
public static int amount2;

//ArrayID #3
public static int ID3;
public static String name3;
public static float price3;
public static int amount3;

//ArrayID #4
public static int ID4;
public static String name4;
public static float price4;
public static int amount4;

public static int[] id = ID1, ID2 ID3, ID4;
//so forth...
}


text:
Q: User fetching with Rails, BCrypt, Mongoid, and MongoLab fails in deployment I'm a first-time poster trying to wade through making MongoDB play nice with Rails and Heroku. Right now, I'm getting errors that make me think there is a problem comparing user passwords (that are supposed to be obscured with Bcrypt) during log in. Eager for more advanced eyes, or a better idea of how to troubleshoot this problem.
In the app, I find and create Users like so:
def create
 password_key = BCrypt::Password.create(params[:user][:password])
 params[:user][:password] = password_key
 newUser = User.create(params[:user])

 flash[:message] = "Account created! Please log in:"

 redirect_to controller: "users", action: "login"
end

def login
end

def find
 username = params[:user][:username]
 @user = User.where( username: username )[0]

 if @user
  if BCrypt::Password.new(@user.password) == params[:user][:password]
    session[:user_id] = @user.id
    redirect_to controller: "application", action: "home"
  else
    flash[:message] = "Wrong password. Try again."
    redirect_to controller: "users", action: "login"
  end
 else
  flash[:message] = "We didn't recognize that username."
  redirect_to controller: "users", action: "login"
 end

end

This worked fine for me in local dev. When I first deployed to Heroku, I received a "Something went wrong." error instantly upon trying to create a new user, which indicated that I didn't have my production environment configured correctly.
After more reading, I decided to use MongoLab to host my production database. I set that up with an add-on to my heroku repository following this tutorial.
Then I set my heroku env. variable MONGOLAB_URI to the appropriate URI, and included the following in my mongoid.yml file:
production:
 sessions:
 default:
  uri: <%= ENV['MONGOLAB_URI'] %>
  options:
    consistency: :strong
    safe: true
    skip_version_check: true

Now, when I access the live app, I no longer get an error when I try to create a user! I am redirected as I would expect and receive my "Account created! Please log in:" flash message.
HOWEVEVER, when I try to login with the credentials I just saved to the database, I'm redirected and my "Wrong password. Try again." flash message fires -- which to me indicates that there is some kind of issue with how passwords are being stored or compared with the combination of BCrypt/Mongoid/MongoLab.
Help, please! Is there something I'm missing about how to use BCrypt with Mongoid? This is only happening to me in production and I'm not sure how to troubleshoot.
Thanks in advance.


text:
Q: How to delete triangles from an openmesh without creating polygons? When I call mesh.delete_face(face_handle) in an OpenMesh using OpenMesh::TriMesh_ArrayKernelT<> I get somehow faces with more than 3 vertices, possibly a polygon around the hole created by deleted faces.
How can I avoid this to just get a boundary around the hole but no polygon? I am a bit surprised that a TriMesh can contain polygonal faces.

A: Calling garbage collection fixes this.
I am a bit surprised as I would have thought you need to call garbage collection after removing and adding faces so you do not delete intermediate configurations possibly losing some objects your handles are pointing to.


text:
Q: MVC Model is null after calling RedirectToAction I'm experiencing a NullReferenceException when I attempt a RedirectToAction after completing a POST Action. Here is a summary of what I'm attempting:
After an Application is POST'ed, if the Application is valid I want the client redirected to another View (and Route) for follow-on processes.
[HttpPost]
public ActionResult SubmitApplication(Application application)
{
    // Do stuff

    if (!ModelState.IsValid)
    {
        return View(application);
    }

    // Create and set variables for the next route

    return RedirectToAction("ApplicationReview", new
    {
        x = "foo",
        y = "bob"
    });
}

[HttpGet]
public ActionResult ApplicationReview(string x, string y)
{
    // Do stuff using x and y as keys

    return View();
}

In the SubmitApplication View I have code similar to the following, although it is more elaborate. After the RedirectToAction is called the Model object in the SubmitApplication View is null and throws an exception. I can sort-of understand why the SubmitApplication View is returned as part of the redirect process, I just can't figure out why the Model is null or how to set it. In the end, the target Action is never reached presumably because the redirect never really occured.
@if (Model.HasSomething)
{
    ...
}

What am I doing wrong? Is there a better way to do this?

A: The second parameter in RedirectToAction is not for the model, but for the routeValues.
To maintain state temporarily for a redirect result, you need to store your data in TempData.

A: It's a little unclear to me what you mean when you say After the RedirectToAction is called the Model object is null and throws an exception., because in the code you show you don't do anything with the Model after you call RedirectToAction.
Do you mean the Model is null in your ApplicationReview view?
EDIT:
A null reference exception indicates that variable is being dereferenced.  There is nothing there that dereferences the model.  Perhaps if you posted the stack track it would help.


text:
Q: Prevent iOS from killing my app after 3 minutes To avoid implementing a persistent caching logic of a whole navigation stack I want to keep my app "alive" (at least for 2 hours) even in the background, so when the user reopens the app it is where it was before going to sleep.
I tried with a background task:
_timerBackgroundTaskId = UIApplication.SharedApplication.BeginBackgroundTask(() =>
{
    // Run some dummy code here. Shouldn´t this prevent the task from actually stopping?
    var remaining = UIApplication.SharedApplication.BackgroundTimeRemaining;
    this.Log().Debug($"Expiration. Remaining: {remaining}. Timer seconds left: {_secondsLeft}");
});
// I´m actually using the timer for something :)
_nsTimer = NSTimer.CreateRepeatingScheduledTimer(TimeSpan.FromSeconds(1), delegate { TimerTick(); });

// later on (after 3 minutes)
UIApplication.SharedApplication.EndBackgroundTask(_timerBackgroundTaskId.Value);

No matter what I try, after 3 minutes iOS kills the app.
Some answers in SO tell how to do it with a fake/silent background sound, but I don´t want any trouble with Apple reviews.
Any advice?

A: In fact, the app was killed because I was running a background task longer than 3 minutes, which is the limit.
The solution to my problem was as easy as limiting the task to 3 minutes max.
By default iOS won´t ever kill your app, unless the device runs severely out of memory.
The 3 minutes limit is applied ONLY when you run some task in the background (i.e: UIApplication.SharedApplication.BeginBackgroundTask) to prevent battery drain.
If you don´t start any background task before the app goes to background, the app will always be there, keeping the state (I´ve tested this waiting for hours).
In my case I was using a background task to keep a countdown/alarm working.
But I´ve just found a workaround scheduling local notifications.
If you MUST run a background task, to keep the app state you´ve got 2 options:

*

*End the task before 3 minutes

*Implement a restoring strategy. iOS itself provides a built-in
API for it.


text:
Q: How to draw (Cartesian, cylindrical, and spherical) coordinates and differential elements? How to draw the following figures?
I tried to do it myself, not an easy job, apparently! I did also find these relevant posts:

*

*For the 1st pic: 3D Cube within a cube?

*For the 2nd & 3rd pics: Draw in cylindrical and spherical coordinates
However, the drawings are a little bit weird and not so accurate. Any help would be appreciated.

A: The figure in spherical coordinates can be found
here
The code for cylindrical coordinates is next:
  \documentclass{article}
\usepackage[pdftex]{graphicx}
\usepackage{tikz}
\usepackage{amssymb,amsfonts,amsmath}
\usepackage{tikz,tkz-euclide}
\usetikzlibrary{arrows,calc,patterns}

\begin{document}
\begin{figure}
  \begin{center}
    \begin{tikzpicture}
      \coordinate (O) at (0,0);
      \coordinate (Ox) at (-3,-3);
      \coordinate (Oy) at (4.243,0);  % sqrt{18}
      \coordinate (Oz) at (0, 6);

      % draw axis
      \draw[-latex, line width=1] (O)-- (Ox) node[below] {$x$};
      \draw[-latex, line width=1] (O)-- (Oy) node[right] {$y$};
      \draw[-latex, line width=1] (O)-- (Oz) node[above] {$z$};

      % draw arcs
       \draw[thick] ($(0, 0) + (236:3cm and 2cm)$(P) arc
         (236:360:3cm and 2cm);
       \draw[thick] ($(0, 0) + (236:3cm and 2cm)$(P) arc
         (236:360:3cm and 2cm);

       \draw[thick] ($(0, 5) + (236:3cm and 2cm)$(P) arc
         (236:360:3cm and 2cm);

       \draw[thick, -latex] ($(0, 0) + (236:1.5cm and 1cm)$(P) arc
         (236:310:1.5cm and 1cm);

         \coordinate (Phi) at (0,-1) ;
         \node[below] at (Phi) {$\theta$};

      \coordinate (A1) at (0, 5);
      \coordinate (B) at (3, 5);
      \coordinate (C) at (-1.7, 3.3);
      \draw[thick] (A1)--(B);
      \draw[thick] (A1)--(C);

      % radius
      \coordinate (D) at (1.9,-1.5);
      \coordinate (P) at (1.9,3.5);
      \draw[thick] (O)--(D);
      \draw[thick, dashed] (A1)--(P) node[right, yshift=-1mm] {$P$};
      \draw[thick] (D)--(P);
      \fill[black] (P) circle (3pt);

      \coordinate (A) at (2.6, 4.0);
      \draw[thick, dashed] (A1)--(A) node[right, yshift=-1mm, xshift=-1mm] {$A$};

      % arcs
       \draw[thick] ($(0, 5) + (310:1.8cm and 1.2cm)$(P) arc
         (310:330:1.8cm and 1.2cm);

       \draw[thick] ($(0, 3.5) + (310:1.8cm and 1.2cm)$(P) arc
         (310:330:1.8cm and 1.2cm);

       \draw[thick] ($(0, 3.5) + (310:3cm and 2cm)$(P) arc
         (310:330:3cm and 2cm);

       \coordinate (Q) at (1.9,1.97);
       \node[below,xshift=2mm] at (Q) {$Q$};
        % \fill[black] (Q) circle (3pt);

      \coordinate (B) at (2.6, 2.5);
      \node[below,xshift=1mm] at (B) {$B$};
       % \fill[black] (B) circle (3pt);
      \draw[thick] (A) --(B);

      \coordinate (S) at (1.15, 4.1);
      \node[below, xshift=-2mm] at (S) {$S$};
       % \fill[black] (S) circle (3pt);

      \coordinate (R) at (1.15, 2.6);
      \node[below, xshift=-2mm] at (R) {$R$};
       %\fill[black] (R) circle (3pt);

      \coordinate (D) at (1.52, 4.42);
      \node[above] at (D) {$D$};
      % \fill[black] (D) circle (3pt);

      \coordinate (C) at (1.54, 2.86);
      \node[below] at (C) {$C$};
      %\fill[black] (C) circle (3pt);

      \draw[thick] (S) --(R);
      \draw[thick] (D) --(C);
      \draw[thick] (R) --(Q);
      \draw[thick] (C) --(B);

      % verticals on the planes
      \coordinate (H) at (-1.65,-1.65);
      %\fill[black] (H) circle (3pt);
      %
      \coordinate (I) at (-1.65,3.35);
      %\fill[black] (I) circle (3pt);
      \draw[thick] (H) --(I);

      \coordinate (J) at (3,0);
      %\fill[black] (J) circle (3pt);
      \coordinate (K) at (3,5);
      %\fill[black] (K) circle (3pt);
      \draw[thick] (J) --(K);

      % filling
      \filldraw[opacity=0.2]
          (D)--(A) arc (325:306:3cm and 2.2cm)--(S)
           arc (305:325:1.8cm and 1.2cm)--cycle;

      \filldraw[opacity=0.2]
          (P) arc (306:325:3cm and 2.2cm)--(B)
           arc (325:306:3.0cm and 2.2cm)--cycle;

       \filldraw[opacity=0.2]
         (P)--(Q)--(R)--(S)--cycle;

      % differential labels
      \node[right, yshift=1mm,xshift=2mm, rotate=-20] at (Q) {$\rho d \theta$};
      \node[right, yshift=6mm, xshift=-1mm ] at (B) {$dz$};
      \node[right,xshift=3mm, yshift=2mm, rotate=-20] at (D) {$d \rho$};

    \end{tikzpicture}
  \end{center}
\end{figure}
\end{document}

The picture is
The cube, is easy and left as homework.


text:
Q: What could be the simple way to integrate data table using AngularJS as I am new to AngularJS? I would like to implement data table just like data table we use in Bootstrap in AngularJS with all the functionalities like sorting pagination ,etc

A: After trying out ngGrid, ngTable, trNgGrid and Smart Table, I have come to the conclusion that Smart Table is by far the best implementation AngularJS-wise and Bootstrap-wise. It is built exactly the same way as you would build your own, naive table using standard angular. On top of that, they have added a few directives that help you do sorting, filtering etc. Their approach also makes it quite simple to extend yourself. The fact that they use the regular html tags for tables and the standard ng-repeat for the rows and standard bootstrap for formatting makes this my clear winner.
Their JS code depends on angular and your html can depend on bootstrap if you want to. The JS code is 4 kb in total and you can even easily pick stuff out of there if you want to reach an even smaller footprint.
Where the other grids will give you claustrophobia in different areas, Smart Table just feels open and to the point.
If you rely heavily on inline editing and other advanced features, you might get up and running quicker with ngTable for instance. However, you are free to add such features quite easily in Smart Table.
Don't miss Smart Table!!!
I have no relation to Smart Table, except from using it myself.


text:
Q: Excel VBA to get all meetings from Outlook including recurrences this is my first time posting to StackOverflow so please bare with me if I'm doing something wrong.
I am using the following macro to get a list of meetings older than 7 days but I can't figure out how to get it to show recurring meetings. Can you please point out what I'm doing wrong?
  Option Explicit

Sub ListAppointments()

Dim olApp As Object
Dim olNS As Object
Dim olFolder As Object
Dim olApt As Object
Dim NextRow As Long

Set olApp = CreateObject("Outlook.Application")

Set olNS = olApp.GetNamespace("MAPI")

Set olFolder = olNS.GetDefaultFolder(9)
Worksheets("GetMeetings").Activate

Range("A1:e1").Value = Array("Organizer", "Subject", "Start", "End")

NextRow = 2

   For Each olApt In olFolder.Items
    If (olApt.Start >= Now - 7) Then

    Cells(NextRow, "A").Value = olApt.Organizer
    Cells(NextRow, "B").Value = olApt.Subject
    Cells(NextRow, "C").Value = olApt.Start
    Cells(NextRow, "D").Value = olApt.End
    'Cells(NextRow, "E").Value = olApt.Location
        NextRow = NextRow + 1
        Else
    End If
Next olApt

    'AutoFit
    Worksheets("GetMeetings").Columns.AutoFit

Set olApt = Nothing
Set olFolder = Nothing
Set olNS = Nothing
Set olApp = Nothing

Columns.AutoFit

End Sub

A: You can expand recurrences if you use Items.Find/FindNext or Items.Restrict and set the Items.IncludeRecurrences to true. See https://learn.microsoft.com/en-us/office/vba/api/outlook.items.includerecurrences for an example and more details.


text:
Q: calculate and replace values inside span I have a site where I show the number of days the product is stored and a percentage of the total is charged based on the days. data-ref holds the percentage value to charge.

var thistotal = $("#total").text();

var percent1 = $("#date-1").attr("data-ref");
var delrate1 = $("#date-rate-1").text();
var replace1_total = thistotal.replace("€", "").replace(",", ".").replace("+", "");
var percentVal = (percent1 / 100) * replace1_total;
$('#date-1').html(percentVal);

Day

      1

        $18.00
        + $10.00

Day

        3

          + $10.00

Day

        5

          + $10.00

$100.00

To display the amount charged by day, I get the percentage value from the span's data-ref attribute, calculate the percentage from the total, and add it to the contents of that span.
I'm individually adding each id ("date-1", "date-2", etc.) to the span, performing the calculation, and its working fine. But the problem is there are many new options added, and some options are not added to certain products. So I have to duplicate the code to do each calculation (The numbers on the ids are the actual day values. Added them to make the ids unique).
What would be the be the best way to achieve this percentage calculation without duplicating the code?

A: If I understand your problem correctly then you can use class selector, like this:
$('.thedate').each((index, item)=>{
  const dateRef = +($(item).attr("data-ref"))
  const dateRate = +($(item).next().html().replace("€", "").replace("$", "").replace(",", ".").replace("+", "").replace(" ", ""))
  $(item).parent().html((dateRef / 100) * dateRate)
})

A: It appears that this is the intended process:

*

*get total from contents of

*get all spans with class="thedate"

*get percent from span's data-ref attribute

*update span's contents using a calculation(percent, total)

The following will produce the intended outcome for all spans with class="thedate":

function setTheDatePrices(total) {

  // get all spans with 'class="thedate"'
  let theDates = Array.from(document.getElementsByClassName('thedate'));

  // set the contents of each "thedate" span
  theDates.forEach(theDate => {
    let percent = Number(theDate.dataset.ref);
    theDate.innerHTML = '$' + (percent / 100 * total).toFixed(2);
  });
}

let run = () => {};

window.onload = () => {

  // obtain total from contents of  `<div id="total">`
  const total = Number(
    document.getElementById('total')
    .innerHTML.match(/[-+]?[0-9]*\.?[0-9]+/)
  );

  run = () => setTheDatePrices(total);

}
<button onclick="run();">Set "thedate" Prices</button>

Day

      1

        + $10.00

Day

        3

          + $10.00

Day

        5

          + $10.00

$100.00


text:
Q: Order of initialization and destruction of block-scope static vs. namespace-scope thread_local in main thread I'm trying to understand the sequencing rules for initialization and destruction of namespace-scope and block-scope objects with static storage duration and thread-local storage duration in the context of the main thread. Consider these two classes:
struct Foo {
    Foo() { std::cout << "Foo\n"; }
    ~Foo() { std::cout << "~Foo\n"; }
    static Foo &instance();
};
struct Bar {
    Bar() { std::cout << "Bar\n"; }
    ~Bar() { std::cout << "~Bar\n"; }
    static Bar &instance();
};

They are identical except for the implementations of their static instance member functions:
thread_local Foo t_foo;
Foo &Foo::instance() { return t_foo; }

Bar &Bar::instance() { static Bar s_bar; return s_bar; }

Bar is a Meyers singleton, a block-scope object with static storage duration.
Foo's instance is a namespace-scope object with thread-local storage duration.
Now the main function:
int main() {
    Bar::instance();
    Foo::instance();
}

Here's the output from GCC 8.1.0 and Clang 5.0.0:
Bar
Foo
~Foo
~Bar

Try it live: https://coliru.stacked-crooked.com/a/f83a9ec588aed921
I had expected that Foo would be constructed first, because it is at namespace scope. I suppose the implementation is permitted to defer the initialization until the first odr-use of the object. I didn't know it could be deferred until after the initialization of a block-scope static, but I can live with that.
Now I reverse the order of the function calls in main:
int main() {
    Foo::instance();
    Bar::instance();
}

And here's the output:
Foo
Bar
~Foo
~Bar

Now I've moved the first odr-use of the Foo instance to before the first call to Bar::instance, and the order of initialization is as I expected.
But I thought the objects should be destroyed in the reverse order of their initialization, which does not appear to be happening. What am I missing?
In relation to the initialization and destruction of objects of static and thread-local storage duration, cppreference and the standard say things like "when the program starts", "when the thread starts", "when the program ends", and "when the thread ends", but how do these concepts relate to each other in the context of the main thread? Or to be more precise, the first thread and the last thread?
In my "real" problem, Foo (the thread-local) is used by the logger, and the destructor of the base class of Bar uses the logger, so it's a static destruction order fiasco. Other threads are spawned, but Bar (the Meyers singleton) is constructed and destroyed in the main thread. If I could understand the sequencing rules, then I could try to solve the "real" problem without resorting to just trying things at random.

A: The standard guarantees that destruction of Foo(the thread local storage) is before Bar(the static storage):
[basic.start.term]/2

The completions of the destructors for all initialized objects with thread storage duration within that thread strongly happen before the initiation of the destructors of any object with static storage duration.

However, there is no guarantee about the construction order. The standard only says that the thread local should be constructed before its first odr-use:
[basic.stc.thread]/2

A variable with thread storage duration shall be initialized before its first odr-use


text:
Q: Kauth event upon start process. - prevention capabilities I'd like to get event in kernel on each new process that starts (fork+execve or posix_spawn), and be able to prevent this operations.
The first option would be using Mac framework named mpo_vnode_check_exec by Hooking to this method with function that return 0 when access is granted or check deferred to next hook.. non zero returned value means access is refused right away.
Unfortunately, this framework is unsupported by apple, and I wish to use a stable alternative like kauth fileop scope with KAUTH_FILEOP_EXEC flag.
However, this framework is for detection only and lacks prevention capabilities..
Perhaps there's a way to prevent the process from running when I get relevant kauth callback on process creation, or halt the process from running until I decide whether it should run or not (and enforce the verdict in another thread).
thanks

A:
However, this framework is for detection only and lacks prevention capabilities..

Correct, if you're only focussing on the File scope.
Register with the Vnode scope and your callback returns whether or not access is allowed.
kauth_listen_scope(KAUTH_SCOPE_VNODE, &myCallback, NULL);

Finally, note that this scope is very noisy, as every type of access to every resource is reported.


text:
Q: ASP.NET Automated deployment to remote ftp server Does anyone know any good solutions for automated deployment to a remote server using SFTP? I am specifically trying to deploy an asp.net mvc website to mosso. I can do it manually every time using an SFTP client, but would much rather have an automated (and consistent) way to do this.

A: I have written a pretty detailed blog post using TeamCity, and Web Deployment projects to automate build and deployment as a starter here:
http://www.diaryofaninja.com/blog/2010/05/09/automated-site-deployments-with-teamcity-deployment-projects-amp-svn
I have then added to this to show FTP addition
http://www.diaryofaninja.com/blog/2010/09/21/continuous-integration-tip-1-ndash-ftp-deployment
A basic process flow is pretty simple:

*

*Using a teamcity build server i download from my SVN repo

*I build and deploy the site to a local folder on the build server

*I fire a command line FTP client that supports scripting called

*WinSCP using the MSBUILD Task EXEC  (http://winscp.net/)

*Upload all my sites content

*Have [insert beverage] of choice

I then make sure that i only deploy the Trunk of my SVN repo, and develop and test everything in an branch before merging - this way only tested stuff gets deployed. Add Automated testing to your build cycle and you've got a match made in heaven.
Some great free tools to get going are:

*

*Visual Studio Web Deployment Project

*TeamCity (free for under 20 build configs)

*Bamboo

A: deployment tools under .NET solutions
Automatic Deployment Resources


text:
Q: sqlite3 multiple inserts really slow I have build a file archiver in Windows which uses sqlite3 to store files and takes advantage of multicore techniques to complete the archive faster.
I am trying a backup of 100.000 files now and insertion is slow.
When I comment the line which inserts, the app uses 100% CPU which is normal. With the insertion line on, it rarely gets above 25%.
As the archiving progresses, insertion gets more and more slow, processing a few files/second with a cpu usage of 11%. No disk usage is shown, so the bottleneck can't be the disk.
I 've:
PRAGMA temp_store = MEMORY
PRAGMA journal_mode = MEMORY
PRAGMA synchronous = OFF

and the entire insertion is within a transaction.
After further analysis it seems that SQLite's problem is to bind the blob64 (if I pass 0, it seems to be fine).
Why SQLite would have a problem inserting a raw blob of data into the archive?
Any ideas?
Thanks.

A: Your answer may lie here:
https://www.sqlite.org/threadsafe.html
Because it says there that:

The default mode is serialized.

which might explain your observations.
According to that document, you can either configure this at compile time (which I would most definitely not myself do) or via:
sqlite3_config (SQLITE_CONFIG_MULTITHREAD);

Just how stratospherically it then performs I wouldn't know.