text:
Q: creating arrays of objects in javascript I'm learning javascript coming from a .NET background. I have a question about how to deal with arrays of objects, creating and manipulating doesn't seem as easy/obvious as .NET.
Often in .NET code I use structs (c#) or structures (VB.NET) for managing simple value constructs, for example (in VB.NET):
    Public Structure WidgetsStruc
        Public Name As String
        Public LocX As Integer
        Public LocY As Integer
    End Structure
    Private myWidgets As New WidgetsStruc
    myWidgets.LocX = 35
    myWidgets.LocY = 312
    myWidgets.Name = "compass"
    Messagebox(myWidgets.Name)              ' shows 'compass'
    ...

in javascript from the research I have done there isn't anything quite equivalent, although you can use an object and 'push' it onto an array like the below which works:
    var widget = new Object();
    var widgetTemplates = new Array();
    widgetTemplates.push(widget);
    widgetTemplates[0].name = "compass";
    widgetTemplates[0].LocX = 35;
    widgetTemplates[0].LocY = 312;
    alert(widgetTemplates[0].name);          // also shows 'compass'

Maybe I'm not used to working in a more loosely typed language but the JavaScript above doesn't seem optimal (eg. having to 'push' an object without a declared structure into the array and initializing the variables afterwards, plus 'pop' and 'slice' for removing).
Have I got this right? Is there a better or easier way of declaring & using arrays of objects? I also looked into JSON but not exactly sure how to use that for manipulating user defined objects in an array.
As a JavaScript n00b - thanks for any guidance!

A: You can use object and array literal notation:
var widgetTemplats = [
    {
        name: 'compass',
        LocX: 35,
        LocY: 312
    },
    {
        name: 'another',
        LocX: 52,
        LocY: 32
    }
]

For simple things like this, the lack of enforced structure is fairly normal. If you do want more enforced structure, or to attach behaviours to your objects, you should look in to classes in JavaScript:
var Widget = function(name, x, y) {
    this.name = name;
    this.LocX = x;
    this.LocY = y;
};

var widgets = [
    new Widget('compass', 35, 312),
    new Widget('another', 52, 32)
];


text:
Q: Async Batch jobs stuck? We have been using Async Batch Jobs for a while now, to process PDF files without converting them to images first. This worked fine, up till last night. After creating the job, the job never seems to get finished. We had a job stuck for 11 hours, after canceling the job I tried some other PDF jobs and they all get stuck.
We upload the files to GCP Storage, start an AsyncBatchAnnotateFilesRequest with Feature_DOCUMENT_TEXT_DETECTION, we then use operation.Wait() so that it check the jobs status every 45 seconds to check whether it's done yet. We do this using the Go library.
Any one else seeing this issues or know what could cause this?

A: I had this happen to me starting last night, guessing something changed on Google's side. What worked for me was making sure the directory/files it was outputting to didn't exist first.
Iterable<Blob> blobs = storage.list(outputBucketName,
    BlobListOption.prefix(outputFolderName.replaceAll("^[^/]*/", ""))).iterateAll();
for (Blob blob : blobs) {
    blob.delete(Blob.BlobSourceOption.generationMatch());
}

EDIT: Actually maybe it was just completely unrelated, google didn't provide details but said it should no longer be stuck now:
https://groups.google.com/forum/#!topic/cloud-vision-discuss/p0PbNQ2KMGg

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pandas merge to list by column Is there a way to merge two pandas dataframes so that same column names end up as list entries in the merged df?
For example:
import pandas as pd
df_1 = pd.DataFrame({'A' : [1,2,3], 'B' : [4,5,6], 'C' : [7,8,9]})
df_2 = pd.DataFrame({'A' : [1,2,3], 'B' : ['a','b','c'], 'C' : ['d','e','f']})

df_merged = df_1.merge(df_2, on='A') # This should be changed, I guess

results in:
   A  B_x  C_x B_y C_y
0  1    4    7   a   d
1  2    5    8   b   e
2  3    6    9   c   f

I was hoping for:
   A  B       C
0  1  [4, a]  [7, d]
1  2  [5, b]  [8, e]
2  3  [6, c]  [9, f]

So it is similar to the groupby.apply(list) function, but for merging dataframes.

A: IIUC we can do groupby with axis=1
s=df_1.merge(df_2, on='A').set_index('A')
s=s.groupby(s.columns.str.split('_').str[0],axis=1).agg(lambda x : x.tolist()).reset_index()
s
   A       B       C
0  1  [4, a]  [7, d]
1  2  [5, b]  [8, e]
2  3  [6, c]  [9, f]


text:
Q: Using a sieve to find number of divisors but only for n^2 Normally I use the following code to find the number of divisors up until a given n (tau function):
L=[0 for i in range(N+1)]
for i in range(1,N+1):
    for j in range(i, N+1,i):
        L[j]+=1
print L

Which outputs
[0, 1, 2, 2, 3, 2, 4, 2, 4, 3, 4]

But what if I want to output divisors for n^2 instead? Right now it's looking at n=0,1,2,3,4,5,6,7,8,9,10, but I want to change it so it's actually looking at 0,1,4,9,16,25,36,49,64,81,100 (no need to mess with any other numbers).
The output should look like:
[0, 1, 3, 3, 5, 3, 9, 3, 7, 5, 9]

A: Depending on how big n is, Nolen's answer may suffice (to be fair your original code isn't optimized to begin with). However, it is worth noting what n**2 is. If we can factorize a number, say 10, we get that:
10    = (2**1)*(5**1)
10**2 = (2**(1+1))*(5**(1+1)) = (2**2)*(5**2)

i.e. the number in the exponent in the prime factorization simply doubles. Assuming you can already find the prime factorization of a number n (which your code can be modified for), the number of divisors can be found for n**2 by (pseudocode)
div  := (list of divisors of n)
div2 := (a list with two copies of div)
loop through all combinations div2:
      if combo <= sqrt(n): keep unique

If we did this for 10 we would get:
div  := (1,2,5,10)
div2 := (1,2,5,10,1,2,5,10)
keep := (1,2,5,10,2*2,2*5)
unique_keep := (1,2,4,5,10)

Each of the numbers in unique_keep divide into 10**2=100 thus they have a corresponding factor as well, except for the singular case of the 10 which is it's own factor. This gives as nine the divisors:
1 -> 100
2 -> 50
4 -> 25
5 -> 20
10 -> 10

A: I believe that you want something like this?
>>> [sum(i**2 % j == 0 for j in range(1, i**2 + 1)) for i in range(11)]
[0, 1, 3, 3, 5, 3, 9, 3, 7, 5, 9]

Or more generally
>>> def divisors(start, end, trans=lambda x:x):
...     return [sum(i % j == 0 for j in range(1, i + 1)) for i in (trans(t) for t in range(start, end+1))]
...
>>> divisors(0, 10, lambda x: x**2)
[0, 1, 3, 3, 5, 3, 9, 3, 7, 5, 9]
>>> divisors(0, 10)
[0, 1, 2, 2, 3, 2, 4, 2, 4, 3, 4]

A: If you have the prime factors of a number, it's just as easy to calculate the number of factors it has as it is to calculate the factors of it's square (or, indeed, any power).
def factor_count(N,power):
    factor_count = list()
    for n in range(N+1):
        prime = 2
        prime_factors = list()
        exponents = list()
        while n > 1:
            while (n / prime) % 1 == 0:
                if prime not in prime_factors:
                    prime_factors.append(prime)
                    exponents.append(1)
                else:
                    exponent = exponents.pop()+1
                    exponents.append(exponent)
                n /= prime
            prime += 1
        factors = 1
        for x in exponents:
            factors *= power*x+1
        factor_count.append(factors)
    print(factor_count)

Also, I'll note that my program differs from yours as to how many factors zero has. It's simple to modify the code to account for this but as divisors are often defined over the natural numbers anyway, it's just as easy to ignore it altogether.
To give you an idea of how efficient this is compared to the other answers given:
power_factors(1000,2000000000)                                        #evaluates almost instantly despite having an exponent of 2 billion
[sum(i**2 % j == 0 for j in range(1, i**2 + 1)) for i in range(1001)] #I got fed up of waiting before it managed to finish even with just an exponent of 2


text:
Q: What does the prompt "[master +1 ~0 -0 !]>" mean when using Git command line? After a few Git commands, I find my command line prompt change from
[master]>

to
[master +1 ~0 -0 !]>

What does this mean?

A: And:

*

*Conflicts ( ! )

