text:
Q: Creating objects from another object with same properties I have an object in C# with lets say 20 properties and it's part of a datacontract. I also have another business entity with similar properties, which I want to populate from the response object.  Is there any way to do this other than assigning each property of one object to the corresponding properties of the other?

A: Yes, take a look at Automapper

A: MiscUtil has an answer to this (PropertyCopy) that uses Expression (.NET 3.5) and a static field to cache the compiled delegate (so there is negligible cost per invoke):
DestType clone = PropertyCopy<DestType>.CopyFrom(original);

If you are using 2.0, then probably reflection would be your friend. You can use HyperDescriptor to improve the performance if you need.

A: Reflection is an option if you want to do it in an automated manner, provided the property names are easily mappable between the objects.

A: Automapper is worth a try, but in the end, I decided it wasn't for me.  The big problem with those sorts of tools is you incur a great deal of runtime overhead each and every time a mapping occurs.  I asked this same question last week and I ended up rolling my own solution (look at the accepted answer).  You're free to modify the source I provided, I make no claims as to it's effectiveness, suitability, performance, you-break-it-you-get-to-keep-the-pieces, etc., but it works well enough for me to create design time object to object mapping.

A: C# Object Clone Wars might be a good starting point.


text:
Q: Formula to add week ended date based on date value in different cell but add another week based on value in a separate cell I have created a formula where the week ended date is added to Column M if a date is entered into Column L and appears blank when Column L is blank.
=IF(L1<>"",L1+6-WEEKDAY(L1),"")

However, I would like to have an additional week added to Column M if there is any value entered into Column K in that same row.
=IF(L16<>"",L16+13-WEEKDAY(L16),"")

If column K is blank, column L has a date, column M will fill with the week ending date of the value in column L
If column K has any value, Column L has a date, column M will fill with the week ending date + 7 days (the following Friday)
I want Column M to appear blank when Column L is not used regardless of a value in Column K
The result should look like this:

Please let me know if this can be done all within one formula.

A: You can modify your original formula to add an additional 0 days if the value in K1 is blank and 7 days if it is not blank.
=IF(ISNUMBER(L1),L1+6-WEEKDAY(L1)+IF(ISBLANK(K1),0,7),"")

Note that I have changed the test on L1 to check for a number. A text value in L1 would cause an error with your formula.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Time slot from table with available hours (not time slots in table) PHP/MySQL SELECT
I have a table with available hours a specific day for a meeting room. The Temp_Res get the timestamp when a booking is ongoing (to lock those rows). I would like to get every possible time slot if meeting to be booked is 2 hours.
Day     Hour      Temp_Res
22        8           0000-00-00 00:00:00
22        9           0000-00-00 00:00:00
22        10         0000-00-00 00:00:00
22        11         2012-05-18 22:02:00
22        12         2012-05-18 22:02:00
22        13         2012-05-18 22:02:00
22        14         0000-00-00 00:00:00
22        15         0000-00-00 00:00:00
22        16         0000-00-00 00:00:00
22        17         0000-00-00 00:00:00
So, if the time slotneeded is 2 hours, only Hour 8, 9, 14, 15, 16 would be the output. (I would then use the hour and add 2 to get the slots: 8-10, 9-11, 14-16, 15-17 and 16-18)
If time slot is 3 hours, only Hour 8, 14, 15 would be the output and slots: 8-11, 14-17, 15-18....etc
To be able to do this in a SELECT (if possible) there must be a way of looking on the other rows in the table to determine if the specific row shall be included or not.
1. Is it possible to look on other rows and do this with a SELECT with WHERE (or similar)?
2. If possible, could you please guide me into the right direction?
3. Other solutions/ideas (except the ones below) are also very appreciated!
Otherwise I have to solve it by:
a) creating an extra time slot table
b) having an extra column stating the maximum time slot for that specific row, see below.
Day     Hour   Slot      Temp_Res
22        8        3           0000-00-00 00:00:00
22        9        2           0000-00-00 00:00:00
22        10      1           0000-00-00 00:00:00
22        11      0           2012-05-18 22:02:00
22        12      0           2012-05-18 22:02:00
22        13      0           2012-05-18 22:02:00
22        14      4           0000-00-00 00:00:00
22        15      3           0000-00-00 00:00:00
22        16      2           0000-00-00 00:00:00
22        17      1           0000-00-00 00:00:00
SELECT Day, Hour FROM table
WHERE Slot>=2 AND Temp_Res<"2012-05-18 22:00:00"
GROUP BY Day, Hour

A: I would suggest using the start time and the meeting length to compute the end time, which is equivalent to "the last hour that needs to be free in order for this booking to occur." You can then use an inner join to only select start times where every hour up to the end time is also unbooked. For a four-hour meeting, your query might look like this:
SELECT start.day, start.hour from table as start
INNER JOIN table as hour1
    ON ((hour1.hour = start.hour + 1) AND (hour1.TempRes = '0000-00-00 00:00:00'))
INNER JOIN table as hour2
    ON ((hour2.hour = start.hour + 2) AND (hour2.TempRes = '0000-00-00 00:00:00'))
INNER JOIN table as hour3
    ON ((hour2.hour = start.hour + 3) AND (hour3.TempRes = '0000-00-00 00:00:00'))
WHERE table.TempRes = '0000-00-00 00:00:00'

You can use a loop in PHP to add the required number of inner join clauses onto your query text (and because you're using a variable you calculated yourself, you don't have to worry about injection). It will always be (duration of meeting - 1).
This will return no open times if someone tries to schedule a meeting that would go across midnight, but if that's undesired you can easily write logic to increment the day variable appropriately.


text:
Q: Android create semi resizeable box So basically I have 3 boxes on screen, each displaying different information regarding audio frequencys.
The top box shows the Note, Middle shows the pitch of that Note, and 3rd shows your pitch.
I wanted to have the numbers in a box, and since they constantly change, I wanted the box to remain a certain size instead of constantly increasing in size to fit the text. However, I also don't want to give the boxes a specific size as I want them to be able to resize depending on the screen size.
Is there a way to do this easily? Or would I have to create separate XML files for each device or something?
I will attach an image so you can see what I mean.
Image: http://i.imgur.com/5NVR54N.png
So just imagine that each box is resizing itself depending on what text is placed in the box.
Any help with this would be great thanks!

A: *

*If "So just imagine that each box is re-sizing itself depending on what text is placed in the box" this is needed then in the XML for the TextView widget that you use for displaying the values use.,
android:layoutWidth="wrap_content", android:layoutHeight="wrap_content" . The wXh of the view would be adjusted according to the content (values) .

*If "I wanted the box to remain a certain size instead of constantly increasing in size to fit the text." -If this is not done, that is if you have fixed width text widgets, then the text will be clipped if they exceed the max width.
2.1 By above if you mean same size on each device, then figure out the maximum possible width/height on a mdpi (320X480 mdpi) emulator for each textview, say 100px width and 80px height and  is what suits you for the Note, then in the XML for the TextView widget for Note use  android:layoutWidth="100dp", android:layoutHeight="80dp" where "dp" would give you device independent pixel size, meaning the size will be adjusted according to the screen density on which the emulator is running.
http://developer.android.com/training/multiscreen/screensizes.html and related material should help.


text:
Q: How to perform feature selection with gridsearchcv in sklearn in python I am using recursive feature elimination with cross validation (rfecv) as a feature selector for randomforest classifier as follows.
X = df[[my_features]] #all my features
y = df['gold_standard'] #labels

clf = RandomForestClassifier(random_state = 42, class_weight="balanced")
rfecv = RFECV(estimator=clf, step=1, cv=StratifiedKFold(10), scoring='roc_auc')
rfecv.fit(X,y)

print("Optimal number of features : %d" % rfecv.n_features_)
features=list(X.columns[rfecv.support_])

I am also performing GridSearchCV as follows to tune the hyperparameters of RandomForestClassifier as follows.
X = df[[my_features]] #all my features
y = df['gold_standard'] #labels

x_train, x_test, y_train, y_test = train_test_split(X, y, random_state=0)

rfc = RandomForestClassifier(random_state=42, class_weight = 'balanced')
param_grid = {
    'n_estimators': [200, 500],
    'max_features': ['auto', 'sqrt', 'log2'],
    'max_depth' : [4,5,6,7,8],
    'criterion' :['gini', 'entropy']
}
k_fold = StratifiedKFold(n_splits=10, shuffle=True, random_state=0)
CV_rfc = GridSearchCV(estimator=rfc, param_grid=param_grid, cv= k_fold, scoring = 'roc_auc')
CV_rfc.fit(x_train, y_train)
print(CV_rfc.best_params_)
print(CV_rfc.best_score_)
print(CV_rfc.best_estimator_)

pred = CV_rfc.predict_proba(x_test)[:,1]
print(roc_auc_score(y_test, pred))

However, I am not clear how to merge feature selection (rfecv) with GridSearchCV.
EDIT:
When I run the answer suggested by @Gambit I got the following error:
ValueError: Invalid parameter criterion for estimator RFECV(cv=StratifiedKFold(n_splits=10, random_state=None, shuffle=False),
   estimator=RandomForestClassifier(bootstrap=True, class_weight='balanced',
            criterion='gini', max_depth=None, max_features='auto',
            max_leaf_nodes=None, min_impurity_decrease=0.0,
            min_impurity_split=None, min_samples_leaf=1,
            min_samples_split=2, min_weight_fraction_leaf=0.0,
            n_estimators='warn', n_jobs=None, oob_score=False,
            random_state=42, verbose=0, warm_start=False),
   min_features_to_select=1, n_jobs=None, scoring='roc_auc', step=1,
   verbose=0). Check the list of available parameters with `estimator.get_params().keys()`.

I could resolve the above issue by using estimator__ in the param_grid parameter list.

My question now is How to use the selected features and parameters in x_test to verify if the model works fine with unseen data. How can I obtain the best features and train it with the optimal hyperparameters?
I am happy to provide more details if needed.

A: You can do what you want by prefixing the names of the parameters you want to pass to the estimator with 'estimator__'.
X = df[[my_features]]
y = df[gold_standard]

clf = RandomForestClassifier(random_state=0, class_weight="balanced")
rfecv = RFECV(estimator=clf, step=1, cv=StratifiedKFold(3), scoring='roc_auc')

param_grid = {
    'estimator__n_estimators': [200, 500],
    'estimator__max_features': ['auto', 'sqrt', 'log2'],
    'estimator__max_depth' : [4,5,6,7,8],
    'estimator__criterion' :['gini', 'entropy']
}
k_fold = StratifiedKFold(n_splits=3, shuffle=True, random_state=0)

CV_rfc = GridSearchCV(estimator=rfecv, param_grid=param_grid, cv= k_fold, scoring = 'roc_auc')

X_train, X_test, y_train, y_test = train_test_split(X, y)

CV_rfc.fit(X_train, y_train)

Output on fake data I made:
{'estimator__n_estimators': 200, 'estimator__max_depth': 6, 'estimator__criterion': 'entropy', 'estimator__max_features': 'auto'}
0.5653035605690997
RFECV(cv=StratifiedKFold(n_splits=3, random_state=None, shuffle=False),
   estimator=RandomForestClassifier(bootstrap=True, class_weight='balanced',
            criterion='entropy', max_depth=6, max_features='auto',
            max_leaf_nodes=None, min_impurity_decrease=0.0,
            min_impurity_split=None, min_samples_leaf=1,
            min_samples_split=2, min_weight_fraction_leaf=0.0,
            n_estimators=200, n_jobs=None, oob_score=False, random_state=0,
            verbose=0, warm_start=False),
   min_features_to_select=1, n_jobs=None, scoring='roc_auc', step=1,
   verbose=0)

A: You just need to pass the Recursive Feature Elimination Estimator directly into the GridSearchCV object. Something like this should work
X = df[my_features] #all my features
y = df['gold_standard'] #labels

