text:
Q: Compute the solution of the IVP and determine the largest interval Compute the solution of the IVP
$$
\begin{cases}
x'(t) = - \frac{t}{x(t)},\\
\\
x(t_0)=x_0,  x_0>0,
\end{cases}
$$
and determine the largest interval where the solution
exists and satisfies the IVP,. depending on $t_0$ and $x_0$.
I have worked out I have to use the method for separable equations but am unsure of how it works if anyone can help me out it would be deeply appreciated sorry this isn't as progressed as it really should be but I have hit a bit of a wall with this subject.

A: The method for separable equations gives the general solution for the ODE:
$$x(t)=\sqrt{-2t+C},$$
where $C \in \mathbb R.$
If $x(t_0)=x_0$, then
$$x_0=\sqrt{-2_0t+C},$$
Hence $C=x_0^2+2t_0$. Therefore the solution of the IVP is given by
$$x(t)=\sqrt{-2t+x_0^2+2t_0},$$
therefore we must have $-2t+x_0^2+2t_0 >0.$ This means $ t < \frac{x_0^2+2t_0}{2}.$
Consequence: largest interval where the solution exists and satisfies the IVP is
$$(- \infty, \frac{x_0^2+2t_0}{2}).$$


text:
Q: Simultaneous creation of Rails resource and nested resources fails, but not systematically Ok sorry for the weird title, it's hard to sumarize.
I have this basic setup
class Release
  has_many :batches
end

and
class Batch
  belongs_to :release
end

and the batches database table has a non-nil constrain on the foreign-key release_id.
I have a simple form that creates both a release and its first batch in one go :
form_for @release do |f|
  ...
  f.fields_for :batches do |ff|
    ...
  end
end

That works perfectly locally as well as most times in production.
In some rare occasions, the creation fails because the batch's release_id is nil at the time of creation. This means that sometimes it is set, sometimes it is not. Without digging into ActiveRecord, my best guess is that this is a question of timing.

A: I'm gonna try this solution : https://rails.lighthouseapp.com/projects/8994/tickets/4599-validations-on-nested-attributes-fail-on-nil-foreign-key-on-object-creation

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding Courses together in formula in Crystal Reports I'm creating a custom Transcript for our school and at the bottom of the report I need to add all the courses together for "Credits Earned". Most are 1 point each, but then there are a few that are half points.
I started creating a formula for this and it works just fine, but now it's starting to get confusing with all the different variations the student could have. haha.
Is there a simpler way of doing this? Thanks.
Here's what I have so far:
.5 credit are - Physics, Bio, Chemistry, Personal Project, Debate I/II, Intro to Film, MMUN
If isnull ({Export_20230208T155906_.Comment}) then Count ({Export_20230208T155906_.Course Title})
else
If {Export_20230208T155906_.Course Title} = "Personal Project"
and {Export_20230208T155906_.Comment} = "Biology: .5" then Count ({Export_20230208T155906_.Course Title}) + 1
else
If {Export_20230208T155906_.Course Title} = "Personal Project"
and {Export_20230208T155906_.Comment} = "Chemistry: .5 credit Physics: .5 credit" then Count ({Export_20230208T155906_.Course Title}) + 1.5
else
If {Export_20230208T155906_.Course Title} = "Personal Project"
and {Export_20230208T155906_.Comment} = "Biology: .5 credit Chemistry: .5 credit Physics: .5 credit" then Count ({Export_20230208T155906_.Course Title}) + 2
else
If {Export_20230208T155906_.Course Title} = "IB MYP Intro to Film 1"
and {Export_20230208T155906_.Comment} = "Biology: .5" then Count ({Export_20230208T155906_.Course Title}) + 1
else
If {Export_20230208T155906_.Course Title} = "IB MYP Intro to Film 1"
and {Export_20230208T155906_.Comment} = "Chemistry: .5 credit Physics: .5 credit" then Count ({Export_20230208T155906_.Course Title}) + 1.5
else
If {Export_20230208T155906_.Comment} = "Biology: .5 credit" then Count ({Export_20230208T155906_.Course Title}) + .5
else
If {Export_20230208T155906_.Comment} = "Chemistry: .5 credit" then Count ({Export_20230208T155906_.Course Title}) + .5
else
If {Export_20230208T155906_.Comment} = "Physics: .5 credit" then Count ({Export_20230208T155906_.Course Title}) + .5
else
If {Export_20230208T155906_.Comment} = "Biology: .5 credit Chemistry: .5 credit" then Count ({Export_20230208T155906_.Course Title}) + 1
else
If {Export_20230208T155906_.Comment} = "Biology: .5 credit Physics: .5 credit" then Count ({Export_20230208T155906_.Course Title}) + 1
else
If {Export_20230208T155906_.Comment} = "Chemistry: .5 credit Physics: .5 credit" then Count ({Export_20230208T155906_.Course Title}) + 1
else
If {Export_20230208T155906_.Comment} = "Biology: .5 credit Physics: .5 credit" then Count ({Export_20230208T155906_.Course Title}) + 1
else
If {Export_20230208T155906_.Comment} = "Biology: .5 credit Chemistry: .5 credit Physics: .5 credit" then Count ({Export_20230208T155906_.Course Title}) + 1.5

A: Why not include in the export the number of credits for each course? You can then simply sum the value in that column.
If for some odd reason your database doesn't have that value, it should be added to your database.
That would remove the need for you to assign credit values to courses in your reporting.

A: If you can't access that value, one option is to create your own table and join to it. That would allow you to delegate the responsibility of assigning the correct value to someone on the academic side.
Otherwise, if you must maintain this logic in a Crystal formula, then simply create a detail level formula that returns the number of credits for that row. Then, simply SUM that formula at whatever level of grouping you need (e.g. Student, DEPT, Grand Total). There is no need to accumulate the value using a variable.
Also, the detail-level formula can use OR logic to avoid so many branches. Another excellent mechanism to avoid many IF THEN branches is the use of a SELECT CASE statement.


text:
Q: Custom UITableViewCell does not size properly when Accessory is added I'm having trouble getting a custom UITableViewCell to size properly when an Accessory is set. Why does the Accessory blow the cell sizing up on the initial display? When I scroll, with the accessory set, the sizing corrects itself - however, the initial view is not sizing correctly.
I've watched the WWDC14 (what's new in tableview) video several times and I've read many stackoverflow questions and tried many solutions. I think I have most of the problem solved - cells do resize for dynamic text - but I'm stumped on this strange initial behavior. I am running XCode 6.1.1 deploying to iOS 8.1.
I'm using a storyboard. I have a UITableViewController and custom UITableViewCell. I define constraints in the storyboard and there are no constraint warnings and I see no constraint messages in the console at runtime.
In my UITableViewController viewDidLoad()
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableViewAutomaticDimension

with override
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("TableViewCell", forIndexPath: indexPath) as TableViewCell

    cell.configure(titles[indexPath.row])

    return cell
}

This is my entire custom UITableViewCell
class TableViewCell: UITableViewCell {

@IBOutlet weak var titleLabel: UILabel!

func configure(title: NSString) {
    titleLabel.text = title
    titleLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
}

override func layoutSubviews() {
    super.layoutSubviews()
    titleLabel.preferredMaxLayoutWidth = frame.width
}

}
This is what it looks like when Accessory None is set on the cell

This is what it looks like when I set Accessory Disclosure Indicator on the cell

Again, when I scroll with the accessory set the sizing corrects itself. I've tried adding a vertical constraint to the cell both in storyboard and also by adding all constraints programmatically with no success. Thank you for any thoughts.

A: I've seen this problem too with storyboard designed self-sizing cells. Try adding self.layoutIfNeeded() to an override of didMoveToSuperview in your cell class. I don't know if this is a bug, or we're just missing something that we're supposed to be doing.


text:
Q: Parent process has multiple child and 2 child process has a child process I have a parent process from which i want to create 4 child processes, and 2 of the child processes has one child process each.
I was able to create the 4 child processes from the parent. But when i try to create the child processes for 2 child process i have an infinite loop.
I used the loop for to create the 4 processes and added a condition which is when the second child process and fourth child process are created, create a child process for each one.

*

*Parent has (child1 chil2 child3 child 4)

*Child2 has (child 5 child6)

Source:
#include <stdio.h>
#include <unistd.h>
#include <sched.h>
#include <sys/time.h>
#include <sys/resource.h>

int main(int argc, char **argv)
{
    int i;
    for(i = 0; i <= 3; i++)
    {
        if(fork() == 0)
        {
            printf("process %d and his parent is %d \n",
                getpid(), getppid());

            if(i = 1)
            {
                if(fork() == 0)
                {
                    printf("process %d and his parent is %d \n",
                        getpid(), getppid());
                    break;
                }
            }
        }
    }

    return 0;
}

A: Two issues.  First:
if(i = 1)

You're using = which is an assignment instead of == which compares for equality.  What's actually happening here is that i is being assigned the value of 1 and that value (1) is being evaluated in boolean context, which is always true.  So each child enters the if block and forks its own child.
Use the comparision operator instead, and also check if i is either 1 or 3 if you want the second and fourth children to also fork:
if ((i == 1) || (i == 3))

Second, at the end of the if(fork()==0) block, the child process continues on for the next iteration of the for loop.  So each child will invoke the parent behavior of looping and forking.  This results in many more processes being created than expected.
You need to add an exit statement at the end of this block.  Also, be sure to #include <stdlib.h> for the definition of exit:
if (fork()==0)
{
    ...
    exit(0);
}

