text:
Q: add new elements XSLT Have the following input xml which would like to transform to output XML
Input XML:
<O1>
    <A1>
        <C1>
            <CA1/>
        </C1>
    </A1>
    <A2>
        <C1>
            <C2>
                <CA2/>
            </C2>
        </C1>
    </A2>
</O1>

Output XML:
<O1>
    <A1>
        <C1>
            <CA1/>
            <status/>
        </C1>
        <status/>
    </A1>
    <A2>
        <C1>
            <C2>
                <CA2/>
                <status/>
            </C2>
            <status/>
        </C1>
        <status/>
    </A2>
</O1>

Input and Output structure are exactly same with exception of "status"
Have first done a copy of all nodes from input to output using
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

Have difficulty in adding the status field under each of them now.
Have tried defining another template but didnt succeed
Goal is to add the status element under each "A" and "C"

A: Assuming that you want to add a <status /> element after each element that starts with the letter C, simply add the following XSLT-1.0 template next to the identity template:
<xsl:template match="*[starts-with(local-name(),'C')]">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
  <status />
</xsl:template>

The output is as desired.


text:
Q: What is the definition of a presheaf in EGA? In EGA I, Grothendieck says he is not going to bother recalling the definition of a presheaf (on a given topological space $X$ with values in some category $\textbf{K}$).  I was just wondering what that definition was.  I know a presheaf should be a contravariant functor $\mathcal F$ from the category of open sets of $X$ to $\mathbf{K}$, but I was wondering if there is anything else to the definition?  For example, do we require that $\mathcal F(\emptyset)$ be a terminal object in $\mathbf{K}$?  (thereby assuming something about $\mathbf{K}$)

A: Always use the Springer edition of EGA I from 1971, which is more complete than the 1960 original. The definition of a presheaf is in (3.1.1) (Chapter 0). Of course, you can find it also elsewhere.

redpajama_set_name: RedPajamaStackExchange


text:
Q: updating timestamp php mysql database I have a sample database of students in a class with their id(UNIQUE), name,gender, birhdate, marks etc.
What i intend to do is :

*

*if the student has not entered his data, it should insert the data.

*if the student is using for the second time, the time should update.
i used the code below but its not working .

Thanks!!
// open connection
      $con = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
      // select database
      mysql_select_db($db) or die ("Unable to select database!");
      mysql_query("INSERT INTO UserData VALUES ('$id','$name','$gender','$email','$birthday','Marks','NOW()')");
      mysql_close($con);

A: I will strongly suggest that you use the field names in the query:
INSERT INTO UserData (`id`, `name`, `gender`, `email`, `bday`, `marks`, `time`)
VALUES ('$id','$name','$gender','$email','$birthday', $marks, NOW())
ON DUPLICATE KEY UPDATE `time` = NOW()

I am assuming that you have a unique index on id (or it is the primary key). Also, please replace the column names in the query above with the actual column names as per your schema.
For more details, see this.
If you can post your table schema, then I can provide the exact query that you need to use.

A: INSERT != UPDATE
If you want to update an existing record you need to write an UPDATE query. You could use a REPLACE query, but it will overwrite the entire row.

A: I recommend using an ORM like Propel which allows you to write code like this:
$user = UserQuery::create()->findPK($id);
if(!$user) {
  $user = new User();
  $user->setId($id);
}
$user->setName($name);
$user->setGender($gender);
$user->setEmail($email);
$user->save();

A: remove the quotes enclosing NOW()
so instead of 'NOW()' it should be just NOW(), as it is a MYSQL function


text:
Q: Mark the respective row checkbox true when any changes in row made in VF page When I modify any row data then make respective checkbox checked by Jquery in VF Page.
I've tried the below jquery code but it is not working as required.
<apex:page standardController="Assessment__c" sidebar="false" showHeader="false" showChat="true" extensions="Assessment2ctrl">

 <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>

    $(".mc").change(function(e){
         var r = confirm("Are you sure you want to edit these activities?");
        $(this).parent('.cc_row').find('.chkSel').prop('checked',true);
    });
</script>
//I've tried the above script but script is not working

<apex:form >
    <apex:pageBlock id="block1">
        <apex:pageMessages ></apex:pageMessages>
            <apex:pageBlockSection title="Assessments" id="Assessments" columns="1" collapsible="true" >
                <apex:outputPanel id="ButnRef">
                     <apex:actionStatus id="actStatusId" >
                        <apex:facet name="start" >
                            <img src="/img/loading.gif" />
                        </apex:facet>
                     </apex:actionStatus>
                     <apex:commandButton value="Refresh table" style="float:right;" reRender="refTble" status="actStatusId"/>
                    <apex:commandLink action="{!createAssesmnt}" target="_blank"><apex:commandButton value="New Assesment" style="float:right;" reRender="ButnRef"/></apex:commandLink>
                   <apex:commandButton action="{!updateAss}" value="Update Assesment" style="float:right;" reRender="refTble" status="actStatusId" />
                   </apex:outputPanel>

                <apex:outputPanel Id="blockrefresh">
                <apex:pageBlockTable value="{!Asses}" var="a" Id="refTble" styleClass="cc_row">
                     <apex:column headerValue="Select" >
                     <apex:inputCheckbox value="{!a.selected}"  styleClass="chkSel" id="my_chk_bx"/>
                    </apex:column>

                    <apex:column headerValue="Description"  styleclass="mc">
                        <apex:inputField value="{!a.asm.Assessment_Description__c}" style="overflow:hidden"/>
                    </apex:column>

                    <apex:column headerValue="Last Screening" styleclass="mc">
                        <apex:inputField value="{!a.asm.Last_Screening__c}" style="overflow:hidden"/>
                    </apex:column>

                </apex:pageBlockTable>
                    </apex:outputPanel>
            </apex:pageBlockSection>
     </apex:pageBlock>
</apex:form>

A: Replace $(this).parent('.cc_row') with $(this).closest('.cc_row').
Because the structure of apex:pageBlockTable might differ and would be as:
table.mc > tr > td.cc_row

With parent you only access its own tr; whereas element with class name chkSel might exist in different tr. Closest is much cleaner and helpful in this scenario.
Documentation for jQuery closest.


text:
Q: MongoDB shell breaks the syntax for long queries I have a query that takes 3 lines. In the mongo shell, I can type it out so it is on one line, but if I paste it, it goes to 3 lines, and that breaks the syntax.
The same thing happens when I am writing a JavaScript Shell script to execute some mongo queries.
Is there any way around this issue?
Thanks!

A: It sounds like you are using an early version 2 which had some multiline-line issues. I think what you are doing should work. Try upgrading Mongo if you can.


text:
Q: is there a name for a series wich alternates + and - terms? Is there a specific name for a geometric series such as this?
$1-\frac{c (os\theta)}{k}+\frac{c^2}{k^2}-\frac{c^3}{k^3}+\frac{c^4}{k^4}-....$
How can we identify it if positive terms are even or odd?
Also, does its definition change if  the numerator follows a more complex pattern such as:
$1-\frac{c (os\theta)}{k}+\frac{c^2}{k^2}-\frac{c^3+c^2}{k^3}+\frac{c^4+c^3}{k^4}-....$

A: It is series expansion of alternating ( not specifically mentioned as alternating sign but it is implied) geometric series for
$$ \dfrac{1}{1+\dfrac{c}{k}}$$
Alternating series.. this refers to sign changes only regardless of numerator or denominator pattern in $n^{th}$ general term $a_n$. The changes are anyhow taken care of in the definition of $a_n$.

A: It's the Taylor expansion of $\frac 1 {1+ \frac c k}$
$$1-\frac{c}{k}+\frac{c^2}{k^2}-\frac{c^3}{k^3}+\frac{c^4}{k^4}-....=\sum_{n=0}^{\infty}(-1)^n( \frac c k)^n=\sum_{n=0}^{\infty}( \frac {-c} k)^n=\frac 1 {1+ \frac c k}$$

A: An alternating series is such that the values of the successive terms summed change in sign every time.
For example
$$1-1+1-1+1-1+1-1+\cdots,$$
but not
$$1-1-1+1-1-1+1-1+1+\cdots$$
In your first example, the series is alternating when $\dfrac ck>0$.
Your second example is a little harder. The first term is positive, hence the second must be negative, requiring $\dfrac ck>0$. Then the third is fine. The fourth must be negative and
$$\frac{c^3+c^2}{k^3}=\frac{c^2(c+1)}{k^3}>0.$$
Continuing with the next terms (assuming a regular pattern), the constraints are
$$\frac ck>0,\\\frac{c+1}k>0.$$
Hence,
$$(k<0\land c<-1)\lor (k>0\land c>0).$$


text:
Q: How to add label to each geom_density line? I have a column for Devices, and Values and I'm plotting a density curve for each Device.
library (ggplot2)
library(magritrr) # for the pipe operator
df %>% ggplot(aes(x = Value, group = Device)) + geom_density()

Now how do I add a label to each line? (I want the Device name to appear beside each density line on the graph and not in the legend)

A: I created a new summary dataset specifically for the labels. I positioned the labels at the peak of each density plot by picking the max Value for the x-axis and the max density for the y-axis. Hopefully this is helpful.
library(ggplot2)
library(dplyr)

Device = c("dev1","dev2","dev3","dev1","dev2","dev3","dev1","dev2","dev3")
Value = c(10,30,77,5,29,70,12,18,76)
df <- data.frame(Device, Value)

labels <- df %>%
  group_by(Device) %>%
  summarise(xPos = max(Value),
            yPos = max((density(Value))$y))

ggplot() +
  geom_density(data=df, aes(x = Value, group = Device, colour=Device)) +
  geom_label(data=labels, aes(x=xPos, y=yPos, colour=Device, label=Device)) +
  theme_light() +
  theme(legend.position = "None")


text:
Q: Watch OS2 NSTimer problems I'm working on an App where I need to start a timer (using NSTimer) when the Watch is activated. With the Timer I asks some information to the iPhone (about every 1 seconds and maximum for 5 seconds). I'm using this to start the timer
timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(myfunction) userInfo:nil repeats:NO];

In the "myfunction" function, I restart the timer for the next time.
- (void) myfunction
{
   //Here I update a label text
   // [...]

   [timer invalidate];
   timer = nil;

   counter++;
   if(counter<5)
   {
     timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(myfunction) userInfo:nil repeats:NO];
   }
}

My problem is that in the simulator all works fine but in a real watch (Watch-OS2 GM) the timer sometimes doesn't start or sometimes it starts but only for one time and after seems freeze! I see this because i Update a label in the watch at every elapsed period that shows a counter and I'm sure all is initialized in the "will activate" function. I don't understand why. Someone with the same issue?

A: From documentation

Use your interface controller's init and awakeWithContext: methods to
  load any required data, set the values for any interface objects, and
  prepare your interface to be displayed. Do not use the willActivate to
  initialize your interface controller. The willActivate method is
  called shortly before your interface is displayed onscreen, so you
  should use that method only to make last-minute changes. For example,
  you might also use that method to start animations or start other
  tasks that should only happen while your interface is onscreen.

So, what method did you use to instantiate timer?
make sure you use  willActivate method and also use the didDeactivate method to clean up your interface and put it into a quiescent state. For example, use this method to invalidate timers and stop animations.
Hope this helps

A: My problem is solved with Watch OS 2.1. The problem was related to a quickly movement of the wrist: with the latest update of WatchOS all the timer are correctly restore after a quick move and all works fine


