text:
Q: CDO CreateMHTMLBody locks the file in JScript I'm making a JScript script that sends e-mail messages in HTML format via CDO. I have a message template in .html file, and I put some unique data into each message being sent. So, I create a copy of the original .html file for each message.
The problem is that I cannot detele this temporary file from within script after sending the message. I've checked with ProcessExplorer, which process locks the file, and it is cscript.exe/wscript.exe (wichever is being used to run the script).
Here is the example (simplified) code:
//-------------------------------------------
var fso = new ActiveXObject("Scripting.FileSystemObject");
var BodyFileName = fso.GetAbsolutePathName(WScript.Arguments(3));
var BodyExtensionName = fso.GetExtensionName(BodyFileName)
var BodyFile = fso.OpenTextFile(BodyFileName, 1);
var Body = BodyFile.ReadAll();
BodyFile.Close();
//-------------------------------------------
// Replace something in Body here
//-------------------------------------------
BodyFileName = fso.BuildPath(fso.GetParentFolderName(BodyFileName), fso.GetTempName() + "." + BodyExtensionName);
var TmpBodyFile = fso.OpenTextFile(BodyFileName, 2, true);
TmpBodyFile.Write(Body);
TmpBodyFile.Close();
// Here ProcessExplorer shows that the file is closed
//-------------------------------------------
var objEmail = new ActiveXObject("CDO.Message");
objEmail.From = WScript.Arguments(0);
objEmail.To = WScript.Arguments(1);
objEmail.Subject = WScript.Arguments(2);
objEmail.CreateMHTMLBody("file:///" + BodyFileName.replace("\\","/"));
// Here the file is open again
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2;
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "192.168.0.1";
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25;
objEmail.Configuration.Fields.Update();
objEmail.Send();
objEmail = null;
//-------------------------------------------
// The following loop becomes endless
for (;;) {
  try {
    fso.DeleteFile(BodyFileName, true);
  } catch(e) {
    WScript.Sleep(100);
    continue;
  } finally {
  }
  break;
}
//-------------------------------------------

Thanks.

A: Did you try programmatically killing the mail prcess and then deleting the file(Unless you need the mail program running after you send the mail)
Do you have IIS SMTP service installed, might be worth trying
CreateObject("cdonts.NewMail")
or
CreateObject("outlook.application")
But you might have to kill the related process in a similar situation.


text:
Q: Prediction Result Interpretation I got a prediction result and it is not seemingly good.
But, I am not sure how horrible is this result.
Brief summary of the result is as follows:

*

*My dependent variable is a binary variable

*I separated my data set in two data set (1) cross-validation set (2) test set
(In both sets, the proportion of the dependent variable's values is 1:9)
(That is, y = 1 is 10% and y = 0 is 90%)

*I selected the best method and model only using the cross-validation set.

*After fitting model only using the cross-validation set, I predicted the test set's dependent variable
using the test set's features

*the result is pretty shocking. Every predicted result is just zero.

In this situation, I am not sure is it horrible or a just bad result because the real proportion of y = 0 is 1:9 in the test set.
How do you think that? I want some comments.
Thank you.

A: To formalize things a little bit, you are solving a binary classification problem where you have a modest level of class disbalance.
It would be helpful to get a more detailed description of what you mean by selecting the best method and model.
Given that you have a dedicated test dataset and, as far as I understood, you used cross-validation (by the way, which type did you use?) to fine-tune hyperparameters, it seems that there is nothing obviously wrong.
That said, since your classes are imbalanced, double-check that you are using stratified splits so as to avoid the cases when one of the splits consists entirely of the first-class objects.
It's also worth noting that using accuracy as a metric in such unbalanced scenarios is not the best approach. Getting an accuracy of $0.9$+ and most predictions as zeros makes sense and you should also pay attention to other metrics.
What also matters for such tasks is determining how you are going to use your model in the future. It's often the case that trying to concentrate too much on 0/1 outcomes from the beginning does not correlate very much with the really useful possible applications of the model. Try to check other metrics like AUC ROC that can be much more representative of your model's true prediction capability (but please also keep in mind that this is a metric that evaluates your model's ranking talent and is a composite indicator across all possible thresholds, not just one as opposed to accuracy, precision, recall, f1.
Another thought regarding the distribution of classes: as long as you are confident that it matches the data in the wild, there is no need to do downsampling or oversampling, but you could try and use the so-called "cost-sensitive learning" and use the class_weight="balanced" parameter available in most sklearn-ish libraries.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Finding specific caller in composition relation class MyDate{
    Calendar effectiveDate, cancelDate;
    //Getter and setter
}

class Member{
    private String fName, lName
    private MyDate date;
    //getter setters
}

class Policy{
    private int policyId
    private MyDate date;
    //getter setters
}

class Address{
    private int addressType
    private MyDate date;
    //getter setters
}

I have many more classes like Contract, Payment, Address etc. having reference to Date class
Then I have multiple services which calls setEffectiveDate()
Service1{
    member.getDate().setEffectiveDate(effDate);
}

Service2{
    policy.getDate().setEffectiveDate(effDate);
}

Service3{
    contract.getDate().setEffectiveDate(effDate);
    address.getDate().setEffectiveDate(addressEffDate);
}

I want to set a debug pointer in setEffectiveDate() such that it will suspend execution only when setEffectiveDate() is called on, say Address object.
I tries using Thread.currentThread().getStackTrace() but it gives me name of calling Service class (Service3 in this case) but not the actual parent Object(Address) on which the method was called.
Note: Using Java 7, RSA/Eclipse
Right now I am using a very cumbersome method as follows
class MyDate{
    Calendar effectiveDate, cancelDate;
    //Getter and setter
    public String source; //This is temporary variable I introduce just for debugging purpose
    public setEffectiveDate(Calendar effectiveDate){
        this.effectiveDate = effectiveDate;
        /* This is temporary code for debugging */
        if(this.source.equals("address"){
            System.out.println("Called from address"); //Set a debug pointer on this line
        }
    }
}

Then later in Address class I set source = "address"
class Address{
    private int addressType
    private MyDate date;
    public getDate(){
        this.date.source = "address"; //Temporary code just for debugging
        return date;
    }
}

Any help would be greatly appreciated

A: First of all the use of the name Date is discouraged as any developer will think it's the standard Java Date class instead of your custom one. I'd recommend you think of renaming it.
Second of all, you can add conditions to break points. In Eclipse you tick the conditional checkbox and then you can add something that will return a boolean like this.source.equals("address") and it will only stop when that condition is satisfied.


text:
Q: jQuery: if my css visibility:hidden, how can i appear my elements? in my css i've set some elements visibiliy:hidden, how can I show them?
I've done it before with opacity, but i've some bug in IE:
var i = 0;
$mySelection.each(function(i) {
    $(this).delay((i * 100) + ($mySelection.length)).animate(
        { opacity: "1"},
        {queue:true, duration:1000, easing:"quartEaseIn"}
    );
})

How can i do if I want controll visibility with jQuery instead of opacity?
thank you

A: $(":hidden").css("visibility", "visible");

A: Rather than using visibility: hidden, use display:none, then if you want to fade in your hidden element use fadeIn.  For example:
$("div:hidden").fadeIn("slow");

Edit: Given that you want to use visibility, try this:
var i = 0;
$mySelection.each(function(i) {
    $(this).delay((i * 100) + ($mySelection.length)).css(
        { 'opacity': '0', 'visibility': 'visible'}).animate(
            { opacity: "1"},
            {queue:true, duration:1000, easing:"quartEaseIn"});
});

A: I used this code to change the CSS visibility attribute with Jquery. Where the element1 on hover will change visibility of element2.
Did two different script for same element to give a mouseover-mouseleave effect.
 <script>$(document).ready(function(){
 $(".element1").mouseover(function(){
     $(".element2").css("visibility","visible");
 });

});
         <script>$(document).ready(function(){
 $(".element1").mouseleave (function(){
     $(".element2").css("visibility","hidden");
 });

});
Note.- That Element2 the one thats CSS is being affected, originally is hidden. so when mouse is over Element1, Element2 shows up. When mouse leaves element1, Element2 Hides again. Hope it helps
-Expiriance of this code reaserching and mixing some other codes from users in stack overflow

A: $(':hidden').show();

I hope this helps and I hope I understood your question :) http://api.jquery.com/show/

A: Try
$mySelection.show();


text:
Q: What does "|=" mean in Java? Note my question is not regarding != but |=
A usage example is here
I assume that x |= y is the same as x = x | y but I could not find confirming documentation and wanted to be sure
Thanks

A: It's a bitwise "or" plus assignment, so you are quite correct in your assumption.

A: Yes, it's a bitwise inclusive or assignment: http://www.cafeaulait.org/course/week2/03.html

A: More correctly, x |= y is actually computed as x = x | (y).
Here is an interesting example of why this is important.
int c = 2;
c %= c++ * ++c;

The interesting consequence here is that it would be written as
c = c % (c++ * ++c);

Java specifications tell us that the JVM will see the initial c first and store it, anything preceding it will have no effect on it, thus c++ & ++c will not actually affect the outcome of the calculation. It will always be c = 2 %  which equals 2 :)

A: You can read Java Langauge Specification


text:
Q: How should be EJB Stateless Session Bean correctly injected into the web module? Being completely new to Java EE (but not to Java itself) I'm trying to build a very simple "Enterprise Application" with Hibernate as JPA provider and JSF as the actual UI framework. For this purposes I'm using the NetBeans 7 with GlassFish 3.1.
{ApplicationName}-ejb:
I've accomplished to generate entity classes from database and local sesssion beans for these entities. Beans.xml is in place.
@Stateless
public class QuestFacade extends AbstractFacade<Quest> implements QuestFacadeLocal {
    // some methods here as well as EntityManager injection ...
}

{ApplicationName}-war:
I've created a simple POJO as a backing bean for the JSF page. I've annotated it with javax.inject.@Named and javax.enterprise.context.@SessionScoped. This backing bean is now accessible from the JSF page as well as being injected when the actual page is accessed. Beans.xml is in place as well.
@Named
@SessionScoped
public class QuestBean implements Serializable {

    @EJB
    protected QuestFacade questFacade;

    // several methods delegating lookups to the questFacade ...
}

Having this deployed and page accessed, I'm, however, getting an error from GlassFish that the QuestFacade cannot be looked up by the JNDI.
The stacktrace is quite long but the initial cause could be enough:
Caused by: javax.naming.NamingException: Lookup failed for 'model.session.QuestFacade#model.session.QuestFacade' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: model.session.QuestFacade#model.session.QuestFacade not found]
    at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:518)
    at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:455)
    at javax.naming.InitialContext.lookup(InitialContext.java:392)
    at javax.naming.InitialContext.lookup(InitialContext.java:392)
    at com.sun.ejb.EjbNamingReferenceManagerImpl.resolveEjbReference(EjbNamingReferenceManagerImpl.java:173)
    ... 74 more