Usually there is no conflict, but sometimes it occurs (for example when a file is changed in both your local repository and the online repository, and you want to pull. So Git doesn't know which one to keep).
In these cases, you have to correct and save the conflicting file (that is already marked by Github, showing the conflicting lines) manually.

A: This represents the number of files:

*

*added (+)

*modified (~)

*deleted (-)

*conflict (!) (from alisa's answer)

You can see a powershell version of that prompt here.

Those represent the status before commit (added means added to the index, or 'staged')
Here is a more complete version of that prompt, which also display the number of commits ahead or behind an upstream repository.

When you do some changes and commit them, your state is 1 commit ahead of remote. It is very useful to know how many commits you have unpushed.

A: Since you do have a conflict (!).
Type: git status       -to find out which folder has the conflict.


text:
Q: How to SOAP API Python request with keys After spending an entire day on trying to make things work (watching tutorials, reading through wikipedia and blogs), I thought it could be a good idea to ask some experts here on stack overflow.
So I am in the following situation:

*

*I am trying to extract some information using an SOAP API with python

*I have access to an URL and the WSDL definition (url ends with .php)

*A PDF document which says, that when accesing the API I need to provide a NameB object with valid set of identification keys. (HOW DO I DO THIS?)

*Valid set of keys

*I have tried both the zeep library and suds.client without any success

Could somebody explain to me what I need to do in order to receive the desired data?
The WSDL definition looks something like this:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <NameA>
            <body>
                 <NameB>
                             <Guid1>GUID</Guid1>
                             <Guid2>GUID</Guid2>
                 </NameB>
                 <Include>1</Include>
                 <NumberA> Number_A </NumberA>
            </body>
         </NameA>
     </s:Body>
</s:Envelope>

I assume that I need to enter the keys between elements Guid1 and Guid2, but HOW?
As you might read between the lines I am not an expert with python.
Thank you in advance! I am grateful for any kind of help!
Please let me know if something is unclear.

A: I am not a python expert but I am also using ZEEP and Python to call SOAP services.
"that when accesing the API I need to provide a NameB object with valid set of identification keys. (HOW DO I DO THIS?)"
try creating an object and pass it to the call.
NameB = {
'Guid1': your_value,
'Guid2': your_value
}


text:
Q: Train HMM in R with multiply sequences I have a data.frame (40K lines) .
         [,1]      [,2]      [,3]      [,4]      [,5]
[1,] "state 1" "state 3" NA        NA        NA
[2,] "state 2" "state 4" "state 4" NA        NA
[3,] "state 2" "state 4" "state 5" "state 3" "state 82"

Each line contains info about sequence of states. Number of states is fixed (~200). Length of sequence varies.
Is it possible to exec some function for finding multiply sequences with max probabilities:
get_rank_seq(df = myframe, states = levels(as.factor(c(myframe))) )

I don't want to apply that "model" to test data. Required to analyze only the original data set. I think that this problem is based on the Language Processing and HMM.
Thanks to all.


text:
Q: How to Create ArrayList of 2D Arrays I've run across a very perturbing problem. I'm trying to create a "chunking" system for this little game I'm making. What I want to do right now is just generate infinite chunks of dirt blocks. It works right now, but I'm just using a two dimensional array, which stores the column and the index of the dirt. Here is the actual code:
public void generate(){
    int newMax = dirtCount + dirtGeneratorChunk;
    int oldCount = dirtCount;
    for(int i = oldCount;i<newMax;i++){
        dirt[dirtCount] = newDirt(spawnDirtX+column*16,
                    spawnDirtY,16,16,column,columnNumber);
        columnNumber ++;
        blockGrid[column][columnNumber] = spawnDirtY;
        updateBlockGrid(column,(spawnDirtY-spawnDirtTop)/16,spawnDirtY);
        dirtX[i] = spawnDirtX+column*16;
        dirtY[i] = spawnDirtY;
        hasDirt = true;
        dirtCount ++;
        spawnDirtY += 16;
        if(spawnDirtY>500){
            column++;
            columnNumber = 0;
            spawnDirtY = spawnDirtYOriginal;
        }
    }
    repaint();
}

Hopefully that is helpful to show what I'm trying to do. As I'm sure you can tell by the code, I'm pretty new to Java and may be using bad practices/inefficient methods. If you have any suggestions on how I can improve my programming, I would love to hear them! Back to the point. Here is what I have so far on the ArrayList:
//Construct a new empty ArrayList for type int[][]
    ArrayList<int[][]> chunkHolder = new ArrayList<int[][]>();
    //Fill ArrayList (index, int[][])
    chunkHolder.add(chunkCount, createBlockGrid());
    chunkCount ++;
    Object[] chunkArray = chunkHolder.toArray();
    System.out.println(chunkArray[0]);

    public static int[][] createBlockGrid(){
        int[][] blockGrid = new int[64][256];
        return blockGrid;
    }

When I attempt to use System.out.println(chunkHolder.get(0));, it returns: [[I@337838. Obviously this isn't what I want... what am I doing wrong?
Thank you all for your help!
~Guad
(If I explained anything without clarity, please tell me!)

A: Your ArrayList holds int[][] elements, that is two dimensional integer arrays.
By retrieving the first element using chunkHolder.get(0), you get a two dimensional integer array. These things, if printed, produce something like what you got.
If you wanted the array elements, you would

*

*Retrieve an array element (like you did)

*Retrieve the elements of the array

As suggested, you might want to use (from Java 5) Arrays.deepToString(arr):
System.out.println(Arrays.deepToString(chunkHolder.get(0)));

Otherwise, you can loop over the array to print it out.
For example:
int[][] a = chunkHolder.get(0);
for (int[] b : a) {
 for (int c : b) {
  System.out.print(c + " ");
 }
 System.out.println();
}


text:
Q: Get userId from Spotify iOS SDK Is there a way to get the userId using the Spotify iOS SDK rather than using the web api?

A: Not sure if you're still looking, but SPTSession has a property:
/** @brief The canonical username of the authenticated user. */
@property (nonatomic, copy, readonly) NSString *canonicalUsername;

Which seems to be the id needed to make requests.

A: Yes.
Here's an example of how to do it in Swift 3:
SPTUser.requestCurrentUser(withAccessToken:(SPTAuth.defaultInstance().session.accessToken)!) { (error, data) in
        guard let user = data as? SPTUser else { print("Couldn't cast as SPTUser"); return }
        let userId = user.canonicalUsername
})


text:
Q: How can I have a single NAT Gateway with multiple public IPs? I have a project that involves running several hundred Lambda functions fetching data from the internet.
These functions are running inside a private subnet of my VPC.
I would like these functions to not all have the same IP for their internet traffic.
My understanding is that I should create a NAT gateway in a public subnet, but I cannot find how to have multiple public IPs on that NAT gateway to have some sort of randomization.
Is that even possible?
How should one proceed to achieve this?

A: It's not possible with a NAT gateway, since you can only attach one public IP per NATG.
However it is possible if you are willing to use NAT instances (more manual configuration and admin overhead).  You can set up multiple NAT instances. Correspondingly deploy your lambdas into multiple private subnets, each one configured to go to one of the NAT instances.

A: The other answers here were correct previously, but as of Feb 2023, NAT Gateway now supports registering multiple IP addresses, allowing you to scale up to about 440,000 concurrent connections to the same destination IP / destination port.
Here's the announcement, and here are the relevant API docs for the new capabilities:

*

*associate-nat-gateway-address

*disassociate-nat-gateway-address

*assign-private-nat-gateway-address

*unassign-private-nat-gateway-address

A: Unfortunately, this is impossible as you cannot associate multiple Elastic IPs with a public NAT gateway.

A public NAT gateway can only use 1 assigned Elastic IP, according to the documentation:

The NAT gateway replaces the source IP address of the instances with the IP address of the NAT gateway. For a public NAT gateway, this is the elastic IP address of the NAT gateway.

You can associate exactly one Elastic IP address with a public NAT gateway.

To use a different Elastic IP address for your NAT gateway, you must create a new NAT gateway with the required address, update your route tables, and then delete the existing NAT gateway if it's no longer required.

Having multiple Elastic IPs & multiple NAT gateways also won't really be feasible as the default (but adjustable) limit on Elastic IPs is 5 per region & on NAT gateways, 5 per AZ.
If you're using IaC (e.g. Terraform, CloudFormation etc.) you could theoretically create multiple private NAT instances (after increasing the per-region service quota) however I would advise creating your own NAT AMI in that case.
Raising the service quota to hundreds of instances as well as purchasing hundreds of Elastic IPS will definitely raise some alarms.
I would look to rearchitecting your application if possible (unless the nature of your application requires it in which case, AWS may not be the best option).


text:
Q: Compilation error concerning operator[] I created a template class vect that allows me to create arrays of elements of type T, access them from 1 to n (instead of 0 to n-1) and permute them (I have to permute them that way instead of permuting them the classical way).
Here's the header file:
#ifndef VECT_HPP

#define VECT_HPP

#include <vector>

template <class T>
class vect
{
public:
    vect(int=0);
    ~vect();
    void show(void) const;
    void permute(int,int);
    T& operator[](int);
    const T& operator[](int) const;
    void init_perm(void);
private:
    int n;
    double* p;
    std::vector<int> s;
};

#endif /* GUARD_VECT_HPP */
#include "vect.cpp"

and here's the source file:
#ifndef VECT_CPP
#define VECT_CPP

#include "vect.hpp"
#include <iostream>

using namespace std;

template <class T>
vect<T>::vect(int a): n(a)
{
    p=new double[n];
    s.resize(n);
    init_perm();
}

template <class T>
vect<T>::~vect()
{
    delete [] p;
}

template <class T>
void vect<T>::show(void) const
{
    for (int i = 0; i < n; i++)
        cout << p[i] << endl;
}

template <class T>
void vect<T>::permute(int a,int b)
{
    static int c;
    a--;
    b--;
    c=s[a];
    s[a]=s[b];
    s[b]=c;
}
template <class T>
T& vect<T>::operator[](int i)
{
    return p[s[i-1]-1];
}

template <class T>
const T& vect<T>::operator[](int i) const
{
    return p[s[i-1]-1];
}

template <class T>
void vect<T>::init_perm(void)
{
    for (int i = 0; i < n; i++)
        s[i]=i+1;
}

#endif

and here's the file main.cpp that I uesd to test the class:
#include "vect.hpp"
#include <iostream>

using namespace std;

int main(void)
{
    vect<int> v(5);
    v.show();
    for (int i = 1; i <=5; i++)
        v[i]=10*i;
    v.show();
    cout << "Permuted 3 and 5" << endl;
    v.permute(3,5);
    v.show();
    v.init_perm();
    cout << "Initialized permutations" << endl;
    v.show();
    return 0;
}

I get the following error:
In file included from vect.hpp:25:0,
                 from main.cpp:1:
vect.cpp: In instantiation of 'T& vect<T>::operator[](int) [with T = int]':
main.cpp:11:6:   required from here
vect.cpp:43:19: error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'
  return p[s[i-1]-1];

I searched on Internet about this error and how it can be caused by a bad implementation of operator[], but after correction I still have the same error, even when I return p[i-1] instead of p[s[i-1]].
Could you please help me?

A: The problem stems from the type-mismatch of p compared to the template T.
You have an array of double, pointed to by p. And the template T is an int. Normally that's not a big problem since double can implicitly be converted to an int. But this isn't the normal case, because you want to return a reference to int.
The compiler does the conversion to int for you, but this converted value is an rvalue and a temporary, and references can't bind to rvalues.
The solution is to not have a mismatch of the types, and have p point to an array of T instead. Or better yet, have it be a std::vector.

A: The problem is here:
template <class T>
T& vect<T>::operator[](int i)
{
    return p[s[i-1]-1];
}

in your example, T is deduced to int, but p is always of type double. So when you return p[s[i-1]-1], an int& tries to bind to a double. At this point that double value implicitly is converted to a rvalue int which cannot be bound to a int&.


text:
Q: How to allow unsafe code for Release and Debug on visual studio 2019 .net5.0 I viewed this question asking how to allow unsafe code for azure functions publish code.
This suggest to "Make sure you set the Allows unsafe code for the Release build as well."
I already enabled unsafe mode on Project Properties -> Build -> Check Allow unsafe code.
But I don't find the difference between enable unsafe code on Debug and Release.
Im using Visual Studio 2019 .Net 5.0
Where is the path to enable it on Release?

A: Right-click on your project file then apply the following image. Configuration menu should have Release mode too.

A: No matter what IDE you use, you can just activate that by adding a property group to your csproj file like done in this example for both Release and Debug.
<Project Sdk="Microsoft.NET.Sdk">

      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net5.0</TargetFramework>
      </PropertyGroup>

      <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
        <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
      </PropertyGroup>

      <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
        <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
      </PropertyGroup>

    </Project>


text:
Q: OnTextChanged forcing me to click button twice I'm working on an asp.net, c# web app. I have a textbox (with validators) defined as...
      <asp:TextBox ID="VehicleAmt" runat="server" AutoPostBack="True"
   OnTextChanged="VehicleAmt_OnTextChanged"
   causesvalidation="true"
   Width="35px"></asp:TextBox>
  <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" Font-Size="12px"
          ControlToValidate="VehicleAmt" ErrorMessage="*" ForeColor="#CC3300"
          SetFocusOnError="True" ValidationExpression="[0-99999]*" Display="Dynamic">
  </asp:RegularExpressionValidator>
  <asp:RequiredFieldValidator id="RequiredFieldValidatorVehicleAmt"
         ControlToValidate="VehicleAmt"
         Display="Dynamic"
         ErrorMessage="Required"
         runat="server"/>

Elsewhere on the form I have a telerik RadGrid with the last column being a button. This is defined as...
    <telerik:GridTemplateColumn UniqueName="ActionColumn">
 <ItemTemplate>
  <asp:LinkButton Text="" runat="server" ID="lnkAddVehicle" CausesValidation="false" CommandName="AddVehicle">
   <img src="images/buttons/add.png"/>
  </asp:LinkButton>
 </ItemTemplate>

The VehicleAmt_OnTextChanged method does some db saving. The problem is when I type something in the textbox then click on the add button, I actually have to click on the button TWICE in order for the button code to run. Any ideas why this is happening and how I can enable single click for this?
I did notice that I have a standard asp.net button, and a single click does seem to work for that.
FYI: The code for AddVehicle, in part is this...
    protected void RadGridAvailableItems_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
{
    if (e.CommandName != "Sort" && e.CommandName != "Page" && e.CommandName != "ChangePageSize")
    {
        GridDataItem dataItem = e.Item as GridDataItem;

        int VehicleId = Convert.ToInt32(dataItem["VehicleId"].Text);

    switch (e.CommandName)
        {

            case "AddVehicle":
                :
                break;
        }
    }
    rebindGrids();

    panErrorMessages.Visible = false;
}

A: With AutoPostback set to "true", your textbox is going to fire the TextChanged event as soon as the textbox loses focus - this includes trying to click on a button.
It might look like you're having to click the button twice, but what's actually happening is: -

*

*you go to click on a button or set the focus to another control

*the  default ASP.NET client-side javascript posts the form, and your
textbox's TextChanged event fires

*the page loads again

*you can now press the Save button (or move the focus to another control) without causing the TextChanged event again
You can verify this by attaching a debugger and putting a breakpoint inside your TextChanged event.


text:
Q: Analog of an open map for uniform structures In topology, a function is continuous if the inverse image of an open set is open.
A function is open if the image of an open set is open.
Uniformity continuity can be defined in a similar way as continuity.
A map $f$ between two uniform spaces is uniformly continuous if the inverse image (under $f \times f$) of an entourage is an entourage.
Now consider the following "uniform analog" of openness: the image (under $f \times f$) of an entourage is an entourage.
Question. Was this property studied? And if yes, is there a well-established name for it?
Motivation. I need this property in a very special case and I am looking for references.

A: The maps in question appear to be uniformly open surjections. I believe that uniformly open maps were introduced in E. Michael, 'Topologies on spaces of subsets', Trans. Amer. Math. Soc. $\mathbf{71}$ ($1951$), $152$-$182$. If $\langle X,\mathscr{U}\rangle$ and $\langle Y,\mathscr{V}\rangle$ are uniform spaces, a map $f:X\to Y$ is uniformly open if for each $U\in\mathscr{U}$ there is a $V\in\mathscr{V}$ such that $f[U[x]]\supseteq V[f(x)]$ for each $x\in X$.
Suppose that $f$ is a uniformly open surjection, $U\in\mathscr{U}$, and $V\in\mathscr{V}$ is such that $f[U[x]]\supseteq V[f(x)]$ for each $x\in X$. Let $\langle y_0,y_1\rangle\in V$; then there are $x_0,x_1\in X$ such that $f(x_i)=y_i$ for $i=0,1$ and $\langle x_0,x_1\rangle\in U$, so $V\subseteq(f\times f)[U]$, and hence $(f\times f)[U]\in\mathscr{V}$.
I've not read the paper, but Vitaly V. Fedorchuk & Hans-Peter A. Künzi, 'Uniformly open mappings and uniform embeddings of functions spaces', Topology and its Applications $\mathbf{61}$ ($1995$), $61$-$84$ appears to discuss them in considerable detail.


text:
Q: "dir" parameter in Shell.Execute command doesn't work when "verb" parameter contains "runas" option The current directory remains "C:\Windows\System32" despite I pass my current directory to the "dir" parameter.
If CreateObject("WScript.Shell").Run("%ComSpec% /C ""NET FILE""", 0, True) <> 0 Then
    CreateObject("Shell.Application").ShellExecute WScript.FullName, """" & WScript.ScriptFullName & """", CreateObject("WScript.Shell").CurrentDirectory, "runas", 5
    WScript.Quit
End If

How can I solve the problem?
My answer:
I have solved with:
If WScript.Arguments.Count <> 0 Then WScript.Quit 1
RunAsAdmin
Main

Sub RunAsAdmin()
    Set Shell = CreateObject("WScript.Shell")
    Set Env = Shell.Environment("VOLATILE")
    If Shell.Run("%ComSpec% /C ""NET FILE""", 0, True) <> 0 Then
        Env("CurrentDirectory") = Shell.CurrentDirectory
        ArgsList = ""
        For i = 1 To WScript.Arguments.Count
            ArgsList = ArgsList & """ """ & WScript.Arguments(i - 1)
        Next
        CreateObject("Shell.Application").ShellExecute WScript.FullName, """" & WScript.ScriptFullName & ArgsList & """", , "runas", 5
        WScript.Quit
    End If
    Shell.CurrentDirectory = Env("CurrentDirectory")
    Env.Remove("CurrentDirectory")
End Sub

Sub Main()

End Sub


text:
Q: SecurityException is not forwarded from service to its manager I have a service which has external APIs.
In some cases I have to throw SecurityException.
The strange thing is the following:
In some APIs when I throw the exception, the binder successfully makes this transaction
and the exception is caught by the service's manager.
However, in other APIs the exception does not reach the manager, because the Binder swallows
it.
The Binder log message is as follows:
"06-Nov 06:04:05.766  3632    W   Binder  Binder call failed."
As it is seen from the Binder code, the exception is swallowed , since the transaction is ONE WAY:
           if ((flags & FLAG_ONEWAY) != 0) {
737                if (e instanceof RemoteException) {
738                    Log.w(TAG, "Binder call failed.", e);
739                } else {
740                    Log.w(TAG, "Caught a RuntimeException from the binder stub implementation.", e);
741                }
742            } else {
743                // Clear the parcel before writing the exception
744                reply.setDataSize(0);
745                reply.setDataPosition(0);
746                reply.writeException(e);
747            }

I need the exception be forwarded. I don't understand why in some cases the exception is forwarded and in other - not. I don't see any differences between the two types of APIs.  How can I cause my exception be not ONE WAY, if it is possible?
Please help.
Thanks in advance.
Regards , Sveta

A: I'found an answer to my question. The problem occurred because the "problematic" APIs are defined as oneway in the AIDL. So they are asynchronous. That's why it was a mistake to send an Exception from within those API, because in oneway APIs the link to the app process (in context of which manager runs) is lost.


text:
Q: mysql very low speed when looping through table after inserting a hug number of rows I have a procedure in MYSQL database that should collect some data from multiple tables and loop through it.
I have created a table to insert this data in it, the table has a primary key and a none unique index.
The inserted data is about 200000 rows, the insert is don in few seconds, but the while loop takes very long time (about 30 mins) to complete!!!
The while loop code is something like below:
    SET @I = 0;
    WhileLoop: WHILE (1=1)
       SELECT KeyRW
       INTO @I
       FROM MyTable
       WHERE KeyRW> @I
       ORDER BY KeyRW
       LIMIT 1;

       IF @I IS NULL THEN
           leave WhileLoop;
       END IF;

      (Some simple calculation...)

    END WHILE WhileLoop;

We moved the loop code into another procedure and execute it manually after the insert is done (there was a few minutes delay) and it executed very very faster!!!
Then we moved the loop back into the previous procedure and added a delay before it, and now its working, it seems that MYSQL is indexing data asyncly and we should wait for it!!
Did i understand correctly?
If yes then how much should we wait based on size of data?
If no then whats the problem and why a delay is solving this?


text:
Q: Hash based implementation of Set in Java Collection Framework? I am learning Java collection framework in Java, and got fair idea of various Classes and interfaces.
While going through Set interface, one of the implementations is HashSet (among others).
I am not able to understand what is the logic of implementing Set based on the Hash, what advantage does it serve?
Can anyone help me understand what is the need of Hash based implementation of Set in Java Collection Framework?

A: Simple: performance and efficiency.
The key element of Sets is: uniqueness. You want to quickly be able to tell wether some x is in (x, y, z) or not.
And hashing is a very elegant and efficient way of approaching this problem.
That is all there is to this.


text:
Q: Examples and Documentation for Apache Deltaspike - where are they? I followed the path of Java EE for quite a while now, used JBoss Seam and followed its standardization within CDI.
Now after trying to solve the first steps on the hard path from Seam 2 to 3 migration, I learned that all was moved to Apache Deltaspike.
But while Seam was decently documented and equipped with examples, Deltaspike is not. There are menu items leading to "Documentation", which is very poor, littered with TODOs and without any visible structure and to "Examples", which is more or less a joke.
Ever since I tried to step up to Java EE 6, I feel a bit like standing in the rain - even though it's great, that many concepts of Seam 2 went into the standard, I miss many things I had before - and exactly those things should be covered by CDI extensions. Here again, it's great that there is a common effort to channel those extensions in a project like Apache Deltaspike - but at the moment there is a very high hurdle to get benefits from it, even if you're not a beginner in the technology.
So - can anyone lead me to decent resources, documentation and examples how to use and understand the CDI extensions?

A: DeltaSpike is still early in its development. It is only at version 0.3; it might be quite some time before it's production-ready. Until then, you might take a look at MyFaces CODI or Seam, two projects whose development has halted as they are presently being merged into DeltaSpike.
The documentation at the DeltaSpike web site, I agree, is quite insufficient for users; I bet it's just for people that want to test it out or develop for it.

A: As noted in other responses, the DeltaSpike documentation is a little lacking. You could always take a look at the tests and javadoc. For examples, I think you'll find JBoss jdf quickstarts to be the best location for examples currently. Do a search on the right for DeltaSpike and you should see around seven examples.

A: Here's a concrete example.  I am a reasonably experienced software person.  I would like to use DeltaSpike BeanProvider.getContextReference to inject an EJB into some code that is not itself an EJB.  I included the requisite Maven dependencies and added the BeanProvider.getContextReference code to one of my classes.  I'm getting error messages that tell me that DeltaSpike is not configured.  Two hours with the documentation did not get me any closer to understanding what I need to do simply to turn it on.  What seems to be missing is a "How to configure DeltaSpike core." page.


text:
Q: Initializing a static const char* array with text file data? I have a text file containing words
Every word in a single line.
And I have this array in my c++ code:
static const char *array[]= {"text"};
How do I initialize the array with all the txt file data ?
I know how to initialize int array with this data using ifstream, but I don't know how to do it with static const char *


text:
Q: How to Fix ErrorException in HasAttributes.php I need to append one more attribute by some logic. So I write getPercentageAttribute function into App\User_Tax. Code is
protected $appends = 'percentage';

public function getPercentageAttribute()
{
    $p = SystemParameterSP::where([
      ['serviceprovider_id', $this->user_type_id]
    ])->first();
    if($p != null){
      return $p->value1;
    }
    else{
      $d = DB::table('user_taxes_dependencies')->where('system_tax_id', $this->system_tax_id)->first();
      return $d->percentage;
    }
}

Then I get User_Tax model to pass to the blade. Code is
$user_taxes = User_Tax::where([
                                ['user_taxes.user_type', 3],
                                ['user_taxes.status', 1]
                            ])->get();

into the blade file, I need to convert this laravel variable to javascript variable.
var user_taxes = {!! json_encode($user_taxes) !!};

if I try to convert, then I get error
ErrorException in HasAttributes.php line 207:
count(): Parameter must be an array or an object that implements Countable

I could not solve this error. Could anyone suggest any solution to solve it?

A: If I understand you correctly, you'll need to serialise the result first:
In your template:
var user_taxes = '{!! $user_taxes->toJson() !!}';


text:
Q: Unable to send mail in android emulator I want to send mail automatically from my android app, so I configured the gmail account in my emulator and used the following code:
Intent emailIntentt = new Intent(android.content.Intent.ACTION_SEND);
emailIntentt.setType("plain/text");
String aEmailList[] = { "xxxx@gmail.com" };
emailIntentt.putExtra(android.content.Intent.EXTRA_EMAIL, aEmailList);
emailIntentt.putExtra(android.content.Intent.EXTRA_SUBJECT, "Feedback");
emailIntentt.putExtra(android.content.Intent.EXTRA_TEXT, "hello");
startActivityForResult(emailIntentt, 1);

But, it says no app found to send mail.
Also, while configuring email, I am unable to sync with the mail account from emulator. Does this cause the problem?

A: First, the MIME type of plain text is text/plain, not plain/text.
Second, as the comments indicate, you need an email app configured with an email account to be able to send email messages via ACTION_SEND.


text:
Q: has_one :through association returns nil I have a has_one through association that returns nil. Basically, I have a Review model that belongs to an Enrollment model, which belongs to a Section model. The Section model belongs to a Cluster.
I'm specifying that a Review has_one :section, through: :enrollment - this works. However, Review has_one :cluster, through :section does not work. See below for how I have my models defined:
The Review model:
class Review < ActiveRecord::Base
  belongs_to :reviewer,
    class_name: 'Enrollment'

  has_one :section,
    through: :reviewer,
    source: :section

  has_one :cluster,
    through: :section
end

The Enrollment model:
class Enrollment < ActiveRecord::Base
  belongs_to :section,
    inverse_of: :enrollments

  has_one :cluster,
    through: :section

  has_many :reviews,
    foreign_key: :reviewer_id,
    inverse_of: :reviewer
end

The Section model:
class Section < Active::Record
  belongs_to :cluster,
    inverse_of: :sections

  has_many :enrollments,
    inverse_of: :section
end

Finally, the Cluster model:
class Cluster < ActiveRecord::Base
  has_many :sections,
    inverse_of: :cluster
end

In my rails console:
[30] pry(main)> r = Review.new(reviewer: Enrollment.all.sample)
  Enrollment Load (3.5ms)  SELECT "enrollments".* FROM "enrollments" => #<Review id: nil, submission_id: nil, created_at: nil, updated_at: nil, expires_at: nil, reviewer_id: 94, completed_at: nil, submitted: false>
[31] pry(main)> r.section
  Section Load (0.5ms)  SELECT  "sections".* FROM "sections" INNER JOIN "enrollments" ON "sections"."id" = "enrollments"."section_id" WHERE "enrollments"."id" = $1  ORDER BY sections.class_number ASC LIMIT 1  [["id", 94]]
=> #<CampusSection id: 3, created_at: "2014-08-30 19:17:47", updated_at: "2014-08-30 19:17:47", cluster_id: 1, class_number: 157593622, type: "CampusSection", carmen_id: "218401898">
[32] pry(main)> r.section.cluster
  Cluster Load (0.2ms)  SELECT  "clusters".* FROM "clusters"  WHERE "clusters"."id" = $1 LIMIT 1  [["id", 1]]
=> #<Cluster id: 1, created_at: "2014-08-30 19:17:47", updated_at: "2014-08-30 19:17:47", name: "Schuppe, Lueilwitz and Keeling 106", consent_agreement_id: 1>
[33] pry(main)> r.cluster
=> nil

Any help is appreciated. Thanks guys.
Post updated:
Relevant parts of my schema:
ActiveRecord::Schema.define(version: 20140829191322) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "clusters", force: true do |t|
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "name"
    t.integer  "consent_agreement_id"
  end

  create_table "enrollments", force: true do |t|
    t.integer  "enrollee_id",                    null: false
    t.string   "enrollee_type",                  null: false
    t.integer  "section_id",                     null: false
    t.datetime "created_at"
    t.datetime "updated_at"
    t.datetime "disenrolled_at"
    t.boolean  "disenrolled",    default: false
    t.boolean  "consent",        default: false
    t.datetime "consented_at"
  end

  add_index "enrollments", ["disenrolled"], name: "index_enrollments_on_disenrolled", using: :btree
  add_index "enrollments", ["disenrolled_at"], name: "index_enrollments_on_disenrolled_at", using: :btree
  add_index "enrollments", ["enrollee_id", "enrollee_type", "section_id"], name: "index_enrollments_on_eid_and_etype_and_sid", unique: true, using: :btree

  create_table "reviews", force: true do |t|
    t.integer  "submission_id",                 null: false
    t.datetime "created_at"
    t.datetime "updated_at"
    t.datetime "expires_at",                    null: false
    t.integer  "reviewer_id",                   null: false
    t.datetime "completed_at"
    t.boolean  "submitted",     default: false, null: false
  end

  add_index "reviews", ["reviewer_id"], name: "index_reviews_on_reviewer_id", using: :btree
  add_index "reviews", ["submission_id", "reviewer_id"], name: "index_reviews_on_submission_id_and_reviewer_id", unique: true, using: :btree
  add_index "reviews", ["submission_id"], name: "index_reviews_on_submission_id", using: :btree

  create_table "sections", force: true do |t|
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "cluster_id",   null: false
    t.integer  "class_number", null: false
    t.string   "type",         null: false
    t.string   "carmen_id"
  end

  add_index "sections", ["carmen_id"], name: "index_sections_on_carmen_id", using: :btree
  add_index "sections", ["class_number"], name: "index_sections_on_class_number", using: :btree
end

A: I guess the review needs to be persisted before you can get the corresponding cluster back directly, not sure why...


text:
Q: Filter array items using forEach I have one question about filter array in forEach. So I would like filter (bigger than in example) array using outside variable filterKey. I think that my function is correct by after filtered newArr is undefined. Could you explain what is incorrect?
var filterKey = 123456,
var array = [{
              ratings:{ users:[id: 123456]}, user: xyz
             },
             {
              ratings:{users:[id:9787389023]}, user:zyx
            }],

And my filter function
var newArr = array.forEach((ele) =>
                ele.ratings.users.filter((newEl) =>
                    newEl.id == filterKey))

A: Use array.filter method

let array = [
{
  id: 123456, user: 'xyz'
},
{
  id:9787389023, user: 'zyx'
},
{
  id: 123456, user: 'che'
}
]

let newArray = array.filter((element) => element.id === 123456)
console.log(newArray)

A: Use .filter and you'll be able to filter your result set without using foreach since it'll loop across the array.

var find = 123456;
var arr = [
  {
    id: 123456,
    user: 'john'
  },
  {
    id: 9787389023,
    user: 'leah'
  }
];

var results = arr.filter(function(node) {
  return node.id === find;
});

console.log(results);


text:
Q: How to install mfpdev-cli to offline environment? I am trying to setup offline (does not have internet access) OS X machine for MobileFirst Platform 8.0 development, and failing to install MobileFirst CLI.
I am referring to this article.
I have installed 8.0.0.0-MFPF-DevKit-MacOSX-IF2016080923.zip on the offline machine, then run.sh and console.sh.
Development server has successfully launched, and now I can access to Operations Console.
I have downloaded mfpdev-cli.tar from the Console, and followed the article I cited above.

*

*Copy mfpdev-cli.tar to online machine.

*On the online machine, npm --cache ./.cache install mfpdev-cli.tar

*Archive .cache directory, and copy the archive file to the offline machine.

*On the offline machine, unarchive .cache directory.

*sudo npm install --cache ./.cache ./mfpdev-cli.tar -g
Then, I got below:

npm ERR! fetch failed https://registry.npmjs.org/http-proxy/-/http-proxy-1.13.2.tgz
  npm WARN retry will retry, error on last attempt: Error: getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443

Those ERR! and WARN repeats for many other packages.
And at last:

npm ERR! Darwin 15.6.0
  npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "--cache" "./.cache" "./mfpdev-cli.tar" "-g"
  npm ERR! node v4.5.0
  npm ERR! npm  v2.15.9
  npm ERR! code ENOTFOUND
  npm ERR! errno ENOTFOUND
  npm ERR! syscall getaddrinfo

  npm ERR! network getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443
  npm ERR! network This is most likely not a problem with npm itself
  npm ERR! network and is related to network connectivity.
  npm ERR! network In most cases you are behind a proxy or have bad network settings.
  npm ERR! network
  npm ERR! network If you are behind a proxy, please make sure that the
  npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

  npm ERR! Please include the following file with any support request:
  npm ERR!     /Users/babatch/Downloads/mfpdev-cli/npm-debug.log

How do I install mfpdev-cli on offline machine?

A: The problem is that npm is attempting to contact its online repository still due to some file dependency on the http-proxy package.
What you can do is to get/add this dependency independently and then try again.

A: I have tried some methods, and finally it got working.
The procedure is below:

*

*On the online machine, npm install ./mfpdev-cli.tar (without -g)

*cd node_modules

*tar -cvzf mfpdev-cli.tgz mfpdev-cli and copy mfpdev-cli.tgz just created to the offline machine.

*On the offline machine, tar -xvzf mfpdev-cli.tgz

*sudo cp -r mfpdev-cli /usr/local/lib/node_modules

*cd /usr/local/bin

*sudo ln -s ../lib/node_modules/mfpdev-cli/bin/cli.js ./mfpdev
At present, it seems to be working fine.


text:
Q: using get und set method to change format of a string - set method never gets called I get a datetime via http and want to format it before I use it. For that I use the get and set method, but the set method never gets called.
My component (AdminComponent):
import { Component, OnInit } from '@angular/core';

import { AdminService } from './admin.service';
import { Config } from './_config';

@Component({
  selector: 'app-admin',
  templateUrl: './admin.component.html',
  styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit {

    config: Config = new Config();

    constructor(private adminService: AdminService) { }

    ngOnInit() {

      this.getConfig();
    }

    getConfig(): void { //THIS IS THE IMPORTANT PART FOR THIS QUESTION
        this.adminService.getConfig().subscribe(config => {
            this.config = config;
            console.log(this.config); //just to debug
        });
    }
    saveConfig(): void {
        //here will come the save
    }

}

the AdminService:
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { Config } from './_config';

@Injectable({
  providedIn: 'root'
})
export class AdminService {

    private getConfigUrl = '//../getConfig.php';
    private saveConfigUrl = '//../saveConfig.php';

  constructor(private http: HttpClient) {
      this.getConfigUrl = window.location.protocol+this.getConfigUrl;
      this.saveConfigUrl = window.location.protocol+this.saveConfigUrl;
  }

    getConfig(): Observable<Config> {
        var data = ""; //is used but not necessary for this example.
        var headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'});
        return this.http.post<Config>(this.getConfigUrl, data, { headers: headers } ).pipe(catchError(this.handleError('admin getConfig', [])));
    }

    saveConfig(config: Config) {
        var data = "config="+JSON.stringify(config);
        var headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'});
        return this.http.post<string>(this.saveConfigUrl, data, { headers: headers } ).pipe(catchError(this.handleError('admin saveConfig', [])));
    }

          /**
   * Handle Http operation that failed.
   * Let the app continue.
   * @param operation - name of the operation that failed
   * @param result - optional value to return as the observable result
   */
  private handleError<T> (operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {

      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }
}

And the Config class (where I use the get and set method):
export class Config {
    title: string;
    _startdate: Date;
    enddate: Date;

    public get startdate(): string {
        console.log("get called");
        return this.parseDateToStringWithFormat(this._startdate);
    }

    public set startdate(v: string) {
        console.log("set called");
        let actualParsedDate = v ? new Date(v) : new Date();
        let normalizedParsedDate = new Date(actualParsedDate.getTime() + (actualParsedDate.getTimezoneOffset() * 60000));
        console.log("from: "+v+" to: "+normalizedParsedDate);
        this._startdate = normalizedParsedDate;
    }

    private parseDateToStringWithFormat(date: Date): string {
        //formats the date-string to be usable in the input type="datetime-local"
        return date.toISOString().substring(0,16);
    }
}

I changed the name of startdate to _startdate and created a get and set method for startdate. In my template I use doublebinding to a input field like : <input type="datetime-local" [(ngModel)]="config.startdate">
Looking at my console, the set method is never called, but the get method is called. When the get is called this._startdate is undefined. So I guess I do something fundamentally wrong.
My goal is to not have to handle the date-formation in the component and I would like to do it directly in the Config class.
Edit: if I change the function getConfig() from the AdminService to set every variable separately it works, see here:
getConfig(): void {
        this.adminService.getConfig().subscribe(config => {
            this.config.title = config.title;
            this.config.startdate = config.startdate;
            this.config.enddate = config.enddate;
            console.log(this.config);
        });
    }

As Config has only 3 variables this is not a big deal, however in bigger Classes this is not really what I looking for. Also I am not sure why the first version does not work?

A: I know why now, you are not setting anything to it... SET will be called when your code set values in
getConfig(): void { //THIS IS THE IMPORTANT PART FOR THIS QUESTION
    this.adminService.getConfig().subscribe(config => {
        this.config = config; // this is where you are calling GET
        config.startdate = 'foo'; // this is a SET example
        console.log(this.config);
    });
}

EDIT:
If your code get too big you can use a constructor in Config class:
class Config {

    private title: string;
    private startdate: string;
    private enddate: string;

    constructor(title: string, startdate: string, enddate: string) {
        this.title = title;
        this.startdate = startdate;
        this.enddate = enddate;
    }

    // ... getters/setters
}

I think this is the best way to use classes in typescript


text:
Q: INNER JOIN not working in hibernate? I have a oneToMany association between Movie and actor Table and a ManyToOne association reverse way. One JOIN works but when I have a filter clause in JOIN it fails. please find the relevant code sections with comments above it describing it.
I have read this post. But this did not help
Join Query not working in Hibernate
Here are the relevant parts in my Entity:
@Entity
public class Movie {
    ......
    @OneToMany(mappedBy="movie",fetch=FetchType.EAGER,cascade=CascadeType.ALL)
    private Set<Actor> actors=new HashSet<>();
    //getters and setters
}

@Entity
public class Actor {
    .....
    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name="ACTOR_MOVIE")
    //getters and setters
}

Here is my HibernateTest class:
public class HibernateTest {

    public static void main(String[] args) {
       Movie movie1 = new Movie("Mr and Mrs.Smith", new Date(2005, 6, 5));
        Actor actor3=new Actor("Brad");
        actor3.setMovie(movie1);
        Actor actor4=new Actor("Joe");
        actor4.setMovie(movie1);
        movie1.getActors().add(actor3);
        movie1.getActors().add(actor4);

        Movie movie = new Movie("Titanic", new Date(1997,12,19));
        Actor actor1=new Actor("Leo");
        Actor actor2=new Actor("Kate");
        actor1.setMovie(movie);
        actor2.setMovie(movie);
        movie.getActors().add(actor1);
        movie.getActors().add(actor2);

        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.persist(movie);
        session.persist(movie1);

        session.getTransaction().commit();
        session.close();

        session = sessionFactory.openSession();
        session.beginTransaction();

        //The following query works
        //List<Object[]> actor_from_movies=session.createQuery("select m.name,act.name from Movie m INNER JOIN m.actors act").list();

        //This throws error
        List<Object[]> actor_from_movies=session.createQuery("select m.name,act.name from Movie m INNER JOIN m.actors act"
                + "where act.name=:acname").setParameter("acname", "Brad").list();

       System.out.println("actor_from_movies "+ actor_from_movies);

       session.getTransaction().commit();
    session.close();
}
}

ERROR message:
Sep 30, 2014 11:08:42 AM org.hibernate.hql.internal.ast.ErrorCounter reportError
ERROR: line 1:92: unexpected token: act
Sep 30, 2014 11:08:42 AM org.hibernate.hql.internal.ast.ErrorCounter reportError
ERROR: line 1:92: unexpected token: act
line 1:92: unexpected token: act
    at org.hibernate.hql.internal.antlr.HqlBaseParser.fromJoin(HqlBaseParser.java:1727)
    at org.hibernate.hql.internal.antlr.HqlBaseParser.fromClause(HqlBaseParser.java:1380)
    at org.hibernate.hql.internal.antlr.HqlBaseParser.selectFrom(HqlBaseParser.java:1086)
    at org.hibernate.hql.internal.antlr.HqlBaseParser.queryRule(HqlBaseParser.java:731)
    at org.hibernate.hql.internal.antlr.HqlBaseParser.selectStatement(HqlBaseParser.java:323)
    at org.hibernate.hql.internal.antlr.HqlBaseParser.statement(HqlBaseParser.java:186)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:295)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:203)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:126)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:88)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:167)
    at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1800)
    at com.example.hibernate.HibernateTest.main(HibernateTest.java:142)

