text:
Q: Reshape in R without aggregation (for example MTurk response strings) Ordinarily, I'd use a pretty basic long-to-wide reshape for this, but it seems to be dropping my aggregation variables. The setup is I had a job on mechanical Turk that I performed in triplicate---I want MTurk1, Mturk2, MTurk3's answers to be their own variables in the data frame but uniquely id'd by a field I input with the job, so that I can compare them against each other with a function later.
Current Format:
> head(mturk)
  AssignmentStatus     Input.id  Input.State  Answer.Q1thing
1         Approved       134231           NY         Myguess
2         Approved       134231           NY         Myguess
3         Approved       134231           NY        BadGuess
4        Submitted       134812           CA         Another
5         Approved       134812           CA         Another
6         Approved       134812           CA         Another

I'd like this to become
Input.id   Input.State Answer.Q1thing.1 Answer.Q1thing.2 Answer.Q1thing.3  AssignmentStatus.1 AssignmentStatus.2  AssignmentStatus.3
134231              NY          Myguess          Myguess         BadGuess          Approved             Approved            Approved
134812              CA          Another          Another          Another         Submitted             Approved            Approved

or ideally, if there's a variable that can redo column names in the operation....
Id               State          Answer1          Answer2          Answer3          Status1               Status2             Status3
134231              NY          Myguess          Myguess         BadGuess          Approved             Approved            Approved
134812              CA          Another          Another          Another         Submitted             Approved            Approved

dat <- reshape(mturk, timevar="Answer.Q1thing", idvar=c("Input.id", "Input.state"), direction="wide")

This seems to be failing because most reshape long-to-wide functions expect that the variable that becomes wide itself a categorical text-field---that is, this is not a long-to-wide reshape operation because I don't want a variable named "MyGuess" "BadGuess" and "Another", but I want a generic "Answer.X" variable containing these values.  I'm not trying to aggregate in any way, such as mean or sum, just list the value in a new place.
So, two directions for this question:

*

*Does this kind of operation have another name?  Is this an unfold, unpivot, uncast or something?

*How to do this in R?

A: If your data is in a data.table it's a one-liner can be done as follows:
library(data.table)
mturk.dt <- as.data.table(mturk)

mturk.dt[, as.list(
         rbind(c(Answer.Q1thing, AssignmentStatus))
         )
        , by=list(Id=Input.id, State=Input.State)]

Note that the by argument handles the name-changing too!

If you want to properly name the other columns, use setnames after the fact or, more dynamically, using setattr  within the j=.. argument as follows:
After the Fact:
## Assuming 'res' is the reshaped data.table form above:
## Change the names of the six V1, V2.. columns
setnames(res, paste0("V", 1:6), c(paste0("Answer", 1:3), paste0("Status", 1:3)))

Dynamically, in j=..
## Use `as.data.table` instead of `as.list`, to preserve new names
mturk.dt[, as.data.table(
         rbind(c(
              setattr(Answer.Q1thing,   "names", paste0("Answer", seq(Answer.Q1thing  )))
            , setattr(AssignmentStatus, "names", paste0("Status", seq(AssignmentStatus)))
            ))
         )
        , by=list(Id=Input.id, State=Input.State)]

       Id State Answer1 Answer2  Answer3  Status1  Status2  Status3
1: 134231    NY Myguess Myguess BadGuess Approved Approved Approved
2: 134812    CA Myguess Myguess BadGuess Approved Approved Approved

A: Using plyr:
res = ddply(dat,.(Input.id,Input.State),
            function(x)unlist(as.character(x$Answer.Q1thing)))
setNames(res,c('Id','State','Answer1','Answer2','Answer3'))
  Id State Answer1 Answer2  Answer3
1 134231    NY Myguess Myguess BadGuess
2 134812    CA Another Another  Another

EDIT
In case you have fewer than 3 answers:
res = ddply(dat,.(Input.id,Input.State),
            function(x)
              {
              xx= unlist(as.character(x$Answer.Q1thing))
              if(length(xx)==3)xx
              else c(xx,rep(NA,3-length(xx)))
            })

A: That was super helpful, @Ricardo and @agstudy.  I realized my reshape wasn't working only because it demanded a unique, categorical "timevar".  I think in most cases, you do have a categorical label/factor like this that makes it easy, but it is not much harder to count them, and make the count into a label.
I had a second problem was that my number of answers were not consistent; you both gave good help for that, but I was also able to just generate a counter and then implemented my original long-to-wide.
Where the count was < 3, that is where an Input.id only had 2 Answers, I got NAs for this, which is what I wanted.
So altogether:
mturk$idx <- with(mturk, ave(Input.id, Input.id, FUN=seq_along)) # weird!
dat <- reshape(mturk, timevar="idx", idvar=c("Input.id", "Input.state"), direction="wide")

I used the syntax for counting sequences within a group that I found here.  This was a little idiosyncratic in the use of the ave() function, but seems to crop up in a couple other answers.  Tried rtl, too, but had no luck.  Using ave(x,x,seq_along) seems to mostly be a hack to avoid sorting.  It's odd to use this work-around for sequences in groups because clearly both count() and rtl() are effectively creating this sequencing under the hood in a temp variable.
I like the way data.table allows this sequencing better.

A: From data.table v1.9.5+, dcast can handle multiple value.var columns, i.e., we can cast multiple columns simultaneously. We can simply do:
dt[, id := seq_len(.N), by=Input.id]
dcast(dt, Input.id + Input.State ~ id,
        value.var=c("AssignmentStatus", "Answer.Q1thing"))
#    Input.id Input.State 1_AssignmentStatus 2_AssignmentStatus 3_AssignmentStatus
# 1:   134231          NY           Approved           Approved           Approved
# 2:   134812          CA          Submitted           Approved           Approved
#    1_Answer.Q1thing 2_Answer.Q1thing 3_Answer.Q1thing
# 1:          Myguess          Myguess         BadGuess
# 2:          Another          Another          Another

Or everything together in one line:
dcast(dt, Input.id + Input.State ~ dt[, seq_len(.N), by=Input.id]$V1,
                 value.var=c("AssignmentStatus", "Answer.Q1thing"))


text:
Q: Have CodeIgniter ignore a file Is there a way to have codeIgniter ignore a HTML file in the CI root directory.  I am working on some jQuery ajax and the html file has to be in the same directory.

A: Why not have the .html file be included by a view? Would work the same, and you would not be breaking the MVC model.

A: Can you clarify "ignore"? If you have a root set up like:
/system
.htaccess
index.php
somefile.html

CI will ignore the somefile.html. If someone directly requests site.com/somefile.html, the server will serve the file. However, if you prevent that, jQuery cannot access it either.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bootstrap container-fluid has a left and right margin I am creating a navigation bar that has a full width layout, I have created the container-fluid class acting as the navigation wrapper and within is the row class followed by the columns.... as far as I'm aware, this is the correct structure of bootstrap, yet I am getting a margin to both the left and right.
Here is my HTML:

Here is my CSS:
.header {
    height:50px;
    background-color:#222222;
}

.header_category_icon, .header_search_icon {
    background-color:#575757;
    height:50px;
}

Thanks for any help

A: Please note col-sm-*'s are supposed to be direct children of .rows:

       ...

Working example:

.header>.row>[class^="col-"] {
  border: 1px solid red;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

            This is an example

Take a closer look at Bootstrap examples.

A: Thanks for your help - The issue was jointly that the col-XX-XX was not a child of the container-fluid, also the header_category_icon & header_search_icon did not need child classes, they could be instead be within the col class like this:


text:
Q: Android Screen Clipped at Bottom I am developing an Android app (see screenshots).
I have a layout that looks fine in the graphical editor. However, the bottom 1/4 of the screen is clipped from view when the app is run in the emulator. The app has several activities, and the problem seems to be widespread to all.

The emulator target is android 2.3, and the problem also occurred on a 2.2 phone.
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="fill_parent"
    android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="fill_parent">
    <ImageView android:layout_height="wrap_content" android:src="@drawable/simpsonstextblack" android:layout_width="fill_parent" android:id="@+id/TitleImage" android:layout_gravity="center_horizontal" android:paddingBottom="20dp"></ImageView>
    <RelativeLayout android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="@+id/RelativeLayout1" android:padding="5dp">
        <Button android:text="Take the Simpsons Challenge" android:gravity="center" android:clickable="true" android:id="@+id/ChallengeButton" android:layout_width="fill_parent" android:layout_height="50dp" android:textSize="20dp" android:background="@drawable/buttonbackgroundblue"></Button>
        <TextView android:layout_width="fill_parent" android:layout_below="@+id/ChallengeButton" android:layout_alignLeft="@+id/ChallengeButton" android:id="@+id/spacer1" android:layout_height="5dp"></TextView>
        <Button android:layout_width="fill_parent" android:text="Free Play" android:clickable="true" android:id="@+id/FreePlayButton" android:layout_height="50dp" android:textSize="20dp" android:background="@drawable/buttonbackgroundblue" android:layout_below="@+id/spacer1"></Button>
        <TextView android:layout_width="fill_parent" android:id="@+id/spacer2" android:layout_below="@+id/FreePlayButton" android:layout_alignLeft="@+id/FreePlayButton" android:layout_height="5dp"></TextView>
        <Button android:layout_height="50dp" android:textSize="20dp" android:id="@+id/HighScoreButton" android:background="@drawable/buttonbackgroundblue" android:layout_width="fill_parent" android:text="High Scores" android:layout_below="@+id/spacer2"></Button>
        <TextView android:layout_width="fill_parent" android:id="@+id/spacer3" android:layout_below="@+id/HighScoreButton" android:layout_alignLeft="@+id/HighScoreButton" android:layout_height="5dp"></TextView>
        <Button android:layout_height="50dp" android:textSize="20dp" android:id="@+id/HelpButton" android:background="@drawable/buttonbackgroundblue" android:layout_width="fill_parent" android:text="Help" android:layout_below="@+id/spacer3"></Button>
    </RelativeLayout>
    <RelativeLayout android:layout_width="fill_parent" android:id="@+id/RelativeLayout1" android:layout_height="fill_parent">
        <TextView android:id="@+id/textView1" android:layout_width="fill_parent" android:layout_height="50dp"></TextView>
        <TextView android:layout_below="@+id/textView1" android:layout_height="wrap_content" android:layout_width="fill_parent" android:textAppearance="?android:attr/textAppearanceMedium" android:id="@+id/QuoteText" android:text='"A woman is a lot like a refrigerator. Six feet tall, 300 pounds…it makes ice."'></TextView>
        <TextView android:layout_below="@+id/QuoteText" android:layout_width="fill_parent" android:id="@+id/QuoteTextSpeaker" android:gravity="right" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_height="wrap_content" android:text=" - Homer"></TextView>
    </RelativeLayout>
</LinearLayout>

Thank You

A: I had been targeting SDK 3 when it should have been 4. Apparently targeting SDK 3 causes android to clip the screen if it overextends, rather than shrinking it to fit.

A: You should not be using so many dummy LinearLayouts inside other LinearLayouts. You need to use RelativeLayouts for these kind of views.


text:
Q: Replace brackets for negative numbers with hyphen I'm processing a list of numbers (as strings) in Ruby:
"4.3", "2.1", "(0.1)", "(3.4)"

When I process, I'd like to leave the positive numbers alone. For the negative numbers, I'd like to remove the brackets and insert a hyphen (keeping them as strings is fine):
"4.3", "2.1", "-0.1", "-3.4"

I've stripped the brackets with gsub:
"(0.1)".gsub(/[()]/, "")

But adding the hyphen to signify the negative causes problems, as this:
"(0.1)".gsub(/[()]/, "-\1")

... supposedly replaces both brackets, and puts two hyphens, along with an unknown character.
I'm not married to the gsub/regex approach, so anything that works quickly would work.

A: ["4.3", "2.1", "(0.1)", "(3.4)"]
.map{|s| s =~ /\((.+)\)/ ? "-#$1" : s}


text:
Q: How to make Element.scrollIntoView() on Chromium-based browsers not depend on smooth-scrolling flag? I have a JavaScript function that attempts to smoothly scroll an element into view:
dom_element.scrollIntoView({
    'behavior': 'smooth',
    'block': 'nearest'
});

On Firefox, this works perfectly fine.
But I realized that scrolling was instant, i.e. not respecting behaviour': 'smooth' on Chromium-based browsers (Chrome, Opera, Brave).
Both MDN and caniuse.com showed that Chrome supported behaviour: smooth, so I was quite puzzled.
After a frustrating hour of debugging, I realized that the code works if I specifically go to chrome://flags/#smooth-scrolling and toggle Smooth Scrolling from Default to Enabled. After some experimentation, I deduced that a value of Default for Smooth Scrolling meant Disabled.
The strange thing was: on another computer (laptop), the above code worked as expected without needing to tweak Smooth Scrolling. It was left as default, and scrolling was smooth.
Both PCs run the latest Chrome v83.0.4103.61 on Win 10 Pro.
Questions:

*

*Why is the default setting for the Smooth Scrolling flag different for two computers? If hardware matters, one is a desktop i7-6700K with nVidia 1060GT, and the other is a laptop i7-8550U with GeForce MX110.

*Since it's impractical to tell users to enable this flag before using the site, is it possible to override this flag programmatically in JS?

A snippet that demonstrates this problem for some PCs on Chrome:

let dom_target = document.querySelector('#target');

// Make clicks anywhere scroll smoothly to target (number 14)
document.addEventListener('click', function() {
    dom_target.scrollIntoView({
        'behavior': 'smooth',
        'block': 'nearest'
    });
});
#container {
  overflow: scroll;
  border: 1px solid #333;
}