Caused by: javax.naming.NameNotFoundException: model.session.QuestFacade#model.session.QuestFacade not found
    at com.sun.enterprise.naming.impl.TransientContext.doLookup(TransientContext.java:248)
    at com.sun.enterprise.naming.impl.TransientContext.lookup(TransientContext.java:215)
    at com.sun.enterprise.naming.impl.SerialContextProviderImpl.lookup(SerialContextProviderImpl.java:77)
    at com.sun.enterprise.naming.impl.LocalSerialContextProviderImpl.lookup(LocalSerialContextProviderImpl.java:119)
    at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:505)
    ... 78 more

I understand that I'm persuading GlassFish to inject an EJB from a different module within the same application. Should the @Remote interface be used instead? I've also tried to explicitely specify the name for both @Stateless and @EJB annotation but without any success.
I believe that I'm doing something fundamentaly wrong, but I cannot find out what.
Any suggestion or would be greatly appreciated!

A:
I believe that I'm doing something fundamentaly wrong, but I cannot find out what.

What you're doing wrong is that if you implement a business interface (either @Local or @Remote), then you must declare the variable where injection takes place as having the type of that interface, not of the actual bean class.
So in your case:
@Named
@SessionScoped
public class QuestBean implements Serializable {

    @EJB
    protected QuestFacadeLocal questFacade;

    // several methods delegating lookups to the questFacade ...
}

However, a business interface is not required in EJB when you're doing local (in-jvm) communication. As you discovered, if you don't specify a business interface at all for your EJB, you can inject the bean class itself. This is because you then automatically get the so-called no-interface view.
If you want, you can optionally declare that you want BOTH the local view and the no-interface view. In that way, you can inject your bean class in places whether either the bean type itself is declared or its business interface. For this you use the @LocalBean.
@Stateless
@LocalBean
public class QuestFacade extends AbstractFacade<Quest> implements QuestFacadeLocal {
    // some methods here as well as EntityManager injection ...
}

Injection can thus happen in two ways now:
@Named
@SessionScoped
public class QuestBean implements Serializable {

    @EJB
    protected QuestFacadeLocal questFacade; // possible because of local view
    @EJB
    protected QuestFacade questFacadeN; // possible because of no-interface view

    // several methods delegating lookups to the questFacade ...
}

In practice I didn't found much use for having both methods available at the same time though, but maybe this adds to your understanding.

A: Apparently the problem was that I generated @Local session beans. Per this tutorial it is no longer necessary (?) to specify the @Local or @Remote interface. I still not completely understand the problem though.
I Hope this answer could potentialy save up some time to somebody :-)
Jarda


text:
Q: recursion-get sequence of parent folders in .Net using recursion I have a table with the following structure
    ID          Name                                               Parent
----------- -------------------------------------------------- -----------
1           Root                                               NULL
2           Root_A                                             1
3           Root_B                                             1
4           Root_C                                             1
5           Root_C_A                                           4
6           Root_C_A_A                                         5
7           Root_C_A_A_A                                       6

So if I pass 7, I would like to get the following
Root --> Root_C --> Root_C_A --> Root_C_A_A

That means I want to traverse back to root from a child. How can I do it using SQL Server 2008 Stored Procedures or with other .Net techniques ?
I think I can accomplish the task using recursive function

A: You can implement recursion in Sql Server 2005+ using a common table expression. CTEs let you join to themselves in order to recurse. The CTE continues to recurse until no rows are returned, so you'll want to ensure you reliably meet that end condition.
declare @folders as table (id int, name nvarchar(20), parent int);
insert into @folders values(1, 'Root',  null);
insert into @folders values(2, 'Root_A', 1);
insert into @folders values(3, 'Root_B', 1);
insert into @folders values(4, 'Root_C', 1);
insert into @folders values(5, 'Root_C_A', 4);
insert into @folders values(6, 'Root_C_A_A', 5);
insert into @folders values(7, 'Root_C_A_A_A', 6);

declare @folderID int;
set @folderID=7;

with Folders (id, name, parent, number) as
(
    select ID, name, parent, 0 as number
        from @folders
        where id=@folderID
    union all
    select i.ID, i.Name, i.Parent, d.number + 1
        from @folders as i
        inner join Folders as d on d.Parent = i.ID
)
select id, name, number
from Folders
order by number desc;

A: try this:
declare @result varchar(100)
declare @id int
set @id = 7
select @result=Name,@id=Parent from temp where id=@id
while(exists(select 1 from temp where id=@id))
begin
    select @id=Parent,@result=case @result when '' then Name else Name + '-->' end + @result from temp where id=@id
end
select @result


text:
Q: What does the "n copies of type type" mean by OpenGL core profile I'm looking at OpenGL 4.6 core profile. In chapter 23 table 23.12 it writes
Get value                  |    Type     |   Get Command  | Initial value |
TEXTURE_BINDING_BUFFER     |   80* x Z^+ |   GetIntegerv  |      0        |

and table 23.1 explain type code

Z^+ is Non-negative integer or enumerated value
n × type is n copies of type type (n∗ indicates n is minimum)

But OpenGL 4 Reference Pages writes glGetIntegerv will return a single value for this enumerator. It seems like that type 80 x Z^+ or Z^+ makes no difference. So I think I do not quite understand the table 23.1's explanation about "n x type", can anyone explain this for me? Thanks.

A: The state vector for this get enumerator consists of 80* values. However, an individual glGetIntegerv for this enumerator only returns one of those values. Specifically, the one for the currently active texture unit, as defined by a call to glActiveTexture.
The specification defines how this works in section 22.5. You can also use glGetIntegeri_v to select from a specific texture unit, as also specified in 22.5.
Basically, you can't just use the state table to know how a particular get call works.


text:
Q: Using hyperref package with index, pdf vs. manuscript pages I am using the hyperref package with the following options:
  \usepackage[breaklinks=true,
              hypertexnames=false,
              linktocpage,
              plainpages=false,
              pdfpagelabels]{hyperref}

I need to select hypertexnames=false, as otherwise links to theorems, definitions, etc., go to the wrong chapter.  (I.e., a link to Theorem 1.9 might go to Theorem 8.9).
However, if I select hypertexnames=false, the links in my index go to the pdf page--and not the book page (which, due to front matter, may be more than a 10 page difference).  I.e., if I select in the index "Topic X p. 312" it m

A: You'll need to provide more of a minimal working example to show the problem. With the following (admittedly different from your preamble), I don't see the problem:
\documentclass{book}
\usepackage{hyperref}
\usepackage[thref,hyperref]{ntheorem}
\newtheorem{theorem}{Theorem}[chapter]

\begin{document}

\frontmatter
\tableofcontents

\addtheoremline*{example}{\vspace{\baselineskip}\hspace{-\leftmargini}\bfseries{List of theorems}}
\listtheorems{theorem}

\mainmatter
\chapter{One}
Here's a theorem:
\begin{theorem}[First Theorem]\label{one}
Something in the first theorem
\end{theorem}

As seen in \thref{one} but not in \thref{two}, \ldots

\chapter{Two}
Here's another theorem:
\begin{theorem}[Second Theorem]\label{two}
Something in the second theorem
\end{theorem}

As seen in \thref{two} but not in \thref{one}, \ldots

\end{document}

I don't know about making an index of theorems, but the list of theorems I have there has correct page numbers and links.


text:
Q: Segemented Bar listing dynamic I'm new to flutter I have been doing segemented bar, for time being I have done the static code and looking to do dynamic I'm facing issue while doing listing to dynamic, Below code is written.
     import 'dart:async';
    import 'dart:convert';
    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    import 'package:westerAf/paymentPage.dart';
    import 'package:http/http.dart' as http;

    class EventsPage extends StatefulWidget {
      @override
      EventsPageState createState() => new EventsPageState();
    }

    class EventsPageState extends State<EventsPage> {
      List data = List();

      String url = 'https://d57b9120.ngrok.io/api/events/westernaf/packages';
      Future<String> makeRequest() async {
        var response = await http
            .get(Uri.encodeFull(url), headers: {"Accept": "application/json"});

        setState(() {
          var extractdata = json.decode(response.body);
          data = extractdata["result"];
        });
      }

      int theirGroupValue = 0;

      final Map<int, Widget> logoWidgets = const <int, Widget>{
        0: Text('Early Bird'),
        1: Text('General'),
        2: Text('Onsite'),
      };

      static Widget giveCenter(String ListView) {
        return Container(
          child: Text(
            "Text: $ListView",
            style: TextStyle(color: Colors.blue, fontSize: 20.0),
          ),
        );
      }

     @override
  void initState() {
   super.initState();
    this.makeRequest();
  }

      List<Widget> bodies = [
        new ListView.builder(
          itemCount: data == null ? 0 : data.length,
          itemBuilder: (BuildContext context, i) {
            return new ListTile(
              title: new Text(data[i]["package"]),
              subtitle: new Text(data[i]["packageName"].toString()),
            );
          },
        ),
      ];

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: bodies[theirGroupValue],
          appBar: AppBar(
            elevation: 2.0,
            backgroundColor: Colors.white,
            centerTitle: true,
            title: Text(
              'title',
              style: TextStyle(color: Colors.black),
            ),
            bottom: PreferredSize(
              preferredSize: Size(double.infinity, 45.0),
              child: Padding(
                padding: EdgeInsets.only(top: 5.0, bottom: 10.0),
                child: Row(
                  children: <Widget>[
                    SizedBox(
                      width: 15.0,
                    ),
                    Expanded(
                      child: CupertinoSegmentedControl(
                        groupValue: theirGroupValue,
                        onValueChanged: (changeFromGroupValue) {
                          setState(() {
                            theirGroupValue = changeFromGroupValue;
                          });
                        },
                        children: logoWidgets,
                      ),
                    )
                  ],
                ),
              ),
            ),
          ),
        );
      }
    }

