text:
Q: Retaining data while modifying column data type I am trying to modify a data type while retaining the existing data. Here is the current setup:
create or replace type xyz.Varray2 is varray(50) of varchar2(20);

CREATE TABLE xyz.owner (
MODIFIED DATE,
ID Varchar(18),
STATE Varchar(2),
CONTRIBUTOR_IDS xyz.Varray2
)

An example record looks like this:
10-MAR-13 408923100000000002 CA VARRAY2('Bob', 'Tom', 'Mary', 'Henry', 'Bart')

I need to modify the Varray2 data type to be a varray(150). I would rather keep the Varray2 type, but if necessary a new Varray3 type could be created for use.
This table contains millions of records that need to be retained. In order to modify the existing Varray2 type, I have to drop the table, which is my first problem. I tried to export the table and then import it after changing Varray2 to 150, but it gives an error that the types are different. I tried to create a backup table with the new data type, but it gave an error when trying to save the data (incompatible type again). It would not let me modify the column data type on the fly, either (ORA-22859).
I am on the verge of writing a cursor or even a bash script to parse spooled output to generate INSERT commands to insert into the new table, but that seems excessive. I was hoping someone here would be able to come up with a simpler solution.

A: The upper limit of the varray2 data type can be increased with alter type statement:
create or replace type Varray2 is varray(50) of varchar2(20);
/
TYPE VARRAY2 compiled

create table owner (
  modified        date,
  id1             Varchar2(18),  --   use varchar2 data type, not varchar.
  state           Varchar2(2),
  contributer_ids Varray2
)
/

table OWNER created.

Current information about varray2 data type:
SQL> clear screen;
SQL> column type_name format a11;
SQL> column upper_bound format a11

SQL> select t.type_name
  2       , t.upper_bound
  3   from all_coll_types t
  4  where type_name = 'VARRAY2';

TYPE_NAME   UPPER_BOUND
----------- -----------
VARRAY2              50

Change the upper limit of the varray2 data type:
SQL> alter type Varray2 modify limit 150 cascade;

type VARRAY2 altered.

After the upper limit of the varray2 data type has changed:
SQL> clear screen;
SQL> column type_name format a11;
SQL> column upper_bound format a11

SQL> select t.type_name
  2       , t.upper_bound
  3   from all_coll_types t
  4  where type_name = 'VARRAY2';

TYPE_NAME   UPPER_BOUND
----------- -----------
VARRAY2             150

cascade clause of the alter type statement propagates the data type change to the dependent objects, whether it's a table or another data type.


text:
Q: Sunspot: boost elements when match a multiple values field I have an object Foo which has many objects Bee.
    class Foo
       has_many :bees
I index my object A with Sunspot SOLR like this.
searchable do
  text :title, boost: 5
  text :content, boost: 2
  integer :bee_ids, multiple: true
  ...
end

to keep track of Bee ids related to my Foo object.
Now I have a User that performs searches on Foos objects. The User has many Bees too.
class User
    has_many :bees
    ...
end

When I search Foos objects I would like to boost objects which have bees that matches User's bees.
Foo.search do
    fulltext query
    any_of do
       ...
       with(:bee_ids, @user.bees.pluck(:id))
    end
end

I want to give priorities to objects that matches user's interests. Any idea?

A: Well. I found a solution for the problem above.
You need to use bq parameter to do that and give a boost to that condition.
I added
adjust_solr_params do |params|
  params[:bq] = " bee_ids_im:(#{@user.bees.pluck(:id).join(' OR ')})^20"
end

and I give a boost to the above condition of 20 times.
Actually that the solution to the more generic problem of giving boost to specific conditions in the query.
Sunspot support boost queries with boost command.
So I changed my query with:
Foo.search do
  fulltext query do
    boost(20.0) do
      with(:bee_ids, @user.bees.pluck(:id))
    end
  end
  any_of do
    ...
    with(:bee_ids, @user.bees.pluck(:id))
  end
end

and I obtained the same result.
Hope this can help someone else.

redpajama_set_name: RedPajamaStackExchange


text:
Q: FirebaseAuth Error - Credential __FIRAPP_DEFAULT[0] not found (Unity) Iam using firebase auth on unity, when i try use auth.CreateUserWithEmailAndPasswordAsync that errors appear:
LoadUserData: Credential  I REMOVED THE CREDENTIALS.firebase.auth/__FIRAPP_DEFAULT[0] not found
UnityEngine.Debug:Log (object)
Firebase.Platform.FirebaseLogger:LogMessage (Firebase.Platform.PlatformLogLevel,string) (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/platform/Unity/FirebaseLogger.cs:89)
Firebase.LogUtil:LogMessage (Firebase.LogLevel,string) (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/src/LogUtil.cs:69)
Firebase.LogUtil:LogMessageFromCallback (Firebase.LogLevel,string) (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/src/LogUtil.cs:77)
Firebase.AppUtil:PollCallbacks () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/android_unity/armeabi-v7a/app/swig/Firebase.App_fixed.cs:4614)
Firebase.Platform.FirebaseAppUtils:PollCallbacks () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/platform/FirebaseAppUtils.cs:33)
Firebase.Platform.FirebaseHandler:Update () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/platform/Unity/FirebaseHandler.cs:208)
Firebase.Platform.FirebaseMonoBehaviour:Update () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/platform/Unity/FirebaseMonoBehaviour.cs:45)

Failed to read user data for app (__FIRAPP_DEFAULT).  This could happen if the current user doesn't have access to the keystore, the keystore has been corrupted or the app intentionally deleted the stored data.
UnityEngine.Debug:Log (object)
Firebase.Platform.FirebaseLogger:LogMessage (Firebase.Platform.PlatformLogLevel,string) (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/platform/Unity/FirebaseLogger.cs:89)
Firebase.LogUtil:LogMessage (Firebase.LogLevel,string) (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/src/LogUtil.cs:69)
Firebase.LogUtil:LogMessageFromCallback (Firebase.LogLevel,string) (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/src/LogUtil.cs:77)
Firebase.AppUtil:PollCallbacks () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/android_unity/armeabi-v7a/app/swig/Firebase.App_fixed.cs:4614)
Firebase.Platform.FirebaseAppUtils:PollCallbacks () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/platform/FirebaseAppUtils.cs:33)
Firebase.Platform.FirebaseHandler:Update () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/platform/Unity/FirebaseHandler.cs:208)
Firebase.Platform.FirebaseMonoBehaviour:Update () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/platform/Unity/FirebaseMonoBehaviour.cs:45)

DeleteUserData: Credential I REMOVED THE CREDENTIALS.firebase.auth/__FIRAPP_DEFAULT[0] not found
UnityEngine.Debug:Log (object)
Firebase.Platform.FirebaseLogger:LogMessage (Firebase.Platform.PlatformLogLevel,string) (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/platform/Unity/FirebaseLogger.cs:89)
Firebase.LogUtil:LogMessage (Firebase.LogLevel,string) (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/src/LogUtil.cs:69)
Firebase.LogUtil:LogMessageFromCallback (Firebase.LogLevel,string) (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/src/LogUtil.cs:77)
Firebase.AppUtil:PollCallbacks () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/android_unity/armeabi-v7a/app/swig/Firebase.App_fixed.cs:4614)
Firebase.Platform.FirebaseAppUtils:PollCallbacks () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/platform/FirebaseAppUtils.cs:33)
Firebase.Platform.FirebaseHandler:Update () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/platform/Unity/FirebaseHandler.cs:208)
Firebase.Platform.FirebaseMonoBehaviour:Update () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/platform/Unity/FirebaseMonoBehaviour.cs:45)

I dont know why that started happening, just started after i switched the google-services.json for a new one, cause i changed my firebase project
Code:
public static bool Registry(string email,string password, string confirmPassword, out string messageError){
    bool connected = false;
    string error = "";

    FirebaseApp.CheckAndFixDependenciesAsync();

    Firebase.FirebaseApp.LogLevel = Firebase.LogLevel.Debug;

    if (string.Equals(password,confirmPassword)) {
        FirebaseAuth auth = FirebaseAuth.DefaultInstance;

        auth.CreateUserWithEmailAndPasswordAsync(email, password).ContinueWith(task => {

            if (task.IsCanceled) {
                Debug.LogError("SignInWithEmailAndPasswordAsync was canceled.");
                return;
            }
            if (task.IsFaulted) {
                error = task.Exception.ToString();
                return;
            }
            Firebase.Auth.FirebaseUser newUser = task.Result;

            Debug.LogFormat("User signed in successfully: {0} ({1})",newUser.DisplayName, newUser.UserId);

            connected = true;
        });
    }else{
        error = "Password and Confirmed Password doenst match";
    }

    messageError = error;
    return connected;
}


text:
Q: Canvas interaction through an overlapping HTML element I'd like to have canvas interaction through a different HTML element.
I have been using the particles.js package and I added an overlapping HTML element to it. The overlapping element has no background (i.e. background: none) and only some text. However, the background of the overlapping element still blocks any canvas interaction.
I expect that the dots make connecting lines with the cursor both inside and outside of the box.
Here is an interaction:

Here is no interaction, where I would want it:

A minimum working example can be found here.
This example has been adapted from another codepen in order to show the problem clearly.
Is there any way to get an interaction through overlapping HTML elements?

A: As markE mentioned in the comments.
Setting pointer-events: none makes it possible to sent canvas interaction through an overlapping element.
edit: I have added the working code to the minimum working example. One only needs to uncomment it in the css.


text:
Q: DISM unable to capture a dir located on network disk
I am trying to capture an image with DISM, where the /capturedir path is located on a NAS mapped to Z: via net use in the same elevated command prompt that is running DISM (Z: works fine with any other utility from the same command prompt, including 7-zip console commands), and I receive error:
Dism /Capture-Image /ImageFile:"jobs.wim" /CaptureDir:"z:\sav\jobs" /Name:"test"

  Error: 161
  The specified path is invalid.

*

*I have searched for similar cases, but found nothing, with the closest case being the opposite (/capturedir on local disk to NAS)

*At this point, I wonder if it's even possible for DISM to capture from NAS

Of course, I can copy the dir to local disk and capture from there, but it's a waste of time, and why can 7-zip capture from NAS where DISM can't?
UPDATE 05/12/2021: I'm adding an image showing the problem, as you can see the admin cmd prompt has no problem listing files on both source and destination folder paths,yet DISM from the very same cmd prompt fails saying the path is invalid. I found a similar case here


text:
Q: How can i change size of sudoku I have a script to solve a Sudoku with size= 9*9
i have 81 variables and i define the rules for them,
How can change this code to solve a sudoku with any size?
for example for a sudoku 16*16, the rules will be for subsquares 4*4.