.item {
  border: 1px solid #333;
  height: 100px;
  background-color: red;
  text-align: center;
  color: white;
  font-size: 40px;
  line-height: 100px;
}

#target {
  background-color: blue;
}

Clicking anywhere scrolls to 14, and the scrolling behavior should be smooth.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

A: You can't.1
This is controlled by an accessibility setting that you can trigger from the "Show animations in Windows" setting in Windows "Settings > Ease of Access > Display".
This being an accessibility feature from the OS, the browser won't let your website override it.
(Also note that the flag you mentioned might get removed in favor of letting only this setting control this behavior, so it may not even be a possible workaround in the future).
But that shouldn't be a problem, since users with this setting certainly did set it for a good reason.
1: Of course you can make this manually, but really you shouldn't go against user's preferences.

A: I have tried this approach in my project and it is working, I hope you find this helpful.
What you have to do is just remove the 'behavior': 'smooth', from your file.
So your code should look like below:
let dom_target = document.querySelector('#target');

// Make clicks anywhere scroll smoothly to target (number 14)
document.addEventListener('click', function() {
dom_target.scrollIntoView({
    'block': 'nearest'
 });
});

And you just add the style scroll-behavior: smooth to your element with id target.
So your HTML file should be somewhat like this:

Clicking anywhere scrolls to 14, and the scrolling behavior should be smooth.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

Please try this once and I hope you can resolve your problem.


text:
Q: An example of a prime quotien ideal where his corresponding ideal is not prime If $R$ is a comutative ring with identity ring and $K$ is an ideal from it, let $R'=R/K$ and $I$ an ideal of $R$ satisfy $K\subseteq I$ and $I'$ is the coresponding ideal of $R'$ (we knew that correspondence theorem gives a certain one-to-one corespondence between the set of ideals of $R$ containing $K$ and the set of ideals of $R'$).
can you give me some examples where $I'$ is prime then $I$ is not.

A: I do not know why you want to replace 'prime' by 'principal', since these properties do not really relate, but here is an example:
$R=k[x,y], K=(x), I=(x,y)$. $I$ is not principal but $I'=I/K=(y)$ is principal in $R'=R/K=k[y]$.

A: Note that we have by the third isomorphism theorem
$$ R/I \cong R/K\bigm/I' $$
hence $R/I$ is a domain iff $(R/K)/I'$ is, therefore $I$ is prime iff $I'$ is.


text: Q: PCA on returns: to scale or not to scale I am running PCA on time series data that has returns for a particular stock. Usually, when I run PCA for non-financial data I always scale the data with some R command like prcomp(data,scale=TRUE). However, I believe that returns data is scaled to a certain level. So when using returns data should my command be prcomp(returns,scale=False)?


text:
Q: Solutions $3 p\sin x - (p+\sin x)(p^2-p \sin x +\sin ^{2} x) =1$ $3 p \sin x - (p+\sin x)(p^2-p \sin x + \sin ^{2} x) =1$ has a solution for $x$. Then number of integral solutions of $p$ are ?

A: On simplifying the the expression is $3p \sin x - p^{3} -\sin^{3}x=1$ which can be written as $(p)^{3}+(\sin x)^3+(1)^3=3 \cdot 1 \cdot p \cdot \sin x$, i.e $a^3+b^3+c^3=3abc$ form.
This means either $p+\sin x+1=0$ or $p=\sin x =1$
Hence possible values of p are $-2,-1,0,1$, i.e 4 integer solutions.


text:
Q: $\lim \limits_{h \to 0} 3a^2 $ Easy question.
Consider $\lim \limits_{h \to 0} 3a^2 + 3ah + h^2$ (derivative of $x^3$)
If I were to split it up into $\lim \limits_{h \to 0} 3a^2 + \lim \limits_{h \to 0} 3ah + \lim \limits_{h \to 0} h^2$, how would I evaluate the first term? I imagine it would be equal to $3a^2$?
I just don't see how $|h-0| < \delta \Rightarrow |3a^2 - 3a^2 | < \epsilon$ works

A: You wrote
$$|h-0|<\delta\implies 0<\epsilon,$$ which is certainly true, by hypothesis on $\epsilon$.


text:
Q: Next.js render app inside html markup coming as string I need to build my Next.js app inside a third-party html markup.
The markup is given as follows:
header.txt

    <title>Some title</title>

    Some header

footer.txt

    Some footer

This files are dynamically generated into a folder. When I render my next.js application, I need to wrap them around my application.
I created a working example using the package called: html-react-parser
I parse the markup from the files in the _document.js and I am looking for a custom element id which I am replacing with the next js app as follows:

const header = fs.readFileSync(path.resolve(ROOT + '/resources', 'header.txt'), 'utf8');
const footer = fs.readFileSync(path.resolve(ROOT + '/resources', 'footer.txt'), 'utf8');
const shell = `
    ${header}

    ${footer}
`;

// later in the render method od _document.js:

render() {
        return (
            <React.Fragment>
                {parse(shell, {
                    replace: domNode => {
                        if (domNode.attribs && domNode.attribs.id === 'react-app') {
                            return (
                                <React.Fragment>

                                    <NextScript/>
                                </React.Fragment>
                            )
                        }
                    }
                })}
            </React.Fragment>
        )
    }

Although this works, my problem is, that this is not the purpose of the html-react-parser because it converts the markup of the files to react components, and throws many warnings during the conversion about wrongly used html props which react can not use.
Maybe the solution would be to use dangerouslySetInnerHTML, but in this case I can not inject and .

// it fails because it wont treat the components as normal html
// <NextScript/> are not evaluated

const header = fs.readFileSync(path.resolve(ROOT + '/resources', 'header.txt'), 'utf8');
const footer = fs.readFileSync(path.resolve(ROOT + '/resources', 'footer.txt'), 'utf8');
const shell = `
    ${header}
      <React.Fragment>

        <NextScript/>
      </React.Fragment>
    ${footer}
`;

// later in the render method od _document.js:

render()

If anybody has an Idea how could I manage to wrap my next app around my markup coming from the files, please give me some advice.

A: You can achieve that with custom server,
const express = require('express')
const next = require('next')

const header = fs.readFileSync(path.resolve(ROOT + '/resources', 'header.txt'), 'utf8');
const footer = fs.readFileSync(path.resolve(ROOT + '/resources', 'footer.txt'), 'utf8');

const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then(() => {
  const server = express()

  server.all('*', async (req, res) => {
    const nextResponse = await handle(req, res);
    return mergeHTML(header, footer, nextResponse); // You will need to "merge" cause nextResponse has `head` & `body` as well.
  })

  server.listen(port, err => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})

mergeHTML should merge head from your header & next's head & the body. You can use cheerio to help you with that.

A: I solved the problem using dangerouslySetInnerHTML. Basically It does not care about the string syntax you pass into it, so I came up with the following solution in _document.js:

      <NextScript />

Both calls of dangerouslySetInnerHTML are taking the odd number of elements and wrapping around the next.js components.
By the was if anybody has an another solution maybe without dangerouslySetInnerHTML please comment it.


text:
Q: Easy implementation of Repository Pattern I am using ADO.NET directly with MVC 5 and not Entity Framework.
I am referring to this example to implement Repository Pattern.
For a simple implementation of Repository Pattern:

*

*I will create a Model

*I will create an interface with CRUD method declarations

*I will create a class in Data Access Layer which will implement the above interface and will have CRUD method implementations

I want to know why Interface is used? Can I not directly use a class, as per point (3) above.
What is the role of interface?
As per the above three points mentioned, is it the correct implementation of Repository Pattern?

A: In good-designed code you have to use interfaces, but not implementations. It have benefits. Imagine you have a class with a code fragment:
IBookRepository bookRepository;

public Book GetInterestingBook() {
  var book = bookRepository.getBooks().FirstOrDefault(x => x.IsInteresting);
  return book;
}

Now I'll show you some benefits:

*

*Using interface allows you to create bookRepository instances implicitly via Dependency Injection (Ninject, Unity, etc. There are many of them). If you decide to change repository implementation from Entity Framework to NHibernate you don't need to make changes in code. Just change mapping in mapping file to use for IBookRepository NHibernateRepository instead of EFBookRepository. Of course, NHibernateRepository should be developed too.

*Using interface allows you to implement great unit-testing via MockObjects. You just need to implement MockBookRepository and use it on injection. There are many Mock frameworks that can help you with it - Moq for example.

*You can switch repositories dynamically without changing you code. For example if your database is temporary down, but you have another one that can handle new orders for example as they are critical (bad example, i know). In this case you detect DB fall down and make something like:
currentRepository = temporaryOrdersOnlyRepository;
Now your code continues functioning except your get data and delete methods returns exceptions but CreateNewOrder() method will save orders to string file )
Good luck!

A: Here is a service
public interface IFoodEstablishmentService
{
    Task<int> AddAsync(FoodEstablishment oFoodEstablishment);
    Task<int> UpdateAsync(FoodEstablishment oFoodEstablishment);
}

This is my normal implementation
public class FoodEstablishmentService : IFoodEstablishmentService
{
    public async Task<int> AddAsync(FoodEstablishment oFoodEstablishment)
    {
       // Insert Operation
        return result;
    }

    public async Task<int> UpdateAsync(FoodEstablishment oFoodEstablishment)
    {
        // Update Logic
        return result;
    }
}

This is how i use it
IFoodEstablishmentService oFoodEstablishmentService =  new FoodEstablishmentService();
oFoodEstablishmentService.AddAsync(oFoodEstablishment);

But wait what if I might need to pass my insert logic through queue rather than directly to server, wait for insert operation to complete and then return result, rather pass on queue and then the queue worker handles those operation?
So instead of messing everything, I just implement another class with same interface
public class FoodEstablishmentQueueService : IFoodEstablishmentService
{
    public async Task<int> AddAsync(FoodEstablishment oFoodEstablishment)
    {
       // Insert Queue Operation
        return result;
    }

