text:
Q: Change the background color of CardView programmatically The CardView has an attribute card_view:cardBackgroundColor to define the background color.
This attribute works fine.
At the same time there isn't a method to change the color dynamically.
I've just tried solutions like:
mCardView.setBackgroundColor(...);

or using a Layout inside the cardView
   <android.support.v7.widget.CardView>
        <LinearLayout
            android:id="@+id/inside_layout">
    </android.support.v7.widget.CardView>

 View insideLayout = mCardView.findViewById(R.id.inside_layout);
 cardLayout.setBackgroundColor(XXXX);

These solutions don't work because the card has a cardCornerRadius.

A: A little late here & partially off topic since this is not programmatically but I find it best to setup styles for Widgets and you can do this for a CardView just create a style it will keep your xml cleaner...
<style name="MyCardViewStyle" parent="CardView">
    <!-- Card background color -->
    <item name="cardBackgroundColor">@android:color/white</item>
    <!-- Ripple for API 21 of android, and regular selector on older -->
    <item name="android:foreground">?android:selectableItemBackground</item>
    <!-- Resting Elevation from Material guidelines -->
    <item name="cardElevation">2dp</item>
    <!-- Add corner Radius -->
    <item name="cardCornerRadius">2dp</item>
    <item name="android:clickable">true</item>
    <item name="android:layout_margin">8dp</item>
</style>

this is using android.support.v7.widget.CardView
and then setting the style in the layout file:
 <?xml version="1.0" encoding="utf-8"?>
 <android.support.v7.widget.CardView
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_height="wrap_content"
     android:layout_width="match_parent"
     style="@style/MyCardViewStyle">
    <!-- Other fields-->
 </android.support.v7.widget.CardView>

you need to import the appcompat-v7 library using Android studio via gradle:
 dependencies {
     compile 'com.android.support:appcompat-v7:22.2.0'
 }

hope this helps. happy coding

A: It is very simple in kotlin. Use ColorStateList to change card view colour
   var color = R.color.green;
   cardView.setCardBackgroundColor(context.colorList(color));

A kotlin extension of ColorStateList:
fun Context.colorList(id: Int): ColorStateList {
    return ColorStateList.valueOf(ContextCompat.getColor(this, id))
}

A: Simplest way for me is this one (Kotlin)
card_item.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#fc4041"))

A: In Kotlin, I was able to change the background color like this:
var card: CardView = itemView.findViewById(com.mullr.neurd.R.id.learn_def_card)
card.setCardBackgroundColor(ContextCompat.getColor(main,R.color.selected))

Then if you want to remove the color, you can do this:
card.setCardBackgroundColor(Color.TRANSPARENT)

Using this method I was able to create a selection animation.
https://gfycat.com/equalcarefreekitten

A: You can use this in XML
card_view:cardBackgroundColor="@android:color/white"

or this in Java
cardView.setCardBackgroundColor(Color.WHITE);

A: What you are looking for is:
CardView card = ...
card.setCardBackgroundColor(color);

In XML
 card_view:cardBackgroundColor="@android:color/white"

Update:
in XML
app:cardBackgroundColor="@android:color/white"

A: In JAVA
cardView.setCardBackgroundColor(0xFFFEFEFE);

android use ARGB colors. you can use like this (0xFF + RGB COLOR)--Hard-coded color.

A: I used this code to set programmatically:
card.setCardBackgroundColor(color);

Or in XML you can use this code:
card_view:cardBackgroundColor="@android:color/white"

A: I came across the same issue while trying to create a cardview programmatically, what is strange is that looking at the doc https://developer.android.com/reference/android/support/v7/widget/CardView.html#setCardBackgroundColor%28int%29, Google guys made public the api to change the background color of a card view but weirdly i didn't succeed to have access to it in the support library, so here is what worked for me:
CardViewBuilder.java
    mBaseLayout = new FrameLayout(context);
    // FrameLayout Params
    FrameLayout.LayoutParams baseLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    mBaseLayout.setLayoutParams(baseLayoutParams);

    // Create the card view.
    mCardview = new CardView(context);
    mCardview.setCardElevation(4f);
    mCardview.setRadius(8f);
    mCardview.setPreventCornerOverlap(true); // The default value for that attribute is by default TRUE, but i reset it to true to make it clear for you guys
    CardView.LayoutParams cardLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    cardLayoutParams.setMargins(12, 0, 12, 0);
    mCardview.setLayoutParams(cardLayoutParams);
    // Add the card view to the BaseLayout
    mBaseLayout.addView(mCardview);

    // Create a child view for the cardView that match it's parent size both vertically and horizontally
    // Here i create a horizontal linearlayout, you can instantiate the view of your choice
    mFilterContainer = new LinearLayout(context);
    mFilterContainer.setOrientation(LinearLayout.HORIZONTAL);
    mFilterContainer.setPadding(8, 8, 8, 8);
    mFilterContainer.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT, Gravity.CENTER));

    // And here is the magic to get everything working
    // I create a background drawable for this view that have the required background color
    // and match the rounded radius of the cardview to have it fit in.
    mFilterContainer.setBackgroundResource(R.drawable.filter_container_background);

    // Add the horizontal linearlayout to the cardview.
    mCardview.addView(mFilterContainer);

filter_container_background.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="8dp"/>
<solid android:color="@android:color/white"/>

Doing that i succeed in keeping the cardview shadow and rounded corners.

A: I have got the same problem on Xamarin.Android - VS (2017)
The Solution that worked for me:
SOLUTION
In your XML file add:
 xmlns:card_view="http://schemas.android.com/apk/res-auto"

and in your  android.support.v7.widget.CardView element add this propriety:
card_view:cardBackgroundColor="#ffb4b4"

(i.e.)
<android.support.v7.widget.CardView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_margin="12dp"
    card_view:cardCornerRadius="4dp"
    card_view:cardElevation="1dp"
    card_view:cardPreventCornerOverlap="false"
    card_view:cardBackgroundColor="#ffb4b4" />