text:
Q: Automapper table mapping Table 0..1-* Relationship I have been using Automapper in our projects and just recently ran into an issue not previously encountered.
When the table I am trying to Map has a 0..1 TO * relationship Automapper is not performing the mapping.
I tried examining and altering the CreateMap call and the lambda expression of the .ForMember(..) is not allowing me to access the tableObject's properties.
Can someone point me to the right direction on this?
I checked another table that I hadn't tried using in our model which is also 0..1 TO 1 and noticed the same problem.
Thanks,
Victor
EDIT:
Found the issue... the two classes were coincidentally incorrectly setup. They were public but didn't have any public properties (the public keyword was ommitted for all properties).
I tried to provide an answer but don't have enough reputation for self-answer in < 8hrs.
Thanks,
Victor

A: Found the issue... the two classes were coincidentally incorrectly setup. They were public but didn't have any public properties (the public keyword was ommitted for all properties).
I tried to provide an answer but don't have enough reputation for self-answer in < 8hrs.
Thanks, Victor


text:
Q: How to solve this non-linear system using nleqslv package in R I´m trying to solve this system with package nleqsl, but I´m not succeeding. Can someone help me?
require(nleqslv)

fun<-function(x, E1, V1, E2,V2) {
  y <- rep(NA, length(x))

  y[1]=E1-(x[1]/x[2]+x[4]*x[1]/x[2]^3)
  y[2]=V1-(x[3]/x[2]^2+x[4]*x[1]^2/x[2]^4)
  y[3]=E2-(x[2]/x[1]+x[3]*x[2]/x[1]^3)
  y[4]=V2-(x[4]/x[1]^2+x[3]*x[2]^2/x[1]^4)

  return(y)
}

E1=2.08
V1=0.2
E2=0.505
V2=0.0125
xstart <- c(1, .9, 1,.9)

nleqslv(xstart, fun, E1=E1,V1=V1,E2=E2,V2=V2)

Expected answer: x=c(10,5,1,1)
Answer:
$x
[1] 13384651 12046186 26769295 24092367
$fvec
[1]  0.96888871  0.19999961 -0.39500014  0.01249974
$termcd
[1] 5
$message
[1] "Jacobian is too ill-conditioned (1/condition=4.7e-018) (see allowSingular option)"
$scalex
[1] 1 1 1 1
$nfcnt
[1] 1
$njcnt
[1] 1
$iter
[1] 2

Thanks in advance!


text:
Q: Is this a bug with array_search?  if(array_search('test',array('0'=>'test'))){
    echo 'test';
}

Isn't echoing anything. But:
if(array_search('test',array('0'=>'random', '1'=>'test'))){
    echo 'test';
}

Echoes test?

A: array_search() is returning 0, which (in a non-strict comparison) is false:
var_dump(array_search('test',array('0'=>'test'))); // int(0)
var_dump(array_search('test',array('0'=>'random', '1'=>'test'))); // int(1)

Use !== false (as the docs suggest) instead:
if(array_search('test',array('0'=>'test')) !== false){
    echo '1 ';
}
if(array_search('test',array('0'=>'random', '1'=>'test')) !== false){
    echo '2 ';
}

A: You can use (in_array) function to check if var in array or not
like this:
if(in_array('test',array('0'=>'random', '1'=>'test'))){
echo 'exist';
}


text:
Q: Site not shared message after visual web part click I have created a Visual Web Part. Inside, there is submit button that
on click runs some code.
It works fine with my Site Collection Administrator.
but it doesn't work with my test user. This test user has read permissions only on the site.
When I click on the Visual Web Part button I get:
"Sorry this site is not shared with you"

are there any permission I need to set to enable a user to submit from a visual web part?
Edit:
On click method:
protected void btninvia_Click(object sender, EventArgs e)
    {
            SPSecurity.RunWithElevatedPrivileges(delegate()
        {

        SPSite spsite = SPContext.Current.Site;
        SPWeb spweb = spsite.RootWeb;

            ... code that works ....

                SPListItem item = addMissione(user.User); // this method causes the authorization problem

           ... not executed code

        });

    }

addMission method:
private SPListItem  addMissione(SPUser spuser)
{
            SPListItem item =null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                Logger.WriteLog(Logger.Category.Information, "addMissione", "spuser" + spuser.LoginName);

          SPSite spsite = SPContext.Current.Site;
          SPWeb spweb = spsite.RootWeb;
          SPList splist = spweb.Lists["Missions"];

          item = splist.AddItem();

          item["Field1"] = spuser;

          item["Field2"] = Field2.Text;
          item["Start Date"] = startdate.SelectedDate;

     ....
          item.Update();
          Logger.WriteLog(Logger.Category.Information, "addMission", "item update"); // this code is not run

        ...

             Logger.WriteLog(Logger.Category.Information, "addMissione", "fine addMissione");

           });

            return item;
}

A: It all depends on the code you run on the button click. Can you please share it with us?
It's more than probably something done by your code, and your user does not have permissions to perform the action. e.g. you create a list item by code, while your "read-only" user obviously cannot create items...
If you really need to take some actions on behalf of read-only users, and if you can be sure from your code the operation is allowed as per the business rules, you can use an "elevation", i.e. run your code as the "system account". That way, all operations are allowed. Use this carrefully...
[EDIT]
Now that I've seen your code, the mistake is obvious. You need to open new SPSite and SPWeb objects inside the elevated section. See for instance my answer https://sharepoint.stackexchange.com/a/171392/35604 ("However, as a side note...").
i.e., try Something like this:
  SPSecurity.RunWithElevatedPrivileges(delegate()
  {
      Logger.WriteLog(Logger.Category.Information, "addMissione", "spuser" + spuser.LoginName);

      using(SPSite spsite = new SPSite(SPContext.Current.Site.ID))
      {
           using(SPWeb spweb = spsite.RootWeb))
           {
                spweb.AllowUnsafeUpdates = true;
                SPList splist = spweb.Lists["Missions"];

                SPListItem item = splist.AddItem();

                item["Field1"] = spuser;

                item["Field2"] = Field2.Text;
                item["Start Date"] = startdate.SelectedDate;
 ....
                item.Update();
 ....
           }
      }
  }

Note the spweb.AllowUnsafeUpdates = true;: it is important here as we're dealing with an SPWeb not unlocked by the HTTP context (see https://sharepoint.stackexchange.com/a/149719/35604 on this matter).

A: You are not elevating in a correct way, you need to create new objects for SPSite and SPWeb.
But since you use the root web, as you do, you do not need to explicitly create a new object for that, so you can do the below
SPSecurity.RunWithElevatedPrivileges(delegate()
{
     using(SPSite spsite = new SPSite(SPContext.Current.Site.Url))
     {
         SPWeb spweb = spsite.RootWeb;
     }
}


text:
Q: Copy files from a zip folder to another folder in nant I want to copy the files from the zip folder to another folder.
I am doing this , but it doesn't works
    <copy todir="Lib">
<fileset basedir="Output/RCxSL.Client.zip/ServiceClientDlls">
    <include name="*.dll" />
</fileset>
    </copy>

How to achieve this ? the folder is  zipped.

A: A ZIP folder is not a folder, it is a ZIP file, even though the operating system (through your files explorer) may make it look like a folder. Instead of using <fileset> and <copy>, use the unzip task of NAnt.
<unzip zipfile="Output/RCxSL.Client.zip" todir="Lib" />


text:
Q: How to assign @Id and @OneToMany annotations to same variable in Hibernate? I would like to add the @Id and @OneToMany Annotations to the same variable, but i am getting the bleow exception:
Caused by: java.lang.NullPointerException
    at org.hibernate.cfg.Ejb3JoinColumn.checkReferencedColumnsType(Ejb3JoinColumn.java:537)
    at org.hibernate.cfg.BinderHelper.createSyntheticPropertyReference(BinderHelper.java:125)
    at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:114)
    at org.hibernate.cfg.Configuration.processEndOfQueue(Configuration.java:1580)
    at org.hibernate.cfg.Configuration.processFkSecondPassInOrder(Configuration.java:1503)
... 40 more
Here is my Entity Class :
@Entity

@Table(name="TABLE_A", schema="Test")
public class TableA implements Serializable {
@Id
@PrimaryKeyJoinColumn
@OneToMany(mappedBy="tableB.prcCatIdNo")
private List<TableB> ident;

@Column(name="FOP_DAYS")
private BigDecimal fopDays;
...

}
Can someone please help


text:
Q: Why Does String Not Equal What Is Stored? This is a simple, odd question...
if(tableViewNum == @"One") {
        if ([drinkArray objectAtIndex:0] == currentDate) {
            [updatedArray addObject:drinkArray];
            NSLog(@"MADE THE ELSE1");
        }
        NSLog(@"MADE THE ELSE2");
    }
    else if (tableViewNum == @"Two") {
        if ([[drinkArray objectAtIndex:0] isEqualToString:yesterdayDate])
            [updatedArray addObject:drinkArray];
    } else {
        NSLog(@"MADE THE ELSE %@",tableViewNum);
        [updatedArray addObject:drinkArray];
    }

In the very first if statement I ask if tableViewNum == @"One"
But I don't go in that section of the if statement even though tableViewNum actually does equal @"One"
As you can see the very last NSLog all ways comes out as
MADE THE ELSE One

But if tableViewNum really equaled One it would have gone through the if statement not the else statement code...?????

A: You can't compare strings with the == operator. Use isEqualToString instead:
if([tableViewNum isEqualToString:@"One"]) {
    // etc.

… and the same for the rest of the conditions. You're already doing it right in the second block.

A: To be more specific, you shouldn't compare ANY objects using ==. This compares just the pointers. Use [obj isEqual: otherObj] or with NSStrings isEqualToString: as described above.


text:
Q: AEADBadTagException: Tag mismatch I encrypt data in android phone using AES GCM mode and sent it to java application in windows
The cipher text is created and received successfully
at decryption process an exception appeared(Tag miss match)
I tried to remove associated data update
I tried to set the provider to SunJCE
The code works great between  java desktop applications but the error appears when use encryption decryption process between android and java
I use openjdk1.8
public static byte[] gcmMode(int gcmCipherMode, byte[] aadHeader,char[] password, byte[] inputBytes) {
    byte[] outputBytes = new byte[0];
    byte[] salt;
    byte[] iv;
    byte[] res;
    SecretKeySpec ks;
    try {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
        switch (gcmCipherMode) {
            case Cipher.ENCRYPT_MODE:
                salt = new byte[16]; random.nextBytes(salt);
                iv = new byte[12]; random.nextBytes(iv);
                res = salt(password, salt);
                ks = new SecretKeySpec(res, "AES");
                c.init(Cipher.ENCRYPT_MODE, ks, new GCMParameterSpec(128, iv));
                if (aadHeader != null) {
                    c.updateAAD(aadHeader);
                }
                outputBytes = arrayByteConcatenate(salt, iv);
                outputBytes = arrayByteConcatenate(outputBytes, c.doFinal(inputBytes));
                break;
            case Cipher.DECRYPT_MODE:
                if (inputBytes.length > 44) {
                    salt = arrayByteSplit(inputBytes, 0, 16);
                    iv = arrayByteSplit(inputBytes, 16, 28);
                    res = salt(password, salt);
                    ks = new SecretKeySpec(res, "AES");
                    c.init(Cipher.DECRYPT_MODE, ks, new GCMParameterSpec(128, iv));
                    if (aadHeader != null) {
                        c.updateAAD(aadHeader);
                    }
                    // Return our Decrypted String
                    outputBytes = c.doFinal(arrayByteSplit(inputBytes, 28, inputBytes.length));
                }else{
                    System.out.println("Wrong cipher");
                }
                break;

            default:
                System.out.println("UnKnown");
                break;
        }

    } catch (NoSuchAlgorithmException | NoSuchPaddingException
            | InvalidKeyException | IllegalBlockSizeException
            | BadPaddingException | InvalidParameterException
            | InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    }
    return outputBytes;
}

static byte[] salt (char[] password, byte[] salt) {
    SecretKeyFactory skf = null;
    byte[] res = new byte[0];
    try {
        skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        PBEKeySpec spec = new PBEKeySpec(password, salt, 100000, 128);
        SecretKey key = skf.generateSecret(spec);
        res = key.getEncoded();
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        e.printStackTrace();
    }
    return res;
}

Error
javax.crypto.AEADBadTagException: Tag mismatch!
    at com.sun.crypto.provider.GaloisCounterMode.decryptFinal(GaloisCounterMode.java:578)
    at com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:1116)
    at com.sun.crypto.provider.CipherCore.fillOutputBuffer(CipherCore.java:1053)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:853)
    at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
    at javax.crypto.Cipher.doFinal(Cipher.java:2164)
    at algorithm.encryption.AESencryption.gcmMode(AESencryption.java:91)
    at ServerWorker.handleAuthentication(ServerWorker.java:97)
    at ServerWorker.startMessageReader(ServerWorker.java:67)
    at ServerWorker.handleClientSocket(ServerWorker.java:44)
    at ServerWorker.run(ServerWorker.java:36)