and below code I'm trying to do dynamic. I have the http get request data. here data has the list of information and data getting error. I don't know how to do dynamic. please help me to figure out where I went wrong.
List<Widget> bodies = [
    new ListView.builder(
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (BuildContext context, i) {
        return new ListTile(
          title: new Text(data[i]["package"]),
          subtitle: new Text(data[i]["packageName"].toString() +
              ' ' +
              " price: " +
              data[i]["price"].toString()),
        );
      },
    ),
  ];

error

here data is showing in red color, saying that only static member can access init

A: 1) Change
@override
  void initState() {
    this.makeRequest();
  }

to
@override
  void initState() {
   super.initState();
    this.makeRequest();
  }

Why?
initState() is a method called the first time a stateful widget is inserted in the widget-tree.
super.initState() forwards to the default implementation of the State<T> base class of your widget. You can't miss it in initState method.
2) Change
List data;
to
List data = List();
Why?
To tell the framework that the list is not fixed. Otherwise it will assume that your list is null, since you have have not assigned any default value to it.
Rest of the code seems fine, it should work. Let us know in comments if it still doesn't work.


text:
Q: Port knocking: Hide UDP port from scanners I am interested in using port knocking to strengthen security of a private server on the internet.
I was unhappy with implementations that most commonly shows up on the internet (where a sequence of ports are tried) because they're vulnerable to sniffing attacks. I thought about implementing a dynamic sequence based on time/secrets.
I then stumbled upon Tumbler which does mostly what I want.
The only problem is that it now runs a service that is not even as secure as SSH itself and which is just as discoverable. This article recommends setting up a firewall rule that DROPs all other incoming UDP packets instead of REJECTing so that UDP port scanners think ALL ports are open (and take very long). I think that's bad practice.
Instead, I'd like to ACCEPT the packets on the Tumbler port but still send the ICMP port unreachable message so that it looks like the port is closed. How can I do this? I can't see a way with iptables.
One could argue that if that's possible then knocking isn't even required. That is true for protecting simple port scanners but not for protection against SSH connection attempts to random ports.
In summary, what I'd like is (for example):
1 Tumbler or similar listening (UDP 5678)
2 sshd listening on (TCP 5679)
3 IPTABLES ACCEPT packets to (UDP 5678) but still send ICMP unreachable port (thus UDP 5678 looks closed/uninteresting to scanners)
4 IPTABLES REJECT all others
5 On successful knock to Tumbler (which remains silent), IPTABLES to ACCEPT connections to SSH (Tumbler does this anyway)
How do I do point 3?
Thanks!

A: You won't be able to implement this on application level (i.e. by using Tumbler). It has to be done in the iptables itself, by using the pknock match from xtables-addons kernel extension. They also support secure cryptographic SPA (single packet authorization) over single UDP port, so if you got access to your kernel they are preferable to tumbler or anything on application level.
Build it and add to your kernel by googling the guide for your OS.
https://www.howtoforge.com/xtables-addons-on-centos-6-and-iptables-geoip-filtering - for example this one for CentOS 6...


text:
Q: In Entity Framework, getting the value of an identity column after inserting I'm using EF4. I want to insert a new MyObject into the database. MyObject has two fields:
Id:   int (Identity) and
Name: string
As I've seen in documentation Entity Framework is supposed to set MyObject.Id to the value generated by database after the call to SaveChanges() but in my case that doesn't happen.
using (var context = new MyEntities())
{
    var myObject = MyObjects.CreateMyObject(0, "something"); // The first parameter is identity "Id"
    context.MyObjects.AddObject(myObject);
    context.SaveChanges();
    return myObject.Id; // The returned value is 0
}

UPDATE:
This happens in one of my entities and others work fine. By the way, I checked and the DB column is identity and StoreGeneratedPattern is set to Identity.
Here is the SSDL. I don't see any difference. The first one isn't working right:
    <EntityType Name="OrgUnit">
      <Key>
        <PropertyRef Name="Srl" />
      </Key>
      <Property Name="Srl" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
      <Property Name="TypeId" Type="smallint" Nullable="false" />
      <Property Name="Name" Type="varchar" Nullable="false" MaxLength="80" />
    </EntityType>

    <EntityType Name="OrgType">
      <Key>
        <PropertyRef Name="Srl" />
      </Key>
      <Property Name="Srl" Type="smallint" Nullable="false" StoreGeneratedPattern="Identity" />
      <Property Name="Title" Type="varchar" Nullable="false" MaxLength="120" />
      <Property Name="Options" Type="int" Nullable="false" />
    </EntityType>

The update is done successfully in the database and the identity is generated but the entity object is not updated with the new identity.

A: If you're using Oracle Entity Framework 4 Provider, like I do, from ODP.NET, there is a bug in Designer. Just selecting the Identity value in drop down box will not do. It will annotate the conceptual property in conceptual model with

annotation:StoreGeneratedPattern="Identity"

like in
<Property Type="Int32" Name="Id" Nullable="false" cg:SetterAccess="Private" annotation:StoreGeneratedPattern="Identity" />

But, it will fail to do the same for Storage Model, ie. you need to do it manually. Find the Property (in my case ID) in EntityType of interest and add StoreGeneratedPattern="Identity".
    <EntityType Name="PROBLEMI">
      <Key>
        <PropertyRef Name="ID" />
      </Key>
      <Property Name="ID" Type="number" Nullable="false" Precision="10" StoreGeneratedPattern="Identity" />

I'm not aware of the same bug in SQL EF provider 'cos I didn't use it.

A: This should "just work." Make sure the DB column actually is IDENTITY, and that StoreGeneratedPattern is set to Identity in EDMX.

A: wow! that was a nightmare but at last I solved it, although I didn't understand what the problem was. Maybe this helps someone with the same problem.

*

*Generate the script for creating the table and its data.

*Drop the table.

*Run the script.

A: If you are using Linq To Entities, and get this error even if you followed the advices of marc_s (that are really good), you should look at your entites directly in the edmx (xml view) and check if they have the following attribute :
    <EntityType Name="MyEntity">
      <Key>
        <PropertyRef Name="pk" />
      </Key>
      <Property Name="pk" Type="bigint" Nullable="false" StoreGeneratedPattern="Identity" />
      <Property Name="value" Type="float" Nullable="false" />
    </EntityType>

The StoreGeneratedPattern="Identity" is also required.

A: In that case, you EF model is probably not up to date - EF should automagically get your new ID from the database. Try refreshing your EF model.
Your identity column's properties should look like this in your EDMX model:

A: Try using refresh method after Save Changes, it has been documented in MSDN
"To ensure that objects on the client have been updated by data source-side logic, you can call the Refresh method with the StoreWins value after you call SaveChanges."
http://msdn.microsoft.com/en-us/library/bb336792.aspx
Though i feel what @Craig has suggested might also work.

A: I ran into this today. The difference though was I was using an insert function, where the above person doesn't specify that. What I had to do was make my insert function stored procedure return SCOPE_IDENTITY() and use a result binding for the id returned.
Fixed my issue.


text:
Q: java gui mysql query for different buttons For school I'm working on a program that connects to a MySQL database and perform queries such as an ATM machine might.
So far I've made a simple program where I've been putting my connection code in the submit button, but now I need to support many different buttons for balance query, withdrawal, etc.
For my initial screen where the user enters their login and PIN I have the following code, but I'm kind of lost as to how I can do these queries under other buttons with the variables I have in this button:
private void bSubmitActionPerformed(java.awt.event.ActionEvent evt) {
    String login = jLogin.getText();
    String pin = jPin.getText();

    try {
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/bankaccount", "root", "password");

        Statement st = (Statement) con.createStatement();
        PreparedStatement ps;
        String sqlCommand;
        ResultSet rs;

        sqlCommand = "SELECT * FROM accounts WHERE loginID= '" + login + "' AND pin='" + pin + "'";

        rs = st.executeQuery(sqlCommand);

        if (rs.next()) {

            do {

                card2.setVisible(true);
                card1.setVisible(false);

            } while (rs.next());
        } else {
            jWarning.setText("please try again");
        }

    } catch (Exception e) {
    }
}

A:     public ResultSet execute(String sqlCommand ){

    ResultSet rs = null;

    try {
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/bankaccount", "root", "password");

        Statement st = (Statement) con.createStatement();
        PreparedStatement ps;

        rs = st.executeQuery(sqlCommand);

    } catch (Exception e) {
    }

    return rs;

}

public void submitButton1(){
     String login = jLogin.getText();
    String pin = jPin.getText();

ResultSet rs = execute("SELECT * FROM accounts WHERE loginID= '" + login + "' AND pin='" + pin + "'");

   /// do whatever with your rs

}

public void submitButton2(){
     String login = jLogin.getText();
    String pin = jPin.getText();

ResultSet rs = execute("more sql");

   /// do whatever with your rs

}

appending the update method:
public int update(String sqlCommand ){

       int affected_rows = 0;
        try {
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost/bankaccount", "root", "password");

            Statement st = (Statement) con.createStatement();

            affected_rows = st.executeUpdate(sqlCommand);

        } catch (Exception e) {
        }

        return affected_rows;

    }

The update method also can be used to insert and delete. An update statament could be something like this:
update accounts
set columnA = "a value",
columnB = "other value"
where loginID = 4;


text:
Q: Windows Phone 8.1 ScrollViewer disable overscroll effect How to disable overscroll effects of ScrollViewer for Windows Phone 8.1? And how to disable overzoom/overpinch effect?

A: Unfortunately this effect is inherent to the ScrollViewer behaviour and is made by design, so that there is no easy and fast method to do this, if any.
I would recommend you follow the same design guidelines as this will create a consistent user experience.


text:
Q: Visual Studio Test Run can't load test There is a problem with Visual Studio 2010 test runner. Today I've loaded test results from night build on build server. Exproted this results to *.trx file, removeed from it information about test agent to run test localy. And than imported this file to VS Test Result window. After try of run failed tested, I received message One or more tests could not be found and message Test ... has not been loaded and cannot be added to the test run.
What does it mean? What is the problem?
I've created my project with tests like Class Library Project, not like Test Project. Can it be a reason of error?
PS. I tryed to add image with this error, but I need more reputation.
I can upload image to external resource, if it'll be able to help to solve my problem.

A: Yes you are right.
If you use MsTest and want to use Visual Studio 2010 test runner, your tests should be placed into a project created like Test Project.
There is a discussion on MSDN Forum on converting project to Test Project.
I suggest you to create new Test Project.
It is the easiest solution.
Otherwise you have to edit *.csproj file and add Guid {3AC096D0-A1C2-E12C-1390-A8335801FDAB} inside ProjectTypeGuids.
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