clf = RandomForestClassifier(random_state = 42, class_weight="balanced")
rfecv = RFECV(estimator=clf, step=1, cv=StratifiedKFold(10), scoring='auc_roc')

param_grid = {
    'n_estimators': [200, 500],
    'max_features': ['auto', 'sqrt', 'log2'],
    'max_depth' : [4,5,6,7,8],
    'criterion' :['gini', 'entropy']
}
k_fold = StratifiedKFold(n_splits=10, shuffle=True, random_state=0)

#------------- Just pass your RFECV object as estimator here directly --------#

CV_rfc = GridSearchCV(estimator=rfecv, param_grid=param_grid, cv= k_fold, scoring = 'roc_auc')

CV_rfc.fit(x_train, y_train)
print(CV_rfc.best_params_)
print(CV_rfc.best_score_)
print(CV_rfc.best_estimator_)

A: Basically you want to fine tune the hyper parameter of your classifier (with Cross validation) after feature selection using recursive feature elimination (with Cross validation).
Pipeline object is exactly meant for this purpose of assembling the data transformation and applying estimator.
May be you could use a different model (GradientBoostingClassifier, etc. ) for your final classification. It would be possible with the following approach:
from sklearn.datasets import load_breast_cancer
from sklearn.feature_selection import RFECV
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    test_size=0.33,
                                                    random_state=42)

from sklearn.pipeline import Pipeline

#this is the classifier used for feature selection
clf_featr_sele = RandomForestClassifier(n_estimators=30,
                                        random_state=42,
                                        class_weight="balanced")
rfecv = RFECV(estimator=clf_featr_sele,
              step=1,
              cv=5,
              scoring = 'roc_auc')

#you can have different classifier for your final classifier
clf = RandomForestClassifier(n_estimators=10,
                             random_state=42,
                             class_weight="balanced")
CV_rfc = GridSearchCV(clf,
                      param_grid={'max_depth':[2,3]},
                      cv= 5, scoring = 'roc_auc')

pipeline  = Pipeline([('feature_sele',rfecv),
                      ('clf_cv',CV_rfc)])

pipeline.fit(X_train, y_train)
pipeline.predict(X_test)

Now, you can apply this pipeline (Including feature selection) for test data.


text:
Q: Javascript regex get only page number from URL i have URL like
https://example.com/my-list/page/35/?a=45&b=56
I want to get page number using regex that is after /page/ in url,
the result i want is 35

A: There's 2 easy ways you could do it using RegEx:
The first way:
var s = "https://example.com/my-list/page/35/?a=45&b=56";
//  First way uses capture groups based on what comes before the page number: "/page/"
s.match(/\/page\/(\d*)/)[1]; // "35"

The second way:
//  The second involves using capture grouping based on the search param that appears to follow.
//  However, this way might not be ideal as you may extend the URI and make a major change that would then require an edit to this. Of course, that could happen with the previous as well.

s.match(/(\d*)(?=\/\?)/)[0]  //  "35"

You can also split the string, and then use regex to grab just the beginning of the string:
s.split("/page/")[1].match(/^\d*/);  //  "35"

You could also simply split the whole string based on the most common element: "/". If your URI pattern is always the same, then this is probably one of the most simply and easy to read solutions. However, if the URI pattern changes to have more fields, then you may have to adjust the index number.
s.split("/")[5]  //  "35"

You could also use substr based on the index of "page". The problem with this is the page number might be 1 digit, 2 digits, or more:
s.substr(s.indexOf("page/")+5, 2)  //  "35"
//  +5 due to length of phrase i use

You could use the substr and index grab the string you want, having the page number at the very start of the string. Then use regex to pull the number and have it rest at 0 index. This might be more practical in case, for whatever reason, there is no page number. For instance, the user ends up at the "page" index base.
s.substr(s.indexOf("page/")+5).match(/^\d*/)[0]  //  35

A: WordPress can also use another url format where page number is stored in url query paged parameter so the safest solution would be to cover both url formats. Another problem is that on first page of any archive you will not find page number in the url so we need to cover that case also.
Here is the simple function that will work for every case:
function getPageFromUrl( url ) {
    const match = url.match(/(?:\/page\/|[?&]paged=)([1-9]\d*)/)
    if ( match ) {
        return Number(match[1]);
    }
    return 1;
}


text:
Q: Linux sort command efficiency/algorithm I was looking into the efficiently sorting values in a very large file. At first it seemed that splitting the file, sorting individually, and then running sort with merge against them all would be more efficient than running sort on one large file.
sort across multiple files in linux
Then reading this article:
http://vkundeti.blogspot.com/2008/03/tech-algorithmic-details-of-unix-sort.html
It seems that sort command is already using a merge sort algorithm under the hood at a different abstracted level. Is it really more efficient to split then? Haven't ran any extensive tests yet, just wondering if someone knows off hand.
Is sort command multi-threaded? Are there memory bounds when running sort on single large file as opposed to sort on multiple file as separate processes? I know that sort uses memory for the sort in general, but temporary files on disk if the memory usage is above a certain threshold.


text:
Q: f# Seq of tuple item1 I don't understand why I'm getting the error below:
> let x = "ABCDAACCECFG"|>Seq.sort|>Seq.groupBy (fun x->x);;
val x : seq<char * seq<char>>

> x;;
val it : seq<char * seq<char>> =
  seq
    [('A', seq ['A'; 'A'; 'A']); ('B', seq ['B']);
     ('C', seq ['C'; 'C'; 'C'; 'C']); ('D', seq ['D']); ...]