go(L) :-
        L=[A1,A2,A3,A4,A5,A6,A7,A8,A9,
        B1,B2,B3,B4,B5,B6,B7,B8,B9,
        C1,C2,C3,C4,C5,C6,C7,C8,C9,
        D1,D2,D3,D4,D5,D6,D7,D8,D9,
        E1,E2,E3,E4,E5,E6,E7,E8,E9,
        F1,F2,F3,F4,F5,F6,F7,F8,F9,
        G1,G2,G3,G4,G5,G6,G7,G8,G9,
        H1,H2,H3,H4,H5,H6,H7,H8,H9,
        I1,I2,I3,I4,I5,I6,I7,I8,I9],
        fd_domain(L,1,9),
    fd_alldifferent([A1,A2,A3,A4,A5,A6,A7,A8,A9]),
    fd_alldifferent([B1,B2,B3,B4,B5,B6,B7,B8,B9]),
    fd_alldifferent([C1,C2,C3,C4,C5,C6,C7,C8,C9]),
    fd_alldifferent([D1,D2,D3,D4,D5,D6,D7,D8,D9]),
    fd_alldifferent([E1,E2,E3,E4,E5,E6,E7,E8,E9]),
    fd_alldifferent([F1,F2,F3,F4,F5,F6,F7,F8,F9]),
    fd_alldifferent([G1,G2,G3,G4,G5,G6,G7,G8,G9]),
    fd_alldifferent([H1,H2,H3,H4,H5,H6,H7,H8,H9]),
    fd_alldifferent([I1,I2,I3,I4,I5,I6,I7,I8,I9]),

    fd_alldifferent([A1,B1,C1,D1,E1,F1,G1,H1,I1]),
    fd_alldifferent([A2,B2,C2,D2,E2,F2,G2,H2,I2]),
    fd_alldifferent([A3,B3,C3,D3,E3,F3,G3,H3,I3]),
    fd_alldifferent([A4,B4,C4,D4,E4,F4,G4,H4,I4]),
    fd_alldifferent([A5,B5,C5,D5,E5,F5,G5,H5,I5]),
    fd_alldifferent([A6,B6,C6,D6,E6,F6,G6,H6,I6]),
    fd_alldifferent([A7,B7,C7,D7,E7,F7,G7,H7,I7]),
    fd_alldifferent([A8,B8,C8,D8,E8,F8,G8,H8,I8]),
    fd_alldifferent([A9,B9,C9,D9,E9,F9,G9,H9,I9]),

    fd_alldifferent([A1,A2,A3,B1,B2,B3,C1,C2,C3]),
    fd_alldifferent([A4,A5,A6,B4,B5,B6,C4,C5,C6]),
    fd_alldifferent([A7,A8,A9,B7,B8,B9,C7,C8,C9]),

    fd_alldifferent([D1,D2,D3,E1,E2,E3,F1,F2,F3]),
    fd_alldifferent([D4,D5,D6,E4,E5,E6,D4,D5,D6]),
    fd_alldifferent([D7,D8,D9,E7,E8,E9,D7,D8,D9]),
    fd_alldifferent([G1,G2,G3,H1,H2,H3,I1,I2,I3]),
    fd_alldifferent([G4,G5,G6,H4,H5,H6,I4,I5,I6]),
    fd_alldifferent([G7,G8,G9,H7,H8,H9,I7,I8,I9]),
    fd_labeling([A1,A2,A3,A4,A5,A6,A7,A8,A9,
    B1,B2,B3,B4,B5,B6,B7,B8,B9,
    C1,C2,C3,C4,C5,C6,C7,C8,C9,
    D1,D2,D3,D4,D5,D6,D7,D8,D9,
    E1,E2,E3,E4,E5,E6,E7,E8,E9,
    F1,F2,F3,F4,F5,F6,F7,F8,F9,
    G1,G2,G3,G4,G5,G6,G7,G8,G9,
    H1,H2,H3,H4,H5,H6,H7,H8,H9,
    I1,I2,I3,I4,I5,I6,I7,I8,I9]).

should i write another script or just i can change this one?
Thanks,

A: The code will need a rewrite to work for a general case. It is currently completely hard-coded for all the dimensions, so it can't be just tweaked to generalize it.
Here is an example to show you how you can use maplist as a tool for a problem like this. It is not a complete solution to your problem, but should get you started.
% Auxiliary predicates that will be maplist-friendly (the list is the last argument)
%
length_(N, L) :- length(L, N).
fd_domain_(Min, Max, L) :- fd_domain(L, Min, Max).

constrained_matrix(N, Matrix) :-
    length(Matrix, N),                   % Matrix has N elements
    maplist(length_(N), Matrix),         % Each element of Matrix has N elements
    maplist(fd_domain_(1, N), Matrix),   % The domain of each sublist is 1 to N
    maplist(fd_all_different, Matrix),   % Each sublist must have elements all different
    maplist(fd_labeling, Matrix).

And run a query like this:
| ?- constrained_matrix(3, L).

L = [[1,2,3],[1,2,3],[1,2,3]] ? ;

L = [[1,2,3],[1,2,3],[1,3,2]] ? ;

L = [[1,2,3],[1,2,3],[2,1,3]] ? ;

L = [[1,2,3],[1,2,3],[2,3,1]] ? ;
...

As you can see, the solution set is all 3x3 matrices which have rows with unique elements, but columns can be anything. You can add more constraints by writing/using Prolog predicates that can transpose a matrix (interchange rows versus columns in Matrix) and use maplist again to constrain the columns. You can add even more constraints for subsquares as needed (write a predicate to extract a submatrix, for example, and make good use of maplist).


text:
Q: How can I most simply, elegantly & robustly avoid awkwardness with Biblatex and author-year, when two authors share a surname and \citeauthor is used? If I have multiple authors with the same surname, then \citeauthor always prints their first initials when using the author-year style provided by Biblatex.
It would not be too bad if this occurred only the first time the author was cited in a section or paragraph, but it becomes stupidly repetitive when the same author is mentioned multiple times, while no other author with the same surname gets a look-in.
Biblatex insists on doing this even when the author-year label does not need to include the initial to be unique - for example, because no authors with the same surname published cited sources in a single year. But the main point is that the usage is totally insensitive to context. It doesn't matter that this is the author I'm discussing in this section and there's no ambiguity at all, Biblatex doesn't care.

I don't recall if older versions of Biblatex did this, but I've certainly only noticed it with recent versions, so it might be an effect of the recent changes to name handling.
How can I avoid the inclusion of the initial? I'm fine if I need to define a command other than \citeauthor for this, so long as I can use the same command everywhere I currently use \citeauthor (and similarly for \Citeauthor).
I know this is not a problem with numeric citation styles, but those really aren't an option for me. It has to be author-year. Also, adding shortauthor to every entry in my database files is not an appealing option, even if this works. (I haven't tried it because I regard it as absolutely a last resort.)
Here's an MWE:
\begin{filecontents}{\jobname.bib}
@article{minister-wid,
  author    =   {Minister, Prime},
  title     =   {What I Did},
  journal   =   {Westminster Chronicles},
  volume    =   11,
  number    =   2,
  pages     =   {33--56},
  year      =   2003}
@article{minister-wis,
  author    =   {Minister, Yes},
  title     =   {What I Said},
  journal   =   {Westminster Chronicles},
  volume    =   13,
  number    =   3,
  pages     =   {78--95},
  year      =   2005}
\end{filecontents}
\documentclass{article}
\usepackage[backend=biber,style=authoryear-comp]{biblatex}
\bibliography{\jobname}
\begin{document}
\Citeauthor{minister-wis} discusses this matter in \citetitle{minister-wis} \autocite*{minister-wis}, arguing that black may, after all, be white and that zebra crossings should, therefore, be banned.
Although \citeauthor{minister-wis} does not explicitly mention the implications of this argument, it is clear that it entails nothing less than an identification of red with green and the demise of the nation's caterpillars.

A lot of other rubbish then follows, discussing many things and not limited, for example, to cabbages or kings.

Then there is a brief mention of some other stuff \autocite{minister-wid}.

\printbibliography
\end{document}

I know that \citeauthor etc. is essentially producing the labelname list although it is not, in fact, the list as it appears in the label in the bibliography, since names appear there in full.
I'm assuming that it is basically outputting a formatted version of \field{labelname} which ends up producing author for the simple cases above, as explained on page 188 in the explanation of \DelcareLabelname.
However, \citename{minister-wis}{labelname} does not, in fact, give the same output as \citeauthor{minister-wis}, so I assume the latter is using another format for the field.
I can say
\DeclareNameFormat{enwteulu}{% addaswyd o biblatex.def
  \usebibmacro{name:family}
    {\namepartfamily}
    {\namepartgiven}
    {\namepartprefix}
    {\namepartsuffix}%
  \usebibmacro{name:andothers}%
}

and then
\citename{minister-wis}[enwteulu]{labelname}

produces just the surname. I realise that I should make a wrapper command rather than use \citename. But is this the right direction to go in or is there a simpler solution?
Is the default behaviour even the intended output or is it a bug? It seems exceptionally kludgey and awkward, and quite unsuitable for a default!

A: Sorry to disagree, but I think the default solution is the best. AT least, it is the standard recommendation. For instance, see http://www.lib.umd.edu/tl/guides/citing-chicago-ad (sectio : "How to construct an in-text parenthetical reference") or http://www.cws.illinois.edu/workshop/writers/citation/apa/intextcitation/, or again : http://blog.apastyle.org/apastyle/2014/01/when-to-use-author-initials-for-text-citations.html. Even if for you as an author, there is no ambiguity when changing locally the references, for a reader (and a publisher), the situation is different : we want the same label all along in the article (and sorry, thus, to be able to skip a paragraph without being lost). A key issue in bibliography and typography is consistency (whatever the choice, the same all along: see http://www.math.illinois.edu/~ajh/tex/bibliographies.html, which addresses also the first issue). The author date system allows/should allow the reader to know immediately who is writing about what. All the most because often, publishers will erase the first name after one instance of it.


text:
Q: simple joined-subclass example tries to update the identity column of the base table I must be missing something very important in the concept to get this
error so any help appreciated.
I get
----> System.Data.SqlClient.SqlException : Cannot update identity
column 'ProductID'.
when i run this
 var tblEvent = session.Load<TblEvent>(17);
           tblEvent.Code+= " - test update";
           using (var tran = session.BeginTransaction())
           {
               session.SaveOrUpdate(tblEvent);
               tran.Commit();
           }