A: Create new project and cut and paste files in new project
restart VS


text:
Q: my html page says an object i used earlier in my page does not exist im trying to put in the username as a parameter in my link. doing this through jquery the only problem is i get this error,note the object call works for some reason on the span tag. I've been looking at tutorials but to no avail when trying to get the span tags value via $(#emailTarget).attr("id"); and putting said id onto the span tag it gives me the value of undefined rather than the username.
error stack
org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler.handleText(InlinedOutputExpressionMarkupHandler.java:80)
    at org.attoparser.HtmlMarkupHandler.handleText(HtmlMarkupHandler.java:208)
    at org.attoparser.AbstractChainedMarkupHandler.handleText(AbstractChainedMarkupHandler.java:203)
    at org.attoparser.MarkupParser.parseBuffer(MarkupParser.java:557)
    at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:301)
    ... 98 more
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "principal.username" (template: "index" - line 49, col 25)
    at org.thymeleaf.spring5.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:292)
    at org.thymeleaf.standard.expression.VariableExpression.executeVariableExpression(VariableExpression.java:166)
    at org.thymeleaf.standard.expression.SimpleExpression.executeSimple(SimpleExpression.java:66)
    at org.thymeleaf.standard.expression.Expression.execute(Expression.java:109)
    at org.thymeleaf.standard.expression.Expression.execute(Expression.java:138)
    at org.thymeleaf.standard.processor.AbstractStandardExpressionAttributeTagProcessor.doProcess(AbstractStandardExpressionAttributeTagProcessor.java:144)
    at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74)
    at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95)
    at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633)
    at org.thymeleaf.engine.ProcessorTemplateHandler.handleOpenElement(ProcessorTemplateHandler.java:1314)
    at org.thymeleaf.engine.OpenElementTag.beHandled(OpenElementTag.java:205)
    at org.thymeleaf.engine.TemplateModel.process(TemplateModel.java:136)
    at org.thymeleaf.engine.TemplateManager.process(TemplateManager.java:519)
    at org.thymeleaf.util.LazyProcessingCharSequence.writeUnresolved(LazyProcessingCharSequence.java:85)
    at org.thymeleaf.util.AbstractLazyCharSequence.write(AbstractLazyCharSequence.java:103)
    at org.thymeleaf.engine.AbstractTextualTemplateEvent.writeContent(AbstractTextualTemplateEvent.java:224)
    at org.thymeleaf.engine.Text.write(Text.java:78)
    at org.thymeleaf.engine.OutputTemplateHandler.handleText(OutputTemplateHandler.java:71)
    ... 107 more
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'username' cannot be found on null
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:213)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:104)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.access$000(PropertyOrFieldReference.java:51)

my home page
<!DOCTYPE html>

        <meta charset="ISO-8859-1">
        <title>Registration and Login App</title>

        <link rel="stylesheet"
              href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
              integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
              crossorigin="anonymous">

                    <button type="button" class="navbar-toggle collapsed"
                            data-toggle="collapse" data-target="#navbar" aria-expanded="false"
                            aria-controls="navbar">
                        Toggle navigation
                    </button>
                    Registration and
                        Login Module

Logout

Registration and Login with Spring Boot, Spring Security,
                Thymeleaf, Hibernate and MySQL

            Welcome  User

        Delete

my repository url: https://github.com/jonathanIckovich/realtyKing.git

