text:
Q: Filter with range of order reference in list view of sale ordres? i have a list Sales orders from S001 to S120 and i want to filter this list from S010 to S050.
can i search with range Order Reference, i want a list depends on Order Reference range not date because i didn't found operator between in Order reference.
please any help, thanks


text:
Q: Setting a tag for UIAlertController in SWIFT? How to set tag for the alert view in swift. I couldn't set the tag alert.tag = 1, if I did, I get an error like 'UIAlertController' does not have a member named 'tag'. Below is the code that i have written,
var alert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "YES", style: UIAlertActionStyle.Default, handler:{ (ACTION :UIAlertAction!)in }))
alert.addAction(UIAlertAction(title: "NO", style: UIAlertActionStyle.Default, handler:{ (ACTION :UIAlertAction!)in }))

alert.tag = 1 // Error is shown here

self.presentViewController(alert, animated: true, completion: nil)

We used to set tags for alert views in Obj-C. Could someone please help me on this. Thanks in advance.

A: UIAlertController doesn't have a property tag. The hint is in the error "'UIAlertController' does not have a member named 'tag'".
UIAlertController is not a subclass of UIView it is a subclass of UIViewController.
There are almost no reasons for ever using tag though, even when it is available.
What you probably want is to set it into a property instead.

A: I like the answer from @Fogmeister and wanted to add:
The only reason you want to use a tag on an alert view is to identify it so that you can differentiate which one is calling the delegate method (without the overhead of storing each potential in a property and checking all the pointers). This isn't ideal, but it's a quick work around, and as stated previously it's usually a hack of some kind.
The whole delegation approach is replaced in UIAlertController with a block based interface so there should no longer be any need to use the tag. The blocks you supply to the alert actions can reference self with dedicated code and can capture any local variables you need to so there should be no need to do the same thing that you might have been using a tag for previously.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Design Pattern Question to use for Scenario I am writing an application that will post a message to an internal wiki page and an internal message service. I anticipate that I will need to post this message to additional interfaces down the road. Because of this, it seemed like a good opportunity to learn to use design-patterns. I'm a bit new to design patterns.
I've been reviewing them here. My question is, for my scenario, what do you think is the best option? They seem to overlap in some cases. Thank you for your input!

A: If the various "destination" services each have a different API, an Adapter pattern will likely make your life a little easier.  See my response to this stackoverflow question for greater detail.

A: Certainly Observer Pattern is there to rescue you ;)
For an elaborated example
You can do something like this
public void postMessage(Message message) { // you can
    // save message

    // now notify :))
    notifyObservers();
}

A: If you're looking to deal with messages and routing them to services, I would recommend taking a look at the Enterprise Integration Patterns.  They were specifically designed to handle the case where you are taking a message in and needing to transform it and send it elsewhere.


text:
Q: Executed as user: NT Service\SQLSERVERAGENT. Exception calling "Send" with "1" argument(s): "Failure sending mail." I've want to send mail from SQL Server. I have tried with Google account with the below mentioned  Windows PowerShell Codes and it's been working perfectly.
Google account script:
$EmailTo = "xxxxxxx@gmail.com"
$EmailFrom = "xxxxxxx@gmail.com"
$Subject = "Test"
$Body = "Test Body"
$SMTPServer = "smtp.gmail.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("xxxxxxx@gmail.com", "MyPassword");
$SMTPClient.Send($SMTPMessage)

but I have need to change the script to my office email id (microsoft account id), So I've changed the script as I written below and and It's also working perfectly.
Microsoft account script (Outlook):
$EmailTo = "xxxxxxxxx@office.co.in"
$EmailFrom = "xxxxxxxxx@office.co.in"
$Subject = "Test"
$Body = "Test Body"
$SMTPServer = "smtp.office365.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("xxxxxxxxx@office.co.in", "MyPassword");
$SMTPClient.Send($SMTPMessage)

Whenever I tried this code on my machine it's working fine, but I shared the same code to office machine. The Google account code working fine and I received the mails too. But the Microsoft account code is not working properly it gives some errors and not able to receive the mail.
Error:

Executed as user: NT Service\SQLSERVERAGENT. Exception calling "Send" with "1" argument(s): "Failure sending mail."


text:
Q: How to write a python console application with REPL I am currently developing a console application in python.It takes commands from the terminal in the format <my-python-module.py> <command> <other-args>
However i want to drop into REPL and when i write

my-program

It should do like the fololowing
my-program> command 1
my-program> command 2
my-program> exit
good-bye!

How do i do that?

A: The standard library has cmd which gives you "support for line-oriented command interpreters":

The Cmd class provides a simple framework for writing line-oriented command interpreters. These are often useful for test harnesses, administrative tools, and prototypes that will later be wrapped in a more sophisticated interface

There's also prompt-toolkit:

prompt_toolkit is a library for building powerful interactive command lines and terminal applications in Python.


text:
Q: The groups with symmetric subgroups lattice Let $G$ be a group and $\frak L (G)$ be set of all subgroups of $G$. Clearly, $\frak L (G)$ is a lattice.
If we know that $\frak L (G)$ is symmetric then what can be said about the group $G$ ?
Any reference and observation would be appriciated.
Example: Elemantary abelian $p$ groups, the groups that all Sylow subgroups of prime orders are such examples.

A: This is covered in Chapter 8 of Schmidt's book "Subgroup lattices of groups"; everything in this answer is there, but I summarize it here for convenience.
Say a group $G$ has a dual $\hat{G}$ if their subgroup lattices are anti-isomorphic. Your question is about when $G$ is dual to itself.
Baer (1939) proved that every group w/ dual is torsion, i.e. all its elements have finite order.
For locally finite groups (which means every finitely generated subgroup is finite), there is a complete classification of groups with duals. (This is Theorem 8.2.2 in Schmidt, due to Suzuki and Zacher):
If $G$ is a locally finite group, and $\delta$ is a lattice anti-isomorphism to $L(\hat{G})$, then:

*

*$G = \prod_{\lambda} G_{\lambda}$ where the $G_{\lambda}$ are coprime to one another

*$\hat{G} = \prod_{\lambda} \delta(\hat{G}_\lambda)$, where $\hat{G}_\lambda := \langle G_{\mu} : \mu \neq \lambda \rangle$ and the $\delta(\hat{G}_\lambda)$ are coprime to one another

*For every $\lambda$, there exists (not nec. distinct) primes $p,q$ such that one of the following holds:

*

*$G_\lambda$ is a cyclic $p$-group, $\delta(\hat{G}_\lambda)$ is a cyclic $q$-group, or

*$G_\lambda$ and $\delta(\hat{G}_\lambda)$ are both either elementary abelian of order $p^n$ or a semi-direct product of an elementary abelian group of order $p^{n-1}$ by a group of order $q$, or

*$G_\lambda$ and $\delta(\hat{G}_\lambda)$ are finite non-Hamiltonian $p$-groups with modular subgroup lattices

Maybe from these more can be said when $G$ is self-dual ($G = \hat{G}$)...


text:
Q: Firestore security rules not working when using multiple levels of get() calls Been spending a couple hours on this - very frustrating.
I have an app with exactly the following DB - the comms documents are the items that users (who belong to groups which belong to depts) want to access, and comms are accessible only to the depts they list.
/users/user1   { group: /groups/group1 }
/groups/group1 { dept: /depts/dept1 }
/depts/dept1   { }
/comms/comm1   { depts: [/depts/dept1] }

(Can also post screenshots of these DB records if that's helpful for some reason.)
I'm seeing this:

Note how there is no line being highlighted as the cause, making this difficult to debug, but from lots of experimentation/simplifying example data, this seems to be triggered by the two levels of get() indirection:

*

*first we get() the user object to read the group,

*and then get() the user's group to read the dept.

If I simplify the DB to only need one level of indirection by making the comm ACLs in terms of groups rather than depts, then the rules work.
/comms/comm1 { groups: [/groups/group1] }

Even if I could get rid of depts, I still can easily run up against needing multiple levels of indirection - I simply need to inspect a field inside the group object, e.g.:
allow write: if get(user().data.group).data.isActive;

Here is the full rule code:
service cloud.firestore {
  match /databases/{database}/documents {
    function userPath() {
      return /databases/$(database)/documents/users/$(request.auth.uid);
    }
    function user() {
      return get(userPath());
    }
    match /users/{userId} {
      allow read: if true;
      allow write: if userId == request.auth.uid;
    }
    match /comms/{commId} {
      allow read, write: if get(user().data.group).data.dept in resource.data.depts;
    }
    match /{document=**} {
      allow read, write: if false;
    }
  }
}

A: In your example data you specify the user's group as
/users/user1   { group: /groups/group1 }

in your get you would be trying to access /groups/group1, what is missing here is the /databases/$(database)/documents path and most probably that is why your get isn't returning anything.


text:
Q: How do I fetch embeddable document from a value field of a MongoDB and Cosmos DB? How do I fetch embeddable document (small part of a larger JSON stored) from a value field of MongoDB and Cosmos DB?
If I want to store data in MongoDB in a {key,value} way where key is student roll number and value is the complete data structure of Student Object in JSON format.
For Example below is the Value stored in MongoDB for Key RollNumber of Student

{
  "name": "Rahul",
  "class": 12,
  "marks": {
    "maths": 45,
    "bio": 56,
    "chemistry": 76,
    "practicals": {
      "bio": 20,
      "chemistry": 25,
      "phy": 30
    }
  },
  "address": {
    "city": "bangalore",
    "per": {
      "adminUserId": 25,
      "name": "Rahul Gupta",
      "admin": false,
      "active": true,
      "email": "Rahul.Gupta@mail.com"
    }
  }
}

From above value, I want to fetch only "Marks" or "practicals" JSON from the full document to avoid network load of transferring full document from MongoDB to Client.

A: db.yourcollection.find({name:"Rahul"},{marks:1})

should do. As you see in MongoDB , you can specify criteria as well as fields that you want to retrieve.
For more options check here

A: you can write below query
db.student.aggregate([
{ $match : {'name': "Rahul" }},
{ $project :{"marks":1} }
])


text:
Q: Right click menu then item pointing to a class I want to be able to right click on an image and for there to be a menu show up. When I then click on one of the items I want it to point to a class:
    private void link1add_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
        ContextMenu cm = new ContextMenu();
        cm.MenuItems.Add("Add", HandleContextMenuAdd);
        cm.MenuItems.Add("Remove", HandleContextMenuRemove);
        link1add.ContextMenu = cm;
        }
    }
        private void HandleContextMenuAdd(object sender, EventArgs e)
        {
            MessageBox.Show("Adding");
        }
        private void HandleContextMenuRemove(object sender, EventArgs e)
        {
            MessageBox.Show("Removing");
        }

Code edited since first posted.
Thanks all for your help.

A: What about a lambda expression?
cm.MenuItems.Add("Item 2", (_, __) => {
  if (...) ReadDocument();
});

or
cm.MenuItems.Add("Item 2", (_, __) => { this.myClassInstance.DoSomething(); });

Alternatively, you can create a method with the signature of the expected event handler:
cm.MenuItems.Add("Item 2", HandleContextMenuClick);

private void HandleContextMenuClick(object sender, EventArgs e)
{
  if (...) ReadDocument();
}

That method doesn't need to be in the same class (you can write this.myClassInstance.HandleContextMenuclick for example). But I would hide the implementation detail from other classes to avoid unnecessary coupling.

A: Pattern for your own code after this:
    public class ReadDocumentEventArgs : EventArgs
    {
        public string ImageInfo { get; set; }
    }

    public void ReadDocument(object sender, ReadDocumentEventArgs ea)
    {
        // do whatever you need to do
        MessageBox.Show(ea.ImageInfo);  // example
    }

    private void link1add_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            PictureBox imageCtrl = sender as PictureBox;

            // get the information you need to get from your control to identify it
            string imgInfo = "Hello, World!"; // example

            ContextMenu cm = new ContextMenu();
            cm.MenuItems.Add("Item 1");
            cm.MenuItems.Add("Item 2",
               (EventHandler)((s, rde) =>
               { ReadDocument(s, new ReadDocumentEventArgs()
                  { ImageInfo = imgInfo });
               }));

            link1add.ContextMenu = cm;
        }
    }