> (x|> Seq.head).GetType();;
val it : System.Type =
  System.Tuple`2[System.Char,System.Collections.Generic.IEnumerable`1[System.Char]]
    {Assembly = mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;
     AssemblyQualifiedName = "System.Tuple`2[[System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Collections.Generic.IEnumerable`1[[System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
...
     DeclaredProperties = [|Char Item1;
                            System.Collections.Generic.IEnumerable`1[System.Char] Item2;
                            Int32 System.ITuple.Size|];
...;}

> x|> Seq.map (fun x -> x.Item1, x.Item2)|>dict;;

  x|> Seq.map (fun x -> x.Item1, x.Item2)|>dict;;
  ------------------------^^^^^

stdin(123,25): error FS0039: The field, constructor or member 'Item1' is not defined.

It appears to me that x is a sequence of tuples where each tuple has an Item1 (Char) and Item2 (seq Char) property.  I'd like to turn this into a dictionary.
Clearly, I'm missing something.  Can anyone help me understand what I'm doing wrong and how to get it right?

A: It doesn't appear that F# surfaces the Item1 and Item2 properties from the underlying tuple like in C#. I tried the following which appear to work without error.
Using functions fst and snd:
x|> Seq.map (fun x -> fst x, snd x) |> dict

Using pattern matching:
x|> Seq.map (function (key, value) -> (key, value)) |> dict

And apparently without using Seq.map works as well:
x |> dict


text:
Q: Detecting and Updating a small number of changes in a table I have a table of employees of a company.
Everyday, I am getting a spreadsheet of the latest list of employees of the company.  If any person (based on SSN) in the table is not in the spreadsheet, that employee has left and an EndDate column in the table is updated.  If a person is in the spreadsheet but not in the table, it is a new employee and has to be inserted.  Otherwise, it is an existing employee, and zero or more columns (eg telphone number, supervisor, etc) could have changed and that row in the table has to be udpated.
Given that the company size is just under 1,000 employees, and that each day the changes are about  50 employees, what is the recommended way to do this data refresh?
I understand that there is no one best solution, but would like to see what creative implementations there are out there.  Thanks.

A: You can create SSIS package for this and automate it when ever you get a new spreadsheet.The design could be as simple as the one below

A: SQL Server provides a special merge command for situations like this.
You can use this simple approach:

*

*Write the content of the entire spreadsheet into a temporary table

*Execute a merge of the employee table and the temporary table using SSN match as your merge search condition

*Use WHEN NOT MATCHED BY SOURCE for changing the EndDate

*Use WHEN NOT MATCHED BY TARGET for adding new employees

*Use WHEN MATCHED for all remaining updates.

A: As per your requirement you describe i come up with one idea/solution which i will use..
Step 1: Create Employee.CSV File With req. employee filed wich need to Add/Updated in Database.Ex(Name,Add1,Add2,City,State,ZIp,SSN.....)
Step 2:Create One page in Application wich upload the csv file..I will read CSV file and create generic List(Employee) object.
Step 3 : Call Stored procedure which   insert/Update Data from employee object
1) Impalement Transaction in code.
2) loop throw each employee in object.
3) Rollback if any Error Occurred.
4) Implement Stored procedure in database for your case like..

if (Ltrim(Rtrim(isnull(@ssN,''))==''))
    'Your logic
    return
end if
if (ssn != '')
    'Edit case
    return
end if
'Existing employee
--Sample of SP
CREATE PROCEDURE  sp_Uploademployee
(
    @cCode VARCHAR(200),
    @cName  VARCHAR(500),
    .....ETC
)
AS
SET NOCOUNT ON
DECLARE @ID INT
IF ISNULL(@cName,'') <> '' And ISNULL(@ccode,'')<> ''
BEGIN
    IF NOT EXISTS (SELECT iID FROM employee WHERE cCode=@cCode AND cName=@cName  )
    BEGIN
        INSERT INTO  employee ()
        VALUES ()
    END
    ELSE
    BEGIN

    END
END
ELSE
BEGIN
    RAISERROR('your Error', 16, -1)
    RETURN
END


text:
Q: Simple url Htaccess Redirection + youtube Need help in forwarding below url with .htaccess rules
https://www.example.com/watch?v=yzwRsQ7rR-o
forward to
https://www.example.com/?url=https://www.youtube.com/watch?v=yzwRsQ7rR-o
I've following exisitng rules
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

A: Check this redirect with query string
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_URI} ^watch
RewriteCond %{QUERY_STRING} v=([A-Za-z0-9-]+) [NC]
RewriteRule (.*) /?url=https://www.youtube.com/watch?v=$1 [R=301,L]
</IfModule>


text:
Q: what condition of A makes transpose(A)*A nonsingular? What contidion of A makes $$A^TA$$ nonsingular?
If so, that is $$A^TA$$ is non-singular than a unique solution exists.

A: Let $A$ be a $m \times n$ matrix. The rank of $A^T A$ turns out to be the same as the rank of $A$, and $A^T A$ is a $n \times n$ matrix. So $A^T A$ is nonsingular if and only if the rank of $A$ is $n$, i.e. if $A$ has linearly independent columns.

A: Here is a conceptual approach. Note that
$$\langle Au, Av \rangle = \langle A^T A u, v \rangle$$
where, say, $u, v \in \mathbb{R}^n$ and $Au, Av \in \mathbb{R}^m$. Then $A^T A$ is nonsingular iff the bilinear form on the RHS, and hence the bilinear form on the LHS, is nondegenerate, which is true iff $A$ has full rank, or equivalently is injective as a linear map $\mathbb{R}^n \to \mathbb{R}^m$.


text:
Q: XSLT, transformation between RDF and XML I have this file in .rdf
<rdf:RDF
    xmlns:vitro-public="http://vitro.mannlib.cornell.edu/ns/vitro/public#"
    xmlns:c4o="http://purl.org/spar/c4o/"
    xmlns:ero="http://purl.obolibrary.org/obo/"
    xmlns:pvs="http://vivoweb.org/ontology/provenance-support#"
    xmlns:owl2="http://www.w3.org/2006/12/owl2-xml#"
    xmlns:scirr="http://vivoweb.org/ontology/scientific-research-resource#"
    xmlns:vivo="http://vivoweb.org/ontology/core#"
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:bibo="http://purl.org/ontology/bibo/"
    xmlns:afn="http://jena.hpl.hp.com/ARQ/function#"
    xmlns:foaf="http://xmlns.com/foaf/0.1/"
    xmlns:scires="http://vivoweb.org/ontology/scientific-research#"
    xmlns:dcterms="http://purl.org/dc/terms/"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
    xmlns:geo="http://aims.fao.org/aos/geopolitical.owl#"
    xmlns:skco="http://www.w3.org/2004/02/skos/core#"
    xmlns:event="http://purl.org/NET/c4dm/event.owl#"
    xmlns:dcelem="http://purl.org/dc/elements/1.1/"
    xmlns:vitro="http://vitro.mannlib.cornell.edu/ns/vitro/0.7#"
    xmlns:vann="http://purl.org/vocab/vann/"
    xmlns:skos="http://www.w3.org/2008/05/skos#"
    xmlns:swvs="http://www.w3.org/2003/06/sw-vocab-status/ns#"
    xmlns:owl="http://www.w3.org/2002/07/owl#"
    xmlns:fabio="http://purl.org/spar/fabio/"
    xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#">

  <rdf:Description rdf:about="http://vivo.iu.edu/individual/n5798">
    <rdf:type rdf:resource="http://vivoweb.org/ontology/core#Project"/>
    <rdfs:label rdf:datatype="http://www.w3.org/2001/XMLSchema#string">Kuali Open Library Environment</rdfs:label>
    <vivo:abbreviation>KOLE</vivo:abbreviation>
    <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Thing"/>
    <vivo:webpage rdf:resource="https://www.kuali.org/ole"/>
    <vivo:dateTimeInterval rdf:resource="http://vivo.iu.edu/individual/n5812339"/>
  </rdf:Description>

  <rdf:Description rdf:about="http://vivo.iu.edu/individual/grant42915">
    <rdf:type rdf:resource="http://vivoweb.org/ontology/core#Grant"/>
    <vivo:totalAwardAmount>12452.7</vivo:totalAwardAmount>
    <vivo:hasFundingVehicle rdf:resource="http://vivo.iu.edu/individual/n5798"/>
  </rdf:Description>

  <rdf:Description rdf:about="http://vivo.iu.edu/individual/n5812339">
    <rdf:type rdf:resource="http://vivoweb.org/ontology/core#DateTimeInterval"/>
    <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Thing"/>
    <vivo:start rdf:resource="http://vivo.iu.edu/individual/n2359024"/>
    <vivo:end rdf:resource="http://vivo.iu.edu/individual/n2788825"/>
    <vitro:mostSpecificType rdf:resource="http://vivoweb.org/ontology/core#DateTimeInterval"/>
  </rdf:Description>

<rdf:Description rdf:about="http://vivo.iu.edu/individual/n2359024">
    <rdf:type rdf:resource="http://vivoweb.org/ontology/core#DateTimeValue"/>
    <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Thing"/>
    <vivo:dateTimePrecision rdf:resource="http://vivoweb.org/ontology/core#yearPrecision"/>
    <vivo:dateTime rdf:datatype="http://www.w3.org/2001/XMLSchema#dateTime">2001-01-01T00:00:00</vivo:dateTime>
    <vitro:mostSpecificType rdf:resource="http://vivoweb.org/ontology/core#DateTimeValue"/>
</rdf:Description>

  <rdf:Description rdf:about="http://vivo.iu.edu/individual/n2788825">
    <rdf:type rdf:resource="http://vivoweb.org/ontology/core#DateTimeValue"/>
    <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Thing"/>
    <vivo:dateTimePrecision rdf:resource="http://vivoweb.org/ontology/core#yearPrecision"/>
    <vivo:dateTime rdf:datatype="http://www.w3.org/2001/XMLSchema#dateTime">2002-02-02T00:00:00</vivo:dateTime>
    <vitro:mostSpecificType rdf:resource="http://vivoweb.org/ontology/core#DateTimeValue"/>
  </rdf:Description>
</rdf:RDF>

And I am using that .xsl sheet
 <?xml version="1.0"?>

<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:vivo="http://vivoweb.org/ontology/core#"
xmlns:foaf="http://xmlns.com/foaf/0.1/"
xmlns:owl2="http://www.w3.org/2006/12/owl2-xml#"
xmlns:iuvivo="http://vivo.iu.edu/ontology/iuvivo#"
version="1.0">

<xsl:output
    method="xml"
    indent="yes"
    omit-xml-declaration="no"
    encoding="utf-8"/>

<xsl:template match="rdf:RDF">

<CERIF
 xmlns="urn:xmlns:org:eurocris:cerif-1.5-1"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 release="1.5" date="2012-10-17"
 sourceDatabase="Project Profile">

        <xsl:if test="rdf:Description/rdf:type/@rdf:resource='http://vivoweb.org/ontology/core#Project'">
            <cfProj>
                <cfProjId><xsl:value-of select="rdf:Description/@rdf:about"/></cfProjId>
                <cfAcro><xsl:value-of select="rdf:Description/vivo:abbreviation"/></cfAcro>
                <cfURI><xsl:value-of select="rdf:Description/vivo:webpage //@rdf:resource"/></cfURI>
                <xsl:if test="rdf:Description/vivo:dateTimeInterval/@rdf:resource=rdf:Description/@rdf:about and rdf:Description/vivo:start/@rdf:resource=rdf:Description/@rdf:about">
                    <cfStartDate><xsl:value-of select="rdf:Description/vivo:dateTime"/></cfStartDate>
                </xsl:if>
                <xsl:if test="rdf:Description/vivo:dateTimeInterval/@rdf:resource=rdf:Description/@rdf:about and rdf:Description/vivo:end/@rdf:resource=rdf:Description/@rdf:about">
                    <cfEndDate><xsl:value-of select="rdf:Description/vivo:dateTime"/></cfEndDate>
                </xsl:if>

                    <cfProj_Class>
                        <cfClassId>0bd2d47a-8688-4758-a63c-45e76825a0f6</cfClassId>
                        <cfClassSchemeId>794234b8-25bb-46df-9d26-ae660bca64bc</cfClassSchemeId>
                    </cfProj_Class>

                    <xsl:if test="rdf:Description/vivo:hasFundingVehicle/@rdf:resource=rdf:Description/@rdf:about">
                        <cfProj_Fund>
                            <cfFundId><xsl:value-of select="rdf:Description/@rdf:about"/></cfFundId>
                            <cfAmount><xsl:value-of select="rdf:Description/vivo:totalAwardAmount"/></cfAmount>
                            <cfClassId>eda2b2e6-34c5-11e1-b86c-08000200c9a66</cfClassId>
                            <cfClassSchemeId>759af93b-34c5-11e1-b86c-0800200c9a66</cfClassSchemeId>
                            </cfProj_Fund>
                            <xsl:if test="rdf:Description/vivo:dateTimeInterval/@rdf:resource=rdf:Description/@rdf:about and rdf:Description/vivo:start/@rdf:resource=rdf:Description/@rdf:about">
                                <cfStartDate><xsl:value-of select="rdf:Description/vivo:dateTime"/></cfStartDate>
                            </xsl:if>
                            <xsl:if test="rdf:Description/vivo:dateTimeInterval/@rdf:resource=rdf:Description/@rdf:about and rdf:Description/vivo:end/@rdf:resource=rdf:Description/@rdf:about">
                                <cfEndDate><xsl:value-of select="rdf:Description/vivo:dateTime"/></cfEndDate>
                            </xsl:if>
                    </xsl:if>
            </cfProj>
        </xsl:if>

        <xsl:if test="rdf:Description/rdf:type/@rdf:resource='http://xmlns.com/foaf/0.1/Person'">
            <cfPers>
                <cfPersId><xsl:value-of select="rdf:Description/@rdf:about"/></cfPersId>
                <cfGender><xsl:value-of select="rdf:Description/owl2:gender"/></cfGender>
                <cfURI><xsl:value-of select="rdf:Description/vivo:webpage //@rdf:resource"/></cfURI>
                <cfPersName>
                    <cfFirstNames><xsl:value-of select="concat(rdf:Description/foaf:firstName, ' ', rdf:Description/vivo:middleName)"/></cfFirstNames>\n
                    <cfFamilyNames><xsl:value-of select="rdf:Description/foaf:lastName"/></cfFamilyNames>
                </cfPersName>
                <cfPersKeyw>
                    <cfKeyw><xsl:value-of select="rdf:Description/iuvivo:freetextKeyword"/></cfKeyw>
                </cfPersKeyw>

                    <cfPers_OrgUnit>
                                <cfClassId>eda2b2e6-34c5-11e1-b86c-08000200c9a66</cfClassId>
                                <cfClassSchemeId>759af93b-34c5-11e1-b86c-0800200c9a66</cfClassSchemeId>
                        <xsl:if test="rdf:Description/vivo:dateTimeInterval/@rdf:resource=rdf:Description/@rdf:about and rdf:Description/vivo:start/@rdf:resource=rdf:Description/@rdf:about">
                            <cfStartDate><xsl:value-of select="rdf:Description/vivo:dateTime"/></cfStartDate>
                        </xsl:if>
                        <xsl:if test="rdf:Description/vivo:dateTimeInterval/@rdf:resource=rdf:Description/@rdf:about and rdf:Description/vivo:end/@rdf:resource=rdf:Description/@rdf:about">
                            <cfEndDate><xsl:value-of select="rdf:Description/vivo:dateTime"/></cfEndDate>
                        </xsl:if>
                    </cfPers_OrgUnit>
            </cfPers>
        </xsl:if>

        <xsl:if test="rdf:Description/rdf:type/@rdf:resource='http://xmlns.com/foaf/0.1/Organization'">
            <cfOrgUnit>
                <cfOrgId><xsl:value-of select="rdf:Description/@rdf:about"/></cfOrgId>
                <cfAcro><xsl:value-of select="rdf:Description/vivo:abbreviation"/></cfAcro>
                <cfURI><xsl:value-of select="rdf:Description/vivo:webpage //@rdf:resource"/></cfURI>
                <cfOrgKeyw>
                    <cfKeyw><xsl:value-of select="rdf:Description/iuvivo:freetextKeyword"/></cfKeyw>
                </cfOrgKeyw>

                    <cfPers_OrgUnit>
                                <cfClassId>eda2b2e6-34c5-11e1-b86c-08000200c9a66</cfClassId>
                                <cfClassSchemeId>759af93b-34c5-11e1-b86c-0800200c9a66</cfClassSchemeId>
                        <xsl:if test="rdf:Description/vivo:dateTimeInterval/@rdf:resource=rdf:Description/@rdf:about and rdf:Description/vivo:start/@rdf:resource=rdf:Description/@rdf:about">
                            <cfStartDate><xsl:value-of select="rdf:Description/vivo:dateTime"/></cfStartDate>
                        </xsl:if>
                        <xsl:if test="rdf:Description/vivo:dateTimeInterval/@rdf:resource=rdf:Description/@rdf:about and rdf:Description/vivo:end/@rdf:resource=rdf:Description/@rdf:about">
                            <cfEndDate><xsl:value-of select="rdf:Description/vivo:dateTime"/></cfEndDate>
                        </xsl:if>
                    </cfPers_OrgUnit>

            </cfOrgUnit>
        </xsl:if>

</CERIF>
</xsl:template>
</xsl:stylesheet>

The results I get are this:
<?xml version="1.0" encoding="utf-8"?><CERIF release="1.5" date="2012-10-17" sourceDatabase="Project Profile" xmlns:foaf="http://xmlns.com/foaf/0.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:iuvivo="http://vivo.iu.edu/ontology/iuvivo#" xmlns:owl2="http://www.w3.org/2006/12/owl2-xml#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:vivo="http://vivoweb.org/ontology/core#" xmlns="urn:xmlns:org:eurocris:cerif-1.5-1">
<cfProj>
<cfProjId>http://vivo.iu.edu/individual/n5798</cfProjId>
<cfAcro>KOLE</cfAcro>
<cfURI>https://www.kuali.org/ole</cfURI>
<cfStartDate>2001-01-01T00:00:00</cfStartDate>
<cfEndDate>2001-01-01T00:00:00</cfEndDate>
<cfProj_Class>
<cfClassId>0bd2d47a-8688-4758-a63c-45e76825a0f6</cfClassId>
<cfClassSchemeId>794234b8-25bb-46df-9d26-ae660bca64bc</cfClassSchemeId>
</cfProj_Class>
<cfProj_Fund>
<cfFundId>http://vivo.iu.edu/individual/n5798</cfFundId>
<cfAmount>12452.7</cfAmount>
<cfClassId>eda2b2e6-34c5-11e1-b86c-08000200c9a66</cfClassId>
<cfClassSchemeId>759af93b-34c5-11e1-b86c-0800200c9a66</cfClassSchemeId>
</cfProj_Fund>
<cfStartDate>2001-01-01T00:00:00</cfStartDate>
<cfEndDate>2001-01-01T00:00:00</cfEndDate>
</cfProj>

There are two things that are not well. First is how I can format the output with the "tabs" define in the .xsl sheet. The second is that some results are not well for example the values in:
1)
http://vivo.iu.edu/individual/n5798 has to be     http://vivo.iu.edu/individual/grant42915 which is the value in the second "Description" set
2)
Both values of 2001-01-01T00:00:00 should be 2002-02-02T00:00:00 which is a value from the 5th set of Description
Thanks a lot

A: Although Ian Roberts and Joshua Taylor have a point regarding using a RDF library to process the rdf file, if you are sure the RDF will never change then using XSLT is less work. However, if you are not it is better write your own method to write statements (from the RDF library) to XML.
To answer your questions.

*

*The formatting depends on on your XSLTransformer, I use Java's(javax.xml.transform.Transformer) and then I need to set the ident size like this (it might be different for your transformer):
TransformerFactory factory = TransformerFactory.newInstance();
Source xslt = new StreamSource(new File("test.xslt"));
Transformer transformer = factory.newTransformer(xslt);
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

*Retrieving the wrong results. The way your are doing it now is not the correct way to do XSLT. Your select statements can target any of the rdf:Description tags and select the relevant property. If you want to process the projects then you should write a template that matches this property and then process these attributes. Something like this (I'm not entirely sure about your data, so this could be wrong):
<xsl:template match="rdf:Description">
    <xsl:if test="rdf:type/@rdf:resource='http://vivoweb.org/ontology/core#Project'">
        <cfProj>
            <cfProjId><xsl:value-of select="@rdf:about"/></cfProjId>

This will select the rdf:about value of each rdf:Description that has type Project.


text:
Q: Solved but I'm not sure why: Google Service Account Authentication fails in Ubuntu, works on on Raspberry Pi I have a python script successfully updating google sheets through Raspberry pi using oauth2client and gspread.  When I try and run the same script off my desktop Ubuntu it throws an error 403 Insufficient Permissions. I'm running them both in IDLE2 if that matters.
I am a novice, but I have imported gspread & oauth2client libraries, and some things called pypy, openSSL & pycrypto. I have copied the whole folder from the Raspberry pi and am running it out of that folder so it contains the same json Key document.
I'm probably missing something obvious.  If you can answer, please dumb it down for a relative newbie.  Thanks.
Update 9:20PM March 13:  I downloaded new credentials from google directly to Ubuntu, updated the code and tried again but received the same error.
Here's the error:
`Traceback (most recent call last):
  File "/home/heather/Desktop/Heather/DEV/18-03-11-Category-Log.py", line 15, in <module>
    wks = gc.open("meditation_logger").sheet1
  File "/home/heather/.local/lib/python2.7/site-packages/gspread/v4/client.py", line 103, in open
    self.list_spreadsheet_files()
  File "/home/heather/.local/lib/python2.7/site-packages/gspread/v4/client.py", line 80, in list_spreadsheet_files
    r = self.request('get', url)
  File "/home/heather/.local/lib/python2.7/site-packages/gspread/v4/client.py", line 73, in request
    raise APIError(response)
APIError: {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "insufficientPermissions",
    "message": "Insufficient Permission"
   }
  ],
  "code": 403,
  "message": "Insufficient Permission"
 }
}`

Here's the code (I've used #### to cover my key file name):
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from datetime import datetime
import serial
from time import localtime, strftime
#import time
import serial

#rpi serial port with arduino
ser = serial.Serial('/dev/ttyACM0',115200)
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('################.json', scope)
gc = gspread.authorize(credentials)
#sh = gc.create('meditation_logger1')
wks = gc.open("meditation_logger").sheet1
wks.resize(1)

#wks.update_acell('B2', 'crud')

def ok_to_begin():
    print "ok to begin"

ok_to_begin()

while True:
    wks = gc.open("meditation_logger").sheet1
    data = ser.readline().strip()

(... etc. I think the rest of the code isn't really relevant.. just logging instructions for different serial data)


text:
Q: using separation of variables to solve $u_{tt}=16u_{xx}, u(x,t)$ Question:
Find a nontrivial family of solutions of the following PDEs by the method of separation of variables. You need not find the most general solution obtainable in this way.
4c. $u_{tt}=16u_{xx}, u(x,t)$
My Attempt: I am using separation of variables to find a nontrivial family of solution for this particular PDE.
First, I need my product solutions so I need to let $u=u(x,t)$ be $ u =f(x)g(t)$. Subsituting this condition on my PDE, I get
$f(x)g''(y)=16f''(x)$
So I am going to divide by $f(x)$ to bring my f's on one side
$g''(y) = \frac{16f''(x)}{f(x)}$
I split these two up and end up with the following equations
$g''(y) = \lambda$ and $ \frac{16f''(x)}{f(x)}=\lambda$
while my $g''(y)$ stays the same I will have $16f''(x)=f(x) \lambda$ which becomes $16f''(x)-f(x) \lambda = 0$
So my equations are $g''(y) = \lambda$ and $16f''(x)-f(x) \lambda = 0$. The main question is on how to solve them. I think if I apply the ODE technique of characteristic equations I would have $r^2 = \lambda$ and by taking the square root I will have $r = \lambda$ and $-\lambda$. Now what would happen to $16f''(x)-f(x) \lambda = 0$?
Would it become $16r^2 - \lambda =0$
$16r^2 = \lambda$ ? But wait what is going to happen to my 16?
The answer is $(c_1e^{\lambda x}+c_2e^{-\lambda x})(d_1e^{4 \lambda t}+d_2e^{-4 \lambda t})$. I can see the $ \lambda $ and $- \lambda$ and I know that there is going to be a 4 in play if I take the square root of 16, but I'm not sure if that is right
Edit: Let me try this again.
4c. $u_{tt}=16u_{xx}, u(x,t)$
for $ u(x,t) = f(x)g(t)$ for product solutions, so I have to substitute them into my equation
$g''(t)f(x)=16f''(x)g(t)$
dividing with f(x) I will get
$g''(t)=16 \frac{f''(x)}{f(x)} g(t)$
and dividing with $g(t)$ I will have
$\frac{g''(t)}{g(t)} = 16 \frac{f''(x)}{f(x)}$
so splitting these equations up I should get
$\frac{g''(t)}{g(t)} = \lambda$
$ g''(t) = \lambda g(t)$
$g''(t) - \lambda g(t) = 0$
$r^2 - \lambda = 0$
$r^2 = \lambda$
$ r = + \lambda$ and $ r = - \lambda$
Now for $16 \frac{f''(x)}{f(x)} = \lambda$
$ 16 f''(x) = f(x) \lambda$
$16f''(x) -f(x) \lambda = 0$
$16r^2 - \lambda = 0$
$ 16r^2 = \lambda$
and I am still messed up unless I divide the 16
$ r^2 = \frac{\lambda}{16}$
but then I will have $r = \frac{\sqrt{\lambda}}{4}$ and $ r = -\frac{\sqrt{\lambda}}{4}$


text:
Q: Non deterministic behaviour while using libtensorflow with C API I'm trying to run inference on a TensorFlow model with the libtensorflow library from a program written in C/C++. The C library is not well documented but I figured out how to do thanks to some tutorials I could find on the Web. A minimal program reproducing my problem can be found below. It basically loads the model from disk, checks the dimensions of the input and output tensors and feed some data into.
As I trained and tested the model in Python, I know exactly what is the expected output for a given input. Normally, for the input set up in this minimal program, the output has to be this vector:
0.0061
0.0349
0.0843
0.7584
0.0767
0.0320
0.0073

and this is the result I find back from my C/C++ program, ..., sometimes. But this is not deterministic at all. It works well maybe 1 time out of 5. The other times I just got wrong values like this:
1.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000

I can understand there is something wrong in my program but I have hard time to explain why I get this stochastic behaviour.
I tested this program on different machines, both on Windows 10 and Linux. The library I use is the one that can be downloaded here, version 2.4 CPU only. In case of the code is not enough, I also uploaded my model here.
I would truly appreciate if someone could pinpoint what is wrong in this code.

#include <string>
#include "tensorflow/c/c_api.h"

static void NoOpDeallocator (void* /*data*/, size_t /*a*/, void* /*b*/)
{
}

int InputIndicesToIndex (int x, int y, int z)
{
    int index = x * 7 * 4 + y * 4 + z;
    return index;
}

int main (void)
{
    const char* path = "./Model";
    const char* input_name = "serving_default_input_1";
    const char* output_name = "StatefulPartitionedCall";

    // Load graph
    TF_Graph* graph = TF_NewGraph ();
    TF_Status* status = TF_NewStatus ();
    TF_Buffer* runOptions = nullptr;
    TF_SessionOptions* options = TF_NewSessionOptions ();

    const char* tags = "serve";
    int ntags = 1;

    TF_Session* session = TF_LoadSessionFromSavedModel (options, runOptions, path, &tags, ntags, graph, nullptr, status);
    if (TF_GetCode (status) != TF_OK)
    {
        printf ("\n[ERROR] While loading TensorFlow saved model, got: %s", TF_Message (status));
        return -1;
    }

    // Check graph input and output
    TF_Output input = {TF_GraphOperationByName (graph, input_name), 0};
    if (input.oper == nullptr)
    {
        printf ("\nCould not find operation name in graph, got message: \"%s\"", TF_Message (status));
        return -1;
    }

    TF_Output output = {TF_GraphOperationByName (graph, output_name), 0};
    if (output.oper == nullptr)
    {
        printf ("\nCould not find operation name in graph, got message: \"%s\"", TF_Message (status));
        return -1;
    }

    if (TF_OperationOutputType (input) != TF_FLOAT || TF_OperationOutputType (output) != TF_FLOAT)
    {
        printf ("\nUnexpected data type");
        return -1;
    }

    // Check input shape
    int64_t dims [16];
    int numDims = TF_GraphGetTensorNumDims (graph, input, status);
    TF_GraphGetTensorShape (graph, input, dims, numDims, status);
    if (TF_GetCode (status) != TF_OK) {
        printf ("\nCould not retrieve tensor shape, got message: \"%s\"", TF_Message (status));
        return -1;
    }
    if (numDims != 4 || dims [0] != -1 || dims [1] != 6 || dims [2] != 7 || dims [3] != 4)
    {
        printf ("\nUnexpected input tensor dimensions");
        return -1;
    }

    // Bind data array to graph input
    float inputData [1 * 6 * 7 * 4];
    dims [0] = 1;
    TF_Tensor* inputTensor = TF_NewTensor (TF_FLOAT, dims, numDims, inputData, sizeof (float) * 6 * 7 * 4, &NoOpDeallocator, 0);
    if (inputTensor == nullptr)
    {
        printf ("\nCould not create input tensor");
        return -1;
    }

    // Check output shape
    numDims = TF_GraphGetTensorNumDims (graph, output, status);
    TF_GraphGetTensorShape (graph, output, dims, numDims, status);
    if (TF_GetCode (status) != TF_OK) {
        printf ("Could not retrieve tensor shape, got message: \"%s\"", TF_Message (status));
        return -1;
    }
    if (numDims != 2 || dims [0] != -1 || dims [1] != 7)
    {
        printf ("\nUnexpected output tensor dimensions");
        return -1;
    }

    // Feed input with some data
    for (int y = 0; y < 6; y ++)
    {
        for (int x = 0; x < 7; x ++)
        {
            inputData [InputIndicesToIndex (y, x, 0)] = 0.0f;
            inputData [InputIndicesToIndex (y, x, 1)] = 1.0f;
            inputData [InputIndicesToIndex (y, x, 2)] = 0.0f;
            inputData [InputIndicesToIndex (y, x, 3)] = 0.0f;
        }
    }

    // Run the session to compute the output
    TF_Tensor* outputTensor;
    TF_SessionRun (session, nullptr, &input, &inputTensor, 1, &output, &outputTensor, 1, nullptr, 0, nullptr, status);
    if (TF_GetCode (status) != TF_OK)
    {
        printf ("\n[ERROR] Could not run graph inference, got %s", TF_Message (status));
        return -1;
    }

    // Read out the result
    float* outputData = (float*) TF_TensorData (outputTensor);
    for (int i = 0; i < 7; i ++)
        printf ("\n%f", outputData [i]);

    if ((int) (outputData [3] * 1000.0f) != 758) {
        printf ("\n[ERROR] Unexpected inference result");
        return -1;
    }
    else {
        printf ("\n[OK] Inference ran fine");
        return 0;
    }
}

A: OK, I continued to investigate myself after having posted this question and I could finally figure out what happens. I write my explanation here in the hope it could help someone one day.
The problem comes from an undocumented behaviour of the libtensorflow library (as far as it is possible for an undocumented library). While reading the include files I discovered an additional way to create a tensor, by using TF_AllocateTensor instead of TF_NewTensor. I tried this function and then it worked finally like a charm.
However, it is worth to understand why.
By using TF_NewTensor, you basically ask TensorFlow to create a new tensor wrapping a data buffer that you provide. But the problem is: TensorFlow may decide or not to use your data buffer or to potentially reallocate it elsewhere. One can say in its favour that it warns you by calling the deallocating function that you have to provide. But it can get completely unnoticed as all the tuto I found simply provide an empty deallocating function (see NoOpDeallocator  in the code).
This behaviour is triggered by some memory management mechanism in the internal library machinery, so you must always get ready for that to happen. This means that you cannot do things in this order:

*

*Allocate a buffer

*Call TF_NewTensor

*Fill in your buffer with some data,

because TensorFlow may not use your buffer by the time you fill it in. Therefore you have to fill it before calling TF_NewTensor. Then if you have to modify it, you have to call TF_TensorData to be sure to have the good address in hand.
The second option consists in asking TensorFlow to make the data allocation itself by using TF_AllocateTensor. This is a far better option in my case as the data buffer could be moved anyway.


text:
Q: JavaFX - handle MouseEntered event on a button (with fxml) I'm trying to learn event handling and made an example with an fxml button that looked like that:
<Button fx:id="button" onAction="#Handle">

and the following handler method in my controller:
@FXML
 private void Handle () {

    btn_welcome.setOnMouseClicked((event) -> {

        System.out.println("test");

    });

So far this works fine. Now I would like to handle the event of entering the button with the mouse. I tried
@FXML
 private void Handle () {

    btn_welcome.setOnMouseEntered((event) -> {

        System.out.println("test");

    });

but it doesn't seem to work.

A: You shoud not put another listener onto a control to get it to execute the function. What you are doing is adding another listener every single time you call your handle method.
Use onMouseEntered="#methodToBeCalled" in FXML, and in your code just create that method:
@FXML
public void methodToBeCalled(){
   System.out.println("mouse entered");
}

It's that simple. The method will be called, and all you have to do is specify id/method name, and use annotation.

A: you can also try this
 btn_welcome.addEventHandler(MouseEvent.MOUSE_ENTERED,
        new EventHandler<MouseEvent>() {
          @Override
          public void handle(MouseEvent e) {
           //your code here
          }
        });


text:
Q: Simple proof about prime filters. Exercise. Let $F$ be an true filter in a set $X$. Show that $F$ is an ultrafilter ($\Leftrightarrow$ prime) iff a subset of $X$ intersects every set of $F$ then this same subset is in $F$.
UPDATE.
My attempt. $(\Rightarrow)$ Suppose $F$ is an ultrafilter. Then, we have that $A,B \in F \Rightarrow A \cap B \in F$ and $A \in F, A \subseteq B \Rightarrow B \in F$ by definition of a filter. Let $S \subset X$ s.t. $S \cap A \neq \emptyset$, $\forall A \in F$. This guarantees that there is another filter $F'$ s.t. $F \subseteq F'$ and $S \in F'$, but $F$ is maximal and thus $F=F'$, meaning $S \in F$, proving what's wanted.
$(\Leftarrow)$ Suppose now that the second condition is verified for every subset $S$ of $X$. By the same reasoning as before, we can guarantee that there exists a filter $F'$ s.t. $F \subseteq F'$ and $S \in F'$. If we show that $F=F'$ we have that $F$ is maximal, and that's what we want. Let's assume that $F \neq F'$, i.e., that there is a set $Z$ such that $Z \in F'$ and $Z \notin F$. Then we have: $(X\backslash Z)\cup Z = X \in F$ ($F$ is a filter). But this is equivalent to saying that $X\backslash Z \in F \vee Z \in F$ but $Z \notin F$ and thus $X \backslash Z \in F \Rightarrow X\backslash Z \in F'\Rightarrow Z \notin F'$ which is a contradiction. Thus $F=F'$ e so $F$ is maximal.
Is this formulation right? I have some issues understanding this basic concepts about filters and some of my proofs go wrong because of it. Thanks for all the help in advance.

A: Your left to right direction ($\Rightarrow$) is correct, but it would be good if you justify the existence of $F'$ a bit more. For example, there is an easy explicit description in terms of $F$ and $S$:
$$
F' = \{A \subseteq X : S \cap B \subseteq A \text{ for some } B \in F\}.
$$
We call $F'$ the filter generated by $F \cup \{S\}$.
The right to left direction ($\Leftarrow$) needs work. To show that $F$ is maximal you have to show $F = F'$ for any (proper) filter $F'$ with $F \subseteq F'$. As you have currently written it, $F'$ is of a specific form (namely with $S \in F'$). Even though you do not use this in what follows, the reasoning still breaks down. The problem is in the step where you claim that "$(X \setminus Z) \cup Z \in F$ implies $X \setminus Z \in F$ or $Z \in F$". This is true for prime filters, but that is exactly what you have to prove (being prime is equivalent to being an ultrafilter, as you noted as well).
It might be good to have an example why this step generally breaks down. We consider $X = \mathbb{N}$ and we let $F$ be the filter of cofinite sets. That is, $A \in F$ if and only if $\mathbb{N} \setminus A$ is finite. It should be easy to verify that this is a filter. Now let $E \subseteq \mathbb{N}$ be the set of even numbers, and $O \subseteq \mathbb{N}$ be the set of odd numbers. Clearly $E \cup O = \mathbb{N}$, so $E \cup O \in F$, but at the same time $E \not \in F$ and $O \not \in F$.
So how do we prove the right to left direction? We can take your approach of proving maximality. So let $F'$ be a proper filter with $F \subseteq F'$. Let $S \in F'$, we need to show that $S \in F$ because then we can conclude that $F = F'$ and so $F$ must be maximal because $F'$ was an arbitrary filter containing $F$. By our assumption on $F$ it is enough to show that $A \cap S \neq \emptyset$ for all $A \in F$, because then we get $S \in F$. Can you now finish the proof, using that $F \subseteq F'$ and that $F'$ is a filter?


text:
Q: Convert different certificate revocation list formats in .net I need to convert a bunch of certificate revocation list in .crl extension,they are in DER format (Binary), and I need to convert them into PEM format (Base64 string representation of the binary content of each .crl file).
As per instructions in Convert .der to .pem using OpenSSL-Net, I have created the following code trying to convert a single .crl file from its DER format to PEM format:
    private static void generateCrl()
    {
        byte [] certbyte = File.ReadAllBytes("D:\\certsunzip\\DODIDCA_44.crl");
        Console.WriteLine("First byte: {0}", certbyte[0]);
        X509Certificate2 cert = new X509Certificate2(certbyte);
        string pem = "-----BEGIN X509 CRL-----\r\n" + Convert.ToBase64String(cert.RawData, Base64FormattingOptions.InsertLineBreaks) + "-----END X509 CRL-----";
        using (StreamWriter outputFile = new StreamWriter(@"D:\certsunzip\test.crl"))
        {
            foreach (char chr in pem)
            outputFile.WriteLine(chr);
        }
    }

However, when I run the code, the X509Certificate2 constructor is throwing me an CryptographicException saying "Cannot find the requested object". I would like to know is there another way I can do this conversion, maybe the X509Certificate2 constructor does not like the crl files?

A: Remove 3rd line, because it doesn't make sense (because X509Certificate2 class doesn't support CRLs) and use 'certbyte' variable on a 4th line:
private static void generateCrl()
{
    byte [] certbyte = File.ReadAllBytes("D:\\certsunzip\\DODIDCA_44.crl");
    Console.WriteLine("First byte: {0}", certbyte[0]);
    string pem = "-----BEGIN X509 CRL-----\r\n" + Convert.ToBase64String(certbyte, Base64FormattingOptions.InsertLineBreaks) + "-----END X509 CRL-----";
    using (StreamWriter outputFile = new StreamWriter(@"D:\certsunzip\test.crl"))
    {
        outputFile.Write(pem);
    }
}

This will work.


text:
Q: SQL Server 2000 Table Optimization Ive been working all day on optimizing a SQL Server 2000 db table with ~9million rows. My only db experience has been with tables with a few hundred rows, so I've never really had to deal with optimization.
I am doing selects and updates based on a 21 digit number.
Using an indexed char(21) type, the queries take more then 2 seconds and the SQL Server process takes 1.5gigs of ram and 100% cpu.
With a indexed bigint type my queries take a few milliseconds and the process takes ~100MB of ram.
I just want to understand what is happening here, is this normal, or is there a specific way a char type can be indexed for better performance?
Heres some of my sql:
CREATE TABLE data
(
    tableID int NOT NULL IDENTITY PRIMARY KEY,
    tag char(21) NOT NULL UNIQUE,
    dataColumn1 datetime NULL,
    dataColumn2 char(8) NULL,
    lastModified datetime NOT NULL
)

Parameterized query from c#:
SELECT tag FROM data WHERE tag = @tag;

Thanks for any help.

A: This really isn't unusual, SQL handles numbers much better than characters.  A bigInt field uses 8 bytes, which fits neatly into a memory page.   A char field takes 21 bytes which almost triples the amount of storage to put it in an index..
Another consideration, is either index clustered?   The clustered index will perform much faster than a non-clustered index.   There are a lot of additional factors to consider, beyond the simple, general statement that numbers will perform better and use less space in the index.

A: Character comparisons are somewhat slower - the collation sequence has to be considered - not to mention the physical difference in size between a 21-character string and a bigint (8 bytes). The index seek just can't be as efficient because it has to evaluate each byte in your char(21) values, decide what the character's sort order is, then decide how that compares to the matching character in the value you're looking for.
A clustered index will perform better for almost any query because the data (including the index pages iirc; I'm not a DBA) are in disk-seek order.  Or at least closer to it.

A: My money's on the possibility that you're trying to query on some function of the char column, i.e. something like:
SELECT Column
FROM Table
WHERE UPPER(CharColumn) = 'ABC'

Obviously I'm just guessing, but this is a common source of performance issues with char/varchar/nvarchar columns.  If you're writing queries like this, you have to realize that wrapping the column in a function prevents SQL Server from performing an index seek.
Also take into account the number of rows you're actually returning; 9 million rows isn't necessarily a lot to have in the table, but even 100,000 rows is a huge amount to have in a result set.  Sometimes the bottleneck is just streaming all the results.
If none of this describes your problem, then I suggest updating your post with some information about the schema, the indexes you have, and the query that's running slow.  There are further optimizations you can do, although SQL Server 2000 is getting on in years, so your options are limited.

Based on the schema you posted, assuming you have an index on the tag column, that you are only selecting tag and no other columns that might not be covered, that your WHERE condition is a simple equality on the tag column, and that the number of results returned is reasonably small, I don't think that there are any further optimizations you can do.  You've pretty much reduced this to the simplest possible case.


text:
Q: How to query a database for several table? I have problem with databases. Namely, how to retrieve a query so that the query method looks at several arrays?
For examply, I have a databse table: People, Car, Job, Weather etc.
SQLiteOpenHelper databaseHelper = new DatabaseHelper(this);
databaseHelper.query("People",
   new String[]{"_id", "NAME"},
   "FAVORITE = 1",
    null, null, null, null, null);

So how to put more than one table? How to get "_id" and "NAME" from these data?

A: you can use rawquery to write sql statements(select * from table1,table2 where col1=col2)


text:
Q: Prolog File not being read despite file existing Good day! I wrote a load_rules to be able to read files that I would be utilizing in my Prolog program. However, it seems that Prolog doesn't read my file, despite me having created it in the first place.
My code:
load_rules :-
  write('file name? '),
  read(F),
  load_rules(F).

load_rules(F) :-
 % clear_db,
  see(F),
  lod_ruls,
  write('rules loaded'), nl,
  seen, !.

lod_ruls :-repeat,
           read_word_list(L), size(L,X),write(X),nl,
           formal_english(L,[]), write('rule:    '), printlist(L), nl,
           translate(L,X),
           L=[end].

Query:
?- load_rules.
file name? joggers_facts_and_rules.

ERROR: source_sink `joggers_facts_and_rules' does not exist (No such file or directory)
ERROR: In:
ERROR:   [10] see(joggers_facts_and_rules)
ERROR:    [9] load_rules(joggers_facts_and_rules) at c:/users/user/desktop/formal_english.pl:88
ERROR:    [7] <user>
ERROR:
ERROR: Note: some frames are missing due to last-call optimization.
ERROR: Re-run your program in debug mode (:- debug.) to get more detail.
?- :- debug.
ERROR: Undefined procedure: (:-)/1
ERROR:   Directives must be loaded from a file
ERROR:   See FAQ at http://www.swi-prolog.org/FAQ/ToplevelMode.txt
ERROR: In:
ERROR:    [9] throw(error(existence_error(procedure,...),_7042))
ERROR:    [8] '$dwim':dwim_existence_error(error,user:(:-)/1) at c:/program files/swipl/boot/dwim.pl:113
ERROR:    [6] '$dwim':correct_goal((:-debug),user,[],_7128) at c:/program files/swipl/boot/dwim.pl:85