You can also add cardElevation and cardElevation.
If you want to edit the cardview programmatically you just need to use this code:
For (C#)
    cvBianca = FindViewById<Android.Support.V7.Widget.CardView>(Resource.Id.cv_bianca);
    cvBianca.Elevation = 14;
    cvBianca.Radius = 14;
    cvBianca.PreventCornerOverlap = true;
    cvBianca.SetCardBackgroundColor(Color.Red);

And now you can change background color programmatically without lost border, corner radius and elevation.

A: I was having a similar issue with formatting CardViews in a recylerView.
I got this simple solution working, not sure if it's the best solution, but it worked for me.
mv_cardView.getBackground().setTint(Color.BLUE)

It gets the background Drawable of the cardView and tints it.

A: You can use below
cardview.setBackgroundColor(Color.parseColor("#EAEDED"));

A: Use the property card_view:cardBackgroundColor:
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="fill_parent"
    android:layout_height="150dp"
    android:layout_gravity="center"
    card_view:cardCornerRadius="4dp"
    android:layout_margin="10dp"
    card_view:cardBackgroundColor="#fff"
    >

A: The way it's set in the initialize method uses the protected RoundRectDrawable class, like so:
RoundRectDrawable backgroundDrawable = new RoundRectDrawable(backgroundColor, cardView.getRadius());
cardView.setBackgroundDrawable(backgroundDrawable);

It's not pretty, but you can extend that class. Something like:
package android.support.v7.widget;

public class MyRoundRectDrawable extends RoundRectDrawable {

    public MyRoundRectDrawable(int backgroundColor, float radius) {
        super(backgroundColor, radius);
    }

}

then:
final MyRoundRectDrawable backgroundDrawable = new MyRoundRectDrawable(bgColor,
            mCardView.getRadius());
mCardView.setBackgroundDrawable(backgroundDrawable);

EDIT
This won't give you the shadow on < API 21, so you'd have to do the same with RoundRectDrawableWithShadow.
There doesn't appear to be a better way to do this.

A: You can use this in java.
cardView.setCardBackgroundColor(Color.parseColor("#cac8a0"));
code color form http://www.color-hex.com/

A: I finally got the corners to stay.  This is c#, Xamarin.Android
in ViewHolder:
CardView = itemView.FindViewById<CardView>(Resource.Id.cdvTaskList);

In Adapter:
vh.CardView.SetCardBackgroundColor(Color.ParseColor("#4dd0e1"));

A: You can use this in XML
card_view:cardBackgroundColor="@android:color/white"

or by programmatically
cardView.setCardBackgroundColor(ContextCompat.getColor(this, R.color.my_color));

A: If you wanna change card tint color just try this code it works for me.
For me this code works. I use it with card and image views but i thins it works in any view to change their tints colors. cardBookmark is my cardView name.
var cardDrawable: Drawable = binding.cardBookmark.background
cardDrawable = DrawableCompat.wrap(cardDrawable)
DrawableCompat.setTint(cardDrawable, resources.getColor(R.color.shuffleColor))
binding.cardBookmark.background = cardDrawable

A: Is some cases its going to be a little tricky becase not all the time the code cardview.setBackgroundColor(R.color.red) is going to work.
I solved my problem this way..
final color = ColorStateList.valueOf(context.getResources().getColor(R.color.light_tab_selected));
userNoteTabCardView.setBackgroundTintList(color);

A: in the activity of fragment do this to get the color in values/color
  cardView.setCardBackgroundColor(Color.alpha(R.color.gray999ea4));

A: Cardview is a bit coy. I had list of colors in my structure and Model is like
class ModelColor : Serializable {

var id: Int? = 0
var title: String? = ""
var color: Int? = 0// HERE IS THE COLOR FIELD WE WILL USE

constructor(id: Int?, title: String?, color: Int?) {
    this.id = id
    this.title = title
    this.color = color
}

}
load the model with color, last item on constructure taking from R.color
 list.add(ModelColor(2, getString(R.string.orange), R.color.orange_500))

and finaly you can setBackgrıundResource
 cv_add_goal_choose_color.setBackgroundResource(color)

A: You only need to set card background color.
yourCard.setCardBackgroundColor(Color.WHITE);

A: One sufficient way to change the background color for cardView is setBackgroundResource, You can create drawable file as well and pass to setBackgroundResource,
holder.cardView.setBackgroundResource(R.drawable.white_frame)
or
holder.cardView.setBackgroundResource(R.color.white)

A: private MaterialCardView imgIgnition;
imgIgnition = findViewById(R.id.imgIgnition);
imgIgnition.setCardBackgroundColor(Color.parseColor("#198754"));

THE Above Code Worked For Mee

A: app:cardBackgroundColor="" in xml

A:
try it works easy

<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    card_view:cardBackgroundColor="#fff"
    card_view:cardCornerRadius="9dp"
    card_view:cardElevation="4dp"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingTop="10dp"
    android:paddingBottom="10dp">

A: CardView cardView;

cardView.setCardBackgroundColor(getResources().getColor(R.color.colorPrimary));


text:
Q: StateFieldPathExpression error on DQL I'm finding hard to discover why this simple Doctrine's DQL is generating the "Error: Invalid PathExpression. Must be a StateFieldPathExpression" error:
SELECT a.state
  FROM MyBundle:Alocation a JOIN a.state JOIN a.client
 WHERE a.client = :client

I got 3 entities: State(id, name), Client(id, name) and Alocation(id, state, client). What I what is get the states present in alocation for a specific client. I got dozens of simple DQLS like this in the my system. What's the problem of this DQL ?
I've seen my questions here on SO and other places but most uses createQueryBuilder() and I'm using DQL. The questions I found who use DQL doesn't seem to apply to my case.
Edit:
Anyway I try to use createQueryBuilder() like this:
$this->doctrine->getManager()
->createQueryBuilder()
->add('select', 'a.state')
->add('from', 'MyBundle:Alocation a')
->innerJoin('a.state', 'st')
->innerJoin('a.client', 'c', 'WITH', 'a.client = :client')
->setParameter("client", $client)
->getQuery()

same error.
Edit2:
I tried to use partial to solve it, like this:
SELECT PARTIAL a.{state}
  FROM MyBundle:Alocation a JOIN a.state JOIN a.client
 WHERE a.client = :client

but it didn't work. Got the error: "Expected end of string, got 'a' ". I also tried to use WITH instead of WHERE.Same thing.
Edit3: What I'm trying to do is to get the State entity ONLY. I can solve it loading all the Alocation entity. But I don't want to load more data than I need.

A: if your state field have Few field number, you can use this query:
SELECT s.name, s.id, s.value
  FROM MyBundle:Alocation a JOIN a.state s JOIN a.client c
 WHERE c.id = :client

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to specify gradle source sets with a pattern? I have the following structure in my project directory:

*

*subfolder1/src/main/java/...

*subfolder2/src/main/java/...

*subfolder3/src/main/java/...

*...

Is there a way to tell gradle to look in any folder that matches "src/main/java" for the source directories? I'm trying the following, but it doesn't work:
sourceSets {
    main {
        java {
            srcDir '**/src/main/java'
        }
    }
}

A: Whilst this is completely whacky, you can likely use a FileTree for this.
sourceSets {
    main {
        java {
            srcDirs fileTree(projectDir).matching {
                include '**/src/main/java'
            }
        }
    }
}


text:
Q: How do I set a SQL Server 2008 Reporting Services Template to a Default Font? I'm creating a new template to create reports from at a later date.
I know how to create one, and I know where to save it. However, the problem is this.
Everything that is created on the report uses the default font of Arial with a size of 10pt. I need to set mine to default to Tahoma 11pt.
I can create a mock title, mock tables, etc and save those to Tahoma 11pt, but any new controls that are used on any version of this report will default back to Arial 10pt.
How do I fix this?

A: AFAIK, you cannot change these defaults for new report items when you drag-drop or add them from the toolbox.
The product team made some design decisions regarding default values of certain elements, in order to keep the generated XML for the RDL a little leaner.
If you take a peak at the RDL with notepad, notice that when you have default report items without any customization, you should not actually find the defaults explicitly stated in the XML - they're baked into the code and the renderer (design time and runtime) implicitly applies them if not overridden by an explicit value.
However, if this is a critical deal for you, you "might could" write an XSLT transformation (or .NET app that parses XML with XPATH) for the RDL file, that finds the nodes you want and add the appropriate attributes and values and spits out the new RDL file to disk.  Kinda risky...
Also, if you are using the Report Wizard, you can customize the layout styles and templates used by the wizard (like the cool blue one everybody likes to use).  Here's an article with more details: http://beacspeak.spaces.live.com/blog/cns!69043F34B6D40843!125.entry
HTH
Thiago


text:
Q: sql group by per month and year with one row id I have a table with month, year and an id like this.
+-------+-----------+-----
| month |    year   |  id
+-------+-----------+-----
| 1     |  2016     |1
+-------+-----------+-----
| 2     | 2016      |2
+-------+-----------+-----
| 2     | 2016      |3
+-------+-----------+-----

and i want a sql query that give me only one row per month/year with the id if is single or the id null if there are multiple row for that month year.
in the case above
+-------+-----------+-----
| month |    year   |  id
+-------+-----------+-----
| 1     |  2016     |1
+-------+-----------+-----
| 2     | 2016      |null
+-------+-----------+-----

how can i do this query qith sql server 2012?

A: You can do this with aggregation and case:
select month, year,
       (case when min(id) = max(id) then min(id) end) as id
from t
group by month, year;

Note:  month and year are bad names for columns, because they are reserved words.  If these are really the names of your columns, you will need to escape them.

A: **Question:**only one row per month/year with the id if is single or the id null if there are multiple row for that month year
with cte
    as
    (
    select row_number() over (partition by month,year  order by (Select 1)) as rn,
    month,year,id
    from
    table
    )
    select
    case when rn>1 then null else id end as 'id',
    month,
    year
    from
    cte

A: I missed the part about the NULL in the OP, here's an adjusted query
DECLARE @tbl TABLE
(
    Month INT NOT NULL,
    Year INT NOT NULL,
    Id INT NOT NULL
)

INSERT INTO @tbl VALUES
   (2016, 1, 1)
   ,(2016, 2, 2)
   ,(2016, 2, 3)

SELECT
    Month
   ,Year
   ,CASE WHEN COUNT(Id) > 1 THEN NULL ELSE COUNT(Id) END AS [Id]
FROM @tbl
GROUP BY Month, Year

http://rextester.com/FWVHI57098

A: Do a GROUP BY that counts each month and year's number of rows. Have a case expression that if one row, returns it using min(id), otherwise (more than 1 row) returns null.
select month, year, case when count(*) = 1 then min(id) else null end
from tablename
group by month, year;


text:
Q: How can I fit my table in the text block? I want to make my table fit in the text block. At the minute, a large part of my table is being cut off at the right-hand edge the page. My code is:
\documentclass{article}
\usepackage{graphicx} % for \scalebox macro
\begin{document}
\begin{table}[h]
        \begin{center}
            \scalebox{0.8}{
            \begin{tabular}{|l|l|l|l|l}
                \cline{1-4}
                Risk Event                          & Chance of Happening & Severity      & Measures to be taken                                                                                &  \\ \cline{1-4}
                Team member missing meetings        & Significant         & Low           & Encourage team members to read over minutes and inform of any tasks set. If regularly absent issue a warning and then card. &  \\ \cline{1-4}
                QA/Project manager missing meetings & Significant         & Low/Moderate  & Deputy in role will act as manager.                                                                                &  \\ \cline{1-4}
                Team member leaving project group   & Low                 & Moderate/High & List all tasks assigned to missing team member and reassign them, after this refactor the timetable and planning.           &  \\ \cline{1-4}
            \end{tabular}}
        \end{center}
    \end{table}
\end{document}

I have tried replacing \begin{center} with flushleft to no avail. How can I make the table fit in the page?

A: Your table has only four real columns; the fifth is always empty and should thus be omitted entirely. If you remove the fifth column, you can also replace all \cline{1-4} instructions with the simpler \hline.
The main problem with the table is, though, that it's much too wide for any normal page dimension unless you let the text in all four columns wrap. Hence, instead of the basic l column type, you should use a column type that lets the text wrap. I suggest you use the tabularx package and a (modified form of) that package's X column type. Set the width of the tabularx environment to \textwidth. Separately, because the columns are quite narrow, I suggest you typeset the material ragged-right rather than fully justified, in order to avoid very wide inter-word spaces.

\documentclass{article}
\usepackage{tabularx,ragged2e}
\newcolumntype{Y}{>{\RaggedRight\arraybackslash}X}
\begin{document}
\begin{table}
\begin{tabularx}{\textwidth}{|*{4}{Y|}}
   \hline
   Risk Event & Chance of Happening & Severity      & Measures to be taken \\
   \hline
   Team member missing meetings & Significant  & Low    & Encourage team members to read over minutes and inform of any tasks set. If regularly absent issue a warning and then card. \\ \hline
   QA/Project manager missing meetings & Significant  & Low/Moderate  & Deputy in role will act as manager.\\ \hline
   Team member leaving project group   & Low    & Moderate/High & List all tasks assigned to missing team member and reassign them, after this refactor the timetable and planning.  \\
   \hline
\end{tabularx}
\end{table}
\end{document}

Addendum: Just for the sake of comparison, here's the original look of your table, where I've made only one adjustment to your code: I've used \resizebox{\textwidth}{!}{...} instead of \scalebox{0.8}{...} to make the table fit inside the text block. I think we can agree that using resizebox along with l-type columns is not the way to go in this case.

A: You can do that with the tabularx package. To improve the tavle I also load cellspace , for a less tight vertical spacing of cell contents, and makecell for a common formatting of column heads and the possibility of line breaks in cells.
I didn't understand what the empty last column is here for, but if you don't use it, you might as well delete it. That would enable both to simplify the code and have the last vertical rule aligned with right margin.
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage[showframe, nomarginpar]{geometry}
\usepackage{array, tabularx}
\renewcommand{\tabularxcolumn}[1]{>{\raggedright}m{#1}}
\newcolumntype{Y}{ >{\hsize =0.8\hsize}X}
\newcolumntype{Z}{ >{\hsize =1.2\hsize}X}
\usepackage{makecell}
\renewcommand\theadfont{\bfseries}
\renewcommand\theadalign{lc}
\renewcommand\cellalign{lc}
\usepackage{cellspace}
\setlength\cellspacetoplimit{5pt}
\setlength\cellspacebottomlimit{5pt}
\addparagraphcolumntypes{X, Y, Z}

\begin{document}

\begin{table}[!htbp]
        \begin{tabularx}{\linewidth}{|Y|l|l|S{Z}|l}
            \cline{1-4}
\thead{Risk Event} & \thead{Chance\\ of Happening} & \thead{Severity} & \thead{Measures\\ to be taken} & \\
\cline{1-4}
            Team member\break missing meetings & Significant & Low & Encourage team members to read over minutes and inform of any tasks set. If regularly absent issue a warning and then card. & \\
            \cline{1-4}
            QA/Project manager missing meetings & Significant & Low/Moderate & Deputy in role will act as manager. & \\
            \cline{1-4}
            Team member leaving project group & Low & Moderate/High & List all tasks assigned to missing team member and reassign them, after this refactor the timetable and planning. & \\
            \cline{1-4}
        \end{tabularx}%
\end{table}

\end{document}

A: Use @{}:
\documentclass{article}
\usepackage[showframe]{geometry}
\begin{document}
\noindent\begin{tabular}{@{}*5{l}}
1 & 2 & 3 & 4 & 5\\
A & B & C & D & E\\
\end{tabular}
\end{document}

For future reference, please make your code compilable and minimal.

EDIT
As John points out in his comment, you don't even need @{} if you have vertical lines in your table:
\documentclass{article}
\usepackage[showframe]{geometry}
\begin{document}
\noindent\begin{tabular}{*5{|l}}
1 & 2 & 3 & 4 & 5\\
A & B & C & D & E\\
\end{tabular}
\end{document}


text:
Q: codeigniter template, how to add a sidebar I have download a simple template system and put it to my codeigniter project, but I want to show something in my sidebar, and maybe on my footer.
Can you guys tell me how or fork my project on github and edit my file(s) so I can see what to do.  :)
Here is my project on github.
https://github.com/SimonJ/Hip-hop-project

A: I'm unfamiliar with your CI template library, however I can recommend either of the following as having the flexibility you require:
http://williamsconcepts.com/ci/codeigniter/libraries/template/index.html
http://philsturgeon.co.uk/code/codeigniter-template/


text:
Q: Qual API usar para criar uma galeria Preciso criar uma galeria mas não sei como carregar as imagens do cartão nas view.
Alguém pode me ajudar a qual API usar?

A: Você vai usar uma biblioteca chamada Glide ou Picasso. Elas tratam de carregar as imagens nas listas sem travar o Android.
Exemplo do uso:
Glide.with(this).load(imagem).into(imageView);
//this é o contexto
//imagem pode ser um link da internet, um drawable...qualquer coisa carrega.
//imageView é o lugar onde vai carregar

Funciona tanto na activity quanto em fragmentos ou em adaptadores.


text:
Q: Is there yet a solution that affords collaboration with two users, two cursors, one monitor? I am looking for a solution that is similar in some ways to multiseat, but with one important difference:
I want two (or perhaps n) users to be able to sit at the same monitor, sharing the same desktop environment, but be able to use their own keyboard and mouse, with their own cursor.
The basic use case is that I want my wife and I to be able to collaborate, mostly working on our own things, but occasionally directly collaborating.  I want to be able to say, "hey, do you think this is right?"  ...and for her to be able to jump over with her cursor, making corrections or copying-and-pasting.
Ideally, I want this to be a linux environment.
It seems that X11 provides for this possibility with a configuration called "Multi-pointer X," or "MPX."  Here's the article about it on the X-wiki.
However, I'm surprised to find that, apparently, this solution hasn't been implemented by any window managers, at least in a documented way.  Instead, they seem regard "the user" as owning all HIDs, and all working on a single cursor and focal point.
Here's a SuperUser question that contains an answer, but it is unsatisfying as it does not allow keyboard input to different window at the same time.
Since the architecture of GNU / Linux / X11 doesn't seem to preclude this configuration, so I'm surprised to see that it hasn't come of age, as it strikes me as of great use in a number of cases, personal and professional.
Or am I wrong and there's something right in front of me? :-)

A: This does not work with bare Windows, but might be possible with third-party software.
TeamPlayer (shareware, $49.95) is described as :

It allows multiple users to simultaneously utilize the operating
  system, applications and files.

*

*Multiple cursors on screen with multiple attached mice/keyboards

*Remote connecting users from anywhere using the free TeamCONNECT app

*Cursor-colors and on-the-fly editable cursor labels

*Area restrictions of cursors, confining them to any resizeable area on screen

*Limited free LITE version available (for non commercial uses only)

TeamPlayer LITE is the free version, limited to a maximum of two users,
which seems to be the version you need.
Comment : I have no experience with this product.

A: I have used a program called GlovePIE for Windows, and it is able to bind HID's to almost literally whatever you want.  They have a free example script that enables 2 mice to be used to control 2 different pointers on the screen.  One cursor acts as the real cursor, and the other one acts as a fake.  Anytime that the fake cursor needs to click, the real cursor and the fake cursor temporarily switch positions.
This program can definitely suit your needs of multitasking using one computer.  Some functions can even be created using its GUI, such as binding the 'a' key to the left arrow key.  However, to actually do what you are talking about would take some expertise in general coding, as implementing a multi-user configuration would not be something you could create inside of the GUI easily.  There is extensive help in the program itself, and this can be a feasible alternative for multiseat.

A: Looks like you still can't - not perfectly anyway. WM support is actually a pretty minor thing, tho having separate themes per cursor would be nice. Getting single session/multi seat is oddly trivial, with each keyboard and mouse paired, though you can't pick two different spots on a file and start typing at once -  I suspect this is a limitation of whatever software you run rather than the system. I got this running on ubuntu 16.10, though xinput2 should be supported on most modern linuxes.
Many of the moving parts you need exist - multi pointer X is built into modern versions of X, though the closest thing to a working window manager hasn't been updated to close to a decade -and the documentation seems require x2x for some odd reason. You can totally get two cursors with their own keyboards working
Now, here's what works perfectly
I'm testing this with lubuntu - I've gotten two pointers (which look the same) with their own keyboard and mouse support.
You'll want to install xinput - apt has this.
xinput list gives you a list of devices. Now, you'd want to create a second (or third, or forth) set of pointers
⎡ Virtual core pointer                        id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ TPPS/2 IBM TrackPoint                     id=11   [slave  pointer  (2)]
⎜   ↳ SynPS/2 Synaptics TouchPad                id=10   [slave  pointer  (13)]

⎣ Virtual core keyboard                       id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard                 id=5    [slave  keyboard (3)]
    ↳ Power Button                                id=6    [slave  keyboard (3)]
    ↳ Video Bus                                   id=7    [slave  keyboard (3)]
    ↳ Sleep Button                                id=8    [slave  keyboard (3)]
    ↳ AT Translated Set 2 keyboard                id=9    [slave  keyboard (3)]
    ↳ ThinkPad Extra Buttons                      id=12   [slave  keyboard (3)]
    ↳ Chicony USB Keyboard                        id=17   [slave  keyboard (3)]

Create the second set of inputs with and add the two devices with
xinput create-master pointer2
xinput reattach 10 "pointer2 pointer"
xinput reattach 17 "pointer2 keyboard"
This attaches the SynPS/2 Synaptics TouchPad  and
Chicony USB Keyboard  to the secondary inputs. I suspect you can use the names of the devices as well.
Now comes the part where I'm stuck - your software has to be aware that there's two cursors with seperate inputs - and I don't mean sublime text style. There's nothing out there, and it isn't really a window manager issue.
So yeah, you can get 90% of what you want, but not all the way. You can't simultaniously type, but you can move your cursors independantly, and 'hotseat' between your keyboards.
You'd also need to run these commands as needed, there's no documentation on X for this from what I can tell.

A: Why uncessasirly restrict yourselves to what can fit on the screen, when you can have a better experience with multiple screens, using a shared notepad such as Etherpad, Piratepad, or ten other similar programs here: http://alternativeto.net/software/piratepad/

A: THere's another similar answer for this
  - Can two users simultaneously share one pc
the quick answer is NO.. multi user input has not yet been fully developed, due to the essential need for two parallel user accounts being shared simultaneously, an additional layer of processor priority control being lacking, and the general confusion which would surround a computer trying to determine WHO is in control....
It might seem like an innocuous thing.. However, imagine two pilots trying to fly a plane at the same time - - both pushing and pulling on the yoke... the plane wouldn't know fi it should go up or down.... not a good thing...


text:
Q: Macro for giving all shapes on a page a common border I am using CorelDraw X7. I have a page containing many shapes and I wish to construct a macro to change it,
so that the bounding rectangle of alle shapes (the smallest one containing them all)
will have a common border of a given size.
I can find the size of the bounding rectangle and have tried to use the ActiveSelection.AlignAndDistribute sub
to move the shapes, but this sub has a lot of parameters, which I do not understand ("Help" does not help me).
My idea is this:

*

*Specify the border, say pgBorder.

*Get the width and height of the bounding rectangle, say shpsWidth and shpsHeight.

*Move the shapes so that the lower left corner of the new bounding rectangle will have coordinates (pgBorder, pgBorder).

*Reset the page size to shpsWidth + 2 * pgBorder resp. shpsHeight + 2 * pgBorder.

The shape bounding rectangle should now be surrounded with a border of size pgBorder.
This is what I have so far:
Sub GivePageCommonBorder()
    Dim pgBorder As Double, shpsWidth As Double, shpsHeight As Double
    Dim doc As Document
    Dim pg As Page

    Set doc = ActiveDocument
    doc.Unit = cdrMillimeter
    pgBorder = 20
    Set pg = doc.ActivePage
    ' Select all shapes on the page
    pg.Shapes.All.CreateSelection
    shpsWidth = ActiveSelection.SizeWidth
    shpsHeight = ActiveSelection.SizeHeight

    ' This is what I am lacking:
    ' Move the selection so its lower left corner has coordinates (pgBorder,pgBorder)

    ' Adjust page size
    pg.SizeWidth = shpsWidth + 2 * pgBorder
    pg.SizeHeight = shpsHeight + 2 * pgBorder
End Sub

Best wishes
Holger

A: I just stumbled upon the .Move method and constructed the following solution:
Sub GivePageCommonBorder()
    Dim pgBorder As Double
    Dim doc As Document
    Dim pg As Page

    Set doc = ActiveDocument
    doc.Unit = cdrMillimeter
    pgBorder = 5
    Set pg = doc.ActivePage
    pg.Shapes.All.CreateSelection
    With ActiveSelection
        pg.SizeWidth = .SizeWidth + 2 * pgBorder
        pg.SizeHeight = .SizeHeight + 2 * pgBorder
        .Move pgBorder - .LeftX, pgBorder - .BottomY
    End With
End Sub

Holger


text:
Q: Add Wordpress shortcode on page without 'get_header' I'm trying to add just a wordpress plug-in widget to a page. No blog, no template or anything, just the widget. I can get the widget to load properly, but it's pulling in a bunch of styles that are over-riding my current CSS. Is there an easy way do this without having to create a custom page?
<?
  require( '../blog/wp-load.php' );
  get_header();
?>
..//..
<?
  do_shortcode('[my shortcode]');
?>

I tried removing the get_header(), but the widget won't pull any data. Is there a way to just get the Wordpress functionality running right?

A: Glad it worked for you.
Find the js and css requirements of the widget and add it to the page manually. This will remove the requirement for the get_header() function.


text:
Q: Exam Class: \vsword I can already fill in the values of \pointpoints, \vqword, \vpword and
\vtword for \gradetable. How to fill in the \vsword column?
I want to fill it like this.

\documentclass[a4paper,10pt]{exam}
\usepackage[hmargin=1.5cm,bmargin=1.5cm]{geometry}
\usepackage[indonesian]{babel}
\usepackage{fouriernc}
\renewcommand{\rmdefault}{put}
\usepackage{amsmath,amssymb}
\usepackage[inline,shortlabels]{enumitem}
\usepackage[svgnames]{xcolor}
\usepackage{tikz}
\let\ds\displaystyle
\parindent0em

\printanswers
\newcommand{\class}{MATEMATIKA}
\newcommand{\examnum}{\large\bfseries Penskoran Penilaian Tengah Semester Ganjil}
\newcommand{\examdate}{23 September 2019}

\pagestyle{headandfoot}
\firstpageheader{\class}{\examnum}{\examdate}
\runningheader{\class}{\examnum}{Hal. \thepage\ dari \numpages}
\runningfooter{}{}{}
\runningheadrule

\pointpoints{exam-point}{poin}
\pointpoints{bobot}{bobot}
\vqword{No. Soal}
\vpword{Bobot Soal}
\vtword{Jumlah}
\vsword{Skor Maksimum}
\qformat{\bfseries Soal Nomor \thequestion\hspace{14cm} bobot = \totalpoints\hfill}
\renewcommand{\solutiontitle}{\noindent\textbf{Jawaban:}\enspace}

\begin{document}

\rule[2ex]{\textwidth}{1pt}%

\addpoints
\begin{center}
\gradetable[v][questions]
\end{center}

\begin{questions}
\question[15]
The question for number one.
    \begin{solution}
The solution
\flushright \textbf{Skor maksimum = 6}
    \end{solution}

 \question[10]
The question for number two.
\begin{solution}
The solution
\flushright \textbf{Skor maksimum = 3}
   \end{solution}

\end{questions}

\end{document}


text:
Q: Is Firefox 6/7 handling max-width:320px media query wrong? I'm seeing strange behavior with media query in Firefox lately, and I was wondering who's doing it right (compared to Chrome and IE9).
I've got the following css:
@media screen and (max-width:320px){
#sfWrapper{max-width:280px;font-size:0.625em;line-height:1.2em}
#cpw_banner{display:none;visibility:hidden;}
#cpw_content{width:100%;}#cpw_aside{width:100%;}
}

And Firefox (when resizing the browser, doesn't seem to notice the max:width 320px while it reacts to the bigger screen media queries.
Not only that, but when I use ctrl + often enough on a window it will kick in, where as Chrome and Internet Explorer 9 don't apply new media queries on ctrl + / ctrl -

Anyone know what's the 'standard' behavior with regards to ctrl+/ctrl- and media queries?
Thanks in advance...
J.

A: I dont know why the answer provided has been ticked as it doesn't answer the OP's question.  The reason why the media query doesn't fire 320 pixels is because of the navigation toolbar in Firefox.
If you turn it off (go to VIEW - TOOLBARS - NAVIGATION TOOLBAR and untick it) then the media query will fire at 320 pixels.

A: In Firefox, depending on your exact toolbar setup, it may be impossible for the content area to shrink below a certain width.  If you set up a page with a vertical scrollbar, you can see the scrollbar start disappearing when the window gets to be smaller than that minimal width.  At that point, the browser window is getting smaller, but the page viewport is NOT.  So if that minimal width is greater than 320px in your case, then the media query above would never apply.
The key point being that media queries match on the page viewport width, not the browser window width.
Furthermore, media queries match on CSS pixels, not device pixels.  Zooming in Firefox changes the size of a CSS pixel in device pixels, so the page viewport size (which is fixed in device pixels) changes in CSS pixels.
There is no standard of what zoom should do.

A: I've been working on a responsive design for 320px but Firefox just wouldn't respond.
I found that, for some reason, if you set your media query to 480px - (max-width:480px) - then Firefox will apply the media queries anyway.


text:
Q: unable to access env variables in app bootstrap I am trying to use Slack to post my debug messages to. i have followed some exmaple code and have this in my app.php file
$app->configureMonologUsing(function ($monolog) {
$monolog->pushHandler($chromeHandler = new \Monolog\Handler\ChromePHPHandler());
$chromeHandler->setFormatter(new \Monolog\Formatter\ChromePHPFormatter());

$slackHandler = new \Monolog\Handler\SlackHandler('xoxp-dasdasdzxczxcasdasdasdas', '#general');
$slackHandler->setLevel(\Monolog\Logger::INFO);
$slackHandler->setFormatter(new \Monolog\Formatter\LineFormatter());
$monolog->pushHandler($slackHandler);

});

which works and send mesages to slack using the following command
  Log::info('thing to log');

I want to only send debug messages to slack if I am on a local machine.
I have tried reading in the the APP_ENV variable using env() but it is not returning anything.
I can access it using the same code in the controller. THerefore I assume it has not been loaded in the app.php file when I am trying to get it.
is there a better place to add the slack code, or anther way to detect the env variable?


text:
Q: How to delete dynamic allocated class object in list? I just create list of Coordi object as below inside of a functions. Coordi is class object which I defined.
list<Coordi> LstOfCoordi;
for (int i = 0; i < 10; ++i)
{
    Coordi *tmp = new Coordi();
    LstOfCoordi.push_back(tmp);
}

I want release the list and each objects to the system before program termination.
If each element of list should have to be released, how to handle it ? I tried to below codes to use delete each of them, but it made compile error.
for (int i = 0; i < 10; ++i)
{
    myClass tmp = LstOfMyCalss.back();
    delete &tmp;
    LstOfMyClass.pop_back();
}

So, I am wondering deletion from the list is enough or not.
At a glance with below codes, each element was allocated and they are not released properly when the list destroyed.
for (int i = 0; i < 10; ++i)
{
    //myClass tmp = LstOfMyCalss.back();
    //delete &tmp;
    LstOfMyClass.pop_back();
}

Please let me know the best way to release all allocated objects.

A: Edit:
Sample code on creating list of objects using std::list.
class MyClass {
public:
    std::list<Coordi> m_listCoordi;
}

//---creation of list of objects
for(int a = 0; a < numObjects; a++){
    m_listCoordi.push_back(Coordi());  //note: no 'new' is used.
}

//---destroying list of objects
m_listCoordi.clear();

Sample code on creating list of pointer to objects using std::list.
class MyClass {
public:
    std::list<Coordi*> m_listCoordi;  //<---note: now list of pointer
}

//---creation of list of objects
for(int a = 0; a < numObjects; a++){
    m_listCoordi.push_back(new Coordi());
}

//---destroying list of objects
for(int a = 0; a < numObjects; a++){
    delete m_listCoordi[a];  //note: an item in m_listCoordi is already a pointer.
}
m_listCoordi.clear();

I apologized for a messy answer. I don't have much time to make it clean and more formal. I hope it helps anyway.

Prev answer:
If your list, say std::vector<YourClass*>, the elements hold pointer values. It's your responsibility to allocate and deallocate memory block from that pointer values that you save in the list. Whatever your method of allocating/deallocating, it's up to you. Just make sure your code won't produce memory leaks.
//---deallocate all elements before clearing the list.
for(auto& pItem : LstOfMyClass){
    //note: since LstOfMyClass is a list of pointer values, pItem is a pointer variable.
    delete pItem;
}
//---clear the list.
LstOfMyClass.clear();

If objects in the LstOfMyClass does not move around or the list does not grow or shrink, better use list of objects instead of list of pointer to objects. With this you don't have to worry about allocating and deallocating. The list will do it for you if the list variable is destroyed.


text:
Q: Spring Integration WS inbound gateway Remove Soap empty header My project using Spring integration ws-inbound-gateway.
<int-ws:inbound-gateway id="shop-inbound-gateway"
            error-channel="shopCoreErrorChannel"
            request-channel="shopRequestChannel"
            reply-channel="shopResponseChannel" />

Response:
<SOAP-ENV:Envelope xmlns:SOAP-     ENV="http://schemas.xmlsoap.org/soap/envelope/">
           <SOAP-ENV:Header/>
           <SOAP-ENV:Body>
           <shop:RailShopAPIResponse>
            ......
            ......
           </shop:RailShopAPIResponse>
           </SOAP-ENV:Body>
        </SOAP-ENV:Envelope>

Even though I didn't map any mapped-reply-headers/mapped-request-headers but the response will always have the empty soap header.

*

*Why is this soap empty header is coming?

*Is it a default behavior?

*If so then how to remove the empty soap header?

A: Consider to add some custom EndpointInterceptor to your EndpointMapping and implement clean up logic in the handleResponse:
/**
 * Processes the outgoing response message. Called after {@link EndpointAdapter} actually invoked the endpoint. Can
 * manipulate the response, if any, by adding new headers, etc.


text:
Q: Assign javascript array to list of JSON objects with a property name? I would like to convert a javascript array which looks like:
['https://www.google.com', 'https://www.facebook.com']

to a list of JSON objects that looks like this:
[{"redirectUri": "https://www.google.com"},
{"redirectUri": "https://www.facebook.com"}]

I have tried using Object.assign({}, array);
however this retuns json with the parameter name as the index of the array value and are all in a single object:
{"0": "https://www.google.com", "1": "https://www.facebook.com"},

is there a way to change this to use a custom parameter name dynamically?

A: You just need to map your elements respectively, using Array.map() method:
let result = arr.map(o => {
  return {
    "redirectUri": o
  }
});

Demo:

let arr = ['https://www.google.com', 'https://www.facebook.com'];

let result = arr.map(o => {
  return {
    "redirectUri": o
  }
});
console.log(result);


text:
Q: Getting only the subdocuments using couchbase N1QL In our couchbase db, we have a bucket with relatively large objects. These objects have other objects inside let's say people. This should be an array, however for some reasons we had to create it as an object of objects, and this is how it looks like:
{
    "companyName": "company name",
    "companyid": "11111-GUID-11111",
    "people": {
        "22222-GUID-22222": {
            "peopleid": "22222-GUID-22222",
            "name": "name1"
        },
        "33333-GUID-33333": {
            "peopleid": "33333-GUID-33333",
            "name": "name2"
        },
        "44444-GUID-44444": {
            "peopleid": "44444-GUID-44444",
            "name": "name3"
        }
    }
}

Using this structure I can create a query for getting a "people" object using a query like the following:
SELECT c.*
FROM companies c
WHERE ANY v IN OBJECT_VALUES(c.people) SATISFIES v.peopleid = "22222-GUID-22222" END;

The problem with this structure is that the database responds with the whole company object, however I only need the "people" object which satisfies the condition, and I don't need people with other id than "22222-GUID-22222".
Is there any way to achieve this using couchbase?

A: SELECT FIRST v FOR v IN OBJECT_VALUES(c.people) WHEN v.peopleid = "22222-GUID-22222" END AS people
FROM companies c
WHERE ANY v IN OBJECT_VALUES(c.people) SATISFIES v.peopleid = "22222-GUID-22222" END;


text:
Q: First item in selectfield is always checked and never updates field in sencha touch Am having a problem with the following selectfield on my form:
 {
                xtype: 'selectfield',
                label: 'Title',
                displayField: 'ItemName',
                valueField: 'Id',
                listeners: {
                    initialize: function () {
                        var titleStore = Ext.create('MyApp.store.Titles', {});
                        this.setStore(titleStore);
                    }
                }
},

On the form which uses the selectfield, whenever I select the option the form updates correctly, but the first item in the list always has a check mark against it. Also when selecting the first item in the list never updates the form.  My knowledge of ST is limited but surely this should work out of the box?
Any ideas why this isn't working?

A: This was down to a silly error.  The data coming from the server had identical 'Id' values, so when an item in the list was selected it had the same value as the rest of the items. The select field would then just show the first item that matched the 'Id' value which would be the first in the list.


text:
Q: Convert Electret Microphone output to digital data for transmition I might be asking a stupid question but....
I was wondering about whether or not there is a circuit to convert the output of an electret microphone to 1s and 0s for transmission. And then we can use the reverse method to convert the data back to voice to play on a speaker.
I have read this webpage, and I found out that we can transmit ons and offs at 27Mhz. So I was thinking about using a microphone to convert real time data from the microphone to 1s and 0s and then to send them out to the receiver to be played.
But the problem is, I don't see a way to convert the output of the electret microphone (for example this one from sparkfun) to 1s and 0s, WITHOUT any special parts.
Any suggestions?
Thanks in advance
EDIT: Define Special Parts: Pre-made complex circuits counts as special parts. Something like the arduino and raspberry pi all counts as pre made parts. Bluetooth moduels counts too. However, something like an h-bridge motor driver. The 555 Time doesn't count too. Furthermore, diodes, capacitators, resistors and etc. don't count.

A: Get off you idea of "WITHOUT any special parts". An electret microphone will output a low level analog signal when some bias current is applied to the part via a resistor from a supply voltage. That low level signal then needs to be amplified to some level that is compatible with the analog to digital converter that will be used to produce the 1's and 0's that represent the analog signal level in real time.
Already there are quite a handful of specialized parts just to get off first base with what you think you want to do. If you do not want to have to build all that then maybe you want to look into a USB or BLUETOOTH microphone that already has the essential components in place. Such unit will be spewing out the  1's and 0's in packets of data suitable for transmission to the target connected device.

A: A typical digital microphone circuit is produced of a few parts. Power, Microphone + Analog Pre-amp, a Analog to Digital Converter, and the Microcontroller/Receiver. Often the ADC and Controller are one piece. The Preamp can be as well.
For example, the OVC3860 Bluetooth Audio IC is an all in one IC that provides Mic power, pre-amp and ADC, as well as bluetooth connection.

A: If you would indicate what sort of receiving setup you plan to use it would guide the answers.
A (continuously variable) slope delta (CVSD) modulator IC (special part) would have been one method in the past but they are rarely used these days. The data is free running or synchronous usually.
An 8 pin microcontroller and bit of code (special part) could generate a chosen digital modulation bit stream. I have used one to convert audio to 115200 bps asynch data with a 6kHz bandwidth. Very few other parts required, just to amplify signal to 0 to 5V for the ADC. You could use any of a number of modulation schemes depending mostly on the type of receiver you plan to use.
There are duty cycle modulators circuits using an NE555 IC that can be implemented but they will not be clocked or synchronised though it might be enough for you
EDIT:
The CVSD modulator ICs could often be connected to work in reverse.
A microcontroller receiving data should be able to use a PWM, R-2R or other setup to generate an analogue output after decoding the data stream.
A filter can be used to filter out modulating frequency of a pulse width modulated signal leaving the baseband voltage behind.

A: Well you could do something like a one bit delta sigma converter with jellybean opamps and comparators and a D flipflop plus some sort of oscillator for the clock, nothing special there... You can even do away with the flipflop by doing a self oscillating design in the style of the UcD class D amps (You don't need the power level, but the phase lead network should be giving you ideas).
Conversion back to audio would be a low pass filter on the output of the receiver...
Downside is the Mb/s data rate, but everyone should build their own delta sigma modulator at least once, the things are fascinating.
Regards, Dan.


text:
Q: Electric field inside a cavity in non conducting sphere Why electric field inside a concentric cavity in non conducting sphere is zero but not in non concentric cavity ?

A: The electric field inside a spherical cavity is dependent on the distance between the centre of sphere of which the cavity is a part, and the centre of cavity.
That distance is zero for a concentric cavity, hence field strength is also zero. That's not the case for a non concentric cavity.
I'd also like to point out here, that the field strength inside a cavity is constant in direction and magnitude, at all the points of the cavity. So no matter how large the concentric spherical cavity is, the field strength inside it is zero at all points.


text:
Q: Unable to boot after Ubuntu upgrade from 18.04 to 20.04 I did an upgrade on Dell precision 3520 from  18.04 to 20.04 , but I am not able to boot. I can see the Grub menu, I select Ubuntu but after I see only the Dell logo.
 I disabled secure boot. The SATA operation on AHCI. I found a post speaking about ppt but I did not found ppt in boot configuration.

A: in the grub menu you can edit/read the commands grub's going to execute.
There are 3 commands that are important:
set root='hdX,msdosX'
linux /boot/vmlinuz-5.X root=Y ...
initrd  /boot/initrd.img-5.X

you can remove quiet splash behind the linux command, so you will get more infos, what's happening during the boot.


text:
Q: Order a dataframe primarily by the count of times a value appears in a column and secondarily by a second column I have the dataframe below which I would like to order primarily numerically by the count of times a value appears in the first column (bigger values first) and secondarily alphabetically(A-Z) based on the second column.
Name<-c("jack","jack","bob","david","mary")
Surname<-c("arf","dfg","hjk","dfgg","bn")
n1<-data.frame(Name, Surname)

It should be something like:
n1<-n1[
  order( n1[,1], n1[,2] ),
  ]

but I do not know how to order numerically based on count of values.

A: Using sqldf likes the following:
library(sqldf)

n2 <- sqldf('SELECT * FROM
             n1 JOIN (SELECT Name, COUNT(*) as C FROM n1 GROUP BY Name) as T
             on n1.Name = T.Name
             ORDER BY C DESC, Surname')

First grouped the names and then sort based on the count in decent order and Surname alphabetically.

A: As suggested by @thelatemail, you can do this in base R using:
n1[order(-table(n1$Name)[n1$Name], n1$Surname), ]

To sort by surname first, swap the arguments to order() around.

A: Using dplyr like the following:
library(dplyr)
n1 %>%
  as_tibble() %>%
  count(Name) %>%
  right_join(n1, by = "Name") %>% # join the count back to your original frame
  arrange(desc(n), Surname) %>% # order by highest count first, then Surname
  select(-n) # just return the original frame, with the sorting you asked for


text:
Q: Read/write binary file in C++ How can I create a linux I/O benchmark for read and write operations of binary file using C++?
I have tried to generate a file of 10MB with the code below but it returns me "segmentation fault (core dumped)".
#define FILE_SIZE 10240

#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

int main()

{
    int fd, i;
    int stream[FILE_SIZE];
    double span;

    clock_t start,end;

    start=clock();

    fd=open("data.bin", O_CREAT|O_TRUNC|O_WRONLY, S_IRWXU);

    srand(time(NULL));

    for(i=0; i<FILE_SIZE; i++){

        stream[i]=rand()%2;
        write(fd, (char*)stream[i], strlen((char*)stream[i]));

    }

    for(i=0; i<FILE_SIZE; i++)
        read(fd, (char*)stream[i], strlen((char*)stream[i]));

        close(fd);

        end=clock();
        time_lapse=((double)(end-start))/CLOCKS_PER_SEC;

        return 0;
}

Then it returns me some warnings due to the conversion included in the write and read functions, I'm sure there is a better way to do this.
Could anyone help me?
Thanks in advance,
Antonio

A: Your biggest problem is that you treat stream[i] as a string! It's not a string, it's an int value.
Use &stream[i] to get a pointer to it, and use sizeof stream[i] to get its size. In fact, you don't need to write each element separately, you could just write the whole array at once:
write(fd, stream, sizeof stream);

You could read it just the same.
A big sign of the problem is that you need to use C-style casting. If you need to do it in C++ then it's a sing of you doing something you should not.

Besides that you're not really doing anything C++-specific, your code could be plain C.
A C++ solution would be using std::fstream instead.
If you still need to use the POSIX low-level function, don't forget error checking. Each of the function you call could fail. And that actually includes the call to close.

A: strlen((char*)stream[i]) is wrong because stream[i] is int, not char*. Hence, strlen will keep on reading memory until it finds a 0 byte or runs off the mapped memory and you get a SIGSEGV.
Fix: sizeof stream[i].


text:
Q: Returning object with decimal from interop I have made a com interop object in c# like this:
[return: MarshalAs(UnmanagedType.SafeArray)]
public OrderStateModel[] GetOrders(int count, int offset);

I call it from MS Access and it shows great potential but I've given up on marshaling the decimals.
[Guid("6A6A7BF5-867D-47F3-B28A-10B74511A72D")]
public interface IOrderStateModel
{
   ...

    [return: MarshalAs(UnmanagedType.Currency)]
    Decimal Amount { get; set; }

    [return :MarshalAs(UnmanagedType.Currency)]
    Decimal AmountPaid { get; set; }
}

I've scoured the web for solutions but I really can't get my head around the type juggling and what it really implies in practice. I've dabbled with CurrencyWrapper as well. In the returned object the decimals end up as huge numbers.
I appreciate any help.


text:
Q: disable multiple dates in primefaces calendar based on input fields values

    <f:view contentType="text/html">
        <h:head>
            <f:facet name="first">
                <meta content='text/html; charset=UTF-8' http-equiv="Content-Type"/>
                <title>PrimeFaces</title>
            </f:facet>
            <script>
                 jQuery(document).ready(function() {
//                      $('#datepicker').datepicker({changeMonth : true,
//         changeYear : true,
//         dateFormat: 'yy-mm-dd',
//         minDate: 0,
//         beforeShowDay: function(date) {
//                                var day = date.getDay();
//                                return [(day != 0), ''];
//                        }
//      });
 var datelist = jQuery.parseJSON('#{bean.res}');
                        $("#datepicker").datepicker({
                            changeMonth : true,
                            changeYear : true,
                            dateFormat: 'yy-mm-dd',
                            beforeShowDay: function(d) {
                                var dmy = "";
                                dmy += ("00" + d.getDate()).slice(-2) + "-";
                                dmy += ("00" + (d.getMonth() + 1)).slice(-2) + "-";
                                dmy += d.getFullYear();
                                 var day = d.getDay();
                                if ($.inArray(dmy, datelist) >= 0) {
                                    // Hide Given Dates IN Array
                                      // For Sunday (day !== 0) (or) false
                                    return [false, ""];
                                }
                                else {
                                    // For Sunday (day !== 0) (or) true
                                    return [(day !== 0), ""];
                                }
                            }
                        });
                 });
   $(function() {

$( "#datepicker1" ).datepicker({
        changeMonth:true,
        changeYear:true

                        });
                 });
function tuesdaysAndFridaysDisabled(date)
{
  var day = date.getDay();

  return [(day != 2 && day != 5), '']
}
  </script>
 </h:head>
 <h:body>
<p:layout fullPage="true">

                <p:layoutUnit position="north" size="100" resizable="true" closable="true" collapsible="true">
                    Header
                </p:layoutUnit>

                <p:layoutUnit position="south" size="100" closable="true" collapsible="true">
                    Footer
                </p:layoutUnit>

                <p:layoutUnit position="west" size="175" header="Left" collapsible="true">
                    <p:menu>
                        <p:submenu label="Resources">
                            <p:menuitem value="Demo" url="http://www.primefaces.org/showcase-labs/ui/home.jsf" />
                            <p:menuitem value="Documentation" url="http://www.primefaces.org/documentation.html" />
                            <p:menuitem value="Forum" url="http://forum.primefaces.org/" />
                            <p:menuitem value="Themes" url="http://www.primefaces.org/themes.html" />

                        </p:submenu>

                    </p:menu>
                </p:layoutUnit>

                <p:layoutUnit position="center">

                        <p:inputText   id="datepicker"/>
                        <p:inputText   id="datepicker1"/>
  <p:calendar value="#{dateBean.date}" beforeShowDay="tuesdaysAndFridaysDisabled" />
                </p:layoutUnit>

            </p:layout>

        </h:body>

    </f:view>
</html>

in above i posted the xhtml page but i was confuesed to handle this problem  because the calender input field is based on another input field for example employee_id field means based on the  employee_id field value the calender value should appear.


text:
Q: SQL combining multiple schedule availability and limitation information I am working on a booking application in SQL Server 2016 where the main table has timeslots which can be booked for each staff. There are multiple other tables which provide information on whether a booking can be made (either positive or negative). For example there can be a staff availability table (positive) which shows when staff can be booked , and a holiday table showing when staff can not be booked.
Main table:
CREATE TABLE [tbl_timeslots]
(
    [slotid] [int] ,
    [fromdate] [datetime] ,
    [todate] [datetime] ,
    [staffid] [int]
)

Positive table (when staff is available)
CREATE TABLE [tbl_availability]
(
    [staffid] [int] ,
    [fromdate] [datetime] ,
    [todate] [datetime]
)

Negative table(when staff is not available)
CREATE TABLE [tbl_holidays]
(
    [staffid] [int] ,
    [fromdate] [datetime] ,
    [todate] [datetime]
)

Task: find all timeslots from main table where staff is available and not on holiday.
I am looking for a way to combine these multiple positive/negative tables to determine if a specific staff is available for a specific start/end period.
I know this can be done using EXISTS / NOT EXISTS like the example below, but the problem is as soon as you have to iterate over a large number of available options and several positive/negative tables this becomes very slow.
select
    staffid, fromdate, todate
from
    tbl_timeslots
where
    exists (select staffid from tbl_availability
            where tbl_availability.staffid = tbl_timeslots.staffid
              and tbl_availability.fromdate <= tbl_timeslots.fromdate
              and tbl_availability.todate >= tbl_timeslots.todate)
    and not exists (select tbl_holidays.staffid from tbl_holidays
                    where tbl_holidays.staffid = tbl_timeslots.staffid
                      and tbl_holidays.fromdate < tbl_timeslots.todate
                      and tbl_holidays.todate > tbl_timeslots.fromdate)

My question is whether there is a better way tm combine/merge all of these positive/negative tables using SQL to generate one output table showing availability.

A: You can use the  left join as follows:
select distinct staffid, fromdate,todate
  from tbl_timeslots t
Left join tbl_availability a
       On A.staffid=t.staffid and a.fromdate<=t.fromdate and a.todate>=t.todate
Left join tbl_holidays h
       On h.staffid=t.staffid and h.fromdate<t.todate and h.todate >t.fromdate
Where h.staffid is null and a.staffid is not null


text:
Q: multiple image upload in database in single input using php I am attempting to upload multiple images in PHP with single id. But I got only one image uploaded with id in all values.
Specifically, in the below code multiple images upload in database but I got only one value updated for entire images and only one image is storing. In echo statement it is showing three different images correctly and MySQL statements 3 individual 111 coming.
$id = $_GET['c_id'];

if (isset($_GET['c_id'])){
$id = $_GET['c_id'];

if (isset($_POST['submit'])) {
    extract($_POST);
    $error = array();
    $extension = array("jpeg", "jpg", "png", "gif");
    foreach ($_FILES["files"]["tmp_name"] as $key => $tmp_name) {

        $file_name = $_FILES["files"]["name"][$key];

        $file_tmp = $_FILES["files"]["tmp_name"][$key];
        //  $ext=pathinfo($file_name,PATHINFO_EXTENSION);

        $filename = basename($file_name);
        $newFileName = $filename . '.' . $ext;
        move_uploaded_file($file_tmp = $_FILES["files"]["tmp_name"][$key], "uploads/" . $newFileName);

        echo $sql = "UPDATE
     categories c
    LEFT JOIN category_icons e ON e.category_id = c.id SET e.image='$newFileName' where c.id=$id";

        $sql = mysql_query("UPDATE
     categories c
    LEFT JOIN category_icons e ON e.category_id = c.id SET e.image='$newFileName' where c.id=$id");

        /*  if($sql)
                {
        echo "";
                }*/
    }
}
$qry = mysql_query("SELECT c.*, e.image,e.id
    FROM  `categories` c
    LEFT JOIN category_icons e ON e.category_id = c.id WHERE c.id='$id'");

$cd_row = mysql_fetch_array($qry);

while ($cr_row = mysql_fetch_array($qry)){

?>

    <form method="post" action="" enctype="multipart/form-data">

            <input id="logo" name="files[]" placeholder="logo" type="file">
            <input type="hidden" name="imagehidden" class="form-control" value="<?php echo $cr_row['image']; ?>">
            <img src="<?php echo $cr_row['image']; ?>" style="float:right;width:120px;height:100px;margin-top: 0px;" class="logo-default">

        <a href="javascript:sureToApprove(<?php echo $cr_row['id']; ?>)" style="float:right;" class="btn btn-danger">del

        <?php }
        } ?>

            <input type="submit" name="submit" class="btn btn-info">
            <a href="add_category_icon.php?ci_id=<?php echo $id; ?>" class="btn btn-primary">add

</form>

What is the problem? If you can find it or any tips for that. Thank you advance.

A: You have placed the update query at wrong place.
In your code, what actually happens is, in each loop it will upload file and update image name for the same category id. So in Each loop, it will be overridden with previous value.
What you need to do is, you need to store imageNames of each file in variable, and outside the loop, you need to perform update query with comma separated string.
Please refer below code:
if(isset($_POST['submit'])){
  extract($_POST);
    $error=array();
    $extension=array("jpeg","jpg","png","gif");
    $fileNames = array();
    foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name)
            {

             $file_name=$_FILES["files"]["name"][$key];

               $file_tmp=$_FILES["files"]["tmp_name"][$key];
               //  $ext=pathinfo($file_name,PATHINFO_EXTENSION);

               $filename=basename($file_name);
                  $newFileName=$filename.'.'.$ext;
                   move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"uploads/".$newFileName);

                $fileNames[] = $filename;
            }
        $imageFileNames = implode(',',$fileNames);
         $sql= mysql_query("UPDATE
            categories c
            LEFT JOIN category_icons e ON e.category_id = c.id SET e.image='$imageFileNames' where c.id=$id");

}