In your MouseDown over your image you can create a menu item using the code I supplied above that will call an event handler called ReadDocument. Notice that there is a ReadDocumentEventArgs class that you can customize to contain the necessary properties that will help you identify which image you have clicked on.
So, in the example I have above one of the first things that happens in MouseDown is that you get the instance of image control (I assume it's a Picture Box, but you can cast it to whatever it really is).
At that point, you can then get a file name or whatever from your image that identifies it from the other controls on your form.
Next, when creating a context menu item, it tells the menu item to call ReadDocument but passes in the special data just taken from the image control.
In the ReadDocument method, you can then do whatever you need to do. In my example, I simply throw up a MessageBox to show you what data you passed in.

A: What you will want is to put another event handler and call your readdocument method.


text:
Q: Add AWS EC2 instance to existing Availability Group I currently have an AG with 2 replicas both running SQL Server 2016. These are both located on premise. I was looking to add a third node using a AWS EC2 instance and asynchronous replication.
Networking issues aside, is this an acceptable approach?
The only resources I can find on the internet appear to use distributed AGs but that would mean having a second EC2 instance in AWS

A: I assume it would be like this hybrid it: disaster recovery scenario but with AWS instead of Azure. There is an interesting point in the article about having your Active Directory available in the cloud.
I think you'd have to give some thought to how quorum would work. For example, what would happen if you did a manual failover to the cloud instance, then later your on-premises instances came back online?
HTH


text:
Q: IsapiRewrite rules generate strange pages/folders? i'm using IsapiRewrite from helicontech for my custom classic ASP shopping cart.
My actual httpd.ini file is:
[ISAPI_Rewrite]
RewriteBase /
RewriteCond %HTTPS off
RewriteCond Host: (?!^www.domain.com)(.+)
RewriteRule /(.*) http\://www.domain.com/$2 [I,RP]
RewriteRule /httpd(?:\.ini|\.parse\.errors).* / [I,O]
RewriteRule /(.+)-([^-]*)-([^-]*)-([^-]*)\.html$ /detail.asp?brand=$1&model=$2&id=$3&lg=$4 [L]

So i'm actually using this component only to rewrite the product detail page in a nice way.
Lately looking in google cache i find some folders with files inside cached by googleBot that doesn't exist on my server eg: domain.com/carrera-CHAMPION ... and so on.
The page drawn if i access these strange pages is the detail.asp page but without css and some js loaded.
I tested recently the site with Acunetix scanner and seems like he found too these strange folders.
First i added a javascript check to se if Jquery not loaded then that means the page is one of these so i throw an alert and redirect user to homepage ..
Do you know what could be ? or how i could solve this via a rule in httpd.ini?
Hope i make myself clear if no feel free to ask me details,
thank you

A: Can you confirm that when you disable ISAPI_Rewrite these strange pages/folders disappear?
Please note that ISAPI_Rewrite only rewrites response headers and can't generate anything, so it's highly unlikely to be the cause of the issue.
BTW, your config is the mixture of ISAPI_Rewrite 2 and 3 syntax. If it's v2, please fix it like this:
[ISAPI_Rewrite]
RewriteCond %HTTPS off
RewriteCond Host: (?!www.domain.com).+
RewriteRule /(.*) http\://www.domain.com/$1 [I,RP]
RewriteRule /httpd(?:\.ini|\.parse\.errors).* / [I,O]
RewriteRule /(.+)-([^-]*)-([^-]*)-([^-]*)\.html$ /detail.asp\?brand=$1&model=$2&id=$3&lg=$4 [L]


text:
Q: Diagonalizable matrices Question is to prove that the set of all diagonalizable matrices are dense in $M_n(\mathbb{C})$.
I am sure this question is discussed in this site previously but i am looking for a more constructive proof..
The very first example of an element in $M_2(\mathbb{C})$ that is not diagonalizable is $A=\begin{bmatrix}1&1\\0&1\end{bmatrix}$..
Now, I want a sequence of matrices $A_n$ converging to $A$ such that all $A_n$ are diagonalizable...
I see matrix convergence as convergence of each element...
So, atleast we need a sequence converging to $0$.. The very first sequence that we come across is $\frac{1}{n}$
So, i was considering $A_n=\begin{bmatrix}1&1\\\frac{1}{n}&1\end{bmatrix}$ converging to $A$..
Incidentally all these $A_n$ are diagonalizable with eigenvalues $\frac{n-\sqrt{n}}{n}$ and $\frac{n+\sqrt{n}}{n}$..
$A_n$ for me was just a random choice..
I just want to know if some thing like this works in case of $n\times n$  matrices..

A: The denseness follows easily from two properties: eigenvalues depend continuously on the entries of a matrix and matrices with distinct eigenvalues are diagonalizable.
A nondiagonalizable matrix $A$ is conjugate to a Jordan canonical form $J=S^{-1}AS$. Simply change slightly the entries of the main diagonal of $J$ to obtain a matrix $J'$ and consider $SJ'S^{-1}$. You have just obtained a diagonalizable matrix that can be made arbitrarily close to $A$.


text:
Q: Achieve some TradingView Chart like functions with amStockCharts v3 I am using amStockCharts for my website and want to add some tradingView chart-like functionality in my charts for users. I know that Trading view Chart is a full featured chart and not all the functionality can be met with amStockCharts, but I am ready write code myself to do this.
Basically, below are the 3 main things I wish to achieve as shown in the image described with red text and yellow background:

My question is whether this is achievable with amStockCharts? If yes, please guide me in the right direction.


text:
Q: Why am I getting System.Security.AccessControl.PrivilegeNotHeldException in my WPF application? I have a simple WPF application which is trying to find the ActiveDirectory groups a given user is a member of. The code for retrieving the groups is:
public static HashSet<string> GetUserGroups(string userLogon)
{
    var groups = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
    var identity = new WindowsIdentity(userLogon);

    if (identity.Groups == null) { return groups; }

    var type = typeof(NTAccount);

    foreach (var group in identity.Groups)
    {
        groups.Add(group.Translate(type).ToString());
    }

    return groups;
}

However when I try running this at the startup of the app, I get the following exception thrown when the method tries to create the new WindowsIdentity(userLogon):

System.Security.AccessControl.PrivilegeNotHeldException: 'The process
  does not possess the 'SeTcbPrivilege' privilege which is required for
  this operation.'

Not this does not happen if I run the code in a Console app. Any ideas on what could be causing this?

A: It turned out I was only seeing this exception due to enabling All Common Language Exceptions in Common Language Exception dialog.
This exception appears to be thrown internally.


text:
Q: Proving Riordan's identity that $\sum_{k=1}^{n} {n-1 \choose k-1} \frac{k!}{n^k}=1$ In a book titled  "Advances in Problem Solving," authored by Sailesh Shirali, Riordan's identity is mentioned which can also be written as
$$S=\sum_{k=1}^{n} {n-1 \choose k-1} \frac{k!}{n^k}=1~~~~(1)$$
Here, we prove it by the integral representation of $(j+1)!$ as:
$$S=\sum_{j=0}^{n-1} {n-1 \choose j} \frac{(j+1)!}{n^{j+1}}=\sum_{j=0}^{n-1} {n-1 \choose j} \frac{1}{n^{j+1}} \int_{0}^{\infty} x^{j+1} e^{-x} dx$$
$$\implies S=\frac{1}{n^{n}}\int_{0}^{\infty} x ~(n+x)^{n-1} e^{-x} dx=n^{-n}\int_{0}^{\infty} [(x+n)^n-n(x+n)^{n-1}]~ e^{-x} dx$$ $$S=-n^{-n}\left. (x+n)^n~ e^{-x}\right|_{0}^{\infty}=1.$$
It will be interesting to see other approaches for proving (1).

A: We seek to show that
$$S= \sum_{k=0}^{n-1} {n-1\choose k} \frac{(k+1)!}{n^{k+1}} = 1.$$
The sum is
$$\frac{(n-1)!}{n}
\sum_{k=0}^{n-1} \frac{k+1}{(n-1-k)!} \frac{1}{n^k}.$$
We get without the factor  in front
$$\sum_{k=0}^{n-1} \frac{-n+k+1}{(n-1-k)!} \frac{1}{n^k}
+ \sum_{k=0}^{n-1} \frac{n}{(n-1-k)!} \frac{1}{n^k}
\\ = - \sum_{k=0}^{n-2} \frac{n-1-k}{(n-1-k)!} \frac{1}{n^k}
+ \sum_{k=0}^{n-1} \frac{1}{(n-1-k)!} \frac{1}{n^{k-1}}
\\ = - \sum_{k=0}^{n-2} \frac{1}{(n-2-k)!} \frac{1}{n^k}
+ \sum_{k=0}^{n-1} \frac{1}{(n-1-k)!} \frac{1}{n^{k-1}}
\\ = - \sum_{k=1}^{n-1} \frac{1}{(n-1-k)!} \frac{1}{n^{k-1}}
+ \sum_{k=0}^{n-1} \frac{1}{(n-1-k)!} \frac{1}{n^{k-1}}
\\ = \frac{1}{(n-1)!} \frac{1}{n^{-1}}.$$
Restoring the factor in front we find
$$\frac{(n-1)!}{n} \times
\frac{1}{(n-1)!} \frac{1}{n^{-1}} = 1$$
as claimed.

A: We shall count the number of length $n+1$ sequences $(x_1,\ldots,x_{n+1})$ over a set of $n$ elements in two different ways.
The first is to just independently choose each $x_i$, yielding $n^{n+1}$ sequences.
Alternatively, let $x_{k+1}$ be the first repeated element in the sequence (a repetition must occur because the length of the sequence is greater than $n$). The first $k$ elements of the sequence can be chosen in $k!\binom{n}{k}$ ways (they must all be distinct), and $x_{k+1}$ can be chosen in exactly $k$ ways (choosing which of the first $k$ elements is repeated). The elements at the remaining $n-k$ positions can then be chosen in $n^{n-k}$ ways (there is no restriction on them). Multiplying these together and summing over $k$, we get
$$n^{n+1}=\sum_{k=0}^nk!\binom{n}{k}\cdot k\cdot n^{n-k}$$
$$1 = \sum_{k=0}^n \frac{k}{n}\binom{n}{k}\cdot\frac{k!}{n^k}$$
$$1=\sum_{k=1}^n\binom{n-1}{k-1}\frac{k!}{n^k}$$
which is exactly what we want.


text:
Q: android - show horizontal scrollview when textview is clicked i'm new to android. I'm developing an app. I have a textView as the header and a horizontal_scroll_view with the content. Now, when I press the textView I need the horizontal_scroll_view to popup down the header.
XML layout-
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="20dp"
                android:paddingStart="20dp"
                android:onClick="DailyUseItems"
                android:clickable="true"
                android:text="Daily Use Products"
                android:textColor="#FFFFFF"
                android:textSize="24sp" />

        <HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#EEEEEE"
            android:id="@+id/daily_use_items"
            android:scrollbars="none">
        </HorizontalScrollView>

A: If you wish to show it as popup you could make custom dialog https://developer.android.com/guide/topics/ui/dialogs.html But If you would like to make HorizontalScrollView invisible and make it visible on header click you can set in xml android:visibility="invisible" or android:visibility="gone" and then in java click listener horizontalScrollView.setVisibility(View.VISIBLE); To make it popup/slide down the header you would need to use android animation. Here is how I would do it, based on this code https://gist.github.com/rafali/5146957:
MainActivity.class
public class MainActivity extends AppCompatActivity {

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

    final HorizontalScrollView hsc = (HorizontalScrollView) findViewById(R.id.daily_use_items);
    TextView tv = (TextView) findViewById(R.id.header);

    hsc.setAlpha(0.0f);

    tv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            hsc.animate().alpha(1.0f);
            ResizeAnimation resizeAnimation = new ResizeAnimation(hsc,hsc.getHeight());
            resizeAnimation.setDuration(600);
            hsc.startAnimation(resizeAnimation);
        }
    });
}
}

ResizeAnimation.class
public class ResizeAnimation extends Animation {
final int startHeight;
final int targetHeight;
View view;

public ResizeAnimation(View view, int targetHeight) {
    this.view = view;
    this.targetHeight = targetHeight;
    startHeight = 0;
}

@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
    int newHeight = (int) (startHeight + (targetHeight - startHeight) * interpolatedTime);
    view.getLayoutParams().height = newHeight;
    view.requestLayout();

}