One other thing that would be useful: At the end of the loop, have the parent wait for all children to finish.  Otherwise, it may exit before its children and the children would report process ` as the parent
So after these fixes, the code looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sched.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>

int main(int argc, char **argv)
{
    int i;
    for(i = 0; i <= 3; i++)
    {
        if(fork() == 0)
        {
            printf("process %d and his parent is %d \n",
                getpid(), getppid());

            if ((i == 1) || (i == 3))
            {
                if(fork() == 0)
                {
                    printf("process %d and his parent is %d \n",
                        getpid(), getppid());
                    exit(0);
                }
                while (wait(NULL) != -1);
            }
            exit(0);
        }
    }
    while (wait(NULL) != -1);

    return 0;
}

A: You are assigning value 1 to i instead of comparison.
if(i = 1)

should be
if(i == 1)

if you intended to test equality of i and value 1. Assigning to the loop control variable creates an infinite loop when i is always set to value 1.
However, based on your description that states you want to create a child process for the second and fourth of the 4 initial child processes, this does not yet accomplish what you are after.
Given the constraints of 4 original children, you can write
if((i & 1) != 0)

which evaluates to true for values 1 and 3 where the lowest bit of the binary representation of i is set.


text:
Q: TextView bounds must get clipped by rounded ImageView I am trying to achieve this effect.
The blue area is a textView inside a rounded ImageView.

I tried doing it with clipRect, but no succes.
Any other idea?


text:
Q: How to get unique values of every column in PySpark DataFrame and save the results in a DataFrame? Assume that I have a Spark DataFrame as below:
data = [("A", "A", 1), \
    ("A", "A", 2), \
    ("A", "A", 3), \
    ("A", "B", 4), \
    ("A", "B", 5), \
    ("A", "C", 6), \
    ("A", "D", 7), \
    ("A", "E", None), \
    ]

columns= ["col_1", "col_2", "col_3"]
df = spark.createDataFrame(data = data, schema = columns)

I want to get a list of unique entries for every column and save the results in a DataFrame. The output will be:

Column_Name
Unique_Values

col_1
['A']

col_2
['A', 'B', 'C', 'D', 'E']

col_3
[1, 2, 3, 4, 5, 6, 7, Null]

Any idea how to do that?

A: One way to achieve is:

*

*Introduce a dummy column with some const value.

*Group by this dummy column and collect all columns as set.

*Since the result is "summary" data, it wont hurt to convert to Pandas. The dataframe transpose is little too much in Spark < v3.4 where melt() function is not available.

*Transpose the pandas dataframe.

sdf = sdf.withColumn("dummy", F.lit("1")) \
         .groupBy("dummy") \
         .agg(*[F.collect_set(c).alias(c) for c in sdf.columns]) \
         .drop("dummy") \

[Out]:
+-----+---------------+---------------------+
|col_1|col_2          |col_3                |
+-----+---------------+---------------------+
|[A]  |[C, E, B, A, D]|[1, 5, 2, 6, 3, 7, 4]|
+-----+---------------+---------------------+

pdf = sdf.toPandas() \
         .T \
         .reset_index() \
         .rename(columns={0: "Unique_Values", "index": "Column_Name"})
[Out]:
  Column_Name          Unique_Values
0       col_1                    [A]
1       col_2        [C, E, B, A, D]
2       col_3  [1, 5, 2, 6, 3, 7, 4]

As you can see, the None or null is not included. To include it, you need to do some extra processing: convert columns to type string. If you want to retain the original types, then you need to track each column and cast them appropriately.
for c in sdf.columns:
  sdf = sdf.withColumn(c, F.col(c).cast("string")).na.fill("_NULL_")

and replace back:
pdf["Unique_Values"] = pdf["Unique_Values"].apply(lambda x: [None if v == "_NULL_" else v for v in x])

Full example:
data = [("A", "A", 1), \
    ("A", "A", 2), \
    ("A", "A", 3), \
    ("A", "B", 4), \
    ("A", "B", 5), \
    ("A", "C", 6), \
    ("A", "D", 7), \
    ("A", "E", None), \
  ]

columns= ["col_1", "col_2", "col_3"]
sdf = spark.createDataFrame(data = data, schema = columns)

for c in sdf.columns:
  sdf = sdf.withColumn(c, F.col(c).cast("string")).na.fill("_NULL_")

sdf = sdf.withColumn("dummy", F.lit("1")) \
         .groupBy("dummy") \
         .agg(*[F.collect_set(c).alias(c) for c in sdf.columns]) \
         .drop("dummy") \

pdf = sdf.toPandas() \
         .T \
         .reset_index() \
         .rename(columns={0: "Unique_Values", "index": "Column_Name"})

pdf["Unique_Values"] = pdf["Unique_Values"].apply(lambda x: [None if v == "_NULL_" else v for v in x])

[Out]:
  Column_Name                Unique_Values
0       col_1                          [A]
1       col_2              [C, E, B, A, D]
2       col_3  [3, None, 1, 2, 5, 4, 7, 6]


text:
Q: Git Commit adds line breaks that wasn't commited I've been working fine deploying profile permissions on git via VSC.
Recently I started to have some issues where I check the changes stage those, check again and see like 10 lines modified.
Then when i do the commit, Just before the commit is accepted,if I undo last commit and see the file, it changes and adds line breaks ending up with structure like this
<fieldPermissions>
        <editable>true</editable>
        <field
    >ObjectName.FieldName</field>
        <readable>true</readable>
    </fieldPermissions>

This of course is a major issue since we lost tracking of the changes commited but I just can't seem to find a reason why this is ocurring and I end up when I do my PR with 5k+ lines of modification.
I've reinstalled VSC, Node to a stable versions. And this are my configurations for xml files.
{
    "salesforcedx-vscode-apex.advanced.enable-completion-statistics": true,
    "salesforcedx-vscode-apex.enable-semantic-errors": true,
    "salesforcedx-vscode-apex.java.home": "C:\\Program Files\\Java\\jdk-11.0.13",
    "salesforcedx-vscode-core.retrieve-test-code-coverage": true,
    "redhat.telemetry.enabled": true,
    "git.autofetch": true,
    "explorer.confirmDelete": false,
    "git.confirmSync": false,
    "editor.foldingMaximumRegions": 50000,
    "xml.symbols.maxItemsComputed": 50000
}

Last 2 values I modified the standard I had of 5k since I thought that could be the issue. But it still the issue persists.
This seems to be happening only with profiles which makes me think this has to be something to do with large xml files but I can't figure out what.
UPDATE: It has to do something with hooks since when I do my commit on command line it detects correctly the lines but when I do it via the VSC button on source control pannel all hell break loose. But still have no idea exactly how to fix this.


text:
Q: C++ non-copyable lambda behaves copyable? Why does the following code compile?
#include <memory>
#include <vector>

int main()
{
    std::vector<std::unique_ptr<int>> uncopyableStuff;
    for(int i = 0; i < 5; ++i)
        uncopyableStuff.emplace_back(std::make_unique<int>(i));
    auto lambda = [uncopyableStuff = std::move(uncopyableStuff)](){};
    static_assert(std::is_copy_constructible<decltype(lambda)>::value);
}

It seems to me that lambda is uncopyable, because when I try to copy it like:
auto copy = lambda;

This gives me a compile error (as I would expect). Is there some exception for lambda's and copy constructability traits?
See link for godbolt example:
https://godbolt.org/z/GByclH
EDIT:
What is the correct way to find out whether a lambda will compile when attempted to copy. I geuss I'm not interested in the theoretical copy constructibility of a given callable, but a detection of successful copy construction. It still seems very strange to me that the vector copy constructor is defined in this way.

A:
Is there some exception for lambda's and copy constructability traits?

No. If you test std::is_copy_constructible<std::vector<std::unique_ptr<int>>>::value you will find that it's also true.
The reason is that std::vector has an accessible and non-deleted copy constructor even if the element type is noncopyable. If the copy constructor is instantiated, it will fail to compile, but that's outside the immediate context, and thus cannot be detected by the std::is_copy_constructible trait.
It might be tempting to make the copy constructor of std::vector SFINAE on the copy constructibility of the element type, but I believe it will break a type that stores a vector of the type itself as a member: struct Node { std::vector<Node> children; }, since in this case, the copy constructibility of Node and std::vector<Node> would be mutual dependent.


text:
Q: Not using the else I'm try to not use the else in the code and just the if. But when I run it and enter "Q" it say error of converting in the total += Convert.ToInt32(input);. Is there a way around this?
do
{
    Console.Clear();
    Console.WriteLine("Enter a number or Q to quit", input);
    input = Console.ReadLine();

    if (input.ToUpper() == "Q")
    {
        Console.WriteLine("Press any key to continue");
        Console.ReadKey();
    }
    else
    {
        total += Convert.ToInt32(input);
        numbersEntered++;
        average = ((double)total / numbersEntered);
        Console.WriteLine("Total: {0}\t Numbers Entered: {1}\t Average: {2}\t", total, numbersEntered, average);
        Console.ReadKey();
    }
}

while (input.ToUpper() != "Q");

A: Try using break; to stop the loop so you don't need the else.
do{
    Console.Clear();
    Console.WriteLine("Enter a number or Q to quit", input);
    input = Console.ReadLine();
    if (input.ToUpper() == "Q"){
        Console.WriteLine("Press any key to continue");
        Console.ReadKey();
        break;
    }
    total += Convert.ToInt32(input);
    numbersEntered++;
    average = ((double)total / numbersEntered);
    Console.WriteLine("Total: {0}\t Numbers Entered: {1}\t Average: {2}\t", total, numbersEntered, average);
    Console.ReadKey();
} while (input.ToUpper() != "Q");

A: Use TryParse to test if the input is a numeric. Here's an example for int (you'll need to define the out variable yourself).
else if (Int32.TryParse(input,out inputVal) {


text:
Q: display image in Javascript and HTML I'm currently working on a school exercise and I can't find how to do one thing.
So I have this :

When I click on one of the case, the right image (image is a Mario picture for example) is supposed to display but the problem is that I only get the name of it. I would like to know what I have to change to be able to show the pics instead of the name.
Please, let me know what I should change in my code, I'm a beginner. Thank you very much!
Here is my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title></title>

A: I think you need to put the url in your css inside the quotes. And if that doesn't help, use the full address instead of a relative one.

A: Use background: url("images/memoryBg.png") no-repeat;
instead of background: url(images/memoryBg.png) no-repeat;


text:
Q: Spring Boot and Mongo - how to query by nested property I have the following problem - how to query by nested property with @Query?
My Product class (document in Mongo):
@Document(collection = "products")
public class Product {

    @Id
    private String id;

    @DBRef
    private ProductProperties properties;

How does it look in Mongo:
{
    "_id" : ObjectId("5d5e78d20e8e3d0006079a84"),
    "companyId" : "1234",
    "properties" : {
        "$ref" : "properties",
        "$id" : ObjectId("5df8dd2331ea7b4a9384335b")
    },
    "calendar" : [
        {
            "startDate" : ISODate("2019-09-04T22:00:00.000Z"),
            "endDate" : ISODate("2019-09-09T22:00:00.000Z")
        }
    ],
    "_class" : "org.abc.def"
}

ProductProperties class (document in Mongo):
    @Document(collection = "product_properties")
    public class ProductProperties {
        @Id
        private String id;
(...)

How does it look in Mongo:
   {
    "_id" : ObjectId("5df8dd2331ea7b4a9384335b"),
    "brand" : "offer Brand_1",
    "model" : "offer model_1",
    "modelNumber" : "offer model number_1",
    "size" : {
    ...
}

My Spring repository:
public interface ProductRepository extends MongoRepository<Product, String> {

    @Query("{'properties.id': ?0 }")
    List<Product> findByPropertiesId(String propertiesId);

I've tried also:
List<Product> findByProperties_id(String propertiesId)

or
@Query("{'properties.$id': ?0 }")
        List<Product> findByPropertiesId(ObjectId propertiesId);

but WITHOUT success. DO you know what's wrong?
When I invoke:
public List<Product> findProductsByPropertiesId(String properties) {
        if (properties == null) {
            throw new IllegalArgumentException("onFind: propertiesId should not be null.");
        }
        return productRepository.findByProperties_Id(properties);
    }

I get empty list:(
Maybe there is impossible to do that via Query?

A: @Query("{'properties.$id': ?0 }")
List<Product> findByPropertiesId(ObjectId propertiesId);

public List<Product> findProductsByPropertiesId(String properties) {
    if (properties == null) {
        throw new IllegalArgumentException("onFind: propertiesId should not be null.");
    }
    return productRepository.findByPropertiesId(new ObjectId(properties));
}


text:
Q: struts 1 throws org.hibernate.TransientObjectException I am trying to add activity auditing to my struts 1 application. I change an object and then I want to create a row in my auditing table that refers to the changed object. I am getting TransientObjectException because I've changed the referent object. I tried flushing the session, but that didn't solve it and I'm not sure why.
merchant.setTrusted(false);
merchantDAO.saveOrUpdate(merchant);
// trying to resolve org.hibernate.PropertyValueException: not-null property references a null or transient value: com.rc.model.ActivityAudit.user
SessionManagerFactory.getSessionManager(DatasourceType.M).getSession().flush();

ActivityAuditManager.addActivityAudit("Set merchant to untrusted", merchant, userAccount);

where ActivityAuditManager.addActivityAudit() is:
public static void addActivityAudit(String action, Merchant merchant, IMerchantUserAccount user) {
    ActivityAudit activityAudit = new ActivityAudit(merchant, action, user, new Date());
    activityAuditDAO.saveOrUpdate(activityAudit);
}

The exception I'm getting is:
org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

but as far as I can tell I am.
ETA mapping:
<class name="com.rc.model.ActivityAudit" table="activity_audit" discriminator-value="0">
...
    <many-to-one name="merchant" class="com.rc.model.Merchant"
                 column="merchantid" unique="false" not-null="true" cascade="none"/>
...

I tried cascade="all" and cascade="save-update" and neither improves the situation.
ETA: See my own answer, below, but cascade="save-update" actually did fix it.

A: There were two problems. The second one, which was uncovered when I fixed the first, initially obscured the fact that cascade="save-update" actually did resolve this issue.
In this question,
object references an unsaved transient instance - save the transient instance before flushing
user nanospeck posted a method for debugging that helped me a lot.
I didn't notice the second problem until I used that debugging method and examined the Exception in more detail.


text:
Q: Moving app to GAE Context:
We have a web application written in Java EE on Glassfish + MySQL with JDBC for storage + XMPP connection for GCM CCS upstream messaging + Quartz scheduler library. Those are the main components of the app.
We're wrapping up our app development stage and we're trying to figure out the best option for deploying it, considering future scalability, both in number of users and their geographical location (ex, multiple VMS on multiple continents, if needed). Currently we're using a single VM instance from DigitalOcean for both the application server and the MySQL server, which we can then scale up with some effort (not much, but probably more than GAE).
Questions:
1) From what I understood, Cloud SQL is replicated in multiple datacenters across the world, thus storage-wise, the geographical scalability is assured. So this is a bonus. However, we would need to update the DB interaction code in the app to make use of Cloud SQL structure, thus being locked-in to their platform. Has this been a problem for you ? (I haven't looked at their DB interaction code yet, so I might be off on this one)
2) Do GAE instances work pretty much like a normal VM would ? Are there any differences regarding this aspect ? I've understood the auto-scaling capability, but how are they geographically scalable ? Do you have to select a datacenter location for each individual instance ? Or how can you achieve multiple worldwide instance locations as Cloud SQL does right out of the box ?
3) How would the XMPP connection fare with multiple instances ? Considering each instance is a separate VM, that means each instance will have a unique XMPP connection to the GCM CCS server. That would cause multiple problems, ex if more than 10 instances are being opened, then the 10 simultaneous XMPP connections limit cap will be hit.
4) How would the Quartz scheduler fare with the instances ? Right now we're saving the scheduled jobs in the MySQL database and scheduling them at each server start. If there are multiple instances, that means the jobs will be scheduled on each instance; so if there are multiple instances, the jobs will be scheduled multiple times. We wouldn't want that.
So, if indeed problems 3 & 4 are like I described, what would be the solution to those 2 problems ? Having a single instance for the XMPP connection as well as a single instance for the Quartz scheduler ?

A: 1) Although CloudSQL is a managed replicated RDBMS, you still need to chose a region when creating an instance. That said, you cannot expect the latency to be great seamlessly globally. You would still need to design a proper architecture to achieve that.
2) GAE isn't a VM in any sense. GAP is a PaaS and, therefore, a runtime environment. You should expect several differences: you are restricted to Java, PHP, GO and Python, the mechanisms GAE provide do you out-of-the-box and compatible third-parties libraries. You cannot install a middleware there, for example. On the other hand, you don't have to deal with anything from the infrastructure standpoint, having transparent high-availability and scalability.
3) XMPP is not my strong suit, but GAE offers a XMPP service, you should take a look at it. More info: https://developers.google.com/appengine/docs/java/xmpp/?hl=pt-br
4) GAE offers a cron service that works pretty well. You wouldn't need to use Quartz.
My last advice is: if you want to migrate an existing application, your best choice would probably be GCE + CloudSQL, not GAE.
Good luck!
Cheers!


text:
Q: Open another application inside a fragment This is a follow up question to this question:
Open another app within a fragment
I'm creating an application with a single activity with a SlidingTabsLayout and every tab is a fragment. Is there a way to open an installed application and just run it as it is inside one of the tabs? The other application is just a single activity which I want to display in my tab as it is. The answer in the question above said I can't do it, but maybe in the 1.5 years that passed since the question was asked, something has changed?

A:
Is there a way to open an installed application and just run it as it is inside one of the tabs

No.

The answer is the question above said I can't do it

The answer is correct.


text:
Q: nth-of-type not behaving as expected HTML

&#10003 Everything is OK!

asfdasdf

asdfasdf

asfasdf

asdfasdf

asfasdf

asdfasdf

CSS
.small:nth-of-type(1) {
    background-color: black;
    border-style: solid;
    border-width: 15px;
    border-color: black;
}

.small:nth-of-type(2) {
    background-color: red;
}

In this example: http://jsfiddle.net/CNBsY/2/  I can't quite figure out why nth-of-type(1) doesn't select anything while nth-of-type(2) selects the first thing I want to select. Does anybody understand why this is happening?

A: That's because it's nth-of-type, not nth-of-class.
First div in your HTML does not have small class, so there is no element matching both .small and nth-of-type(1).

A: The pseudo selector :nth-of-type() selects the type of tag.
In your example it is a div. As you set the selector on the class (.small:nth-of-type(1)) the css is aplied only if the first div has that class which isn't the case.

A: Try this :
HTML

    &#10003 Everything is OK!

asfdasdf

asdfasdf

asfasdf

asdfasdf

asfasdf

asdfasdf

CSS
li:nth-of-type(1) {
    background-color: black;
    border-style: solid;
    border-width: 15px;
    border-color: black;
}

li:nth-of-type(2) {
    background-color: red;
}

It's a better semantic.


text:
Q: Convert Field of View value, to CSS3D perspective value If I would like to have a camera, with 60° fov, then how to calculate the CSS3D perspective value?
perspective: ?;
perspective-origin: center center;

I've found a description about, how to calculate the projection matrix from perspective value, but I still don't really understand it: http://www.w3.org/TR/css-transforms-1/#perspective-matrix-computation
So if I have a given Field of View, and I know the element's offsetWidth/offsetHeight, then how should I calculate the needed perspective value?
And where are the near plane and the far plane?

A: I asked a similar question a few years ago and got the response below.  The article linked has since changed, so I'm quoting the text since it no longer exists in the article (but there may still be other useful info).
If I'm reading it correctly, you have a pyramid with the base at [perspective px] away from the viewer.  So if you want a 60° fov, you have a 30° triangle from the center to the corners and you need to find the length of the adjacent edge:
Math.pow( w/2*w/2 + h/2*h/2, 0.5 ) / Math.tan( 30 * Math.PI / 180 )

I think ;)  It yields a perspective of 968 for a 1000x500 view, which seems about right from having played randomly with -webkit-perspective a fair bit

The CSS 3D Transforms Module working draft gives the following explanation:

perspective(<number>)
specifies a perspective projection matrix. This matrix maps a viewing cube onto a pyramid whose base is infinitely far away from the
  viewer and whose peak represents the viewer's position. The viewable
  area is the region bounded by the four edges of the viewport (the
  portion of the browser window used for rendering the webpage between
  the viewer's position and a point at a distance of infinity from the
  viewer). The depth, given as the parameter to the function, represents
  the distance of the z=0 plane from the viewer. Lower values give a
  more flattened pyramid and therefore a more pronounced perspective
  effect. The value is given in pixels, so a value of 1000 gives a
  moderate amount of foreshortening and a value of 200 gives an extreme
  amount. The matrix is computed by starting with an identity matrix and
  replacing the value at row 3, column 4 with the value -1/depth. The
  value for depth must be greater than zero, otherwise the function is
  invalid.


text:
Q: Is there any way to know whether a reader is associated with a command object or not I have a layer where function openconnection closeconnection ... are written .
I have a big business logic file which has many data reader has used.
My problem is this that the data-readers has not been closed.
So the number of connection at in my app pool keep increasing.
Is there any wany to find is there any reader is associated with the commnad and if then in the closeconnection function I can check command object and close the reader.
Since we are using ref-cusor of oracle to read the data. And as far I know this type of cursor is not managed by oracle.
It is very much difficult for me to check all the bll.
Kindly suggest.
Edit1:
I have also some confusion about dispose if I dispose the command object weather or not the reader dispose will be called. Or If I dispose the Connection object the reader will be disposed.


text:
Q: Gulp require "Cannot Find Module" even though it exists I've encountered a strange issue and I'm running out of ideas to try. I'm trying to learn JS unit testing, so am setting up gulp with Jasmine. The problem is, when my gulp build runs I get:
Error: Cannot find module 'gulp-jasmin'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/Users/path/to/project/gulpfile.js:5:19)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)

Now, I know this is a common issue, but I've tried everything that typically resolves these. My package.json:
{
  "name": "boxfish",
  "version": "0.3.0",
  "devDependencies": {
    "gulp": "^3.9.0",
    "gulp-jasmine": "^2.0.1",
    "gulp-livereload": "^3.8.0",
    "gulp-notify": "^2.2.0",
    "gulp-uglify": "^1.2.0"
  }
}

And my ./node_modules folder:

I've tried doing an rm -rf ./node_modules to clear it out and then followed by npm install to load fresh copies. I can clearly see module their, and all the other modules load just fine, it's just this one.
My gulpfile.js looks like this:
/**
 * Dependencies
 *****************/
var gulp        = require('gulp');
var jasmine     = require('gulp-jasmin');
var notify      = require('gulp-notify');

/**
 * Unit Testing
 *****************/

gulp.task('test', function () {
  gulp.src('./tests/*.js')
    .pipe(jasmine())
    .on('error', notify.onError({
      title: 'Jasmine Test Failed',
      message: 'One or more tests failed, see the cli for details.'
    }));
});

When I run gulp test, I get the missing module error. If I comment out the task and comment the require for gulp-jasmin, it will require the other modules without a hitch.
Any ideas what I can do to get it to recognize this module? Is there some sort of autoload or registration that it is suppose to do with npm that I can check?

A: Are you positive it's not just a typo? Both your gulpfile and the error make it look like you mistyped gulp-jasmine (missing the 'e' on the end):
Error: Cannot find module 'gulp-jasmin'

var jasmine     = require('gulp-jasmin');


text:
Q: KeyboardDatePickerExample: Onchange set date as moment.utc() in State, when rendering display as moment.local() in React import React, { useState } from "react";
import { moment } from "moment";
import {
  KeyboardDatePicker,
  MuiPickersUtilsProvider
} from "@material-ui/pickers";
import MomentUtils from "@date-io/moment";
function KeyboardDatePickerExample(props) {
  const [selectedDate, handleDateChange] = useState(null);

  const handleDateChangeMethod = (date) => {
    //store in state moment date as date.utc();
    handleDateChange(date.utc());
    // But this is not setting as date.utc(); instead storing as date.local()
  };

  return (
    <MuiPickersUtilsProvider utils={MomentUtils}>
      <KeyboardDatePicker
        value={selectedDate && selectedDate.local()}
        onChange={handleDateChangeMethod}
        format="DD/MM/YYYY HH:mm"
        ampm={false}
      />
    </MuiPickersUtilsProvider>
  );
}

export default KeyboardDatePickerExample;

// value={selectedDate && selectedDate.local()}

In the above component "value" date.local() is mutating my state value from date.utc() to date.local()

I should only display in date.local() but I wanted to store the date in date.utc() format

In the state I cannot use another state variable to store date as date.utc()

A: import React, { useState } from "react";
import { moment } from "moment";
import {
  KeyboardDatePicker,
  MuiPickersUtilsProvider
} from "@material-ui/pickers";

Blockquote: Setting setDefault UTC will solve the issue

 moment.tz.setDefault("UTC")
import MomentUtils from "@date-io/moment";
function KeyboardDatePickerExample(props) {
  const [selectedDate, handleDateChange] = useState(null);

  const handleDateChangeMethod = (date) => {
    //store in state moment date as date.utc();
    handleDateChange(date.utc());
    // But this is not setting as date.utc(); instead storing as date.local()
  };

  return (
    <MuiPickersUtilsProvider utils={MomentUtils}>

Blockquote: binding value as it is without converting it to local when displaying.

      <KeyboardDatePicker
        value={selectedDate}
        onChange={handleDateChangeMethod}
        format="DD/MM/YYYY HH:mm"
        ampm={false}
      />
    </MuiPickersUtilsProvider>
  );
}

export default KeyboardDatePickerExample;


text:
Q: CPU and memory utilization discrepancies for ejabberd and Riak clusters on AWS I'm running a 2-node ejabberd cluster (behind an elastic load balancer) that in turn connects with a 3-node Riak cluster (again, via an ELB) on AWS. When I load-test the platform via Tsung (creating 0.5 million user registrations), I notice that the CPU utilization for the ejabberd nodes differs amongst themselves by around 10%. For the Riak nodes, the CPU and memory utilization amongst nodes differs by around 5%.
The nodes are of identical configuration, so wondering what could be leading to these non-trivial differences in utilization. Can anyone throw some light here please / educate me?
Is it due to the load balancer? Or a network impact? I expect that once a cluster is formed (either of ejabberd or of Riak KV), the nodes are all identical in behavior, especially for ejabberd where the entire database is replicated across the cluster.
Not that these differences are a problem, but would be good to understand the inner workings of the clusters here...
Many thanks.

A: Elastic Load Balancing mechanism

*

*DNS server uses DNS round robin to determine which load balancer node in a specific Availablity Zone will receive the request

*The selected load balancer checks for "sticky session" cookie

*The selected load balancer sends the request to the least loaded instance

And in greater details:
Availability Zones (unlikely your case)
By default, the load balancer node routes traffic to back-end instances within the same Availability Zone. To ensure that your back-end instances are able to handle the request load in each Availability Zone, it is important to have approximately equivalent numbers of instances in each zone. For example, if you have ten instances in Availability Zone us-east-1a and two instances in us-east-1b, the traffic will still be equally distributed between the two Availability Zones. As a result, the two instances in us-east-1b will have to serve the same amount of traffic as the ten instances in us-east-1a.
Sessions (most likely your case)
By default a load balancer routes each request independently to the server instance with the smallest load. By comparison, a sticky session binds a user's session to a specific server instance so that all requests coming from the user during the session will be sent to the same server instance.
AWS Elastic Beanstalk uses load balancer-generated HTTP cookies when sticky sessions are enabled for an application. The load balancer uses a special load balancer–generated cookie to track the application instance for each request. When the load balancer receives a request, it first checks to see if this cookie is present in the request. If so, the request is sent to the application instance specified in the cookie. If there is no cookie, the load balancer chooses an application instance based on the existing load balancing algorithm. A cookie is inserted into the response for binding subsequent requests from the same user to that application instance. The policy configuration defines a cookie expiry, which establishes the duration of validity for each cookie.
Routing Algorithm (less likely your case)
Load balancer node sends the request to healthy instances within the same Availability Zone using the leastconns routing algorithm. The leastconns routing algorithm favors back-end instances with the fewest connections or outstanding requests.
Source: Elastic Load Balancing Terminology And Key Concepts
Hope it helps.


text:
Q: How to change the word's color in string The picture I load is my target:

This is my code in mathematica
    StringTemplate["``Ratio is ``,``Ratio is ``,``Ratio is ``,"][
 Sequence @@
  Flatten@Transpose[{{Style["red", Red, Bold],
      Style["green", Green, Bold], Style["blue", Blue, Bold]}, {0.1,
      0.2, 0.3}}]]

But the result is

What's problem in my code?Can Anybody give some advice?

A: Row@MapThread[
  Row[{Style[#1, ToExpression@#1, Bold], " Ratio is ", #2, #3}] &,
  {{"Red", "Green", "Blue"}, {0.1, 0.2, 0.3}, {", ", ", ", ""}}]

A: TemplateApply[
 StringTemplate["`` Ratio is ``, `` Ratio is ``, `` Ratio is ``"],
 Flatten[Transpose[{ToString[#, StandardForm] & /@ {Style["Red", Red,
       Bold], Style["Green", Green, Bold],
      Style["Blue", Blue, Bold]}, {0.1, 0.2, 0.3}}]]]

A: As per How to join Styled strings
str = StringJoin[
  ToString[Style["red ", Red], StandardForm],
  "Ratio is 0.1, ",
  ToString[Style["green ", Green], StandardForm],
  "Ratio is 0.2, ",
  ToString[Style["blue ", Blue], StandardForm],
  "Ratio is 0.3"]

StringQ[str]

True


text:
Q: Direction of unit normal defined from surface implicit function If $F$ is the implicit function of a three dimensional surface $\partial S$ , the unit normal vector function $\mathbb{\hat{n}}(x,y,z):=\nabla F(x,y,z)/\|\nabla F(x,y,z)\|$ at every point $(x,y,z)\in \partial S$ is always inward or outward ?

A: $\nabla F$ points in the direction of $F$ increasing. If that is inward or outward depends then on your definitions.
Example.
If $F(x,y,z)=x^2+y^2+z^2$ then $F=1$ represents a sphere of radius $1$ centred at the origin. $\nabla F=2(x,y,z)$ points outwards, because $F$ increases in that direction ($F=1+\varepsilon$ is a larger sphere for $\varepsilon>0$, external to $F=0$).
On the other hand, if $F(x,y,z)=-x^2-y^2-z^2$ then $F=-1$ represents the same sphere as before, but $F=-1+\varepsilon$ is a smaller sphere for $\varepsilon>0$, hence $\nabla F=-2(x,y,z)$ points inwards.


text:
Q: Javascript or operator not working var strExt  = GetAttributeFromItemTable(itemTable, "Ext", "FileType");

I did a alert for strExt and it resolves.
    if (strExt!='wav')
    {
     // this works
    }
if (strExt!='wav' || strExt!='mp3')
{
// this does not work.
}

A: || says: if any condition is true, It'll return true, without looking at the ones after it.
So true || false is true, false || true is true.
In your case, you say "if strExt is not equal to wav and is not equal to mp3, then execute the code". In case that one of them is true, it executes.
I'm thinking that you're looking for the && symbol. The logical and says "I'll return true only if every condition is true" - when it hits a false, it returns false.
What I think your code should look like:
if (strExt!='wav' && strExt!='mp3')

A: Your logic is flawed:
if your variable strExt was equal to 'wav' it would not be equal to 'mp3', and versa-visa.
Please explain your desired results more clearly.
I think what you're trying to say is something like (neither 'wav' nor 'mp3'):
if ( !( strExt == 'wav' || strExt == 'mp3' ) )

which is logically equivalent to (not 'wav' and not 'mp3'):
if ( strExt != 'wav' && strExt != 'mp3' ) )

A: I would expect the result of the second expression to be True regardless of the value of the string strExt (any extension is either not equal to "wav" or not equal to "mp3"). What do you expect?
Are you certain you don't mean a Boolean AND instead of an OR ("extension is neither 'wav' nor 'mp3'")?

A: just add the another parenthesis, like so:
if ((strExt!='wav') || (strExt!='mp3'))
 {
     // this does not work.
 }

A: The logic behind this makes no sense wouldn't you want to do:
if ((strExt !== "wav") && strExt !== "mp3") {

}

AND instead of OR makes more sense in this situation.

A: If you want to get into second if, when strExt is not equal to both 'wav' and 'mp3' you need to use an && operator.
if (strExt!='wav' || strExt!='mp3')

when strExt='wav' => strExt!='wav' = false;  strExt!='mp3' = true => false or true = true and gets into if statement and is the case is similar when strExt='mp3'  .


text:
Q: Ruby two comparisons in unless Im ruby beginner and very frustrated with this code:
unless ((f[-4..-5] == '.png') || (f[-4..-5] == '.jpg'))

Somehow the second comparison is not recognized by ruby! Whats wrong?

A: I think you should use f[-4..-1] instead of f[-4..-5].
Or you can use regular expression:
unless f =~ /\.(png|jpg)$/

or use String#end_with?:
unless f.end_with?('.png', '.jpg')

A: f[-4..-5] would be an empty string, which will never match '.png'. So the second term of your disjunction will never be evaluated.
If you are conditioning by the file extension, then you may do this:
case File.extname(f)
when ".png", ".jpg"
else
  ...
end

A: How is below :
ext_nm = File.extname(f)
unless [".png", ".jpg"].include? ext_nm


text:
Q: What's the deal with the "Quantum Gravity Research Organization"? www.quantumgravityresearch.org
It looks like they're an independent research group, but the main guy behind it, Klee Irwin, sounds crackpotty:

Klee guides the team in developing emergence theory, a new, first principles quantum gravity theory that unifies space, time, energy, matter, information and consciousness.

But the rest of the people associated it seem like they produce actual papers, but I'm not really capable of judging how legit they are.  Does anyone know anything about this?


text:
Q: Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: javax.swing.JFrame.setContentPaneel http://puu.sh/hLNH1/74b40dff89.png
I have tried googling this issue for many hours been asking around on Skype I haven't found the solution yet. So I think it's time to ask professional developers what's going on.
Alright so I get the following error:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: javax.swing.JFrame.setContentPaneel
    at Vb0301.main(Vb0301.java:11)

I've just started to learn Java for my study and the cody provided in the Puush link is a direct copy from the book.
I know it has something to do with:
frame.setContentPaneel(new Paneel() );

So I tried switching it from that to:
frame.setContentPane(new Paneel() );

But at this point I get new errors link: http://puu.sh/hLNVU/c760502ca9.png
It's starting to annoy the heck out of me to setup IDE in the first place the last couple of days have been errors after errors...
I hope someone is able to help I've been looking around here but didn't find the specific question. I hope to get replies soon, thanks in advance.
Naomi,

A: You are using the wrong class name. Paneel does not exist, it should be Panel instead.
Also, the method you are calling is called setContentPane(). See the reference for more information.
Edit: As you can see in the comments on this answer, the problem was in the Panel class (but not as stated above).
Panel has to extend JPanel to allow it to be added to the frame.

A: It should be frame.setContentPane(new Paneel()) - more on JFrame.
Here Paneel should be a container like JPanel. More on JPanel- JPanel

A: It's because it's not allowed to add a JFrame with setContentPane(), it expects a container like it checks here :
 /**
 * Checks that the component is not a Window instance.
 */
private void checkNotAWindow(Component comp){
    if (comp instanceof Window) {
        throw new IllegalArgumentException("adding a window to a container");
    }
}


text:
Q: mongodb spring data save I'm quite new to MongoDB and Spring Data, I'm doing some code to improve my skills.
I think I'm doing all right, but I have a problem (a strange one).
I've a small example, let me say instead of classic Hello Word, I'm coding a small expense report tool.
This is the TestMain App
package com.jaex.model;

import java.util.ArrayList;
import java.util.Currency;
import java.util.Date;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

import com.jaex.repositories.ExpenseCategoryRepository;
import com.jaex.repositories.ExpenseRepository;
import com.jaex.repositories.ProjectRepository;
import com.jaex.repositories.UserRepository;

public class Main {

    public static void main(String[] args) {
        ApplicationContext ctx = new GenericXmlApplicationContext("spring-config.xml");

        ExpenseCategoryRepository ur = (ExpenseCategoryRepository) ctx.getBean("expenseCategoryRepository");
        ExpenseRepository ur1 = (ExpenseRepository) ctx.getBean("expenseRepository");
        UserRepository userrepo = (UserRepository) ctx.getBean("userRepository");
        ProjectRepository prjRepo = (ProjectRepository) ctx.getBean("projectRepository");

        Project p = prjRepo.findByProjectId("123456");
        if (p == null) {
            p = new Project("123456", "The Project", true, new Date());
            p = prjRepo.save(p);
        }

        ExpenseCategory c1 = ur.findByName("Dinner");
        if (c1 == null) {
            c1 = new ExpenseCategory("Dinner", "");
            c1 = ur.save(c1);
        }

        User user = userrepo.findByUserId("freeman");
        if (user == null) {
            user = new User("freeman");
            user.setLastName("Doe");
            user.setFirstName("J.");

            user  = userrepo.save(user);

        }

        List<ExpenseReport> a = new ArrayList<ExpenseReport>();
        for (int i = 0; i < 10; i++) {
            ExpenseReport er  = new ExpenseReport();
            er.setExpenseNumber("ER" + System.currentTimeMillis());
            er.setComment("a comment");
            er.setName("a name");
            er.setSubmittedBy(user);

            List<ExpenseEntry> list = new ArrayList<ExpenseEntry>();

            double amount = (Math.random()) + Math.random();

            list.add(new ExpenseEntry(p.toLite(),  amount, Currency.getInstance("EUR"), c1.toLite()));

            er.addToTotal(amount);

            amount = (Math.random()) + Math.random();

            list.add(new ExpenseEntry(p.toLite(),  amount,Currency.getInstance("USD"), c1.toLite()));
            er.addToTotal(amount);

            amount = (Math.random()) + Math.random();

            list.add(new ExpenseEntry(p.toLite(),  amount,Currency.getInstance("USD"), c1.toLite()));
            er.addToTotal(amount);

            er.setExpenses(list);

            a.add(er);

        }

        try {

            ur1.save(a);
        } catch (Throwable t) {
            System.err.println(t.getMessage());
        }

        System.out.println(ur1.count());

    }

}

As you can see I'm doing a small "for" just to put some data inside.
The issue is that anyway I got just one record every Main execution. (this was an improved with the old mongodb I just got ONE record, no way to put more than one)
this is the Expense class
package com.jaex.model;

import java.io.Serializable;
import java.util.List;

import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

    @Document(collection = "ExpenseReports")
    public class ExpenseReport implements Serializable {

    private static final long serialVersionUID = 2244814936573280668L;

    @Id
    private ObjectId id;

    @Indexed(unique = true)
    private String expenseNumber;

    private String name;
    private String comment;

    private double total;

    private User submittedBy;

    private List<ExpenseEntry> expenses;

    public ExpenseReport() {
        this.total = 0;
    }

    public String getExpenseNumber() {
        return expenseNumber;
    }

    public void setExpenseNumber(String expenseNumber) {
        this.expenseNumber = expenseNumber;
    }

    public String getName() {
        return name;
    }

    public String getComment() {
        return comment;
    }

    public User getSubmittedBy() {
        return submittedBy;
    }

    public List<ExpenseEntry> getExpenses() {
        return expenses;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public void setSubmittedBy(User submittedBy) {
        this.submittedBy = submittedBy;
    }

    public void setExpenses(List<ExpenseEntry> expenses) {
        this.expenses = expenses;
    }

    @Override
    public String toString() {
        return String.format("ExpenseReport [id= %s, expenseNumber=%s, name=%s, comment=%s, submittedBy=%s, expenses=%s]",
                getId(), expenseNumber, name, comment, submittedBy, expenses);
    }

    public double getTotal() {
        return total;
    }

    public void setTotal(double total) {
        this.total = total;
    }

    public void addToTotal(double total) {
        this.total = this.total + total;
    }

    public ObjectId getId() {
        return id;
    }

    public void setId(ObjectId id) {
        this.id = id;
    }

}

All repositories
extends CrudRepository<T, ObjectId>

JDK: 1.8

MongoDB: MongoDB shell version: 3.2.4

Spring data: 1.9.1.RELEASE (org.springframework.data/spring-data-mongodb)

Any help?
Got it!
The issue is not with ER class but with User.
If I use the Indexed annotation doesn't work, without works.
Now I've two questions:

*

*Why there is no exception ?

*The user if you have a look at the main, is just inserted one time, then used over and over.... so where is my error?

Below the code class
package com.jaex.model;

import java.io.Serializable;

import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.IndexDirection;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

@Document (collection  = "Users")
public class User implements Serializable, Comparable<User>{
    private static final long serialVersionUID = 990052324161479791L;

    @Id
    private ObjectId id;

    @Indexed(unique = true, direction = IndexDirection.ASCENDING, useGeneratedName = true)
    private String userId;

    private String firstName;
    private String lastName;

    public User() {

    }

    public User(String userId) {
        this.userId = userId;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public int compareTo(User o) {
        return o.getUserId().compareTo(userId);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((userId == null) ? 0 : userId.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        User other = (User) obj;
        if (userId == null) {
            if (other.userId != null)
                return false;
        } else if (!userId.equals(other.userId))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return String.format("User [userId=%s]", userId);
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

}

Thanks

A: setExpenseNumber in your forloop uses System.currentTimeInMillis which is still so fast that it could probably have the same ER number for the whole list and your document expects unique expenseNumber. Why not try to use the index i as suffix  to be sure its unique and check if this works?


text:
Q: Laravel resource collection, return data from resource to collection I'm using Laravel v6 and writing Resource and resource collection. I would like to use some data from the resource inside the resource collection. For example, I have the following UserResource and UserCollection:
class UserResource extends JsonResource
{
    public $data = 0;
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $this->data + = 5;
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
    public function getAdditionalData(){
            return $this->data;
    }
}

class UserCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'data' => $this->collection,
            'additional-data' => [
                (new UserResource(null))->getAdditionalData(),
            ],
        ];
    }
}

I want to return some data calculated in the resource and use it in the resource collection. The value that i'm receiving is 0 while I'm expecting 5. How can I return this data from the resource into the collection?

A: You have not called the resource's toArray() function, so your data is not being incremented. Try calling the function first, for example:
$userResource = new UserResource(null);
$userResource->toArray(); // Returns an array. Your data is incremented here
$additionalData = $userResource->getAdditionalData(); // what you actually want

It would help if you provided a bigger picture of what you are trying to do.

A: **Use this method in Collection below toArray Method**

public function toArray($request) {
    return $this->collection;
}

public function withResponse($request, $response) {
    $jsonResponse = json_decode($response->getContent());
    $jsonResponse->settings = array_values(ResponseManager::getResult('', $this->status, $this->message, $this->code))[0];

    if (isset($jsonResponse->links) && isset($jsonResponse->meta)) {
        unset($jsonResponse->links);
    }

    $response->setContent(json_encode($jsonResponse));
}


text:
Q: 1-1 relation load with bookshelf I have 2 tables something likes;
Property {id, name, address_id}
Address {id, city, country, add_line_1, ...}

I linked Property to Address via address_id.
How can I config Bookshelf model to load Property with associated Address via address_id.
I'm trying  something likes;
PROPERTY = bookshelf.Model.extend({
   tableName: 'PROPERTY',

   address: function() {
       return this.hasOne(ADDRESS, 'address_id');
   }
});

ADDRESS = bookshelf.Model.extend({
   tableName: 'ADDRESS',

   property: function() {
       return this.belongsTo(PROPERTY);
   }
});

The error: "Unknown ADDRESS.address_id in where clause"

A: From the documentation the hasOne() expects the foreign key to be ON THE OTHER table. So try changing your models to:
PROPERTY = bookshelf.Model.extend({
   tableName: 'PROPERTY',

   address: function() {
       return this.belongsTo(ADDRESS, 'address_id');
   }
});

ADDRESS = bookshelf.Model.extend({
   tableName: 'ADDRESS',

   property: function() {
       return this.hasOne(PROPERTY);
   }
});

And query using, by example:
PROPERTY.fetchAll({withRelated:'address'}).then((a)=>
  {console.log(a.toJSON())});


text:
Q: How to set height and width of Date Picker Dialog How can i set width and height of date picker dialog dynamically. It appears on full screen not in required area.

A: yo go his XML file and set the height and width.


text:
Q: What are "safe point functions" as alluded to in the Go source code? In the file runtime/proc.go of the Go source code, there are many comments referring to safe point functions, which appear to be related to points in time where it is safe to garbage collect. However, I could not find any definitions of these functions.
What are safe point functions, what are they used for, and what are some examples of such functions?

A: Here is everything I could dig up on this topic.
I found some discussion about Go's GC safepoints here.
It looks like safe points (as used in the Go implementation) are effectively the same as the traditional definition of a safe point:

key points where the GC can track what all variables and registers
  hold

Another user on the same thread mentions that the GC

folds the preemption points into the stack checks during function
  prologs

and that the source for this claim is the following: https://github.com/golang/go/issues/10958
According to this post on the golang-dev mailing list, safepoints are also called "call sites".
To gain some insight into the nature of Go's safepoints, I think it's important to look at the evolution of its GC. This post  mentions the following:

Prior to Go 1.5, Go has used a parallel stop-the-world (STW)
  collector.
Go 1.5 introduces a concurrent collector.

Another answer to that question mentions:

As of Go 1.7, the one remaining source of unbounded and potentially
  non-trivial stop-the-world (STW) time is stack re-scanning.

As of 1.8, it looks like worst-case stop-the-world times have been improved.
Also, here is the current implementation of Go's garbage collector. If you read through the comments, you'll see that it is a non-generational mark-sweep collector. You can read more about this here: https://blog.plan99.net/modern-garbage-collection-911ef4f8bd8e#.udz1kjk3b
Finally, here is an old post by Gil Tene on the golang-dev mailing list which motivates the use of a moving garbage collector. He claimed (at the time in 2012) that Go was using a "conservative, non-relocating collector" and he discussed the characteristics of safepoints which would permit a long-running garbage collector.
While Go's garbage collector has been moving away from long pauses and is now a "concurrent, tri-color, mark-sweep collector", it's still a non-generational GC. It also looks like Go's GC is building on GC ideas from the 70s rather than modern, enterprise approaches.
It looks like Go's notion of a safepoint is more in line with the traditional notion of a safepoint rather than a safepoint with modern qualities which permit generational garbage collection.


text:
Q: Cannot create a multiple polygon in tcpdf I am using tcpdf to create a pdf using php and mysql, i have successfully created one polygon using below code but when am trying to create the second polygon it is unable to create and the previous polygon also disappears
How to create the multiple polygons?
First Polygon
$pdf->StarPolygon(94, 110, 39, 90, 3, 0, 1, 'CNZ');
$pdf->SetLineStyle( array( 'width' => 1, 'color' => array(145,191,56)));
$pdf->Image('@'.$imgdata1, 50, 70, 90, 90, '', '', 'C', false, 300, '', false, false, 0, false, false, false);
$pdf->StopTransform();

Second Polygon
$pdf->StarPolygon(147, 58, 29, 90, 3, 0, 1, 'CNZ');
$pdf->SetLineStyle( array( 'width' => 1, 'color' => array(145,191,56)));
$pdf->Image('@'.$imgdata2, 25, 130, 70, 60, '', '', 'R', false, 300, '', false, false, 0, false, false, false);
$pdf->StopTransform();

A: You should add StartTransform before code for second polygon:
// Secodn polygon
$pdf->StartTransform();
$pdf->StarPolygon(147, 58, 29, 90, 3, 0, 1, 'CNZ');
$pdf->SetLineStyle( array( 'width' => 1, 'color' => array(145,191,56)));
$pdf->Image('@'.$imgdata2, 25, 130, 70, 60, '', '', 'R', false, 300, '', false, false, 0, false, false, false);
$pdf->StopTransform();


text:
Q: angular and asp.net mvc delete with post I currently have the following grid on my page:

{{cartItem.Title}}

    @using (Html.BeginForm("Delete", "MyController", FormMethod.Post))
    {
        @Html.AntiForgeryToken()
        <input type="submit" value="Delete" id="DeleteBtn" name="DeleteBtn" class="btn blue" />
    }

Our users have requested that the delete happen with a post to the server, so we setup a form in the grid, i'm not sure if that's the best way to go about it.  also how would we pass in the Id (cartItem.Id) of the item to delete to the action? Is it common to have a form in each row like this? otherwise we can convince the users to do it through client side.


text:
Q: How to display 3 lines from a text file in char arrays using strtok in C I have a homework and i can't really find where the problem with the code is. The main problem is to read 3 lines from a text file and use them to build a binary tree. The text file has these lines:
7
2 4 0 0 7 0 0
3 5 6 0 0 0 0

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
  const char* p;
  const char* v1;
  const char* v2;
  char buf[100];
  FILE *fptr = fopen("sd.in", "r");
  if (fptr == NULL) {
    printf("Failed to open file\n");
    return -1;
  }
  if(fgets(buf,100,fptr)!=NULL)
    p=strtok(buf,"\n");
  printf("%s\n", p);
  while((p = strtok(NULL,"\n"))!=NULL)
  {
    printf("%s\n", p);
  }

  fclose(fptr);
  return 0;
}

This is my code so far. When i compile it, it only shows the first line with number 7. How could i display all the lines? Thank you very much!
UPDATE of the code. Right now i can display the first and the second line but without number 2. I want to store the second line in v1 and the third line in v2.
        if(fgets(buf,100,fptr)!=NULL)
         p=strtok(buf,"\n");
         printf("%s\n", p);
       if((p = strtok(buf,"\n"))!=NULL && fgets(buf,100,fptr)!=NULL)
       v1 = strtok(NULL,"\n");
       printf("%s\n ",v1);

A: Here is the working code.
Cannot use char pointer for v1 and v2 since memory address of buffer is not constant.  They need to be stored into arrays like you mentioned in the title but your description says the other thing. Need to skip lines with just newline characters.
#include <stdio.h>
#include <string.h>
int
main(void)
{
   FILE *fp;
   char caBuffer[50];
   char caV1[50], caV2[50], caCnt[2];
   const char *cp;
   const char *cpDelimeter = "\n";
   int iLoopCnt = 0;

   if( ( fp = fopen( "xyz.txt", "r" ) ) == NULL ){
      printf( "failed opening\n" );
      return 1;
   }

   while( fgets( caBuffer, sizeof(caBuffer), fp ) != NULL ){
      //skip the lines with newline char
      if( strlen(caBuffer) > 1 )
      {
         cp = strtok(caBuffer, cpDelimeter);

         if( cp != NULL ){
            switch( iLoopCnt++ )
           {
              case 0:
                  strcpy(caCnt, cp );
                  break;
              case 1:
                  strcpy(caV1, cp );
                  break;
              case 2:
                  strcpy(caV2, cp );
                  break;
            }
        }
    }
}

printf("caCnt = %s\n", caCnt );
printf("caV1  = %s\n", caV1 );
printf("caV2  = %s\n", caV2 );

fclose(fp);

return 0;

}

Updates were made per suggestion below.
Thanks.


text:
Q: PDFkit - different page size on production machine I have a Django project in which I generate PDF from HTML with PDFkit.
On my local machine I see the pdf just fine but on production machine the generated pdf page is a little bigger.
The html is correct and identical on both machines.
The OSes are the same (ubuntu 14.04).
Checked all the packages versions and they are the same.
My pdf generating code is:
options = {'page-size': 'A2', 'margin-top': '0in', 'margin-right': '0in', 'margin-bottom': '0in', 'margin-left': '0in'}
pdf_location = '/...../executive_summary.pdf'
pdfkit.from_string(my_template.render(context_dict), pdf_location, options=options, css='/....../executive_summary.css')

wkhtmltopdf is the latest
pdfkit==0.6.1
The screenshots are attached. Where else can be the problem?


text:
Q: Writing a VBA macro that evaluates an IF statement in a specified cell range in SheetA that sets the text color of two cell ranges in SheetB I have gotten this to run but it is not working properly.  (Interestingly, only one cell in my specified SheetB is being changed to the red font upon running.) My assumption is that I am not specifying which sheets and/or ranges to use at the proper locations in the script, or that my syntax is plainly just wrong. Thank you for your help.
Sub RedBold()
'Sets color of current cell to red
With ActiveCell.Font
    .Color = -16776961
    .TintAndShade = 0
End With
ActiveCell.Font.Bold = True
End Sub

Option Explicit

Sub LowInventory()

Dim cell As Range
Dim deltaQ As Range

'Assign specific cell range in the Inventory Quantities sheet to variable          deltaQ
Set deltaQ = Sheets("Inventory Quantities").[E3:E190]

'Conditional loop that checks for low deltaQ values and assigns a color to   two specific cell ranges in the Inventory Costs, Sources sheet
For Each cell In deltaQ.Cells
    'if deltaQ value is less than 2
    If cell.Value < 2 Then
        'Specify cell ranges in specific sheet to be affected by low inventory check loop
        Sheets("Inventory Costs, Sources").Range("B3:B190, C3:C190").Select
        Call RedBold
    End If
Next

End Sub


text:
Q: Centralized function to delegate form onSubmit to Flux Actions I have a react app with many different forms I'm looking to not have to write the same code over and over for each form, and I'm looking for a simple way to centralize the onSubmit() handlers for all forms. From a central location I can trigger the specific Flux action that will trigger an ajax call.
I'm picturing one function that takes care of all form requests.
function (event) {
  event.preventDefault()
  var $elm = $(event.target)
  var d = {}
  d.method = $elm.attr('method')
  d.action = $elm.attr('action')
  d.data = $elm.serialize()
  console.log(d)
}

From here I can check the action and method and make a switch for each possibility.
Does this make sense within the Flux architecture?

A: You will anyway need to collect data from specific components, so you will have to write individual functions for it, but the rest of task like sending an action can be done in the onSubmit function of a parent component. So delegate all onSubmit events in children components with data to the onSubmit functions of parent component via props.
You can also add an identifier like we do as constants in dispatchers, to identify particular onSubmit event and then in parent component use switch statements to send particular actions based on identifier.
If there's a use case, I guess it makes sense.


text:
Q: Should I create two different gulp tasks? This is a pretty general question - but as a newcomer to taskrunners I'm a little confused about the workflow.  I understand that you can create a task that does things like uglify and minify but what about debugging while you write the code? Specifically, if I need to view my js source to identify issues, what would be my workflow?  Do I create a different task that doesn't effect my javascript files for developing, then run the task that does everything when I know things are working properly?

A: It's hard to answer in context of the parts of your workflow you hint at but don't mention, but for uglification/minification one good solution would be sourcemaps, or more specifically, since you're asking about gulp: gulp-sourcemaps.
From their docs:
gulp.task('javascript', function() {
  gulp.src('src/**/*.js')
    .pipe(sourcemaps.init())
      .pipe(plugin1())
      .pipe(plugin2())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('dist'));
});

Those plugins (plugin1, etc) would be things like uglify, but do need to be sourcemaps-compatible.
All this allows your browser to find its way back from concatenated, minified code, all the way to the correct source files.
As a footnote, the alternative you already mention can also work okay: compose your build tasks in a way that you can serve source (or at least: unminified) files in development, and provide minified code in staging and production.
As with all such (somewhat) broad questions: it depends.


text:
Q: Is there a difference between A1435 and A1425 chargers? I own a A1502 MacBook Pro Retina 13" display. It came with a 60W charger model A1435. I want to get a case for the charger, I see there are lots of accessories available for A1425 and many spare parts suppliers list A1435 and A1425 together. Are those compatible?

*

*What is the actual difference between A1435 and A1425?

*Are those compatible when it comes to their specification? Can both of them charge A1502 MacBook?

*Are those dimensionally compatible? Can same accessories fit both models?

Thanks in advance for the answers!

A: The A1425 is the Macbook itself, the A1435 is the charger. So they are "compatible" in the sense that the accessories of the cases just add the identifier of the macbook that the charger came with.
So it is the same thing, once described by it's model number and once by the macbook that it was shipped with. You can buy accessories with either identifier and they will fit.


text:
Q: Can't create Multi-AZ Aurora RDS Instance When I restore a MySQL snapshot, I'm given the option to make the new instance Multi-AZ. However for some reason when I restore to Aurora, the "Multi-AZ Deployment" selection is disabled.
I thought possibly this meant it was automatically enabled. However when I go to the running instance details, it specifically lists Multi-AZ: "No".
Is there something I'm missing? Is there some other step I need to do to make Aurora Multi-AZ?

A: Multi-AZ doesn't mean the same thing in Aurora as it does for MySQL and MariaDB.  With Aurora, any replica in the cluster can take over for the master on failure (though the selection is based on priority, so it isn't just a randomly selected replica, if there is more than one replica), and the storage is already/always multi-AZ in Aurora because that's a core part of the Aurora design.  So, Aurora can be "converted" to Multi-AZ.
Apparently, that's the only way it is done when creating an Aurora instance from a snapshot, based on this:

You can migrate a DB snapshot of an Amazon RDS MySQL DB instance to create an Aurora DB cluster.
...
You can migrate either a manual or automated DB snapshot. After the DB cluster is created, you can then create optional Aurora Replicas.
http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Aurora.Migrate.RDSMySQL.html

If you create a multi-AZ Aurora cluster without a snapshot, that's all that happens -- a master and a replica are created.  In that case, you can actually delete the replica and make it non-multi-AZ, which is a different process than what's involved with MySQL or MariaDB.
"Create a cluster" -- as used in the quote, above -- is a potentially confusing term, since you would naturally assume a cluster means two or more, but in fact an Aurora cluster can technically be a "cluster" of just one instance.  Every Aurora instance is part of exactly one cluster.  One instance is the primary (master) and any additional instances are replicas.

If the DB cluster doesn't contain any Aurora Replicas, then the primary instance is recreated during a failure event.
http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Aurora.Managing.html#Aurora.Managing.FaultTolerance


text:
Q: Where do I set the username and password for an OpenVPN server? I'm having trouble finding where to edit the password of a VPN user that I setup over 5 years ago. I don't know a lot about this stuff and surprised I ever got this working many years ago.
It's a Centos server running OpenVPN - PPTP server whereby the users connect with a simple username and password.
The username/password are not the users of the server- I remember they were stored literally in plain text in a file in the form of {username}:{password}.
I can't remember where this file is stored! Any ideas how to find it?
My /etc/openvpn/server.conf file looks like this:
local xx.xx.xx.xx
port 1194
proto udp
dev tun
tun-mtu 1500
tun-mtu-extra 32
mssfix 1450
ca /etc/openvpn/easy-rsa/2.0/keys/ca.crt
cert /etc/openvpn/easy-rsa/2.0/keys/server.crt
key /etc/openvpn/easy-rsa/2.0/keys/server.key
dh /etc/openvpn/easy-rsa/2.0/keys/dh1024.pem
server 10.8.0.0 255.255.255.0
push "route 10.104.17.0 255.255.255.0"
route 192.168.5.0 255.255.255.0
client-config-dir /etc/openvpn/client-configs
ifconfig-pool-persist /etc/openvpn/ipp.txt
keepalive 5 30
comp-lzo
persist-key
persist-tun
status 1194.log
verb 5
daemon

A: Are you sure your OpenVPN server is serving your PPTP connections?
I ask as officially OpenVPN does not support the PPTP protcol and you would likely need to be using an openvpn client to connect to your openvpn server instead.
Quote from OpenVPN manual:

Does OpenVPN support IPSec or PPTP?
There are three major families of VPN implementations in wide usage today: SSL, IPSec, and PPTP. OpenVPN is an SSL VPN and as such is not compatible with IPSec, L2TP, or PPTP.

Additionally if openVPN was using a username/password based authentication I would expect to see an authentication configuration directive in your config file to assign the login method; as OpenVPN defaults to using certificate based authentication.
My advice: If you are sure you are running PPTP, check if you are running a pptpd daemon that serves these connections. If you are using openvpn, could you update your question with a client configuration file as example, it would help us pinpoint the login methods you are using, but judging by this configuration it is likely certificate based. More information on key generation for your setup can be found here:
https://openvpn.net/easyrsa.html , essentially you generate a key, download this and distribute it to any of your users alongside an ".ovpn" configuration file and your public ca certificate.
If you have specific questions about configurations for either pptpd or openvpn feel free to ask.

A: Here's how you create a new OpenVPN user:
Go to /etc/openvpn/easy-rsa/2.0
Then, edit with your favorite editor the vars file.
when you finish save the file and run:
source ./vars

Then, run:
./build-key-pass username

Here's an example output:
[root@centolel 2.0]# ./build-key-pass itaitikal
Generating a 1024 bit RSA private key
.++++++
...........++++++
writing new private key to 'itaitikal.key'
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [IL]:
State or Province Name (full name) [SH]:
Locality Name (eg, city) [TelAviv]:
Organization Name (eg, company) [none]:
Organizational Unit Name (eg, section) [changeme]:
Common Name (eg, your name or your server's hostname) [itaitikal]:
Name [itaitikal1]:
Email Address [mail@host.domain]:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from /etc/openvpn/easy-rsa/2.0/openssl-1.0.0.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'IL'
stateOrProvinceName   :PRINTABLE:'SH'
localityName          :PRINTABLE:'TelAviv'
organizationName      :PRINTABLE:'none'
organizationalUnitName:PRINTABLE:'changeme'
commonName            :PRINTABLE:'itaitikal'
name                  :PRINTABLE:'itaitikal1'
emailAddress          :IA5STRING:'mail@host.domain'
Certificate is to be certified until Feb 20 15:44:56 2027 GMT (3650 days)
Sign the certificate? [y/n]:y

1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

Make sure that the CN name is unique, otherwise you won't be able to sign the certificate.
Next, browse to /etc/openvpn/easy-rsa/2.0/keys and take the username.crt, username.key that you've just created and the server's ca.crt, zip them and send them to the user.
The user will have to place them somewhere and point to them in his .ovpn file.
I wrote an article about this whole procedure, so feel free to check it out:
http://www.geek-kb.com/install-and-configure-openvpn-centos-6-x/


text:
Q: What is the importance of unitary (in-)equivalent representations? Say we have two representations of the observables from an abstract $C^*$-algebra $\mathcal A$ on two Hilbert spaces $H_1$ and $H_2$, i.e. consider the maps $\pi_1,\pi_2: \mathcal A \longrightarrow \mathcal B(H_1), \mathcal B(H_2)$.
If these representations are unitary equivalent, this means that there exists a unitary $U$ such that $\pi_2(A) = U\pi_1(A)U^{-1}$ for all $A\in \mathcal A$. Similarly, if an abstract state is normal with respect to both of these representations, i.e. can be represented by a density matrix on the respective Hilbert space, we find $\rho_2 = U\rho_1 U^{-1}$. And so all predictions we make are the same, irrespective of the Hilbert space on which we represent these observables and states.
However, even for unitary inequivalent representations we can find a unitary $U$ (as the Hilbert spaces are isomorphic) such that $\rho^\prime=U\rho_1 U^{-1}$ and $A^\prime = U\pi_1(A)U^{-1}$ on $H_2$, but with $\rho_2\neq \rho^\prime$ and $\pi_2(A)\neq A^\prime$.
But all expectation values and hence all predictions agree with our first representation. And isn't this the only important thing? So what is the significance of unitary (in-)equivalent representations? It seems that I am missing a crucial thing here.

A: When the algebra has a non trivial center, then it is easy to understand how inequivalent representations pop out and what is the physical difference between them.
Consider a $C^*$ (or simply $*$) algebra $\cal A$ with non trivial center and two unitary representations $\pi_i: {\cal A} \to \mathfrak{B}(H)$, $i=1,2$, on the same Hilbert space $H$. Finally assume that the two representations are irreducible. If $a=a^* \in \cal A$ is an element of the center (e.g. a Casimir operator in the universal enveloping algebra associated to a Lie group), the operators  $\pi_i(a)$ must be proportional to the unit element $\pi_i(a)= c_iI$ for a pair of reals $c_i$ (Schur's lemma). These values are physical observables and can be measured. The choice of these values distinguishes between the two representations which are unitarily inequivalent: Every unitary intertwiner operator should transform $c_1I$ to $c_2I$ and this is not possible if the two constants are different. However both operators represent the same central element $a$. Both representations are physically admissible, in principle, but physics chooses the value of $a$ and declares which representation is the right one. If $\pi_1$ produces the wrong value of $c_1$, every unitary map from $H$ to $H$ gives rise to a new representation $\pi'_1= U\pi_1U^{-1}$ as you say, but it is  not able to change the wrong value of $c_1$. The new representation is physically admissible, but it is not the right one.
The values of the constants representing the center are fixed by the algebraic pure  states. (Pure states gives rise to irreducible GNS representations.)
Indeed, if $\omega: {\cal A}\to \mathbb{C}$ is an algebraic pure state and $\pi_\omega$ is its GNS representation and $a$ stays in the center, then
$$\omega(a)= \langle \Psi_\omega, \pi_\omega(a)\Psi_\omega\rangle=  \langle \Psi_\omega, c_aI \Psi_\omega\rangle= c_a.$$
The nature of the difference of inequivalent unitary representations of algebras with trivial center (as an infinite dimensions Weyl algebra) is more subtle. A recent book on that is the one  by Schmudgen.


text:
Q: Sun CodeModel: Annotation within annotation How can a create an annotation like
@Table(name="batch", uniqueConstraints=
    @UniqueConstraint(columnNames = {"compound_id", "batch_Number"}))

using suns codemodel package?
My problem is the @UniqueConstraint Annotation withn @Table.

A: This is embarrassing. You just need to use .annotationParam instead of .param.
JAnnotationUse uniqueConstraint = tableAnnotation.annotationParam("uniqueConstraints", UniqueConstraint.class);
JAnnotationArrayMember uniqueFields = uniqueConstraint.paramArray("columnNames");
for (String fieldName : uniqueConstraints) {
    uniqueFields.param(fieldName.trim());
}

don't now how i could oversee this method...


text:
Q: Trying to get X11 over SSH working: Connection refused by server Using Cygwin/X11
Launch command in local Xterm for SSH:

xterm -e ssh -Y -v -l MyUser myserver.mydomain.com &

After logging in, I've run

setenv DISPLAY myclient.mydomain.com:0.0

When I try to launch an Xterm I get:

Xlib: connection to "myclient.mydomain.com:0.0" refused by server
Xlib: No protocol specified
xterm Xt error: Can't open display: myclient.mydomain.com:0.0

On another server I have no issues launching new xterm windows without running the setenv.
"echo $DISPLAY" on that server returns "localhost:11.0"
If I try using that on the other server I get the following:

$ setenv DISPLAY localhost:11.0
$ xterm
xterm Xt error: Can't open display: localhost:11.0

I figure I'm missing something pretty basic, but I'm not sure what it is.

EDIT:
Tried not setting the $DISPLAY:
Here's the results

$ echo $DISPLAY
DISPLAY: Undefined variable.
$ xlogo
Error: Can't open display:

Still not working :-(

EDIT Again:
The above was on a straight login.  I did not remove the $DISPLAY or change it before trying to run xlogo

A: Don't set the display on the remote side.  By using the -Y parameter on SSH, it will set up a listener on the (remote)local side that gets tunneled back to the local side.
You should be able to do this:
local$ ssh -Y user@remote
remote$ xlogo

...and the xlogo will pop up.
Edit: this assumes that the display is set up on the local system first, ie:
local$ xlogo

...should work before you perform the ssh, as ssh just plugs the forward back to whatever the originating session thinks is the correct display.  This is useful, since you can carry your display through multiple ssh sessions:
local$ ssh remote
remote$ ssh further
further$ xlogo

...should work.

A: David pretty much nailed one half of the equation -- the ssh mechanism automatically takes care of setting up the xauth authentication and defining your display, so don't override that manually by setting the DISPLAY variable yourself.
The other issue is that some ssh daemons on the destination side of things are configured to deny X forwarding even if you ask politely.
ssh -v will tell you if the server declines to allow X forwarding; you can also look at the sshd_config to see if it disallows X forwarding.

A: you must be using X11 R5. With that revision, your X11 windows must be running on the server. Then issue the following cmds -
printenv | grep 'X11'
printenv | grep 'ssh'

if you find that X11 windows is running, then -
xterm -e 'ssh remote.machine.domain
xhost + remote.machine.domain
setenv DISPLAY local.machine.domain:0.0
xterm &

When you do issue the above commands, if xterm pops out a GUI, then aha, your X11 environment is configured to run with ssh. If not, check the latest revision for X11 is installed.
If this does not work, drop me a note. I will look into the logs. ok!.

A: You should do after login a
echo $DISPLAY

Probably you will get something like "localhost:11.0". This means ssh will automatically forward any connection going to localhost display 11 to your X11 server on the laptop. So, just start your program.
When you modify the DISPLAY you tell the program to connect directly to your laptop (without encryption). In order that to work you should allow it on your laptop (do something like "xhost +myclient.mydomain.com).
Also, when you do "ssh -Y", on the server the X server should listen to a TCP port 6000+n where n is the display number assigned to your trusted connection. You can check by doing:
netstat -l -t

then check if there is anything open after port 6000 (for example 6011). If, for any reason the DISPLAY is set wrong (maybe to your colleague machine?) then try to do:
setenv DISPLAY localhost:11.0

A: From man ssh:
-X   Enables X11 forwarding. This can
     also  be specified on a per-host
     basis in a configuration file.


text:
Q: Options for managing Smart Array P400 on an ESXi 5 host I'm about to install ESXi 5.0U2 on a RAID10 exposed by an HP Smart Array P400i.  (The server is a DL580 G5.)  However, I notice that the ROM-based utility lacks many of the features of the browser-based HP Array Configuration Utility, but the latter only runs in Windows or Linux distros.
I can't do any PCI passthrough on this server, so as far as I can see I can't just install ACU into a guest OS and expect to get anywhere.
The only way I can see to use ACU is to have an installation of Windows on a separate drive to boot to when I need to do array management, but this is very inconvenient and also does nothing for monitoring.
Do I have any better options for managing the hardware RAID on such a host?

A: There are several good options for handling this nowadays. The HP BIOS-based RAID utility is only meant for quick and simple logical drive configuration. For more complex arrangements, you need to use one of the following:

*

*The HP SmartStart and Service Pack for ProLiant bootable disks allow fine-grained array configuration, as they boot the server into an offline Linux configuration environment.

*The new Array Configuration Utility Offline CD is a 100mb bootable CD and a quicker way of doing the initial configuration. It boots into either an ACU command line tool or a full ACU graphical interface.

*A Linux boot disk with the hpacucli tool was my old approach before I start making use of the bootable HP CD's.
My typical VMware ESXi install would look like below, where I'd carve out a 16GB or 18GB logical drive for ESXi to live on, then give the rest to VMFS:
/opt/hp/hpacucli/bin # ./hpacucli ctrl all show config

Smart Array P410i in Slot 0 (Embedded)    (sn: 5001438010A99E30)

   array A (SAS, Unused Space: 0  MB)

      logicaldrive 1 (18.0 GB, RAID 1+0, OK)
      logicaldrive 2 (392.1 GB, RAID 1+0, OK)

      physicaldrive 1I:1:1 (port 1I:box 1:bay 1, SAS, 146 GB, OK)
      physicaldrive 1I:1:2 (port 1I:box 1:bay 2, SAS, 146 GB, OK)
      physicaldrive 1I:1:3 (port 1I:box 1:bay 3, SAS, 146 GB, OK)
      physicaldrive 1I:1:4 (port 1I:box 1:bay 4, SAS, 146 GB, OK)
      physicaldrive 2I:1:5 (port 2I:box 1:bay 5, SAS, 146 GB, OK)
      physicaldrive 2I:1:6 (port 2I:box 1:bay 6, SAS, 146 GB, OK)

   SEP (Vendor ID PMCSIERA, Model  SRC 8x6G) 250 (WWID: 5001438010A99E3F)

Once you have ESXi installed, you should be adding the HP CIM drivers and HP Utilities packages. These will give you HP-specific reporting to VMware and the HP ILO and array command-line configuration utilities.
This will give you the ability to fully manage your storage array from the VMware command line.
Note:
PCI-passthrough of a Smart Array controller works when the server hardware supports it. The system in question is too old and doesn't support VMware VMDirectPath I/O. In newer ProLiant systems, I'm fully able to pass a Smart Array controller or otherwise to a virtual guest.