The load works correctly and i can inspect all the properties but the update fails.
Heres the mapping file
<hibernate-mapping namespace="Booking.BLL" assembly="Booking.BLL" xmlns="urn:nhibernate-mapping-2.2" >
 <class name="TblProduct" table="tblProduct" schema="dbo">
   <id name="_productID" access="field" column="ProductID"    type="Int32" >
     <generator class="native"  />
   </id>
   <property name="Active" type="Boolean" not-null="true" />
   <property name="AllowBackOrder" type="Boolean" not-null="true" />
   <property name="BuyY" type="Int32" precision="10" />
   <property name="BuyYQty" type="Int32" precision="10" />
   <property name="CategoryID" type="Int32" precision="10" />
   <property name="Code" type="String" length="50" />
   <property name="ColourID" type="Int32" precision="10" />
   <property name="ColourNameOverride" type="String" length="250" />
   <property name="Cost" type="Decimal" precision="10" not-null="true" />
   <property name="CreatedBy" type="Int32" precision="10" />
   <property name="CreatedDate" type="DateTime" />
   <property name="CustomSort1" type="Int32" precision="10" />
   <property name="CustomSort2" type="Int32" precision="10" />
   <property name="CustomSort3" type="Int32" precision="10" />
   <property name="DefaultImageID" type="Int32" precision="10" />
   <property name="Depth" type="Decimal" precision="10" not-null="true" />
   <property name="DispatchCategoryID" type="Int32" precision="10" />
   <property name="DisplayIfNoStock" type="Boolean" not-null="true" />
   <property name="GetXFree" type="Int32" precision="10" />
   <property name="GetXPercentDiscount" type="Decimal" precision="6" />
   <property name="Height" type="Decimal" precision="10" not-null="true" />
   <property name="IsFavourite" type="Boolean" not-null="true" />
   <property name="IsFeatured" type="Boolean" not-null="true" />
   <property name="IsInSite" type="Int32" precision="10" />
   <property name="IsSpecial" type="Boolean" not-null="true" />
   <property name="Keywords" type="String" length="250" />
   <property name="LongDescription" length="2147483647" />
   <property name="LongDescription2" length="2147483647" />
   <property name="LongDescription3" length="2147483647" />
   <property name="ManufacturerID" type="Int32" precision="10" />
   <property name="Name" type="String" length="250" not-null="true" />
   <property name="NoStockMessage" type="String" length="250" />
   <property name="OrderRanking" type="Int32" precision="10" />
   <property name="ParentID" type="Int32" precision="10" />
   <property name="Price" type="Decimal" precision="10" not-null="true" />
   <property name="PriceMember" type="Decimal" precision="10" />
   <property name="PriceRRP" type="Decimal" precision="10" />
   <property name="PriceSpecial" type="Decimal" precision="10" />
   <property name="PromotionID" type="Int32" precision="10" />
   <property name="RefExt" type="String" length="250" />
   <property name="SellBundledOnly" type="Boolean" />
   <property name="Sex" type="Int32" precision="10" />
   <property name="ShortDescription" type="String" length="500" not-null="true" />
   <property name="Size" type="String" length="50" />
   <property name="SizeID" type="Int32" precision="10" />
   <property name="SizeNameOverride" type="String" length="250" />
   <property name="SizeUnit" type="String" length="10" />
   <property name="SpecialEnd" type="DateTime" />
   <property name="SpecialStart" type="DateTime" />
   <property name="Status" type="Boolean" not-null="true" />
   <property name="Stock" type="Int32" precision="10" not-null="true" />
   <property name="SupplierID" type="Int32" precision="10" />
   <property name="TaxExempt" type="Boolean" not-null="true" />
   <property name="UpdateBy" type="Int32" precision="10" />
   <property name="UpdateDate" type="DateTime" />
   <property name="WeightKG" type="Decimal" precision="10" not-null="true" />
   <property name="Width" type="Decimal" precision="10" not-null="true" />
   <many-to-one name="Parent" class="TblProduct" column="ProductID" not-null="true" />
   <bag name="TblProducts" table="tblProduct" inverse="true">
     <key column="ProductID" />
     <one-to-many class="TblProduct" />
   </bag>
       <joined-subclass name="TblEvent" table="tblEvent">
       <key column="EventID" />
               <property name="AttachmentFileURL" type="String" length="200" />
               <property name="GLAccountNo" type="String" length="20" />
               <property name="MultiDayEvent" type="Boolean" not-null="true" />
               <property name="PromotionActive" type="Boolean" not-null="true" />
               <property name="RequiresLogin" type="Boolean" not-null="true" />
               <property name="TopLevelCategoryID" type="Int32" precision="10" not-null="true" />
               <property name="TotalAllocation" type="Int32" precision="10" not-null="true" />
               <bag name="TblSessionTemplates" table="tblSessionTemplate" inverse="true">
                 <key column="EventID" />
                 <one-to-many class="TblSessionTemplate" />
               </bag>
               <bag name="TblSessions" table="tblSession" inverse="true">
                 <key column="EventID" />
                 <one-to-many class="TblSession" />
               </bag>
       </joined-subclass>
 </class>
</hibernate-mapping>

A: Ok turns out it was the many-to-one relationship pointing to ProductID instead of parentID.
db2hbm seems to have not been able to handle self referencing foreign keys


text:
Q: The following code produces this error: "conflicting types for 'fptr' ." While debugging this code I get the following error: "conflicting types for 'fptr'." This shows at 3 lines with the same piece of code. I'll just identify one line: 158 in the void list() section. I'm no expert in files. I ask if you know what's the issue if you could please intervene? Thank you in advance!!
Header file:
struct employee
{
        char name[50];
        char sex[7];
        char adrs[50];
        char dsgn[25];
        int age;
        int empID[9];
        float slry;
};

Problem:
     printf("-------------------------------");
     printf("\nEmployee Details: \n---------------------------------\n");
     rewind(fptr);///moves file to start of the file
     size_t fread(void *fptr, size_t size, size_t nmemb, FILE *fptr)///read the file and fetch the
     record one record per fetch

Entire code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <ctype.h>
#include <stdbool.h>
#include <windows.h>
#include "struct.h"

void insert();
void list();
void edit();
void del();
void exit();
int tolower();

FILE * fptr, *ftemp;
struct employee e;
size_t recsize ;
char empname[50];

int main()
{
    int choice;
    fptr = fopen("ems.txt", "r+");

    if (fptr == NULL)
    {
        printf("Can't find file! Attempting to create file... \n");

        fptr = fopen("ems.txt","w+");
        if(fptr == NULL)
        {
            printf("Can't create file. Exiting...");
         exit(1);
        }
    }

    //Explain the reason for this?
    recsize = (long int) sizeof(e);

    while(1)
    {
        printf("*******************************\n");
        printf("\nEmployee management system");
        printf("\n1. Insert employee information");
        printf("\n2. List all employee information");
        printf("\n3. Edit employee information");
        printf("\n4. Delete employee information");
        printf("\n5. Exit");
        printf("\n\n*****************************\n");
        printf("\n\n Enter your choice: ");
        scanf("%d", &choice);
        int ch;  while( ( ch = getchar() ) != EOF && ch != '\n' ){;}

        switch(choice)
        {
            case 1:
                puts("Insert was chosen");
                insert();

                break;
            case 2:
                puts("List was chosen");
                list();
                break;
            case 3:
                puts("Edit was chosen");
                edit();
                break;
            case 4:
                puts("Delete was chosen");
                del();
                break;
            case 5:
                puts("Exit was chosen");
                exit(1);
                break;
            default:
                puts("Choice is incorrect!!");
                break;
        }
    }

    return 0;
}

void insert()
{
    char next;

    do
    {
        printf("********************************************************** \n");
        printf("\nEnter the name of the employee: ");
        fgets(e.name, sizeof(e.name), stdin);
        e.name[strcspn(e.name, "\n\r")] = '\0';

        printf("\nEnter the sex of the employee (M/m or F/f): ");
        scanf("%6s",e.sex);

        switch(*e.sex)
        {
            case 'M':
            case 'm':
                printf("\nMale.\n");
                break;
            case 'F':
            case 'f':
                printf("\nFemale.\n  ");
                break;
            default:
                printf("Unspecified Sex.");
        }

        printf("\nEnter the address of the employee: ");

        fseek(stdin, 0, SEEK_END); // ADD THIS TO AVOID SKIP

        fgets(e.adrs, sizeof(e.adrs), stdin); // this
        e.adrs[strcspn(e.adrs, "\n\r")] = '\0';

        printf("\nEnter designation of the employee: ");
        fgets(e.dsgn, sizeof(e.dsgn), stdin); // this
        e.dsgn[strcspn(e.dsgn, "\n\r")] = '\0';

        printf("\nEnter age of the employee: ");
        scanf("%d", &e.age);
        printf("\nEnter basic salary of the employee: ");
        scanf("%f", &e.slry);
        printf("\nEnter the employee's ID: ");
        scanf("%8d", e.empID);
        fprintf(fptr, "%s\n", e.name);
        fprintf(fptr, "%6s\n", e.sex);
        fprintf(fptr, "%s\n", e.adrs);
        fprintf(fptr, "%s\n", e.dsgn);
        fprintf(fptr, "%d \n%f \n%d \n", e.age, e.slry, e.empID[9]);
        fwrite(&e,recsize,1,fptr);
        int ch;  while( ( ch = getchar() ) != EOF && ch != '\n' ){;}
        //fflush(stdin);//
        printf("\nDo you want to input more? (y/n): ");
        next = getche();
        printf("\n");
    }
    while( tolower(next) != 'n' );

    //fclose(fptr);
}

void list ()
{
     printf("-------------------------------");
     printf("\nEmployee Details: \n---------------------------------\n");
     rewind(fptr);///moves file to start of the file

L158///  size_t fread(void *fptr, size_t size, size_t nmemb, FILE *fptr)///read the file and fetch the
record one record per fetch
{
printf("\n\n%s \t\t%6s \t%s \t%s \t%d \t%.2f \t%d",e.name, e.sex, e.adrs, e.dsgn, e.age,
e.slry, e.empID[9]);
return;
}
getch();
     /*printf("Name        : %s\n",e.name);
     printf("Address     : %s\n",e.adrs);
     printf("Sex         : %c\n",e.sex);
     printf("Designation : %s\n",e.dsgn);
     printf("Age         : %d\n",e.age);
     printf("Salary      : %.2f\n",e.slry);
     printf("Employee-ID : %d\n",e.empID);*/
}

void edit ()
{
    char next;
    do
    {
        printf("Enter the employee's name to be edited: ");
        scanf("%49[^\n]", empname);
        rewind(fptr);
        size_t fread(void *fptr, size_t size, size_t nmemb, FILE *fptr)///fetch all records from file
        {
            if(strcmp(e.name,empname) == 0) ///if entered name matches with that in file
                {
                printf("\nEnter new name, sex, address, designation, age, salary and employee ID: ");
                scanf("%s%c%s%s%d%f%d", e.name, e.sex, e.adrs, e.dsgn, &e.age, &e.slry, e.empID);
                fseek(fptr, -recsize, SEEK_CUR);/// move cursor 1 step back from current position
                fwrite(&e, recsize,1,fptr); ///override the record
                break;
                }
        return ;}

        printf("\nEdit another record(y/n)");
        next = getche();
        int ch;  while( ( ch = getchar() ) != EOF && ch != '\n' ){;}

    }
    while(next != 'n');

    return ;
}

void del()
{
    char next;
    do
    {
        printf("\nEnter name of employee to delete: ");
        scanf("%s",empname);
        ftemp = fopen("Temp.dat","wb"); ///create a intermediate file for temporary storage
        rewind(fptr); ///move record to starting of file
        size_t fread(void *fptr, size_t size, size_t nmemb, FILE *fptr)  ///read all records from file
        {
            if(strcmp(e.name,empname) != 0)  ///if the entered record match
            {
                fwrite(&e,recsize,1,ftemp); ///move all records except the one which is to be deleted to temp file
            }
            return ;
        }

        fclose(fptr);
        fclose(ftemp);
        remove("ems.txt"); ///remove original file
        rename("Temp.dat","ems.txt"); ///rename temp file to original file name
        fptr = fopen("ems.txt", "rb+");
        printf("Delete another record(y/n)");
        int ch;  while( ( ch = getchar() ) != EOF && ch != '\n' ){;}
        next = getche();

    }while( tolower(next) != 'n' );
    fclose(fptr);
    exit(0);
}


text:
Q: How to parse and access columns based on headers in file? - Python I believe this is a 3 step process but please bear with me.
I'm currently reading Shell output which is being saved to a file and the output looks like this:
Current Output:
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 123.345.789:1234        0.0.0.0:*               LISTEN      23044/test
tcp        0      0 0.0.0.0:5915            0.0.0.0:*               LISTEN      99800/./serv
tcp        0      0 0.0.0.0:1501            0.0.0.0:*                           -

I'm trying to access each columns information based on the header value. This is something I was able to do in Powershell but not sure how to achieve it in Python.
Expected Output:
Proto,Recv-Q,Send-Q,Local Address,Foreign Address,State,PID/Program name
tcp,0,0,123.345.789:1234,0.0.0.0:*,LISTEN,23044/test
tcp,0,0,0.0.0.0:5915,0.0.0.0:*,LISTEN,99800/./serv
tcp,0,0,0.0.0.0:1501,0.0.0.0:*,,-

proto = data["Proto"]
for p in proto:
    print(p)