Hope this will help you.

A: Code get error Undefined variable: ext in line $newFileName=$filename.'.'.$ext; because $ext define inside comment.
Here is the complete code
if(isset($_POST['submit'])){
extract($_POST);
$error='';
$extension=array("jpeg","jpg","png","gif");
$fileNames = array();
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name)
        {

        $file_name=$_FILES["files"]["name"][$key];

        $file_tmp=$_FILES["files"]["tmp_name"][$key];
        $ext=pathinfo($file_name,PATHINFO_EXTENSION);

            if(in_array($ext, $extension)){
                $filename=basename($file_name);
                $newFileName=$filename.'.'.$ext;
                move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"uploads/".$newFileName);

                $fileNames[] = $filename;
            }else{
                $error ="File extension not support";
            }

        }
    if($error==''){
    $imageFileNames = implode(',',$fileNames);
    $sql= mysql_query("UPDATE categories c LEFT JOIN category_icons e ON e.category_id = c.id SET e.image='$imageFileNames' where c.id=$id");
    }
    else{
    echo $error;
    }

}


text:
Q: OpenMP parallelise std::next_permutation I have written the function scores_single, which calculates all the permuatations of a board and scores it.
I tried to follow this SO answer to parallelise the function using OpenMP, and came up with scores_parallel. The problem is that the parallel version iterates over the same permutations in multiple loops.
The code follows:
#include <iostream>
#include <omp.h>
#include <vector>