text:
Q: Change Label depending on boolean JavaFX I am super new to JavaFX and for my checkers game I want to display who's turn it is above my board. I have read through multiple very similar questions, but it doesn't seem to get me where I want to go. I hope you can help me!
I have a FXML file with the following code:
<HBox fx:id="topBox" alignment="TOP_CENTER" prefHeight="45.0" prefWidth="200.0" spacing="10.0" BorderPane.alignment="CENTER" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.SampleController">
     <children>
        <Label fx:id="labelTurn" text="test" />
        <Button fx:id="buttonResign" alignment="CENTER" mnemonicParsing="false" onAction="#doResign" prefHeight="25.0" prefWidth="80.0" text="Resign" />
     </children>
  </HBox>

In my main:
public class Main extends Application {

    Checkers content = new Checkers();
    BorderPane border = new BorderPane();

    @Override
    public void start(Stage primaryStage) throws Exception {
        try {
            border.setTop(FXMLLoader.load(getClass().getResource("Sample.fxml")));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        border.setCenter(createContent());
        Scene scene = new Scene(border);
        primaryStage.setTitle("Checkers from main");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

My controller:
public class SampleController {
    @FXML
    private Label labelTurn;

    @FXML
    private HBox topBox;

    @FXML
    private Button buttonResign;

    private Checkers content = new Checkers();

    @FXML
    void doResign(ActionEvent event) {
        content.resign();
        // System.exit(0); //TODO eine tatsächliche Methode eingeben!!

    }

    public void setLabelTurn(Label labelTurn) {
        this.labelTurn = labelTurn;

        String setLabelText() {
        String s = " ";
        if (content.getWhiteTurnPropValue()) {
            labelTurn.setText("White, it is your turn.");
            s = "White, it is your turn.";
            return s;
        } else {
            labelTurn.setText("Black, it is your turn.");
            s = "Black, it is your turn.";
            return s;
        }
    }
    @FXML
    void initialize() {
        assert buttonResign != null : "fx:id=\"buttonResign\" was not injected: check your FXML file 'Sample.fxml'.";
        assert topBox != null : "fx:id=\"topBox\" was not injected: check your FXML file 'Sample.fxml'.";
        assert labelTurn != null : "fx:id=\"labelTurn\" was not injected: check your FXML file 'Sample.fxml'.";
        labelTurn.textProperty().setValue(setLabelText());
    }
}

My game data has a BooleanProperty to show who's turn it is. It gets changed after every successful move.
BooleanProperty whiteTurnProp = new SimpleBooleanProperty(true);

public BooleanProperty getWhiteTurnProp() {
    return whiteTurnProp;
}

public void setWhiteTurnPropValue(Boolean whiteTurn) {
    this.whiteTurnProp.setValue(whiteTurn);
}

public boolean getWhiteTurnPropValue() {
    return this.whiteTurnProp.getValue();
}

As far as I have understood, I need to bind the Label to the value, which I have done in the initialize method. But when I play and the value in my game class changed, the label stays the same. How do I update the label? I think I need to add a change listener to something, but I dont know how to do that and more specifically WHERE.
Thank you so much for your help! I shortened my code a bit and hope it is still not too long.
Best,
Lisa

A: In initialize: labelTurn.textProperty().setValue(setLabelText()); is not a binding, it is a simple set on the property. A really strange one as setLabelText() sets the text of the Label and also return the string which was set, which value is used again to the text of the Label.
You could create a real binding instead:
labelTurn.textProperty().bind(Bindings.createStringBinding(() -> {
    String s = " ";
    if (content.getWhiteTurnProp().get())
        s = "White, it is your turn.";
     else
        s = "Black, it is your turn.";

    return s;
}, content.getWhiteTurnProp()));


text:
Q: Why does specifying my shell change the EUID of root? If I specify my shell as /bin/bash in a script, then the EUID of root is 0.  If I don't, and the script runs in my default shell (also /bin/bash), the EUID of root is an empty string!  I'm new to scripting and thought there was no difference as long as bash ran the show.
The code I'm running checks if the program is run by root, and restarts the program as sudo if not.
#!/bin/bash
echo euid = $EUID
echo shell = $SHELL

if [ $EUID -ne 0 ]; then
    sudo "$0"
    exit $?
fi

When run, I see
euid = 1000
shell = /bin/bash
euid = 0
shell = /bin/bash

But if I remove the she-bang line, I get
euid = 1000
shell = /bin/bash
euid =
shell = /bin/bash
./test.sh: 4: [: -ne: unexpected operator

The script runs in the same shell all four times, so why does it act differently when sudo calls it without specifying /bin/bash?
I'm running Ubuntu 14.04 if that matters.
Thanks in advance!

A: By removing the shebang line, you are calling Ubuntu default shell, which is Dash, not Bash.
Dash does not define $EUID, leading to an empty assignment. In fact, $EUID is one of many enhancements brought by Bash over the POSIX standard. Instead, Dash is meant to be as small, fast and lightweight as possible, and implements only the minimal set of features required by the standard.
You assert that it runs in the same shell all four times, but in fact it doesn't. The environment variable $SHELL does not refer to the shell running the current process; it refers to your account's login shell, defined in /etc/passwd or equivalent.


text:
Q: WP plugins for building a database? I am a beginner at WP, I need some ideas on how to proceed with the following problem:
I need to create a tool that will build a database for a client's WordPress site.
The database surrounds authors of old literary texts and the information related to them(name, bio, education, etc.). The data relating to each author is quite extensive.
I need to store these data entries in a database on the website, these entries should be able to be queried and displayed for the user searching through the database.
I have thought of using a form plugin for this, however, i am not sure if that i the right approach.

A: WordPress natively stores content in a database. It sounds like you're wanting to store info in that database, and retrieve and present it - rather than actually create a separate database.
If that's the case, creating custom post types are likely the way to go. An author can be a custom post type, which would allow visitors to browse or search through authors. Their name would simply be the post title. You can add custom taxonomies where appropriate - for example, a genre taxonomy might make sense, so you can easily query all authors who write Science Fiction, for example. You can also add custom postmeta, such as education and bio, if you want to be able to search/filter through that information. If you go the custom taxonomy and/or postmeta route, you'll likely end up wanting to create a child theme, so that you can set up an Archive for the authors where visitors can sort and filter by different criteria.
Or, you could keep it simpler, and just place each author's information inside the post_content itself. WP will natively search through post titles and post content when returning search results, and of course as visitors view each single author URL, they would be able to view all that data without any customization of the theme or content output.


text:
Q: Django Calculate Mean Of 2 Fields Inside Multiple Objects I'm trying to do a very simple math problem but I don't know how to convert it into python. Basically I need to calculate the mean entry price for a trade based on multiple "buy" entries. To do that all one needs to do is calculate
∑ (entry.amount * entry.price) / ∑ (entry.amount)

This should be the variable "total_entry_price2" in the end.

*

*Where am I going wrong with the calculation? How Can I add all the ∑'s together?

*Is this the best way to do it?

models.py
class Trade(models.Model):
    ...

class Entry(models.Model):
    ...
    trade = models.ForeignKey(Trade, on_delete=models.CASCADE)
    amount = models.FloatField()
    price = models.FloatField()
    entry_type = models.CharField(max_length=3, choices=ENTRY_TYPE_CHOICES, default=BUY)

views.py
@login_required
def trade_detail_view(request, pk):
    logger.info('trade detail view')
    if request.method == 'GET':
        trade = get_object_or_404(Trade, pk=pk)
        entries = Entry.objects.filter(trade=trade)
        entries_buy = Entry.objects.filter(trade=trade, entry_type="buy")
        patterns = Pattern.objects.filter(trade=trade)

        for entry in entries_buy:
            total_entry_price = Sum(entry.amount * entry.price)
            total_entry_price2 = total_entry_price / entries_buy.aggregate(Sum('amount'))
            print(total_entry_price2)

        context = {
            'trade': trade,
            'entries': entries,
            'patterns': patterns,
            'max_amount': entries_buy.aggregate(Sum('amount')),
            'total_fees': entries.aggregate(Sum('fee')),
            'entry_price': entries_buy.aggregate(Avg('price'))
        }

Current Terminal print:
Sum(Value(60.0)) / Value({'amount__sum': 40.0})
Sum(Value(10.0)) / Value({'amount__sum': 40.0})

Example data

The correct answer should be $1.75
(30 * 2 + 10 * 1) / 40 = 1.75

Final Solution (added upon from Oleg Russkin's Answer)
The revisions I did are as follows:
total_entry_cost = entries_buy.annotate(
    s=F('amount') * F('price')
).aggregate(
    total_entry_cost=ExpressionWrapper(
        Sum(
            Cast('s', output_field=models.FloatField())
        ) / Sum('amount'),
        output_field=models.FloatField()
    )
)['total_entry_cost']
print(total_entry_cost)

A: Example query to calculate required value.
Cast() to float may be avoided if the result of Sum is float, not an integer.
from django.db import models
from django.db.models import ExpressionWrapper, F, Sum
from django.db.models.functions import Cast

total_entry_price2 = Entry.objects.annotate(
    s=F('amount')+F('price')
).aggregate(
    price2=ExpressionWrapper(
        Sum(
            Cast('s',output_field=models.FloatField())
        ) / Sum('amount'),
        output_field=models.FloatField()
    )
)['price2']

# Actual result of the query is dictioanry
# so we get the key
# {'price2': 0.59633706227207}

Updated Answer By OP
This answer almost got us all the way. It was my fault not to be more clear on the exact answer I was looking for. I updated my question near the end to reflect it.
The revisions I did are as follows:
total_entry_cost = entries_buy.annotate(
    s=F('amount') * F('price')
).aggregate(
    total_entry_cost=ExpressionWrapper(
        Sum(
            Cast('s', output_field=models.FloatField())
        ) / Sum('amount'),
        output_field=models.FloatField()
    )
)['total_entry_cost']
print(total_entry_cost)


text:
Q: Using Asterisk to Click2Dial Via Command Line I'd like to make an in house click2dial application the problem is I'm not sure how to get Asterisk via the command line to dial myself and then dial an extension like google voice does now or how grand central did.
I know about the Dial() command in Asterisk and the T option for transfer. Anyone have any insight on this?
thanks.

A: Let's assume you have something like this in your extensions.conf:

[outbound]
exten => _NXXNXXXXXX,1,Dial(SIP/${EXTEN}@provider,,T)

Then have a look at the originate CLI command:
*CLI> help originate

And then you can do something like:
$ asterisk -rx "originate SIP/1000 extension 4105556666@outbound"

Where SIP/1000 is the local user and 4105556666 is the number you want that SIP phone connected with.

A: Maybe you can use this on the Asterisk box and write a client for that...


text:
Q: Erro ordenar lista? ViewBag.ListaEspecialidades = Especialidade.ListarEspecialidades().Sort();

Da um erro

"cannot implicitly convert type void to dynamic".

A: Acredito que isso resolva:
Especialidade.ListarEspecialidades().Sort();
ViewBag.ListaEspecialidades = Especialidade.ListarEspecialidades();

O Sort() é um metodo void não tem retorno, por isso do erro, tem a funcionalidade de ordenar a lista atual.

A: Você pode utilizar o OrderBy(x => x.NomeDoCampo) ou OrderByDescending(x => x.NomeDoCampo).
Exemplo:
ViewBag.ListaEspecialidades = Especialidade.ListarEspecialidades().OrderBy(x => x.NomeDoCampo);


text:
Q: Square root of $\sqrt{700} + \sqrt{280}$ Is there a way to express $\sqrt{\sqrt{700}+\sqrt{280}}$ under only one radical sign like what is done to the example below?
$$\sqrt{9+4\sqrt5}=\sqrt{4+5+2\sqrt{20}}=\sqrt{(\sqrt4+\sqrt5)^2}=2+\sqrt5$$
** I have done not much of a generalization but
when I try to express $\sqrt{A+B}$ in the form of $\,R\,(a+\sqrt{b}\,)$ where $A$>$B$, $R$ is an adjustable ratio, and with $A$, $B$, $a$ and $b$ not being necessarily rational or irrational, I have arrived at this : $$a=\sqrt{b}\;\left(k\,\pm\sqrt{k^2-1}\,\right)$$  where $k = A/B$
In this equation I can plug in an arbitrary $b$ and find $a$ and after that make up a suitable value of $R$ to equal things up (I wonder if there exists such phrasal verb? ).
The problem with this is that, in  $\sqrt{\sqrt{700}+\sqrt{280}}$ where $k=\sqrt{2.5}$, the R seems to always become another radicalsign-inside-radicalsign irrational number with a $k$ value of exactly $\sqrt{2.5}$ again regardless of what the value of $a$ and $b$ is.
Is it that there isn't really a methodology to do it or that there is indeed a way and I have been missing things out?  Thanks in advance.

A: *

*Let me resolve your first problem in a general way.

Suppose there are two numbers $x$ and $y$ such that
$$ \sqrt{9 + 4\sqrt5} = \sqrt{(x + y\sqrt5)^2} = x + y\sqrt5\quad (1)$$
Square both sides:
$$ 9 + 4\sqrt5 = x^2 + 5y^2 + 2xy\sqrt5 $$
This equation can be satisfied by the following choice:
$$  \begin{align} x^2 + 5y^2 &= 9 \quad (2) \\
2xy &= 4 \quad (3)\end{align} $$
From $(3) \Rightarrow y = 2/x$, plug into $(2)$:
$$ x^4 -9x^2 + 20 = (x^2 - 4)(x^2 - 5) = 0 $$
$$ x^2 = 4, 5 \Rightarrow x = 2,\sqrt5$$
where we have rejected the negative values of x as required by $(1)$.
Therefore, there are two solutions:
$$(x,y) = (2,1), (\sqrt5, \frac{2}{\sqrt5}). \quad (4)$$
Plugging both solutions to $(1)$, we obtain the same result:
$$ \sqrt{9 + 4\sqrt5} = 2 + \sqrt5 $$

*Now consider the problem $A = \sqrt{\sqrt{700} + \sqrt{280}}$.

We will use the same method above, noting the following irreducible radical form:
$$\begin{align} \sqrt{700} &= 10\sqrt7, \\
 \sqrt{280} &= 2\sqrt{2\cdot5\cdot7} = 2\sqrt{10}\sqrt7
\end{align}
$$
Thus,
$$ A = \sqrt{ \sqrt7(10 + 2 \sqrt{10}) } = \sqrt[4]7\sqrt{10 + 2 \sqrt{10}} . \quad (5)$$
Suppose there are two numbers $m$ and $n$ that satisfy:
$$ \sqrt{ 10 + 2 \sqrt{10} } = \sqrt{ (m + n\sqrt{10})^2 } = m + n\sqrt{10}. \quad(6) $$
Squaring both sides:
$$ m^2 + 10 n^2 = 10, \quad (7)$$
$$ 2mn = 2 \Rightarrow n = 1/m. \quad (8)$$
It follows:
$$ \begin{align} (6) \Rightarrow m^4 -10m^2 + 10 &= 0 \\
 (m^2 -5)^2 -15 &= 0\\
m^2 &= 5 \pm \sqrt{15}
\end{align} $$
Therefore, the solutions are as follows, after rejecting negative solutions as required by (6):
$$ \begin{align}
  m &= \sqrt{5 \pm \sqrt{15}}, \\
 n &= \frac{1}{\sqrt{5 \pm \sqrt{15}}} \\
  &=\frac{\sqrt{5 \pm \sqrt{15}}}{5 \pm \sqrt{15}} \\
  &= \frac{(5\mp\sqrt{15}) \sqrt{5 \pm \sqrt{15}} }{10}.
\end{align}$$
When plugging the values of $m$ and $n$ to (6), we can see that the right hand side of (6) cannot be simplified to $a + b\sqrt{10}$ where $a$ and $b$ are rational numbers.
Thus, we can conclude that it is impossible to write
$$ A = \sqrt{ \sqrt7(10 + 2 \sqrt{10}) } = \sqrt[4]7 (a + b \sqrt{10}), $$
where $a$ and $b$ are rational numbers.
As the final note, let us remark that (6) can also be recast as
$$ \sqrt{ 10 + 2 \sqrt{10} } = \sqrt{ (x\sqrt2 + y\sqrt5)^2 } = x\sqrt2 + y\sqrt5.$$
Using the same procedure to solve for $x$ and $y$, we can prove that this form does not lead to a solution where $x$ and $y$ are rational numbers.


text:
Q: Finding the maximum value of $\displaystyle \frac{x^n-a\sin x}{x^{n+1}}\ (x\gt 0)$ For $a\ge 1\in\mathbb R,n\ge 1\in\mathbb N$, let us define $f(x)$ as $$f(x)=\frac{x^n-a\sin x}{x^{n+1}}\ \ \ (x\gt 0).$$
Also, let $M(a,n)$ be the maximum value of $f(x).$
We may be able to know the approximate value of $M(a,n)$ using some tools, but...

Question 1 : Can we represent $M(a,n)$ by $a,n$?

Since Question 1 seems very difficult for me, I've been trying to find the explicit value of $M(a,n)$ for smaller $(a,n)$. However, even proving that $M(1,1)=1/\pi$ for $x=\pi$ was not very easy for me. So...

Question 2 : For what $(a,n)\not=(1,1)$ can we find the explicit value of $M(a,n)$?

Edit : I noticed that $a\ge 1\in\mathbb R$ is needed for the existence of $M(a,1)$.

A: I don't think there is a analytical solution. However we can take derivative and analyse it's root. So
$$
f^\prime(x)=-\frac{1}{x^2}-\frac{a\cos(x)}{x^{n+1}}+\frac{a\sin(x)(n+1)}{x^{n+2}}
$$
Rearranging the terms and making $f^\prime(x)=0$ we can get the following equation
for the analysis:
$$
a\sqrt{1+\frac{(n+1)^2}{x^2}} \sin(x-\arctan(\frac{(n+1)}{x}))=x^{n-1}
$$
At least we can confirm that you are correct for the case $a=1,n=1$ because then
$$
(1+4/\pi^2)\sin(\pi-\arctan(\frac{2}{\pi})=(1+4/\pi^2)\cos(\arctan(\frac{2}{\pi}))=\frac{1+4/\pi^2}{1+4/\pi^2}=1
$$
Sorry that I cannot help you more.


text:
Q: Why my assignment operator does not work? (no known conversion for argument 1) I have two classes:

*

*buffer, which allocates char buffer

*file, which manages file io
My file.read() functions wants to return a buffer object, but i cannot assign it to a variable (see main() at the end of the code is where the error is))
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

class buffer {
public:
    buffer(int _size) : buf((char *)malloc(_size)), len(_size)
    {
    }

    char *ptr()
    {
        return buf;
    }

    int size()
    {
        return len;
    }

    ~buffer()
    {
        free(buf);
    }

    buffer() : buf(0), len(0)
    {
    }

    buffer(buffer& rhs)
    {
        buf = (char *)malloc(rhs.len);
        memcpy(buf, rhs.buf, rhs.len);
    }

    operator=(buffer& rhs)
    {
        free(buf);
        buf = (char *)malloc(rhs.len);
        memcpy(buf, rhs.buf, rhs.len);
    }
private:
    char *buf;
    int len;
};

class file {
public:
    file(const char *filename, const char *mode) : f(fopen(filename, mode))
    {
    }

    int size()
    {
        int ret;
        int pos = ftell(f);
        fseek(f, 0, SEEK_END);
        ret = ftell(f);
        fseek(f, 0, pos);
        return ret;
    }

    buffer read(int n)
    {
        buffer buf(n);
        fread(buf.ptr(), 1, n, f);
        return buf;
    }

    void write(buffer& buf)
    {
        fwrite(buf.ptr(), 1, buf.size(), f);
    }

    ~file()
    {
        fclose(f);
    }
private:
    FILE *f;
};

int main(int argc, char *argv[])
{
    if (argc == 3) {
        file infile(argv[1], "rb");
        file outile(argv[2], "wb");
        buffer buf = infile.read(infile.size());
    }
}

Please ignore that the code is not generic (no templates and poor error handling) this is just a demo I am learning c++.
Update
Still not working:
buffer& operator=(const buffer& rhs)
{
    free(buf);
    buf = (char *)malloc(rhs.len);
    memcpy(buf, rhs.buf, rhs.len);
}

file infile(argv[1], "rb");
file outile(argv[2], "wb");
buffer buf = infile.read(infile.size()); // error


text:
Q: im getting a geofencing reuest error using HERE api {"faultCode":"s73552fd8-9c05-4bbd-a929-359aadde38c6","responseCode":"400","message":"The request is missing the app_id and app_code parameters. They must both be passed as query parameters. If you do not have app_id and app_code, please obtain them through your customer representative or at http://developer.here.com/myapps."}

I use just the API key. I don't have an app_id and app_code

A: check the new HERE domain for the apikey from here and try-
https://developer.here.com/documentation/geofencing/dev_guide/topics/request-constructing.html
If you are using api key than for geofencing api request basedUrl should be https://fleet.ls.hereapi.com.

A:     <script src="https://js.api.here.com/v3/3.1/mapsjs-core-legacy.js" type="text/javascript" charset="utf-8"></script>
    <script src="https://js.api.here.com/v3/3.1/mapsjs-service-legacy.js" type="text/javascript"
        charset="utf-8"></script>

Add the core legacy libraries.


text:
Q: Web Server with PKCS11 support for server certificates? I have a PKCS#11-compatible smart card with either a private key, or a combination of a certificate and a private key on it (I can have both).
I want to present the certificate from the smart card to visitors, or use a regular certificate file on disk but do decryption of traffic on the smart card using the private key that's only stored there.
This seems like something that should be possible, but existing support for that appears to be non-existent (everyone is focusing on client certificates, which is not what I want).
Windows + IIS seems to not support the option (certificates from file only).
Linux + Apache + mod_ssl seems to come closest, but fails to recognize my pkcs11 engine out of the box. When applying the following patch (https://issues.apache.org/bugzilla/show_bug.cgi?id=52473) the server doesn't start up anymore (seemingly due to a double-locking bug).
No other web server seems to support this at all, at least, none that I can find. Am I wrong? Is there a web server that can do this? Does someone have a better mod_ssl patch? Am I silly to want this in the first place? Please help.

A: I've not used it myself, but nginx has implemented support for OpenSSL engines in the last few months.  It doesn't look like Apache has moved forward with the bug report referenced, sadly.


text:
Q: Symmetry of the Polyakov action? Let us look at the Polyakov action for a string moving in a spacetime with metric $g_{\mu \nu}(X)$:$$S_P = -{1\over{4\pi \alpha'}} \int d^2 \sigma \sqrt{-\gamma} \gamma^{ab} \partial_a X^\mu \partial_b X^\nu g_{\mu\nu}(X) \tag{1}$$ and suppose there exists a Killing vector $k_\mu$ in spacetime satisfying Killing's equation
$$\nabla_\mu k_\nu + \nabla_\nu k_\mu = 0.\tag{2}$$
Does this lead to a symmetry of the Polyakov action?

A: The answer is: Yes, the Polyakov action is invariant under a Killing symmetry in the target space.

*

*Hints: Perform an infinitesimal variation
$$ \delta X^{\mu}~=~\varepsilon K^{\mu}(X) \tag{A} $$
in the target space along the Killing vector field. Here $\varepsilon$ is an infinitesimal parameter.

*Show that the induced metric
$$ (X^{\ast}G)_{ab}~:=~\partial_a X^{\mu} ~\partial_b X^{\nu}~ G_{\mu\nu}(X)\tag{B} $$
is invariant under the infinitesimal variation (A)
$$  \delta(X^{\ast}G)_{ab}~=~0.\tag{C}  $$
Conclude that the Polyakov action is invariant as well.

*Further hints to eq. (C): Use that
$$ \partial_a \delta X^{\lambda} ~=~ \varepsilon\partial_a X^{\mu}~\partial_{\mu}K^{\lambda}, \qquad \delta G_{\mu\nu}~=~\varepsilon K^{\lambda}~\partial_{\lambda}G_{\mu\nu}.\tag{D}$$

*It is easier to use the Lie derivative definition of a Killing vector field
$$0~=~({\cal L}_K G)_{\mu\nu}~=~ K^{\lambda}~\partial_{\lambda}G_{\mu\nu} + \partial_{\mu}K^{\lambda}~G_{\lambda\nu}+G_{\mu\lambda}~\partial_{\nu}K^{\lambda} \tag{E} $$
rather than the equivalent eq. (2).

A: Killing vector fields correspond to infinitesimal isometry generators of the spacetime manifold and any physical action including the Polyakov action should be preserved under it. In fact, any physical action should be invariant under the (infinitely) larger group of diffeomorphisms of a manifold. Isomotry transformations are just a finite subset of these diffeomorphisms.


text:
Q: ¿ Por que la variable de instancia toma el valor de la variable de clase? Estoy haciendo pruebas y me he encontrado este comportamiento que me parece curioso, y es que la variable de instancia self.id toma el valor de la variable de clase id cuando en un principio no son la misma variable, que se puede aprecia bien en este pequeño fragmento de código.
class otra_clase:
  id = 3 # Variable de clase
  def __init__(self):
    self.id += 5 # Variable de instancia
    print("La variable de instancia vale:",self.id)
    print("Pero la variable de clase sigue valiendo:",otra_clase.id)

self.id +=5 debería causar error ya que no existe, pero lo que sucede es que pasa a valer 8 mientras que id sigue valiendo 3 como se demuestra en el segundo print.
¿Alguien sabe el motivo de este comportamiento?. No encuentro gran información al respecto. Solo una pequeña nota en la documentación de python que dice que cuando coincide una variable de clase con una de instancia la búsqueda da prioridad a la de instancia, lo que me hace pensar es que en este caso se mostraría primero la variable de instancia, no que la variable de instancia tome el valor de la variable de clase. Enlace a documentación de Python Ver punto 9.4
Gracias.

A: El problema aquí es mas bien algo que tiene que ver en como se manejan las variables (o atributos) en una clase. La variable id existe dentro de la clase otra_clase y es compartida por cualquier intsnacia. La palabra self se usa para hacer referencia a una instancia de una clase y sus métodos y atributos son propios de esa instancia y claramente no son compartidos por las demás instancias.
Si nosotros hacemos otra_clase.id obviamente veremos el valor 3 de igual forma podemos cambiar su valor otra_clase.id += 2. En el constructor (inicializador) de tu clase estas creando una variable llamada id específica para una instancia (self.id), pero python busca en los atributos de la clase para saber si ya existe una variable con ese nombre y al existir ya una variable con el nombre id python usa ese valor para asignar el nuevo valor a tu atributo de instancia.
Algo curioso es que si hacemos:
class otra_clase:
    id = 3 # Variable de clase
    def __init__(self):
        print(f"id:{self.id}")

Se imprimirá el valor 3 esto por lo que había dicho, primero se busca la definición de la variable en la clase, si existe se toma su valor. Esto se puede confirmar si hacemos:
class otra_clase:
    id = 3 # Variable de clase
    def __init__(self):
        print(f"id:{self.valor}") #no existe esa variable en la clase

a = otra_clase()

Nos dará el siguiente error:
AttributeError                            Traceback (most recent call last)
<ipython-input-33-27bced46d37d> in <module>()
----> 1 a = otra_clase()

<ipython-input-32-4ab3b797ec8f> in __init__(self)
      2     id = 3 # Variable de clase
      3     def __init__(self):
----> 4         print(f"id:{self.valor}")

AttributeError: 'otra_clase' object has no attribute 'valor'

Donde claramente dice 'otra_clase' object has no attribute 'valor' lo que significa que la clase otra_clase no tiene un atributo valor.
Por último para aclarar lo que decias:

[...] una pequeña nota en la documentación de python que dice que cuando coincide una variable de clase con una de instancia la búsqueda da prioridad a la de instancia [...]

Esto quiere decir que si existe una variable de instancia con el mismo nombre que una de clase se te mostrará la de instancia, tal vez lo tengas más claro con el siguiente ejemplo.
class otra_clase:
    id = 3 # Variable de clase
    gato = True
    def __init__(self):
        self.id += 5 # Variable de instancia

a = otra_clase()

print("----accediendo a atributos de clase")
print(otra_clase.id)
print(a.id) #devuelve el atributo de instancia y no de clase
print(a.gato)

Resultado
----accediendo a atributos de clase
3
8
True

Como puedes ver, al tratar de acceder al atributo id de la clase otra_clase mediante la instancia a nos devuelve el valor de la instancia y no de la clase, por que se ha priorizado la instancia, a diferencia del atributo gato que solo existe en la clase y no en la instancia.


text:
Q: LOOP,EXCEPTION,CURSOR DECLARE
    DM DEPARTMENTS.DEPARTMENT_NAME%TYPE;
    DI EMPLOYEES.DEPARTMENT_ID%TYPE;
CURSOR ZADANIE5 IS
SELECT DEPARTMENT_NAME,COUNT(DEPARTMENT_ID) FROM DEPARTMENTS
JOIN EMPLOYEES USING(DEPARTMENT_ID)
GROUP BY DEPARTMENT_NAME;
BEGIN
    OPEN ZADANIE5;
    LOOP
        FETCH ZADANIE5 INTO DM,DI;
        IF ZADANIE5%NOTFOUND THEN
        raise_application_error(-20010, ' IN department ' || DM || ' no employees ');
        ELSE
                DBMS_OUTPUT.PUT_LINE(' In Department ' || DM || ' work ' || DI || ' employees ');
   END IF;
    END LOOP;
    CLOSE ZADANIE5;
    END;

I have a problem because the program does not work properly. I want it to throw an exception where the employee does not work but the loop repeats and flies again and I get an error that I do not work in accounting but actually  work two of them there

A: I think your code needs many more modifications. It throws error once it finds the department with 0 employees and then the program will exit. Instead of it, you can just print out the information.
You can use LEFT JOIN to find all the departments and their employees count even if they have no employees (0 in that case).
DECLARE
    DM   DEPARTMENTS.DEPARTMENT_NAME%TYPE;
    DI   NUMBER; -- CHANGE HERE
    CURSOR ZADANIE5 IS
    SELECT D.DEPARTMENT_NAME, COUNT(E.DEPARTMENT_ID )
    FROM DEPARTMENTS D
        LEFT JOIN EMPLOYEES E ON ( D.DEPARTMENT_ID = E.DEPARTMENT_ID )
    GROUP BY DEPARTMENT_NAME;
BEGIN
    OPEN ZADANIE5;
    LOOP
        FETCH ZADANIE5 INTO
            DM, DI;
        EXIT WHEN ZADANIE5%NOTFOUND; -- CHANGE HERE
        IF DI = 0 THEN -- CHANGE HERE
--            RAISE_APPLICATION_ERROR(-20010, ' IN department '
--                                            || DM
--                                            || ' no employees ');
              DBMS_OUTPUT.PUT_LINE(' IN department '
                                            || DM
                                            || ' no employees ');
        ELSE
            DBMS_OUTPUT.PUT_LINE(' In Department '
                                 || DM
                                 || ' work '
                                 || DI
                                 || ' employees ');
        END IF;
    END LOOP;
    CLOSE ZADANIE5;
END;

Find the changes in the code and description of the changes inline.

A: DECLARE
    DM   DEPARTMENTS.DEPARTMENT_NAME%TYPE;
    DI   NUMBER; -- CHANGE HERE
    CURSOR ZADANIE5 IS
    SELECT DEPARTMENT_NAME, COUNT(DEPARTMENT_ID)
    FROM DEPARTMENTS
        LEFT JOIN EMPLOYEES USING ( DEPARTMENT_ID )
    GROUP BY DEPARTMENT_NAME;
BEGIN
    OPEN ZADANIE5;
    LOOP
        FETCH ZADANIE5 INTO
            DM, DI;
        EXIT WHEN ZADANIE5%NOTFOUND; -- CHANGE HERE
        IF DI = 0 THEN

              DBMS_OUTPUT.PUT_LINE(' IN department '
                                            || DM
                                            || ' no employees ');
        ELSE
            DBMS_OUTPUT.PUT_LINE(' In Department '
                                 || DM
                                 || ' work '
                                 || DI
                                 || ' employees ');
        END IF;
    END LOOP;
    CLOSE ZADANIE5;
END;

In Department Sales work 34 employees
 In Department Control And Credit work 1 employees
 In Department Recruiting work 1 employees
 In Department Corporate Tax work 1 employees
 In Department IT Support work 1 employees
 In Department Government Sales work 1 employees
 In Department Retail Sales work 1 employees
 In Department Marketing work 2 employees
 In Department IT Helpdesk work 1 employees
 In Department Administration work 1 employees
 In Department Purchasing work 6 employees
 In Department Contracting work 1 employees
 In Department NOC work 1 employees
 In Department Shipping work 45 employees
 In Department IT work 5 employees
 In Department Executive work 3 employees
 In Department Finance work 6 employees
 In Department Public Relations work 1 employees
 In Department Shareholder Services work 1 employees
 In Department Benefits work 1 employees
 In Department Payroll work 1 employees
 In Department Human Resources work 1 employees
 In Department Accounting work 2 employees
 In Department Treasury work 1 employees
 In Department Manufacturing work 1 employees
 In Department Construction work 1 employees
 In Department Operations work 1 employees

everywhere where is 1 employee should print no employes


text:
Q: Minicom offline when trying to communicate using USB to RS232 cable I'm using a USB to RS232 cable to communicate between two linux machines. On the machine with the USB side connected, I run:
dmesg | grep tty

And get the following output:
console [tty0] enabled
serial8250: ttyS0 at I/O 0x3f8 (irq = 4) is a 16550A
serial8250: ttyS1 at I/O 0x2f8 (irq = 3) is a 16550A
00:0a: ttyS0 at I/O 0x3f8 (irq = 4) is a 16550A
00:0b: ttyS1 at I/O 0x2f8 (irq = 3) is a 16550A
usb 2-1.2: pl2303 converter now attached to ttyUSB0

So far so good. Now I run a minicom -s and using "Serial port setup", I change "Serial Device" to be "/dev/ttyUSB0", "BPS/Par/Bits" to be "115200 8N1", and select "No" for "Hardware Flow Control" and "Software Flow Control".
I save these settings as default, exit from minicom, and then run minicom again.
Minicom opens, however it remains "offline". I can't enter any commands. The other Linux machine connected to the Serial port side of the wire is on and running fine. Why can't I connect to this other Linux machine?

A: Minicom decides offline/online based on whether DCD line is connected or not. I created a null modem cable and tested that data is transferred as it should however minicom shows offline. Browsing through the code I found that it checks for DCD line connection to set a variable for online.
This library I used for testing in java serial port https://github.com/RishiGupta12/serial-communication-manager


text:
Q: JSONP забрать ответ Есть удалённый сервер (на клиентской машине), который принимает запросы только определённого формата, если указать на примере JQuery dataType:JSONP. Иначе запросы отвергаются, как кросс-браузерные.
Однако, сервер принимает следующий запрос:
<script type="text/javascript">
    $.ajax({
    url: "http://site.com:6898/server/api",
    jsonp: "callback",
    dataType: "jsonp",
    data: {
        method: "get_token",
    },
    success: function( response ) {
        console.log("success:");console.log(response );
    }
    error: function( xhr, status, error ) {
        console.log("error:"); console.log(JSON.stringify(xhr) );

    },
 complete: function (xhr, textStatus){
            console.log( "complete: " + JSON.stringify(xhr)+" "+ textStatus);
            }
});
</script>

Ключевым, здесь является dataType: "jsonp". Если указать любой другой тип, запрос отвергается, как кросс-доменный, запрещённый севером.
Однако, ввиду особой спецификации JSONP, ответ (RAW тело) выглядит следующим образом:
{"result": {"token": "85973778790d3f951631a6406d9186b758048bbcb0e56b2f73bb5ed23720a705"}, "error": null}

Т.о., броузер не в состоянии обработать такой ответ, т.к. нет названия callback функции, и возвращает ошибку:
SyntaxError: missing ; before statement
В консоле, обработанный ответы
ERROR:
{"readyState":4,"status":200,"statusText":"load"}
COMPLETE (textStatus):
parsererror
Всё логично. Браузер не может распарсить JSONP, т.к. формат кривой. Однако, только так сервер отвечает.
Вопрос: как всё-таки можно забрать RAW ответ (тело)?


text:
Q: Delayed job failed during capistrano deploy I'm using ActiveAdmin, capistrano to deploy, thinkng_sphinx to search and delayed_job to automatically run reindex for ts after adding new record.
Part from my deploy.rb
before 'deploy:update_code', 'thinking_sphinx:stop'
after 'deploy:update',  'thinking_sphinx:index', 'thinking_sphinx:start'

after 'deploy:finalize_update', 'sphinx:symlink_indexes', "delayed_job:stop", "delayed_job:start"

The problem is when running this command during deploy
 executing "RAILS_ENV=production /.../current/script/delayed_job stop"

I got
/.../shared/bundle/ruby/1.9.1/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:503:in `load_missing_constant'
Expected /.../releases/20120804075838/app/admin/users.rb to define Users (LoadError)
from /.../shared/bundle/ruby/1.9.1/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:192:in `block in const_missing'

...
Here is app/admin/users.rb
ActiveAdmin.register ::User do
  index do
    column :name
column "E-mail", :email
 end
end

I tried to rename app/admin/users.rb to app/admin/user.rb - nothing
But if I run just from server command line:
RAILS_ENV=production script/delayed_job stop

all works fine
From my Gemfile
gem 'delayed_job'
gem 'delayed_job_active_record'
gem 'daemons'
gem 'thinking-sphinx'
gem 'ts-delayed-delta', :require => 'thinking_sphinx/deltas/delayed_delta'

thinking-sphinx (2.0.12)
ts-delayed-delta (1.1.2)
delayed_job (3.0.3)
delayed_job_active_record (0.3.2)
activeadmin (0.4.4)

A: Try this in your deploy.rb.
require "delayed/recipes"

delayed recipes uses rails_env variable
set :rails_env,   "production"

# Delayed Job
after "deploy:stop",    "delayed_job:stop"
after "deploy:start",   "delayed_job:start"
after "deploy:restart", "delayed_job:restart"
after "deploy:update_code", "delayed_job:restart"

namespace :delayed_job do

desc "Stop the delayed_job process"
task :stop, :roles => :app do
  run "cd #{current_path}; script/delayed_job -e #{rails_env} stop"
end

desc "Start the delayed_job process"
task :start, :roles => :app do
  run "cd #{current_path}; script/delayed_job -e #{rails_env} start"
end

desc "Restart the delayed_job process"
task :restart, :roles => :app do
  run "cd #{current_path}; script/delayed_job -e #{rails_env} restart"
end
end


text:
Q: How to change only frontend language in Cakephp 3 I have created multilingual website in English and Danish language using I18N and .po file. But if I change the language using I18n::locale() it changes the language of admin panel too. I want to change the language of frontend only. Please suggest.
Thanks in advance.

A: Changing the locale the way you're doing it is correct:
I18n::locale('da_DK');

But if it's changing it in your admin panel too, then the question is purely about how your application is structured and where you are changing the locale.
If you set the locale in AppController for example, then it's going to change for all controllers. There are many ways you could do it. You could create an AdminController which handles an /admin prefix, and changes the locale just for that prefix.
    namespace App\Controller\Admin;

    use App\Controller\AppController;
    use Cake\Event\Event;
    use Cake\I18n\I18n;

    /**
     * Application Controller for `admin` prefixed controllers.
     *
     * All controllers within the `app/Controller/Admin` directory should extend this
     * controller rather than the normal `AppController`.
     */
    class AdminController extends AppController
    {

        public function beforeFilter(Event $event)
        {
            parent::beforeFilter($event);

            I18n::locale('en_GB');
        }
    }

Then ensure you have correctly set up a prefix route for /admin so that you can put all your admin controllers in app/Controller/Admin, and all those controllers should extend AdminController instead of AppController.
https://book.cakephp.org/3.0/en/development/routing.html#prefix-routing

A: I didn't want to change the flow of my website. So I used 18n::locale('en_GB') in my all front-end controllers. That resolved my problem.


text:
Q: Как на php вырезать из контента слайдер? Приветствую. Есть у меня сайт на wordpress и есть на странице слайдер, который выводится с помощью шорткода [rev_slider]. Краткое описание поста получаю таким способом $post_content = mad_post_content_truncate(get_the_content(), 100, " ", "...");, где на выходе имею html

...

Булочки в форме полумесяцев (нем. Kipferl) выпекались...

Вопрос: как вырезать  из контента весь слайдер с содержимым (может располагаться в любом произвольном месте контента) и сохранить в какой-нить переменной, чтобы иметь возможность с ним работать?
Пробую решить через strpos, сам слайдер нахожу, но пока не знаю что делать дальше
$pos = strpos($post_content, 'slider'); if($pos) {..}

A: Если PHP 5.4 и Libxml 2.6 то можно так
<?php

$post_content = '

...

Булочки в форме полумесяцев (нем. Kipferl) выпекались...

';

// создаем DOM дерево
$dom = new DOMDocument;
// этот кусок нужно добавлять для правильной работы с кодировкой
$xmlEncodding = '<?xml version="1.0" encoding="UTF-8"?>';
// парсим строку с HTML
$dom->loadHTML($xmlEncodding . $post_content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
if (!$dom) {
    // Ошибка при разборе документа
}
// ищем слайдер по аттрибуту – id
$slider = $dom->getElementById('rev_slider_1_1_wrapper');
// удаляем слайдер и получаем его в ответе
$oldSlider = $slider->parentNode->removeChild($slider);
// созраняем контент без слайдера в строку
$content = str_replace($xmlEncodding, '', $dom->saveHTML());
// сохраняем слайдер в строку
$sliderContent = $dom->saveHTML($oldSlider);
// удаляем временные переменные
unset($slider);
unset($dom);
unset($oldSlider);
// используем переменные где нужно
echo $content;
echo $sliderContent;

?>


text:
Q: c# How to dapperRow to strongly typed object displayed in grid view I am sure i have not the best practice solution like the most of u guys could program, but im new in the business so pls give me a chance :P
i created a table in my sqlite database and added a Employee to the Employee table.
I Set the DataContext of my GridView to the returned List from my ModelView.
But my grid is emtpy. i guess i have a logical error in the art i convert my dapperRow.
Please take a look at it. i Dont get an error or something. My gridView is just empty.
 public List<Employee> GetAllEmployees()
    {
        List<Employee> employees = new List<Employee>();
        List<dynamic> results = _dataAccess.SelectAllEmployees();
        List<IDictionary<string, object>> dapperRowDic = results.Select(x => (IDictionary<string, object>)x).ToList();
        foreach(var dapperRow in dapperRowDic)
        {
            object id;
            object firstName;
            object lastName;
            object experience;
            object salary;

            dapperRow.TryGetValue("ID", out id);
            dapperRow.TryGetValue("FirstName", out firstName);
            dapperRow.TryGetValue("LastName", out lastName);
            dapperRow.TryGetValue("Experience", out experience);
            dapperRow.TryGetValue("Salary", out salary);

            employees.Add(new Employee((int)(long)id,(string)firstName,(string)lastName, (int)(long)experience, (int)(long)salary));
        }

        return employees;
    }

public class SQLiteDataAccess : IDataAccess
{
    public SQLiteDataAccess()
    {
        if (!File.Exists(SqLiteBaseRepository.DbFile))
            CreateDatabase();
    }

    public void InsertEmployee(int id,string firstName, string lastName, int experience, int salary)
    {
        using (var con = SqLiteBaseRepository.SimpleDbConnection())
        {
            var parameters = new { FIRSTNAME = firstName, LASTNAME = lastName, EXPERIENCE = experience, SALARY = salary, ID = id };
            con.Execute("insert into Employee (ID,FirstName,LastName,Experience,Salary) " +
                "Values (@ID ,@FIRSTNAME, @LASTNAME, @EXPERIENCE,@SALARY)", parameters);
        }
    }

    public List<dynamic> SelectAllEmployees()
    {
        using (var con = SqLiteBaseRepository.SimpleDbConnection())
        {
            return con.Query<dynamic>("SELECT * FROM Employee").ToList();
        }
    }

public partial class MainWindow : Window
{
    private EmployeeViewModel _employeeViewModel;

    public MainWindow()
    {
        InitializeComponent();
        string mode = "SQLite";
        _employeeViewModel = new EmployeeViewModel(DataAccessFactory.GetDataAccessObject(mode));
        List<Employee> employees = _employeeViewModel.GetAllEmployees();
        this.DataContext = employees;
        this.Show();
    }

    private void btnSave_Click(object sender, RoutedEventArgs e)
    {
        int id = int.Parse(txtId.Text);
        string firstName = txtFirstName.Text;
        string lastName = txtLastName.Text;
        int experience = int.Parse(txtExperience.Text);
        int salary = int.Parse(txtSalary.Text);
        _employeeViewModel.CreateEmployee(id, firstName,lastName,experience,salary);
        this.DataContext = _employeeViewModel.GetAllEmployees();
    }
}

<Window x:Class="Employee_List_SQLite_Dapper_Wpf.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Employee_List_SQLite_Dapper_Wpf"
    mc:Ignorable="d"
    Title="" Height="450" Width="800">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="auto"></ColumnDefinition>
        <ColumnDefinition Width="200"></ColumnDefinition>
        <ColumnDefinition Width="200"></ColumnDefinition>
        <ColumnDefinition Width="200"></ColumnDefinition>
        <ColumnDefinition Width="35"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="auto"></RowDefinition>
        <RowDefinition Height="auto"></RowDefinition>
        <RowDefinition Height="auto"></RowDefinition>
        <RowDefinition Height="auto"></RowDefinition>
        <RowDefinition Height="auto"></RowDefinition>
        <RowDefinition Height="auto"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>
    Employee
    ID:
    First Name:
    Last Name:
    Experience:
    Salary:
    <TextBox x:Name="txtId" Grid.Row="1" Grid.Column="1" Margin="2"></TextBox>
    <TextBox x:Name="txtFirstName" Grid.Row="2" Grid.Column="1" Margin="2"></TextBox>
    <TextBox x:Name="txtLastName" Grid.Row="3" Grid.Column="1" Margin="2"></TextBox>
    <TextBox x:Name="txtExperience" Grid.Row="4" Grid.Column="1" Margin="2"></TextBox>
    <TextBox x:Name="txtSalary" Grid.Row="5" Grid.Column="1" Margin="2"></TextBox>
    <Button Name="btnSave" Grid.Row="5" Grid.Column="2" Width="80" Click="btnSave_Click">Save</Button>
    <ListView Grid.Row="6" Grid.ColumnSpan="5" ItemsSource="{Binding Employee}" Margin="5,20,20,20">
        <ListView.View>
            <GridView x:Name="gridEmployee">
                <GridViewColumn Header="ID" DisplayMemberBinding="{Binding ID}" Width="30"/>
                <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="200" />
                <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="200"/>
                <GridViewColumn Header="Experience" DisplayMemberBinding="{Binding Experience}" Width="100"/>
                <GridViewColumn Header="Salary" DisplayMemberBinding="{Binding Salary}" Width="150"/>
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

A: Here's what your Dapper code should look like for retrieving all employees:
var employees = connection.GetAll<Employee>();

That's it.  You can find out more about the GetAll<T>() method here.
Your Insert Employee code looks OK, but all you really need to do is:
var employee = new Employee
{
    FirstName = firstName,
    LastName = lastName,   // etc.
}

connection.Insert(employee);

You will need to properly annotate your Employee class to make this work correctly.  The Dapper.Contrib page I linked above explains how to do this.
For MVVM, I suggest a good tutorial, like this one.


text:
Q: In C# is there a way to override a private or public function through a plugin? I have an application that loads plugins. I have a plugin that has complete access to a form instance. If I have a function in a form that needs to be overridden, but is not a virtual function, is there another way to override it?
Here is a very generic example:
//Form I am modifying
public partial class MyForm : Form
{
    public int myVariable1;
    public int myVariable2;

    //Constructor and other methods here

    private void setVar(int replacementValue)
    {
        myVariable1 = replacementValue;
    }
}

...then in a separate dll...
//My plugin
public class MyPlugin : IMyPluginBase
{
    MyForm theForm; //Reference to the form in the main application

    //Constructor and other methods here

    private void setVar(int replacementValue)
    {
        theForm.myVariable2 = replacementValue;
    }
}

In this example the function in the form sets 'myVariable1', but the 'setVar' function in the plugin sets 'myVariable2'.
So, the question is, in the case of this example, can I replace/override the form's 'setVar' function with the one in the plugin? Maybe with messages or reflection?

A: No. You cannot "replace" or overide private non-virtual methods in C#.
The C# language (and .NET runtime) don't support dynamic replacement of methods in the manner you describe. Very few languages support this capability, to my knowledge (I believe that SmallTalk and Objective-C both do).
If this is the only place in your application where you need this kind of extensibility, you can achieve it through an interface, delegate, or inhertance+virtual methods. Any of these approaches could work ... which one you choose depends on what kind of extensibility you desire.
If you expect to have many such extensibility points in your app, then you should probably take a look at the Managed Extensibility Framework (MEF). It provides a Microsoft-supported model for creating plug-in architectures using patterns and technique that work well in .NET.

A: If a function is not marked as virtual or part of an interface that your class implements there's exactly 0 chance you would be able to override it. No plugin, no reflection, no nothing, simply forget about it or use some other dynamic language but not C#.

A: The short answer to your question is no.  What you can do, however, is give your form a copy of the IMyPluginBase, and have Form.setVar() call out to MyPluginBase.SetVar().
The code will look something like this:
public partial class MyForm : Form
{
    public int myVariable1;
    public int myVariable2;

    public IMyPluginBase MyPlugin;

    //Constructor and other methods here

    private void setVar(int replacementValue)
    {
        MyPlugin.setVar(replacementValue);
        //myVariable1 = replacementValue;
    }
}

public class MyPlugin : IMyPluginBase
{
    MyForm theForm; //Reference to the form in the main application
    public void setVar(int replacementValue)
    {
        theForm.myVariable2 = replacementValue;
    }
}

Note that setVar() will need to be defined in IMyPluginBase.


text:
Q: DataTables & JQuery Jeditable, how to pass in row data? I am using Jeditable,
http://www.appelsiini.net/projects/jeditable

And DataTables,
http://datatables.net/download/

To try and make an live editable table but whenever I edit, it does not post the row ID that I am getting it from so I want to try and pull the right ID when you edit a column. However, no matter what I try it does not seem to get anything. Any ideas?
Code:
 $(document).ready(function() {

          var oTable = $('#example').dataTable( {
         "bProcessing": true,
        "bServerSide": true,
        "sAjaxSource": "scripts/getData.php",
        "fnDrawCallback": function () {
            $('#example tbody td').editable( 'examples_support/editable_ajax.php', {
                "event" : 'dblclick',
                "tooltip" : 'Click to edit.',
                "submitdata" : {id: $(this).parent().index()},
                "callback": function( sValue, y ) {
                console.log(sValue);
                console.log($(this).parent().index());
                console.log($(this).parent().find('td:eq(3)').html());
                    /* Redraw the table from the new data on the server */
                    oTable.fnDraw();
                },
                "height": "14px"
            } );
        }
        } );
    } );

In this particular example, submitdata returns 1 while the console.log in teh callback returns the correct info.

A: Try wrapping the submitdata object in a function to keep this in scope...
    ...
    "submitdata" : function() {return {id: $(this).parent().index()}},
    ...

It worked for me, hope that helps.
Cheers.

A: I don't know if this is still alive, but I ended up with:
"submitdata" : function(){return {id: $(this).closest('tr').attr('id')}},

if you are using DT_RowID from DataTables it should return it correctly.
Best.


text:
Q: How to align a nested Angular Material table with its parent columns? I am using Angular Material's table (not the display: flex version) and I am using a nested table, but I want the columns of the nested table to line up with the headings for the parent table.
This way the parent's column labels will apply to both itself and the nested table.
This is what it looks like now. But I want the 2 columns in the nested table to also be aligned such that Street aligns with "name" and the number aligns with "email".

Here is a stackblitz for the table.
CSS
table {
  width: 100%;
}

tr.example-detail-row {
  height: 0;
}

.example-element-row td {
  border-bottom-width: 0;
}

.example-element-detail {
  overflow: hidden;
  display: flex;
}

.inner-table {
  width: 100%;
}

HTML

    <ng-container matColumnDef="{{column}}" *ngFor="let column of columnsToDisplay">
         {{column}}
         {{element[column]}}
    </ng-container>

    <ng-container matColumnDef="expandedDetail">

            <ng-container matColumnDef="{{innerColumn}}" *ngFor="let innerColumn of innerDisplayedColumns">
               {{element[innerColumn]}}
            </ng-container>

    </ng-container>

This stackblitz originally came from this link and I just modified it a bit.

A: It's better to use Angular Material Table Flex Version, but with adding some dirty code this will be fix:
I added below css code to css file:
.mat-column-name {
  width: 200px;
}

.mat-column-street {
  padding-left: 0 !important;
  width: 200px;
}

also you can see stackblitz link.
in this way name column & street column fixed to 200px or how much you want.


text:
Q: Setting attributes in constructor for Django model I have an abstract BaseModel from which many models will inherit the behavior to initialize attributes values from the constructor:
class BaseModel(models.Model):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for key in kwargs:
            setattr(self, key, kwargs[key])

    class Meta:
        abstract = True

Then, I try to initialize one of its specializations like this:
BaseModelSon(attr1=val1, attr2=val2, ...)

Is this a good practice? Do you know any other way to achieve this dynamic initialization for Django models?

A: You can already create regular Django model instances with
MyModel(field1='value1', field2='value2')

so I don't think your __init__ method is necessary.

A: Also you'll probably find useful Model.objects.create() method for new Django models instances creation:
instance = MyModel.objects.create(field1='value1', field2='value2'...)

If there are some auto-generated fields (for example, id or some date with auto_now_add=True option) — you'll get their values in instance if you have used Model.objects.create().


text:
Q: Do not update not specified fields in Entity with Spring JPA I am creating an application with REST API so one of the endpoints is to create and another to update. My issue comes when I try to update the entity it updates the fields I added in the creation but not in the update.
I am trying with @DynamicUpdate and @SelectBeforeUpdate and it still follows the same behaviour.
Controller
@RestController
@RequestMapping("/v01")
@Slf4j
public class ProjectController {

@Autowired
private ProjectServiceIface projectService;

@PostMapping(path = "/project", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Project> createProject(@Valid @RequestBody Project project, BindingResult result){
    if(result.hasErrors()){
        throw new BusinessServiceException(result.getFieldError().getDefaultMessage(), result.getFieldError().getField() + " " + result.getFieldError().getCode());
    }
    Project projectSaved = projectService.createProject(project);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Location", projectSaved.getId().toString());

    return new ResponseEntity<>(project, headers, HttpStatus.CREATED);
}

@PatchMapping(path = "/project", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Project> updateProject(@Valid @RequestBody Project project, BindingResult result){
    if(result.hasErrors()){
        throw new BusinessServiceException(result.getFieldError().getDefaultMessage(), result.getFieldError().getField() + " " + result.getFieldError().getCode());
    }
    Project projectUpdated = projectService.updateProject(project);

    if(projectUpdated == null) {
        return new ResponseEntity<>(null, new HttpHeaders(), HttpStatus.NOT_FOUND);
    }
    HttpHeaders headers = new HttpHeaders();
    headers.add("Location", projectUpdated.getId().toString());

    return new ResponseEntity<>(projectUpdated, headers, HttpStatus.CREATED);
}
}

Service
@Service
public class ProjectServiceImpl implements ProjectServiceIface {

@Autowired
private ProjectRepository projectRepository;

@Autowired
private ProjectRepository projectRepository;

@Override
public Project createProject(Project project) {
    Project projectFound = projectRepository.findByName(project.getName());
    if(projectFound != null){
        throw new BusinessServiceException(Constants.FUNCTIONAL_ERROR, "The Project already exists");
    }
    project.setCreateTime(new Date());

    Project projectSaved = projectRepository.save(project);
    return projectSaved;
}

@Override
public Project findProjectById(String id) {
    Project projectFound = null;
    if(!StringUtils.isNumeric(id)){
        throw new BusinessServiceException(Constants.FUNCTIONAL_ERROR, "The ID is not in a correct format");
    }
    Optional<Project> projectOptional = projectRepository.findById(Integer.valueOf(id));
    if(projectOptional.isPresent()){
        projectFound = projectOptional.get();
    }
    return projectFound;
}

@Override
public Project updateProject(Project project) {
    Project projectUpdated = null;
    Optional<Project> projectFound = projectRepository.findById(project.getId());
    if(projectFound.isPresent()){
        project.setUpdateTime(new Date());
        //Project projectMapped = EntityMapper.projectMapper(project);
        projectUpdated = projectRepository.save(project);
    }
    return projectUpdated;
}

@Override
public Project findProjectByName(String projectName) {
    Project project = projectRepository.findByName(projectName);

    return project;
}
}

Repository
public interface ProjectRepository extends CrudRepository<Project, Integer> {

@Query(value = "SELECT * FROM project p WHERE p.name = :projectName", nativeQuery = true)
Project findByName(String projectName);

 }

Project (Entity)
@Entity
@Data
@DynamicUpdate
@SelectBeforeUpdate
@Table(name = "project")
public class Project implements Serializable {
private static final long serialVersionUID = -6163778458602900643L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@NotEmpty
private String name;
@NotEmpty
private String tag;
private String icon;
@Column(name = "create_user", updatable = false)
private String createUser;
@Column(name = "update_user")
private String updateUser;
@Column(name = "create_time", updatable = false)
private Date createTime;
@Column(name = "update_time")
private Date updateTime;
}

This is the request I use for creating:
{
"name" : "Test12",
"tag" : "TST",
"icon" : "/var/usr"
}

The response I obtain:
{
"id": 5,
"name": "Test12",
"tag": "TST",
"icon": "/var/usr",
"createUser": null,
"updateUser": null,
"createTime": "2020-01-24T22:33:48.499+0000",
"updateTime": null
}

And this is the request I perform to update:
{
"id": 5,
"name": "Test5",
"tag": "AAA"
}

The response I obtain:
{
"id": 5,
"name": "Test67",
"tag": "AAA",
"icon": null,
"createUser": null,
"updateUser": null,
"createTime": null,
"updateTime": "2020-01-24T22:44:50.914+0000"
}

As you can see both icon and createTime have been set to null. I only want to be updated specifically the fields I send in the request/entity.

A: You can use Spring Data Rests Patch method, or explicitly call merge on EntityManager

A: it would be helpful if you share the code that you are trying to insert/update
 for creation time remove updatable = false in entity class
Issue is you are not getting the values for Project from database ..you are checking in DB if the value exists but saving the values sent in json in Project Json icon is not there
fix is you need to get the values based on ID and set the values again which are going to be changed..this way old values willl be retrieved and new values will be updated


text:
Q: Rsync exclude from root I'm confused with rsync's exclude.
I'm trying to backup every starting with / but exclude /media/ /mnt/ /home/files/ and /home/backup
sudo rsync -a \
       --progress \
       --stats \
       --exclude-from=/home/files/ \
       --exclude-from=/media/ \
       --exclude-from=/mnt/ \
       --exclude-from=/home/backup/ \
   / /home/backup

Won't work.
I end up copying files to /home/backup/home/backup/...
I read that I have to write my excludes relative to my transfer root, but i guess if / is my transfer root then /media/ should be relative to that right?

A: man rsync

--exclude=PATTERN       exclude files matching PATTERN
--exclude-from=FILE     read exclude patterns from FILE

exclude-from is used to point to a file that lists the folders that you don't want. Try the option --exclude

A: Your syntax is incorrect; that's why it isnt't working.
You say:
--exclude-from=/home/backup/

when you should simply say
--exclude="/home/backup/*"

Also, you are not using the
--delete-excluded

switch that can synchronize the directories.
As to your question at the end:  Yes, in your case you are specifying / as your beginning for the rsync.   So if you exclude "tmp/*" then it is indeed relative to / so it is the same as specifying "/tmp/*"


text:
Q: MiniProfiler Ruby: Getting a better breakdown for non-SQL calls I'm trying to profile some of our Rails controllers using Mini Profiler, but I think I'm trying to use it for something it isn't built for.  I've got it profiling SQL queries just fine, but I need to break down the non-SQL code, because we're seeing a lot of chug in some pages, but the SQL doesn't seem to be the problem.
Here's a screenshot of what I'm talking about: http://cl.ly/image/2J3i1C1c072O
You can see that the top level (Executing action: show) takes 9136ms to complete, but the queries executed are only a fraction of that total time.  I suppose what I'm asking is if there's a way to display more "detailed" information about the code being executed, or if I need to find a different tool to use.  New Relic isn't an option, unfortunately.
Thanks for any help.

A: You can insert custom steps in the areas you think are responsible.
# in your initializer
Rack::MiniProfiler.profile_method SomeClass, "method"

# or
Rack::MiniProfiler.step "some step" do
  # your code
end

Additionally you can run ruby-prof to figure out what is going on everywhere and then strategically instrument.


text:
Q: Batch updates in JPA (Toplink) Is there any way if executing batch updates (EntityManager persist() or merge()) using JPA Toplink?

A: If you want to do a batch update, you can create a Query (either JPQL or Native SQL) that performs the update using the EntityManager, and then call executeUpdate on that query.


text:
Q: Move coupon section and messages in multistep checkout I wonder if anyone can help. I am looking to move the section that says 'Have a coupon? Click here to enter your code' on the checkout page of my website (www.neverendingcrafter.co.uk). I have currently managed to move the coupon section so that it is at the bottom of the checkout page rather than it being at the top of the page. I have done so using the following code in the fuctions.php file
remove_action( 'woocommerce_before_checkout_form', 'woocommerce_checkout_coupon_form');
add_action( 'woocommerce_after_checkout_form', 'woocommerce_checkout_coupon_form' );

This looks better than it being sat at the top of the page all the time. However, I ideally would like the coupon section to only be shown in the 'Review & Pay' section of the mutlistep checkout and be just before the subtotal is shown. I have had a look at this website for woocommerce checkout hooks https://www.businessbloomer.com/woocommerce-visual-hook-guide-checkout-page/ and I think I would like it to be displayed at the woocommerce_checkout_before_order_review hook placement but I haven't managed to successfully get the coupon section to display there. I am not sure if this is because of the multistep plugin I am using which is https://codecanyon.net/item/woocommerce-multistep-checkout-wizard/8125187 or if I am just approaching this the wrong way.
Any help anyone can offer would be greatly appreciated.


text:
Q: Please explain object versioning in the nodejs module system This question is about the persistance of variables across different modules in nodejs when they don't directly "require" each other, but do "require" a common ancestor.
It is also the generalised version of this stackoverflow question. Whilst I received an answer there that helped me solve my specific case, I'm still unclear as to the answer to the architectural problem I posed. I hoped that the general problem was a good fit for a programmers.stackexchange question.
Assume we have a nodejs program structured like so:

*

*Module Alpha - exports variable a.

*Module Beta - requires module Alpha, reads variable a -> prints it to console periodically

*Module Gamma - requires module Alpha, periodically writes to variable a

Is the instance of module Alpha, and thus variable a, common across all three modules. e.g. can module Gamma make changes to variable a that are successfully printed to the console by module Beta.
If this is true, why is this true even though there is no direct "requires" relationship between modules Gamma and Beta?
If this is not true, can you explain the best way to share a variable than needs to be modified at runtime between multiple node modules?
Can you explain the underlaying data model which is causing this behaviour in nodejs modules?

A: I think the critical piece you're missing is that the result of require("foo") is always the same object. Consider this REPL example:
> var myHttpModule = require("http")
{ ... }
> myHttpModule.someNewProperty = "someValue"
'someValue'
> require("http").someNewProperty
'someValue'

The second call to require("http") did not re-create the http module -- it summoned up the only http module that exists in Node's current execution environment, which had been altered on the previous line.
So, in your example, there's only one Alpha module. When Beta and Gamma call require("alpha"), they're each getting the same reference to the one-and-only Alpha module singleton object.
(Or, to be perfectly precise, they're getting the same reference to the exports value of the Alpha module. require creates a Module object, but returns only the exports property of that module. If you don't fully understand the distinction right now, it's not a big deal.)
Behind the scenes: what's really going on with require caching?
The first time you use require to include a module, Node actually runs the code in that module. The resulting module is stored in require.cache. Subsequent attempts to load the module with require first check for an already-loaded module object in require.cache. (Note: environment-native built-in Node modules like http are exceptions in that they don't use require.cache -- you'll need to test out my code below with a custom module.)
require.cache is an object whose keys are module file path, with associated values that are module objects. For example, assume some module named "foo" in C:\node_modules\foo.js:
> require.cache                             // empty cache
{ }
> require("foo")                            // require foo
{ bar: 'baz' }
> require.cache                             // cache now populated
{ 'C:\\node_modules\\foo.js':
   { id: 'C: \\node_modules\\foo.js',
     exports: { bar: 'baz' },
     parent: { ... },
     filename: 'C:\\node_modules\\foo.js',
     ...
     paths:
      [ ... ] } }

The current value of the foo module is in require.cache["C:\node_modules\foo.js"].exports. We can use require.resolve to get the file path of the module from the name, so we can express it also as require.cache[require.resolve("foo")].exports.
If we call require("foo") a second time, Node sees that require.cache[require.resolve("foo")] is defined, and so it returns the value of require.cache[require.resolve("foo")].exports instead of re-running the module creation code. This exports property of the foo module in require.cache is the single instance of the foo module export value, returned with every subsequent call to require("foo").
One interesting implication here is that you can delete require.cache[require.resolve("foo")] to force a reload of the foo module with the next call to require("foo"), because the object describing the module is removed from the require.cache object.
So what does this mean for me?
Without require, you could still share values between modules using global variables. For example, your Alpha/Beta/Gamma case would work just as well with just Beta and Gamma setting and reading the global value global.a. Instead, with Node's require system, you're actually setting and reading global.require.cache[require.resolve("alpha")].exports.a, which Node lets you read neatly as just require("alpha").a.
In fact, if you just want to share a value and don't need to import your shared data as a module, you could also use a namespacing object, i.e., have Beta and Gamma set and read properties of the object global.alpha. The major advantage to using require is that you don't need to set up require("alpha") external to the other scripts, whereas you would need to define global.alpha = {} before requireing Beta and Gamma. (Alternatively, you could conditionally define global.alpha in each module based on a typeof global.alpha == 'undefined' check instead, to see if it's the first module to use it.)

A: Data sharing between modules depends on how and what modules exports. It's important to keep in mind that require() caches and returns the exports variable. For instance:
// alpha.js
module.exports.a = 5; // returns 'exports' which is an empty object
                      // with "a" as a property. node caches this object

// gamma.js
var alpha = require("alpha");
alpha.a = 666;  // alpha is a reference to the exports object

// beta.js
var alpha = require("alpha");
console.log(alpha.a); // prints 666

Updating it (alpha.a = 666) should work. This means that beta.js should indeed get the latest value each time.
But if you do:
// alpha.js
module.exports = 5; // returns it as an integer which is cached by node.

// gamma.js
var alpha = require("alpha");
alpha = 666; // overwrites the local copy, but nothing else happens

// beta.js
var alpha = require("alpha");
console.log(alpha); // still prints 5

By the way, doing:
// alpha.js
exports = 5;

fails because that code is (conceptually) like this:
// alpha.js
module.exports = {};
var exports = module.exports;
exports = 5;
return module.exports; // returns {}, not 5