    public async Task<int> UpdateAsync(FoodEstablishment oFoodEstablishment)
    {
        // Update Queue Logic
        return result;
    }
}

And this is how I use it, isn't it easy without breaking anything, and with DI Container as stated on earlier answer even works better
IFoodEstablishmentService oFoodEstablishmentService =  new FoodEstablishmentQueueService();
oFoodEstablishmentService.AddAsync(oFoodEstablishment);

I guess don't choose for best pattern rather start with any and then slowly you will have need for something more and then pattern comes to play in addition Repository pattern or generic repository pattern might not be ideal pattern for large scale application where select logic is beyond selecting just a model data. Please search for CQRS pattern.

A: That tutorial is pretty useless. It's just a wrapper over EF's DbSet. Very bad example. The repository pattern itself means you need to design a proper interface based on the domain needs . Usually you have at least 3 needs: Add, Get, Save. But everything depends on your domain and that's important: there is no recipe, it's just what the app needs.
The repository implementation is just the persisting/loading of whole business objects (where a business object is a business concept). You've chosen Ado.net ( you should have chosen a micro-Orm, as there is no benefit in using ado.net) to communicate with the db. OK, just do the saving to db, querying the db routine.
There is no recipe/rule of how to implement a repository. The 'hard' part is designing the interface. The implementation is just a class using the db (in whatever way you want).
We're using interfaces because, usually, a repo's interface is part of the domain, while its implementation is part of the persistence. This also allows for multiple repository implementations and for easy testing (via mocking).
Btw, you have to understand that the repository pattern is just a simple principle. It can be implemented in what way you want, there is no a 'correct' way. What needs to be 'correct' though is the interface design in the way that only business objects should be used and no implementation details (like IQueryable) should be leaked.


text:
Q: How to recreate the beautiful transition when you open an ingredient card in the apple example app "Fruta" I am relatively new to swiftUI and iOS development in general and recently I downloaded Apple's example code "fruta" which uses appclips, widgets, etc.
I want to do something similar to the transition when you open an ingredient but no matter how much I dig into their code I can't find how they did it.

A: i found a way but i don't think it's the most optimal way.
struct IngredientCardTest: View {
@State var isCardShown = false
@Namespace var namespace

var body: some View {
        GeometryReader { geo in
        if isCardShown {
            RoundedRectangle(cornerRadius: 25)
                .matchedGeometryEffect(id: "card", in: namespace)
                .frame(maxWidth: 300, maxHeight: 350, alignment: .center)
                .scaleEffect(isCardShown ? -1 : 1)
                .frame(maxWidth: geo.size.width, maxHeight: geo.size.height, alignment: .center)
                .onTapGesture {
                    withAnimation(.spring()) {
                        isCardShown.toggle()
                    }
                }
        } else {
            RoundedRectangle(cornerRadius: 25)
                .matchedGeometryEffect(id: "card", in: namespace)
                .frame(maxWidth: 190, maxHeight: 190, alignment: .center)
                .scaleEffect(isCardShown ? -1 : 1)
                .frame(maxWidth: geo.size.width, maxHeight: geo.size.height, alignment: .center)
                .onTapGesture {
                    withAnimation(.spring()) {
                        isCardShown.toggle()
                    }
                }
        }
        }
    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
}

}


text:
Q: JOIN with NESTED STATEMENT I have these tables:
CREATE TABLE Financial_plan
(
    ID INT NOT NULL,
    advisor_ID INT NOT NULL,
    product_ID INT NOT NULL,
    price INT NOT NULL,

    PRIMARY KEY (ID)
);

CREATE TABLE Advisor
(
    ID INT NOT NULL,
    role_id INT NOT NULL,
    office_id INT NOT NULL,
    name VARCHAR (50),
    surname VARCHAR (50) NOT NULL,
    active NUMERIC (1) NOT NULL,

    PRIMARY KEY (ID)
);

And I do a new column count_plan like this
SELECT
    Advisor_ID, count_plan
FROM
    (SELECT
         Financial_plan.Advisor_ID,
         COUNT(Financial_plan.ID) AS count_plan
     FROM
         Financial_plan
     GROUP BY
         Financial_plan.Advisor_ID
     ORDER BY
         count_plan DESC)

I would like to JOIN a new table with column count_plan with Advisor table, but can't figure it out
I try
SELECT
    Advisor_ID,
    count_plan
FROM
    (SELECT
         Financial_plan.Advisor_ID,
         COUNT(Financial_plan.ID) AS count_plan
     FROM
         Financial_plan
     GROUP BY
         Financial_plan.Advisor_ID
     ORDER BY
         count_plan DESC) Advisor_plan
LEFT JOIN
    Advisor ON Advisor_plan.Advisor_ID = Advisor.ID

This statement doesnt do the join.
I would like to add to information from Advisor table to record of the best advisors by number of plans.
So I would like to get table like this
Advisor_ID count_plan role_id office_id name surname active

A: As every advisor_id is unique, you have a 1:! relation to advisor, so you need to add only the missing columns

SELECT
    Advisor_ID,
    count_plan,
    role_id,
    office_id,
    name,
    surname,
    active
FROM
    (SELECT
         Financial_plan.Advisor_ID,
         COUNT(Financial_plan.ID) AS count_plan
     FROM
         Financial_plan
     GROUP BY
         Financial_plan.Advisor_ID
     ORDER BY
         count_plan DESC) Advisor_plan
LEFT JOIN
    Advisor ON Advisor_plan.Advisor_ID = Advisor.ID

Advisor_ID | count_plan | role_id | office_id | name | surname | active
---------: | ---------: | ------: | --------: | :--- | :------ | -----:

db<>fiddle here


text:
Q: What is the opposite of "dumb down"? I am trying to figure out what would be the opposite of "dumb down" as in "I can dumb down this presentation". In this example the presentation is too complex and needs to be simplified for the target audience, but what about the other way around, I can't say "complex up", and whilst "smarten up" is valid it doesn't work in this context.

A: If you intend the material to be hard to understand, then I like complicate

*

*complicate
  : to make (something) more difficult or less simple

It does not imply that the material will be digestible. On the contrary, I feel like it implies that the material will be difficult to understand.
If you want to make it more detailed, but still understandable, I would say make something sophisticated.

*sophisticated

*

*:  deprived of native or original simplicity: as
a :  highly complicated or developed :  complex

I didn't see a problem with smarten, or smarten up. You said "it's doesn't work here", but didn't explain why. It sounds like it does.

*smarten
  :  to make smart or smarter; especially :  spruce —usually used with up.

*smarten up

*

*US :  to become more intelligent or aware :  to become smarter

*US :  to make (someone or something) smarter or more aware

A: I'm not sure there is a simple established phrase that complements "dumb down." As you've mentioned in some earlier comments to previous answers, verbs like complicate or complexify don't do the trick – the goal is not to make the presentation more complicated, the goal is to make it less simplistic. Those two aren't quite synonymous.
I can't think of a good single word or established idiom, but I think I'd probably say it something like this:

I can dumb down this presentation, or I can make it speak to the expert.
I don't want to dumb down this presentation, I want it geared it more toward the expert.

Adding the word expert is key, I think. According to Wikipedia, dumbing down is:

the deliberate oversimplification of intellectual content within education, literature, cinema, news, video games and culture in order to relate to those unable to assimilate more sophisticated information (emphasis added)

In regards to a presentation, I think we generally "dumb down" information to make it more digestible for novices and neophytes; therefore, the opposite would be to design the presentation for experts, rather than for the masses.
I looked up expert in a thesaurus, just to see if there was a better word that could be used. Several words were listed (including authority, pundit, maestro, virtuoso, master, wizard, connoisseur, and aficionado), but the only one I thought might be a worthy alternate candidate was specialist:

We don't need to dumb down this presentation; it's designed for the specialist.

A: To complexify
Oxford English Dctionary:

a. trans. To make complex or complicated. rare.
  b. intr. To become (more) complex or complicated. rare.

Or
You could complicate or overcomplicate a presentation.


text:
Q: How does the Announcer badge work? I understand that the Announcer badge can be earned if the question is visited 25 times.
But is this only when I share a link to this question in one of my answers, or can I also share the link (with my user id somewhere to count the accesses) somewhere else, maybe Facebook?

A: You can share the link anywhere, so long as you use the link for questions underneath the question. It does not have to be for your question; you can share the link to any question.

A:

But is this only when I share a link to this quesiton in one of my answer or can I also share the link (with my user id somewhere to count the accesses) somewhere else, maybe facebook?

In order to gain the Announcer badge you must share a link outside the SE network. Sharing a link in one of your answer won't work.
Also, rules for the Announcer, Booster and Publicist badges have changed since 2012-01-10. And sharing direct links to answers now also counts towards these badges.


text:
Q: boost::asio::thread_pool iterating over threads I have a quite nasty deadlock condition in my application which I know how to solve, but it requires me to get all thread ids in advance, after constructing the boost::asio::thread_pool, and before actually using it.
How can I iterate over all threads in a boost::asio::thread_pool in order to get the thread ids?

A: You can insert your threads into the pool:
#include <boost/asio.hpp>
#include <fmt/ranges.h>
#include <ranges>
#include <vector>
using std::ranges::views::transform;

static std::string pretty_id(std::thread::id id) {
    return fmt::format("{:02x}", std::hash<std::thread::id>{}(id) % 0xff);
}
static std::string this_id() { return pretty_id(std::this_thread::get_id()); }

int main() {
    boost::asio::thread_pool pool(0); // empty

    std::vector<std::thread::id> ids;

    for (int i = 0; i<10; ++i) {
        std::thread worker{[&pool] {
            fmt::print("Thread {} attaching\n", this_id());
            pool.attach();
            fmt::print("Thread {} exiting\n", this_id());
        }};

        ids.push_back(worker.get_id());
        worker.detach(); // attach transfers ownership to pool
    }

    fmt::print("Operational: {}\n", ids | transform(pretty_id));

    pool.join();
}

See it Live On Coliru, printing
Thread fa attaching
Thread d3 attaching
Thread 82 attaching
Thread a3 attaching
Thread 31 attaching
Thread 35 attaching
Thread 32 attaching
Thread e5 attaching
Thread f0 attaching
Operational: ["fa", "d3", "a3", "31", "82", "35", "32", "e5", "f0", "d6"]
Thread d6 attaching
Thread d6 exiting
Thread fa exiting
Thread d3 exiting
Thread 82 exiting
Thread a3 exiting
Thread e5 exiting
Thread 31 exiting
Thread f0 exiting
Thread 32 exiting
Thread 35 exiting

CAVEAT: the idea of "fixing" deadlocks with bespoke logic based on thread ids sounds like a design smell.


text:
Q: Vue component - detect outside click So, I've implemented this custom dropdown list in Vue JS (2.x) and pretty much have what I need, except once the list is open, I would like for a click outside the component (anywhere on the parent page or component) to close the list. I tried catching the blur event of the root div of my component, but it understandably didn't work, because divs don't get focus and hence cannot be blurred. So at this moment, the solution seems to be - to be able to listen for a click event outside the component. Is that possible? Can a child listen for events on its parent in Vue? If or even if not, what is the best and/or the easiest way to achieve this behavior?
Here's my code in a CodeSandbox, and I am also reproducing it below for convenience - https://codesandbox.io/s/romantic-night-ot7i8
Dropdown.vue
<template>

    <button class="sel-btn" @click="listOpen = !listOpen">
      {{ getText() }}
    </button>

      <button
        class="item"
        v-for="(l, i) in list"
        :key="i"
        @click="btnClicked(i)"
      >
        {{ l }}
      </button>

</template>