Output: tcp tcp tcp

What I've tried?:
Where do I begin.. I've tried Splitting, Replacing and Translate. Also, I did try Regex but couldn't quite figure it out :/
Proto,Recv-Q,Send-Q,Local,Address,,,,,,,,,,,Foreign Address,,,,,,,,,State,,,,,, PID/Program,name
tcp,,,,,,,,0,,,,,,0 123.345.789:1234,,,,,,,,0.0.0.0:*,,,,,,,,,,,,,,,LISTEN,,,,,,23021/java,,,,,,,,
tcp,,,,,,,,0,,,,,,0 0.0.0.0:5915,,,,,,,,,,,,0.0.0.0:*,,,,,,,,,,,,,,,LISTEN,,,,,,99859/./statserv
tcp,,,,,,,,0,,,,,,0 0.0.0.0:1501,,,,,,,,,,,,0.0.0.0:*,,,,,,,,,,,,,,,LISTEN,,,,,,-

Since some of the headers contain a space in between them it's sort of difficult to map the columns accordingly.
Looking for the best way to approach this.
Thank you.

A: You are post-processing the output of the netstat command.  netstat itself is just reformatting the information in /proc/net/tcp, which you can also read.  As with the netstat output, you may need to make your own header line, but the data lines are all space separated.  A simple line.split() should do it.
If you still want to use netstat, as I said, just throw away the header line and use split.  You know what the columns are.
for ln in output:
    fields = ln.split()
    print( ','.join(fields) )

A: Answer updated to handle missing State value
Skip the first row, indicate that there is no header, assign header names and then split on one or more spaces.
df = pd.read_csv(sim_txt, skiprows=1, header=None, sep='\s+',
                 names=['Proto','cv-Q','Send-Q','Local Address','Foreign Address','State','PID/Program name']
                ).apply(row_fixer, axis=1)
print(df)

  Proto  cv-Q  Send-Q     Local Address Foreign Address   State  PID/Program name
0   tcp     0       0  123.345.789:1234       0.0.0.0:*  LISTEN        23044/test
1   tcp     0       0      0.0.0.0:5915       0.0.0.0:*  LISTEN      99800/./serv
2   tcp     0       0      0.0.0.0:5916       0.0.0.0:*     NaN      99801/./serv
3   tcp     0       0      0.0.0.0:1501       0.0.0.0:*  LISTEN                 -

df.to_csv('output.csv', index=None)

The above depends on the following function.  It looks for a NaN the last column in the row which would indicate that the State value is missing. When that situation is found the last two values are swapped.  (Note: this function detects NaNs by leveraging the fact that NaN != NaN):
def row_fixer(x):
    if x.iat[-1] != x.iat[-1]:
        xc = x.copy()
        xc.iat[-1] = xc.iat[-2]
        xc.iat[-2] = np.NaN
        return xc
    return x

The example above is based on the following example data:
Proto  cv-Q  Send-Q     Local Address Foreign Address   State  PID/Program name
  tcp     0       0  123.345.789:1234       0.0.0.0:*  LISTEN        23044/test
  tcp     0       0      0.0.0.0:5915       0.0.0.0:*  LISTEN      99800/./serv
  tcp     0       0      0.0.0.0:5916       0.0.0.0:*              99801/./serv
  tcp     0       0      0.0.0.0:1501       0.0.0.0:*  LISTEN                 -

A: Split based on a string with two or more spaces using a regex.
for ln in testset:
    splitted = re.split(r'\s{2,}', ln.replace("\n", ""))
    print(splitted)


text:
Q: File Upload option using angular material in angular 2 application Here, I am trying to create form. On one button, I need to upload some files.
But not getting how to upload files using angular 2 material.
Please can any one suggest.
My Code is,

<mat-checkbox>Ignore Errors</mat-checkbox>

<button mat-raised-button color="accent">Upload</button>

<button mat-raised-button color="accent" (click)="dialogRef.close()" >Cancel</button>

A: do it like this:
<input name="file" type="file" class="inputfile" (change)="onFileChange($event)"/>

then you can take care of uploaded file in onFileChange function in your .ts file ...


text:
Q: Sorting a list alphabetically by a Macro output this is an extended question taken by Alphabetically display the items in itemize
The solution posted by Werner is amazing. But what I need is to sort by a value of a macro.
For example \foo{Label} is a function that take Label as argument and give you SortLabel as string.
\foo{Label1} %Will print SortLabel1
\foo{Label2} %Will print SortLabel2
\foo{Label3} %Will print SortLabel3

\begin{sortedlist}
    \sortitem[\foo{Label1}]{Bar1}
    \sortitem[\foo{Label2}]{Bar2}
    \sortitem[\foo{Label3}]{Bar3}
\end{sortedlist}

Tryed to use \expandafter, but seems that datatool can store only by \foo{Label1} and can't sort for SortLabel1....
To be more specific, the function \foo for me is \glossentryname{} that give me the name of a glossary entry. Maybe this could be the reason that expansion doesn't work. Here's a MnWE
\documentclass{article}
\usepackage{datatool}% http://ctan.org/pkg/datatool
\usepackage{glossaries, glossary-tree}
\makeglossaries

%%%%Sorted Functions%%%%
\newcommand{\sortitem}[1]{%
  \DTLnewrow{list}% Create a new entry
  \def\tmp{\DTLnewdbentry{list}{description}}%
  \expandafter\tmp\expandafter{#1}% Add entry as description
}
\newenvironment{sortedlist}{%
  \DTLifdbexists{list}{\DTLcleardb{list}}{\DTLnewdb{list}}% Create new/discard old list
}{%
  \DTLsort{description}{list}% Sort list
  \begin{itemize}%
    \DTLforeach*{list}{\theDesc=description}{%
      \item \theDesc}% Print each item
  \end{itemize}%
}

%%%The Glossary Part%%%%%
\longnewglossaryentry{MVARglossary}{name=MVAR}{
The Description of glossary (not useful at the moment)
}

\begin{document}

Default:
\begin{itemize}
  \item ISDYNSTP:  Is dynamic time step used ?
  \item ISCDCA:
  \item MVAR
  \item IS2TL
\end{itemize}

\def\foo{ISDYNSTP:  Is dynamic time step used ?}
\def\bar{\glossaryname{MVARglossary}}

\glossentryname{MVARglossary}

\bar

Sorted:
\begin{sortedlist}
  \sortitem{\foo}
  \sortitem{ISCDCA:}
  \sortitem{\bar}
  \sortitem{\glossentryname{MVARglossary}}
  \sortitem{IS2TL}
\end{sortedlist}

\end{document}

suggests?

A: Here, I modified Werner's solution by editing \sortitem as
\newcommand{\sortitem}[1]{%
  \DTLnewrow{list}% Create a new entry
  \def\tmp{\DTLnewdbentry{list}{description}}%
  \expandafter\tmp\expandafter{#1}% Add entry as description
}

in order to expand the argument being processed.  Then, in the MWE, I can pass \foo as an item to be sorted (where \foo is a definition unrelated to glossary entry names).
The next problem was that \glossentryname is not expandable.  So I employed the existing \glsentryname macro instead (originally, I had made a limited version of \glossentryname, that is expandable, but Nicola pointed out that also plays with the font).  I then created a macro \sortgloss{<label>} that will invoke \sortitem on the expanded gloss-entry-name.
Here is the MWE (EDITED to take Nicola's suggestion at using the existing expandable \glsentryname rather than create a new expandable macro)
\documentclass{article}
\usepackage{glossaries}
\usepackage[T1]{fontenc}

\usepackage{datatool}% http://ctan.org/pkg/datatool
\makeatletter
\newcommand{\sortitem}[1]{%
  \DTLnewrow{list}% Create a new entry
  \def\tmp{\DTLnewdbentry{list}{description}}%
  \expandafter\tmp\expandafter{#1}% Add entry as description
}
\makeatother
\newenvironment{sortedlist}{%
  \DTLifdbexists{list}{\DTLcleardb{list}}{\DTLnewdb{list}}% Create new/discard old list
}{%
  \DTLsort{description}{list}% Sort list
  \begin{itemize}%
    \DTLforeach*{list}{\theDesc=description}{%
      \item \theDesc}% Print each item
  \end{itemize}%
}

\makeatletter
\newcommand\sortgloss[1]{%
  \protected@edef\x@glossname{\glsentryname{#1}}%
  \sortitem{\x@glossname}%
}
\makeatother
\begin{document}

Default:
\begin{itemize}
  \item ISDYNSTP:  Is dynamic time step used ?
  \item ISCDCA:
  \item MVAR
  \item IS2TL
\end{itemize}

\newacronym{MVx}{MVAR}{Many Virgins Act Responsibly}

\def\foo{ISDYNSTP:  Is dynamic time step used ?}

Sorted:
\begin{sortedlist}
  \sortitem{\foo}
  \sortitem{ISCDCA:}
  \sortgloss{MVx}
  \sortitem{IS2TL}
\end{sortedlist}

\end{document}

The output is the same as Werner's:

Alternately, if one were to define \sortitem to fully expand its argument:
\makeatletter
\newcommand{\sortitem}[1]{%
  \DTLnewrow{list}% Create a new entry
  \protected@edef\tmpA{#1}%
  \def\tmp{\DTLnewdbentry{list}{description}}%
  \expandafter\tmp\expandafter{\tmpA}% Add entry as description
}
\makeatother

then one would be free to invoke it as \sortitem{\glsentryname{MVx}} rather than \sortgloss{MVx}, if consistency of invocation syntax were important.


text:
Q: "In the lock" or "into the lock" Should it be

She put the key INTO the lock.

or

She put the key IN the lock.

Which is the correct preposition to use here?

A: Both are correct are perfectly natural to use.
Looking at the definitions from Google:
In: "expressing the situation of something that is or appears to be enclosed or surrounded by something else" - We can see that this fits the situation when the key is inside the lock. Since you are putting it there you are "putting it in"
Into: "expressing movement or action with the result that someone or something becomes enclosed or surrounded by something else." - We are moving the key and as a result it will be inside the lock, so this fits too.
I would guess that in casual spoken English, "put in" is more common simply because it's one less syllable to say so the 'to' gets dropped, but I could be wrong about this or it could be a regional thing(I'm from England).

A: With put, most prepositions expressing a spatial location are interpreted as a destination:

*

*Put the key in the lock

*Put the flowers on the table

*Put the picture above the sofa

etc. Into and onto can also be used with put to make the destination part of the meaning even more explicit. There is effectively no difference between put the key in the lock and put the key into the lock.


text:
Q: Visualizar una fecha Estoy tratando de visualizar un campo tipo fecha y aunque cuando uso el print la veo no se muestra en el entry,
Que estoy haciendo mal? acá le dejos varias partes del código:
Aquí hago la consulta
for BBDDEscuela in elUsuario:
    miID.set(BBDDEscuela[0])
    miNombre1.set(BBDDEscuela[1])
    miNombre2.set(BBDDEscuela[2])
    miApellido1.set(BBDDEscuela[3])
    miApellido2.set(BBDDEscuela[4])
    miSexo.set(BBDDEscuela[5])
    miFecha=(BBDDEscuela[6])
    miDias.set(BBDDEscuela[7])
miConexion.commit()

Aquí tengo el Entry, me lo muestra en el print pero no en el cuadro del Entry
cuadroFecha=Entry(miFrame1, textvariable=miFecha.strftime("%d/%m/%Y"))
cuadroFecha.grid(row=4, column=1, padx=10)
print(miFecha.strftime("%d/%m/%Y"))

A: Puedes hacer entry.insert(0, "Tu texto") para escribir tu String en la ventana. Vale aclarar que el metodo insert() toma como primer argumento una posición y como segundo la cadena que le quieras pasar, en este caso tu fecha.
Por otro lado para dibujar una variable, como creo que necesitas en este caso, puedes utilizar con Tkinter
entry_var = tk.StringVar()
entry = ttk.Entry(root, textvariable=entry_var)

Mas informacion


text:
Q: Caused by: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint Hi guys I have the following problem :
I have a back-end server written in Spring and working with PostgreSQL. At first, all was OK but now my friend created a SQL script for filling the database with test data. And here we go :
19:46:30,253 INFO  [stdout] (default task-6) Caused by: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "user_pkey"
19:46:30,254 INFO  [stdout] (default task-6)   Detail: Key (id)=(1) already exists.
19:46:30,254 INFO  [stdout] (default task-6)    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2497)
19:46:30,254 INFO  [stdout] (default task-6)    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2233)
19:46:30,254 INFO  [stdout] (default task-6)    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:310)
19:46:30,254 INFO  [stdout] (default task-6)    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:446)
19:46:30,254 INFO  [stdout] (default task-6)    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:370)
19:46:30,255 INFO  [stdout] (default task-6)    at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:149)
19:46:30,255 INFO  [stdout] (default task-6)    at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:124)
19:46:30,255 INFO  [stdout] (default task-6)    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197)
19:46:30,256 INFO  [stdout] (default task-6)    ... 158 more