A: If you want to put a parameter in your link, use this: .... This will result in a uri like this: /delete?email=test@example.com.
If you want to substitute a path variable - @{/delete/{email}(email=${#authentication.principal.username})}.
However the problem you're facing seems more like an internal problem that is connected to principal being null (hence the error message) - this might happen because you're logged off. You should probably check for there being a principle (e.g. #authentication.isAuthenticated()) around the link that you're trying to build.


text:
Q: Add JSONArray to map value in Hashmap I am having a JSON Array which I am populating using a JSON object, and the code looks like this
    Map<String, String> orderLines = new HashMap<>();
    orderLines.put("xx",XX);
    orderLines.put("yy",YY);
JSONObject obj=new JSONObject(orderLines);
JSONArray array = new JSONArray().put(obj);

and I am trying to add this array into my map and add it to the
Map<String, Object> customFields = new HashMap<>();
customFields.put("postOrderRequest.orderLines", array);

but when I am building a json out of these map values using
customFields.forEach((k, v) -> json.set(k, v));

, I am not able to build a json out of the map,what I am trying to achieve is something like this
{
    "orderLines" : [{"xx":"XX","yy":"YY"}]
 }

A: You can try this (without any external library - using only Java 8)
    Map<String, Object> customFields = new LinkedHashMap<>();

    List<String> jsonKeyList = List.of("orderLines1", "orderLines2");
    jsonKeyList.forEach(listItem -> orderKeys(listItem, customFields));

    String result = "{" + customFields.entrySet().stream()
                                      .map(e -> "\"" + e.getKey() + "\":" +
                                                String.valueOf(e.getValue()))
                                      .collect(Collectors.joining(", ")) +
                    "}";

    System.out.println("Result: " + result);
}

public static void orderKeys(final String key, final Map<String, Object> result)
{
    JSONArray array = new JSONArray();
    JSONObject item = new JSONObject();
    item.put("xx", "XX");
    item.put("yy", "YY");
    array.put(item);

    result.put(key, array);
}

Output:
Result: {"orderLines1":[{"xx":"XX","yy":"YY"}], "orderLines2":[{"xx":"XX","yy":"YY"}]}

Else you can use external libraries for your usecase (viz. Underscore-java - library to convert hash map or array list to json and vice versa).
Courtesy:
StackOverflow


text:
Q: Changing a for loop to a while loop, average of dice rolls Can anyone help me write this function as a while loop instead of a for loop?
function RollAverage(){
  //assumes: outputDiv is available for output
  //results: counts rolls and averages them
  var userNum,countTotal,rollSum;
  userNum=parseFloat(document.getElementById('textBox').value);
  countTotal=0;
  for (rollSum=0; countTotal<userNum; countTotal=countTotal++){
    rollSum=rollSum+(RandomInt(1,6) + RandomInt(1,6));
    countTotal++;
  }
  document.getElementById('outputDiv').innerHTML='Heres the average ' +(rollSum/countTotal);
}

A: Are you using any specific library for RandomInt() ? I have used instead
Math.floor(Math.random(1,6) and modified the code for while loop as below:
function RollAverage(){
var userNum,countTotal,rollSum;
userNum=parseFloat(document.getElementById('textone').value);
countTotal=0;
rollSum=0;
while (countTotal < userNum){
 rollSum = rollSum + (Math.floor(Math.random(1,6) + Math.random(1,6)));
    countTotal++;
 }
document.getElementById('myDivId').innerHTML =(rollSum/countTotal);
}

Full working jsfiddle code here


text:
Q: Howto print (JavaPos Printer) with Java Jar App on Linux (Xubuntu 16.04 ) without sudo I am trying to figure out a way how to start my jar app within Xubuntu without having to open a terminal and typing sudo java -jar
In case I don't do it through the terminal, my app will start but won't connect to the JavaPos Thermal Printer; as a result, I cannot print.
Hope someone among you could assist me in this matter.


text:
Q: What are the advantages of Lua over other scripting languages for a TeX implementation? The question is inspired by Martin Schröder's answer to I am new to TeX. Should I use LaTeX, XeLaTeX, …? as well as my two previous questions on this forum:

*

*Automatic document update

*Generate LaTeX Truth Table with Python Cheetah
In retrospect, I am truly surprised that no LuaTeX user offered any answers to my questions as it seems to me that that could be easily done in LuaTeX by embedding Lua scripts into the LaTeX code. Can it be really done (question for LuaTeX users only) and is it easy?
My second question is motivated by the fact that I hate very thought of having to learn another scripting/general programming language (Lua) if I already know Python (you can substitute Perl if you like) just to use it with TeX. Is anybody cooking a Python interface for TeX call it PythonTeX for short
(PerlTeX actually does exist)? As far as I know PythonTeX doesn't exist. There is something called PyTeX but that just look like a tool for people who want to type TeX documents using Python syntax.
Is there an advantage of using Lua over Python as an embedded scripting language for TeX (apart of the fact that people who started LuaTeX probably were more familiar with Lua)?

A: Actually, a good way to use Python code into (plain) TeX code is:

*

*for the typesetting work (boxes, glue and penalties) use only TeX;

*for calculation, databases interface and so on you can build Python modules that you can call from the TeX program via \write18. The Python modules have to leave the output into files that have to be read via the usual \newread and then used into the TeX code.
This solution work best on Linux, as far as on Linux Python is natively installed.

As an example try this:
prepare the module `adder.py' this way:
#!/usr/bin/env python
# file 'adder.py'

import sys

def save(data):
    tempFile = open("temp.dat","w")
    tempFile.write(str(data))
    tempFile.close()

def double(x):
    result = x * 2
    save(result)

if __name__ == "__main__":
    n = int(sys.argv[1])
    double(n)
    sys.exit

now, in the same directory, you can type a TeX file like this:
% file `doubler.tex'
\newread\tempfile
%
\def\double#1{%
    \immediate\write18{python adder.py #1}\relax
    \immediate\openin\tempfile=temp.dat
    \read\tempfile to \var
    \var}%
%
Double 2 is \double2\par
Double 3 is \double3\par
Double 4 is \double4\par
Double 5 is \double5\par
Double 6 is \double6\par
\bye

This TeX file has to be compiled with shell-escape, e.g.:
tex -shell-escape doubler

pdftex -shell-escape doubler

xetex -shell-escape doubler

A: I think that the pdfTeX community analyzed the situation correctly when they chose Lua.
Lua is intended to be embedded into other applications, and it provides a robust, easy to use C API.  The Lua API is straightforward and its design eliminates the need for manual reference management in C code, unlike Python's API.
Python is an opinionated language controlled by essentially one person and many people, myself included do not favour the significance of whitespace.
Yes, for you it maybe easier to use Python as it would have been easier for me if everyone stayed with the original Pascal code. Pascal would have provided everything one needed, it is a beautiful language and everyone is almost using it daily via pseudo-code and it would have provided a good way to migrate TeX to a new generation.
If there is any merit to suggest another language, I would recommend JavaScript. It is gaining in popularity via the web and easy to learn. The maths part of it has already been written, at least for browsers. It also provides full unicode support.

A: Pweave
Much like the original poster, I also do regret the absence of a LaTeX interpreter capable of directly interpreting Python code.
Since PythonTeX got mentioned here in one of the other answers, I also would like to call your attention to Pweave. It is easier to use than PythonTex and also offers a couple more environment options.
Compiling a document that uses PythonTeX involves three steps: run latex, run pythontex.py, and finally run latex again. Pweave only needs two steps: run Pweave, then run pdflatex.
I got started with Pweave by reading a concise but excellent introductory article.
You will also find my minimal working example over here on tex.StackExchange.
I have also posted an easier example involving currency notations and demonstrating the power of locales, Python and Pweave over here.
EDIT:
$ Pweave -l

Pweave supported output formats:

*

*sphinx: reStructuredText for Sphinx

*pandoc: Pandoc markdown

*tex: Latex with verbatim for code and results

*html: HTML with pygments highlighting

*rst: reStructuredText

*texpweave: Latex output with user defined formatting using named environments (in latex header)

*texminted: Latex with predefined minted environment for codeblocks

More info: http://mpastell.com/pweave/formats.html

A: I have been coding "PythonTeX" since last May, and am planning the first public release sometime between next weekend and the beginning of March.  I'm actually planning to call it PythonTeX, by analogy to PerlTeX and SageTeX.
I've created a LaTeX package, and accompanying Python scripts, that provide most functionality of python.sty, SageTeX, and SympyTeX, but with emphasis on speed and usability.  Here's a brief summary of what PythonTeX will bring.

*

*Persistence between commands and environments.  For example, each environment \begin{pythoncode} ... \end{pythoncode} picks up where the last left off, so all variables, functions, etc. persist.  You can optionally name commands and environments, and then there is only persistence between commands and environments with the same name.  For example, \begin{pythoncode}[name] ... \end{pythoncode} only shares persistence with other commands and environments called name.

*Automatic inclusion of printed content.  For example,
\begin{pythoncode}
print(1+1)
\end{pythoncode}

is automatically replaced by 2 in the compiled document.

*Speed.  Each set of named commands and environments is executed in its own process, using Python's multiprocessing package.  Also, each set is hashed, so code is only executed when changed.  The results of running the code are saved, and reused when no changes are detected.

*Code typesetting.  All code that is executed can also be typeset, using fancyvrb and its internals.  Optionally, code can be typeset using Pygments, which is a Python package that does syntax highlighting (Pygments is used by the minted package).  When Pygments is used, all code is hashed and the typeset results are saved, so that only changed code must be processed by Pygments in subsequent runs.  This helps prevent Pygments from slowing things down.

*Meaningful error messages.  All error messages are parsed by code that determines the line of your document where the error occurred (as opposed to the line of the *.py file that is actually executed).  So you know exactly where things went wrong in your document.

*Minimal files.  The code cleans up after itself, so the number of permanent files created by Python is kept to a minimum and all temporary files are deleted after each run.
I can post a link as soon as PythonTeX is released.  I will also be submitting it to CTAN shortly after the first public release.

A: The LuaTeX developers have commented on their choice of Lua over other languages, including Python, on their home page.
Embedding the interpreter is one thing, and apparently no fun with Python. Another is to actually make the innards of TeX visible to the embedded interpreter. While much of the communication code could likely be adapted in some way from LuaTeX to PythonTeX, it will still be a lot of work.
A better approach may be to cheat a bit, and simply piggyback on the LuaTeX interpreter. There is a bridge that 'embeds' Python inside Lua called Lunatic Python, and maybe it can be made to work with LuaTeX also. However, it may be easier to just use XML-RPC: Let LuaTeX spawn a Python process, which acts as the XML-RPC server. LuaTeX commands can then make calls to the Python process. Bonus feature: Once this is implemented on the LuaTeX side, it can be used with any other scripting language, not just Python.

A: Here is a way to call into a persistent Python process from LuaTeX via JSON-RPC. 1)
Required setup:

*

*Download and install jsonrpclib.
This provides the Python server.

*Download a Lua json-rpc client. I adapted some Lua modules I found on the web and zipped them up and put them on my server. Unzip into one of the directories specified in this answer:
"Lua tree" (analogue of texmf tree)
Now, we can write a Python server that exposes some functions:
import sys
from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer

server = SimpleJSONRPCServer(('localhost', 8080))

server.register_function(lambda: "Hello from Python!", 'ping')
server.register_function(lambda *args: sum(args), 'add')

# the counter generator shows that the server can be used
# to preserve state between requests, and even across multiple
# LaTeX compiler runs (which we may not want)
counter = iter(xrange(sys.maxint))
server.register_function(lambda: counter.next(), 'count')

server.serve_forever()

Save this as testserver.py and run.
Here is test document that shows how to call the server:
\documentclass{article}

\directlua{ % make the running python server available as a proxy
    require "jsonrpc"
    pythonserver = jsonrpc.proxy("http://localhost:8080")
}

\newcommand{\python}[2][]{\directlua{%
    result = pythonserver.#2(#1)
    tex.print(result)
}}

\begin{document}

\python{ping}

The sum of 1,2,3,4,5,6,2,4,5,6 is \python[1,2,3,4,5,6,2,4,5,6]{add}

\directlua{%
    for x=0,100,1 do
        result = pythonserver.count()
        tex.print(result)
    end
}

\end{document}

Addressing the original question about how to implement pythontex, all that would
be required now is a shell script that first starts the server, then calls LuaTeX,
and then shuts down the server again. This is left as an exercise to the reader ;)
1) The reason why I used JSON-RPC instead of XML-RPC is that I couldn't find a Lua-only XML-RPC client; the one client that I did find used a C extension library, and I and couldn't figure out how to load that into LuaTeX (blush). The JSON-RPC modules were simpler, and after some kicking and screaming (on my part) could be persuaded to cooperate. Maybe someday I can figure out how to make XML-RPC work also.

A: My take is: Lua as a language was created as an embedded language and is well suited for the job. Now that with LuaTeX a scriptable TeX implementation exists, there is little principled reason to create another one. Of course, you can go ahead and create PythonTeX. But it seems that the community feels that this would not add enough value over LuaTeX to justify the cost.


text:
Q: Is it possible to set button state with dynamic name call using getattr and dictionary keys (Python 2.7, Tkinter)? I'm building a python Tkinter GUI program containing buttons which will be enabled/disabled depending on various situations.
For this reason, I want to refer to buttons dynamically rather than using static names. I've built a global dictionary that links button string descriptors to a Boolean value indicating their desired state (populated during widget creation, and dict values altered as required throughout the program), and another dictionary inside a function linking the same string descriptors to the button object names.
Since I wish to change button states dynamically, the object names aren't hardcoded, instead I'm trying to use getattr with a function call returning the object name using the dictionary function described above:
    class WApplication(Frame):

        buttonStates={}

...

        def buttonDisable(self):
            for i in self.buttonStates:
                #self.Load_Manifest.config(state=DISABLED)   #This line works (i.e., visibly disables the 'Load Manifest' button)
                #print(i+".config(state=DISABLED)")          #Output: Load_Manifest.config(state=DISABLED)
                getattr(self.ObjectDictionary(i),"config(state=DISABLED)")   #AttributeError: Button instance has no attribute 'config(state=DISABLED)'

        def buttonEnable(self):   #Similar error encountered as above when debugging this function
            for i in self.buttonStates:
                if self.buttonStates[i]==True:
                    getattr(self.ObjectDictionary(i),"config(state=NORMAL)")

...

        def ObjectDictionary(self,string):
            "Function that maps dictionary widget keys to their object titles and returns the mapped object title"
            switcher={
                "Load_Manifest":self.Load_Manifest,
                "Update_Manifest":self.Update_Manifest,
                "Fresh_Manifest":self.Fresh_Manifest,
                "Manifest_Details":self.Manifest_Details
            }
            return switcher.get(string)

...

        def createWidgets(self):
            self.QUIT = Button(self.master)
            self.QUIT["text"] = "QUIT"
            self.QUIT["fg"]   = "red"
            self.QUIT["command"] =  self.quit
            self.QUIT.place(x=710,y=10,height=50,width=100)

            self.Load_Manifest=Button(self.master)
            self.Load_Manifest["text"]="Load Manifest"
            self.Load_Manifest["command"]=self.LoadManifestButton
            self.Load_Manifest.config(state=NORMAL)
            self.Load_Manifest.place(x=10,y=10,height=50,width=110)
            self.buttonStates["Load_Manifest"]=True
            self.buttonActions["Load_Manifest"]=False

            self.Update_Manifest=Button(self.master)
            self.Update_Manifest["text"]="Update Manifest"
            self.Update_Manifest["command"]=self.UpdateManifestButton
            self.Update_Manifest.config(state=DISABLED)
            self.Update_Manifest.place(x=130,y=10,height=50,width=120)
            self.buttonStates["Update_Manifest"]=False
            self.buttonActions["Update_Manifest"]=False

            self.Fresh_Manifest=Button(self.master)
            self.Fresh_Manifest["text"]="Create New Manifest"
            self.Fresh_Manifest["command"]=self.FreshManifestWindowButton
            self.Fresh_Manifest.config(state=NORMAL)
            self.Fresh_Manifest.place(x=260,y=10,height=50,width=150)
            self.buttonStates["Fresh_Manifest"]=True
            self.buttonActions["Fresh_Manifest"]=False

...

            self.Manifest_Details=Button(self.master)
            self.Manifest_Details["text"]="Details"
            self.Manifest_Details["command"]=self.ManifestDetailsButton
            self.Manifest_Details.config(state=DISABLED)
            self.Manifest_Details.place(x=10,y=790,height=50,width=100)
            self.buttonStates["Manifest_Details"]=False
            self.buttonActions["Manifest_Details"]=False

...

The buttonDisable and buttonEnable functions are called elsewhere in the program in other functions that are run during button presses. I could just stick to hardcoded widget names and put a load of if statements in my buttonEnable function since there may only be four buttons currently, but I plan on expanding the program adding more with additional buttons, and I wish to disable all buttons during an operation to avoid user entry when the program is busy, so therefore dynamic calls are desired.
During the first call of getattr(self.ObjectDictionary(i),"config(state=DISABLED)") an error is raised:
AttributeError: Button instance has no attribute 'config(state=DISABLED)'

But I would have thought .config() is an attribute of a widget object? And the following hardcoded substitute line self.Load_Manifest.config(state=DISABLED) works as intended, which by my understanding of getattr should be equivalent?

A:
I would have thought .config() is an attribute of a widget object?

Yes, config is an attribute of a widget object. However, the string "config(state=DISABLED)" is not an attribute of a widget object.
If you want to call the configure method of a widget stored in a dictionary, you do it exactly like you would if the widget was a regular variable. The following example breaks it down into two steps to illustrate the point:
widget = ObjectDictionary(i)
widget.configure(state=DISABLED)


text:
Q: Long strings in data statements I'd like to initialize a long string in Fortran 77 in a DATA statement, like this:
      DATA Lipsum /
     *'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendi
     *sse tincidunt, velit id hendrerit bibendum, erat nisl dignissim ar
     *cu'/

but the internal policy of the program I'm contributing to does not like it as it prohibits lines with an odd number of quote marks.
I can "fool" the policy checker by using double quotes instead, or using ' as the continuation character (in the first and last line), but I'd like to know if there is some other way to have long strings in DATA statements, where the concatenation operator // does not seem to be allowed.

A: one approach is to declare an array of short strings and equivalence to your long one:
character*63 cshort(3)/
     *'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspen',
     *'disse tincidunt, velit id hendrerit bibendum, erat nisl digniss',
     *'im arcu'/
character*180 clong
equivalence (cshort,clong)

For this to work you need to count the characters and be sure each line
but the last has the exact length of the short string.  Note 63 is the max string length that will fit in 72 columns along with the quotes and comma.

A: There is a throwback to a bygone era present in gfortran. Other compilers may have it too, I haven't checked.
For long strings, put an ampersand at column 73 of any continued line, and with ampersand always used in column 6 (columns 1-5 are reserved for labels) for starting a continuation line.
Here is a code snippet showing a long string of digits:
character (*), parameter :: &
p = '31415926535897932384626433832795028841971693993751058209749445923&
   &078164062862089986280348253421170679821480865132823066470938446095&
   &50582231725359408128481117450284102701938521105559644622948954930'


text:
Q: Loop through object in jquery I am trying to understanding Jquery and I am having problems to append values from a array.
I have created the object below with:
var obj = [];

I put it trough a loop pushing data:
 obj.push({
     name: name,
     address: address,
     comment: comment,
     distance: distance,
     duration: duration,
     lat: lat,
     lng: lat,
     count: count,
     order: order
 });

My console.log(obj):
0: Object
address: "Test"
comment: "My comment"
count: 1
distance: "3.3 mi"
duration: "13 mins"
lat: "44.971424"
lng: "44.971424"
name: "My House"
order: "3.3"

1 : Object
2 : Object
3 : Object
4 : Object
5 : Object

My question is:
How can I append to a div?
$("#div_result").each(obj, function(){
    // ??
    // This is not working for me.
});

A: If you want to append values from your object to a DIV, you can try the following code.
$.each(obj, function( index, value ) {
    $("#div_result").append(index + ' and ' + value );
});

Let me know if that works.

A: $.each(obj, function( index, value ) {
    console.log(value.address);
    console.log(value.comment);
    .... and so on.....
});


text:
Q: Nearest multiple of a power of two fraction Is there an optimized, performant way to round a double to the exact value nearest multiple of a given power of two fraction?
In other words, round .44 to the nearest 1/16 (in other words, to a value that can be expressed as n/16 where n is an integer) would be .4375. Note: this is relevant because power of two fractions can be stored without rounding errors, e.g.
public class PowerOfTwo {
  public static void main(String... args) {
    double inexact = .44;
    double exact = .4375;

    System.out.println(inexact + ":   " + Long.toBinaryString(Double.doubleToLongBits(inexact)));
    System.out.println(exact + ": " + Long.toBinaryString(Double.doubleToLongBits(exact)));
  }
}

Output:
0.44:   11111111011100001010001111010111000010100011110101110000101001
0.4375: 11111111011100000000000000000000000000000000000000000000000000

A: If you want to chose the power of two, the simplest way is to multiply by e.g. 16, round to nearest integer, then divide by 16. Note that division by a power of two is exact if the result is a normal number. It can cause rounding error for subnormal numbers.
Here is a sample program using this technique:
public class Test {
  public static void main(String[] args) {
    System.out.println(roundToPowerOfTwo(0.44, 2));
    System.out.println(roundToPowerOfTwo(0.44, 3));
    System.out.println(roundToPowerOfTwo(0.44, 4));
    System.out.println(roundToPowerOfTwo(0.44, 5));
    System.out.println(roundToPowerOfTwo(0.44, 6));
    System.out.println(roundToPowerOfTwo(0.44, 7));
    System.out.println(roundToPowerOfTwo(0.44, 8));
  }

  public static double roundToPowerOfTwo(double in, int power) {
    double multiplier = 1 << power;
    return Math.rint(in * multiplier) / multiplier;
  }
}

Output:
0.5
0.5
0.4375
0.4375
0.4375
0.4375
0.44140625

A: If the question is about rounding any number to a pre-determined binary precision, what you need to do is this:

*

*Convert the value to long using 'Double.doubleToLongBits()`

*Examine the exponent: if it's too big (exponent+required precision>51, the number of bits in the significand), you won't be able to do any rounding but you won't have to: the number already satisfies your criteria.

*If on the other hand exponent+required precision<0, the result of the rounding is always 0.

*In any other case, look at the significand and blot out all the bits that are below the exponent+required precisionth significant bit.

*Convert the number back to double using Double.longBitsToDouble()

A: Getting this right in all corner cases is a bit tricky.  If I have to solve such a task, I'd usually start with a naive implementation that I can be pretty sure will be correct and only then start implementing an optimized version.  While doing so, I can always compare against the naive approach to validate my results.
The naive approach is to start with 1 and multiply / divide it with / by 2 until we have bracketed the absolute value of the input.  Then, we'll output the nearer of the boundaries.  It's actually a bit more complicated: If the value is a NaN or infinity, it requires special treatment.
Here is the code:
public static double getClosestPowerOf2Loop(final double x) {
    final double absx = Math.abs(x);
    double prev = 1.0;
    double next = 1.0;
    if (Double.isInfinite(x) || Double.isNaN(x)) {
        return x;
    } else if (absx < 1.0) {
        do {
            prev = next;
            next /= 2.0;
        } while (next > absx);
    } else if (absx > 1.0) {
        do {
            prev = next;
            next *= 2.0;
        } while (next < absx);
    }
    if (x < 0.0) {
        prev = -prev;
        next = -next;
    }
    return (Math.abs(next - x) < Math.abs(prev - x)) ? next : prev;
}

I hope the code will be clear without further explanation.  Since Java 8, you can use !Double.isFinite(x) as a replacement for Double.isInfinite(x) || Double.isNaN(x).
Let's see for an optimized version.  As other answers have already suggested, we should probably look at the bit representation.  Java requires floating point values to be represented using IEE 754.  In that format, numbers in double (64 bit) precision are represented as

*

*1 bit sign,

*11 bits exponent and

*52 bits mantissa.

We will special-case NaNs and infinities (which are represented by special bit patterns) again.  However, there is yet another exception: The most significant bit of the mantissa is implicitly 1 and not found in the bit pattern – except for very small numbers where a so-called subnormal representation us used where the most significant digit is not the most significant bit of the mantissa.  Therefore, for normal numbers we will simply set the mantissa's bits to all 0 but for subnormals, we convert it to a number where none but the most significant 1 bit is preserved.  This procedure always rounds towards zero so to get the other bound, we simply multiply by 2.
Let's see how this all works together:
public static double getClosestPowerOf2Bits(final double x) {
    if (Double.isInfinite(x) || Double.isNaN(x)) {
        return x;
    } else {
        final long bits = Double.doubleToLongBits(x);
        final long signexp = bits  & 0xfff0000000000000L;
        final long mantissa = bits & 0x000fffffffffffffL;
        final long mantissaPrev = Math.abs(x) < Double.MIN_NORMAL
            ? Long.highestOneBit(mantissa)
            : 0x0000000000000000L;
        final double prev = Double.longBitsToDouble(signexp | mantissaPrev);
        final double next = 2.0 * prev;
        return (Math.abs(next - x) < Math.abs(prev - x)) ? next : prev;
    }
}

I'm note entirely sure I have covered all corner cases but the following tests do run:
public static void main(final String[] args) {
    final double[] values = {
        5.0, 4.1, 3.9, 1.0, 0.0, -0.1, -8.0, -8.1, -7.9,
        0.9 * Double.MIN_NORMAL, -0.9 * Double.MIN_NORMAL,
        Double.NaN, Double.MAX_VALUE, Double.MIN_VALUE,
        Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY,
    };
    for (final double value : values) {
        final double powerL = getClosestPowerOf2Loop(value);
        final double powerB = getClosestPowerOf2Bits(value);
        System.out.printf("%17.10g  -->  %17.10g  %17.10g%n",
                          value, powerL, powerB);
        assert Double.doubleToLongBits(powerL) == Double.doubleToLongBits(powerB);
    }
}

Output:
      5.000000000  -->        4.000000000        4.000000000
      4.100000000  -->        4.000000000        4.000000000
      3.900000000  -->        4.000000000        4.000000000
      1.000000000  -->        1.000000000        1.000000000
      0.000000000  -->        0.000000000        0.000000000
    -0.1000000000  -->      -0.1250000000      -0.1250000000
     -8.000000000  -->       -8.000000000       -8.000000000
     -8.100000000  -->       -8.000000000       -8.000000000
     -7.900000000  -->       -8.000000000       -8.000000000
 2.002566473e-308  -->   2.225073859e-308   2.225073859e-308
-2.002566473e-308  -->  -2.225073859e-308  -2.225073859e-308
              NaN  -->                NaN                NaN
 1.797693135e+308  -->   8.988465674e+307   8.988465674e+307
 4.900000000e-324  -->   4.900000000e-324   4.900000000e-324
        -Infinity  -->          -Infinity          -Infinity
         Infinity  -->           Infinity           Infinity

How about performance?
I have run the following benchmark
public static void main(final String[] args) {
    final Random rand = new Random();
    for (int i = 0; i < 1000000; ++i) {
        final double value = Double.longBitsToDouble(rand.nextLong());
        final double power = getClosestPowerOf2(value);
    }
}

where getClosestPowerOf2 is to be replaced by either getClosestPowerOf2Loop or getClosestPowerOf2Bits.  On my laptop, I get the following results:

*

*getClosestPowerOf2Loop: 2.35 s

*getClosestPowerOf2Bits: 1.80 s

Was that really worth the effort?

A: Here is my first attempt at a solution, that doesn't handle all the cases in @biziclop's answer, and probably does "floor" instead of "round"
public static double round(double d, int precision) {
  double longPart = Math.rint(d);
  double decimalOnly = d - longPart;
  long bits = Double.doubleToLongBits(decimalOnly);

  long mask = -1l << (54 - precision);

  return Double.longBitsToDouble(bits & mask) + longPart;
}

A: You are going to need some bit magic if you are going to round to arbitrary powers of 2.
You will need to inspect the exponent:
int exponent = Math.getExponent(inexact);

Then knowing that there are 53 bits in the mantissa can find the bit at which you need to round with.

Or just do:
Math.round(inexact* (1l<<exponent))/(1l<<exponent)

I use Math.round because I expect it to be optimal for the task as opposed to trying to implement it yourself.

A: I came across this post trying to solve a related problem: how to efficiently find the two powers of two that bracket any given regular real value. Since my program deals in many types beside doubles I needed a general solution. Someone wanting to round to the nearest power of two can get the bracketing values and choose the closest. In my case the general solution required BigDecimals. Here is the trick I used.
For numbers > 1:
            int exponent = myBigDecimal.toBigInteger.bitLength() - 1;
            BigDecimal lowerBound = TWO.pow(exponent);
            BigDecimal upperBound = TWO.pow(exponent+1);

For numbers > 0 and < 1:
            int exponent = -(BigDecimal.ONE.divide(myBigDecimal, myContext).toBigInteger().bitLength()-1);
            BigDecimal lowerBound = TWO.pow(exponent-1);
            BigDecimal upperBound = TWO.pow(exponent);

I have only lined out the positive case. You generally take a number, and use this algorithm on it's absolute value. And then if in the original problem the number was negative you multiply the algorithm's result by -1. Finally the orignal num == 0 or num == 1 are trivial to handle outside this algorithm. That covers the whole real number line except infinties and nans which you deal with before calling this algorithm.


text:
Q: Does activiti allow users to define domain-specific extensions like jBPM? jBPM  allows users to extend the default process constructs with domain-specific extensions as specified in their user guide here. Does anybody know if Activiti supports this?

A: Activiti seems to support it. Supporting documentation here : Extending Activiti Designer section.


text:
Q: taking the Swing UI to next level? i have designed an application using java swing, how to improve the look and feel and User interface?

A: It depends upon your objective.

*

*If you want to go in the desktop way, maybe by using some of Kirill Grouchnikov works : Substance LnF and Flamingo (which emulates the Office ribbon using Swing code)

*If you want to go in the pimp'd direction, take a look at old works of Chet Haase and Romain Guy

A: Perhaps change the look and feel to something more "native": http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html

A: While the question is very vague....I'll provide an obvious quick tip.
Make sure to handle events and/or heavy processing on a background thread.
SwingWorker is now included in the Java 6 JRE/JDK
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

            @Override
            protected Void doInBackground() throws Exception {
            //some task

                return null;
            }

            @Override
            protected void done() {
           //when done
           }

        };

        threadPool.submit(worker);