App.vue
<template>

      <Dropdown
        :list="regions"
        v-model="selectedRegion"
        style="margin-right: 10px"
        defaultText="--Select Region--"
      ></Dropdown>
      <Dropdown
        :list="cities"
        v-model="selectedCity"
        defaultText="--Select City--"
      ></Dropdown>

      (This poem excerpt is here to act as a filler)

The Daffodils

William Wordsworth

      I wondered lonely

      As a cloud

      That floats on high

      O'er vales and hills

      When all at once

      I saw a crowd

      A host

      Of golden daffodils.

      Region Selected:  {{ selectedRegion }}

      City Selected:  {{ selectedCity }}

</template>

A: ok... this is by far not the best solution but it is a working solution.
i used all my MacGyver powers and found a way.
please check this CodeSandbox
all i did was to use your listOpen and added a eventListner. i figured out that your custom dropdown has no build in @blur because its not a input ofc.
so i added a event for it inside the mounted hook.
the key is i also added a setTimeout on 100ms because otherwise you where not able to select any item inside your dropdown, the dropdown would close with blur faster then you are able to select anything.

A: The best approach is to use a Vue Custom Directive to hook the focus functionality to your component and propagate events to outside of it when a click happens on the inside or on the outside of it.
In the example bellow, we created the v-ctrlfocus directive that will hook to the root of your component and create a click event listener for the entire window.
That way, when the click event is fired, we can compare if it happened inside the component or outside of it.
If it happened inside, we will fire a focusin event that you can listen outside of your component with @focusin. Conversely, if the click happened outside of the component, it will fire a focusout event.
To be more updated with Vue new toys, I used typescript and
<template>

    ...your component code goes here...

</template>

The credits to this approach goes to this Stackoverflow post and to this great CSS Tricks article about the issues with different approachs to this problem.
You can also globally register this custom directive at the app level and use it all around your code, as Vue docs mention.


text:
Q: Pass Input Object to Start-Job File I can't seem to figure out why the input passed to start-job disappears.  I have this code in one script:
$data = "some test string data"
Start-Job -FilePath ".\Tasks.ps1" -InputObject $data

And in the tasks.ps1 script I get a null value for the $input object unless I call it immediately but disappears after doing so:
$input #displays the data
$input #null

I've tried immediately assigning it to another variable ($newvalue = $input) but the value of that variable shows null too.
What am I missing here?  How do I retain the input data?

A: Ok, I've found the issue.  The $input object is passed as a PilelineReader which I'm assuming is ReadToEnd when called in the job.  When I assign the $input to a variable I'm sending the PipeLineReader instead of its value.  To get around this I used this:
[string]$newData = $input

This did the trick in preventing a read action happening when accessing the object.


text:
Q: SWT UI hangs even when a new thread is started I'm starting a new thread using Display.getDefault().asyncExec(). The thread does something like this:
public void run()
{
    while (! condition)
    {
      //do some processing
      mainWindow.updateStatus(..); //this will call a setText method on a label in
                    //the original thread
    }
}

However when I run this thread, the program hangs rather than showing the status smoothly in the label. What am I doing wrong?

A: You misunderstand the concept of thread. What you call thread is actually just a piece of code that you schedule to be executed on the (UI) thread.
As a rule, code on UI thread should execute quickly and return as soon as possible. Your while loop most likely violates this rule. The solution is to take the loop out of the UI thread i.e. the run method and put it around the Display.asyncExec() call.

A: To expand a bit on Käärik's answer: your code should look like
public class MyTask implements Runnable {
    public void run()
    {
        while (! condition)
        {
            //do some processing without touching the screen
            Display.getDefault().asyncExec(new Runnable() {
                public void run() {
                    mainWindow.updateStatus(..);
                }
            });
        }
    }
}

and then you run it as new Thread(new MyTask()) or e.g. schedule it on a thread pool to repeat each 10 seconds.


text:
Q: Why, after clicking the button "update State" the state inside the super doesnt update to sliced array instead console logs entire array? In the given image below
why, after clicking the updatestate button, doesnt update the state to sliced array that is  ['usa','china'] but instead updates to entire array in console.log, Yet on the page it shows it correctly.?

A: Lines 10 and 11 are called mutating states, which goes against React's recommended way to update the state, so it may or may not work.


text:
Q: Adjusting label according to its data in ios using Swift I have a custom UITableViewCell design as

What I want to is that "points" label should come under the last digit in my Numbers label. Lets say I have 1990 value in my Numbers label the "points" labels should come uder the last digit "0" in this case.
How can I do this?

A: You can add a Horizontal Space between the points label and the number label with a negative value roughly equates the width of 1 character
For instance here:

Here in this example the horizontal space is -30 while the font size of the number label is 61pt. You can see that it is roughly one character width. (Of course you can apply more complicated math if you please to get the exact value you desire or accommodates your design principle)
And with making sure that the number label does not have an explicit width constrain it will automatically expand to fit its contents and therefore pushing the points label appropriately.
like this:


text:
Q: Adding a count and an index in my LinkedList I need to add an index and a count function for my program but I am really confused on how to go about this because my teacher is very broad. Any ideas that I could do for adding an index and a count function into my Linked List?
Here's my code:
    from ListNode import ListNode

    class LinkedList(object):

    #--------------------------------------------------------------

    def __init__(self, seq=()):

        """ Pre: Creates a Linked List
        Post: Creates a list containing the items in the seq=()"""

        if seq == ():

            # If there is no items to be put into the list, then it creates an empty one.
            self.head = None

        else:

            # Creates a node for the first item.
            self.head = ListNode(seq[0], None)

            # If there are remaining items, then they're added while keeping track of the last node.
            last = self.head
            for item in seq[1:]:
                last.link = ListNode(item, None)
                last = last.link

        self.size = len(seq)

    #-------------------------------------------------------------

    def __len__(self):

        '''Pre: Nothing.
           Post: Returns the number of items in the list.'''

        return self.size

    #-------------------------------------------------------------

    def _find(self, position):

        '''This is a private method, which means it only works in this class.
        This returns the last node used. (0 is the first item, size-1 is the last item)
        Pre: 0 (less than or equal to) position (less than) self.size
        Post: Returns the ListNode at the specified position in the list.'''

        assert 0 <= position < self.size

        node = self.head
        # move forward until we reach the specified node
        for i in range(position):
            node = node.link
            return node

    #-------------------------------------------------------------

    def append(self,x):

        '''This adds (Appends) 'x' onto the end of the list
        Post: X is appended to the end of the list.'''

        # First create a new node containing x
        newNode = ListNode(x)

        # This will link it onto the end of the list.

        if self.head is not None:
            # Not an empty list
            node = self._find(self.size - 1)
            node.link = newNode

        else:
            # If it is an empty list.
            # You will set self.head to the new node
            self.head = newNode
        self.size += 1

    #-------------------------------------------------------------

    def __getitem__(self, position):

        ''' returns the data item at the location position
        Pre: 0 <= position < size
        Post: Returns data item at the specified position.'''

        node = self._find(position)
        return node.item

    #-------------------------------------------------------------

    def __setitem__(self, position, value):

        ''' Sets the data item at the location position to the value.
        Pre: 0 <= position < self.size
        Post: Sets the data item at the specified position to value.'''

        node = self._find(position)
        node.item = value

    #--------------------------------------------------------------

    def __delitem__(self, position):

        ''' Deletes the item at the location position from the list.
        Pre: 0 <= position < self.size
        Post: The item at the specified position is removed from the list.'''

        assert 0 <= position < self.size

        self._delete(position)

    #--------------------------------------------------------------

       def __max__(self):

            ''' Goes through each node and compares what the max is for the linked list.
            Post: Finds the max of the linked list and returns that value.'''

            max_value = self.head.item
            node = self.head.next
            while node is not None:
                if node.item > max_value:
                    max_value = node.item
                node = node.link
            return max_value

        #--------------------------------------------------------------

        def __min__(self):

            ''' Goes through each node and compares what the min is for the linked list.
            Post: Finds the min of the linked list and returns that value.'''

            min_value = self.head.item
            node = self.head.next
            while node is not None:
                if node.item < min_value:
                    min_value = node.item
                node = node.link
            return min_value

    #--------------------------------------------------------------

    def _delete(self, position):

        ''' This is a private function where it deletes an item at the location
        position from the list.
        Pre: 0 <= position < self.size
        Post: The item at the specified location is removed from the list.
        The item is then returned ( To be used with pop.)'''

        if position == 0:
            # Save the item from the initial node
            item = self.head.item

            # Change the self.head to point "over" the deleted node.
            self.head = self.head.link

        else:
            # Find the node before the one that you are deleting.
            prev_node = self._find(position - 1)

            # Save the item from the node you are deleting.
            item = prev_node.link.item

            # Change the previous node to go over the deleted node. (Example 2 goes to 4)
            prev_node.link = prev_node.link.link

        self.size -= 1
        return item

    #--------------------------------------------------------------

    def pop(self, i = None):

        ''' This returns and removes whatever is at position 'i' from the list. It is
        defaulted to return and remove the last item.
        Pre: self.size > 0 and ((i is None or (0 <= i < self.size))

        Post: If I is None, then the last item in the list is removed and then returned.
        Otherwise, the item at position 'i' is removed and returned.'''

        assert self.size > 0 and (i is None or (0 <= i < self.size))

        # The default is to delete the last item in the list.
        # 'i' could be zero so we need to compare to None.

        if i is None:
            i = self.size - 1

        return self._delete(i)

    #-----------------------------------------------------------------

    def insert(self, i, x):

        ''' Inserts 'x' at the position 'i' is at in the list.
        Pre: 0 <= i <= self.size
        Post: x is inserted into the list at position 'i', and the old segment
              from position 'i' (oldsize-1) are now at position 'i'+1 (newsize - 1).'''

        assert 0 <= i <= self.size

        if i == 0:
            # Inserting before ) requires changing/updating self.head.
            self.head = ListNode(x, self.head)

        else:
            # Find the item that this node will be inserted after.
            node = self._find(x, self.head)
            node.link = ListNode(x, node.link)

        self.size += 1

    #-----------------------------------------------------------------

    def __copy__(self):

        ''' Post: Returns a new Linked List object that is a shallow copy of self.'''

        a = LinkedList()
        node = self.head
        while node is not None:
            a.append(node.item)
            node = node.link
        return a

    #-----------------------------------------------------------------

    def __iter__(self):

        return LinkedListIterator(self.head)

#---------------------------------------------------------------------

class LinkedListIterator(object):

    #-----------------------------------------------------------------

    def __init__(self, head):
        self.currnode = head

    #-----------------------------------------------------------------

    def next(self):
        if self.currnode is None:
            raise StopIteration
        else:
            item = self.currnode.item
            self.currnode = self.currnode.link
            return item

This may seem basic for you guys but I am struggling to figure out what my teacher wants me to index or count in this program.

A: The best would be to look at python's documentation of those methods:
[].index.__doc__
[].count.__doc__


text:
Q: what is the reason that 'randomNumber1' is always assigned by '0' though i use Random.Range(0,2) I want to randomly assign 0 or 1 to randomNumber1, but I failed with this code.
This is the code in Unity
public class Practice : MonoBehaviour
{

    public static int randomNumber1;
    public static int randomNumber2;

    public class randd
    {
        public void randdom_dd()
        {
            int randomNumber1 = Random.Range(0, 2);
            if (randomNumber1 == 0)
            {
                int randomNumber2 = 1;
            }

            else
            {
                int randomNumber2 = 0;
            }
        }

    }

    public void OnClick()
    {
        if (randomNumber1 == 0)
        {
            print("정답!");
        }

        else
        {
            print("틀렸어!");
        }

    }
}

I think, when I play the codes, randomNumber1 has always same int. I've tried to change the min and max in Random.Range(min, max) and some tries, I failed.