// Single threaded version
int scores_single(const int tokens, const int board_length) {
    std::vector<int> scores;

    // Generate boards
    std::vector<char> board(board_length);
    std::fill(board.begin(), board.end() - tokens, '-');
    std::fill(board.end() - tokens, board.end(), 'T');

    do {
//        printf("Board: %s\n", std::string(board.data(), board.size()).c_str());

        // Score board
        auto value = 3;

        scores.push_back(value);
    } while (std::next_permutation(board.begin(), board.end()));
    return scores.size();
}

// OpenMP parallel version
int scores_parallel(const int tokens, const int board_length) {
    std::vector<std::vector<int>*> score_lists(board_length);

    // Generate boards
    std::vector<char> board(board_length);
    std::fill(board.begin(), board.end() - tokens, '-');
    std::fill(board.end() - tokens, board.end(), 'T');

    printf("Starting\n");
#pragma omp parallel default(none) shared(board, board_length, score_lists)
    {
#pragma omp single nowait
        for (int i = 0; i < board_length; ++i) {
#pragma omp task untied
            {
                auto *scores = new std::vector<int>;

                // Make a copy of the board for this thread
                auto board_thread = board;
                // Subset for this thread, see: https://stackoverflow.com/questions/30865231/parallel-code-for-next-permutation
                std::rotate(board_thread.begin(), board_thread.begin() + i, board_thread.begin() + i + 1);
                do {
                    printf("[%02d] board: %s\n", i, std::string(board_thread.data(), board_thread.size()).c_str());

                    // Score board
                    auto value = 3;

                    scores->push_back(value);
                } while (std::next_permutation(board_thread.begin() + 1, board_thread.end()));
                score_lists[i] = scores;
                printf("[%02d] Finished on thread %d with %lu values\n", i, omp_get_thread_num(), scores->size());
            }
        }
    }

    std::vector<int> scores;

    int k = 0;
    for (auto & list : score_lists) {
        for (int j : *list) {
            scores.push_back(j);
        }
    }
    printf("Finished, size: %lu\n", scores.size());

    return scores.size();
}