I even tried creating a .txt as well as a .pl file just to be sure to no avail :/
I'd appreciate any help on this, many thanks!


text:
Q: Why is parallelism not violated here? The labour union is negotiating a contract with the hospital that will satisfy the demand of the workers and be accepted to all levels of management.
I was asked to find out a mistake in the sentence above. I thought it to be the phrase "be accepted", considering it sounds a little awkward and also not parallel to the tense of the verb "will satisfy" used previously in the sentence.
I was told the sentence has no error. Why is my explanation wrong in this case?

A: You are focusing on the wrong issue. The error is the use of the word "to". As Graffito commented, the contract might be accepted by all levels of management, or accepted at all levels. It might be acceptable to all levels, or acceptable at all levels. It cannot be accepted to all levels.

A: The requirement of "parallelism" is that the conjunction "and" should connect phrases of the same grammatical category, and the constituent formed will be of this same category.  Auxiliary verbs are followed by verb phrases (VP), so in the example, "will" must be followed by a VP.  A VP may consist of two VPs connected by "and", so this gets us a structure "... that will [VP VP and VP ]".  The first of the conjoined VPs is "satisfy the demand of the workers", and the second VP is "be acceptable to all levels of management".  That gets us to the following grammatical structure.

The labour union is negotiating a contract with the hospital that will [VP [VP satisfy the demand of the workers] and [VP be acceptable to all levels of management]].