Exception in thread "main" org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: act near line 1, column 92 [select m.name,act.name from com.example.hibernate.dto.Movie m INNER JOIN m.actors actwhere act.name=:acname]
    at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:91)
    at org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:109)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:304)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:203)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:126)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:88)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:167)
    at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1800)
    at com.example.hibernate.HibernateTest.main(HibernateTest.java:142)

A: Add a blank before where:
" where act.name=:acname").


text:
Q: 25 Oct read as "25" or "25th"? I hear some people read days in names as non-ordinal numbers. Not sure if that is correct.
For example,  25 October is read as "twenty five October" or "twenty fifth October"? Or both?
I am looking for official rule, not slang or casual talk.


text:
Q: relocatable dylibs (e.g. embedded frameworks) are only supported on iOS 8.0 and later (@rpath/libswift_stdlib_core.dylib) I just upgraded from Xcode 6 Beta 2 to Xcode Beta 3 and am now getting the following warning when building my project:
ld: warning: relocatable dylibs (e.g. embedded frameworks) are only supported on iOS 8.0 and later (@rpath/libswift_stdlib_core.dylib)

It is a warning but seems to mean my current setup will not work on iOS 7.1, which is my deployment target. How can I track down which frameworks are embedded, and how can I fix this for iOS < 8.0?