int main() {
    int p = scores_parallel(2, 4);
    int s = scores_single(2, 4);
    std::cout << p << " != " << s << std::endl;
    return 0;
}

Output:
Starting
[01] board: --TT
[03] board: T--T
[03] board: T-T-
[02] board: T--T
[03] board: TT--
[01] board: -T-T
[02] board: T-T-
[00] board: --TT
[03] Finished on thread 10 with 3 values
[00] board: -T-T
[00] board: -TT-
[02] board: TT--
[00] Finished on thread 11 with 3 values
[01] board: -TT-
[02] Finished on thread 12 with 3 values
[01] Finished on thread 4 with 3 values
Finished, size: 12
12 != 6

I think I understand the SO answer I am copying, but I am not sure what I have done wrong.
6 is the expected answer, as 4C2 = 6.

A: Figured it out, I was calculating the same permutation multiple times. I fixed it with the if statement below.
#include <iostream>
#include <omp.h>
#include <vector>

// OpenMP parallel version
int scores_parallel(const int tokens, const int board_length) {
    std::vector<std::vector<int>*> score_lists(board_length);

    // Generate boards
    std::vector<char> board(board_length);
    std::fill(board.begin(), board.end() - tokens, '-');
    std::fill(board.end() - tokens, board.end(), 'T');

    printf("Starting\n");
#pragma omp parallel default(none) shared(board, board_length, score_lists)
    {
#pragma omp single nowait
        for (int i = 0; i < board_length; ++i) {
#pragma omp task untied
            {
                auto *scores = new std::vector<int>;

                // No need to process this branch if it will be identical to a prior branch.
                if (board[i] != board[i + 1]) {
                    // Make a copy of the board for this thread
                    auto board_thread = board;
                    printf("[%02d] evaluating: %s\n", i, std::string(board_thread.data(), board_thread.size()).c_str());
                    // Subset for this thread, see: https://stackoverflow.com/questions/30865231/parallel-code-for-next-permutation
                    std::rotate(board_thread.begin(), board_thread.begin() + i, board_thread.begin() + i + 1);
                    do {
                        printf("[%02d] board: %s\n", i, std::string(board_thread.data(), board_thread.size()).c_str());

                        // Score board
                        auto value = 3;

                        scores->push_back(value);
                    } while (std::next_permutation(board_thread.begin() + 1, board_thread.end()));
                }
                score_lists[i] = scores;
                printf("[%02d] Finished on thread %d with %lu values\n", i, omp_get_thread_num(), scores->size());
            }
        }
    }

    std::vector<int> scores;

    int k = 0;
    for (auto & list : score_lists) {
        for (int j : *list) {
            scores.push_back(j);
        }
    }
    printf("Finished, size: %lu\n", scores.size());

    return scores.size();
}