text:
Q: Disable Mail.app message signing Mail.app insists in digitally signing my outgoing messages, and I would like to disable this for my gmail account but have not managed to find out how.
Any ideas?

A: When you say "digitally signing", you mean that in the crypto sense, not just appending a typical "name and address" email signature to every email, right?
As an extreme measure, you could remove the public-key-certificate/private-key pair from your keychain. You could export the pair first so that you could easily re-import it if you ever wanted to sign a message or decrypt an encrypted message.


text:
Q: How to display image in iphone simulator using objective C I am trying to display image in iphone simulator programmatically using objective c, I am using following code, but it is not displaying anything in simulator
imageview = [[UIImageView alloc] init];
UIImage *myimg = [UIImage imageNamed:@"A1.jpg"];
imageview.image=myimg;

A: Maybe you forgot this:
imageView.frame = self.view.bounds;
[self.view addSubview:imageview];

A: You can use this code
imageview = [[UIImageView alloc] init];
UIImage *myimg = [UIImage imageNamed:@"A1.jpg"];
imageview.image=myimg;
imageview.frame = CGRectMake(50, 50, 150, 150); // pass your frame here
[self.view addSubview:imageview];

A: If you are programmatically creating the imageView then you must  add it to the view heirarchy using below line
[self.view addSubview:imageview];