In that script, we also have some test data for users. And this error is throwing during an attempt to sign up. I understand, this error saying that I cant save user with an existing id to the database. But I actually did not set the id for the user. When I send user to save() method user id = null, and I believe that Hibernate should look at the database or at user_id_sequence and choose last id + 1 for the current saving user. At least it worked like that until we filled our database with the test data. The question is why Hibernate is not choosing (last id + 1) but trying to save a new user with an existing id = 0? Is there any way to solve it?
Id generating strategy :
@Getter
@Setter
@MappedSuperclass
@EqualsAndHashCode
@NoArgsConstructor
@ToString(exclude = {"deleted", "updated"})
public class BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // ...
}

Hibernate configuration :
datasource.url=**********
datasource.username=**********
datasource.password=**********
datasource.driver=org.postgresql.Driver
hibernate.show_sql=false
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.batch.size=200
hibernate.hbm2ddl.auto=update

Sql script looks like a simple script for filling the database with test data :
INSERT INTO public.country (id, created, deleted, updated, code, name, telephone_prefix, continent_id) VALUES (101, NULL, false, NULL, 'ISR', 'Israel', 972, NULL);
....

A: Do you specify a an ID for your seeded data script ? If you do and they are positive numbers, you can try changing the ID to negative numbers. If you don't specify the ID you can try specifying the ID and make them negative numbers


text:
Q: scope.$watch in angular directive does not work proprely I'm using Angular and Bootstrap.
I'm trying to replicate the functionality of ng-model for bootstrap checkbox. What i would like to accomplish is:
i would like that when i click on the checkbox (label really) the model change, and actually that works... but what does not work that when i try to watch the object for changes the behavior is weired, because i need two click insted of one for disable or enable the checkbox.
Moreover if inside the the label element that has as attribute cm-checkbox="model.prop" i put a {{model.anotherprop}} wont work (does not render anything).
From the documentation i understood that because i want the two-way data bind the scope must be defined as i did.
Thank you for your help!
I have the following HTML:

      <input name="claim_free" type="checkbox" value="" data-toggle="checkbox">
      same lable text

And the following JS:
directive('cmCheckbox', function() {
  return {
    restrict: 'A',
    scope: {'cmCheckbox':'='},
    link: function(scope,elm,attrs) {
      scope.$watch('cmCheckbox', function() {
          console.log("first value for "+attrs.cmCheckbox+" is: "+scope.cmCheckbox);
          if (!scope.cmCheckbox) {
            console.log("checked");
            $(elm).removeClass("checked");
            $(elm).children("input").removeAttr("checked");
          } else { // false and undefined
            console.log("unchecked");
            $(elm).addClass("checked");
            $(elm).children("input").attr("checked","checked");
          }
      });
      $(elm).on('click', function(e) {
        e.preventDefault();
        var currentValue = elm.hasClass("checked") ? false : true;
        scope.$apply(function() {
          scope.cmCheckbox = currentValue;
        },true);
        scope.$parent.$apply();
      });
    }
  };
}).

Here is the jsFiddle: jsfiddle.net/pmcalabrese/66pCA/2


text:
Q: Number of distinct rotated strings We have a string S and we want to calculate the number of distinct strings that can be formed by rotating the string.
For example :-
S = "aaaa" , here it would be 1 string {"aaaa"}
S = "abab" , here it would be 2 strings {"abab" , "baba"}
So ,is there an algorithm to solve this in O(|S|) complexity where |S| is the length of string.

A: Suffix trees, baby!
If string is S. Construct the Suffix Tree for SS (S concatenated to S).
Find number of unique substrings of length |S|. The uniqueness you get automatically. For length |S| you might have to change the suffix tree algo a little (to maintain depth info), but is doable.
(Note that the other answer by johnsoe is actually quadratic, or worse, depending on the implementation of Set).

A: You can solve this with rolling hash functions used in the Rabin-Karp algorithm.
You can use the rolling hash to update the hash table for all substrings of size |S| (obtained by sliding a |S| window across SS) in constant time (so, O(|S|) in total).
Assuming your string comes from an alphabet of constant size, you can inspect the hash table in constant time to obtain the required metric.

A: Something like this should do the trick.
public static int uniqueRotations(String phrase){
    Set<String> rotations = new HashSet<String>();
    rotations.add(phrase);
    for(int i = 0; i < phrase.length() - 1; i++){
        phrase = phrase.charAt(phrase.length() - 1) + phrase.substring(0, phrase.length() - 1);
        rotations.add(phrase);
    }
    return rotations.size();
}


text:
Q: Sencha Touch 2: Loading pushed data into form I got some problems loading data into a form which I pushed onSelect.
(loading details for a specific list item)
onProductSelect: function(_dataView, _record)
{
    Ext.getCmp('products').push({
        title: _record.data.name,
        data: _record.data,
        styleHtmlContent: true,
        xtype: 'productDetails'
    });
}

I am pushing another view (productDetails) onto my productView (which is a navigationView). The data (_record.data) is available in the new pushed view via
tpl: '{someField}'

Now I'd like to know how to get this data (the fields data) into a textfield or a button (or sth like this) of a form.
If someone has a better idea how to get the data into the view/form or how to change the views (from list to detail) please let me know :)

A: here are some suggestions to your code:
1.use of underbar ('_') inside Sencha Touch is meant for variables which have get/set/apply/update. Although you are using local variables, it is best practice.
2.the word '_record' hopefully is a record. If so then you should use:
name = _record.get('name');
data = _record.getData();

The best way to fill a form is to use a formpanel and add the values to the formpanel, while all fields have a popper name assigned:
If your data are:
data = {name: 'Kurt001', password: '12er51wfA!'}

You could use this:
Ext.define('App.view.ProductDetails', {
    extend: 'Ext.form.Panel',
    xtype: 'productdetails',

    config: {
        cls: 'product-details',
        scrollable: null,
        layout: 'vbox',

        defaults: {
            labelAlign: 'top',
            clearIcon: false
        },

        items: [{
            xtype: 'textfield',
            name: 'name'
        }, {
            xtype: 'passwordfield',
            name: 'password'
        }, {
            xtype: 'button',
            itemId: 'btnLogin'
        }]
    }
});

And to add the data simply use:
Ext.Viewport.down('.productdetails').setValues(data);

Alternative:
var view = Ext.Viewport.down('.productdetails')
view.down('.textfield').setValue(data.name);
view.down('.passwordfield').setValue(data.password);

Alternative
view.down('.field[name=name]').setValue(data.name);
view.down('.field[name=password]').setValue(data.password);

To get the data from one view to the next you can follow different options:
1.Set the data to the current view and grab them from that view. It looks like you have a list. So you can apply the data to the list:
view.down('.list').myData = data;

Extended version would be to create a custom list with myData inside the config.
That way you could use:
view.down('.list').setMyData(data);

or in your case
_dataview.setMyData(data);

2.Use a store. As you are passing a record already you might want to add a selected field to your store model and simply set the flag.


text:
Q: XCode 7 XCTest(Kiwi) +load category methods called twice In our testing framework (based on Kiwi, which in turn is based on XCTest), we're using the "swizzling on load" technique described on NSHipster here to switch some stuff with mocks on load. It has been working well enough until we upgraded to XCode 7, and now somehow +load methods are called twice. As far as I understand this should never happen no matter what?
Here's the stack trace of the first +load call (takes place before main):
 Foo`+[FooManager(self=FooManager, _cmd="load") load] + 149 at FooExtensions.mm:152
 libobjc.A.dylib`call_load_methods + 292
 libobjc.A.dylib`load_images + 129
 ...
 dyld`dyld::useSimulatorDyld(int, macho_header const*, char const*, int, char const**, char const**, char const**, unsigned long*) + 1053
 dyld`dyld::_main(macho_header const*, unsigned long, int, char const**, char const**, char const**, unsigned long*) + 202
 dyld`dyldbootstrap::start(macho_header const*, int, char const**, long, macho_header const*, unsigned long*) + 428
 dyld`_dyld_start + 71

And this is how the second callstack looks like:
FooTests`+[FooManager(self=FooManager, _cmd="load") load] + 149 at FooExtensions.mm:152
ibobjc.A.dylib`call_load_methods + 292
ibobjc.A.dylib`load_images + 129

libdyld.dylib`dlopen + 70
CoreFoundation`_CFBundleDlfcnLoadBundle + 185
CoreFoundation`_CFBundleLoadExecutableAndReturnError + 336
Foundation`-[NSBundle loadAndReturnError:] + 641
XCTest`_XCTestMain + 542
IDEBundleInjection`____XCBundleInjection_block_invoke_2 + 20
CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 16
CoreFoundation`__CFRunLoopDoBlocks + 195
CoreFoundation`__CFRunLoopRun + 1016
CoreFoundation`CFRunLoopRunSpecific + 470
CoreFoundation`CFRunLoopRunInMode + 123
GraphicsServices`GSEventRunModal + 192
GraphicsServices`GSEventRun + 104
UIKit`UIApplicationMain + 160
Foo`UIApplicationMain(argc=<unavailable>, argv=<unavailable>, principalClassName=0x00000000, delegateClassName=@"AppDelegate") + 227 at ApplicationHooks.m:56
Foo`main(argc=5, argv=0xbfff7778) + 146 at main.mm:15
libdyld.dylib`start + 1

It looks like the dynamic loader initially calls the +load methods as expected, but then the XCTest runtime calls them again.
The thing is, even dispatch_once doesn't work as static variables don't seem to be initiated properly so the dispatch_once_t tokens change between +load invocations! The only thing that worked was creating a C++ class and delegating the dispatch_once call to it (using a proper c++ static variable for the dispatch_once_t).
EDIT - I'm pretty sure this +load order change is related, but I don't see how changing the order would have caused it to be run twice.
EDIT2 - It seems that this behavior is not new. From a comment in a related blog post:

If you are running a test bundle that is injected into an app, and
  both the app and the test bundle link to the same .a file, any load
  method in that .a file will be triggered twice.

A: It appears that you have included the same class extension in both the main application binary and in your test bundle. This would also explain why you see a separate setup of static dispatch_once tokens on the second load.
Why this is the case may be a number of things:

*

*.mm-file is included in both targets

*Xcode loads the test binary twice due to changes in test-procedure

*Both test target and application link to the same .a file containing the +load method


text:
Q: iOS7 App Submission - with only 2x (retina) images? I'm currently developing an application for iPhone with iOS7, only.
From what I read, for iPhone with iOS7, there is no support for older devices than iPhone4.
If that's the case, when it comes to images, all I need is retina images (@2x).
Can I submit to the App Store, an app with only retina images, since the app's minimal requirement is retina devices ?
Thank you.

A: Possible duplicate of Can I dump my non-Retina Images for a iOS7 only app?
Anyway, as long as I know you don't need @2x version of your images as long as you don't support old displays, but remember that your images as to be double width and height, then if you have a 100x100px UIImageView, you need to load a 200x200px image to meet retina resolution.
EDIT: To explain in deep.
Actually, iPad 2 and iPad mini 1st generation run iOS 7 and doesn't have retina display. Anyway using @2x images it is not mandatary. You can just use double size images and set your UIImageViews' contentMode to UIViewContentModeScaleToFill to fit your needs.
PROS -> smaller bundle
CONS -> worst performaces


text:
Q: Using nested folders with react-rails prerender I'm trying to set up react-rails for my app (https://github.com/reactjs/react-rails).
I had no problem getting it to set up initially, but I'm anticipating a lot of different individual components so I want to organize my /javascript/components folder neatly.
So I have something like this
components
 character
   avatar-selector
     AvatarSelector.tsx
 HomeLogo.tsx

The AvatarSelector.tsx exports the component as default.
And I have
const componentRequireContext = require.context("components", true);
const ReactRailsUJS = require("react_ujs");
ReactRailsUJS.useContext(componentRequireContext);

in both packs/application.js and packs/server-rendering.js
When I render the HomeLogo component everything works fine both with and without prerender.
When I then go to render the component with react_component('character/avatar-selector/AvatarSelector', avatar_props, prerender: false) it also works fine.
But when I switch to prerender: true it gives an error.
ExecJS::ProgramError: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.>" when prerendering character/avatar-selector/AvatarSelector

I have already tried directly adding
const AvatarSelector = require('../components/character/avatar-selector/AvatarSelector')

to my packs and trying to render the component as AvatarSelector but I still get the same error.

A:  Regarding Encountered error <ExecJS::ProgramError: Invariant Violation: Element type is invalid: ...:

I think one of the core issues is that module lookup uses try...catch. While the errors are logged to the console shim, that typically doesn't help as a later error (such as the invariant violation) will lead to a fatal error (triggering a 500). If that could be refactored to be a bit more intentional based on environment (instead of just reacting based on exceptions, or at the very least, throwing if the caught exception isn't very specific)
EDIT: Here's something you can do to help with the Invariant Violation bug:

In app/javascripts/packs/server_rendering.js, replace ReactRailsUJS.useContext('require.context('components', true)); with

// So that we don't fall back to the global namespace (which leads to hard to
// parse errors).
function fromRequireContext(reqctx) {
  return function(className) {
    const parts = className.split('.');
    const filename = parts.shift();
    const keys = parts;
    // Load the module:
    let component = reqctx('./' + filename);
    // Then access each key:
    keys.forEach((k) => {
      component = component[k];
    });
    // support `export default`
    if (component.__esModule) {
      component = component.default;
    }
    return component;
  };
}
ReactRailsUJS.getConstructor = fromRequireContext(require.context('components', true));

Reference - https://github.com/reactjs/react-rails/issues/264


text: Q: Unable to use "range" function in MATLAB I need the range of a vector. From the MATLAB documentation, it says "For vectors, range(x) is the range of the elements." However, whenever I try to use it, I get the error "Undefined function 'range' for input arguments of type 'double'." For example, if I use x=[1 2 3 4 5] and then do range(x), I will get this error. Am I crazy or is MATLAB screwing up here? I'm usually pretty good at figuring things out on my own but this one is stumping me.


text:
Q: Zoom/Blowup/Magnify card when clicked to fullscreen (and rotate if in Portrait mode) I have a bunch of card divs inside a flex container.
When clicked the card should scale to be full screen (not fully fill the container, but really full screen, relative to the body/html).
If the devices width is smaller than its height the card should also rotate(90deg).
I tried this:
http://codepen.io/anon/pen/ENyVzm
I think setting the width and height is not gonna work, since it will disrupt the flex layout.
I should instead scale the card to be fullscreen. Scale does not affect the flex layout as it only renders the visual representation and not the flow.
For that to work the card must be rendered (when in non-full screen mode) in the same aspect ratio as the device since we can only scale one factor and not scale width and height individually.
Are my thoughts correct or is there an easier way to accomplish that?


text:
Q: Same SQL Error in a few queries
Possible Duplicate:
Referencing field values between queries

I have 3 similar queries that when run give me the same error
You tried to execute a query that does not include the specified expression 'CompanyName' as part of an aggregate function

I kind of understand the issue but i dont know how to resolve it.. Here are 1 of the 3 queries..
    SELECT qb1.CompanyName, qb1.AssetName, qb1.Year,
    (qb2.MPPOil-SUM(IIf(qb1.DatapointID=2003,
qb1.DatapointValue*1000000,
qb1.DatapointValue))) AS UnallocatedLossesOIL

    FROM PEBaseQuery AS qb1
    INNER JOIN PE_MPPOilRevised AS qb2
    ON qb1.AssetName = qb2.AssetName
    WHERE qb1.DatapointID In (2032,2034,2042,2036,2030,2028);

This is based on the calculation:
Unallocated losses = MPP - (GAS × 1000000) - (Wellwork + Annual shutdown maintenance + Export + Plant + Reservoir losses)
I used similar syntax in another table which runs smoothly :S Heres the code:
SELECT qb1.CompanyName, qb1.AssetName, qb1.Year, (qb1.DatapointValue/qb2.DatapointValue)*1000000 AS TRIPerMillionManHours
FROM HSEBaseQuery AS qb1
INNER JOIN HSEBaseQuery AS qb2
ON qb1.Assetname=qb2.AssetName
WHERE qb2.DatapointID=310005 AND qb1.DatapointID<>qb2.DatapointID;

Why does one work and the other doesnt?? Please help!

A: The first query contains an aggregate function, and anything not part of the calculated value which is being summed must be contained within a group by clause:
SELECT qb1.CompanyName
       , qb1.AssetName
       , qb1.Year
       , (qb2.MPPOil - SUM( IIf( qb1.DatapointID=2003,
                                 qb1.DatapointValue*1000000,
                                 qb1.DatapointValue))) AS UnallocatedLossesOIL
FROM  PEBaseQuery AS qb1
      INNER JOIN PE_MPPOilRevised AS qb2 ON qb1.AssetName = qb2.AssetName
WHERE qb1.DatapointID In (2032,2034,2042,2036,2030,2028)
GROUP BY qb1.CompanyName
         , qb1.AssetName
         , qb1.Year
         , qb2.MPPOil;

As HansUp said, the second query doesn't contain the aggregate function sum(), so no group by is required.


text:
Q: Cross Premise Hybrid Office365 on prem issue We have this Hybrid setup where few pilot users are migrated to office365.
Now the problem started, wherein on-prem users who have access to Calendars for the users who are migrated are getting random password prompts.
Does anyone come across this situation and a solution?

A: Did this issue persist via OWA?
Folders can be accessed cross forest in many scenarios, but they are not fully supported by Microsoft as outlined in Permissions in Exchange hybrid deployments.
I suggest you remove the permission and re-assign it. It is better to create a new profile for test.
The best solution is to move both mailboxes to Exchange Online.


text:
Q: Amount counter works only on first product I have a problem with using javascript with SQL.
It looks like this that I have few items that appears on the screen, they appears from SQL database, and the code looks like shown. Bascially if I have more than one product that is shown on the website, only first one works as it should. Any solutions?

let displayAddCounter = document.querySelector("#add_count_cart");
let displayRemoveCounter = document.querySelector("#remove_count_cart");
let displayCounter = document.querySelector("#amount_count_cart");

var x = 0;

displayAddCounter.addEventListener("click", function(){
    if(x < 10){
    x++;
    displayCounter.innerHTML = x;
  } else {
    alert("If you want to buy more than 10, please contact our support! We will gladly help you :)")
  }
});

displayRemoveCounter.addEventListener("click", function(){
  if(x == 0){
    displayCounter.innerHTML = x;
  } else {
    x--;
    displayCounter.innerHTML = x;
  }

});

let buttonCartAdd = document.getElementById("btn_add_to_cart");
let itemName = document.querySelector(".product_name");

buttonCartAdd.addEventListener("click", function(){
    if(x == 0){
        alert("Please choose amount of items!");
    }
    else if(x > 0){
        alert("You added " + x + itemName.innerHTML + " to the cart!");
    }

});
 <?php
    $sql = "SELECT * FROM products";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        ?>

 <?php echo $row["productName"]?>

            <img class="pic" src="productsImages\<?php echo $row["productID"];?>.jpeg" height="150px" width="120px">

            <?php echo $row["productPrice"];?> SEK

              <button id="remove_count_cart" type="button" class="col_amount btn btn-outline-secondary col-3 col"> - </button>

              0

              <button id="add_count_cart" type="button" class="col_amount btn btn-outline-secondary col-3 col"> + </button>
              <button id="btn_add_to_cart" class="btn btn-lg btn-outline-success col-lg-8 col-md-12 col offset-lg-2"> Add </button>

      <?php
    }
    } else {
        echo "0 results";
    }
    $conn->close();
    ?>

A: You're using the same id for all the HTML elements for each product; you should either use relative routes instead of document.querySelector, or have individual ids for each product


text:
Q: login with apache user I'm following this tutorial step by step,for

Here we clone the repo into a chmodded /var/www/[site_dir] folder.
  Note that we switch to the www-data user before running the git clone
  command. This is an important step because the deploy key we generated
  is owned by the www-data user and it will only work for that user,
  even if you are on the root.

I need to switch to www-data user, but when I try sudo su - www-data ( or sudo su www-data ) I faced with This account is currently not available.
I try ps aux and I see that the www-data user exists, Now I want to know how can I achieve that ? ( login with www-data user)

A: The www-data user is evidently configured with /sbin/nologin (or equivalent) as its shell, and thus the system will not allow you to login to that account. sudo lets you run a command as any user on the system, not just root.  To clone the repo, you just need to sudo -u www-data git clone ... If you really need shell access as that user, sudo -u www-data bash will get you there.
Of course, this all depends on suitable settings in your sudoers file.


text:
Q: emit signal to window I have the following code fragments:
win = new Gtk::Window;
m_canvas = new Goocanvas::Canvas;

sigc::connection conn_t1 = m_canvas->signal_event().connect( sigc::ptr_fun( &AnyEvent));

sigc::connection conn_t2 = win->signal_event().connect( sigc::ptr_fun( &WinHandler));

Now I also register an IdleHandler which generates signals:
Glib::signal_idle().connect( sigc::mem_fun( *this, &IdleSendEvent::Do));

What I want to achieve:
The handler of the canvas should receive an event and should generate a new one and this one should send to the object, so that it will call again the handler of the m_canvas->signal_event().
In other words: Indirectly via the Idle Handler the signal should be send to the sending object itself.
But if I fire to
g_signal_emit_by_name (m_canvas->gobj(), "button-press-event", event, &return_val);