int main() {
    int p = scores_parallel(2, 4);
    int s = scores_single(2, 4);
    std::cout << p << " == " << s << std::endl;
    return p != s;
}


text:
Q: Solve the equation: $-u''=f(x), 0Solve the equation using green's function $-u''=f(x), 0<x<1, u(0)=u(1)=0$
I got the solution as being $u(x)=\frac{x^2}{2}(x-1)f(x)+xf(x)(\frac{1}{2}-\frac{x^2}{2}-1+x$.
Which is wrong. Can anyone see where i went wrong?

A: The next to last formula is wrong, it should have $f(s)$ instead of $f(x)$, that is,
$$
u(x)=\int_0^1G(x,s)f(s)\,ds=-\int_0^x (1-x)sf(s)\,ds-\int_x^1 x(1-s)f(s)\,ds
$$
Without knowing $f$ no further evaluation of the integrals is possible.


text:
Q: Let $b\in\mathbb{R}$ satisfy $0Let $b\in\mathbb{R}$ satisfy $0<b<1$. Show that $\lim_{n\to \infty}(nb^n)=0$ using the $\ln$ and the binomial theorem.
Using the binomial theorem
$b := 1/(1 + a)$ where $a > 0$. Since $(1 + a)^n > \frac{1}
2{}n(n − 1)a^2$, we have
$0<nb^n ≤n/[\frac{1}
2{}n(n − 1)a^2]≤2/[(n−1)a^2]$. Thus $\lim(nbn)=0$
Using the $\ln$
How can I prove it by this way?

A: So $\log(nb^{n})=\log n+n\log b<n^{1/2}+n\log b=(1+n^{1/2}\log b)n^{1/2}$ and $\log b<0$ so $n^{1/2}\log b\rightarrow-\infty$. Then take exponential.


text:
Q: android webview just can not load some specific wap? Here show my code:
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());