A: Add your image view into view like this
imageview = [[UIImageView alloc] initWithframe:CGRectMake(0, 0, 100, 200)];
UIImage *myimg = [UIImage imageNamed:@"A1.jpg"];
imageview.image=myimg;
[self.view addSubview:imageview];

A: First you need to initialize your UIImageView and assign UIImage to it's image property. You already did it in your code. Then you can set the frame to image view.
imageview.frame = CGRectMake(50, 50, 150, 150);

But in most cases it will be more useful to pass sizeToFit message to your image view.
[imageview sizeToFit];

So it will change it's frame to fit image's size. But using this approach you need to assign the origin to your image view's frame later. So the best solution is assign the frame in initialization and then pass sizeToFit.
UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(10.0, 20.0, 0.0, 0.0)];
UIImage *myimg = [UIImage imageNamed:@"A1.jpg"];
imageview.image=myimg;
[imageview sizeToFit];

And don't forget to add image view to view hierarchy.
[self.view addSubview:imageview];

Also you need to check if your image is correctly added to your project. You can check it by finding you image file in Project Navigator and checking it's Target Membership in File Inspector. There should be a tick beside you target's name.


text:
Q: Force and Restrain on same Regex I'm trying to set a password input that will force at least one of each lowercase, uppercase, and numbers, but at the same time refuse any other input like special characters. so far im able to force one of each but haven't been able to deny special characters..
Thank You
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{5,25}"

A: You need to replace the consuming . with [a-zA-Z0-9] character class, or whatever chars/ranges you allow in your regex:
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{5,25}"
                                       ^^^^^^^^^^^

The reason is that . matches any character (other than line break chars).
Note: the length limit works here because HTML5 pattern regex is anchored by default.


text:
Q: Node JS in memory VS external session This is all the information that I have about session stores
"When you use memory-based storage, all session information is stored in memory and is lost when you stop and restart. Better to use a external persistence storage."
But, isn't it the normal phenomenon that session should be lost when we stop or restart. Otherwise there can be security issues.
For example, in Amazon, if I add some products into my cart and I quit or logout. Next time when I login, I find the same items in my cart. This has got nothing with persistent sessions.
Can anyone site me an example with it's practical use.


text:
Q: How do I specify the default font sizer in CK Editor v3 How do I specify the default font size for CKEditor.  I tried changing contents.css (body -> font-size) and I tried changing config.js (config.fontSize_defaultLabel) without any success.  Does anyone know where i should be looking?

A: You seem to be on the right track with the contents.css file.
Is your problem that the font size while working in the editor is not correct or is it that the font size isn't being carried over to the page where you actually display the content?
As you know, ckeditor/contents.css is the default style sheet that is loaded while working in the editor, but if you use "config.contentsCss" to call another style sheet, contents.css won't be loaded.
You can call multiple style sheets like this:
config.contentsCss = ['/contents.css', '/css/anotherstylesheet.css'];

If the font size isn't being carried over to the actual page display, you'll need to set the font size in the style sheet used for the actual pages, the default font size used in the editor isn't inserted into the content output by the editor.
"config.fontSize_defaultLabel" is a label only, it doesn't have any effect on the content. Normally, when you load the editor, the font size selector will display "Size". If you set "fontSize_defaultLabel", the font size selector will display whatever value you entered.
If you can provide more details about the problem, I'll try to post a more accurate answer.
Be Well,
Joe


text:
Q: Can I run a Steam app with a batch script? I have had Steam for a while now and have figured out a lot of tricks and shortcuts for the program. There is still one thing I want to do, but can't figure out: I want to run a Steam app with a batch script to circumvent the Steam GUI. The app in question is GameMaker: Studio. If I try to run the app through the executable directly, I get the follwing error:
GameMaker must be run from within Steam!
I have attempted to use this script, but it does nothing:
Steam.exe "%APPPATH%"
I could just make a desktop shortcut using Steam, but I want to know how to do this with some scripting. Any helpful information is appreciated!

A: As Jeff Mercado mentions above Steam browser protocol is a possible solution. It's also possible to use it from a webpage or other apps that can open a page in your system's default browser, so it can be great with the command line combined with explorer "URL" for example.
One of the problems with this is if you set it to automatically open Steam links by default. The links can do things ranging from installing/launching a game to deleting it, along with a lot more that's not documented either officially in the Steam Command Line Options or unofficially from data extracted from the Linux version of Steam.
Another option is to use the Steam Command Line Options, as linked to above. It allows you to use more of the commands/etc, and you can do so far easier, so it's actually kind-of more powerful than the browser protocol but is not as cross-platform friendly. Of course if you're making a BATch script that doesn't really apply to your situation though ;)