the signal is not received in the canvas itself, but in some child objects there.
Q: How to emmit again to the canvas? Is there something like "get_the_parent_signal_object_handler_father_receiver" or something strange?
I did a lot of gtk_widget_get_parent_window() but all results in runtime errors like:

(go:15430): GLib-GObject-WARNING **: gsignal.c:3484: signal name 'button-press-event' is invalid for instance '0x9afbc48' of type 'GdkX11Window'

I simply have no idea where to find the correct instance which I have to emmit a signal which is then received for the canvas. It looks that the instance for g_signal_emit_by_name fires not to the object itself but all child instances. I can not find a documentation how the signals are processed and how the hierarchy can be walked through. One of the problems is that gtk+ and gtkmm are related but the documentation totally unclear and scattered.

A: You can't emit a signal to a particular object. You can only emit a signal from an object, that will be received by any signal handlers that are connected to that signal of the emitting object. Objects don't receive signals, only signal handlers do. (Although the signal handler may be, for example, a method of an object.)
The first argument of g_signal_emit_by_name() must be the emitting object.
To make a signal handler receive a signal, use g_signal_connect(emitter, signal_name, handler, user_data) or its C++ equivalent, sigc::signal::connect() as you have done in the example code above.


text:
Q: How to extract specific values with point coordinates from Kriging interpolations made in R? By using R version 3.4.2 and the library "geoR", I made kriging interpolations for different variables (bellow I give an example of my process). I also made a matrix with the coordinates for 305 trees with distinct marks (species, DBH, Height) that are within the same space for the interpolations, as seen in the image attached (https://imgur.com/SLQBnZH). I've been looking for ways to extract the nearest value from each variable for each tree and save the corresponding values in a data.frame or matrix, but haven't been successful, and I can't find specific answers to this.
One thing I've been looking at is trying to convert the Kriging result into a Raster (.tif) and proceed from there. But Kriging interpolations are made out of vector data, so is it even posible?
I'd be glad to receive any sort of help, thank you in advance!
P.S. I'm doing this so that I can latter use the data for spatial point patern analysis.
#Kriging####:
PG<-read.csv("PGF.csv", header=T, stringsAsFactors=FALSE)
library("geoR")
x<-(PG$x)
y<-(PG$y)

#Grid
loci<-expand.grid(x=seq(-5, 65, length=100), y=seq(-5, 85, length=100))
names(loci)<-c("x", "y")

mix<-cbind(rep(1,10000), loci$x, loci$y, loci$x*loci$y)

#Model
pH1.mod<-lm(pH1~y*x, data=PG, x=T)
pH1.kg<-cbind(pH1.mod$x[,3], pH1.mod$x[,2], pH1.mod$residuals)
#Transform to geographic data
pH1.geo<-as.geodata(pH1.kg)
#Variogram
pH1.vario<-variog(pH1.geo, max.dist=35)
pH1.vario.mod<-eyefit(pH1.vario)
#Cross validation
pH1.valcruz<-xvalid(pH1.geo, model=pH1.vario.mod)
#Kriging
pH1.krig<-krige.conv(pH1.geo, loc=loci, krige=krige.control(obj.model=pH1.vario.mod[[1]]))
#Predictive model
pH1a.yhat<-mix %*% pH1.mod$coefficients + pH1.krig$predict
#Exchange Kriging prediction values
pH1.krig$predict<-pH1.yhat
#Image
image(pH1.krig2)
contour(pH1.krig2, add=TRUE)

#Tree matrix####:

CoA<-read.csv("CoAr.csv", header=T)
#Data
xa<-(CoA$X)
ya<-(CoA$Y)
points(xa,ya, col=4)

TreeDF<-(cbind.data.frame(xa, ya, CoA$Species, CoA$DBH, CoA$Height, stringsAsFactors = TRUE))
m<-(cbind(xa, ya, 1:305))
as.matrix(m)

I tried to find the value of a point in space (trees [1:305]) through the minimum distance to a predicted value using the following code, (I suggest not running this since it takes too long):
for(i in 1:2){print(c(2:10000)[as.matrix(dist(rbind(m[i,], as.matrix(pH1.krig2$predict))))[i,2:10000]==min(as.matrix(dist(rbind(m[i,],as.matrix(pH1.krig2$predict))))[i,2:10000])])}

A: In the following link aldo_tapia's answer was the approach needed for this problem. Thank you to everyone! https://gis.stackexchange.com/questions/284698/how-to-extract-specific-values-with-point-coordinates-from-kriging-interpolation
The process is as follows:
Use extract() function from raster package:
library(raster)

r <- SpatialPointsDataFrame(loci, data.frame(predict = pH1.krig$predict))
gridded(r) <- T
r <- as(r,'RasterLayer')

pts <- SpatialPointsDataFrame(CoA[,c('X','Y')],CoA)

pH1.arb <-extract(r, pts)

to this I just added the values through cbind to the tree data frame since they are in order.
COA2<-cbind(CoA, pH1val=pH1.arb)

I will repeat the process for each variable.


text:
Q: How to? Downgrade Umbraco 7 to version 6 database We are giving up on Umbraco 7 and want to move back to Umbraco 6. Mostly because of 2 reasons:
1) canvas edit mode is no-where to be found
2) but most importantly, Umbraco Courier does not work with version 7.
We now want to downgrade the v7 database to one of v6. We were hoping that it would be as simple as just pointing v6 to the v7 database (hoping there were no breaking changes).
Does anyone know of a good downgrade strategy for when you do not have a Umbraco 6 version of the db? If it involves some manual work ... that would be ok, as long as we don't have to re-do everything.
Thanks

A: There is no existing downgrade strategy, you are on your own.  Take your backup and continue from there. If you don't have a backup, well then ...  try to recreate the document types manually.  Create a base service where you can serialize all the IPublishedContent nodes and create a service on the v6 to pull them in using your best programming skills.
Can't you find another solution for courier?
Canvas edit is indeed not present.  It can't return in its present state, if you use MVC based rendering.
That being said, I would try to find another solution for courrier in v7 and leave the canvas edit as it is.  Or create your own Javascript based (do I hear surface controller?) canvas edit.  Submit it as a pull request and be the most loved person in the umbraco community.


text:
Q: Using inline assembly from c++ Just to experiment assembly in C++, I tried the following, which is causing the application to crash:
int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
    __asm {
 push 5000
 call Sleep
    }

    ...
}

the assembly part of code is supposed to act like the following line
Sleep(5000);

What am I doing wrong?
edit: I am getting an Access Violation.

A: I just checked the assembly code in VC++ 6.
You have to call the routine like this:
call dword ptr [Sleep]

A: Write the code in straight in C - disassemble it, figure out what the compiler does, then you can write a correct version -

A: It's been a long time since I did this but I recall from the past that sometimes I had to put a single parameter in the EAX register rather than push it on the stack. Or perhaps you need to pop it off again after words if the calling convention requires it.
As Arak says, check that you are matching the compiler calling convention. Masm will force one convention, check your C compiler is enforcing the same.

A: I am not x86 guy, but I think you should check the calling convention used by the compiler. It seems that Sleep cleans after it self, so maybe the compiler is inserting cleaning code also after that?


text:
Q: A regular expression to validate .NET time format Background
I need to validate user input in some fields, where these are defining how to show time in some views.
Requirements
Time format must be expressed in Microsoft .NET way (check this MSDN Library article if you want to learn more about framework's date and time formatting: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx)
Keep in mind I'm looking to validate the format instead of an actual time string.
For example, user may input:

*

*HH:mm

*hh:mm

*ss

*hh:ss

*mm:ss

*... and so on.

In fact, it should validate from the shortest to longest time format available.
Another point is I need to do it in client-side using JavaScript. In other words, any given regular expression by you should work in browsers JavaScript regular expressions' engine.
I'll appreciate any self-taylored one, any link or pasted expression!
Thank you in advance.
NOTE (Update)
I can't use ASP.NET validation engine, or any other. Because of project's requirements, I need to avoid that.

A: As far as I understand, there is no much options - sort of 20, as maximum. Why not just enumerate them all in one big regex without much special symbols? Like
'hh:mm|hh:mm:ss|yyyy-MM-dd hh:mm|<etc>'

you could than make it case sensitive to differentiate between M for month and m for minute, and for hours make it [hH], then make it [:-/] there where you allow for different separators, and lots of other similar things. But the main idea is to simply enumerate all options separated by | with just little amount of regex syntax between | and |.

A: What is your definition of a "valid" format string?  Only once you know that can it be possible to validate a format string.
"K" is also a valid format string
"zz" is also a valid format string
"e" is also a valid format (it would fall into the "The character is copied to the result string unchanged." case)
I'm not even sure what formats would actually cause .NET .ToString() to throw an exception (if that's what you are trying to avoid).


text:
Q: Clicking an item in zoomed in view takes me to another page. But navigating back again does not work I am making an app in C# that uses Semantic Zoom. I have copied the code from an MS sample called BookStore2Universal_10 and I have made some adjustmens to it.
My intention is to click an item in the Zoomed in view. Depending on which item I clicked I want another page to open that downloads and displays a file from the internet.
I've succeeded to navigate to this other page but when I navigate back to the zoomed out view and try to click on another item then the program crashes.
I don't know how remedy this problem. I'm grateful for any help you can provide. Please let me know if you need more details.
This code acts on the item clicked
private void GridView_ItemClick(object sender, ItemClickEventArgs e)
{
    BookSku item = (e.ClickedItem as BookSku);
    ((Frame)Window.Current.Content).Navigate(typeof(Stations));
 }

With the code below I want to get back to the semantic zoom page.
But I don't know how I should navigate back. It seems to me that the
program tries to initialize again and thereby just crashes no matter which
panel name I use instead of the question mark.
private void BackButton_Click(object sender, RoutedEventArgs e)
{
    ((Frame)Window.Current.Content).Navigate(typeof(?));
}

I expect to get back to the zoomed out panel, which I do, and continue    selecting another item. But instead this error message appears:
An unhandled win32 exception occurred in BookStore2Universal_10.exe [4020]


text:
Q: how to play sound with change image repeately in android studio I want to write an app in Android Studio for my son that when he press a button, an image in image view  show and play a sound then after a few second ,automatically  the next image with next sound played, and so on, This process continues when another button is pressed to display another images and sounds.
How do I do this loop replay audio and switch images?
Thank you for your help


text:
Q: Localizing a website Which should you rather use for a medium-sized web site (I don't know the exact number of pages, words, and so on yet):
A) PHP files with static resources:
en.php
    $lang_welcome = 'Welcome';

de.php
    $lang_welcome = 'Willkommen';

B) MySQL table containing translations:
+------+-----------+---------+-------------+
| lang |   path    |  term   | translation |
+------+-----------+---------+-------------+
|  en  | index.php | welcome |   Welcome   |
+------+-----------+---------+-------------+
|  de  | index.php | welcome |  Willkommen |
+------+-----------+---------+-------------+
|  en  |           |  cancel |   Cancel    |
+------+-----------+---------+-------------+
|  de  |           |  cancel |  Abbrechen  |
+------+-----------+---------+-------------+

(The only solution I could think of off the top of my head right now.)
C.) Some other solution.

A: Text translation tables in the database are universally a horrible idea.
For the file translation approach, multiple variations exist. For a very tiny application, a mnemonic id->text approach is ok (typically constants or text arrays). You should however prefer gettext, if that's available and feasible. (There are emulations as native PHP script.)
The data files usually take the form:
 "Welcome at" => "Willkommen bei",

Making a much more readable and maintainable code which doesn't rely on abbreviations or shortened array indexes/constants/variable names:
 print _("Welcome at");