@Override
public void initialize(int width, int height, int parentWidth, int parentHeight) {
    super.initialize(width, height, parentWidth, parentHeight);
}

@Override
public boolean willChangeBounds() {
    return true;
}
}


text:
Q: SQL - Transpose query data with additional rows added in I have come once more to seek your guidance.
I am not actually sure how possible this is, but I can only hope.
I have an already heavily joined and aggregated query which pulls out results as shown in the attached picture.

As mentioned, this is an already heavily editing query with multiple joins and aggregates to take half hour data and sum it hourly.
I am wondering if it is at all possible to now transpose the data so that there are 24 seperate hourly entries for each date?
So instead of having one single line for 2014-01-01 with each hourly reading in a seperate column, is it at all possible to change it so there are just two columns. One for date/time and one with the hourly total.
So it would look more like:

and then continue down for each hour of each day.
I am using SQL Server 2014 if that helps.
Thank you in advance!

A: Assuming your time columns are named time0, time1, ..., time23 you could write
SELECT DateAdd(HOUR, 0, date) as DateTime, time0 as total from table
UNION
SELECT DateAdd(HOUR, 1, date) as DateTime, time1 as total from table
UNION
...
SELECT DateAdd(HOUR, 23, date) as DateTime, time23 as total from table


text:
Q: SQL 2000 TSQL - Creating Pivot Table I am really struggling with figuring out how to convert a MS Access CrossTab query into T-SQL to run on SQL2000 or into Linq-to-SQL.  What I have is a query that looks like this in Access:

And produces this:

The query basically groups by ItemID and StoreID and Sums the Qty sold, but with the CrossTab query in Access, I am able to have a unique ItemID for each row, a column for each StoreID, and the total Qty for each StoreID/ItemID combination as the value.
How do you construct this in T-SQL 2000?  I can build a simple select query with grouping, but it gives me the data in three columns, StoreID, ItemID, and Qty.  But what I need is a column for ItemID and a column for every StoreID in the result set
SELECT     Trans.TranSID as StoreID, TransDetail.TranItemID as ItemID, SUM(TransDetail.Qty) AS TotalQtyForStore
    FROM         Trans INNER JOIN
                          TransDetail ON Trans.TranID = TransDetail.TranID INNER JOIN
                          Item ON TransDetail.TranItemID = Item.ItemID
    WHERE     (Trans.TranDate > CONVERT(DATETIME, '2005-01-01 00:00:00', 102)) AND (Trans.TranTypeID = 'so' OR
                          Trans.TranTypeID = 'ca') AND (Trans.TranStatus <> 'v') AND (Item.ItemClassID = 'RHM')
    GROUP BY Trans.TranSID, TransDetail.TranItemID

Which produces this:

But what I really need to do is transform this data so that the StoreID values become columns, like the Access CrossTab query above.

A: I would do this with dynamic SQL, since you probably don't know all of the store (TranSID) values in advance. This stored procedure takes start/end date as parameters, and generates a cross-tab. You can probably parameterize some of the other things as well, such as TranStatus and ItemClassID, but it wasn't clear if those are fixed or variable elements in your query.
CREATE PROCEDURE dbo.CrossTabByItem
  @StartDate DATETIME,
  @EndDate   DATETIME = NULL
AS
BEGIN
  SET NOCOUNT ON;

  SET @EndDate = COALESCE(DATEADD(DAY, 1, @EndDate), GETDATE());

  DECLARE @sql NVARCHAR(4000); SET @sql = N'';

  SELECT @sql = @sql + ',
    [' + TranSID + '] = SUM(CASE WHEN t.TranSID = '''
    + TranSID + ''' THEN td.Qty ELSE 0 END)' FROM
    (
      SELECT DISTINCT TranSID FROM dbo.Trans
      WHERE TranDate >= @StartDate AND TranDate < @EndDate
    ) AS x ORDER BY TranSID;

    SET @sql = N'SELECT ItemID = td.TranItemID' + @sql + '
      FROM dbo.Trans AS t
      INNER JOIN dbo.TransDetail AS td
       ON t.TranID = td.TranID
      INNER JOIN dbo.Item AS i
       ON td.TranItemID = i.ItemID
      WHERE t.TranDate >= @StartDate
      AND t.TranDate < @EndDate
      AND t.TranTypeID IN (''so'',''ca'')
      AND t.TranStatus <> ''v''
      AND i.ItemClassID = ''RHM''
      GROUP BY td.TranItemID;';

    EXEC sp_executesql @sql,
      N'@StartDate DATETIME, @EndDate DATETIME',
      @StartDate, @EndDate;
END
GO

So you can call it like this, to get everything from January 1st, 2005 until right now:
EXEC dbo.CrossTabByItem @StartDate = '20050101';

Or like this, to get just January of 2005:
EXEC dbo.CrossTabByItem @StartDate = '20050101', @EndDate = '20050131';


text:
Q: How to solve this differential equation? $y=\left(y'\right)^2+4\left(y'\right)^3$ So, hey.
I've tried to substitute $y'=p$ and solve it somehow, but it didn't result in any acceptable equation.
Any help?

A: $y'=p\Rightarrow y=p^2+4p^3\Rightarrow p=y'=(2p+12p^2)p'\Rightarrow p=0$ or $p'=\frac{1}{2+12p}\Rightarrow p=0$ or $2p+6p^2=x+C\Rightarrow p=0$ or $p=\pm\sqrt{\frac{1}{6}x+C}-\frac{1}{6}\Rightarrow y=C$ or $y=\pm\frac{\sqrt{6}}{9}(x+C)^{\frac{3}{2}}-\frac{1}{6}x+C_1$.


text:
Q: adapt username availibility check code I need your help to adapt a code that displays if a username is already taken.
This code is working :

$(document).ready(function()
{
  $("#name").keyup(function()
  {
     var name = $(this).val();

   $.post( "username-check.php", { name: $("#name").val() }, function (data){
          if(data=='1'){
          //the php post result is equal to '1' if the username is already taken.
   // This actualy display "1" in the form if the username is taken.
   $("#result").html(data);
       }
    }); //function(data)
  });
})

I got this code from a website, to check and validate the inputs of my form