text:
Q: imported csv to dataframe objects not recognized I have imported multiple csv files from a folder. First I created a list of all the csv files in the folder and then I provide the length of the list to my function.
The csv files have rows with different column lengths so that is why I think I have to use readlines.
The problem is that when I try to filter the DataFrame the values are not recognized.
I saved it to a sqlite table and pulled it in to R and a value that looks like  "H"
appears to be like this in r  ---  "\"H\""
How can I prevent those extra characters from being added to my object "H"
Or do I have another problem?
x = []
count = 0
while (count < len(filelist) ):
    for file in  filelist:
        filename = open(filelist[count])
        count = count + 1
        for line in filename.readlines():
            x.append(line.split(','))

df = pd.DataFrame(x)

For example I am just trying to create a mask. But I am getting all False. The DataFrame appears to contain "H"?
data['V1'] == "H"

A: Try this
df_list =[]
file_list = []
path = 'file_path'
for file in file_list:
    df_name = 'df_%s' %file
    df_list.append(df_name)
    ('df_%s' % file) = pd.read_csv(path+file)

new_df = pd.concat(df_list)

A: Answer: This code fixed the problem by removing the quotes throughout. Now the mask works.
for i, col in enumerate(df.columns):
    df.iloc[:, i] = df.iloc[:, i].str.replace('"', '')