A: I think php files is more standard. Your text is not going to change. DB's aren't really the best choice since it's read-only data.

A: Use Gettext for static content, and your database schema for dynamic content.

A: We use flat php files with key names including the filename (topic/section) and an identifier
$lang['nav_home_link'] = 'Home';

and then a folder structure that is marked by language code
language |
           |
           | - en
           |      | - nav.php
           | - ja
           |      | - nav.php

Of course we use our own tool to manage the files and get translations done for each of the languages we support. Check it out, might be useful to you as well.
myGengo's String


text:
Q: Send information from ImageView extend to MainClass I have an class
TouchImageView extends ImageView

then I have in this class:
setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:
                    //Tell main class action down
                    break;

                case MotionEvent.ACTION_MOVE:
                    //Tell main class action move

                    break;

                case MotionEvent.ACTION_UP:
                   //Tell main class action up
                    break;

            }

        }

in this class I have implemented onTouch function. What I need is this function will do something in my main class that uses this TouchImageView;
private TouchImageView touch_iv = (TouchImageView) findViewById(R.id.imageView1);

A: Easy thing: implement a setParent(...) method
and then call a specific function of you main class:
I assume your main class is called Main.java.
in TouchImageView:
...

Main parent = null;

public void setParent(Main main)
{
    parent = main;
}

...

setOnTouchListener(new OnTouchListener()
{
    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                if (parent != null)
                    parent.ActionDown(TouchImageView.this, event);
                break;

            case MotionEvent.ACTION_MOVE:
                if (parent != null)
                    parent.ActionMove(TouchImageView.this, event);
                break;

            case MotionEvent.ACTION_UP:
                if (parent != null)
                    parent.ActionUp(TouchImageView.this, event);
                break;
        }
    }
}

...

in Main:
...

    private TouchImageView touch_iv = (TouchImageView)findViewById(R.id.imageView1);
    touch_iv.setParent(this);

...

public void ActionDown(TouchImageView view, MotionEvent event)
{
    //handle down event "event" freom view "view"
}

public void ActionMove(TouchImageView view, MotionEvent event)
{
    //handle move event "event" freom view "view"
}

public void ActionUp(TouchImageView view, MotionEvent event)
{
    //handle up event "event" freom view "view"
}

...

that should work.
now you get a callback everytime when the touchimageview sends one.

A: I would use an interface in this case.
Create an interface, let's say
public interface PassData {
    public void doSomethingTouchUp(); //your methods
    public void doSomethingTouchDown();
}

In your TouchImageView get a reference variable, something like
public PassData delagateObj;//make the ref. public, so no getter/setter needed

Next, in your TouchImageView class, replace
//Tell main class action down

with
delagateObj.doSomethingTouchUp(); //similar for your other method

Finally, in your MainClass, or wherever you use TouchImageView, 2 things are necessary: implement PassData and give a value to the delegateObj, then override the methods:
public class MainClass implements PassData {

private TouchImageView touch_iv = (TouchImageView)findViewById(R.id.imageView1);
    touch_iv.delegateObj = this;

    @Override
    public void doSomethingTouchUp(){
        System.out.println("My method implemented!");
    } //your methods
}

A: Have a look at this:
handler.post(new Runnable() {
            @Override
            public void run() {
                progressBar.setProgress(value);
            }
        });

refer to this example http://examples.javacodegeeks.com/android/core/os/handler/android-handler-example/


text:
Q: Split ConfigMap in two with using Kustomize I have the following ConfigMap. I'm trying to split the two datasources out into two separate files, and merge them at "build time" using Kustomize.
But I just can't figure out how to do that?
This is what I have:
apiVersion: v1
kind: ConfigMap
metadata:
  name: grafana-datasources
  namespace: grafana
data:
  datasources.yaml: |-
    apiVersion: 1
    datasources:
      - name: prometheus
        type: prometheus
        access: proxy
        url: http://prometheus:9090
        isDefault: true
        version: 1
      - name: Azure Monitor
        type: grafana-azure-monitor-datasource
        access: proxy
        version: 1

The parts I want to split into separate files (and later merge into a ConfigMap) are:
      - name: prometheus
        type: prometheus
        access: proxy
        url: http://prometheus:9090
        isDefault: true
        version: 1

And:
      - name: Azure Monitor
        type: grafana-azure-monitor-datasource
        access: proxy
        version: 1

A: You have to create two separate files for datasource.
Create directory to put the base configuration:
$ mkdir -p $DEMO_HOME/base

First datasource should look like this:
$ cat <<EOF >$DEMO_HOME/base/datasource1.yaml

  apiVersion: 1
    datasources:
      - name: prometheus
        type: prometheus
        access: proxy
        url: http://prometheus:9090
        isDefault: true
        version: 1

Second datasource should look like this:
$ cat <<EOF >$DEMO_HOME/base/datasource2.yaml

  apiVersion: 1
    datasources:
      - name: Azure Monitor
        type: grafana-azure-monitor-datasource
        access: proxy
        version: 1

    $ cat <<EOF >$DEMO_HOME/base/kustomization.yaml

Then in kustomization file pass info about configmap and add files:
$ cat <<EOF >$DEMO_HOME/base/kustomization.yaml

configMapGenerator:
- name: my-configmap
  files:
  - datasource1.yaml
  - datasource2.yaml
EOF

Finally you can generate the configMaps for development:
$ kustomize build $DEMO_HOME/base

Please take a look: kustomize-operation, kustomize.
EDIT:
You can also split ConfigMap into two separate ConfigMaps which both of them will include one file.
First one with datasources1.yaml and second one with datasources2.yaml.


text:
Q: Make root window transparent and also other things accessible I want to set my root window transparent, I have done this easily, but I can't move anything in the background of my system, for example my terminal, or anything else.
from tkinter import Tk

self.tk = Tk()
self.tk.attributes('-zoomed', True)  # This just maximizes the window
self.tk.wait_visibility() # just to fix self.tk.attributes
self.tk.attributes('-type', 'dock') # disable title and title buttons
self.tk.attributes('-alpha', 0.1) # transparent
self.tk.mainloop() # main loop

The reason I want to do that, is because I want to make an screenshot application, and I want to make some effects that make the system transparent

A: You could make any color completly transparent in your window.
from tkinter import Tk

root = Tk()

root.configure(bg='white')
root.attributes('-transparentcolor', 'white')
root.attributes('-topmost', True)

root.mainloop()

I think code speaks for itself. (OS dependent, works on windows)


text:
Q: Delete 100 lines from vi editor using single command I am using Ubuntu and trying to delete all 100 lines from vi editor but I got interview question of doing this in one command.

A: If all lines in the file are to be deleted, this vi command specifies the range of deletion:
:1,$d

1 denotes the first line and
$ denotes the last line

A: In normal mode, do
100dd

dd deletes the current line.  Prefacing that command with 100 causes it to repeat 100 times.
If there are fewer than 100 lines in the file starting from the current line, depending on the vi implementation, it will either fail to delete any or delete as many as there are. In the case of vim, that depends on whether the cp aka compatible option is on or not.

A: *

*delete 100 lines forward from (including) the current one

*

*repeat dd (delete current line) 100 times:
100dd

*delete from current line to 99 lines forward
d99j

*delete 100 lines backwards from (including) the current one
d99k

*delete lines in a specific range by line number
:1,100d

*delete lines in a range beginning with the current line
:.,.+99d

etc. etc.

A: You want to delete all the lines in a file? Open the file with vi. While at the beginning of the first line -- the default location of the cursor when you just open the file -- press Esc followed by dG.
Just to note, the action d indicates delete, and G indicates the last line of the file. So, while at any line you press dG, it deletes all the line starting from the current line till the last one.
If you know which consecutive lines to delete -- say, from line 101 to 200 -- type in the following key sequences:
Esc:101,200d.

A: No matter where are you are in the file, you can do ggdG
:%d would do better in less key presses.  Well, counting the shift and enter keys, actually two more key presses than the above.
Doing something like 100dd would only delete up to 100 lines from where you are, and that may not delete all lines from the file, depending on your current line position.

A: Esc n dd.
n is the number of lines to delete from and including the current line.
Press "Esc" button, then "n" and then "dd".
To better your understanding


text:
Q: javascript : simple delayed image show I'm trying to write a simple javascript snippet which delays the image loading by a certain number of millisecs below.

Am I approaching this incorrectly?
thanks in advance

A: This is basically an OK approach.
There are some bugs, namely:
document.getElementByID('showImage')style.visibility = 'hidden';

getElementByID should be getElementById
needs a dot after ('showImage')
You are setting the visibility to 'hidden' in order to show it.  Instead, you should start out as hidden, and then make it appear instead of disappear.

A: document.getElementById('showImage').style.visibility = 'hidden';

A: Well, the code is backwards given the stated goal of delaying the appearance of the image. If I just use your code as a basis, then I would have the visibility of the image as hidden, using CSS, and then trigger the display to visible on the timer.
However, having said that... This doesn't delay the loading of the image, it merely delays the display of it. The other way to handle it is to use the timer to load an Image object in Javascript and then insert it into the DOM. This, then, will actually delay the loading of the image for 3 seconds. Something like this:
function showImage()
{
  var myImage = new Image();
  myImage.src = "gwyneth_paltrow_2.jpg";
  document.getElementById("showImage").appendChild(myImage);
}

I'm doing that from memory, so syntax may not be entirely correct.


text:
Q: Meaning of ${} in javascript I need to work on javascript lately. Unfortunately, I am a newbie.
I have come across the following code and don't understand the meaning of ${count == 0}.
function body_onload()
{
    if(${count == 0})
    {
        document.getElementById("dispaly").style.display="none";
    }
    scanImageReportFrom.shopCodes.focus();
}

Thank you.

Finally I found this that can solve my question.

A: It's not you. :-) That's not valid JavaScript (the { triggers a syntax error).
It could perhaps be a token for some pre-processor that replaces it with something before the JavaScript is passed to the JavaScript engine.

A: Just to update this- it is also valid ES2015/ES6
MDN docs - template literals

let a = 4;
let b = 2;
console.log(`a is ${a} and b is ${b}`);

A: In Javascript the ${} is used to insert a variable to a string.
var foo = "cheese";
console.log(`We want to eat ${foo}!`); // This needs the grave accent (`)
// Outputs "We want to eat cheese!"
console.log("We want to eat " + foo + "!");
// Outputs "We want to eat cheese!"

Sometimes the ${} method could be faster than using quotes.

A: I was reading Template Literals, where in the 2nd para of description I found this:
Along with having normal strings, template literals can also contain other parts called placeholders, which are embedded expressions delimited by a dollar sign and curly braces: ${expression}
And further in Interpolation Strings I found:
Without template literals, when you want to combine output from expressions with strings, you'd concatenate them using the "+" (plus sign) (addition operator):
let a = 5;
let b = 10;
console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');
// "Fifteen is 15 and
// not 20."

That can be hard to read – especially when you have multiple expressions.
With template literals, you can avoid the concatenation operator — and improve the readability of your code — by using placeholders of the form "${expression}" to perform substitutions for embedded expressions:
let a = 5;
let b = 10;
console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);
// "Fifteen is 15 and

// not 20."

More details of using "${}" in Template Literals is given in the documentation of the same


text: Q: Using AWS cognito id token instead of access token After login, AWS cognito provides access token and id token. In the backend I was wondering if I can use ID token instead of access token for authorization. Some blogs suggests that ID token should not be passed to the server. However aws jwt verifier provides option to verify ID token signature. I need some values that are provided in ID token like custom fields. Is there any security issue in using ID token ?