A: It looks like your random_dd method isn't actually being called anywhere.  Because randomNumber1 is defined as a field, it will automatically instantiate to zero.  This is why you are always seeing your random number show up with the same value.
Try calling the random_dd method before the OnClick method is being hit, or just calling the random_dd method at the top of your OnClick method before you evaluate your random variable, and see if that works.  Here's a link to an example that elaborates on the definitions of fields in C# Defining a Field in C#.
You also shouldn't be using the 'int' keyword when assigning a value to variables that have already been defined in your program, which in your case are the randomNumber1 and randomNumber2 variables.

A: thanks all of you! it works with this codes
and yes, you are right, jmrpink. i don't use randomNumber2 in this code. my mistake!
public void OnClick()
{
        int randomNumber1 = Random.Range(0, 2);
        if (randomNumber1 == 0)
        {
            int randomNumber2 = 1;
        }

        else
        {
            int randomNumber2 = 0;
        }
    if (randomNumber1 == 0)
    {
        print("정답!");
    }
    else
    {
        print("틀렸어!");
    }

}


text:
Q: Adding a custom TypeAdapterFactory for Google GSON to detect use of annotations to return custom TypeAdapter dynamically Let us start with sharing working and pastable code (requires google gson package):
package mypackage;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

public final class ALL {
    static final Gson GSON = new GsonBuilder().registerTypeAdapterFactory(new Factory()).create();

    /////////////////////////////////////////////////////////////////////

    @Target( { METHOD, FIELD, ANNOTATION_TYPE, TYPE })
    @Retention(RUNTIME)
    public @interface Serialize {}

    /////////////////////////////////////////////////////////////////////

    public static void main(String[] args) {
        Test test = new Test();

        String json = GSON.toJson(test);

        System.out.println(json);
    }

    /////////////////////////////////////////////////////////////////////

    public static final class Test {
        @Serialize
        String abc = "def";
    }

    /////////////////////////////////////////////////////////////////////

    public static final class Factory implements TypeAdapterFactory {
        @Override
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
            Serialize annotation = type.getRawType().getAnnotation(Serialize.class);

            boolean annotationPresent = type.getRawType().isAnnotationPresent(Serialize.class);

            Annotation[] annotations = type.getRawType().getAnnotations();

            if (annotationPresent) {
                System.out.println("11111111111111");
            }

            if (annotation != null) {
                return new Adapter<>();
            }

            return gson.getDelegateAdapter(this, type);
        }
    }

    /////////////////////////////////////////////////////////////////////

    public static final class Adapter<T> extends TypeAdapter<T> {
        private static final java.util.Base64.Encoder ENCODER = java.util.Base64.getEncoder();
        private static final java.util.Base64.Decoder DECODER = java.util.Base64.getDecoder();

        @Override
        public T read(JsonReader in) throws IOException {
            in.beginObject();
            String a = in.nextString();
            in.endObject();

            try {
                return deserialize( DECODER.decode(a) );
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public void write(JsonWriter out, T value) throws IOException {
            out.value( encode(serialize(value)) );
        }

        private String encode(byte[] serialize) {
            return ENCODER.encodeToString( serialize );
        }

        private byte[] serialize(T value) throws IOException {
            try (ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream os = new ObjectOutputStream(out); ) {
                os.writeObject(value);
                return out.toByteArray();
            }
        }

        private T deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
            try (ByteArrayInputStream in = new ByteArrayInputStream(bytes); ObjectInputStream is = new ObjectInputStream(in); ) {
                return (T) is.readObject();
            }
        }
    }
}

If we look at Test class, the goal is to output something else if the annotation @Serialize is present. In this case we output bytes in String. And when we then read this back, we would like to deserialize it.
Other ways of understanding the goal is to think of maybe using an annotation you would like to encrypt a value and you could decrypt it on readback.
This should be possible, no?
I know i can register TypeAdapters based on field type, however, I would like to be able to use annotations to declare intent instead.
No wrapper classes. You can create a custom JsonSerializer but this requires registering.
In the example above, the type.getRawType().getAnnotation(Serialize.class); is always returning null and Annotation[] annotations = type.getRawType().getAnnotations() always empty, so unable to detect using the factory.
Unsure how to detect the annotation dynamically.
Do you know?

A: How about using @JsonAdapter? You anyway need to know how to do de-/crypting and need to implement tha per type. For string in your case, for example:
public class CryptoAdapter extends TypeAdapter<String> {
    @Override
    public void write(JsonWriter out, String value) throws IOException {
        out.jsonValue(org.apache.commons.lang3.StringUtils.reverse(value));
    }
    @Override
    public String read(JsonReader in) throws IOException {
        return org.apache.commons.lang3.StringUtils.reverse(in.nextString());
    }
}

Usage:
public class Test {
    @JsonAdapter(CryptoAdapter.class)
    String abc = "def";
}

The problem is that Gson does not provide (to my knowledge) any direct means to create some own field processor that lets user to read the field/class member annotations.
In other words you need an access to the field during de-/serialization and that seem not to be possible in an easy way.
That is why there is this @JsonAdapter.
If interested to study more clone source code from GitHub and check:
public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory

Unfortunately final. There is a method named createBoundField (which I think is the logic behind recognizing @JsonAdapter for fields) and the path and overriding that logic is not so straightforward.
For classes there seems to be solution quite similar to yours:
public final class JsonAdapterAnnotationTypeAdapterFactory
    implements TypeAdapterFactory

Both above mentioned are added to the list of TypeAdapterFactories when a new Gson is created.


text:
Q: How to do multiple insert as well update by using dapper .net? How to do multiple insert (50000 record) as well update using dapper .net ?

*

*Is it possible to use SqlBulkCopy to achieve this? If yes then how?

*Is there any best way to implement multiple hierarchical insert or update using Dapper.net?
Technologies : C#, SQL Server 2012, Dapper.net

A: *

*If you just want to insert: SqlBulkCopy should be fine; if you want an "upsert", I suggest table-valued-parameters (which dapper supports) and the merge t-sql operation

*Dapper just simplifies ado.net; if you think of a way to do it in ado.net, dapper can probably make it easier for you; however, it sounds like multiple TVPs might suffice

A: If you are mean to OK and able to segregate insert and update entities separately then I would suggest to use Dapper.Contrib library provided by Dapper.Net guys themselves. It is available via nuget. It has worked very efficiently for my project.
Here is the link to their Github project page.


text:
Q: Firebase-messaging in background I know that this question is so old and there are a lot of answers on it, but I have not found my decision.
I want to update widget with firebase-cloud-messaging, but Firebase method onMessageReceived() is not calling when app is in background.
I've tried to change notification to data as in the most of the answers here, but it not helps me: onMessageReceived() is not calling when app is even in foreground.
So, my Firebase JSON is:
{ "registration_ids": [ "ids" ],
"priority": "high",
"content_available": true,
"data": {
    "id_request": "1229",
    "unreadedAnnouncements": "4",
    "requestsCount": "9",
    "survaysCount": "5",
    "sound":"default",
    "title":"test",
    "message": "test",
    "body": "test" } }

If it matters, my Firebase-dependencies:
implementation 'com.google.firebase:firebase-core:10.2.1'
implementation 'com.google.firebase:firebase-messaging:10.2.1'
implementation 'com.google.firebase:firebase-auth:10.2.1'

Maybe there are some new solutions? On the SO there are the most of solutions from 2016.

A: @Override
public void onMessageReceived(RemoteMessage remoteMessage)
{
    super.onMessageReceived(remoteMessage);

    if (remoteMessage.getData() != null)
        sendNotification(remoteMessage);
}

then you can parse data like this:
    private void sendNotification(RemoteMessage remoteMessage)
    {
       Map<String, String> data = remoteMessage.getData();
       String title = data.get("title");
       String content = data.get("content");
       // your code
    }

A: The solution that is helped me:
In the Firebase I've just changed field registration_ids to to.
Final Firebase JSON:
{ "to": [ "ids" ],
"priority": "high",
"content_available": true,
"data": {
    "id_request": "1229",
    "unreadedAnnouncements": "4",
    "requestsCount": "9",
    "survaysCount": "5",
    "sound":"default",
    "title":"test",
    "message": "test",
    "body": "test" } }


text:
Q: Plot a legend and well-spaced universal y-axis and main titles in grid.arrange I have the following code which will generate two pdf files containing plots to the current working directory:
library(reshape)
library(ggplot2)
require(ggplot2)
source("http://gridextra.googlecode.com/svn/trunk/R/arrange.r")