text:
Q: How can I disable Hotwire / Turbo (the Turbolinks replacement) for all forms in a Rails application? In Rails 7, Turbolinks is replaced by Hotwire / Turbo. This patches up web links so that they become AJAX-style requests just like Turbolinks did, but also patches up forms. On the whole, we found this broke swathes of our application.

*

*Forms that already had some kind of JS behaviour attached conflicted.

*Standard Rails error handling idioms - "set the flash and render :new/render :edit" - break, astonishingly; one must add status: :unprocessable_entity and cross fingers.

*If the controller handling a form submission redirects to a URL that includes a patch anchor (...#foo), Turbo strips it.

In the end, there's only so much data: {turbo: false} it makes sense to scatter all over your code base. Worse, we're using SimpleForm, so this becomes the even-more-cumbersome html: {data: {turbo: false}}.
Is there a way to _globally disable Turbo just for forms (ideally all forms, whatever their origin - just leave the <form> tag and everything inside it completely alone please) but leave the rest of its behaviour unchanged?

A: I posted this Q&A on Stack Overflow as I couldn't find any other solutions out there. Clearly, there are numerous shortcomings and I would much prefer to see a simple configuration flag for Turbo that would make it ignore forms - this would be an overwhelmingly preferable approach.
I still don't have a full solution either way, because forms generated internally by Rails for e.g. a link_to(...method: delete) are still a problem, but I did work around some of it using some monkey patching.
On the one hand there are Rails forms:

*

*Apparently, a data-turbo attribute's value apples to that node and all children so one can wrap e.g. a Rails-generated 'dynamic' form from e.g. a link_to(...method: delete) in a DIV with that attribute set and, at least, work around those problems on a case-by-case basis - though note, I'm having trouble making this work in some cases still.

*If you have a lot of these, though, that's going to be intrusive and ugly, so it'd still be nice to have a way to have Turbo just ignore forms completely.

On the other hand there are SimpleForm forms:

*

*SimpleForm provides no way to globally configure data attributes that will be added to form elements that it constructs. Previous requests for this in GitHub issues have so far been explicitly refused.

*SimpleForm appears to provide no way to configure a wrapper that would go around the form as a whole, only custom wrappers for inputs within a form. So we can't easily just e.g. write a wrapper DIV as mentioned above.

I happened to be involved in a gem called Hoodoo that provides monkey patching facilities that lets you write patch modules which are more like subclasses - super is available to call up to the patched implementation - and, further, patches can be enabled or disabled dynamically and easily. Hoodoo is actually a Rack application service framework, so this is something of a sledgehammer - I always intended to one day extract this into its own gem, but at the time of writing, I have not got around to it (and several years have gone by) - but we can require just the part we need and ignore the rest.
Here, I patch SimpleForm's builder methods. These just call Rails' form helpers under the hood, so I might have a go at patching lower down in Rails instead, but anyway, the following worked.
In your Gemfile, declare the Hoodoo dependency but don't load all of its component parts as you won't want most of them.
# Hoodoo's monkey patch module is useful sometimes:
# https://rubygems.org/gems/hoodoo
#
# MUST use 'require: false' so that the Rack components of Hoodoo middleware
# do not get activated; this is a Rails app, not a Hoodoo service!
#
gem 'hoodoo', '~> 2.12', require: false

...then write something like config/initializers/simple_form_monkey_patch.rb which looks something like this:
require 'hoodoo/monkey'

module SimpleFormMonkey
  module InstanceExtensions
    def simple_form_for(record, options = {}, &block)
      modified_options = {html: {data: {turbo: false}}}
      modified_options.deep_merge!(options)

      super(record, modified_options, &block)
    end
  end
end

Hoodoo::Monkey.register(
  extension_module: SimpleFormMonkey,
  target_unit:      SimpleForm::ActionViewExtensions::FormHelper
)

Hoodoo::Monkey.enable(
  extension_module: SimpleFormMonkey
)

...that'll do it. This has some risk as we're patching things which are - in terms of the module name & nesting - technically private to SimpleForm, but the method signature itself is at least public. You could patch ActionView::Helpers::FormHelper with an override for form_for instead, if you wanted to go lower level and patch an API that's been stable for a very long time. The code would be almost identical as the method signatures are the same.

A: I used Javascript to solve this problem:
  document.querySelectorAll('form').forEach(function (el) {
    el.dataset.turbo = false
  })

No more flaky system tests due to randomly missing flash messages/alerts after form submissions and Devise also works perfectly again.

A: @kamilpogo your solution worked like a charm! ty!!! currently learning and following this GoRails tutorial before i ran into some turbo trouble trying to render "Thanks!" for anyone else out there.
basically, i added the javascript to in /layouts/application.html.erb like below:
<script>
    document.querySelectorAll('form').forEach(function (el) {
                el.dataset.turbo = false
    })
</script>
<script src="js-bootstrap"></script>
  </body>
</html>

UPDATE: comments in the videos have a different work around by setting turbo to 'false' and local to 'true' inside the form:
form_with model: @user, url: sign_up_path, local: true, data: { turbo:false } do |form|


text:
Q: Set android application's name I am trying to set the name of my application and the name of my first activity to different values (I need trademark sign in my activity label, but not in the app name). I found this Naming my application in android and in the last comment the said if I set the app name using @string it will have affect, but it doesn't have. Is ther any way to do this?

A: On your onCreate()
String title = getTitle().toString();
setTitle(title + "(R)");

Being (R) the copyright symbol :)