text:
Q: Strange unrecognized control sequence error with beamer I was trying to include bibliography in my presentation, but I get this error:
! Undefined control sequence.
\beamer@sort #1#2->\long \def \beamer@todo
                                           {#1}\def \beamer@ospec {}\beamer@...

I get this error when I run pdflatex second time, the first run completes with no errors and references appear in the bibliography.
My bibliography looks like this:
\begin{frame}
  \frametitle{References}
  \begin{thebibliography}{nevell1984unified}
    \bibitem[Bandaru and Deb, 2010]{deb10}
      Bandaru, S. and Deb, K. (2010).
      \newblock Automating discovery of innovative design principles through
      optimization.
      \newblock Technical Report 2010001, Kanpur Genetic Algorithms Laboratory,
      Indian Institute of Technology, Kanpur.

    \bibitem[Anderson, 1996]{anderson96}
      Anderson, J. (1996).
      \newblock {\em {The architecture of cognition}}.
      \newblock Lawrence Erlbaum.

  \end{thebibliography}
\end{frame}

I have unsuccessfully tried using bibtex to generate the bibliography but I keep getting equally strange errors, like \newblock unrecognized or \item missing from list environment etc, no matter what I do. If I remove the bibliography, everything works fine apart from the unknown citations warnings. Is there a simple working way to include the bibliography in beamer?

A: I located the problem, it was the \usepackage{cite} in my preamble. After commenting it everything is working fine.


text:
Q: JavaScript: self-calling function returns a closure. What is it for? Studying one JavaScript library I found following construction:
theMethod: function () {
    var m1 = new SomeClass();
    return function (theParameter) {
        this.someMethod();
        m1.methodCall(this.someField1);
        this.someField2 = 'some value';
    }
}()

theMethod is called as follows:
c.theMethod(paramValue);

What did the author want to say with this declaration?
Why not to use such declaration:
theMethod: function (theParameter) {
    var m1 = new SomeClass();
    this.someMethod();
    m1.methodCall(this.someField1);
    this.someField2 = 'some value';
}

A: Declaring the variable outside the function makes the function use the same object every time.
An example (with an integer instead of an object, for simplicity's sake):
var c = {
    theMethod: function () {
        var m1 = 0;
        return function (theParameter) {
            m1++;
            console.log( m1 );
        }
    }()
};

c.theMethod(); c.theMethod();  // output: 1 2

var d = {
    theMethod: function () {
        return function (theParameter) {
            var m1 = 0;
            m1++;
            console.log( m1 );
        }
    }()
};

d.theMethod(); d.theMethod();  // output: 1 1

The self-invoking function works like this:
var c = {
    theMethod: function () {
        var m1 = 0;
        return function (theParameter) {
            m1++;
            console.log( m1 );
        }
    }()
};

When the object c is created, the self-invoking function invokes itself and theMethod now equals the return value of that function. In this case the return value is another function.
c.theMethod = function( theParameter ) {
    m1++;
    console.log( m1 );
};

The variable m1 is available to the function because it was in scope when the function was defined.
From now on when you call c.theMethod() you are always executing the inner function that was returned from the self-invoking function, which itself executed only once at the time the object was declared.
The self-invoking function works just like any function. Consider:
var c = {
    theMethod: parseInt( someVariable, 10 )
};

You don't expect parseInt() to execute every time you use the c.theMethod variable. Replace parseInt with an anonymous function as in the original and it's exactly the same thing.

A: It's for encapsulation. m1 is hidden to other methods and from external access by places that might use theMethod. Javascript programmers usually don't care about encapsulation (but they should on non-trivial scripts) because you need to use closures which complicates design of classes and when implemented poorly can reduce performance. That is why you don't see this kind of structure often outside of libraries.
Also your second piece of code is not equivalent. Something equivalent would be:
theMethod: function (theParameter) {
    if (typeof this.prototype.__private__ === "undefined") {
        this.prototype.__private__= {}
    }
    if (typeof this.__private__.m1 === "undefined") {
        this.prototype.__private__.m1= new SomeClass();
    }
    this.someMethod();
    this.__private__.m1.methodCall(this.someField1);
    this.someField2 = 'some value';
}

But then m1 is not really private here.
Also note that in that piece of code m1 is only visible to the function returned, if theMethod was a member of a class the other methods of that class would not be able to see m1 (making it different than the "private" keyword on Java). Also depending on how you declared theMethod m1 would be the java equivalent to "static" (m1 is a function on the prototype of an object it's static, if it's not on a prototype it's not static).

A: @Juhana is right. Here's a handy tutorial on how closures work. http://www.javascriptkit.com/javatutors/closures.shtml

A:
What did the author want to say with this declaration?

That the m1 value should be reused for every call. In your closure-less alternative, it would instantiate a new SomeClass object with every call. It either is used simply for performance improvement, or (and) to maintain a common state in the m1 object.


text:
Q: what will happen if the motor that is designed for delta connected in star connection I have a motor which is designed for 3 phase, 380V. The power rating of motor is 132kw and motor stator winding is connected in delta connection. If I connect the same motor stator winding in star connection with same 380 V line voltage, what will be the impact on motor line current and power rating of the motor.

A: When you connect it in a star configuration, the voltage across each of the stator windings will be reduced by \$\sqrt3\$ and correspondingly, the peak mechanical power that could be delivered to a load for a given slip and supply frequency will be lowered significantly.
So, for a comparable slip, the current and voltage will both be reduced by about \$\sqrt3\$ and hence the power delivered to a load is reduced by about 3.


text:
Q: Why Nightwatch run every .js file as Child process? (Perhaps i have changed some config) Lately when i run Nightwtch.js , my console run as child process every file .js of every folder or subfolder as Child process. Multiple chrome instances are open with them too. Even module folder with require js libraries.. I think i m forgetting some config.
I only want to run the main Nightwatch js file with one chrome..
My console prints starting..
nightwatch bot.js -c config_chrome.json
Started child process for: tests/extra/assertions/customAssertion
Started child process for: tests/extra/commands/customCommand

tests/extra/assertions/customAssertion finished.
tests/extra/commands/customCommand finished.

Started child process for: tests/extra/commands/customCommandConstructor
Started child process for: tests/extra/commands/other/otherCommand

tests/extra/commands/customCommandConstructor finished.

Started child process for: tests/extra/globals

tests/extra/globals finished.

Started child process for: tests/extra/otherPageobjects/otherPage

tests/extra/otherPageobjects/otherPage finished.

Started child process for: tests/extra/pageobjects/SimplePageFn

tests/extra/pageobjects/SimplePageFn finished.

Started child process for: tests/extra/pageobjects/invalidPageObj

tests/extra/commands/other/otherCommand finished.

Started child process for: tests/extra/pageobjects/simplePageObj

tests/extra/pageobjects/invalidPageObj finished.

A: I forget sending --test to console... :)

A: There's a configuration setting that can cause this behavior as well.
If you've set "test_workers": true in nightwatch.conf.js all of your tests are run in parallel, and this fires up child processes for every file in your the directory where nightwatch runs its tests.
Documentation here:
https://github.com/nightwatchjs/nightwatch-docs/blob/master/guide/running-tests/run-parallel.md


text:
Q: SSMS exporting stored procedure results into a .csv file and scheduling it at the 12th working day of each month i am new to stackoverflow.
I have a task. It requires to scheduling the result of the below stored procedures. at each 12th working day of a month.
Any idea of how to let it work?
DECLARE @DATA_RIF AS nvarchar(8) = N'',
        @NOMEJOB AS nvarchar(8) = N'';
--as
SET NOCOUNT ON;

IF EXISTS (SELECT *
           FROM TMP_BANCHECDSCVADVANOPD
           WHERE CONVERT(datetime, DATA_RIF, 103) <> @DATA_RIF)
OR EXISTS (SELECT *
           FROM TMP_CDS_CVA_DVA_CSA_SI
           WHERE CONVERT(datetime, COMPUTE_DATE, 103) <> @DATA_RIF)
    RAISERROR('Presenza date diverse da quella richiesta', 15, 1);

SELECT 'DATA_RIF' AS DATA_RIF,
       'OWNER' AS OWNER,
       'NDG_CONTROPARTE' AS NDG_CONTROPARTE,
       'DESCRIZIONE' AS DESCRIZIONE,
       'ACC_GROUP' AS ACC_GROUP,
       'ACC_AREA' AS ACC_AREA,
       'IDENT' AS IDENT,
       'FULL_FAIR_VALUE' AS FULL_FAIR_VALUE,
       'VALUTAZIONE' AS VALUTAZIONE,
       'MATURITY' AS MATURITY,
       'BUCKET' AS BUCKET,
       'VITA_RESIDUA' AS VITA_RESIDUA,
       'CDS' AS CDS,
       'CDS_A' AS CDS_A,
       'CDS_B' AS CDS_B,
       'CVA_Cont_Unilaterale' AS CVA_Cont_Unilaterale,
       'CVA' AS CVA,
       'CVA_A' AS CVA_A,
       'CVA_B' AS CVA_B
UNION ALL
SELECT DISTINCT
       CONVERT(varchar, DATA_RIF, 103) AS DATA_RIF,
       OWNER,
       CAST(CONVERT(bigint, NDG_CONTROPARTE) AS varchar) AS NDG_CONTROPARTE,
       DESCRIZIONE,
       ACC_GROUP,
       ACC_AREA,
       IDENT,
       REPLACE(CAST(CAST(FULL_FAIR_VALUE AS decimal(18, 8)) AS varchar), '.', ','),
       REPLACE(CAST(CAST(VALUTAZIONE AS decimal(18, 8)) AS varchar), '.', ','),
       CONVERT(varchar(10), DATA_FINE, 103) AS MATURITY,
       CAST(TC AS varchar) AS BUCKET,
       REPLACE(CAST(CAST(MATURITY AS numeric(18, 8)) AS varchar), '.', ',') AS VITA_RESIDUA,
       REPLACE(CAST(CAST(ROUND(CDS, 3) AS decimal(18, 8)) AS varchar), '.', ','),
       REPLACE(CAST(CAST(ROUND(CDS_A, 3) AS decimal(18, 8)) AS varchar), '.', ','),
       REPLACE(CAST(CAST(ROUND(CDS_B, 3) AS decimal(18, 8)) AS varchar), '.', ','),
       REPLACE(CAST(CAST(CVA_CONT_UNILATERAL AS decimal(18, 8)) AS varchar), '.', ','),
       REPLACE(CAST(CAST(CVA_UNILATERAL AS decimal(18, 8)) AS varchar), '.', ','),
       REPLACE(CAST(CAST(CVA_UNILATERAL_A AS decimal(18, 8)) AS varchar), '.', ','),
       REPLACE(CAST(CAST(CVA_UNILATERAL_B AS decimal(18, 8)) AS varchar), '.', ',')
FROM dbo.TMP_BANCHECDSCVADVANOPD
WHERE OWNER IN ('BANCO', 'BANCA ALETTI', 'BANCA AKROS', 'BPM SPA')
  AND CONVERT(datetime, DATA_RIF, 103) = @DATA_RIF
UNION ALL
SELECT DISTINCT
       CONVERT(varchar, COMPUTE_DATE, 103) AS DATA_RIF,
       BANCA,
       CAST(CONVERT(bigint, NDG) AS varchar) AS NDG,
       CONTROPARTE,
       ACC_GROUP,
       ACC_AREA,
       IDENT_PV,
       REPLACE(CAST(CAST(FULL_FAIR_VALUE AS decimal(18, 8)) AS varchar), '.', ','),
       REPLACE(CAST(CAST(VALUTAZIONE AS decimal(18, 8)) AS varchar), '.', ','),
       CONVERT(varchar(10), MATURITY, 103) AS MATURITY,
       CAST(TC AS varchar) AS BUCKET,
       REPLACE(CAST(CAST((ISNULL(DATEDIFF(DD, @DATA_RIF, MATURITY) / CAST(365 AS float), 0)) AS numeric(18, 8)) AS varchar), '.', ',') AS VITA_RESIDUA,
       REPLACE(CAST(CAST(CDS AS decimal(18, 8)) AS varchar), '.', ','),
       REPLACE(CAST(CAST(CDS_A AS decimal(18, 8)) AS varchar), '.', ','),
       REPLACE(CAST(CAST(CDS_B AS decimal(18, 8)) AS varchar), '.', ','),
       REPLACE(CAST(CAST(CVA_CONT_UNILATERAL AS decimal(18, 8)) AS varchar), '.', ','),
       REPLACE(CAST(CAST(CVA_UNILATERAL AS decimal(18, 8)) AS varchar), '.', ','),
       REPLACE(CAST(CAST(CVA_UNILATERAL_A AS decimal(18, 8)) AS varchar), '.', ','),
       REPLACE(CAST(CAST(CVA_UNILATERAL_B AS decimal(18, 8)) AS varchar), '.', ',')
FROM dbo.TMP_CDS_CVA_DVA_CSA_SI
WHERE BANCA IN ('BANCO', 'BANCA', 'BANCHE', 'BANCHI')
  AND CONVERT(datetime, COMPUTE_DATE, 103) = @DATA_RIF;```


text:
Q: IndexedDB: limit selected fields of retrieving object While getting object(s) from indexeddb is it possible to limit a set of fields being retrieved (not to fetch a whole data piece)? I believe an actual task when you have large objects in store, but need only small part of data for a particular operation.

A: No, according to the IndexedDB spec you'll always get the full object, see: 3.4.2 Object Store Retrieval Operation.

A: as a workaround it's possible to define a key on those fields and then do getAllKeys


text:
Q: Using mysql_fetch_assoc in a while loop with extra condition Why is $row empty when I apply the while loop with mysql_fetch_assoc with an extra condition, but when the extra condition is not there, returns something, is this logical?
while ($row = mysql_fetch_assoc($result)
        && $gen->getMailsSent() < 499) {
     //blah blah
}

In the above code, the compiler enteres the loop, but $row is empty
while ($row = mysql_fetch_assoc($result)) {
     //blah blah
}

In this one, the compiler still enteres the loop, but then $row returns something, this to me i dont get and is not logical, can someone please explain why this occurs?

A: while (($row = mysql_fetch_assoc($result))
        && $gen->getMailsSent() < 499) {
     //blah blah
}

Try this. Your problem is precedence - you actually tell it to
$row = (mysql_fetch_assoc($result) && $gen->getMailsSent() < 499)

See http://php.net/manual/en/language.operators.precedence.php
"&&" comes before "=" in the list, so it gets evaluated first.

A: try
while (($row = mysql_fetch_assoc($result))
        && $gen->getMailsSent() < 499) {
     //blah blah
}

actually it shouldn't be empty, it should be a boolean.

A: Use while loop like this:

while (($row = mysql_fetch_assoc($result))  && ($gen->getMailsSent() < 499)) {
    code goes here..
}

hope this will help..


text:
Q: Привет, помогите написать (исправить мой) код, не понимаю ошибки Напишите функцию, которая вычисляет по заданному в десятичной системе счисления числу N количество единиц в двоичной записи этого числа (0 <= N <= 10^6)
def numberOfOnes(N):
a = 0
while N > 0:
    if N % 2 == 1:
        a += 1
    else:
        break
return a

N = int(input())
k = numberOfOnes(N)
print(k)

A: def numberOfOnes(N):
  a = 0
  while N > 0:
    a += N % 2
    N //= 2
  return a

PS. Для отрицательных всегда возвращает ноль, есссно.

A: Так, для разнообразия, хотя это читерство, конечно )
def numberOfOnes(N):
    return bin(N).count('1')

A: Вот самый короткий вариант:
N = int(input())
f"{N:b}".count('1')

Если версия питона ещё не поддерживает f"",то так:
"{:b}".format(N).count('1')

A: Альтернатива второму ответу
def numberOfOnes(N):
    result = 0
    massiv = list(bin(N))
    massiv = massiv[2:]
    for i in massiv:
        if i == "1":
            result += 1
    return result

N = int(input())
k = numberOfOnes(N)
print(k)


text:
Q: PhpStorm Deployment - Map branch to remote folder Let's say I have a project with multiple git branches.
Of course I have setup a deployment in PhpStorm with default mapping of local to remote folder, and this was OK till I was in development stage.
Now that site is live, I wanted to setup something more appropriate. Basically, I wanted to have two mappings.
One mapping would map my local folder /var/www/html/project/ to my remote folder /production/public_html/ when I'm on a master branch, and second mapping would map same local folder to /staging/public_html when I'm on develop branch.
I wonder if this is possible in PhpStorm. I've been looking around but haven't find anything specific.


text:
Q: JSON object: Get all objects to capitalize their first letters I have a JSON object that looks something like this (result from an AJAX call):
    json{
      code: 0,
      resultVal: Object {
      data:
               [
                 Object{
                        generatedName: name1,
                        generatedValue: value1
                 },
                 Object{
                        generatedName1: name2,
                        generatedValue1: value2
                 }....
                ],
        anotherItem: true,
        ...
       }
     }

To clarify resultVal is an object and data is an array of objects, and each object in that array will have two values who's names I will not know in advance.
I am having a problem because I need generatedName and generatedValue to be GenerateName and GeneratedValue. These names and values are usually not the as each other. I know can access each Object through json.resultVal.data[#], but that's as far as I have gotten. json.resultVal.data[0].name returns undefined.
Once I can get those values isolated I can make the fixes I need.
NOTE I am running these calls through Chrome's debugger. The thinking is once I am able to isolate the value I can write the code to fix it using that call. It takes some time to get to this point in the application.
Any suggestions?

A: If I understood it right, you need to iterate over all keys for all objects in "json.resultVal.data". Try using a for/in loop to iterate over the "data" object, as in:
for( var i in json.resultVal.data ) {
    for( var k in json.resultVal.data[i] ) {
        /* here "k" will be key string ("generatedName", "generatedValue", ...) */
    }
}


text:
Q: Why $2\sqrt{x} + \sqrt{3}$ can't be simplified any further? In How do you simplify the addition of square root, it has been pointed out that it cannot be simplified any further.
As obvious as it seems, the following questions seemed need to be addressed:

*

*What is meant by a simpler form? As matter of fact, what determines what is simpler with respect to something else?

*Suppose we bypass 1, and we all agree that we can decide a simpler form between given any two forms. How do we justify that something is in its simplest form (i.e. it has reached the simplest form and no further simplification can be performed.)?

A: Well, there are at least some cases where one can tell no further simplification is necessary. E.g., the simplest form for a quotient of two integers is that in which the numerator and denominator have no common factor greater than 1. Euclid's algorithm will get you there, and tell you when you have arrived.

A: One approach to simplification is asking whether $2\sqrt{x} + \sqrt{3}$ lives in a simpler field than $\mathbb Q(\sqrt{x},\sqrt{3})$, which has degree 4 over $\mathbb Q(x)$. Any simpler field than that must be a quadratic extension of $\mathbb Q(x)$. So to prove that $2\sqrt{x} + \sqrt{3}$ cannot be simplified any further in this context, one just has to prove that it is not quadratic over $\mathbb Q(x)$. This shouldn't be too hard to do.

A: The simplest way any polynomial expression can be written is
$$\sum_i{a_i \cdot x^i} .$$
Example: there is no simpler way to write $3x^4+2x^2-7x+2$ where $a_4=3, a_2=2, a_1=-7, a_0=2$.
Your expression can also be written as $2 \cdot x^{1/2} + 3 \cdot x^0$ where $a_{1/2}=2,a_0=3$. This expression can't be simplified, even if your $i$ isn't an integer.


text:
Q: Есть данные нужно решить задачу Требуется запустить файл java. Я так понял, первый шаг это конвертация в .class файл.
Итак, исходные данные :
Файл .java
package Main;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello word");
    }
}

Адрес jdk
C:\Program Files\Java\jdk1.8.0_121

Адрес который выводится на cmd
C:\Users\вит\IdeaProjects\untitled11\src

Ошибка

"javac" не является внутренней или внешней командой, исполняемой
  программой или пакетным файлом.

A: У меня компилятор ругается на ваш код, в частности на ваши кавычки. Ниже норм код:
package Main;

public class Main {

    public static void main(String[] args) {
        System.out.println("Hello word");
    }
}

Переменная PATH (Windows)

Windows 10 и Windows 8
В строке "Поиск" выполните поиск:

Система (Панель управления)

Нажмите на ссылку

Дополнительные параметры системы

Нажмите

Переменные среды

В разделе Переменные среды выберите переменную среды

PATH

Нажмите Изменить. Если переменной PATH не существует, нажмите Создать.
В окне Изменение системной переменной (или Новая системная переменная) укажите значение переменной среды PATH(;C:\Program Files\Java\jdk1.8.0_121\bin\). Нажмите ОК. Закройте остальные открытые окна, нажимая ОК.
Откройте заново окно командной строки и выполните код java.

Windows 7

На рабочем столе правой кнопкой нажмите на значок

Компьютер

В контекстном меню выберите

Свойства

.
Нажмите на ссылку

Дополнительные параметры системы

Нажмите

Переменные среды

В разделе Переменные среды выберите переменную среды

PATH

Нажмите

Изменить

Если переменной PATH не существует, нажмите Создать.
В окне Изменение системной переменной (или Новая системная переменная) укажите значение переменной среды PATH(;C:\Program Files\Java\jdk1.8.0_121\bin\). Нажмите ОК. Закройте остальные открытые окна, нажимая ОК.
Откройте заново окно командной строки и выполните код java.

Компиляция java-файла: имя файла должно быть, такое же как и имя класса, т.е. Main.java. Далее после установки PATH:

в моем случае появится рядом с Main.java файлом, файл Main.class(скомпилированный)

A: Пишите полный путь к jdk:
"C:\Program Files\Java\jdk1.8.0_121\bin\javac.exe" YourFile.java

или добавьте переменную среды.


text:
Q: @Before not setting up data during integration test I am creating an integraiton test for a JpaRepository and the testcase fails with "Record not found with random value rand", as null is returned in the find results.
My test case:
@SpringBootTest
class JpatestsApplicationTests {

@Autowired
private JpaRepo jpaRepo;

@Before
void setup() {
    FirstTable firstTable1 = new FirstTable();
    firstTable1.setUid("x");
    firstTable1.setRandom("rand");
    jpaRepo.save(firstTable1);
}

@Test
void testFindByRandom() {
    FirstTable f = jpaRepo.findByRandom("rand");//find by random value 'rand'
    Assert.notNull(f, "Record not found with random value rand ");
}

The entity associated:
@Entity
@Table(name = "table1")
public class FirstTable {

    @Id
    @GeneratedValue
    private String uid;

    @Column
    private String random;

And my Repository:
    @Repository
    public interface JpaRepo extends JpaRepository<FirstTable, Long> {

    FirstTable findByRandom(String rand);
   }

I am using h2 database.
Why is the result coming as null for findByRandom? Also please note that if I move the record saving part  jpaRepo.save(firstTable1) to be within the test case (before the findByRandom("rand") is called, it gets passed.
Why wouldn't it work if I save the record in setup() method annotated with @Before ?

A: You have to add @Transactional on the top of your class.
@Transactional will cause your tests to execute within a test-managed transaction that will be rolled back after the test completes; code executed within the @Before method will be executed inside the test-managed transaction.

A: The latest version of spring-boot-test makes use of junit 5 and @Before is deprecated. It started working after changing to @BeforeAll with annotation of @TestInstance(TestInstance.Lifecycle.PER_CLASS) at the class level
My updated test class:
@SpringBootTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class JpatestsApplicationTests {

@Autowired
private JpaRepo jpaRepo;

@BeforeAll
void setup() {
    FirstTable firstTable1 = new FirstTable();
    firstTable1.setUid("x");
    firstTable1.setRandom("rand");
    jpaRepo.save(firstTable1);
}

@Test
void testFindByRandom() {
    FirstTable f = jpaRepo.findByRandom("rand");//find by random value 'rand'
    Assert.notNull(f, "Record not found with random value rand ");
}

Chose BeforeAll over BeforeEach as I need to run it only once during execution of this class.
Reference: https://junit.org/junit5/docs/current/user-guide/


text:
Q: Get possible values of field of type parameter set How can I get all possible values of field of type parameter set from JavaScript?
I.e. I have entity Entity1 and it has field Field1, which is set of parameters(Param1,Param2,Param3).
How can I retrieve Param1, Param2 and Param3 from crm and pass it to select element of html?

A: If you are in CRM page context you can use
Xrm.Page.getAttribute(attribute).getOptions();

If you don't have page context, have a  look at example in SDK (SDK\SampleCode\JS\SOAPForJScript\SOAPForJScript\Scripts\SDK.MetaData.js). You can find sample usage here.


text:
Q: How to remove XAMPP but keep its modules like mysql? I use XAMPP to host my MySQL database. After I did "ALTER ADD COLUMNS" operation, I can't connect MySQL by phpmyadmin anymore.
My phpmyadmin have some error like image.

I tried to remove xampp but it seems will also remove mysql but I want to keep my data alive.
How to I remove just XAMPP and keep my data in mysql safe? Or did I have any method to fix this error?
I use Unity C# to send MySQL "ALTER" query like below.
for (int i = 0; i < 10; i++)
{
    string query = "";

    query += "ALTER TABLE solutions_" + i + " ADD  ";
    query += "tail_length FLOAT";
    query += ";";

    MySqlCommand myCommand = new MySqlCommand(query, conn);
    myCommand.ExecuteNonQuery();
}