data<-structure(list(Loci = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L,
8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L,
21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L,
34L, 35L, 36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 52L, 44L, 45L,
46L, 47L, 48L, 49L, 50L, 51L, 53L, 54L, 55L, 56L, 57L, 58L, 59L,
60L, 61L, 62L), .Label = c("Baez", "Blue", "C147", "C204", "C21",
"C278_PT", "C294", "C316", "C485", "C487_PigTa", "C536", "Carey",
"Cool", "Coyote", "Deadpool", "Epstein", "Glass", "Harrison",
"Harvest", "Hazel", "i-113", "i-114", "i-120_PigT", "i-126",
"i-127", "Imagine", "Jackstraw_", "Jericho", "Jerry-Garc", "Jude",
"Kitty", "Majesty", "Million", "Monkey", "Mozambique", "Neil",
"Nettie", "Piggies", "Psylocke", "Queen", "Ramble", "Sinv-25",
"Sinv12", "Sol-11", "Sol-18", "Sol-20", "Sol-49", "Sol-6", "Sol-J1",
"Sol-M2", "Sol-M3", "SolB8", "st_stephen", "Starr", "Sun_King",
"Taxman", "Tombstone_", "Wallflower", "Weight", "Wigwam", "Workingman",
"Yellow"), class = "factor"), All = c(0.3357, 0.4166, 0.0242,
0.9708, 0.4518, 0.0666, 0, 0.5925, 0.2349, 0.3242, 0.3278, 0.0246,
0.0352, 0.0646, 0.0563, 0.6854, 0.4664, 0.8298, 0.8831, NA, 0.0078,
0.771, 0.1376, 0.0055, 2e-04, 1, 0.2577, 0.3326, 0.0066, 0.0024,
0.6136, 0.4155, 0.9931, 0.2111, 0.6373, 0.0762, 0.5153, 0.1103,
0.0569, 0, 1, 0.732, 0, 0, 0.9225, 0.1257, 0.1658, 0.9603, 0.4629,
0, 0.4155, 0.0791, 0.0777, 0.3996, 0.1212, 0.6207, 0.5766, 0,
0.1347, 0.3754, 0, 0.2737), X1_only = c(0.4758, 0.3188, 0.1465,
0.3209, 1, 0.0278, 0.2065, 0.6187, 0.9377, 0.8586, 0.7292, 0.0133,
1, 1, 1, 0.961, 0.427, 1, 0.2203, NA, 0.8919, 0.2695, 0.3724,
0.5798, 0.5304, 1, 0.568, 0.2291, 0.4376, 1, 0.1572, 0.2022,
0.9544, 0.2462, 0.9699, 0.4439, 0.2204, 0.1135, 0.3063, 0.0311,
0.0384, 0.2833, 1, 0.7024, 0.7382, 0.4923, 0.4453, 0.2341, 0.7493,
0.0868, 0.8801, 0.8708, 1, 1, 1, 0.0491, 0.291, 0.2037, 0.1342,
0.5321, 0.4787, 0.7801), X78_only = c(0.3379, 0.4102, 0.2134,
0.6807, 0.8242, 1, 0.0046, 0.279, 0.825, 0.7563, 0.6055, 0.7472,
1, 0.4958, 0.0018, 0.0175, 1, 1, 0.5647, NA, 0.2124, 0.519, 0.5204,
0.2272, 0.03, 1, 0.0319, NA, 0.4467, 0.4473, 0.1593, 0.6066,
0.5907, 0.0624, 0.5699, 0.6585, 0.1414, 0.546, 0.6395, 0.0102,
0.3112, 0.791, 0, 0.7753, 0.4155, 0.9279, 0.4834, 0.3059, 0.5967,
0.373, 0.4114, 0.9291, 0.1159, 0.7238, 0.5993, 0.7975, 0.3283,
0.0511, 0.4902, 0.0438, 2e-04, 0.2357), X8_removed = c(0.0967,
0.5831, 0.058, 0.9268, 0.3518, 0.0629, 0, 0.6229, 0.2217, 0.2602,
0.7123, 0.0181, 0.0348, 0.1482, 0.1706, 0.6748, 0.3238, 0.8134,
0.8032, NA, 0.0246, 0.5794, 0.5204, 0.0254, 0.0056, 1, 0.6597,
0.3373, 0.004, 0.0087, 0.9061, 0.577, 0.9565, 0.4168, 0.7951,
0.1069, 0.4071, 0.1457, 0.1453, 0, 0.8385, 0.4658, 0, 0, 0.7396,
0.0748, 0.3677, 0.9571, 0.1188, 0, 0.5673, 0.0396, 0.0708, 0.3645,
0.1147, 0.5851, 1, 0.001, 0.0614, 0.131, 0, 0.4813), X8_only = c(0.1169,
0.8327, 0.2169, 0.0907, 1, 1, 0.07, 0.486, 0.709, 0.8882, 0.4389,
1, 0.7078, 0.4496, 0.1266, 0.1945, 0.4527, 1, 0.6518, NA, 0.3594,
0.7715, 0.134, 0.2389, 0.0203, 1, 0.1061, NA, 0.1293, 0.2558,
0.167, 0.4815, 0.7756, 0.0403, 0.2448, 0.2265, 0.0952, 0.6658,
0.3405, 0.0402, 0.5906, 0.2405, 0.0086, 0.5086, 0.4709, 1, 0.0567,
0.4146, 0.7554, 0.104, 0.1917, 0.8625, 1, 1, 1, 0.8727, 0.1439,
0.0452, 1, 0.5804, 0, 0.2764), X7_removed = c(0.2989, 0.7268,
0.0087, 0.8874, 0.5853, 0.0568, 0, 0.7622, 0.4226, 0.3232, 0.3972,
0.02, 0.0159, 0.0541, 0.4919, 0.5951, 0.5525, 0.8114, 0.5738,
NA, 0.0062, 0.7274, 0.0155, 0.0233, 0.002, 1, 0.232, 0.3476,
0.011, 9e-04, 0.5433, 0.3725, 0.7263, 0.2462, 0.4556, 0.0426,
0.7468, 0.1235, 0.0051, 0, 1, 0.8962, 0.0014, 0, 0.9892, 0.1163,
0.1284, 0.6873, 0.3932, 0, 0.3722, 0.0889, 0.3782, 0.4761, 0.0484,
0.5321, 0.5519, 0, 0.3453, 0.0732, 0, 0.3483), X7_only = c(1,
0.5714, 0.2825, 0.8673, 0.5557, 0.6861, 0.0044, 0.1146, 0.4957,
0.5248, 0.8372, 0.6665, 0.6789, 1, 0.0082, 0.1759, 0.3719, 1,
0.704, NA, 0.2585, 0.4634, 0.4283, 0.6815, 0.4161, 1, 0.1691,
NA, 0.4563, 1, 0.226, 1, 0.2349, 0.5886, 0.8154, 0.8839, 0.1631,
1, 0.5112, 0.1529, 1, 0.7245, 4e-04, 0.3095, 0.6184, 0.5542,
0.749, 0.394, 0.0298, 0.1994, 0.2881, 0.7696, 0.0637, 0.652,
1, 0.1494, 1, 0.3283, 0.134, 0.1992, 0.0848, 0.5826), X5_removed = c(1,
0.1453, 0.0176, 0.8428, 0.2277, 0.2563, 0, 0.5326, 0.1549, 0.4405,
0.395, 0.0195, 0.08, 0.1069, 0.0316, 0.6298, 0.5157, 1, 0.5967,
NA, 0.0265, 0.5703, 0.2667, 0.3485, 0.0021, 1, 0.1821, 0.3006,
0.007, 0.0112, 0.1964, 0.4427, 0.769, 0.1214, 0.6064, 0.0914,
0.4188, 0.021, 0.0814, 0, 0.8372, 0.8052, 0, 0, 0.8662, 0.7917,
0.0924, 0.9316, 0.7399, 0, 0.2031, 0.0701, 0.0652, 0.6636, 0.0513,
0.2049, 0.7161, 0, 0.0407, 0.1729, 0, 0.3079), X5_only = c(0.0642,
0.631, 0.5193, 0.979, 0.5348, 0.1304, 0.02, 0.0217, 0.0871, 0.2022,
0.7602, 1, 0.3532, 0.5292, 1, 0.3677, 0.0896, 0.3702, 0.6084,
NA, 0.1518, 0.3467, 0.1171, 0.0252, 0.7894, 1, 0.9842, 0.7315,
0.8511, 0.0717, 0.0585, 0.7955, 0.3517, 1, 0.8263, 0.6102, 0.268,
0.1071, 0.3837, 0.0175, 0.5887, 1, NA, 0.1198, 0.8537, 0.0101,
0.3807, 0.4939, 0.1469, 0.1368, 0.5458, 0.2514, 1, 0.3692, 1,
0.4877, 0.5787, 0.6025, 0.5888, 1, 0.3472, 1), X4_removed = c(0.4492,
0.3821, 0.0121, 0.9957, 0.5158, 0.0498, 0, 0.718, 0.8003, 0.1716,
0.661, 0.0194, 0.0511, 0.1862, 0.0188, 0.6454, 0.5077, 1, 0.8794,
NA, 0.3458, 0.6059, 0.1315, 0.0099, 0.003, 1, 0.0585, 0.4635,
0.0357, 0.0289, 0.6835, 0.2247, 0.8437, 0.3585, 0.6074, 0.1926,
0.3432, 0.3615, 0.0322, 0, 0.8418, 0.7076, 0, 0.9281, 0.7697,
0.1011, 0.3068, 0.971, 0.4686, 0, 0.3731, 0.1024, 0.0683, 0.8112,
0.3742, 0.7381, 0.2738, 0.0089, 0.2366, 0.6924, 0, 0.1984), X4_only = c(0.6485,
0.0709, 0.1639, 0.6908, 1, 1, 0.4469, 0.639, 0.0378, 0.5116,
0.0026, 0.6549, 0.6928, 0.2884, 1, 0.4386, 0.6246, 0.6188, 1,
NA, 0.0966, 0.3946, 0.7223, 0.1357, 0.8912, 1, 0.4741, 0.7526,
0.2005, 0.013, 1, 0.455, 0.1086, 0.1184, 0.8975, 0.3181, 0.9958,
0.0644, 0.0975, 0.0721, 1, 1, 1, 7e-04, 0.2754, 0.4852, 0.065,
0.747, 0.4823, 0.1971, 0.6178, 0.3781, 1, 0.362, 0.1168, 0.382,
0.4267, 8e-04, 0.188, 0.2115, 0.2937, 1), X3_removed = c(0.3009,
0.3414, 0.02, 0.9935, 0.4216, 0.1273, 0, 0.6406, 0.2728, 0.5307,
0.477, 0.0612, 0.0627, 0.0808, 0.1636, 0.6506, 0.6507, 0.8122,
0.9531, NA, 0.0144, 0.9274, 0.1646, 0.0171, 1e-04, 1, 0.2732,
0.4153, 0.0141, 0.0105, 0.6892, 0.3701, 0.9956, 0.0418, 0.5436,
0.2755, 0.4803, 0.0959, 0.1199, 0, 0.833, 0.5373, 0, 0, 0.9701,
0.1054, 0.1558, 0.9964, 0.6849, 0, 0.2023, 0.1072, 0.3401, 0.3629,
0.2504, 0.6056, 0.5372, 2e-04, 0.1168, 1, 0, 0.242), X3_only = c(1,
0.9325, 0.772, 0.5505, 1, 0.2068, 0.0829, 0.17, 0.8951, 0.0225,
0.8263, 0.2111, 0.5087, 0.768, 0.2471, 0.6294, 0.2815, 1, 0.0496,
NA, 0.3364, 0.6286, 0.2102, 0.6816, 0.372, 1, 0.7311, 0.5138,
0.0683, 0.1996, 0.6998, 1, 0.6988, 0.4426, 0.6669, 0.0412, 0.6081,
1, 0.237, 6e-04, 0.6349, 0.7124, 1, 0.2314, 0.0398, 1, 0.3487,
0.8153, 0.1271, 0.1145, 0.8641, 0.4056, 0.1488, 1, 0.2357, 0.26,
1, 0.2678, 0.5537, 0.0317, 0.0467, 1), X2_removed = c(0.6335,
0.349, 0.2095, 0.9777, 0.8928, 0.0571, 0, 0.4285, 0.2036, 0.3168,
0.3668, 0.0854, 0.413, 0.0608, 0.0526, 0.7608, 0.3094, 0.8186,
0.9273, NA, 0.0014, 0.6512, 0.4424, 0.0275, 0.2121, 1, 0.3008,
0.2381, 0.0173, 0.0075, 0.7423, 0.6126, 0.979, 0.1716, 0.862,
0.0245, 0.5096, 0.2795, 0.4794, 0, 1, 0.6888, 0, 0, 0.6213, 0.0935,
0.1351, 0.6946, 0.4708, 0.1458, 0.899, 0.4391, 0.0727, 0.5004,
0.3974, 0.8854, 0.2696, 0, 0.1846, 0.5871, 0, 0.2966), X2_only = c(0.191,
0.4397, 0.0403, 0.3606, 0.0089, 1, 0.0033, 0.659, 0.1818, 0.0949,
0.5521, 0.1637, 0.0014, 1, NA, 0.8585, 1, 1, 0.9437, NA, 0.4086,
0.1699, 0.0648, 0.9087, 0.0011, 1, 0.1291, 0.5329, 0.2315, 0.2844,
0.6429, 0.0488, 0.1814, 0.8658, 0.0869, 0.8394, 0.5938, 0.1722,
0, 0.0098, 1, 1, 1, 0.1742, 0.3911, 0.8523, 0.7331, 0.1271, 0.5119,
0, 0.0105, 0.0035, 1, 0.5665, 0.072, 0.2928, 0.4224, 0.5491,
0.4274, 0.1054, 0, 0.5817), X1_removed = c(0.1653, 0.7658, 0.0718,
0.7705, 0.4193, 0.1894, 0, 0.5167, 0.1053, 0.2823, 0.0496, 0.1439,
0.0258, 0.0676, 0.031, 0.5465, 0.4909, 0.6464, 0.9383, NA, 0.0124,
0.9288, 0.069, 0.0116, 6e-04, 1, 0.3301, 0.508, 0.0175, 8e-04,
0.6016, 0.7442, 0.9609, 0.4151, 0.6049, 0.1266, 0.4281, 0.2719,
0.0039, 0, 0.315, 1, 0, 0, 0.8931, 0.1124, 0.3804, 0.9233, 0.3355,
0, 0.3542, 0.0363, 0.0679, 0.2652, 0.122, 0.4025, 0.8155, 2e-04,
0.2642, 0.3629, 0, 0.2897)), .Names = c("Loci", "All", "X1_only",
"X78_only", "X8_removed", "X8_only", "X7_removed", "X7_only",
"X5_removed", "X5_only", "X4_removed", "X4_only", "X3_removed",
"X3_only", "X2_removed", "X2_only", "X1_removed"), class = "data.frame", row.names = c(NA,
-62L))