A: This appears to be a bug of Beta 3. As pointed out by Apple Engineer on this post.
I have also been living with this warning when running apps on iOS 7.1 device.

A: You see and add them on the project page when you select the target: tab General->Embedded Binaries (and they then appear in Build Phases->Embed Frameworks).

Embedded frameworks for OSX were available in Xcode 5, but not for iOS.
WWDC session regarding new features in Xcode 6 specifically promised dynamic frameworks for iOS 8 (someone please add citation when developer center comes back online). So far, with all Xcode 6 betas, I have had no problems compiling and debugging an app with frameworks on iOS 7.
But since this wasn't promised, frameworks for iOS7 is something you cannot depend on (e.g. this may stop working in later betas; an app with embedded framework for iOS 7 may be rejected, etc.). That may explain why they added an explicit warning.
There's not much you can do if this feature turns out to be indeed unsupported, other than remove the frameworks from the target and use static libraries as we did with Xcode 5. Or go the iOS8-only route.

A: After using XCode 6.1.1 I am able to put the code on iOS 8+ iOS7.1.2 and iOS 6.1.3 Although the warning is still there but the app works absolutely fine on all the 3 OSs
======================
Lucky guy... My project keeps failing to compile after I referenced the PushKit framework.
The project is a new project created by Xcode with only 3 new functions for testing Push Notification.
The workaround is to put the PushKit framework as "embedded", but this is not a good solution since my working Xcode project will be generated from Unity3d. Making the changes manually will break the auto build process.