webView.setWebViewClient(new WebViewClient() {
    /**
     * 自定义网页加载
     */
    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        if (url.startsWith("tel:")) {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
        } else
            view.loadUrl(url);

        return true;
    }
});

String url1 = "http://192.168.72.203:8080/wap-pc/toOtherLogin?appSource=0";
JavaScriptInterface jsInterface = new JavaScriptInterface();
webView.addJavascriptInterface(jsInterface, "loginInterface");

webView.loadUrl(url1)

It just shows a blank page.  Can anyone help me to resolve this?


text:
Q: Tkinter radiobuttons not selecting properly I'm trying to make a small tkinter program to calculate the area of shapes and volumes
and I've made a main py file "area_volume_calculator.py" and two libraries "area.py" and "volume.py"
The main program's radio buttons work fine, but when I create the second window from Area_calculator I can't seem to get radio buttons to work properly. When it opens, the last 2 radio buttons are selected already.
I can still select an option but self.choice.get() always returns the default value which is -1, I don't know how to get it to work.
Can anyone help me get the radio buttons to work properly?
Any and all help is appreciated
Main Program:
from tkinter import *

from area import *

# from volume import *

class Menu:
    def __init__(self):
        self.window = Tk()
        self.window.title("Areas and Volumes")

        # self.name_label = Label(self.window, text = "Name: ")
        # self.name_label.grid(row=0,column=0)

        # self.name_entry = Entry(self.window)
        # self.name_entry.grid(row=0,column=1)

        # self.age_label = Label(self.window, text = "Age: ")
        # self.age_label.grid(row=1,column=0)

        # self.age_entry = Entry(self.window)
        # self.age_entry.grid(row=1,column=1)

        self.choice = IntVar()

        self.area_radiobutton = Radiobutton(self.window, text = "Area Calculator", var = self.choice, value = 0)
        self.area_radiobutton.grid(row=2,column=0)

        self.volume_radiobutton = Radiobutton(self.window, text = "Volume Calculator", var = self.choice, value = 1)
        self.volume_radiobutton.grid(row=3,column=0)

        self.choice.set(-1)

        self.submit_button = Button(self.window, text = "Submit", command = self.submit)
        self.submit_button.grid(row=4,column=0)

        print(self.choice.get())

        self.window.mainloop()

    def submit(self):
        print(self.choice.get())

        if self.choice.get() == 0:
            area_calculator = Area_calculator()

        # elif self.choice.get() == 1:
        #     volume_calculator = Volume_calculator()

menu = Menu()

area.py library:
from tkinter import *
class Area_calculator():
    def __init__(self):
        self.window = Tk()
        self.window.title
        self.window.title("Area Calculator")

        self.choice_label = Label(self.window, text = "Choose a shape")
        self.choice_label.grid(row=0,columnspan=1)

        self.choice = IntVar()

        self.rectangle_radiobutton = Radiobutton(self.window, text = "Rectangle", var = self.choice, value = 0)
        self.rectangle_radiobutton.grid(row=1,column=0)

        self.triangle_radiobutton = Radiobutton(self.window, text = "Triangle", var = self.choice, value = 1)
        self.triangle_radiobutton.grid(row=2,column=0)

        self.circle_radiobutton = Radiobutton(self.window, text = "Circle", var = self.choice, value = 2)
        self.circle_radiobutton.grid(row=3,column=0)

        self.submit_button = Button(self.window, text = "Submit", command = self.submit)
        self.submit_button.grid(row=4,column=0)

        self.choice.set(-1)
        print(self.choice.get())

        self.window.mainloop()

    def submit(self):
        print(self.choice.get())
#        if self.choice.get() == 0:
#            rectangle_calculator = Rectangle_calculator()
#        elif self.choice.get() == 1:
#            triangle_calculator = Triangle_calculator()
#        elif self.choice.get() == 2:
#            circle_calculator = Circle_calculator()

A: You are creating two instances of tk.Tk() (one in each class) which is never a good idea. tk.Tk() does not just create a new window but also a new embedded Tcl interpreter and this can mess things up, particularly IntVars and other variables such as self.choice. For more information see here.
If you want to have multiple windows then use tk.Toplevel() instead.
In answer to your second question in the comments, you must first add the parameters name and age to the __init__ of the Area_calculator class, and also pass them to the class when creating it in Menu.
Completed code:
Main program:
from tkinter import *

from area import *

class Menu:
    def __init__(self):
        self.window = Tk()
        self.window.title("Areas and Volumes")

        self.name_label = Label(self.window, text = "Name: ")
        self.name_label.grid(row=0,column=0)

        self.name_entry = Entry(self.window)
        self.name_entry.grid(row=0,column=1)

        self.age_label = Label(self.window, text = "Age: ")
        self.age_label.grid(row=1,column=0)

        self.age_entry = Entry(self.window)
        self.age_entry.grid(row=1,column=1)

        self.choice = IntVar()

        self.area_radiobutton = Radiobutton(self.window, text = "Area Calculator", var = self.choice, value = 0)
        self.area_radiobutton.grid(row=2,column=0)

        self.volume_radiobutton = Radiobutton(self.window, text = "Volume Calculator", var = self.choice, value = 1)
        self.volume_radiobutton.grid(row=3,column=0)

        self.choice.set(-1)

        self.submit_button = Button(self.window, text = "Submit", command = self.submit)
        self.submit_button.grid(row=4,column=0)

        print(self.choice.get())

        self.window.mainloop()

    def submit(self):
        print(self.choice.get())

        if self.choice.get() == 0:
            name = self.name_entry.get()
            age = self.age_entry.get()
            area_calculator = Area_calculator(name, age)

menu = Menu()

area.py library:
from tkinter import *

class Area_calculator():
    def __init__(self, name, age):
        self.window = Toplevel()
        self.window.title
        self.window.title("Area Calculator")

        self.name_label = Label(self.window, text = f"{name=}", width=10)
        self.name_label.grid()

        self.age_label = Label(self.window, text = f"{age=}", width=10)
        self.age_label.grid(row=0, column=1)

        self.choice_label = Label(self.window, text = "Choose a shape")
        self.choice_label.grid(row=1,columnspan=1)

        self.choice = IntVar()

        self.rectangle_radiobutton = Radiobutton(self.window, text = "Rectangle", var = self.choice, value = 0)
        self.rectangle_radiobutton.grid(row=2,column=0)

        self.triangle_radiobutton = Radiobutton(self.window, text = "Triangle", var = self.choice, value = 1)
        self.triangle_radiobutton.grid(row=3,column=0)

        self.circle_radiobutton = Radiobutton(self.window, text = "Circle", var = self.choice, value = 2)
        self.circle_radiobutton.grid(row=4,column=0)

        self.submit_button = Button(self.window, text = "Submit", command = self.submit)
        self.submit_button.grid(row=5,column=0)

        self.choice.set(-1)
        print(self.choice.get())

        self.window.mainloop()

    def submit(self):
        print(self.choice.get())


text:
Q: Python: how to do average among different pandas data frame columns? I have the following dataset:
import pandas as pd
df = pd.DataFrame({'ID1': [0, 1, 0, 2, 2, 4],
 'ID2': [1, 0, 3, 4, 4, 2],
 'Title': ['a', 'b', 'c', 'd', 'e', 'f'],
 'Weight': [3, 5, 1, 1, 5, 1]})

df

ID1   ID2   Title  Weight
0      1      a     3
1      0      b     5
0      3      c     1
2      4      d     1
2      4      e     5
4      2      f     1

I wan to check how many times to ID collaborate and count the total frequency and the weighted average. The weighted is the sum of the collaboration over the sum of the Weight. The results should be:
df1

ID1    ID2    Total   Weighted Av.
 1      0       2        0.25
 0      3       1          1
 2      4       3         0.5

I am counting in wrong way the collaboration between ID1 and ID2 in this way
df.groupby(['ID1','ID2']).size().reset_index()

A: Suppose you define
pairs = df.apply(lambda r: (min(r.ID1, r.ID2), max(r.ID1, r.ID2)), axis=1)

Then these are just the normalized pairs of you DataFrame (lower first, higher second). Now you can just groupby these, and find the weighted average:
>>> df.groupby(pairs).apply(lambda g: len(g) / float(g.Weight.sum()))
(0, 1)    0.250000
(0, 3)    1.000000
(2, 4)    0.428571
dtype: float64

To get your exact required DataFrame, some fiddling with the columns is needed, but it's basically the code above:
pairs = df.apply(lambda r: (min(r.ID1, r.ID2), max(r.ID1, r.ID2)), axis=1)
weighted = pd.merge(
    df.groupby(pairs).apply(lambda g: len(g) / float(g.Weight.sum())).reset_index(),
    df.groupby(pairs).size().reset_index(),
    left_index=True,
    right_index=True)
weighted['ID1'] = weighted['index_x'].apply(lambda p: p[0])
weighted['ID2'] = weighted['index_x'].apply(lambda p: p[1])
weighted['Total'] = weighted['0_x']
weighted['Weighted Ave'] = weighted['0_y']
weighted = weighted[['ID1', 'ID2', 'Total', 'Weighted Ave']]
>>> weighted
    ID1     ID2     Total   Weighted Ave
0   0   1   0.250000    2
1   0   3   1.000000    1
2   2   4   0.428571    3

A: You can first sort columns ID1 and ID2 by numpy.ndarray.sort and then groupby with apply custom function f:
print df
   ID1  ID2 Title  Weight
0    0    1     a       3
1    1    0     b       5
2    0    3     c       1
3    2    4     d       1
4    2    4     e       5
5    4    2     f       1

id1id2 = df[['ID1','ID2']].values
id1id2.sort(axis=1)
print id1id2
[[0 1]
 [0 1]
 [0 3]
 [2 4]
 [2 4]
 [2 4]]

df[['ID1','ID2']] = id1id2
print df
   ID1  ID2 Title  Weight