#now make subsets of this big dataset
split1_data<-droplevels(subset(data,data$Loci %in% data$Loci[1:8]))
split2_data<-droplevels(subset(data,data$Loci %in% data$Loci[9:16]))
split3_data<-droplevels(subset(data,data$Loci %in% data$Loci[17:24]))
split4_data<-droplevels(subset(data,data$Loci %in% data$Loci[25:32]))
split5_data<-droplevels(subset(data,data$Loci %in% data$Loci[33:40]))
split6_data<-droplevels(subset(data,data$Loci %in% data$Loci[41:48]))
split7_data<-droplevels(subset(data,data$Loci %in% data$Loci[49:56]))
split8_data<-droplevels(subset(data,data$Loci %in% data$Loci[57:62]))

#and melt each of them
split1_datam<-melt(split1_data,id="Loci")
split2_datam<-melt(split2_data,id="Loci")
split3_datam<-melt(split3_data,id="Loci")
split4_datam<-melt(split4_data,id="Loci")
split5_datam<-melt(split5_data,id="Loci")
split6_datam<-melt(split6_data,id="Loci")
split7_datam<-melt(split7_data,id="Loci")
split8_datam<-melt(split8_data,id="Loci")

#and make a plot for each of the melted subsets
p1<- ggplot(split1_datam, aes(x =Loci, y = value, color = variable, width=.15))+ geom_bar(position="dodge")+ geom_hline(yintercept=0.05)+ opts(legend.position="none",axis.text.x  = theme_text(angle=90, size=8)) + scale_y_discrete(breaks=seq(0,1)) + ylab(NULL)

p2<- ggplot(split2_datam, aes(x =Loci, y = value, color = variable, width=.15)) + geom_bar(position="dodge") + geom_hline(yintercept=0.05)+ opts(legend.position = "none", axis.text.x  = theme_text(angle=90, size=8)) + scale_y_discrete(breaks=seq(0,1))+ scale_fill_grey() + ylab(NULL)

p3<-p <- ggplot(split3_datam, aes(x =Loci, y = value, color = variable, width=.15))
p3<-p3 + geom_bar(position="dodge") + geom_hline(yintercept=0.05)+ opts(legend.position = "none", axis.text.x  = theme_text(angle=90, size=8)) + scale_y_discrete(breaks=seq(0,1)) + ylab(NULL)

p4<-p <- ggplot(split4_datam, aes(x =Loci, y = value, color = variable, width=.15))
p4<-p4 + geom_bar(position="dodge") + geom_hline(yintercept=0.05)+ scale_y_discrete(breaks=seq(0,1))+opts(legend.position="none", axis.text.x  = theme_text(angle=90, size=8)) + ylab(NULL)

p5<-p <- ggplot(split5_datam, aes(x =Loci, y = value, color = variable, width=.15))
p5<-p5 + geom_bar(position="dodge") + geom_hline(yintercept=0.05)+ opts(legend.position = "none", axis.text.x  = theme_text(angle=90, size=8))+ scale_y_discrete(breaks=seq(0,1)) + ylab(NULL)

p6<-p <- ggplot(split6_datam, aes(x =Loci, y = value, color = variable, width=.15))
p6<-p6 + geom_bar(position="dodge") + geom_hline(yintercept=0.05) + scale_y_discrete(breaks=seq(0,1))+ opts(legend.position = "none", axis.text.x  = theme_text(angle=90, size=8)) + ylab(NULL)

p7<-p <- ggplot(split7_datam, aes(x =Loci, y = value, color = variable, width=.15))
p7<-p7 + geom_bar(position="dodge") + geom_hline(yintercept=0.05) + scale_y_discrete(breaks=seq(0,1))+ opts(legend.position = "none", axis.text.x  = theme_text(angle=90, size=8)) + ylab(NULL)

p8<-p <- ggplot(split8_datam, aes(x =Loci, y = value, color = variable, width=.15))
p8<-p8 + geom_bar(position="dodge") + geom_hline(yintercept=0.05) + scale_y_discrete(breaks=seq(0,1))+opts(legend.position="none",axis.text.x  = theme_text(angle=90, size=8)) + ylab(NULL)

#make a bad attempt at creating a legend for the entire multiplot?
leg <- ggplotGrob(p1 + opts(keep="legend_box"))
 ## one needs to provide the legend with a well-defined width
legend=gTree(children=gList(leg), cl="legendGrob")
widthDetails.legendGrob <- function(x) unit(2, "cm")

 #plot the first four plots together
pdf("sensivitity_page_2_plots.pdf")
grid.arrange(p1, p2, p3, p4, nrow=2, legend=legend, main ="Sensitivity", left = "Pvalue")
dev.off()

#same with the next four
pdf("sensivitity_page_2_plots.pdf")

leg <- ggplotGrob(p5 + opts(keep="legend_box"))
 ## one needs to provide the legend with a well-defined width
legend=gTree(children=gList(leg), cl="legendGrob")
widthDetails.legendGrob <- function(x) unit(2, "cm")

grid.arrange(p5, p6, p7, p8, nrow=2, legend=legend, main ="Sensitivity", left = "Pvalue")
dev.off()

The plots will look like this:

I have the following questions:

*

*How can I space the y-axis label so that it's not so close to the edge?

*How can I do the same for the main title

*Why is the legend not appearing? (that portion of the code was lifted from the grid.arrange documentation). And, when it does, how do I space that properly? Anybody else out there use grid.arrange?

*If not, is there another way to apply layout()-like positioning in ggplot?

Thanks so much, everyone!

A: As far as I can tell, your p1 does not have a legend - hence there's no legend to be extracted, and thus no legend to  be drawn in the call to grid.arrange.
Here's a simpler example. It should get you started.
EDIT: Code update for ggplot2 version 0.9.3.1
# Load the required packages
library(ggplot2)
library(gtable)
library(grid)
library(gridExtra)

# Generate some data
df <- data.frame(x = factor(rep(1:5, 2)), Groups = factor(rep(c("Group 1", "Group 2"), 5)))

# Get four plots
p1 <- ggplot(data = df, aes(x=x, y = sample(1:10, 10), fill = Groups)) +
    geom_bar(position = "dodge", stat = "identity") + theme(axis.title.y = element_blank())
p2 <- ggplot(data = df, aes(x=x, y = sample(1:10, 10), fill = Groups)) +
    geom_bar(position = "dodge", stat = "identity") + theme(axis.title.y = element_blank())
p3 <- ggplot(data = df, aes(x=x, y = sample(1:10, 10), fill = Groups)) +
    geom_bar(position = "dodge", stat = "identity") + theme(axis.title.y = element_blank())
p4 <- ggplot(data = df, aes(x=x, y = sample(1:10, 10), fill = Groups)) +
    geom_bar(position = "dodge", stat = "identity") + theme(axis.title.y = element_blank())

# Extracxt the legend from p1
legend = gtable_filter(ggplotGrob(p1), "guide-box")
# grid.draw(legend)    # Make sure the legend has been extracted

# Arrange the elements to be plotted.
# The inner arrangeGrob() function arranges the four plots, the main title,
#   and the global y-axis title.
# The outer grid.arrange() function arranges and draws the arrangeGrob object and the legend.
grid.arrange(arrangeGrob(p1 + theme(legend.position="none"),
                         p2 + theme(legend.position="none"),
                         p3 + theme(legend.position="none"),
                         p4 + theme(legend.position="none"),
                         nrow = 2,
                         top = textGrob("Main Title", vjust = 1, gp = gpar(fontface = "bold", cex = 1.5)),
                         left = textGrob("Global Y-axis Label", rot = 90, vjust = 1)),
    legend,
    widths=unit.c(unit(1, "npc") - legend$width, legend$width),
    nrow=1)

Note how the widths uses the width of the legend. The result is:

The main title and the global y-axis title were positioned using vjust. If you want, say,  the global y-axis title to take more space, then create it as a textGrob, and use widths to set its width. Here, the inner arrangeGrob arranges the four plots and the main title. The outer grid.arrange arranges and draws the global y-axis title, the arrangeGrob object, and the legend. The width of the global y-axis title is set to three lines.
label = textGrob("Global Y-axis Label", rot = 90, vjust = 0.5)
grid.arrange(label,
             arrangeGrob(p1 + theme(legend.position="none"),
                         p2 + theme(legend.position="none"),
                         p3 + theme(legend.position="none"),
                         p4 + theme(legend.position="none"),
                         nrow = 2,
                         top = textGrob("Main Title", vjust = 1, gp = gpar(fontface = "bold", cex = 1.5))),
             legend,
             widths=unit.c(unit(3, "lines"), unit(1, "npc") - unit(3, "lines") - legend$width, legend$width),
             nrow=1)

EDIT
Using your data, and your code for subsetting and reshaping the data, I've drawn the first four plots, extracted the legend from the first plot, then arranged the plots, legend, and label.  The code ran with no problems.
There were some problems with the plots (and also, your code could not have produced the plots shown in your post). I made some minor changes.
# Load the libraries
library(ggplot2)
library(gridExtra)
library(reshape2)

###
# Your code from your post for getting the data, subsetting, and reshaping the data.
###

#and make a plot for each of the melted subsets
p1 <- ggplot(split1_datam, aes(x = Loci, y = value, fill = variable)) +
   geom_bar(position = "dodge", stat = "identity")+ geom_hline(yintercept = 0.05) +
   theme(axis.text.x  = element_text(angle = 90, size = 8)) +
   ylab(NULL)

p2 <- ggplot(split2_datam, aes(x = Loci, y = value, fill = variable)) +
   geom_bar(position = "dodge", stat = "identity")+ geom_hline(yintercept = 0.05) +
   theme(axis.text.x  = element_text(angle = 90, size = 8)) +
   ylab(NULL)

p3 <- ggplot(split3_datam, aes(x = Loci, y = value, fill = variable)) +
   geom_bar(position = "dodge", stat = "identity")+ geom_hline(yintercept = 0.05) +
   theme(axis.text.x  = element_text(angle = 90, size = 8)) +
   ylab(NULL)

p4 <- ggplot(split4_datam, aes(x = Loci, y = value, fill = variable)) +
   geom_bar(position = "dodge", stat = "identity")+ geom_hline(yintercept = 0.05) +
   theme(axis.text.x  = element_text(angle = 90, size = 8)) +
   ylab(NULL)

# Extracxt the legend from p1
legend = gtable_filter(ggplotGrob(p1), "guide-box")
# grid.draw(legend)    # Make sure the legend has been extracted

# Arrange and draw the plot as before
label = textGrob("p value", rot = 90, vjust = 0.5)
grid.arrange(label,
             arrangeGrob(p1 + theme(legend.position="none"),
                         p2 + theme(legend.position="none"),
                         p3 + theme(legend.position="none"),
                         p4 + theme(legend.position="none"),
                         nrow = 2,
                         top = textGrob("Sensitivity", vjust = 1, gp = gpar(fontface = "bold", cex = 1.5))),
             legend,
             widths=unit.c(unit(2, "lines"), unit(1, "npc") - unit(2, "lines") - legend$width, legend$width), nrow=1)


text:
Q: How to display data by the current system date I have tried this, but it's not working:
SELECT day FROM table
 WHERE (SYSDATE - day) *24 < 0.5;

How can I get data in my database with its current date?

A: Assuming that day is a date column, why not do:
select day
from table
where trunc(day) = trunc(sysdate);


text:
Q: How can I bind ViewModel to a Generic View in MAUI? I'm trying to bind a property on an inherited view property that has a generic type.
I get the following error:

Error XFC0009 No property, BindableProperty, or event found for "ViewModel", or mismatching type between value and property.

public abstract class BaseContentView<T> : ContentView where T : BaseVm
{
    public T ViewModel
    {
        get => (T)GetValue(ViewModelProperty);
        set => SetValue(ViewModelProperty, BindingContext = value);
    }
    public BindableProperty ViewModelProperty { get; set; } = BindableProperty.Create(nameof(ViewModel), typeof(T), typeof(BaseContentView<T>));
}