$('document').ready(function()
{
   // Check and validate the username input
   var nameregex = /^[a-zA-Z0-9 ]+$/;

   $.validator.addMethod("validname", function( value, element ) {
   return this.optional( element ) || nameregex.test( value );
   });

 /* To check if the username is taken I think I have to add something like that :
    var checkusernameregex = ??????;

   $.validator.addMethod("checkusername", function( value, element ) {
   return this.optional( element ) || checkusernameregex.test( value );
   }); */

   $("#register-form").validate({

    rules:
    {
     name: {
     required: true,
     validname: true,
   //chekusername : true,
     minlength: 5,
     maxlength: 25
     }
    },
    messages:
    {
     name: {
     required: "Please choose a username",
     validname: "Username can only have alphanumerical characters ",
     //checkusername: "Username already taken";
     minlength: "Username is too short"
      }
    },
 });

//to display errors code, but not needed for my actual request
Thank you


text:
Q: "A majority of those whose family" or "families" Is "family" both plural and singular? or would I have to say families for the plural form? For example, which of these is the best option:

*

*"A majority of those whose family were unaware of their sexuality..."

*"A majority of those whose families were unaware of their sexuality..."

*"A majority of those whose family was unaware of their sexuality..."

Edit: Here are some full sentences to give some context.

Participants whose famil(ies) were aware of their sexuality were predominantly feminine and identified as gay, homosexual, drag queen, or a combination of these identities. All those who assumed their famil(ies) knew about their sexuality were gay identified and a majority identified as feminine. A majority of those whose famil(ies) were unaware were masculine and identified as non-gay, straight, down low or did not identify with any label.

A: Now that you've provided the complete context, I think it is safe to say two things.

*

*Whichever variant works best for the last sentence in isolation — and it is easy to imagine that all three do, depending on dialect and register —, since the construction is repeated in the other two sentences, you'd be well-advised to pick one variant that fits them all, and stick to it throughout. If nothing else, it's at least good style.

*The variant that works best in the first sentence is "Participants whose families were". Why? I have no why, other than It Just Sounds Right™. But when hard-pressed, I might paraphrase this answer to a closely related question: "Plural, because we are, in fact, dealing with several families. A participant has a family, but participants have families."

So the whole text would read:

Participants whose families were aware of their sexuality were predominantly feminine and identified as gay, homosexual, drag queen, or a combination of these identities. All those who assumed their families knew about their sexuality were gay identified and a majority identified as feminine. A majority of those whose families were unaware were masculine and identified as non-gay, straight, down low or did not identify with any label.

I for one find that unexceptionable English. As a bonus, you also sidestep the whole issue of family being singular in American English, but plural in British English. That is, what you get works in both.
And, to quote that other answer once again, "I'm sure others will back me on this".


text:
Q: WIX Generate multilingual installer I'm new to WIX and i'm using Wix 3.8 VS 2012. I managed to Generate .msi to .exe using this amazing tool.
From this tutorial : http://max.zamorsky.name/node/78, I managed to change the installer to French. I would like to make a multilingual installer which the installer could detect the system language & proceed to install.
I tried to understand this link:http://windows-installer-xml-wix-toolset.687559.n2.nabble.com/Localized-bundle-Picking-up-the-right-files-td7265208.html but i couldn't understand.
Please guide me that how can i make this type of installer? Need your help & thank you.
Bundle.WXS
<?xml version="1.0" encoding="UTF-8"?>
<?define SourceDirImages = "C:\Users\krangaraj\Documents\Visual Studio 2012\Projects\PrintUtility\SetupProjectInstaller" ?>
<?define SourceDoc = "C:\Users\krangaraj\Documents\Visual Studio 2012\Projects\PrintUtility\PrintUtilityExe" ?>

<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
         xmlns:bal="http://schemas.microsoft.com/wix/BalExtension">
    <Bundle Name="PrintUtility" Version="1.5" Manufacturer="DNP PIE SAS" IconSourceFile="PartyPrintInstaller.ico"
          UpgradeCode="7ba74925-c154-4939-9c2e-a531eac0cd8a" >
    <BootstrapperApplicationRef Id="WixStandardBootstrapperApplication.RtfLicense" >
      <bal:WixStandardBootstrapperApplication SuppressOptionsUI="yes" SuppressRepair="yes"
        LicenseFile="$(var.SourceDoc)\sample.rtf" ThemeFile="HyperlinkTheme.xml"
        LocalizationFile="HyperlinkTheme.wxl"
        ShowVersion="yes"
        LogoFile="$(var.SourceDoc)\logo.jpg" LogoSideFile="$(var.SourceDoc)\SideLogo.jpg"/>

      <!--For the French language -->
        <Payload Compressed="yes"  Name="1036\thm.wxl" SourceFile="1036\thm.wxl"/>

      <!-- I would like to add German,Greek,English,Es,It,Jp,Ru,Turkish make a common installer

      <Payload Compressed="yes"  Name="1031\thm.wxl" SourceFile="1031\thm.wxl"/>
      <Payload Compressed="yes"  Name="1032\thm.wxl" SourceFile="1032\thm.wxl"/>
      <Payload Compressed="yes"  Name="1033\thm.wxl" SourceFile="1033\thm.wxl"/>
      <Payload Compressed="yes"  Name="1034\thm.wxl" SourceFile="1034\thm.wxl"/>
      <Payload Compressed="yes"  Name="1040\thm.wxl" SourceFile="1040\thm.wxl"/>
      <Payload Compressed="yes"  Name="1041\thm.wxl" SourceFile="1041\thm.wxl"/>

      <Payload Compressed="yes"  Name="1049\thm.wxl" SourceFile="1049\thm.wxl"/>
      <Payload Compressed="yes"  Name="1055\thm.wxl" SourceFile="1055\thm.wxl"/>-->

    </BootstrapperApplicationRef>
    <Chain>
      <!-- TODO: Define the list of chained packages. -->
      <MsiPackage  SourceFile="$(var.SourceDirImages)\Product.msi"/>
    </Chain>

  </Bundle>
</Wix>

A: Assuming that you don't plan to use a bootstrapper that chooses the language and then starts the MSI with the appropriate language transform, you can use the method described on the following site: http://www.installsite.org/pages/en/msi/articles/embeddedlang/
Please note that the method is unsupported by Microsoft, but I had no negative experience with it. Also note that not the UI language of Windows is used to detect the language, but the Standards and format options of Windows.
It basically consists of the following steps:

*

*Create your base MSI file with the base / fallback language, most of the times it will be English.

*Create your language transform files, one for each language. If the UI will not change and you change only UI items, you can reuse these transform files for further builds.

*Add the language transforms as streams, using a VBScript-script from the Windows SDK.

*Update the language entry of the summary information stream to reflect the included languages.

During installation, the initial dialog will pop-up which checks for the configured language, then the UI is shown in the correct language.
As said: this method worked great for me for an installer and > 20 languages.


text:
Q: Can I convert a html page to pdf with htmltodoc and LiveDocx without creating a .doc on server? I am trying to use the class htmltodoc in order to create a .pdf from an html page with :
http://www.phpkode.com/source/s/html-to-doc-classes/html-to-doc-classes/html_to_doc.inc.php
And with the library LiveDocx (with Zend) :
http://srhwd.com/documentation/moodle/_mail_merge_8php_source.html
without creating a .doc . Here is my code :
$htmltodoc= new HTML_TO_DOC();

$htmltodoc->createDocFromURL("http://www.youtube.com/","google.doc",false);

$mailMerge = new Zend_Service_LiveDocx_MailMerge(
    array (
        'username' => 'xxxxxxx',
        'password' => 'xxxxxxx'
    )
);

$mailMerge->setLocalTemplate($htmltodoc);

//$mailMerge->setLocalTemplate('template.doc'); Normally, template.doc is registered on server

$mailMerge->createDocument();

$document = $mailMerge->retrieveDocument('pdf');

header('Content-disposition: attachment; filename=document.pdf');

header('Content-type: application/pdf');

echo $document;

But it returns:

Error HTTP 500 (Internal Server Error)

Can someone help me please ?

A: If you want to convert HTML to PDF you could use a PDF lib such as :

*

*dompdf

*tcpdf (see example 6)


text:
Q: If/else condition in Cypress not working as expected I have this code
Cypress.Commands.add('VerifyLoginState', () => {
    if(cy.contains('Login')) {
        cy.get('.form-control').eq(0).type('firstfield')
        cy.get('.form-control').eq(1).type('secondfield')
        cy.get('.btn-login').click()
        cy.wait(2500)
        cy.contains('Upcoming Appointments').should('be.visible')
    }
    else
    {
        cy.contains('Appointment summary').should('be.visible')
    }
})

How should I write the code so that it can pass to the condition of else, when I am authenticated in the browser and the condition of if is not valid?
In other words, I want to check if an element is present on the page, and even if it is not present, the code should not give an error and move on

A: Cypress yields the result of cy functions, and does not return them. So your if/else will not work as it would in traditional JavaScript. Check out this article from Cypress about conditional testing.
Something like the following should help you out:
// Get the body of the DOM
cy.get('body').then(($body) => {
  // Check if the body contains the `Login` element
  if ($body.contains('Login').length) {
        cy.get('.form-control').eq(0).type('firstfield')
        cy.get('.form-control').eq(1).type('secondfield')
        cy.get('.btn-login').click()
        cy.wait(2500)
        cy.contains('Upcoming Appointments').should('be.visible')
    } else {
        cy.contains('Appointment summary').should('be.visible')
    }

A: Another option is to use within
ref: https://docs.cypress.io/api/commands/within#Syntax
cy.contains('Login')
    .within(() => {
        cy.get('.form-control').eq(0).type('firstfield')
        cy.get('.form-control').eq(1).type('secondfield')
        cy.get('.btn-login').click()
        cy.wait(2500)
        cy.contains('Upcoming Appointments').should('be.visible')
      })

A: You may find it easier to test for either/or text using jQuery :contains and multiple selectors separated by a comma
cy.get('body')
  .children(':contains(Login), :contains(Appointment summary)')  // only one is on the page
  .invoke('text')
  .then(labelText => {
    if (labelText.trim() === 'Login') {
      cy.get('.form-control').eq(0).type('firstfield')
      ... etc
    } else {
      cy.contains('Appointment summary').should('be.visible')
    }
  })


text:
Q: BFS Traversal In MSSQL I have been trying to write queries so that I can get the BFS & DFS traversal of the tree. I am getting the DFS preorder traversal right but unfortunately, I am not able to get the BFS part right.
CREATE TABLE GenericTree (
    NodeID INT NOT NULL,
    ParentNodeID INT NULL,
    CONSTRAINT PK_GenericTree PRIMARY KEY (NodeID),
    CONSTRAINT FK_GenericTree_Parent FOREIGN KEY (ParentNodeID) REFERENCES GenericTree (NodeID)
);
GO

INSERT INTO GenericTree (NodeID, ParentNodeID) VALUES (1, NULL);
INSERT INTO GenericTree (NodeID, ParentNodeID) VALUES (2, 1);
INSERT INTO GenericTree (NodeID, ParentNodeID) VALUES (3, 1);
INSERT INTO GenericTree (NodeID, ParentNodeID) VALUES (4, 1);
INSERT INTO GenericTree (NodeID, ParentNodeID) VALUES (5, 2);
INSERT INTO GenericTree (NodeID, ParentNodeID) VALUES (6, 2);
INSERT INTO GenericTree (NodeID, ParentNodeID) VALUES (7, 3);
INSERT INTO GenericTree (NodeID, ParentNodeID) VALUES (8, 3);
INSERT INTO GenericTree (NodeID, ParentNodeID) VALUES (9, 3);
INSERT INTO GenericTree (NodeID, ParentNodeID) VALUES (10, 6);
INSERT INTO GenericTree (NodeID, ParentNodeID) VALUES (11, 6);
INSERT INTO GenericTree (NodeID, ParentNodeID) VALUES (12, 6);
INSERT INTO GenericTree (NodeID, ParentNodeID) VALUES (13, 6);
INSERT INTO GenericTree (NodeID, ParentNodeID) VALUES (14, 7);
INSERT INTO GenericTree (NodeID, ParentNodeID) VALUES (15, 8);
INSERT INTO GenericTree (NodeID, ParentNodeID) VALUES (16, 8);
INSERT INTO GenericTree (NodeID, ParentNodeID) VALUES (17, 11);
INSERT INTO GenericTree (NodeID, ParentNodeID) VALUES (18, 11);
INSERT INTO GenericTree (NodeID, ParentNodeID) VALUES (19, 16);
INSERT INTO GenericTree (NodeID, ParentNodeID) VALUES (20, 16);
GO

CREATE PROCEDURE usp_DFS_PreOrder
@NodeID INT = NULL
AS
BEGIN
    SET NOCOUNT ON;
    /*
        EXECUTE usp_DFS_PreOrder;
    */

    DECLARE @v_NodeID INT;
    DECLARE c_CUR CURSOR FAST_FORWARD LOCAL FOR
        SELECT NodeID
            FROM GenericTree
        WHERE ISNULL(ParentNodeID, 0) = ISNULL(@NodeID, 0)
        ORDER BY NodeID;
    OPEN c_CUR;
    FETCH FROM c_CUR INTO @v_NodeID;
    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT @v_NodeID;
        EXECUTE usp_DFS_PreOrder @v_NodeID;
        FETCH FROM c_CUR INTO @v_NodeID;
    END;
    CLOSE c_CUR;
    DEALLOCATE c_CUR;
END;
GO

This is my DFS part of the query. I kept everything same except the DFS preorder part of the query. I changed the DFS_Preorder part but I am not getting the correct result for the BFS part. Here is my query for the BFS:-
CREATE PROCEDURE BFS
@NodeID INT = NULL
AS
BEGIN
    SET NOCOUNT ON;
    /*
        EXECUTE BFS;
    */

    DECLARE @v_ParentNodeID INT;
    DECLARE c_CUR CURSOR FAST_FORWARD LOCAL FOR
        SELECT ParentNodeID
            FROM GenericTree
        WHERE ISNULL(ParentNodeID, 0) = ISNULL(@NodeID, 0)
        ORDER BY ParentNodeID;
    OPEN c_CUR;
    FETCH FROM c_CUR INTO @v_ParentNodeID;
    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT @v_ParentNodeID;
        EXECUTE BFS @v_ParentNodeID;
        FETCH FROM c_CUR INTO @v_ParentNodeID;
    END;
    CLOSE c_CUR;
    DEALLOCATE c_CUR;
END;
GO

Any thoughts where I am doing wrong?

A: You will get better performance using a recursive common table expression although the syntax is (some would say) a bit more complicated, fortunately I don't have to explain it as there is an excellent article by Itzik where he handles both breadth first and depth first hierarchy evaluation.
https://sqlperformance.com/2020/09/t-sql-queries/fundamentals-of-table-expressions-part-6-recursive-ctes


text:
Q: SVM - constrained optimization. Is it possible to see atleast two points must be "tight" without geometry? In the support vector machine model, we want to find a plane, $p=w^Tx+b$ that separates two sets of data (labeled positive and negative) with as large a margin as possible. Referencing the notes here, we see on page 7 the objective function:
$$\min_{w,b} \frac 1 2 w^Tw$$
s.t.
$$y^{(i)}(w^Tx^{(i)}+b)\geq 1$$
Now, we can use geometric arguments to see that there must be atleast two points on either side of the separating plane for which the inequalities above are "tight" (i.e. they become equalities). I'm wondering - what if I was just given the optimization problem and had no idea about the geometric interpretation. Would it still be possible to somehow extract this fact? Feel free to use the dual form of the problem on page 12.
Here is how the geometric argument works: Imagine the separating plane has a point that is closest to it on the positive side at distance $d$. The point nearest to it on the negative side is at distance $d+\epsilon$. We can improve the objective function, which is the margin by moving the plane (without changing $w$, only $b$) so that it is $\frac{\epsilon}{2}$ close to the closest negative point.

A: I managed to figure this out, eventually. If you note the very first optimization problem of page 6 of the notes refereed to above, it reads:
$$\max_{\gamma, w, b} \gamma$$
s.t.
$$y^{(i)}(w^Tx^{(i)}+b) \geq \gamma$$
$$w^Tw=1$$
Here, $\gamma$ is a dummy variable, $x^{(i)}$ is the $i$th data point in the feature space and $y^{(i)}$ is the label of that point ($+/- 1$).
If we form the Lagrangian (assuming Lagrange multipliers $\alpha_i$ for each constraint, we get:
$$L = -\gamma -\sum_i \alpha_i (y_i(w^Tx^{(i)}+b)-\gamma) -\beta(w^Tw-1)$$
Here, the $\alpha_i$'s are all $\geq 0$.
Now, taking derivative with respect to $\gamma$ we get:
\begin{equation}\sum \alpha_i = 1 \tag{1}\end{equation}
And taking derivative with respect to $b$:
$$\sum y^{(i)} \alpha_i = 0 \tag{2}$$
If we consider $\textit{I}$ to be the set of positive labels and $\textit{J}$ to be the set of negative labels, we can re-write the above equation:
$$\sum_{i \in \textit{I}} \alpha_i = \sum_{j \in \textit{J}} \alpha_j \tag{3}$$
Equations (1) and (3) along with the fact that all the $\alpha_i$'s are $\geq 0$ imply that there must be at least one non-zero $\alpha_i$ in each of the positive and negative classes. And those two constraints must be tight.


text:
Q: Merging complex dictionaries in C# .net by writing a generic recursive function I have two complex dictionaries in the form
Dictionary<string, Dictionary<string, Dictionary<string, List<string>>>>

So as you see i've inner dictionaries. I want to write a generic recursive function which can merge two complex dictionaries of this form (or any other complex form of dictionaries), by calling itself passing the inner dictionaries (which are of different structure). This question also has another part. How to append one dictionary to other without looping?
A bit more explanation
This dictionary holds LIST OF MESSAGES sent BY A USER chatting in a SPECIFIC GROUP CHAT SESSION to a SPECIFIC USER (read the sentence and interpret the dictionary from the end). So i've two dictionaries of this form. As soon as i dispatch the message to a user i remove it from the dictionary. But i want to have history of messages. So before removing it i just make a copy by appending it to another dic which contains all the messages, in all chat sessions, from all users, to all users till now!
Note: I'm not blessed to use LINQ.
Thank you
NLV

A: If I dare be so bold, using dictionaries in this manner makes for extremely unmaintainable code.
IMHO, The following class structure, or similar, would be much, much easier to understand and work with.
public class User {
  public string Name {get;set;}

  // Sessions this user is participating in
  // (when you add to Session, add here too - Using a method to add both at same would be safest)
  public List<Session> Sessions {get;set;}

  // etc
}

public class Message {
  public User Sender {get;set;}
  public string Text {get;set;}
  // etc
}

public class Session {
  public string Title {get;set;}
  public List<User> Participants {get;set;}
  public List<Message> SentMessages {get;set;}
  public List<Message> UnsentMessages {get;set;}
}

public class ChatSystem {
   // All Users - Indexed by Name
   public Dictionary<string, User> Users {get; set;}

   // All Sessions - Indexed by Title
   public Dictionary<string, Session> Sessions {get; set;}
}

I know this isn't addressing your specific request, but is attempting to address the essence of the request - being able to work with Users, Chat Sessions and Messages easily.
Have fun!

A: Runtime dispatching based on type has to use reflection, which is very messy when generics come into play. I recommend "cheating" and using IDictionary instead.
So, your method declaration would look something like this:
// Merges b into a
void Merge<T>(T a, T b) where T : IDictionary

Then, iterate through each entry of b. If the key does not exist in a, then add the kvp to a and continue iterating. If the value is IDictionary, then pass the a value and b value to Merge recursively. Otherwise, if it is ICollection, then merge its values into the collection in a. Otherwise, error.


text:
Q: Hiding javascript in the page I have a webpage which has an external javascript file attached to it . Now in firebug , I can see all the js code and so can anyone else , is there a way so that the code can be hidden but it would still work?

A: No. There is no way to do that. That's not how the internet works. You cannot do that. Stop worrying about it. You cannot send a file and expect the file not to be sent.

A: The #1 law of software licensing: You don't control your software once you allow it to be installed run on a computer you don't control.
(blatently stolen from my own answer here)


text:
Q: Survey article model theory research I've taken a graduate course in model theory and I like it so much that I can imagine doing research in this area. Are there survey articles or review papers on the current research topics in model theory? Where can I find them?
Also, I wish there is literature about the common proof techniques and tricks one uses in the current research. (Sometimes I have the feeling that everybody just writes down their proofs and nobody writes down the essential ideas or an overview of techniques used.) Do you know of any such text?

A: This answer is partly an answer to your questions, and also partly a response to the conversation unfolding in the comments. So I am just going to list a somewhat disconnected list of resources.
One thing I'll say first though is in response to the query "or are they just the polished versions of the results of the last century" made in a comment. As a "stand alone" field, model theory is not even a century old (barely more than half a century by some accounts). So, yes, textbooks such as Marker's book on model theory are relevant for learning about current research. Other good texts are:

*

*A Course in Model Theory, by K. Tent and M. Ziegler

*A Course in Model Theory, by B. Poizat

*Stable Groups, by B. Poizat

*An Introduction to Stability Theory, by A. Pillay

*Model Theory, by W. Hodges
Another remark is that, in my opinion, it could be difficult to compile a list of common techniques and "tricks" used in model theory research. Perhaps it's because of how new the field is, and so there hasn't been enough time for such things to congeal. It could also be because a major portion of current research in model theory focuses on applications and interactions with other areas of math, and so the "techniques and tricks" are widely varied.
At any rate, here are more papers, books, and notes. These aren't in any particular order, and certainly this list is incomplete. But I think the list covers a lot, and provides starting points into several active areas. The Forking and Dividing website also has many definitions and examples from model theory with citations.

*

*Notes and survey articles. Survey articles on recent research in model theory can be scarce, but you should look through recent volumes of the Bulletin of Symbolic Logic. That being said, here are some survey-type articles that I like.
a. Stability theory and its variants, by B. Hart
b. Seminar and talk notes by E. Casanovas (you can find many topics of current research).
c. Diophantine geometry from model theory, by T. Scanlon
d. Approximate groups (after Hrushovski, and Breuillard, Green, Tao), by L. van den Dries (more "applied" model theory)
e. Notes on the model theory of finite and pseudo-finite fields, by Z. Chatzidakis
f. Unpublished notes of H. Adler

*Papers and books on specific research topics.
a. A Guide to NIP Theories, by P. Simon.
b. Simple Theories, by B. Kim
c. Tame Topology and O-minimal Structures, by L. van den Dries
d. Model Theory of Fields, by D. Marker, M. Messmer, and A. Pillay.
e. Vapnik-Chervonenkis density in some theories without the independence property, I and II, by M. Aschenbrenner, A. Dolich, D. Haskell, D. Macpherson, and S. Starchenko
f. Theories without the tree property of the second kind, by A. Chernikov
g. A geometric introduction to forking and thorn-forking, by H. Adler
h. Model theory for metric structures, by I. Ben Yaacov, A. Bernstein, C. W. Henson, and A. Usvyatsov
i. Topological dynamics of definable group actions, by L. Newelski
Lastly, one can read Classification theory and the number of non-isomorphic models by S. Shelah.


text:
Q: Updating single characters in large TextBox programmatically Reading lots of characters and updating a textbox was suggested to me when I created this question, and it was exactly what I was looking for (couldn't find it by just searching). However a couple of points need clarifying.
I am looking to upgrade to a ListBox or even RichTextBox. For now I want to be able to replace as little of the onscreen (and off, as an added bonus) text as possible.
In the first link Guffa wrote:

If the data is line based, use a list instead of a text box, so that you only have to update the last line when you add a character.

I have a split pane where updates to one TextBox are translated and shown on the other side, and vice-versa. I've briefly toyed with a ListBox but it doesn't provide the intrinsic text-editing funcionality of a TextBox so I went back.
What component should I be using? I wouldn't have thought that with all of .NET available I should have to consider Win32.

A: Ok, no one else has offered an answer so I will propose a solution which is the last one open to me short of refactoring back to Win32 API calls.
The solution is to use two textboxes. Instead of replacing the text element of the on-screen one you replace that of its dupe, which at the time is hidden, you then toggle the visible flags of both.
I'll let you know how it goes but it is major work for not much advantage, I'll prolly just live with a bit of flicker for now.


text:
Q: AutocompleteExtender not working in master page I have a problem regarding the autocomplete extender in ASP.NET - it works fine in all pages I have, but NOT in a master page and i don't know why.
Here is my code:
<asp:TextBox runat="server" ID="txtSearch" Width="200px" CssClass="TextBoxClass"></asp:TextBox>
<cc1:AutoCompleteExtender ID="txtSearch_AutoCompleteExtender" runat="server"
    TargetControlID="txtSearch"
    CompletionInterval="0"
    CompletionListCssClass="autocomplete_completionListElement"
    CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
    CompletionListItemCssClass="autocomplete_listItem"
    CompletionSetCount="10" EnableCaching="true" MinimumPrefixLength="2"
    ServiceMethod="GetCompletionListOggetti"
    ShowOnlyCurrentWordInCompletionListItem="true" UseContextKey="True">
</cc1:AutoCompleteExtender>

Code behind:
<System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()> _
Public Shared Function GetCompletionListOggetti(ByVal prefixText As String, ByVal count As Integer) As String()
    ' Insert code to return a string array here…
    Return AutoCompleteOggetti(prefixText)
End Function

The problem is that GetCompletionListOggetti is never called.
I repeat - it works fine on content page! Thanks in advance.

A: You need to set the ServicePath property of the AutoCompleteExtender to override the default behaviour of calling back to the loading (not master) page.
Add your function to the code-behind of a webservice page (.asmx), a dummy page, or default.aspx etc.
If using a webservice page, you would need to add/uncomment the line:
<System.Web.Script.Services.ScriptService()> _

for VB, or for C#
[System.Web.Script.Services.ScriptService]

A: I managed it by putting the web method (in your case, GetCompletionListOggetti) in the code behind file of the content page instead of master page. And it works only for web method in the same code behind file not in a separate asmx service. For this, don't forget to add EnablePageMethods="true" property to your script manager too.
It seems like AutoCompleteExtender's service method is never called when it's defined inside a user(or custom) control's code behind file and a master page is a kind of control indeed.
The downside of this fix is that you have to put the same service method in EVERY contents page which uses this master page. Not very elegant. Another downside is somehow the css of suggestion dropdownlist is not working properly. Still I couldn't figure out the walkaround. Anybody better idea?


text:
Q: Convert Div element as image, ii should support in IE 7 & 8 I am using jqplot charting library to draw the chart in my ASP.NET MVC application.Inside the div element, rendering the chart.I am trying to convert the div element as image, export to pdf document.
For IE 9  and later, jqplotToImageElem() method [support canvas browsers only] is working fine and able to export.
For IE 7 & 8 it is not working as expected, since it is using excanvas.js to render the chart.
Is there any workaround to implement this for IE 7 & 8 browsers?

A: For IE<9 users you have multiple possibilities:

*

*Use node.js on the server to generate your jqplot image and then let them download that image off the server.

*Require that they install Google Chrome Frame which will works within IE<9 to give it modern capabilities like canvas.  See: https://developers.google.com/chrome/chrome-frame/

*Since jqPlot evidently works but doesn't print in IE<9, just have those users print using a screen capture program.

*Microsoft recently realized that their non-modern IE's were a liability to the web and has begun auto-updating older IE users to modern versions of IE (See: http://www.paulirish.com/2012/the-skinny-on-ies-update-policy/).  So as @amhed suggests, you could require that your users "get with the program" and update to at least IE9.  Alternatively, update to Chrome, Firefox, any-modern-browser.

*There would be very few clients you couldn't service with #1-4 (but we're looking at you "certain banking institutions" who run on XP and for security reasons & disallow browser upgrades).  But for those few clients, you might have to use a GDI-based charting program rather that jqplot.


text:
Q: using a variable inside a nested function I'm using a variable inside the nested function and after assigning a value pass to the parent function but on calling it shows nothing.
function userexists(key) {
  let user = false;
  UsersModel.findOne({ email: key }, function (error, foundUser) {
    if (!error && foundUser) user = foundUser;
    else {
      console.log("error or not found: " + error);
    }
  });

  return user;
}

A: The reason for that is that findOne seems to be an async function. Therefore user is always false. Make sure to async await or add a callback function in the function itself.
Example async await, if possible:
async function abc(key) {
  const response = await UsersModel.findOne({ email: key });
  if (response.error)
    return false;
  }

  return response.foundUser;
}

Example callback function:
function async abc(key, f) {
  UsersModel.findOne({ email: key }, (error, foundUser) => {
    if (!error) f();
  });
}

A: Thanks to FloWy and VLAZ
Before,
function userexists(key) {
  let user = false;
  UsersModel.findOne({ email: key }, function (error, foundUser) {
    if (!error && foundUser) user = foundUser;
    else {
      console.log("error or not found: " + error);
    }
  });

  return user;
}

Using callback inside a function,
function userexists(key, callback) {
  UsersModel.findOne({ email: key }, function (error, foundUser) {
    if (!error && foundUser) return callback(foundUser);
    else return callback(false);
  });
}

On Call,
userexists(username, function (user) {
// you can use user here
});


text:
Q: Modify date format in-place through `sed` command I'm trying to modify the dates in a text in place where there are as 2016-Dec-24 or 2016-12-24 and I have to replace them like 24/12/2016.
Is there any way I can use sed -i to do this?
Input example:

Holiday or Observance Religious Group Dates   Additional Notes
  *Rosh Hashanah (New Year) Jewish  25-Sep-2014 - 26-Sep-2014   Designated non-work day for observers Navaratri/Dassehra    Hindu   Sept. 2014-Oct-03
*Yom Kippur (Day of Atonement)    Jewish  2014-Oct-04,    Designated non-work day for observers
Sponsored Conferences Title   Location    Conference Date 2017 IEEE Sensors
  Applications Symposium (SAS)  United States   2017-03-13, 2017-03-14,
  2017-03-15 2017 IEEE International Symposium on Medical Measurements
  and Applications (MeMeA)  United States   2017-05-07 to 2017-05-10 2017
  IEEE International Instrumentation and Measurement Technology
  Conference (I

That's what I've tried so far.
sed -i -e 's/\([0-9]\{4\}\)-\(01|Jan\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' $1
sed -i -e 's/\([0-9]\{4\}\)-\(02|Feb\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' $1
sed -i -e 's/\([0-9]\{4\}\)-\(03|Mar\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' $1
sed -i -e 's/\([0-9]\{4\}\)-\(04|Apr\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' $1
sed -i -e 's/\([0-9]\{4\}\)-\(05|May\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' $1
sed -i -e 's/\([0-9]\{4\}\)-\(06|Jun\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' $1
sed -i -e 's/\([0-9]\{4\}\)-\(07|Jul\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' $1
sed -i -e 's/\([0-9]\{4\}\)-\(08|Aug\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' $1
sed -i -e 's/\([0-9]\{4\}\)-\(09|Sep\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' $1
sed -i -e 's/\([0-9]\{4\}\)-\(10|Oct\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' $1
sed -i -e 's/\([0-9]\{4\}\)-\(11|Nov\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' $1
sed -i -e 's/\([0-9]\{4\}\)-\(12|Dec\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' $1

A: If you have access to GNU date (the default on Linux systems), you can do:
$ sed -E 's/(.*)-([a-z]+)(.+)/\2\3-\1/i' file |
    while read d; do date -d "$d" +%d/%m/%y; done
24/12/16
24/12/16

That changes lines like 2016-Dec-24 to Dec-24-2016 (a format that GNU date can understand), leaves lines like 2016-12-24 (a format GNU date already understands) alone, and then passes each line as an input date string to date. It doesn't do it in-place and it doesn't use sed -i but is almost certainly the simplest approach.
If you really need to do it using sed, you could make a list of all months and corresponding numbers:
$ for m in {1..12}; do printf '%s %s\n' "$m" $(date -d "$m/1/2016" +%b); done
1 Jan
2 Feb
3 Mar
4 Apr
5 May
6 Jun
7 Jul
8 Aug
9 Sep
10 Oct
11 Nov
12 Dec

Save that as months and then iterate over it to modify your file:
while read num mon; do
    sed -Ei "s/$mon/$num/; s#(.*)-(.*)-(.*)#\3/\2/\1#" file
done < months

Or, if your sed implementation needs separate -e:
while read num mon; do
    sed -i -e "s/$mon/$num/" -Ee 's#(.*)-(.*)-(.*)#\3/\2/\1#' file
done < months

The first substitution will replace all alphabetical month names with their corresponding number and the second moves things around to get your desired format.

A: The only thing I see wrong regex-wise is that in basic (BRE) mode, | is literal - you need \| to make it a logical OR i.e. \(01\|Jan\) and so on.
If your version supports -e then I don't see any good reason to make multiple calls to sed - you can just chain the -e <expr1> -e <expr2> ... in a single call. So
sed -i \
  -e 's/\([0-9]\{4\}\)-\(01\|Jan\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' \
  -e 's/\([0-9]\{4\}\)-\(02\|Feb\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' \
  -e 's/\([0-9]\{4\}\)-\(03\|Mar\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' \
  -e 's/\([0-9]\{4\}\)-\(04\|Apr\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' \
  -e 's/\([0-9]\{4\}\)-\(05\|May\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' \
  -e 's/\([0-9]\{4\}\)-\(06\|Jun\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' \
  -e 's/\([0-9]\{4\}\)-\(07\|Jul\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' \
  -e 's/\([0-9]\{4\}\)-\(08\|Aug\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' \
  -e 's/\([0-9]\{4\}\)-\(09\|Sep\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' \
  -e 's/\([0-9]\{4\}\)-\(10\|Oct\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' \
  -e 's/\([0-9]\{4\}\)-\(11\|Nov\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' \
  -e 's/\([0-9]\{4\}\)-\(12\|Dec\)-\([0-9]\{2\}\)/\3\/\2\/\1/g' $1

However there are more elegant ways to do this - for example in perl using strptime and strftime functions (provided by the Time::Piece module for example):
perl -i -MTime::Piece -pe '
  s|\d{4}-\d\d-\d\d?|Time::Piece->strptime($&, "%Y-%m-%d")->strftime("%Y/%m/%d")|ge;
  s|\d{4}-...-\d\d?|Time::Piece->strptime($&, "%Y-%b-%d")->strftime("%Y/%m/%d")|ge;
' file

A: sed -r -i '
/([0-9]{4})-([[:alpha:]]{3})-([0-9]{2})/ {
    s#([0-9]{4})-Jan-([0-9]{2})#\2/01/\1#g
    s#([0-9]{4})-Feb-([0-9]{2})#\2/02/\1#g
    s#([0-9]{4})-Mar-([0-9]{2})#\2/03/\1#g
    s#([0-9]{4})-Apr-([0-9]{2})#\2/04/\1#g
    s#([0-9]{4})-May-([0-9]{2})#\2/05/\1#g
    s#([0-9]{4})-Jun-([0-9]{2})#\2/06/\1#g
    s#([0-9]{4})-Jul-([0-9]{2})#\2/07/\1#g
    s#([0-9]{4})-Aug-([0-9]{2})#\2/08/\1#g
    s#([0-9]{4})-Sep-([0-9]{2})#\2/09/\1#g
    s#([0-9]{4})-Oct-([0-9]{2})#\2/10/\1#g
    s#([0-9]{4})-Nov-([0-9]{2})#\2/11/\1#g
    s#([0-9]{4})-Dec-([0-9]{2})#\2/12/\1#g
}
s#([0-9]{4})-([0-9]{2})-([0-9]{2})#\3/\2/\1#g
' file


text:
Q: What happens when filter is passed in pipe? I am trying to understand why the below subscription is not working:
  isLoggedIn1$:Observable<boolean> = of(false) // on subscribing it I get value as false

  isLoggedIn2$:Observable<boolean> = of(false).pipe(filter(value => Boolean(value))) // this one is not giving any value even it looks like subscribe is not getting called for this

Is there any documentation for this particular behavior?
As I understand it is being treated equivalent to EMPTY. but then why I am not getting type error for second one.

A: The filter operator filters the value based on given predicate. If that condition specified by filter is fulfilled, then the value will pass down to subscriber else we don't see anything on screen.
For the line
isLoggedIn2$:Observable<boolean> = of(false).pipe(filter(value => Boolean(value)))

The predicate here only allows those value to pass further down the pipe that are true
value => Boolean(value)

If you want to print false you have to modify filter condition as
value => Boolean(value) === false

More on filter operator - https://www.learnrxjs.io/learn-rxjs/operators/filtering/filter


text:
Q: Problema com LEFT JOIN usando Pentaho Kettle Existe um comportamento com relação ao JOIN que não consigo entender.
Tenho duas tabelas nestes formatos
Tabela Doente
 ID_Doente Doente
 1          Pedro
 2          Paulo
 3          Rui

Tabela consulta
 ID_Consulta  ID_Doente Tipo
 1            2        Não Medica
 2            2        Médica

E estou a fazer um left join como este:
SELECT *
FROM Consulta
LEFT JOIN Doente
ON Consulta.ID_Doente =Doente.ID_Doente;

Eu estava com a ideia que o resultado seria algo como isto
ID_Consulta  ID_Doente    Tipo         Doente
 1             2        Não Medica    Paulo
 2             2        Médica        Paulo

Mas no entanto estou a ter isto
ID_Consulta  ID_Doente    Tipo         Doente
 1             2        Não Medica    Paulo
 2             2        Médica        NULL

Alguém sabe a razão?
EDIT: Isto é um exemplo do que está a acontecer, eu estou a realizar isto usando a funcionalidade de merge left join do Pentaho Kettle
EDIT2: Questão foi respondida aqui https://stackoverflow.com/questions/22459143/pentaho-kettle-weird-left-join-results

A: Testei seu SQL no SQLServer e funcionou normalmente:

O problema deve ser na engine do Pentaho Kettle.
O código a seguir é a mesma coisa, mas tente pra ver se funciona, pois deve ser um problema estrutural no Pentaho.
SELECT *
FROM Doente
RIGHT JOIN Consulta
ON Consulta.ID_Doente =Doente.ID_Doente;

A: Olá, tudo bem ?
Acredito que você possa estar utilizando um join sem adicionar o componente Sort senão podem sair resultados não esperados.
Veja a o que cita a documentação do kettle.

Sempre que for utilizar um JOIN no Pentaho adicione um Step Sort com os IDs de ligação para que o pentaho consiga classificar os resultados antes de juntar, assim conseguirá classificar sem maiores problemas

Espero ter ajudado.


text:
Q: Действие OnClick в JavaScript Можно ли в javascript сделать так, чтобы при нажатии на кнопку на странице (без ее перезагрузки) выводилась, например, определенная для каждой кнопки статья. Например, если делать так
<input type="button" value="привет" name="a" OnClick="a();">
<input type="button" value="пока" name="b" OnClick="b();">
<input type="button" value="погода" name="c" OnClick="c();">
<input type="button" value="природа" name="d" OnClick="d();">

то при нажатии на кнопку текст открывается в новом пустом окне.
A: Отлично, Как вывести фразу на сайт? - это то, что надо: теперь все работает

<input type="button" value="Hello!" name="hello" OnClick="a();">
<input type="button" value="Hello!" name="hello" OnClick="b();">

Теперь при нажатии на кнопки выводятся различные статьи без перезагрузки страницы в этом же окне.

A: Надо работать напрямую с DOM:

<input type="button" value="Hello!" name="hello" onclick="hello();">


text:
Q: switch to root to execute commands through Python Hi I start a python script by using python script.py.
But I need to write into a file which is inside the /usr/local/etc folder that requires permission of root. So I think I need to spawn a child process with sudo; the password to run the as sudo must be hardcoded into the script.
How do I do it?


text:
Q: Does joint IID imply marginal IID? Suppose you have a 2 dimension random vector denoted $(X,Y)$ that is Independent and Identically Distributed (IID) for a sequence of draws $((X_1,Y_1),(X_2,Y_2),...,(X_n,Y_n))$. Does this imply that the marginal draws, $(X_1,X_2,...,X_n)$ and $(Y_1,Y_2,...,Y_N)$, are IID?
I think the answer is no. Here is a counterexample. Suppose $\epsilon$ is independent of $(X,Y)$ and assume $Y=X+\epsilon$. Then the distribution of $Y$ depends on $X$ and thus is Independent and Not Identically Distributed.

A: You are conflating a few different things here, which is leading you into some trouble.  The joint-IID condition implies that $X_1,\ldots,X_n$ is IID, and $Y_1,\ldots,Y_n$ is IID, but these two vectors are not necessarily independent of each other, since there is no specification of the relationship within the bivariate vector.

Theorem: If $(X_1,Y_1),\ldots,(X_n,Y_n)$ is IID then $X_1,\ldots,X_n$ is IID and $Y_1,\ldots,Y_n$ is IID.
Proof: From the joint-IID condition there exists a joint-distribution function $F_{X,Y}: \bar{\mathbb{R}} \rightarrow [0,1]$ such that:
$$\mathbb{P}(X_1 \leqslant x_1, Y_1 \leqslant y_1, \ldots, X_n \leqslant x_n, Y_n \leqslant y_n) = \prod_{i=1}^n F_{X,Y}(x_i,y_i),$$
for all argument values in the set of extended real numbers.  Now, if we define the marginal distribution $F_X: \bar{\mathbb{R}} \rightarrow [0,1]$ by $F_X(x) \equiv F_{X,Y}(x, \infty)$ we then have:
$$\begin{equation} \begin{aligned}
\mathbb{P}(X_1 \leqslant x_1, \ldots, X_n \leqslant x_n)
&= \mathbb{P}(X_1 \leqslant x_1, Y_1 \leqslant \infty, \ldots, X_n \leqslant x_n, Y_n \leqslant \infty) \\[6pt]
&= \prod_{i=1}^n F_{X,Y}(x_i,\infty) \\[6pt]
&= \prod_{i=1}^n F_X(x_i), \\[6pt]
\end{aligned} \end{equation}$$
for all argument values in the extended real numbers.  This establishes that $X_1,\ldots,X_n$ is IID.  By analogous reasoning we can also show that $Y_1,\ldots,Y_n$ is IID.


text:
Q: Android Kotlin Coroutines fetching data with chained network requests Q) How can I update my viewModel per item using chained network requests using coroutines?
I'm trying to fetch some objects from an api, but the api requires an initial call to fetch an array of objectIds, and then each object is fetched with an individual call including the objectId. My current implementation chains all the network calls, but only returns when the entire loop has completed.
for example:
@GET ...api/topItems returns [ 1111, 2245, 5456, ... ]
@GET ...api/item?id=1111
@GET ...api/item?id=2245
and so on.
My ViewModel
class FeedItemListViewModel(
private val retrieveItemsFromApiUseCase: RetrieveItemsFromApiUseCase
) : ViewModel() {

private val _feedItemsFromApi = MutableLiveData<List<FeedItem>>()

val feedItemsFromApi: LiveData<List<FeedItem>>
    get() = _feedItemsFromApi

fun retrieveFeedItemsFromApi() {
    viewModelScope.launch {
        val result = retrieveItemsFromApiUseCase.invoke("topItems")
        when (result) {
            is NetworkResult.Success -> {
                _feedItemsFromApi.postValue(result.data)
            }
            is NetworkResult.Error -> Timber.d("no feed items from api ${result.exception}")
        }
    }
}

}
RetrieveItemsFromApiUseCase
class RetrieveItemsFromApiUseCase(private val repository: InMemoryRepository) {

suspend operator fun invoke(feedType: String): NetworkResult<List<FeedItem>> = withContext(Dispatchers.IO) {
    val itemList: MutableList<FeedItem> = mutableListOf()
    val result = repository.fetchTopItems()
    when (result) {
        is NetworkResult.Success -> {
            itemList.addAll(result.data)
            for (i in 0..9) {
                val emptyItem = result.data[i]
                val response = repository.fetchItem(emptyItem.id)
                when (response) {
                    is NetworkResult.Success -> {
                        val item = response.data
                        emptyItem.setProperties(item)
                    }
                }
            }
        }
        is NetworkResult.Error -> return@withContext result
    }
    return@withContext NetworkResult.Success(itemList)
}

}


text:
Q: Rotate function, in respect to another function I am working on a piece of code where I am translating some points along a function, for easing an animation. For example, I have a cubic easing function of f(t) = t^3. However, I want the easing function to return a ratio of where to adjust the point in relation to a linear ease. So instead of having the cubic function above move from (0, 0) to (1, 1), it would move from (0, 1) to (1, 1). In other terms, the line y = x that intersects the curve at the edges should instead be y = 1
So, to put it into pictures, (in case I'm not wording it appropriately) I want to go from this:

to this (edited graph to show what I'm envisioning):

Is there a reasonable way to calculate this?

A: Let $f(t)$ be a function defined on the interval $(0,1)$. Then the line segment from $(0,f(0))$ to $(1,f(1))$ should end up as the line segment from $(0,1)$ to $(0,1)$. First shift everything up/down by $1-f(0)$ so that the line segment starts at the origin $(0,0)$. That is, apply the translation
$$T_1(x,y)=(x,y-f(0)).$$
Next, rotate the plane about the origin so that the other endpoint, which is now at
$$T_1(1,f(1))=(1,f(1)-f(0)),$$
ends up on the $x$-axis. This can be done by the applying rotation map
$$R(x,y):=\begin{pmatrix}
\cos\theta&-\sin\theta\\
\sin\theta&\hphantom{-}\cos\theta
\end{pmatrix}
\begin{pmatrix}x\\y\end{pmatrix}
=(x\cos\theta-y\sin\theta,x\sin\theta+y\cos\theta),$$
where $\theta=-\arctan(f(1))$.
Now we can scale the whole picture so that the line segment becomes $1$ long; apply
$$S(x,y)=\left(\frac{x}{|\sin\theta+(f(1)-f(0))\cos\theta|},\frac{y}{|\sin\theta+(f(1)-f(0))\cos\theta|}\right).$$
Finally, shift everything up by $1$, which is simply
$$T_2(x,y)=(x,y+1).$$
Putting everything together yields the transformation
\begin{eqnarray*}
F(x,y)&=&(T_2\circ S\circ R\circ T_1)(x,y)\\
&=&\left(\frac{x\cos\theta-(y-f(0))\sin\theta}{|\sin\theta+(f(1)-f(0))\cos\theta|},\frac{x\sin\theta+(y-f(0))\cos\theta}{|\sin\theta+(f(1)-f(0))\cos\theta|}+1\right).
\end{eqnarray*}
This means that if your original function was $y=f(x)$, now your function is given by the implicit equation
$$\frac{x\sin\theta+(y-f(0))\cos\theta}{|\sin\theta+(f(1)-f(0))\cos\theta|}+1=f\left(\frac{x\cos\theta-(y-f(0))\sin\theta}{|\sin\theta+(f(1)-f(0))\cos\theta|}\right).$$

A: So you are doing several operations:

*

*You are rotating the figure $-45^\circ$ around the origin

*You are scaling the result from part 1 by multiplying with $1/\sqrt 2$

*You are translating the result from part 2 up by $1$
The best way to deal with these is separately. You have an array of $x$ points, originally $x_0=t$, and $y$ points, originally $y_0=t^3$. The rotation means that you need to calculate the arrays $x_1$ and $y_1$ given by
$$x_1=x_0\cos45^\circ+y_0\sin 45^\circ\\y_1=-x_0\sin 45^\circ+y_0\cos 45^\circ$$
Then for scaling along $x$ you have:
$$x_2=\frac{x_1}{\sqrt 2}\\y_2=y_1$$
Finally, moving it up means $$x_3=x_2\\y_3=y_2+1$$
See if this does what you want.

A: $t^3 + (1-t)$ does the trick! It's not a rotation, instead I am just adding the amount that the linear upper bound $t$ is missing to get to $1$. Hope this helps!
Edit: If you wanted something symmetric about $t=\frac{1}{2}$ instead, you could try the quadratic $at(t-1)+1$ where $a>0$.


text:
Q: Как обойтись без index.html для отправки запроса. GlassFish Например у меня есть сервер приложений с таким вот сервлетом:
http://blog.c2b2.co.uk/2014/03/writing-and-deploying-simple-web.html
Вопрос смогу ли я отправить Post запрос используя скажем PostMan? Какой будет урл? Нужен ли вообще index.html?

A: Да, Post запрос можно отправить.
Урл будет тот что в конфигурации сервлета, в данном примере:
@WebServlet(name = "PersonServlet", urlPatterns = {"/PersonServlet"})

/PersonServlet  будет вашим URL
index.html не нужен.


text:
Q: Inter-process communication in C I have a scenario, where one process should wait for a signal from another process, and this wait should be blocking wait, and as soon as it gets a signal, it should wake up.
However, with mechanisms like kill() or raise(), the first process goes to wait state, but periodically checks after a specified amount of time, whether the even/signal occurred or not, and decides to wait or go on.
My requirement is a bit stringent, I want that process should wake up at the same instant as signal is received.
Please suggest something.

A: This can be achieved using semaphore,mutex or conditional variable. Or You can write wait and signal function by your own and you can control the behavior of these as per need. For reference see here:  IPC examples
IPC concept and Examples Mutex and Conditional Variables


text:
Q: Как сверстать круглый блок с иконками внутри? Подскажите, пожалуйста, как сверстать такое расположение иконок?
Если приглядеться, там по окружности (белый фон с несколькими кругами) расположены кликабельные иконки...
У меня вообще нет идей.

A: Решение SVG

*

*Для реализации тени используются две окружности, одна над другой.

*К нижней окружности применен фильтр Гаусса.  С помощью атрибутов
этого фильтра можно тонко отрегулировать насыщенность и положение
тени.  stdDeviation="4" dx="0" dy="2"   Я сделал, как у автора
вопроса. Если нужно что-то изменить во внешнем виде тени, меняйте эти
атрибуты и радиусы окружностей.

*Иконки добавлены через тег <image> внутри svg файла.       Это
гарантирует, что иконка и окружность с тенью не разъедутся при
изменении масштаба.

*Я использовал для демонстрации 3 комплекта иконок+окружности.  Можно
клонировать и позиционировать комплекты других иконок с помощью
команды

<use xlink:href="#icon" x="20" y="100"/>

*

*Иконки бывают разного размера. В этой технике легко изменить х
размеры с помощью процентов <image>
<image xlink:href="Safari.png" x="90px" y="170px" width="15%" height="15%" />

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="400" height="400" viewBox="0 0 400 400">

   <defs>
    <filter id="dropshadow" width="130%" height="130%">
      <feGaussianBlur in="SourceAlpha" stdDeviation="4"/>
      <feOffset dx="0" dy="2" result="offsetblur"/>
      <feMerge>
        <feMergeNode/>
        <feMergeNode in="SourceGraphic"/>
      </feMerge>
    </filter>
  </defs>

   <g  id="icon">
 <circle cx="100" cy="100" r="30" fill="#FFFFFF" filter="url(#dropshadow)"/>
   <circle cx="100" cy="100" r="35" fill="#FFFFFF" />
     </g>

 <use xlink:href="#icon" x="150" y="50"/>
  <image xlink:href="https://i.stack.imgur.com/P6Rbo.png" x="75px" y="76px" width="12%" height="12%" />

 <use xlink:href="#icon" x="20" y="100"/>
 <image xlink:href="https://i.stack.imgur.com/oEW1L.png" x="90px" y="170px" width="15%" height="15%" />

 <image xlink:href="https://i.stack.imgur.com/y06Su.png" x="220px" y="120px" width="15%" height="15%" />
</svg>

A: Добавляю новый ответ, так как приложение почти полностью переписано и не знаю какое решение больше устроит автора.
Что сделано вновь:

*

*Все изменяемые параметры переведены в проценты для достижения полной
адаптивности.

*Блок окружностей, который обеспечивает круглую основу иконки с тенью
переведен в секцию <defs> для многократного использования с помощью
команды <use>

*Упрощена формула фильтра, который размывает тень

*Убраны фиксированные значения widthи height из шапки SVG для
получения адаптивности

*svg код обернут в
, что позволит менять размеры svg блока,
меняя проценты ширины и высоты родительского
.

*Добавлены ссылки на каждую иконку

*Иконки распределены по всей ширине svg блока

Для настройки размера и интенсивности тени увеличивайте или уменьшайте радиусы двух окружностей относительно друг друга. Так же для этих целей, можно изменять атрибут stdDeviation="4" фильтра

.container {
 width:100%;
 height:100%
}

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"   viewBox="0 0 1200 1200" preserveAspectRatio="xMinYMin meet" >

   <defs>
    <filter id="dropshadow" width="130%" height="130%">
      <feGaussianBlur in="SourceAlpha" stdDeviation="4"/>
      <feOffset dx="0" dy="2" result="offsetblur"/>
    </filter>

    <g  id="icon" fill="#fff">
 <circle cx="0" cy="0" r="2.5%"  filter="url(#dropshadow)"/>
   <circle cx="0" cy="0" r="2.7%"  />
     </g>
</defs>

 <use xlink:href="#icon" x="120px" y="120px" />

  <image  xlink:href="https://i.stack.imgur.com/P6Rbo.png" x="96px" y="96px" width="4%" height="4%" />

 <use xlink:href="#icon" x="1000px" y="120px"/>

  <image  xlink:href="https://i.stack.imgur.com/P6Rbo.png" x="976px" y="96px" width="4%" height="4%" />

 <use xlink:href="#icon" x="530" y="200"/>

  <image xlink:href="https://i.stack.imgur.com/oEW1L.png" x="497px" y="165px" width="5.5%" height="5.5%" />

  <use xlink:href="#icon" x="310" y="148"/>

 <image xlink:href="https://i.stack.imgur.com/y06Su.png" x="280px" y="118px" width="5%" height="5%" />

   <use xlink:href="#icon" x="760" y="148"/>

 <image xlink:href="https://i.stack.imgur.com/y06Su.png" x="730px" y="118px" width="5%" height="5%" />

</svg>

A: Разумеется что нету определённого алгоритма как расположить эти элементы
Я показал только одну часть ибо направляю в нужное русло
Дальше по шагам ... один блок в нём потомки ...и по такому примеру и сколько нужно потомков ...
Нужное правило для этого : transform:origin(x,y,z); и правильное позиционирование
Но лучше конечно для этого применить svg

* {
  margin: 0;
  padding: 0;
}

.items {
  width: 330px;
  height: 330px;
  margin: 90px auto;
  border: 1px solid red;
  position: relative;
  border-radius: 50%;
}

.items>div {
  position: absolute;
  top: -20%;
  left: 35%;
  transform-origin: 50% 230% 0;
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

.item1 {
  background: red;
  transform: rotate(0deg);
}

.item2 {
  background: green;
  transform: rotate(-90deg);
}

.item3 {
  background: blue;
  transform: rotate(90deg);
}

.item4 {
  background: orange;
  transform: rotate(180deg);
}


text:
Q: How to draw the cards of a deck? How to draw the cards from a deck using a Latex package, as TikZ?

A: The closest solution I found is the experimental package poker developed by Olaf Encke. This package is based on PSTricks (with all complications to run in pdflatex) further that this package is not standard and generally is not included in the Standard TeX Distributions (MaCTeX, TeXLive or MiKTeX) and it must be manually installed.
I recommend these steps:

*

*Download and extract the package from MIT webpage.

*Depending of your distribution Install manually the package. (For MiKTeX you must Create a local texmf tree, if you use a system as Linux read How do I install an individual package on a Linux system?, and read here for MaCTeX).

*Run using the path latex->dvips->ps2pdf.

*If you need the figures to include in others files .pdf (with pdflatex, xelatex or lualatex) then clip using
pdfcrop --hires <file> <file.pdf>

Code Example
\documentclass{article}
\usepackage{poker}
\pagestyle{empty} %No number in pages
\begin{document}

\begin{cards}
\crdAs\crdKh
\end{cards}

\begin{cards}
\crdpair{\crdKs}{\crdtenh}%
\crdflop{\crdsevd}{\crdsevc}{\crdQd}%
\crdKc\crdKd%
\end{cards}

\end{document}

Result

A: Depends what you want to do with them. If you going to enter them in a paper to describe probabilities etc, better to use a font. As of Unicode 7.0 there are codepoints for card suite. Use the Symbola free font of George Douros.
\documentclass{article}
\usepackage{fontspec}
\newfontfamily\symbola{Symbola.ttf}
\begin{document}
\Huge
\symbola
\char"1F0AB \char"1F0CF
\end{document}

Use XeLaTeX or LuaLaTeX.

With a unicode font you can just type "The drawn trump suit from the draw deck is a ♣ card (2♣)." and typeset the text easily.

A: Here is a solution using SVG-Cards, inkscape and PDFLaTEX/graphicx/TikZ.
I provide a Makefile :

*

*to download and to extract the SVG-Cards archive (via wget and tar),

*to extract each SVG card from svg-cards.svg (via inkscape)

*to convert each SVG card into a PDF card (via inkscape)

*to compile cards.tex (via pdflatex)
Steps:

*

*Copy the Makefile (note: the white spaces at beginning of lines are tabulations) and the cards.tex below.

*Run make to get cards.pdf
Note: if you can't use this Makefile, I provide cards.tgz. This archive contains all extracted PDF cards (needed to compile cards.tex).

The Makefile:
JOKERS = black_joker red_joker
LEVELS = 1 2 3 4 5 6 7 8 9 10 jack queen king
CLUBS = ${LEVELS:%=%_club}
DIAMONDS = ${LEVELS:%=%_diamond}
HEARTS = ${LEVELS:%=%_heart}
SPADES = ${LEVELS:%=%_spade}
CARDS = ${CLUBS} ${DIAMONDS} ${HEARTS} ${SPADES} ${JOKERS}
CARDS_PDF = ${CARDS:%=card-%.pdf}

all: cards.pdf

cards.pdf: cards.tex $(CARDS_PDF)
    latexmk -pdf cards.tex

card-%.pdf: card-%.svg
    inkscape --export-pdf=$@ $<

card-%.svg: SVG-cards-2.0.1/svg-cards.svg
    inkscape --export-plain-svg=$@ --export-id=${@:card-%.svg=%} --export-id-only $<

SVG-cards-2.0.1/svg-cards.svg:
    wget http://sourceforge.net/projects/svg-cards/files/SVG-cards-2.0.1.tar.gz
    tar zxvf SVG-cards-2.0.1.tar.gz

The cards.tex file:
\documentclass[tikz]{standalone}
\begin{document}
\begin{tikzpicture}
  \foreach \col[count=\c] in {spade,heart,diamond,club}{
    \begin{scope}[shift={(\c*90:1.5cm)}]
      \foreach \level[count=\val] in {1,...,10,jack,queen,king}{
        \node[inner sep=0,anchor=south,rotate={40-(\val*6)}]
        at ({140-(\val*6)}:1cm)
        {\includegraphics[height=1cm]{card-\level_\col}};
      }
    \end{scope}
  }
  \node at (-2,0) {\includegraphics[height=1cm]{card-red_joker}};
  \node at (2,0)  {\includegraphics[height=1cm]{card-black_joker}};
\end{tikzpicture}
\end{document}


text:
Q: Is a shift instruction faster than an IMUL instruction? Which one is faster -
val = val*10;

or
val = (val<<3) + (val<<2);

How many clock cycles does imul take when compared to shift instruction?

A: In this case they probably take the same amount of cycles, though your manual "optimization" needs one more register (which can slow down the surrounding code):
val = val * 10;
lea    (%eax,%eax,4),%eax
add    %eax,%eax

vs
val = (val<<3) + (val<<1);
lea    (%eax,%eax,1),%edx
lea    (%edx,%eax,8),%eax

The compiler knows how to do strength reduction, and probably much better than you. Also, when you port your code to other platform (say, ARM), the compiler knows how to do strenght reduction on that platform too (x86's LEA provides different optimization opportunities than ARM's ADD and RSB).

A: This is the 21st century. Modern hardware and compilers know how to produce highly optimised code. Writing multiplication using shifts won't help performance but it will help you to produce code with bugs in.
You have demonstrated this yourself with code that multiplies by 12 rather than 10.

A: Doing silly "optimizations" like this by hand in a high-level language will accomplish nothing but showing people you're out of touch with modern technology and programming practices.
If you were writing in assembly directly, it would make sense to worry about this, but you're not.
With that said, there are a few cases where the compiler won't be able to optimize something like this. Consider an array of possible multiplicative factors, each consisting of exactly 2 nonzero bits, with code like:
x *= a[i];

If profiling shows this to be a major bottleneck in your program, you might consider replacing that by:
x = (x<<s1[i]) + (x<<s2[i]);

as long as you plan to measure the results. However I suspect it's rare to find a situation where this would help, or where it would even be possible.  It's only plausible on a CPU with a weak multiply unit compared to shifts and total instruction throughput.

A: I'd say, just write val = val * 10; or val *= 10;, and let the compiler worry about such questions.


text:
Q: How to read file without file input? I'm developing an application in Javascript, which requires to read a text file and put it into a variable as input. However, I google many related questions and found that FileReader can't read file without file input because of security reason. Is there any library or dirty ways to read the content of a text file with only local path? Thanks a lot.

A: I think a way to do it would be to load your file with Ajax. Then you can do whatever you want with its content.
var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {
      // Do whatever you want here with this.responseText
   }
};
xhttp.open("GET", "youtext.txt", true);
xhttp.send();

A: It's easier to put your file.txt or file.json to your localhost, or put it on your server.
or this link maybe can help you out
https://github.com/nwjs/nw.js/issues/3227
i understand this question that he want to read file line by line from his local path.


text:
Q: The Gui menu to create widgets is not appearing in Qt Creator It always appeared, but then out of the blue on one new project it wasn't there. I have double checked it was a QWidgets project, and it was.

A: Open Qt Creator, go to the tap: Window > Views >  And check "Widget box"


text:
Q: Problems with remove timestamps in JQuery When I double click the card the dialog pops up, and it is then possible to create comments. So far so good. When creating the comments it is possible to delete it.
The issue is, that the timestamps can't be removed. The way I'm trying to remove the timestamps is by this line: $('.labelStyle').remove();
I want to be able to remove the timestamps, like the others elements but how?
Live Demo
JQuery: "click" handler
$('#divComments').on('click', '.delete', function (e) {
        var uniqueval = $(this).attr("for")
        var NameOfDataValue = $('label[for=' + uniqueval + ']').text();
        $('img[for=' + uniqueval + ']').remove();
        $('label[for=' + uniqueval + ']').remove();
        $('p[for=' + uniqueval + ']').remove();
        $('.labelStyle').remove();
        var arr = $('#divComments').data('comments');
        var theIndex = -1;
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].commentString== NameOfDataValue) {
                theIndex = i;
                break;
            }
        }
        if (theIndex == -1) {
            alert("Error");
        }
        else {
            $('#divComments').data("comments").splice(theIndex, 1);
        }

    });

JQuery: Add comment function
function addComment(commentString) {

        var container = $('#divComments');
        var inputs = container.find('label');
        var id = inputs.length + 1;
        var data1 = {
            commentString: commentString
        };

        var div = $('
', { class: 'CommentStyle' });

        $('', {
            id: 'comment' + id,
            for: 'comment' + id,
            text: commentString
        }).on('change', function () {
            data1.commentString = $(this).text();
        }).appendTo(div);

        $('
').appendTo(div);

        var $Image = $('',
            {
                "src": "/Pages/Images/alert.png",
                "class": "CommentImage",
                "for": "comment" + id
            }).appendTo(container);

        var d = new Date();
        var $fulaDate = $('
' + d.getDate()
            + "-" + monthNames[d.getMonth()]
            + "-" + d.getFullYear()
            + "//" + d.getHours()
            + ":" + d.getMinutes()
            + '
').addClass('labelStyle').append(' ~').appendTo(div);

        var $edit = $('
', {
            class: 'edit',
            for: 'comment' + id,
            text: 'Edit'
        }).append(' ~').appendTo(div);

        var $delete = $('
', {
            class: 'delete',
            for: 'comment' + id,
            text: 'Delete'
        }).appendTo(div);

        div.appendTo(container).focus();

        container.data('comments').push(data1);

    }

A: You could do:
$(this).parent().find('.labelStyle').remove();

This will select the parent of the clicked button (.CommentStyle) then find the .labelStyle and remove it.


text:
Q: Having trouble isolating for y I have this equation $x^3(y-1)^2 = 4y^4(x-1)^3$ and I'm trying to isolate for y.
No matter what I do, I keep getting $\frac{y-1}{y^2} = \frac{2(x-1)^{3/2}}{x^{3/2}}$
I have no idea how to isolate for y here.

A: Try multiplying out by $y^2$ and using the quadratic formula.

A: Rearranging, we get $$\left( \frac{2(x-1)^{3/2}}{x^{3/2}} \right) y^2 - y + 1 = 0.$$ Now use the quadratic formula with $a= \frac{2(x-1)^{3/2}}{x^{3/2}}, b = -1$ and $c=1$.


text:
Q: GWT RPC using classes from another project on client side My question is similar to my previous one, but this time I included the other project to my main project (I would like to use another project classes on my client side).
This is my package hierarchy:

The Common.gwt.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 1.7.0//EN" "http://google-web-toolkit.googlecode.com/svn/tags/1.7.0/distro-source/core/src/gwt-module.dtd">
<module>
<inherits name='com.google.gwt.user.User' />
<source path="dal.entities"></source>
</module>

The Main.gwt.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 1.7.0//EN" "http://google-web-toolkit.googlecode.com/svn/tags/1.7.0/distro-source/core/src/gwt-module.dtd">
<module rename-to="">
<inherits name="com.google.gwt.user.User"/>
<inherits name="org.rj.shared.Shared"/>
<inherits name="Common" />
<entry-point class="org.rj.client.MainEntryPoint"/>
</module>

Thank you for any help!

A: Get a hold of jpa-annotations-source.jar, see comment 14 and add it to your webproject classpath (the one with GWT). This should allow the GWT compiler to "see" the sources for the imports from your entity classes which I assume is causing problems. Hope it works! ;)