0    0    1     a       3
1    0    1     b       5
2    0    3     c       1
3    2    4     d       1
4    2    4     e       5
5    2    4     f       1

def f(x):
    #print len(x)
    #print x['Weight'].sum()
    return pd.Series({'Total':len(x), 'Weighted Av.': len(x) / float(x['Weight'].sum()) })

print df.groupby(['ID1','ID2']).apply(f).reset_index()
   ID1  ID2  Total  Weighted Av.
0    0    1    2.0      0.250000
1    0    3    1.0      1.000000
2    2    4    3.0      0.428571


text:
Q: Firebase Dynamic Links for WEB URL not working on IOS On IOS, the dynamic link either shows a white page that needs to be tapped to continue or the preview page. For Android the dynamic link works as expected.
Steps I'm following when generating a dynamic link on Firebase.

*

*Paste Link

*For Apple I select "Open the deep link URL in a browser"

*For Android I select "Open the deep link URL in a browser"

*For Campaign tracking I select "Skip the app preview page"

Thanks


text:
Q: Shuffle the order of keys in an associative array, if they have the same values? Given an associative array like this, how can you shuffle the order of keys that have the same value?
array(a => 1,
      b => 2,  // make b or c ordered first, randomly
      c => 2,
      d => 4,
      e => 5,  // make e or f ordered first, randomly
      f => 5);

The approach I tried was to turn it into a structure like this and shuffle the values (which are arrays of the original keys) and then flatten it back into the original form. Is there a simpler or cleaner approach? (I'm not worried about efficiency, this is for small data sets.)
array(1 => [a],
      2 => [b, c],  // shuffle these
      4 => [d],
      5 => [e, f]); // shuffle these

function array_sort_randomize_equal_values($array) {
    $collect_by_value = array();
    foreach ($array as $key => $value) {
        if (! array_key_exists($value, $collect_by_value)) {
            $collect_by_value[$value] = array();
        }
        // note the &, we want to modify the array, not get a copy
        $subarray = &$collect_by_value[$value];
        array_push($subarray, $key);
    }

    arsort($collect_by_value);

    $reordered = array();
    foreach ($collect_by_value as $value => $array_of_keys) {
        // after randomizing keys with the same value, create a new array
        shuffle($array_of_keys);
        foreach ($array_of_keys as $key) {
            array_push($reordered, $value);
        }
    }

    return $reordered;
}

A: I rewrote the entire code, since I found another way which is a lot simpler and faster than the old one(If you are still interested in the old one see the revision):

*

*old code   (100,000 executions): Ø 4.4 sec.

*new code (100,000 executions): Ø 1.3 sec.

Explanation
First we get all unique values from the array with array_flip(), since then the values are the keys and you can't have duplicate keys in an array we have our unique values. We also create an array $result for then storing our result in it and $keyPool for storing all keys for each value.
Now we loop through our unique values and get all keys which have the same value into an array with array_keys() and save it in $keyPool with the value as key. We can also right away shuffle() the keys array, so that they are already random:
foreach($uniqueValues as $value => $notNeeded){
    $keyPool[$value] = array_keys($arr, $value, TRUE);
    shuffle($keyPool[$value]);
}

Now we can already loop through our original array and get a key with array_shift() from the $keyPool for each value and save it in $result:
foreach($arr as $value)
    $result[array_shift($keyPool[$value])] = $value;

Since we already shuffled the array the keys already have a random order and we just use array_shift(), so that we can't use the key twice.
Code
<?php

    $arr = ["a" => 1, "b" => 1, "c" => 1, "d" => 1, "e" => 1, "f" => 2,
            "g" => 1, "h" => 3, "i" => 4, "j" => 5, "k" => 5];

    function randomize_duplicate_array_value_keys(array $arr){

        $uniqueValues = array_flip($arr);
        $result = [];
        $keyPool = [];

        foreach($uniqueValues as $value => $notNeeded){
            $keyPool[$value] = array_keys($arr, $value, TRUE);
            shuffle($keyPool[$value]);
        }

        foreach($arr as $value)
            $result[array_shift($keyPool[$value])] = $value;

        return $result;

    }

    $result = randomize_duplicate_array_value_keys($arr);
    print_r($result);

?>

(possible) output:
Array (
    [b] => 1
    [g] => 1
    [a] => 1
    [e] => 1
    [d] => 1
    [f] => 2
    [c] => 1
    [h] => 3
    [i] => 4
    [k] => 5
    [j] => 5
)

Footnotes

*

*I used array_flip() instead of array_unique() to get the unique values from the array, since it's slightly faster.

*I also removed the if statement to check if the array has more than one elements and needs to be shuffled, since with and without the if statement the code runs pretty much with the same execution time. I just removed it to make it easier to understand and the code more readable:
if(count($keyPool[$value]) > 1)
    shuffle($keyPool[$value]);

*You can also make some optimization changes if you want:

*

*Preemptively return, if you get an empty array, e.g.
function randomize_duplicate_array_value_keys(array $arr){

    if(empty($arr))
        return [];

    $uniqueValues = array_flip($arr);
    $result = [];
    //***
}

*Preemptively return the array, if it doesn't have duplicate values:
function randomize_duplicate_array_value_keys(array $arr){

    if(empty($arr))
        return [];
    elseif(empty(array_filter(array_count_values($arr), function($v){return $v > 1;})))
        return [];

    $uniqueValues = array_flip($arr);
    $result = [];
    //***
}

A: Here's another way that iterates through the sorted array while keeping track of the previous value. If the previous value is different than the current one, then the previous value is added to a new array while the current value becomes the previous value. If the current value is the same as the previous value, then depending on the outcome of rand(0,1) either the previous value is added to the new list as before, or the current value is added to the new list first:
<?php

$l = ['a' => 1,'b' => 2, 'c' => 2,
    'd' => 4,'e' => 5,'f' => 5];

asort($l);
$prevK = key($l);
$prevV = array_shift($l); //initialize prev to 1st element
$shuffled = [];

foreach($l as $k => $v) {
    if($v != $prevV || rand(0,1)) {
        $shuffled[$prevK] = $prevV;
        $prevK = $k;
        $prevV = $v;
    }
    else {
        $shuffled[$k] = $v;
    }
}

$shuffled[$prevK] = $prevV;

print_r($shuffled);


text:
Q: Colouring edge of network based on their direction - NetworkX In R ggplot2, there is a simple way to color the edge of a network based on its direction between nodes. So if a line (edge) is directed from the nodes A to B, we can use the code:
geom_edge(aes(colour=stat(index))
Then I tried to redo this in python using NetworkX - to no avail. Here is an example network:
F.add_nodes_from([0,1])
F.add_nodes_from([0,2])
F.add_nodes_from([2,1])
post = nx.circular_layout(F)
nx.draw_networkx_nodes(F, post, node_color = 'r', node_size = 100, alpha = 1)
nx.draw_networkx_edges(F, post, edgelist= [(1,0)], width = 1, alpha = 1)
nx.draw_networkx_edges(F, post, edgelist= [(0,2)], width = 1, alpha = 1)
nx.draw_networkx_edges(F, post, edgelist= [(2,1)], width = 1, alpha = 1)
plt.axis('off')
plt.show()

And I have so far found no way to change the colour according to the direction of the edge. Ideally, I would like to achieve something like this:
Please see photo here

A: This isn't implemented in networkx, but it would be possible in matplotlib, albeit involve a substantial amount of computation, depending on what exactly you would like to do:
If you want to plot your edges as simple lines, you could precompute the node layout, and then follow this guide to plot multicolored lines between the node positions using matplotlib's LineCollection.
If you wanted to draw arrows, you would have to a) compute the path of the corresponding FancyArrowPatch, and then b) use that path to clip an appropriately oriented color-gradient mesh. For a simple triangle, this is demonstrated here.


text: Q: OpenCart 3 + OCFilter. Вывод результатов фильтра в категории OpenCart 3 + OCFilter. Подскажите, где найти место, в котором формируется запрос на вывод товаров после выбора параметров фильтра? Нужно внести некоторые правки - не могу найти! Спасибо!


text:
Q: How can I get the area of the shadowed octagon in the image First of all, this is just a problem sent by a friend, I have an idea of how to calculate it's area but I'm not entirely sure if I'm on the right track

The only data I have is that the area of the small octagon is 63cms^2 and I need to calculate the area of the shadowed area.
I know that to get the area you'll need to subtract the area of the large octagon minus the inner,
It doesn't say but apparently the inner octagon is a regular one, all sides are the same, so I can calculate the width of the inner octagon
$$
    w = (1+√2)s  \text{(s = side)}
$$
and the area formulae
$$
    2(1+√2)s2
$$
With the width I have the length of the large side of the outer octagon, with the side I have the length of the small side of the outer octagon. is this correct?
With this I can calculate the area of the outer octagon by drawing triangles, using angles and the apothem.
Am I on the right track? how do I keep going if so?

A: If everything that looks like lying on grid points actually does so, then the small octagon is $3\times 3$ unit squares minus $4$ triangles and the big octagon is $5\times 5$ unit squares minus $4$ corner triangles. Then the difference is $16$ unit squares. From the given, we conlclude that one unit square is $9\,\text{cm}^2$. So, ...


text:
Q: libGDX pause running for some seconds I have an application, in which I would like to make a short pause. It would be important, to make graphical elements/changes better visible between two automatic interactions.
I have tried to use above code above for 2 minutes of pause, but it causes a pause at the start of the method, not between 2 exact lines of code inside the method.
try {
    Thread.sleep(2000);
} catch(InterruptedException ex) {
    Thread.currentThread().interrupt();
}

A: Libgdx expects the render loop to run regularly (at roughly the screen refresh rate) and to re-draw the screen each time.  As, such while your app may "look" paused, it should not actually be paused.  It should be busy updating the screen, updating animations, being responsive to the back key, etc.
So, you need to decide more explicitly what is being prevented during this window.  Just responding to input?  Adding new elements?  Then you should skip those elements during your window.
long endPauseTime = 0;

When you decide you want to pause:
endPauseTime = System.currentTimeMillis() + (2 * 1000); // 2 seconds in the future

Then in your render calback:
if (endPauseTime < System.currentTimeMillis()) {
   // non-paused mode, so check inputs or whatever
} else {
   // paused mode, so skip some things ..
}


text:
Q: Is the project bootspring v1 or v2 I am a devops engineer currently containerizing java applications for our backend team.
All projects are built with spring-boot and use either spring-boot v2 or (since they're older and more legacy) spring-boot v1.
I have built a spring-boot base image for them to run on and do some additional stuff based on the spring-boot version used.
Sadly for one of the projects I don't have any information if it's v1 or v2. Having no experience with neither java coding nor spring-boot I am at a loss at how to find out.
So the question is: Assuming the source code is present, how can I tell if a project is using spring-boot v2 or v1?
Thanks for your help java gurus!

A: As you mentioned assuming you have source code, Check for the versions in the pom.xml file.

*

*Check for spring-boot-starter-parent dependency version to be 2.0.0 or higher and,

*check the spring framework version downloaded to be 5

Edit:
If you can run the application, you can also check version with the ascii art that printed out, assuming no customization made:
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.3.RELEASE)

Refer:
1. Difference between Springboot 1.X and Springboot 2.0
2. https://content.pivotal.io/springone-platform-2017/whats-new-in-spring-boot-2-0-phillip-webb-madhura-bhave