public partial class MyModelView : BaseContentView<MyModelVm>
{ }

public partial class MyModelVm : BaseVm
{
}

public partial class HomeVm : BaseVm
{
    public MyModelVm SelectedMyModel { get; set; }
}

public partial class HomePage : ContentView
{
}

    <ContentPage x:Class="HomePage">
      <v:MyModelView ViewModel="{Binding SelectedMyModel}" />
      <!--           ^ Error here                        /-->
    </ContentPage>

I this case T is MyModelVm so ViewModel property should be assignable to a MyModelVm in a BaseContentView<MyModelVm> from which MyModelView inherits.
Why this error, am I missing something about the property, its returning type or declaring type?


text:
Q: C# Detect the object sent to the generics class and start processing Im sorry for my bad english. There is a problem that I cannot solve because I am new to generics.
When the constructor method is running, How can I detect the incoming class. I have to continue the process by accessing the class properties. Can you help me about the way I should follow?
 public class IslemeBasla<T> where T : class, IEntity
{
        private string _profilName;
        public int _processCount;
        private IWebDriver _driver;
        private ChromeDriverService _cService;
        private string _arguments;

        public T _hEntity;

        public IslemeBasla()
        {
            Type type = typeof(T);

            switch (type.Name)
            {
                // I want to do something like this.
                case "Facebook": _hEntity = (facebook)T;

                    break;
                case "Twitter":
                    break;
                case "Youtube":
                    break;
                case "Instagram":
                    break;
                default:
                    break;
            }
        }
    }

Update ;
All classes have the same characteristics. they inherit from a single class. but some classes have their own characteristics.
The method I have created for this is as follows. It's a not good example, but that's how I came to the solution.
 public class IslemeBasla<T> where T : class, IEntity
{
        private Facebook _fbHesap;
        private Youtube _ytHesap;
        private Instagram _insHesap;
        private Twitter _twHesap;

        public T _hEntity;
        private string _browserLoc;

        public void SetConfigs()
        {
            Type type = typeof(T);

            switch (type.Name)
            {
                _fbHesap = _hEntity as Facebook;
                _browserLoc = _fbHesap.Mail;
                    break;
                case "Twitter":  _twHesap = _hEntity as Twitter;
                _browserLoc = _twHesap.Mail;
                    break;
                case "Youtube": _ytHesap = _hEntity as Youtube;
                    _browserLoc = _ytHesap.Mail;
                    break;
                case "Instagram": _insHesap = _hEntity as Instagram;
                    _browserLoc = _insHesap .Mail;
                    break;
                default:
                    break;
            }
        }
    }

A: This is not the way to use generics. In the example provided you could just as well just use a regular reference, you can then use pattern matching to handle different implementations and use the object however you wish.
Your example does not show what kind of object you have, or how you intend to use them. So I will pretend they are classes to post messages to some sort of social media platform.
public IEntity _hEntity;
public PostMessage()
{
    switch (_hEntity)
    {
         case FaceBook fb:
                fb.PostMessage("hello World"); // Do something with the object
            break;
         case Instagram ig:
                ig.PostMessage("hello World");
         break;
         default:
            throw new NotImplementedException();
    }
 }

However, a better alternative would be to put the logic in the classes themselves and have an appropriate interface method. This will require that each class can accept the same parameters to do whatever it needs to do:
public interface ISocialMedia{
    public void Post(string message);
}
...
public ISocialMedia socialMedia;
public PostMessage()
{
     socialMedia.Post("Hello World");
}

Another option  (as dai mentions in a comment) that might be appropriate is a discriminated union. This can be useful if you want a single value that can be of several different unrelated types. For example you could either have a hammer or a banana.


text:
Q: Shortest duplicate in a list of strings imagine I got a list of strings containing duplicates with different lengths:
liste = ['I am googling for the solution for an hour now',
         'I am googling for the solution for an hour now --Sent via mail--',
         'I am googling for the solution for an hour now --Sent via mail-- What are you doing?',
         'Hello I am good thanks >> How are you?',
         'Hello I am good thanks',
         'Hello I am good thanks >>']

Wanted Output:
liste = ['I am googling for the solution for an hour now', 'Hello I am good thanks']

As you can see the strings are pretty close to duplicates but aren't exact duplicates. So a approach like this doesn't work:
mylist = list(dict.fromkeys(liste))

Have you got any idea how to just keep the shortest duplicate? The duplicates are always consecutive.
EDIT:
The order of the input list shouldn't be disturbed.

A: You can do the following:
mylist = []
for s in sorted(liste):
    if not (mylist and s.startswith(mylist[-1])):
        mylist.append(s)

You can then recover the original order of occurence:
mylist[:] = filter(set(mylist).__contains__, liste)

A: Ok, so despite my suggestion in the comments to use regular expressions, I chose to try something that doesn't. Instead, I made a numpy array that tracks the similarity of strings and uses that to come up with similar strings. It's a bit klunky and the main algorithm in the nested for loop could probably be cleaned up a bit to optimize performance, but it seems to work.
I use a default when comparing an string to itself of 0.9 instead of 1 to make sure things didn't always default to themselves, but I didn't really explore if this is necessary.
import numpy as np

mylist = ['I am googling for the solution for an hour now',
          'I am googling for the solution for an hour now --Sent via mail--',
          'I am googling for the solution for an hour now --Sent via mail-- What are you doing?',
          'Hello I am good thanks >> How are you?',
          'Hello I am good thanks',
          'Hello I am good thanks >>']

N = len(mylist)

overlap = np.ones((N,N))

for i in range(N):
   for j in range(N):
      if i == j: overlap[i,j] = 0.9
      else:
         x = min(len(mylist[i]), len(mylist[j]))
         for k in range(x):
            if mylist[i][k] != mylist[j][k]: break
         overlap[i,j] = (k+1) / len(mylist[i])

newlist = []
for i in range(N):
   j = np.argmax(overlap[:,i])
   print(f"{mylist[i]} --> {mylist[j]}")
   newlist.append(mylist[j])
#I am googling for the solution for an hour now --> I am googling for the solution for an hour now
#I am googling for the solution for an hour now --Sent via mail-- --> I am googling for the solution for an hour now
#I am googling for the solution for an hour now --Sent via mail-- What are you doing? --> I am googling for the solution for an hour now
#Hello I am good thanks >> How are you? --> Hello I am good thanks
#Hello I am good thanks --> Hello I am good thanks
#Hello I am good thanks >> --> Hello I am good thanks

Then your new set is:
print(list(set(newlist)))
#['Hello I am good thanks', 'I am googling for the solution for an hour now']

A: You can sort your list by length, then loop through each element to see if the others (longer strings) start with it.
mySortedList = list(set(liste))
mySortedList.sort(key=len)
i = 0
while i<len(mySortedList)-1 :
    j = i+1
    while j < len(mySortedList):
        if mySortedList[j].startswith(mySortedList[i]):
            mySortedList.pop(j)
        else:
            j+=1
    i+=1

A: I solved this by this sentence: If two strings start with two equal words, they are considered duplicates. You can change this number if you want.
list_ = ['I am googling for the solution for an hour now',
         'I am googling for the solution for an hour now --Sent via mail--',
         'I am googling for the solution for an hour now --Sent via mail-- What are you doing?',
         'Hello I am good thanks >> How are you?',
         'Hello I am good thanks',
         'Hello I am good thanks >>']

all_duplicates = {}

for string in list_:

    # like 'I am' or 'Hello I'
    first_two_words = ' '.join(string.split(maxsplit=2)[:2])

    if first_two_words in all_duplicates:

        v = all_duplicates[first_two_words]

        # check to see if this item of the list is considered duplicate
        if first_two_words in v:
            if len(string) < len(v):
                all_duplicates[first_two_words] = string
    else:
        all_duplicates[first_two_words] = string

for k, v in all_duplicates.items():
    print(f"{k} --> {v}")

output:
I am --> I am googling for the solution for an hour now
Hello I --> Hello I am good thanks

A: Here is a fully working example. By sorting the list by string length, you can only get duplicate of a given string after the string in the list. This way the code runs faster.
My code returns the smallest substrings in the list. So if a string is contains inside another, it will eliminate the second string.
str_list = [
    "I am googling for the solution for an hour now",
    "I am googling for the solution for an hour now --Sent via mail--",
    "I am googling for the solution for an hour now --Sent via mail-- What are you doing?",
    "Hello I am good thanks >> How are you?",
    "Hello I am good thanks",
    "Hello I am good thanks >>",
]

wrong_strings = []
str_list.sort(key=len)

for idx, item1 in enumerate(str_list):
    for item2 in str_list[idx + 1 :]:
        if item1 in item2:
            wrong_strings.append(item2)

base_strings = [string for string in str_list if string not in wrong_strings]

print(f"{base_strings=}")

This also work when a string has no duplicate in the list.

A: I will implement something not really optimized, just to explain.
Looking at the input data, I assume you want not only one shortest sentence, but the set of shortest that are not similar.
Here the proposed implementation
liste = ['I am googling for the solution for an hour now','I am googling for the solution for an hour now --Sent via mail--', 'I am googling for the solution for an hour now --Sent via mail-- What are you doing?', 'Hello I am good thanks >> How are you?','Hello I am good thanks', 'Hello I am good thanks >>']

# First you need some function to get the common part between two sentences
def common_part(sen1, sen2):
    min_length = min( len(sen1), len(sen2) )

    for i in range(min_length):
        if sen1[i] != sen2[i]:
            return sen1[:i]
    # if we exit for loop sentences are equal or
    # one is a substring of the other
    return sen1[:min_length]

# than you can implement some logic checking for common parts

# I create a set to contains elements that has the advantage
# to avoid repetition if you add the same element twice
small_sentences = set()

# than you compare each element with others
# this is not a good algorithm, Big O notation is O(2^n)

for f1 in liste:
    shortest = f1  # store the sentence and compare with all others
    for f2 in liste:
        common = common_part(f1, f2)
        # I define a minimum of 5 chars to be considered "similar"
        # Than if the common part is smaller we take it as good
        if len(common) > 5 and len(shortest) > len(common):
            shortest = common
    small_sentences.add(shortest)

print(small_sentences)


text:
Q: Disable iOS keyboard from displaying I'm doing an iPad app. I'm developing a custom keyboard. However, when I click on the textfield the default keyboard pops up. I want to prevent that disabling the keyboard.
I saw some similar posts here where they put a dummy View on top, or they disable the editing, but that won't do what I want.

A: Using this you can disable normal keyboard
textField.inputView = UIView()

so putting your custom view can make the work
textField.inputView = YourKeyboard()

EDIT 2
Try to put this
youtTextField.inputAssistantItem.leadingBarButtonGroups.removeAll()
yourTextField.inputAssistantItem.trailingBarButtonGroups.removeAll()

A: This might help you solve your problem.
iOS hide default keyboard and open custom keyboard
Essentially you need to hide the default keyboard and then present your custom keyboard.


text:
Q: USB 2.0 ports don't work on Sony VAIO S series laptop I have a Sony VAIO S-series laptop running Ubuntu 14.04 LTS. My USB 3.0 port works but my two USB 2.0 ports do not work.
I've read through this thread but could not find a solution to my problem. All USB ports work just fine in Windows 8 (I have this laptop set up to dual boot Win8 and Ubuntu) but in Ubuntu, the two USB 2.0 ports don't even seem to charge my iPod when I connect it.
What can I do to fix this problem?


text:
Q: Extend nano menu Some hotkeys for nano are listed in the bottom depends on window scaling. How can I switch through this menu to see all the available hotkeys?

A: You can press ctrl+G to see all the nano shortcuts in a new buffer. If you want to come back to editing your file, you just need to press ctrl+X one time.