A: I had this error after adding a C++ framework (DeepBelief) to a project. Adding an empty .cpp file to the project fixed it.
I'm using Beta4, and found the answer on the DeepBelief github site:

XCode may be skipping the standard C++ library, and that's needed by
  the DeepBelief.framework code. One workaround I've found is to include
  an empty .mm or .cpp file in the project to trick XCode into treating
  it as a C++
  project.

A: Read this github post from ReactiveCocoa
The bug is still present in XCode6 GM and so XCode6 final release:

Well, I get the exact same issue in xcode6GM no matter whether I
  create framework for swift OR objc :-[[[[[[[[[[[[[[[

According to Apple Extension Programming Guide:
You can make a containing app available to users running iOS 7 or earlier, but then must take precautions to safely link embedded frameworks when running in iOS 8 or later.
talking about app extensions, but if you read it, you can understand that this applies to embedded frameworks in general.

A: After using XCode 6.1.1 I am able to put the code on iOS 8+ iOS7.1.2 and iOS 6.1.3
Although the warning is still there but the app works absolutely fine on all the 3 OSs
Yes not able to submit the app for review.
Had to do by changing the modern frameworks to Static libs.

A: this is happening because one of your embedded binaries's deployment target is lower than your applications target. lower your embeded binaries's building target and be fine.
this was the error cause in xcode 6.1.1
i was using xcglogger with deployment target ios 8.0, and my application's deployment target 7.0. set the xcglogger's deployment target ios 7.0 and problem solved.


text:
Q: Access relative CSS/JS files with htaccess rewrite rule I was recently asked if I could make my friends server address more user friendly. His current urls looks like this:
http://wwww.example.com/site/index.php?page=home
http://wwww.example.com/site/index.php?page=about/john
http://wwww.example.com/site/index.php?page=portfolio/concept-art/2013

He would like them to look like this
http://wwww.example.com/site/home
http://wwww.example.com/site/about/john
http://wwww.example.com/site/portfolio/concept-art/2013

which I thought would be pretty simple so I wrote this following rewrite.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !/(admin|css|fonts|ico|include|js)/
RewriteRule ^([^_]*)$ index.php?page=$1 [L]

which seems to work for the basic links like
http://wwww.example.com/site/home

but for something like this
http://wwww.example.com/site/about/john

none of the css or js will load. So I fixed that for now by making all of the files absolute paths but I am worried that my friend is going to add a new plugin or something and forget that he has to make it an absolute path.
My Question
Is there something I could change or add in my htaccess file to get the css and js files to load with a relative path? If so what would I need to do?

A: Better to use this rule:
RewriteEngine On
RewriteBase /site/

RewriteCond %{REQUEST_FILENAME} !/(admin|css|fonts|ico|include|js)/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+?)/?$ index.php?page=$1 [L,QSA]

Then for css/js/images better to use absolute path in your css, js, images files rather than a relative one. Which means you have to make sure path of these files start either with http:// or a slash /.
Alternatively You can try adding this in your page's header:
<base href="/" />

OR
<base href="http://domain.com/site/" />

A:
Is there something I could change or add in my htaccess file to get the css and js files to load with a relative path? If so what would I need to do?

You could just add the proper relative URI base in your page header:
<base href="/site/" />

Or you could brute force redirect them using mod_rewrite (not preferable):
RewriteRule ^(.+)/(admin|css|fonts|ico|include|js)/(.*)$ $2/$3 [L]


text:
Q: Application of Biot-Savart's law on a current-carrying wire of finite length
In this figure, how will the wire elements between O&a and O&-a affect the magnetic field at point 'P' which lies at a distance x from point O? Because none of the field lines created due to the wire elements between points a and O and points -a and O seem to pass through point P. Maybe I'm lacking some important concept.

Consider a point 'P' at some horizontal distance 'x' from the middle point of the wire. If we draw the magnetic field lines due to an infinitesimally small current-carrying wire element, then they don't seem to pass through point 'P' but still, we say that it affects the magnitude of the magnetic field vector at point 'P'...why?...because in order to do so the field lines due to all the tiny elements on the wire should pass through point 'P'...

A:
The field lines are concentric circles  in all plains perpendicular to the current density shaded in purple.
I have drawn smaller circles to indicate magnitude, but they extend to infinity.
Hence the field from the current density reaches point p

A: Physically speaking the current could not just end like you show. There should be charging on the apex of the wiring, otherwise wire should go somewhere. Anyway the Biot-Savare law stands that in vacuum
\begin{equation}
 \vec{B} = \frac{\mu_0} {4\pi}\int_{wire} \frac{I \vec{dl}\times \vec{r'} }{ |\vec{r'}|^2 }
\end{equation}
where $\vec{r'}$ is the vector from the local current to the observation point. So if you have a finite current source you could formally integrate over your finite wire in order to get the magnetic field.


text:
Q: Suggestions with Strings from File I am trying to read from a external file. I have successfully read from the file but now I have a little problem. The file contains around 88 verbs. The verbs are written in the file like this:
be was been
beat beat beaten
become became become
and so on...
What I need help with now is that I want a  quiz like programe where only two random strings from the verb will come up and the user have to fill inn the one which is missing. Instead of the one missing, I want this("------"). My english is not so good so I hope you understand what I mean.
    System.out.println("Welcome to the programe which will test you in english verbs!");
    System.out.println("You can choose to be tested in up to 88.");
    System.out.println("In the end of the programe you will get a percentage of total right answers.");

    Scanner in = new Scanner(System.in);
    System.out.println("Do you want to try??yes/no");

    String a = in.nextLine();
    if (a.equals("yes")) {
        System.out.println("Please enter the name of the file you want to choose: ");

    } else {
        System.out.println("Programe is ended!");
    }

    String b = in.nextLine();
    while(!b.equals("verb.txt")){
        System.out.println("You entered wrong name, please try again!");
         b = in.nextLine();

    }
    System.out.println("How many verbs do you want to be tested in?: ");
    int totalVerb = in.nextInt();
    in.nextLine();

    String filename = "verb.txt";
    File textFile = new File(filename);
    Scanner input = new Scanner(textFile);

    for (int i = 1; i <= totalVerb; i++){

        String line = input.nextLine();

        System.out.println(line);
        System.out.println("Please fill inn the missing verb: ");
        in.next();
    }

    System.out.println("Please enter your name: ");
    in.next();

A: You can do something like this
import java.util.Scanner;
import java.io.*;

public class GuessVerb {

    public static void main(String[] args) throws IOException{

        Scanner in = new Scanner(System.in);
        System.out.println("Enter a file name: ");

        String fileName = in.nextLine();
        File file = new File(fileName);

        Scanner input = new Scanner(file);

        String guess = null;
        int correctCount = 0;

        while(input.hasNextLine()) {
            String line = input.nextLine();          // get the line

            String[] tokens = line.split("\\s+");    // split it into 3 word

            int randNum = (int)(Math.random() * 3);  // get a random number 0, 1, 2

            String newLine = null;                          // new line

            int wordIndex = 0;
            switch(randNum){                         // case for random number
                case 0: newLine = "------ " + tokens[1] + " " + tokens[2];
                            wordIndex = 0; break;
                case 1: newLine = tokens[0] + " ------ " + tokens[2];
                            wordIndex = 1; break;
                case 2: newLine = tokens[0] + " " + tokens[1] + " -------";
                            wordIndex = 2; break;
           }

           System.out.println(newLine);

           System.out.println("Please fill inn the missing verb: ");
           guess = in.nextLine();

           if (guess.equals(tokens[wordIndex])){
               correctCount++;
           }
        }
        System.out.println("You got " + correctCount + " right");
    }
}

Above is complete running program.


text:
Q: How to set up node socket connection and access with REST I want to have a route on my sailsjs node server that is a socket connection. I want to then send a rest request to that route from outside the app and have the socket hear the event and update the UI of my app.
So far all I have seen on the web is to have a websocket server by itself. Is there no way to integrate it into an existing server?
I'm a bit lost here. Can anyone point me to a tutorial that is doing this?
Question: How do I send a rest request to my server from outside the app and have the server update the UI of my app?
If you need more clarity here, please let me know.

A: You Have to use WebSockets I think. The UI does not know anything about the server unless it is notified. The only other way to have it running without WebSockets is to have a long polling AJAX request, but that solution would work for a limited use cases.
Adding a Socket.io server to a node server is pretty trivial, I would give it a try.

A: Use socket.io, it can be added to every Node.js server. For example:

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs');

app.listen( 80 );

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(data);
  });
}

io.set('log level', 1);

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

You can use any socket event here.


text:
Q: Cleaning Android FrameLayout I'm trying to write simple animation in Java, so I'm asking if any of You know how to clean completly framelayout.

A: Reference your frame layout and then call removeAllViews() on that layout. This should clear the layout of all views.


text:
Q: What is "com.JWVD.cbcache.plist"? I'm trying to solve some problems and have run across a few things in Etrecheck of which I cannot determine the origin. One such item is the Launch Daemon "com.JWVD.cbcache.plist".
Does anyone know what this is? A Google Search reveals 3 previous posts of my own Etrecheck report containing this item and two German message board threads neither of which seem to be answering this particular question.
The content of the plist is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.JWVD.cbcache</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Library/PrivilegedHelperTools/com.JWVD.cbcache</string>
    </array>
    <key>ServiceIPC</key>
    <true/>
    <key>Sockets</key>
    <dict>
        <key>Listener</key>
        <dict>
            <key>SockPathMode</key>
            <integer>438</integer>
            <key>SockPathName</key>
            <string>/var/run/cbcache.socket</string>
        </dict>
    </dict>
    <key>StandardErrorPath</key>
    <string>/var/log/cbcache.err.log</string>
    <key>StandardOutPath</key>
    <string>/var/log/cbcache.out.log</string>
</dict>
</plist>

A: Google reckons it's Notifyr - https://itunes.apple.com/gb/app/notifyr-receive-ios-notifications/id873639935?mt=8
JWVD is probably the app author's initials - https://twitter.com/JWVD


text:
Q: How to format my dataset (from Grahpad Prism) to be usable with R (one row per sample)? I imported my dataset from Graphpad Prism:
library(xml2)
library(pzfx)
pzfx_tables("Dataprism.pzfx") #read prism file
datapoids <- read_pzfx("Dataprism.pzfx", "poidsXY") #import wanted sheet

datapoids
   time ttt1_1 ttt1_2 ttt1_3 ttt2_1 ttt2_2 ttt2_3 ttt3_1 ttt3_2 ttt3_3
1     1      0      0      0      0      0      0      0      0      0
2     2     15     17     19     45     51     57     90    102    114
3     3     20     22     25     60     66     75    120    132    150
4     4     30     34     36     90    102    108    180    204    216
5     5     40     50     47    120    130    141    240    300    282
6     6     50     50     60    150    150    180    300    300    360
7     7     60     65     70    210    228    245    420    455    490
8     8     70     75     86    245    262    301    490    525    602
9     9     80     90    110    280    315    385    560    630    770
10   10     90    120    130    315    420    455    630    840    910
11   11    130    160    195    455    560    683    910   1120   1365
12   12    160    200    240    560    700    840   1120   1400   1680
13   13    240    300    360    720    900   1080   1440   1800   2160
14   14    320    400    480    960   1200   1440   1920   2400   2880
15   15    450    500    650   1350   1500   1950   2700   3000   3900

> dput(head(datapoids, 10000000))
structure(list(time = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15), ttt1_1 = c(0, 15, 20, 30, 40, 50, 60, 70, 80, 90,
130, 160, 240, 320, 450), ttt1_2 = c(0, 17, 22, 34, 50, 50, 65,
75, 90, 120, 160, 200, 300, 400, 500), ttt1_3 = c(0, 19, 25,
36, 47, 60, 70, 86, 110, 130, 195, 240, 360, 480, 650), ttt2_1 = c(0,
45, 60, 90, 120, 150, 210, 245, 280, 315, 455, 560, 720, 960,
1350), ttt2_2 = c(0, 51, 66, 102, 130, 150, 228, 262, 315, 420,
560, 700, 900, 1200, 1500), ttt2_3 = c(0, 57, 75, 108, 141, 180,
245, 301, 385, 455, 683, 840, 1080, 1440, 1950), ttt3_1 = c(0,
90, 120, 180, 240, 300, 420, 490, 560, 630, 910, 1120, 1440,
1920, 2700), ttt3_2 = c(0, 102, 132, 204, 300, 300, 455, 525,
630, 840, 1120, 1400, 1800, 2400, 3000), ttt3_3 = c(0, 114, 150,
216, 282, 360, 490, 602, 770, 910, 1365, 1680, 2160, 2880, 3900
)), row.names = c(NA, 15L), class = "data.frame")

Where the first column represent each timepoint. Other columns represent various measurment of weight at each timepoint in different group: group1 (3 individuals: ttt1_1, ttt1_2, ttt1_3), group1 (3 individuals: ttt2_1, ttt2_2, ttt2_3) and group3 (3 individuals: ttt3_1, ttt3_2, ttt3_3).
But to draw a plot with ggplot2 I have to change how my dataset is arranged.
I manually formated the dataset too look like this:
> print.data.frame(datapoids)
    weight group time
1        0     1    1
2        0     1    1
3        0     1    1
4        0     2    1
5        0     2    1
6        0     2    1
7        0     3    1
8        0     3    1
9        0     3    1
10      15     1    2
11      17     1    2
12      19     1    2
13      45     2    2
14      51     2    2
15      57     2    2
16      90     3    2
17     102     3    2
18     114     3    2
19      20     1    3
20      22     1    3
21      25     1    3
22      60     2    3
23      66     2    3
24      75     2    3
25     120     3    3
26     132     3    3
27     150     3    3
28      30     1    4
29      34     1    4
30      36     1    4
31      90     2    4
32     102     2    4
33     108     2    4
34     180     3    4
35     204     3    4
36     216     3    4
37      40     1    5
38      50     1    5
39      47     1    5
40     120     2    5
41     130     2    5
42     141     2    5
43     240     3    5
44     300     3    5
45     282     3    5
46      50     1    6
47      50     1    6
48      60     1    6
49     150     2    6
50     150     2    6
51     180     2    6
52     300     3    6
53     300     3    6
54     360     3    6
55      60     1    7
56      65     1    7
57      70     1    7
58     210     2    7
59     228     2    7
60     245     2    7
61     420     3    7
62     455     3    7
63     490     3    7
64      70     1    8
65      75     1    8
66      86     1    8
67     245     2    8
68     262     2    8
69     301     2    8
70     490     3    8
71     525     3    8
72     602     3    8
73      80     1    9
74      90     1    9
75     110     1    9
76     280     2    9
77     315     2    9
78     385     2    9
79     560     3    9
80     630     3    9
81     770     3    9
82      90     1   10
83     120     1   10
84     130     1   10
85     315     2   10
86     420     2   10
87     455     2   10
88     630     3   10
89     840     3   10
90     910     3   10
91     130     1   11
92     160     1   11
93     195     1   11
94     455     2   11
95     560     2   11
96     683     2   11
97     910     3   11
98    1120     3   11
99    1365     3   11
100    160     1   12
101    200     1   12
102    240     1   12
103    560     2   12
104    700     2   12
105    840     2   12
106   1120     3   12
107   1400     3   12
108   1680     3   12
109    240     1   13
110    300     1   13
111    360     1   13
112    720     2   13
113    900     2   13
114   1080     2   13
115   1440     3   13
116   1800     3   13
117   2160     3   13
118    320     1   14
119    400     1   14
120    480     1   14
121    960     2   14
122   1200     2   14
123   1440     2   14
124   1920     3   14
125   2400     3   14
126   2880     3   14
127    450     1   15
128    500     1   15
129    650     1   15
130   1350     2   15
131   1500     2   15
132   1950     2   15
133   2700     3   15
134   3000     3   15
135   3900     3   15

> dput(head(datapoids, 10000000))
structure(list(weight = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 17,
19, 45, 51, 57, 90, 102, 114, 20, 22, 25, 60, 66, 75, 120, 132,
150, 30, 34, 36, 90, 102, 108, 180, 204, 216, 40, 50, 47, 120,
130, 141, 240, 300, 282, 50, 50, 60, 150, 150, 180, 300, 300,
360, 60, 65, 70, 210, 228, 245, 420, 455, 490, 70, 75, 86, 245,
262, 301, 490, 525, 602, 80, 90, 110, 280, 315, 385, 560, 630,
770, 90, 120, 130, 315, 420, 455, 630, 840, 910, 130, 160, 195,
455, 560, 683, 910, 1120, 1365, 160, 200, 240, 560, 700, 840,
1120, 1400, 1680, 240, 300, 360, 720, 900, 1080, 1440, 1800,
2160, 320, 400, 480, 960, 1200, 1440, 1920, 2400, 2880, 450,
500, 650, 1350, 1500, 1950, 2700, 3000, 3900), group = structure(c(1L,
1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L,
3L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L,
3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 1L, 2L,
2L, 2L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L,
1L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L,
1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 3L,
3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L,
2L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 1L,
2L, 2L, 2L, 3L, 3L, 3L), .Label = c("1", "2", "3"), class = "factor"),
    time = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L,
    5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 7L,
    7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
    8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 10L, 10L, 10L,
    10L, 10L, 10L, 10L, 10L, 10L, 11L, 11L, 11L, 11L, 11L, 11L,
    11L, 11L, 11L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L,
    13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 14L, 14L, 14L,
    14L, 14L, 14L, 14L, 14L, 14L, 15L, 15L, 15L, 15L, 15L, 15L,
    15L, 15L, 15L), .Label = c("1", "2", "3", "4", "5", "6",
    "7", "8", "9", "10", "11", "12", "13", "14", "15"), class = "factor")), row.names = c(NA,
-135L), class = c("tbl_df", "tbl", "data.frame"))

But is there a way to do it within R? Thanks for your help!

A: Early on I experimented implementing a way for users to "reshape" pzfx tables with replicates in subcolumns, but ended up not doing it because I felt table transformation seems better done downstream, using the tidyverse suite for example. In your case, I'd do:
library(tidyverse)

datapoids <- structure(list(time = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15), ttt1_1 = c(0, 15, 20, 30, 40, 50, 60, 70, 80, 90,
130, 160, 240, 320, 450), ttt1_2 = c(0, 17, 22, 34, 50, 50, 65,
75, 90, 120, 160, 200, 300, 400, 500), ttt1_3 = c(0, 19, 25,
36, 47, 60, 70, 86, 110, 130, 195, 240, 360, 480, 650), ttt2_1 = c(0,
45, 60, 90, 120, 150, 210, 245, 280, 315, 455, 560, 720, 960,
1350), ttt2_2 = c(0, 51, 66, 102, 130, 150, 228, 262, 315, 420,
560, 700, 900, 1200, 1500), ttt2_3 = c(0, 57, 75, 108, 141, 180,
245, 301, 385, 455, 683, 840, 1080, 1440, 1950), ttt3_1 = c(0,
90, 120, 180, 240, 300, 420, 490, 560, 630, 910, 1120, 1440,
1920, 2700), ttt3_2 = c(0, 102, 132, 204, 300, 300, 455, 525,
630, 840, 1120, 1400, 1800, 2400, 3000), ttt3_3 = c(0, 114, 150,
216, 282, 360, 490, 602, 770, 910, 1365, 1680, 2160, 2880, 3900
)), row.names = c(NA, 15L), class = "data.frame")

datapoids %>%
  gather(group_indiv, weight, 2:ncol(datapoids)) %>% # make the "tidy" thin & tall table
  mutate(group = as.integer(gsub("ttt|_.*", "", group_indiv))) %>% # extract group info
  select(weight, group, time) # select and order as needed

and this gives the table you described:
    weight group time
1        0     1    1
2       15     1    2
3       20     1    3
4       30     1    4
5       40     1    5
6       50     1    6
7       60     1    7
8       70     1    8
9       80     1    9
10      90     1   10

Output truncated.


text:
Q: How to get confidence interval for smooth.spline? I have used smooth.spline to estimate a cubic spline for my data. But when I calculate the 90% point-wise confidence interval using equation, the results seems to be a little bit off. Can someone please tell me if I did it wrongly? I am just wondering if there is a function that can automatically calculate a point-wise interval band associated with smooth.spline function.
boneMaleSmooth = smooth.spline( bone[males,"age"], bone[males,"spnbmd"], cv=FALSE)
error90_male = qnorm(.95)*sd(boneMaleSmooth$x)/sqrt(length(boneMaleSmooth$x))

plot(boneMaleSmooth, ylim=c(-0.5,0.5), col="blue", lwd=3, type="l", xlab="Age",
     ylab="Relative Change in Spinal BMD")
points(bone[males,c(2,4)], col="blue", pch=20)
lines(boneMaleSmooth$x,boneMaleSmooth$y+error90_male, col="purple",lty=3,lwd=3)
lines(boneMaleSmooth$x,boneMaleSmooth$y-error90_male, col="purple",lty=3,lwd=3)

Because I am not sure if I did it correctly, then I used gam() function from mgcv package.
It instantly gave a confidence band but I am not sure if it is 90% or 95% CI or something else. It would be great if someone can explain.
males=gam(bone[males,c(2,4)]$spnbmd ~s(bone[males,c(2,4)]$age), method = "GCV.Cp")
plot(males,xlab="Age",ylab="Relative Change in Spinal BMD")

A: The R package mgcv calculates smoothing splines and Bayesian "confidence intervals." These are not confidence intervals in the usual (frequentist) sense, but numerical simulations have shown that there is almost no difference; see the linked paper by Marra and Wood in the help file of mgcv.
library(SemiPar)
data(lidar)
require(mgcv)

fit=gam(range~s(logratio), data = lidar)
plot(fit)
with(lidar, points(logratio, range-mean(range)))

A: I'm not sure the confidence intervals for smooth.spline have "nice" confidence intervals like those form lowess do. But I found a code sample from a CMU Data Analysis course to make Bayesian bootstap confidence intervals.
Here are the functions used and an example. The main function is spline.cis where the first parameter is a data frame where the first column are the x values and the second column are the y values. The other important parameter is B which indicates the number bootstrap replications to do. (See the linked PDF above for the full details.)
# Helper functions
resampler <- function(data) {
    n <- nrow(data)
    resample.rows <- sample(1:n,size=n,replace=TRUE)
    return(data[resample.rows,])
}

spline.estimator <- function(data,m=300) {
    fit <- smooth.spline(x=data[,1],y=data[,2],cv=TRUE)
    eval.grid <- seq(from=min(data[,1]),to=max(data[,1]),length.out=m)
    return(predict(fit,x=eval.grid)$y) # We only want the predicted values
}

spline.cis <- function(data,B,alpha=0.05,m=300) {
    spline.main <- spline.estimator(data,m=m)
    spline.boots <- replicate(B,spline.estimator(resampler(data),m=m))
    cis.lower <- 2*spline.main - apply(spline.boots,1,quantile,probs=1-alpha/2)
    cis.upper <- 2*spline.main - apply(spline.boots,1,quantile,probs=alpha/2)
    return(list(main.curve=spline.main,lower.ci=cis.lower,upper.ci=cis.upper,
    x=seq(from=min(data[,1]),to=max(data[,1]),length.out=m)))
}

#sample data
data<-data.frame(x=rnorm(100), y=rnorm(100))

#run and plot
sp.cis <- spline.cis(data, B=1000,alpha=0.05)
plot(data[,1],data[,2])
lines(x=sp.cis$x,y=sp.cis$main.curve)
lines(x=sp.cis$x,y=sp.cis$lower.ci, lty=2)
lines(x=sp.cis$x,y=sp.cis$upper.ci, lty=2)

And that gives something like

Actually it looks like there might be a more parametric way to calculate confidence intervals using the jackknife residuals. This code comes from the S+ help page for smooth.spline
  fit <- smooth.spline(data$x, data$y)      # smooth.spline fit
  res <- (fit$yin - fit$y)/(1-fit$lev)      # jackknife residuals
sigma <- sqrt(var(res))                     # estimate sd

upper <- fit$y + 2.0*sigma*sqrt(fit$lev)   # upper 95% conf. band
lower <- fit$y - 2.0*sigma*sqrt(fit$lev)   # lower 95% conf. band
matplot(fit$x, cbind(upper, fit$y, lower), type="plp", pch=".")

And that results in

And as far as the gam confidence intervals go, if you read the print.gam help file, there is an se= parameter with default TRUE and the docs say

when TRUE (default) upper and lower lines are added to the 1-d plots at 2 standard errors above and below the estimate of the smooth being plotted while for 2-d plots, surfaces at +1 and -1 standard errors are contoured and overlayed on the contour plot for the estimate. If a positive number is supplied then this number is multiplied by the standard errors when calculating standard error curves or surfaces. See also shade, below.

So you can adjust the confidence interval by adjusting this parameter. (This would be in the print() call.)


text:
Q: Arduino Nano SD Append data from existing File (.csv) I saw the function "fseek" to get a position into a File. But it doesn't works, i dont know why. I want to add text in the end of the file (append)and have the historical measurements from differents days.
    void init_SD(void) {
     // init sd
      Serial.print("Iniciando SD ...");
      if (!SD.begin(chip_select)) {
        Serial.println("No se pudo inicializar");
        return;
      }
      Serial.println("Inicializacion exitosa");

      if (!SD.exists("filename.csv")) // voy a escribir el archivo llamado "ensayo.csv": si existe, lo escribo. Si NO existe, lo crea
      {
        // uso de archivo--> see below "A"
        myFile = SD.open("filename.csv", FILE_WRITE);
        if (myFile) {
          myFile.fseek(myFile.size());
          myFile.println("Titulo Archivo");
          myFile.println("Hora de Medicion,Tiempo [s],Corriente [A]");
          myFile.close();
        } else {
          Serial.println("Error creando el archivo");
        }
      }
    }

"A": when i use this, the text doesnt appear in the .csv. Should i use "file.fread" before use fseek?
I used SD.open("filename.csv", O_APPEND) and  SD.open("filename.csv", O_WRITE) but the same problem.
Hw: Arduino nano + shield "datalogger" with RTC and SD card.
Sw: Arduino IDE with (SD.h, SPI.h).
Thanks!


text:
Q: How to tune this PID loop I have a DC motor that is controlled by an FPGA and a L298N motor driver board. The FPGA generates a PWM signal based on feedback from a dual channel quadrature rotary encoder (1000ppr per channel).
I have the code at the bottom of this post showing the PID code used to produce the error (PWM) signal for the motor driver. The PID code takes the setpoint and actual speeds in RPM and calculates the error based on the PID constants. The PID scan rate is 16ms which I think is to slow for this application, but as fast as I can currently get and I would like the tune the PID loop for this code run time.
I have some information about the running with constant changes (kd and ki not used yet):
Setpoint = 3500rpm and kp = 4, motor runs at constant 2750rpm and 80% duty cycle.
Setpoint = 3500rpm and kp = 5, motor fluctuates between 2830rpm and 2920rpm and between 79% and 83% duty cycle.
Setpoint = 3500rpm and kp = 6, motor fluctuates between 2920rpm and 3050rpm and between 78% and 85% duty cycle.
Setpoint = 3500rpm and kp = 7, motor fluctuates between 2970rpm and 3130rpm and between 77% and 86% duty cycle.
Setpoint = 3500rpm and kp = 8, motor fluctuates between 3000rpm and 3280rpm and between 68% and 90% duty cycle.
Setpoint = 3500rpm and kp = 9, motor fluctuates between 3020rpm and 3330rpm and between 71% and 91% duty cycle.
Setpoint = 3500rpm and kp = 10, motor fluctuates between 3080rpm and 3390rpm and between 70% and 94% duty cycle.
Setpoint = 3500rpm and kp = 13, motor fluctuates between 3100rpm and 3600rpm and between 25% and 91% duty cycle changing rapidly.
You can see with kp = 9, the duty cycle is starting to oscillate with the rpm value also starting to oscillate with some steady error.
And with kp = 13, the oscillation is very bad.
How should I go about tuning this system from here?

--This code contains the logic for generating the PWM output signal for the motor, based
--on the PID control loop.

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;
use work.Data_Sizes_Package.ALL;

entity PWM_Counter_and_Comparator is

 Generic (Max_Counter_Value : integer := 5000);

 Port (PWM_Comparison_Value : in std_logic_vector(27 downto 0);
       Clock : in std_logic;
       PID_Run_Command : in std_logic;
       Run_Reset : in std_logic;
       PWM_Output : out std_logic
       );
end PWM_Counter_and_Comparator;

architecture Behavioral of PWM_Counter_and_Comparator is

signal Setpoint_RPM : integer range 0 to 5000 := 0;
signal Actual_RPM : integer range 0 to 5000 := 0;
signal Count_Value : integer range 0 to 5000 := 0;
signal PID_Comparison_Value : integer range 0 to 5000 := 0;
signal PID_Comparison_Value_Buffer : integer range 0 to 5000 := 0;

constant Kp : integer := 5;
constant Ki : integer := 0;
constant Kd : integer := 0;

begin

Setpoint_RPM <= conv_integer(unsigned(PWM_Comparison_Value(13 downto 0)));  --Convert setpoint RPM from a vector to an integer
Actual_RPM <= conv_integer(unsigned(PWM_Comparison_Value(27 downto 14)));   --Convert actual RPM from a vector to an integer

Process(Clock , Run_Reset)  --This process generates a counter ranging from 0 to 5000 with a 100MHz clock.
                            --Used to create a 20kHz PWM output frequency.
begin

    if(Run_Reset = '0') then    --When run command is low, reset counter.
      Count_Value <= 0;

    elsif(rising_edge(Clock)) then

         if(Count_Value = Max_Counter_Value) then
            Count_Value <= 0;                                       --Resets counter back to 0 once it reaches 5000.
            PID_Comparison_Value <= PID_Comparison_Value_Buffer;    --Updates the new counter comparison value from PID calculation only when counter = 0

         elsif(Run_Reset = '1') then
               Count_Value <= Count_Value + 1;      --Increments counter on clock rising edge.

         end if;

     end if;

end Process;

Process(Clock)

variable Error_RPM :  integer range -5000 to 5000 := 0;
variable Last_Error_RPM : integer range -50000000 to 50000000 := 0;
variable Error_Sum:  integer range -50000000 to 5000000 := 0;
variable Error_Change:  integer range -50000000 to 50000000 := 0;
variable PID_Temp:  integer range -50000000 to 50000000 := 0;
variable PID_Output:  integer range 0 to 5000 := 0;

begin

    if(Run_Reset = '0') then
      Error_RPM := 0;
      Last_Error_RPM := 0;
      Error_Sum := 0;
      Error_Change := 0;
      PID_Output := 0;

    elsif((falling_edge(Clock)) and Run_Reset = '1' and PID_Run_Command = '1') then  --PID clock is 41.67Hz, perfoming this process every 16ms.

      Error_RPM := Setpoint_RPM - Actual_RPM;   --Calculate error in rpm

      Error_Sum := Error_Sum + Error_RPM;       --Integral not used yet

      if(Error_Sum > 20000) then                --Setting max integral limit
         Error_Sum := 20000;

      elsif(Error_Sum < -20000) then
         Error_Sum := -20000;                   --Setting min integral limit
      end if;

      Error_Change := Error_RPM - Last_Error_RPM;   --Derivative not used yet

      PID_Temp := ((Kp * Error_RPM) + (Ki * Error_Sum) + (Kd * Error_Change) / 100); --PID output signal calculation

      Last_Error_RPM := Error_RPM;

        if(PID_Temp > Max_Counter_Value) then --Max_Counter_Value = 5000 = 100% duty cycle
            PID_Temp := Max_Counter_Value;

         elsif(PID_Temp < -5000) then  -- -5000 = 0% duty cycle
           PID_Temp := -5000;

          end if;

      end if;

      PID_Output := (PID_Temp + 5000) / 2;     --This scales the PID_Temp calculation result from -5000 to 5000, into a
                                               --value between 0 and 5000 to match the counter value for duty cycle.

      PID_Comparison_Value_Buffer <= PID_Output;    --Buffer used to hold the PID_Output until counter is equal to zero.

end Process;

Process(Clock , Run_Reset)

begin

    if((Count_Value < PID_Comparison_Value) and (Run_Reset = '1')) then
      PWM_Output <= '1';
                                                --This process sets the output pin high and low at a frequency of 20kHz.
    else                                        --Compares the counter value with the PID calculation output.
      PWM_Output <= '0';                        --The ratio between count value and comparison value is the duty cycle.
                                                --i.e. count value = 5000, comparison value = 2500, duty cycle = 5000/2500 = 50%
    end if;

end Process;

end Behavioral;
```

A: I remember to have gone through your code some days ago. Finaly thinking that you had fixed your issue I did not comment.
Frankly speaking it is really dirty what you coded from an FPGA engineering point of view. It would not pass a code review in the industry.
Here are my remarks:
1- PWM_Comparison_Value port: Just a cosmetic remarks, it does not improve readability to concatenate 2 signals in one
2- Reset: All signals are not reset
3- Reset: Is the reset synchronously deasserted somewhere?
4- Integers: Use integers for signals if you are totally aware of what is synthesized by the tool inside the FPGA. Otherwise make the effort to use unsigned or signed types
4b- Avoid to use variables / pipeline your design so operations are done in several clock pulses
5- Math operations scalling: I recommend you to check that all your Maths operation line of codes do not overflow. That your calculations fit inside signals ranges.
6- No if falling edge: There is a common FPGA coding rule to use only rising or falling edge on a clock but not both. Functionally it looks like you gain half a clock cycle of latency. Behind the scene you double the constraint frequency.
7- Testbench: Create a testbench of your module in closed loop, tune it, make it working and then continue on target. You can create a simple model in the top testbench file.
Point 7 is the most important to me.
I hope this helps


text:
Q: IRenderFactory help in Minecraft Forge I've been having trouble with the new syntax for entity registry, specifically rendering the entity. Before, you simply added the RenderingRegistry.registerEntityRenderingHandler line to your ClientProxy, and that was that. But now, it's asking me to use RenderingRegistry.registerEntityRenderingHandler in the preInit along with a parameter called IRenderFactory. I'm not really sure how IRenderFactory works, or how I can create one (if I need to).
I've been told that you can use a method reference to pass your Render class's constructor (RenderMyEntity::new) as an IRenderFactory instead, but I really don't know how to go about this. I've done all kinds of research, but none of it makes sense.
Here's my MobExample class (the line RenderingRegistry.registerEntityRenderingHandler(RenderGelZombie.class, renderFactory) only works in the preInit of MobExample class, which is why it's there and not in ClientProxy):
package com.aideux.mobexample;

import com.aideux.basemod.BaseMod;

import net.minecraft.client.model.ModelZombie;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.fml.common.registry.EntityRegistry;

public class MobExample
{
public static int currentEntityId = 0;

public static void preInit()
{
    createEntityWithEgg(EntityGelZombie.class, "CustomMob", 0x00FF00, 0xFF0000);
    RenderingRegistry.registerEntityRenderingHandler(RenderGelZombie.class, renderFactory);
}

public static void init()
{
    BaseMod.proxy.registerEntityRenderers();
}

public static void createEntityWithEgg(Class entityClass, String entityName, int solidColor, int spotColor)
{
    int entityId = currentEntityId++;
    EntityRegistry.registerModEntity(entityClass, entityName, entityId, BaseMod.instance, 250, 1, true, solidColor, spotColor);
}
}

A: The IRenderingFactory interface in Forge creates instances of the Render class for your Entity. The docs that zapl linked above explain more about what an interface is as a concept.
In this case, you've got a class called RenderGelZombie that handles actually rendering your zombie in the game. Forge used to use this class directly when registering renderers, but now it uses IRenderingFactory to make instances of the render class. You'll need a factory class like this:
public class RenderGelZombieFactory implements IRenderFactory<EntityLiving> {

    public static final RenderGelZombieFactory INSTANCE = new RenderGelZombieFactory();

    @Override
    public Render<? super EntityLiving> createRenderFor(RenderManager manager) {
        // TODO Auto-generated method stub
        return new RenderGelZombie(manager, new ModelBiped(1.0f), 1.0f);
    }

}

Now that you've got a class that implements the IRenderFactory, you can pass it to the new entity rendering registry method:
RenderingRegistry.registerEntityRenderingHandler(EntityGelZombie.class, RenderGelZombieFactory.INSTANCE);

Source: I'm the curriculum developer for the iD Tech Camps Minecraft Modding course, and it looks like some of your code might have come from there!