A: AFAIK there is no way to achieve this in the manifest since the name attribute is used in the launcher automatically (I suggest that's what you mean with 'application name'). But you can do this in your code by simply using:
setTitle(R.string.yourActivityTitle)

-> The string in your manifest is used as "application name" and the string in your code is used for activity name.
Hope that helps...


text:
Q: Как исправить ? На граничных значениях неверные сообщения Постановка задания:

Написать консольное приложение на java, с использованием maven.
Приложение должно выводить на экран приветственное сообщение, в
  зависимости от текущего времени суток.
Good morning, World! в 06:00 - 09:00 Good day, World! в 09:00 - 19:00
  Good evening, World! в 19:00 - 23:00 Good night, World! в 23:00 -
  06:00 Код должен содержать все возможные юнит-тесты и создавать
  читабельный лог файл.
Выводящиеся на консоль сообщения должны быть получены из message
  resource и зависеть от системной локали пользователя. Сделать перевод
  на русский язык.

Вопрос: Как исправить ? На граничных значениях неверные сообщения.  Тесты на эти случаи не добавлены. Во всех тестах, также, в assertEquals попутаны местами ожидаемые и реальные значения.
public class World {

    private static final Logger log = Logger.getLogger(World.class);

    public static void main(String[] args) {

        Event event = new Event();
        String events = null;
        try{
            events = event.getEvent();
            System.out.println(events);
        }catch (ParseException e){
            log.error("Parse exception",e);
        }
    }
}

public class Event {

    private static final Logger log = Logger.getLogger(Event.class);

    private static SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    private Date current;//текущий
    private Date morning;//утро
    private Date day;//день
    private Date evening;//вечер
    private Date night;//ночь
    private Date currentDate;//текущая дата
    private String ress;

    public Event(){
        currentDate = new Date();
    }

    public Event(String event) throws ParseException{
        currentDate = dateFormat.parse(event);
    }

    public String  getEvent() throws ParseException{

        Locale.getDefault();
        ResourceBundle res = ResourceBundle.getBundle("message");

        current = dateFormat.parse(dateFormat.format(currentDate));
        morning  = dateFormat.parse(BorderEvent.MORNING.toString());
        day  = dateFormat.parse(BorderEvent.DAY.toString());
        evening = dateFormat.parse(BorderEvent.EVENING.toString());
        night = dateFormat.parse(BorderEvent.NIGHT.toString());

        if(current.after(morning) && current.before(day)){
            ress = res.getString("morning");
            log.info(ress);
            return ress;
        }
        else if (current.after(day) && current.before(evening)){
            ress = res.getString("day");
            log.info(ress);
            return ress;
        }
        else if (current.after(evening) && current.before(night)){
            ress = res.getString("evening");
            log.info(ress);
            return ress;
        }
        else
             ress = res.getString("night");
        log.info(ress);
        return ress;
    }
}

public enum BorderEvent {

    MORNING("06:00:00"),
    DAY("09:00:00"),
    EVENING("19:00:00"),
    NIGHT("23:00:00");

    private final String time;

    BorderEvent(String time) {
        this.time = time;
    }

    @Override
    public String toString() {
        return time;
    }
}

Тесты:
public class TestEvent {

    private static final Logger log = Logger.getLogger(TestEvent.class);
    private Event event;

    @Test
    public  void testGetEvent() throws ParseException {
        event = new Event();
        log.info(event.getEvent());
        switch (event.getEvent()){
            case "MORNING": break;
            case "DAY": break;
            case "EVENING":break;
            case "NIGHT": break;
            default:
                Assert.fail();
        }
    }

    @Test
    public void testNightFirst()throws ParseException{
        event = new Event("23:00:00");
       // Assert.assertEquals(event.getEvent(), "NIGHT");
        log.info(event.getEvent());
    }

    @Test
    public void testNightSecond()throws ParseException{
        event = new Event("05:59:59");
        //Assert.assertEquals(event.getEvent(), "NIGHT");
        log.info(event.getEvent());
    }

    @Test
    public void testNightThree()throws ParseException{
        event = new Event("23:00:01");
        //Assert.assertEquals(event.getEvent(), "NIGHT");
        log.info(event.getEvent());
    }

    @Test
    public void testNightFour()throws ParseException{
        event = new Event("02:00:00");
        //Assert.assertEquals(event.getEvent(), "NIGHT");
        log.info(event.getEvent());
    }

    @Test
    public void testMorningFirst()throws ParseException{
        event = new Event("06:00:01");
        //Assert.assertEquals(event.getEvent(), "MORNING");
        log.info(event.getEvent());
    }

    @Test
    public void testMorningSecond()throws ParseException{
        event = new Event("08:59:59");
        //Assert.assertEquals(event.getEvent(), "MORNING");
        log.info(event.getEvent());
    }

    @Test
    public void testMorningThree()throws ParseException{
        event = new Event("07:25:01");
        //Assert.assertEquals(event.getEvent(), "MORNING");
        log.info(event.getEvent());
    }

    @Test
    public void testMorningFour()throws ParseException{
        event = new Event("08:00:00");
        //Assert.assertEquals(event.getEvent(), "MORNING");
        log.info(event.getEvent());
    }
    @Test
    public void testDayFirst()throws ParseException{
        event = new Event("09:00:01");
        //Assert.assertEquals(event.getEvent(), "DAY");
        log.info(event.getEvent());
    }

    @Test
    public void testDaySecond()throws ParseException{
        event = new Event("18:59:59");
        //Assert.assertEquals(event.getEvent(), "DAY");
        log.info(event.getEvent());
    }

    @Test
    public void testDayThree()throws ParseException{
        event = new Event("15:35:51");
        //Assert.assertEquals(event.getEvent(), "DAY");
        log.info(event.getEvent());
    }

    @Test
    public void testDayFour()throws ParseException{
        event = new Event("16:53:15");
        //Assert.assertEquals(event.getEvent(), "DAY");
        log.info(event.getEvent());
    }

    @Test
    public void testEveningFirst()throws ParseException{
        event = new Event("19:00:01");
        //Assert.assertEquals(event.getEvent(), "EVENING");
        log.info(event.getEvent());
    }

    @Test
    public void testEveningSecond()throws ParseException{
        event = new Event("22:59:59");
        //Assert.assertEquals(event.getEvent(), "EVENING");
        log.info(event.getEvent());
    }

    @Test
    public void testEveningThree()throws ParseException{
        event = new Event("21:25:01");
        //Assert.assertEquals(event.getEvent(), "EVENING");
        log.info(event.getEvent());
    }

    @Test
    public void testEveningFour()throws ParseException{
        event = new Event("22:00:00");
        //Assert.assertEquals(event.getEvent(), "EVENING");
        log.info(event.getEvent());
    }
}

A: У тебя нету условия того что время равно, есть только больше и меньше. Необходимо его добавить в условия
if(current.after(morning) && current.before(day) || current.equal(morning)){
        ress = res.getString("morning");
        log.info(ress);
        return ress;
    }
    else if (current.after(day) && current.before(evening)|| current.equal(day)){
        ress = res.getString("day");
        log.info(ress);
        return ress;
    }
    else if (current.after(evening) && current.before(night)|| current.equal(morning)){
        ress = res.getString("evening");
        log.info(ress);
        return ress;
    }
    else
         ress = res.getString("night");
    log.info(ress);
    return ress;
}


text:
Q: Create the table without a Primary Key. openpyxl to sqlite So here I am sorting from an excel file using openpyxl to then move the data into a sqlite database.. So I have sorted it by creating a dictionary and using the serial number as the primary key... Unfortunately, this is wrong as there shouldn't be any primary key in my table.. how do I change this so I get all the values even if they duplicate
 violations_lookup = {}
 skip_row = True
 for row in
 violations_sheet_obj.iter_rows('A{}:E{}'.format(violations_sheet_obj.min_row,
 violations_sheet_obj.max_row)):
     if not skip_row:
         points, serial_number, violation_code, violation_description,
 violation_status = [cell.value for cell in row[:]]
         violations_lookup[serial_number] = (
             serial_number, points, violation_code, violation_description,
 violation_status
         )
     else:
         skip_row = False

 violations_data = list(violations_lookup.values())


text:
Q: Upraded Xcode, I have 2 Identicle views with UIScrollView. One View adds components to UIScroll fine, the other does not I have an app that has been working just fine for ages.  I upgraded XCode and now 1 of my views is doing weird things.
None of the objects I attempt to add to the UIScrollview show up.
I have 2 screens that are basically identical in code (i literally copy and pasted).  One of them works just fine, I click a button to move to the other screen, and it doesn't display ANY components I attempt to add to the scroll view.
Any ideas as to what could be wrong?  Why it would suddenly stop adding components after upgrading Xcode?
I have a background image that I have tested and changed to self.view that changes just fine.  But anything I try to add to my UIScrollView, nothing gets added.  Some sample code...
my .h declaration
@interface OutgateInputViewController : UIViewController<UITextFieldDelegate,UIPickerViewDelegate>{
IBOutlet UIScrollView *outputsView;

a sample in my .m
UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:@"inputbackground.png"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

self.view.backgroundColor = [UIColor colorWithPatternImage:image];

int x = 20;
int y = 20;

CGRect myImageRect = CGRectMake(0, 15, 320, 32.5);
UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];
NSString *imgName = @"screen_logo.png";
[myImage setImage:[UIImage imageNamed:imgName]];
[outputsView addSubview:myImage];
y = y + 30;

pretty standard stuff.  its an EXACT copy up to this point of the screen that works.  (even a copy long after, i just pull data from a different location).  So any ideas on what changed?

A: I went back and re-did everything from scratch, and apparently for some reason THIS View needs the additional __weak at the start of the declaration in the .h   ...
no idea why as of yet, but this solved the issue of the entire view being broken.
__weak IBOutlet UIScrollView *outputsView;


text:
Q: rowSelectListener="#{bean.method}" throws javax.el.ELException: The class 'com.example.Bean' does not have the property 'method' I changed PrimeFaces JAR library to version 5 from version 2 and now get this exception.

javax.servlet.ServletException: /home.xhtml: The class
  'com.primefaces.sample.UserManagedBean' does not have the property
  'onUserSelect'.
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:606) root
  cause
javax.el.ELException: /home.xhtml: The class
  'com.primefaces.sample.UserManagedBean' does not have the property
  'onUserSelect'.

xhtm page contains p:datatable
rowSelectListener="#{userManagedBean.onUserSelect}"
rowUnselectListener="#{userManagedBean.onUserUnselect}"

Bean:
public void onUserSelect(SelectEvent event) {
    selectedUser = (User) event.getObject();
    System.out.println("selectedUser = " + selectedUser);
}

public void onUserUnselect(UnselectEvent event) {
    selectedUser = null;
}

So why this doesn't work with PrimeFaces 5 while works with PrimeFaces 2 version?

A: If you check Primefaces 5 user guide, you'll notice that you cannot find the rowSelectListener attribute anywhere, but it existed in Primefaces 2. Perhaps you want to take a look at the onRowSelect and onRowUnselect listeners of <p:ajax> events for rowSelect and rowUnselect (page 167 of Primefaces 5 user guide). See here also: Primefaces tag rowSelectListener not found.