text:
Q: Problem using mysql++ library I've read the tutorial at, and I generally get how that works:
http://tangentsoft.net/mysql++/doc/html/userman/tutorial.html#simple
I am trying to build this mysql++ code, and I'm getting an error:
std::ostringstream query3;
query3<<"select pipe_id from pipe where version_id='"<<id<<"'";
std::storeQueryResult ares=query3.store();

for(size_t i=0;i<ares.num_rows();i++)
   cout<<ares[i]["version_id"]<<ares[i]["pipe_id"]<<std::endl;

mysql_query(&mysql,query3.str().c_str());

The error is that store is not a member of ostringstream.  I'm not sure how to correct the problem.

Hi Merlyn,
Thanks for the code and looking at my problem.
I tried the above code but again I am getting the error
error: request for member 'query' in 'connection' which is non-class type 'MYSQL*'
on this line of code
// Construct a query object with the query string mysqlpp::Query query =
connection.query(query_string);

kindly help where I am going wrong?

A: The problem is that you have to use a mysql++ query object to execute a query, not an ostringstream.  The ostringstream just lets you build the query string, but won't let you perform the query.
There is a tutorial that shows basic usage at:
http://tangentsoft.net/mysql++/doc/html/userman/tutorial.html#simple
To get from your code to a query that works, you need to take your dynamic query, turn it into a string, and use it to construct the mysql++ query object.
// todo: create the connection here

// Construct the query string.  You were already doing this in your code
std::ostringstream query_builder;
query_builder << "select pipe_id from pipe where version_id='" << id << "'";

// Convert the ostringstream to a string
std::string query_string = query_builder.str();

// Construct a query object with the query string
mysqlpp::Query query = connection.query(query_string);

// Perform the query
mysqlpp::StoreQueryResult result = query.store();
for(size_t i = 0; i < result.num_rows(); i++)
   std::cout << result[i]["version_id"] << result[i]["pipe_id"] << std::endl;


text:
Q: Callback URL changes to localhost even though the hostname is changed So, I have installed WSO2 API Manager 3.0.0, as a Windows service, on a server and ran into no problems accessing it from there. After that, I, then, tried to access it from another computer. The management console (/carbon) seemed to work just fine. But, when it comes to the other pages (/publisher and /devportal), it would work, is what it would seem like at first, but when it loads the login call back url, that's when it goes back to using localhost, which, obviously, will result in it not being able to load. So far, I have tried the things I found on the internet, but nothing worked so far, I even did a reinstall and just used the deployment.toml file as it is the only config file needed as per the documentation. Through there, I changed the hostname accordingly as it seemed to be the likely fix based on what I was able to find. After doing so, a different problem occurs, it says that it is currently unable to handle the request, and it's shown to be as "HTTP ERROR 500".
I'm pretty clueless as to what to do now, and, admittedly, I'm having difficulties on further understanding the technicalities that this entails as it is not my area of expertise. In any case, what would be the best course of action with regards to this kind of issue? Thanks in advance.
Note (just in case that it might be needed/useful): When it loads the call back url and eventually redirects to localhost, changing localhost back to the hostname, and then reloading the page works. And if it does that again, which it does at every chance it gets, I just change it again then reload.

A: APIM portals used authorization code grant to authenticate users. Once the user login is successful, the user will be redirected back to the given callback URL. The callback URL is basically where your portals/web app are hosted.
Callback URLs are derived from the hostname and proxy port at startup referring to deployment.toml. If the URLs are different(In case LB and not localhost), either you have to define then in the deployment.toml before the start or change the callback URL of the portal applications.
You can change the callback URL of a portal by login to the management console(/carbon) and editing the correct service provider of the portal application.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Got issue with apple certificate request I got a weird problem with certificate request that I submit successfully, but when trying to approve it, Apple said that...error without any detailed description in the history tab.
I did it many times, these steps are quite easy and always success but this time. I double checked all related things about how to generate CSR that: AWDRCA, email, OCSP, Key size...etc everything seems right.
Anybody meet this problem please help me.

A: This seems to be a bug that a lot of people are hitting at the moment. There's no known workaround yet, but you can follow along with the developer forums thread about it.
As of around 17:00 GMT 12th March 2012, this is now fixed.


text:
Q: How do I format 12 hour data with am/pm without NAs? The reformatting works for just the date, but when I add in the am/pm data it doesn't work. Here is the code and data:
str(Hourly_Steps$activity_hour)
 chr [1:22099] "4/12/2016 12:00:00 AM" "4/12/2016 1:00:00 AM" ...

This worked to format just the date...
    > day <- strptime(Hourly_Steps$activity_hour, format = "%m/%d/%Y %I:%M:%S")
> day
  [1] "2016-04-12 00:00:00 IST" "2016-04-12 01:00:00 IST"
  [3] "2016-04-12 02:00:00 IST" "2016-04-12 03:00:00 IST"
  [5] "2016-04-12 04:00:00 IST" "2016-04-12 05:00:00 IST"
  [7] "2016-04-12 06:00:00 IST" "2016-04-12 07:00:00 IST"
  [9] "2016-04-12 08:00:00 IST" "2016-04-12 09:00:00 IST"
 [11] "2016-04-12 10:00:00 IST" "2016-04-12 11:00:00 IST"

But when I try add in the %p for am/pm info, it goes back to 24hr...
    > day <- strptime(Hourly_Steps$activity_hour, format = "%m/%d/%Y %I:%M:%S %p")
> day
  [1] "2016-04-12 00:00:00 IST" "2016-04-12 01:00:00 IST"
  [3] "2016-04-12 02:00:00 IST" "2016-04-12 03:00:00 IST"
  [5] "2016-04-12 04:00:00 IST" "2016-04-12 05:00:00 IST"
  [7] "2016-04-12 06:00:00 IST" "2016-04-12 07:00:00 IST"
  [9] "2016-04-12 08:00:00 IST" "2016-04-12 09:00:00 IST"
 [11] "2016-04-12 10:00:00 IST" "2016-04-12 11:00:00 IST"
 [13] "2016-04-12 12:00:00 IST" "2016-04-12 13:00:00 IST"
 [15] "2016-04-12 14:00:00 IST" "2016-04-12 15:00:00 IST"

What am I missing here?

A: Your code works correctly.
You are starting with a "character" vector, and strptime() correctly reads your imperial time into "POSIXt" time format. The "POSIXt" is only stored in this specific "YYYY-MM-DD HH:MM:SS TZ" format and this is what you see displayed.
x <- c("4/12/2016 1:00:00 AM", "4/12/2016 1:00:00 PM", "4/12/2016 12:00:00 AM",
       "4/12/2016 12:00:00 PM")

y <- strptime(x, '%d/%m/%Y %I:%M:%S %p')
y
# [1] "2016-04-12 01:00:00 CEST" "2016-04-12 13:00:00 CEST"
# [3] "2016-04-12 00:00:00 CEST" "2016-04-12 12:00:00 CEST"

and
class(y)
# [1] "POSIXlt" "POSIXt"

Maybe you are looking for a way to change your output format, where you'd want to use strftime().
z <- strftime(y, '%m/%d/%Y %I:%M:%S %p')
z
# [1] "04/12/2016 01:00:00 am" "04/12/2016 01:00:00 pm"
# [3] "04/12/2016 12:00:00 am" "04/12/2016 12:00:00 pm"

Note, however, that you now have a "character" class.
class(z)
# [1] "character"

So, altogether you may want:
strftime(strptime(x, '%m/%d/%Y %I:%M:%S %p'), '%d/%m/%Y %I:%M:%S %p')
# [1] "12/04/2016 01:00:00 am" "12/04/2016 01:00:00 pm"
# [3] "12/04/2016 12:00:00 am" "12/04/2016 12:00:00 pm"

Sidenote: Midnight may not be displayed even though it is stored internally.
strptime("4/12/2016 12:00:00 AM", '%m/%d/%Y %I:%M:%S %p')
# [1] "2016-04-12 CEST"


text:
Q: fuelux wizard submit multiple forms or one form wrapping? I am using fuelux wizard for a multistep order process.
I have got the wizrd working fine but if I wrap the whole wizard in a form no matter what I try, it submits the form whenever I click to the next step.
I have tried adding type="button"  to the buttons so that they are not treated as submit buttons and to allow me to programmatically submit the form .on('finished' but then the wizard doesn't progress through the steps.
I have tried:
 $('#fuelux-wizard').wizard().on('change' , function(e, info){
                e.preventDefault();
}

But after logging the e in question it is 'change' so I think it is to do with the wizard not the form.
My jquery/javascript knowledge and understanding of events etc is not good enough to figure this out, I'm stuck.
The alternative seems to be to have individual forms within each step and then combine them in some way but this seems ridiculously complicated when wrapping the wizard in a single form would do the trick if I could control the submit, which seems like it should be possible.
Can anyone give me any pointers?
Thanks.

A: I found a solution.
Not sure that it is particularly elegant but it works.
So, before the initialisation of the wizard, I bound preventDefault to the submit event on the form.
$('#order_form').on('submit',function(e){
                e.preventDefault();
            });

then in the wizrd init, I bound this into the 'finished' event
thus:
$('#fuelux-wizard').wizard().on('finished', function(e,data) {
                // allow order form to be submitted
                $('#order_form').unbind('submit');
                // submit order form
                $('#order_form').submit();
   });

Anyone suggest a more elegant solution or see any probloems with what I have done?


text:
Q: Delegate Returning Incorrect Instance Number of ViewController I have a ViewController "LandingPageViewController" which has an embedded PageViewController "pageViewController".
I have created a delegate function to write from "pageViewController" to LandingPageViewControlelr".  This works fine and the data is sent to the "LandingPageController" however i cant interact with any of its elements because the delegate is creating a new instance.

When the app first launches it goes to "LandingPageViewController" and if I print(self) in viewDidLoad and viewDidAppear this is the result:
Delegate viewDidLoad...<ParseStarterProject_Swift.LandingPageViewController: 0x7fbf29406e60>
Delegate viewDidAppear...<ParseStarterProject_Swift.LandingPageViewController: 0x7fbf29406e60>

Then once i have scrolled over to the 3rd page and the delegate is called i get the following result of print(self)
Delegate function...<ParseStarterProject_Swift.LandingPageViewController: 0x7fbf2940e3a0>

This is the code from my "LandingPageViewController" that is receiving the data:
protocol GetMyIndexDelegate {
    func getIndex(index: Int)
}

class LandingPageViewController: UIViewController, GetMyIndexDelegate {
 @IBOutlet var createAccountButton: UIButton!

 //delegate functionto get index
func getIndex(index: Int) {
    if index == 3 {
        print("Delegate function...\(self)")

        //print(createAccountButton)

    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    print("Delegate viewDidLoad...\(self)")
}
}

and here is the code from the "pageViewController" class:
class pageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {

let myHeight = 667
let myCenter = 333.5

// define the delegate for use
var indexDelegate: GetMyIndexDelegate?

func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
    if (completed && finished) {
        if let currentVC = pageViewController.viewControllers?.last {
            let index = vcArr.index(of: currentVC)

            if index == 3 {

                // this is the line causing problem
                self.indexDelegate = LandingPageViewController()

                print("PageView Index Defined As...\(self.indexDelegate)")
                indexDelegate?.getIndex(index: index!)

                //goToVC()

            }
        }
    }
}

i believe this is the problem here:
self.indexDelegate = LandingPageViewController()

it is defining incorrect instance?????
As a side clue, i had another delegate method going in the other direction, from a viewController to the first page of the "pageViewController" and the issue there was that i had to correctly define the index of the page within the UIPageViewController with the following code:
self.delegate = self.childViewControllers[0] as! pageViewController

im not sure how this would work in the question above as the LandingPageViewController is the parent? of the pageViewController?

A: The self.indexDelegate = LandingPageViewController() is incorrect because you are instantiating a new view controller programmatically rather than referring to the one that was already instantiated for you by the storyboard.
You have an embed segue, which you are using to embed the page view controller within the other view controller's scene. So, you can use prepareForSegue in the parent view controller to set whatever properties you want in the child view controller.
But if you're simply looking for a reference to the child view controller in the parent, it's childViewControllers.first or childViewControllers[0]. And if the child is looking for a reference to its parent view controller, it's merely parent (or in your case, parent as? GetMyIndexDelegate).


text:
Q: How to change given string to regex modified string using javascript Example  strings :
 2222
 333333
 12345
 111
 123456789
 12345678

Expected result:
2@222
333@333
12@345
111
 123@456@789
 12@345@678

i.e. '@' should be inserted at the 4th,8th,12th etc last position from the end of the string.
I believe this can be done using replace and some other methods in JavaScript.
for validation of output string i have made the regex :
^(\d{1,3})(\.\d{3})*?$

A: You can use this regular expression:
/(\d)(\d{3})$/

this will match and group the first digit \d and group the last three \d{3} which are then grouped in their own group. Using the matched groups, you can then reference them in your replacement string using $1 and $2.
See example below:

const transform = str => str.replace(/(\d)(\d{3})$/, '$1@$2');

console.log(transform("2222")); // 2@222
console.log(transform("333333")); // 333@333
console.log(transform("12345")); // 12@345
console.log(transform("111")); // 111

For larger strings of size N, you could use other methods such as .match() and reverse the string like so:

const reverse = str => Array.from(str).reverse().join('');
const transform = str => {
  return reverse(reverse(str).match(/(\d{1,3})/g).join('@'));
}

console.log(transform("2222")); // 2@222
console.log(transform("333333")); // 333@333
console.log(transform("12345")); // 12@345
console.log(transform("111")); // 111
console.log(transform("123456789")); // 123@456@789
console.log(transform("12345678")); // 12@345@678

A:

var test = [
    '111',
    '2222',
    '333333',
    '12345',
    '123456789',
    '1234567890123456'
];
console.log(test.map(function (a) {
  return a.replace(/(?=(?:\B\d{3})+$)/g, '@');
}));

A: You could match all the digits. In the replacement insert an @ after every third digit from the right using a positive lookahead.
(?=(?:\B\d{3})+$)

*

*(?= Positive lookahead, what is on the right is

*

*(?:\B\d{3})+ Repeat 1+ times not a word boundary and 3 digits

*$ Assert end of string

*) Close lookahead

Regex demo

const regex = /^\d+$/;
["2222",
  "333333",
  "12345",
  "111",
  "123456789",
  "12345678"
].forEach(s => console.log(
  s.replace(/(?=(?:\B\d{3})+$)/g, "@")
));


text:
Q: How to read line-by-line of a single parameter (input) from a JavaScript function? I'm working on a Racker Rank problem whose function in JavaScript receives a single parameter (input).
Input Format:
The first line contains an integer,  (the number of test cases).
Each line  of the  subsequent lines contain a String.
I need to print the even-indexed and odd-indexed characters of each string (S) separated by a space on a single line (see the Sample below for more detail).
2
Hacker
Rank

Hce akr
Rn ak

Is there a way to read the input line-by-line and save each string in a specific variable? If I achieve that I know how to solve the problem by iterating through the string. Otherwise, I'm lost. If not, how else could I handle the input? Thanks!
Readline doesn't seem to be the way to go.
function processData(input) {
    //Enter your code here

}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

What I have tried without success:
function processData(input) {

    let myArray = input.split("\n");

    let even_indexed = "";
    let odd_indexed = "";

    for (let i = 1; i <= myArray.length; i++) {
        let str = myArray[i];
        let len = str.length;

        for (let j = 0; j < len; j++){
            if (j % 2 == 0) { //check if the index is even;
                even_indexed.concat(str[j]);
            }
            else {
                odd_indexed.concat(str[j]);
            }
        }
    }
    console.log("%s  %s", even_indexed, odd_indexed);
}

A: Can't you just use split() method with a newline operator?

<script>
let x= `Hey
I'm
a
multiline
string`

console.log(x.split("\n"))
</script>

The result will be an array on which every element represents a line of your input.

A: I made this pretty quickly so I apologize for it being kinda messy and I know there are probably more efficient ways of doing this, but it does what you are asking for.

let input = `This
is
a
multiline
string`

let splitWords = [];
input.split(/\r?\n/).forEach(function(e){ // Split the array by \n (newline) and/or \r (carriage return)
  currentLine = {evenIndex: [], oddIndex: []}
  for(let i = 0; i < e.length; i++){
    if((i + 1)%2 === 0){
      currentLine.evenIndex.push(e[i]);
    }
    else{
      currentLine.oddIndex.push(e[i]);
    }
  }
  splitWords.push(currentLine);
});
splitWords.forEach(function(e){
  console.log(e.oddIndex.join('') + " " + e.evenIndex.join(''))
});


text:
Q: Own Events in Java not able to modify Classobjects? this is My Situation:
I want to make two classes communicate with each other. So MainActivity is
making a new Object of SomeOtherstrangeClass.
public class MainActivity extends AppCompatActivity implements myEventListener {

    private TextView txtHelloSet;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtHelloSet = (TextView) findViewById(R.id.txtHello);

        SomeOtherStrangeClass someOtherStrangeClass = new SomeOtherStrangeClass();
    }

    @Override
    public void someEvent(int e) {
        Log.v("[Listener]", "SomeEvent triggered. Number: " + e);
        txtHelloSet.setText("Event came in!");
    }
}

#
public class SomeOtherStrangeClass {

    public  SomeOtherStrangeClass(){

        EventThrower eventThrower = new EventThrower();
        MainActivity mainActivity = new MainActivity();

        eventThrower.addListener(mainActivity);
        Log.v("[Listener]", "Throwing event");

        eventThrower.someEvent(13);

    }
}

interface myEventListener extends java.util.EventListener {
    void someEvent(int e);
}

public class EventThrower {

    private List<myEventListener> listeners = new ArrayList<myEventListener>();

    public void addListener(myEventListener toAdd){
        listeners.add(toAdd);
    }
    public void removeListener(myEventListener toRemove){
        listeners.remove(toRemove);
    }

    public void someEvent(int e){
        for(myEventListener el : listeners)
            el.someEvent(e);
    }

}

So this is how I'am doing it. But the Problem is, that when an event is thrown its like I'am still calling the Methode someEvent which is in MainActivity in SomeOtherStrangeClass. So I'am not able to modify any Objects in MainActivity. It's like they are not existing. I'am getting a NPE:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

Why this is so?
Is there any solution for that?

A: MainActivity mainActivity = new MainActivity();

You are doing something wrong here. It is not supposed to create Activity objects like this. You should rethink about your application logic.

A: You need to reference the instance of MainActivity that is currently in foreground in order to recognize any callbacks in it.
Try changing the constructor for SomeOtherStrangeClass like this:
public  SomeOtherStrangeClass(myEventListener listener) {
        EventThrower eventThrower = new EventThrower();
        eventThrower.addListener(listener);
        Log.v("[Listener]", "Throwing event");
        eventThrower.someEvent(13);
    }

Then, in onCreate() of your activity,
SomeOtherStrangeClass someOtherStrangeClass = new SomeOtherStrangeClass(this);


text:
Q: Error with ECS container: ResourceInitializationError : failed to create Cloudwatch log stream I am trying to set up an ECS Fargate container but it throws me this error:

"ResourceInitializationError: failed to validate logger args: create stream has been retried 1 times: failed to create Cloudwatch log stream: ResourceNotFoundException: The specified log group does not exist. : exit status 1"

I've already checked and the log group exists and it has the same name in the task definition. I've checked the ecsTaskExecutionRole policy (it has cloudWactchLogsFullAccess policy), also thought that could be the internet access but I checked the vpc, subnet, and route table and everything seems ok (I don't know how to check if the container really has internet access).

A: One of my Fargate services had mysteriously stopped and I was seeing this error as well.
In my case, I had deleted the log group which the service was using and this caused the launching of the task to fail on subsequent retries.
You say that your log group still exists though, so I'm not sure if it's the same problem.
Anyway, my FIX using the AWS Console:

*

*Navigate to the task that failed to launch

*View in CloudWatch

*Get the name of the CloudWatch log group that the task is expecting to save to

*Create a new CloudWatch log group matching with this name

Now the service has a log group to save to and your tasks should successfully start again.


text:
Q: Delphi component installation using .DCU file I am delphi developer and want to install component for Delphi 7 on Windows XP and 2007. I have .DCU files only.
When I try to install .DCU from Component > insatll packege > Add> select .DCU file then it shows error like "Invalide Package file"
Please help.
Thanks in advance.

A: You are using the wrong mechanism to install the component. Instead of Install Packages you need to select Install Components. This will present a dialog which allows you to specify the unit file name that contains the component(s). You get the choice of installing the component into a new package, or an existing package.


text:
Q: How to increase speed when writing Spark DataFrame to Redis? I am developing a book recommendation API based on Flask, and it was found that to manage multiple requests I'll need to pre-calculate similarity matrix and store it somewhere for future queries. This matrix is created using PySpark based on ~1.5 million of database entries with book id, name and metadata, and the result can be described by this schema (i and j are for book indexes, dot is for similarity of their metadata):
StructType(List(StructField(i,IntegerType,true),StructField(j,IntegerType,true),StructField(dot,DoubleType,true)))

Initially, it was my intention to store it on Redis, using spark-redis connector. However, the following command appears to work with a very slow speed (even if initial book database query size is limited to a very modest 40k batch):
similarities.write.format("org.apache.spark.sql.redis").option("table", "similarities").option("key.column", "i").save()

It took around 6 hours to advance through 3 of the 9 stages Spark separated the initial task into. Strangely, storage memory usage by Spark executors was very low, around 20kb. A typical stage active stage is described as such by Spark Application UI:
org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:271)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
py4j.Gateway.invoke(Gateway.java:282)
py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
py4j.commands.CallCommand.execute(CallCommand.java:79)
py4j.GatewayConnection.run(GatewayConnection.java:238)
java.lang.Thread.run(Thread.java:748)

Is it possible to somehow speed up this process? My Spark session is set up this way:
SUBMIT_ARGS = "  --driver-memory 2G --executor-memory 2G --executor-cores 4 --packages mysql:mysql-connector-java:5.1.39 pyspark-shell"
os.environ["PYSPARK_SUBMIT_ARGS"] = SUBMIT_ARGS
conf = SparkConf().set("spark.jars", "spark-redis/target/spark-redis_2.11-2.4.3-SNAPSHOT-jar-with-dependencies.jar").set("spark.executor.memory", "4g")
sc = SparkContext('local','example', conf=conf)
sql_sc = SQLContext(sc)

A: You may try to use Append save mode to avoid checking if the data already exists in the table:
similarities.write.format("org.apache.spark.sql.redis").option("table", "similarities").mode('append').option("key.column", "i").save()

Also, you may want to change
sc = SparkContext('local','example', conf=conf)

to
sc = SparkContext('local[*]','example', conf=conf)

to utilize all cores on your machine.
BTW, is it correct to use i as a key in Redis? Shouldn't it be a composition of both i and j?


text:
Q: Singleton pattern When should we use the Singleton pattern and why?

A: Java Runnable is the best example of the Singleton Pattern. When you want to add a restriction which does not allow you to create more than a single instance of a particular class then it is better to implement a  Singleton Pattern.
Key points to implement singleton :

*

*Private Constructor

*Static Private Instance Variable of Singleton class itself

*Public getter method only at very first time it will initialize above variable, and always return same instance of a Singleton class.
class Singleton {

      private static Singleton instance;

      private Singleton(){
      }

      public static Singleton getInstance(){
         if(instance=null){
            instance=new Singleton();
         }

         return instance;
      }
      ........
    }

And for thread safety :
       getInstance() needs to be synchronized.

A: If you have a situation when exactly one object is needed to coordinate actions across the system, then you can use this pattern. A good example of this is the Facade, that is, Facades can be implemented as singletons because often one Facade object is needed across the system.
But in general, it's usually a bad practice and should be avoided, one big reason is it greatly inhibits extensibility.

A: http://sites.google.com/site/steveyegge2/singleton-considered-stupid

Why is the Singleton so attractive? I'll be the first to admit: I liked it too. No, scratch that - I loved the Singleton. It felt like an old friend from the moment I laid eyes on it. It was simple and beautiful.
I'll tell you why: it's because the Singleton pattern is a throwback to non-OO programming. It's a lifeline for people who didn't understand a single word that the Gang of Four were trying to say. I don't know how it got in there in the first place -- some political OOPSLA pressure, no doubt -- but it doesn't belong in there. It's Evil...
Here's the "short" summary...
a) I haven't covered even a tenth of the issues. But I'll name a few of them.
b) One is memory management; a Singleton is basically just a memory leak, if nobody is going to be using it for a while. But you have no idea when to deallocate it, because nobody's going to call you and say "nobody's going to be using you for a while!"
Besides, you can't tell who has kept around references to your Singleton instance, since you were pretty blase about handing it out, weren't you? (Note: Java's weak references can help with this issue).
c) Speaking of memory leaks, what if your Singleton has a handle to some limited resource, like a database or file handle? I guess you get to keep that sucker open until your program ends. Thank God C++ programs never last longer than about 10 minutes before crashing, usually from running out of resources, or from trying to access a Singleton that someone freed.
d) Another issue is that the Singleton design is syntactically noisy; most languages don't support it (well, Ruby does, sadly, but that was probably before Matz knew any better), so you have to stick in boilerplate code not only in the Singleton, but in everyone who uses it.
e) Then there's the subclassing thing. It's almost impossible to subclass a Singleton, and if you manage it, then you shouldn't have been using a Singleton in the first place. You don't even want to go there. I've walked roads that I dare not recount. Just pretend you can't do it, and you'll save yourself amazing amounts of pain.
f) static methods are as flexible as granite. Every time you use one, you're casting part of your program in concrete. Just make sure you don't have your foot jammed in there as you're watching it harden. Someday you will be amazed that, by gosh, you really DO need another implementation of that dang PrintSpooler class, and it should have been an interface, a factory, and a set of implementation classes. D'oh!
Don't suppose that's all. There are many other problems. For instance, try adding multithreading in and see what happens. Well, I'll tell you what happens: half the time, you get a Doubleton or a Tripleton, unless you're a synchronization expert, and having a Tripleton is about as desirable as having three Balrogs show up at your tea party. And even if you're a synchronization expert and get the double-check idiom right, you've still got one Balrog to deal with, and they're no picnic.
But these problems all fade into insignificance compared to the Big One, which is that the Singleton "pattern" encourages you to forget everything you know about OO design, since OO is hard, and procedural is easy...

A: In theory: when you need to restrict the instantiation of an object to one instance. In practice: never.

A: As said the intention of a singleton pattern is to ensure that a single instance of a class is instantiated.
The singleton pattern is considered as one of the "bad" patterns in the GOF pattern catalog since the singleton leads to coupling in code and makes (unit) testing of code hard. The latter point is not 100% true in (most) dynamic/loosely typed languages because you can monkey patch code.
Let's take a look at coupling: Every code piece that uses the Singleton is coupled directly to the implementation of the Singleton. This is hard/impossible to mock and since Singletons are often used for infrastructure services like a database access layer the unit that you want to test is coupled to the concrete implementation of the database access layer. But for a unit test you do not want to hit the database, you want to have some mock data access layer. You end up in a situation where you ask yourself why you used the singleton pattern.
I'd recommend the singleton pattern only for "simple" software but as we all know software has a tendency to grow. To start simple and end complex after some years.

A: When you don't want to create multiple instances of same type you need to go for singleton. But the same can be achieved if you use Static Classes. So the point here is it's not the only one instance but the control over instance creation, thus avoiding unneccessary consumption of precious resources.

A: Think of everything where more than one instance would be an error (inconsistence). THis could be an Application object (root object for a app) or a application wide securityManager etc. The singleton is just a way to enforce that at class can only have one instance.

A: The Singleton pattern is about to ensure a class has only one instance, and provide a global point of access to it.

A: When you want a bunch of different objects to be able to make reference to one single object. Maybe they want to all use the same PhysicsEngineDude or something... You don't want different objects having different physics models when they live in the same world!

A: When you just need one instance from a class. One of the best example is the logger. You just need an instance of it.

A: When only one instance from a class that is needed in the system.Since it has only one instance, so you can rigidly decide how the users can get access to it.

A: *

*In software engineering, the singleton pattern is a design
pattern that restricts the Instantiation of a class to one object.
This is useful when exactly one object is needed to coordinate
actions across the system.

*Application needs one, and only one, instance of an object.
Additionally, lazy initialization and global access are necessary.
More here...
http://www.dzone.com/links/r/java_ee_singleton_design_pattern_introduction.html


text:
Q: jQuery selector with "and" and "or" Can somebody help me with the syntax of what I'm trying to do here?
jQuery('(div[data-positiontype="3"]) && (div[data-positiontitle*="test"] || div[data-positiondesc*='test'])')

Basically I need the ability to select all divs that have a particular "data-positiontype" attribute and a token in either the "data-positiontitle" attribute or the "data-positiondesc" attribute.

A: You stack the selectors together to find elements that matches both, and use the , combinator between selectors:
jQuery('div[data-positiontype="3"][data-positiontitle*="test"],div[data-positiontype="3"][data-positiondesc*="test"]')

A: $('div[data-positiontype="3"]').filter('[data-positiontitle*="test"], [data-positiondesc*="test"]').

or the straightforward:
$('div[data-positiontype="3"][data-positiontitle*="test"], div[data-positiontype="3"][data-positiondesc*="test"]').


text:
Q: Vba download file from internet WinHttpReq with login not working I have been looking for a solution to automatize the dowload of a csv table from a site, but I haven't found a working solution.
If I get on IE or Chrome, after previous log in I enter the url and the file automatically start dowloading. At this purpose I have another way of achieving what I need through IE and HTML object by navigating and then saving, but it uses sendkeys and it is not a suitable solution.
I also tried to achieve that by a WinHttpReq download which to me seems the most efficient and elegant way to do it. The problem is : it downloads the file but unfortunately it outputs a csv file with the HTML code of the login page -> Thus it must fail logging in. The site is an HTTP.
Following my code which I found posted as is in several forums.
Sub DownloadFile()

Dim myURL As String
valore = Range("f6").value
myURL = "www.myurlpointingtodownload.com"

Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False, "eimail@g.com", "passs"
WinHttpReq.send

myURL = WinHttpReq.responseBody
If WinHttpReq.Status = 200 Then
    Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write WinHttpReq.responseBody
    oStream.SaveToFile "C:\Users\mee\Desktop\fileoioi.csv", 2
    oStream.Close
End If

End Sub

Thank you,
bob.

A: Thanks to alex and Kyle's hints I looked up to these 2 posts which solved my problem.
nb -> no cookie handling and Fiddlr body copy of the http POST request the 2 required steps for me
here it is my solution:
Sub eds()

Dim strCookie As String, strResponse As String, _
  strUrl As String
  Dim xobj As Object
  Dim WinHttpReq As Object
  Set xobj = New WinHttp.WinHttpRequest

  UN = "2myusername"
  PW = "mypass"

  strUrl = "http://my.website.com/"
  xobj.Open "POST", strUrl, False
  xobj.SetRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36"
  xobj.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
  xobj.Send "username=" & UN & "&password=" & PW & "&login=login"
  strResponse = xobj.ResponseText

  strUrl = http://my.website.com/date=09-10-1945%&search 'the url pointing to the CSV file
  xobj.Open "GET", strUrl, False

  xobj.SetRequestHeader "Connection", "keep-alive"
  xobj.SetRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36"
  xobj.Send

  strCookie = xobj.GetResponseHeader("Set-Cookie")
  strResponse = xobj.ResponseBody

 If xobj.Status = 200 Then
    Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write xobj.ResponseBody
    oStream.SaveToFile "C:\Users\me\Desktop\ciao\file.csv", 1
    oStream.Close
End If
End Sub


text:
Q: I keep on getting the error: Unable to load config info from c:openssl/ssl/openssl.cnf When using open ssl When using this command: openssl req -new -x509 -days 3652 -key customerCA.key -out customerCA.crt
I get an error: Unable to load config info from c:openssl/ssl/openssl.cnf.
I have opensll installed on: C:\Users\nicko\Desktop\cluster-csr\feb9\openssl-0.9.8k_X64\ and the opensll .cnf file is under `the openssl-0.9.8k_X64:
Proof of file location
I also made an enviroment variable:
Proof of env variable
I've looked at Unable to load config info from /usr/local/ssl/openssl.cnf on Windows (another stackoverflow post) and nothing there helps. If anyone has any idea why this is happening, I'd apreciate any answer.


text:
Q: Checking how many characters are in a String (JavaScript) I'm trying to find out how many of the characters in my array are in my string password.
It errors in the console saying, Uncaught SyntaxError: Unexpected identifier. I'm trying to port this code from java but I'm not sure how to do it.
var password = "h@llo";

var list = [];

list.push('!');
list.push('@');

var charcount = 0;

for (var ch : password.toString){

    if(list.contains(ch)){
        charcount ++;
    }

}

$("#console").append(charcount + "<br/>");

A: Your description was unclear, but I've edited my code and should fit your expectations now.

var password = "h@llo";
var elements = ['h', '@'];
var count = 0;
password.split('').forEach(v => elements.some(c => c == v) ? count++ : null);

console.log(`There are ${count} elements from elements array inside password string.`);

Using Array#filter.

var password = "h@llo";
var elements = ['h', '@'];
var count = password.split('').filter(v => elements.some(c => c == v)).length;

console.log(`There are ${count} elements from elements array inside password string.`);

A: *

*It's for(var ch of ...) not for(var ch : ...). Try this:

*password is already a string so toString is useless

*Arrays don't have a function called contains, use indexOf instead!

Try this:

var password = "h@llo";

var list = [];

list.push('!');
list.push('@');

var charcount = 0;

for (var ch of password){
    if(list.indexOf(ch) != -1){
        charcount ++;
    }
}

console.log(charcount);

A: Here are two ways to do it:
With a Set and split('') (equivalent of Java's charToArray), and filter:

var password = "h@llo";
var list = new Set(['!', '@']); // make it a set for direct access
var charCount = password.split('').filter( ch => list.has(ch) ).length;
console.log(charCount);

and with a regular expression:

var password = "h@llo";
var re = /[!@]/g;
var charCount = password.match(re).length;
console.log(charCount);

A: @Leon it's indexOf(ch) != -1 not just indexOf(ch)! as -1 is true! – ibrahim mahrir 28 mins ago
This worked, I don't really know whwat != -1 means though so does anyone know of a doc that explains that or could explain it now?


text:
Q: Hibernate and Spring with Hibernate Annotations = "Unknown Entity..." I have a Project with Spring and Hibernate and I want to use Hibernate Annotations (@Entitity, @MappedSuperClass) in my classes.
I have the following hibernate-config.xml:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.h2.Driver" />
    <property name="url" value="jdbc:h2:mem:test_iep;USER=root;PASSWORD=root" />
    <property name="username" value="root" />
    <property name="password" value="root" />
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan">
        <list>
            <value>ch.foo.enterpriseportal</value>
        </list>
    </property>

    <property name="hibernateProperties">
        <value>
            hibernate.dialect=org.hibernate.dialect.H2Dialect
            hibernate.hbm2ddl.auto=create
        </value>
    </property>

    <property name="configurationClass">
        <value>org.hibernate.cfg.AnnotationConfiguration</value>
    </property>
</bean>

My Person-Class which I want to persist:
    import org.hibernate.annotations.Entity;

    @Entity
    public class Person extends Party {

private String firstName;

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}
}

If I try to persist the Person-Object, I get this stacktrace:
 org.springframework.orm.hibernate3.HibernateSystemException: Unknown entity: ch.foo.enterpriseportal.domain.entities.party.Person; nested exception is org.hibernate.MappingException: Unknown entity: ch.foo.enterpriseportal.domain.entities.party.Person
    at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:679)
    at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412)
    at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411)
    at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
    at org.springframework.orm.hibernate3.HibernateTemplate.persist(HibernateTemplate.java:793)
    at ch.foo.enterpriseportal.domain.HibernateSetupIT.testHibernateSetup(HibernateSetupIT.java:34)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.hibernate.MappingException: Unknown entity: ch.foo.enterpriseportal.domain.entities.party.Person
    at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:693)
    at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:1494)
    at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:202)
    at org.hibernate.event.def.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:531)
    at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:102)
    at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:61)
    at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:808)
    at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:782)
    at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:786)
    at org.springframework.orm.hibernate3.HibernateTemplate$21.doInHibernate(HibernateTemplate.java:796)
    at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
    ... 32 more

I really don't know where the problem exactly is, but I think it might be a configuration-problem.
Can anybody help?

A: Use the javax.persistence.Entity annotation instead of org.hibernate.annotations.Entity. org.hibernate.annotations.Entity only provides some hibernate-specific features to an entity already annotated with javax.persistence.Entity.
If you really want to use the Hibernate @Entity annotation, use its FQN to make it clearer it's an engine-dependent annotation:
import javax.persistence.Entity;

@Entity
@org.hibernate.annotations.Entity(...)
public class Person extends Party {
    //...
}

These questions might be useful to you:

*

*Hibernate annotation.

*Difference between JPA Entity and Hibernate Entity


text:
Q: The gradient in different dimensions I study to final exam in calc 3.
Question: Are my thoughts about the gradient correct?
The gradient is a normal vector to a plane given a point in $xyz$-plane. With this vector you can calculate the equation for the tangent plane.
If I have a curve $f(x)$, I can consider this as a level curve for a function $f(x,y)$.
If I take the gradient of $f(x,y)$ I will get a 2-dim vector that is orthogonal to the level curve. But the level curve is $f(x)$.
If I was given a point $(x_0)$ and my task is to calculate the tangent line in that point. I can just consider $f(x_0)$ as a level curve on $f(x_0,f(x_0))$, take the gradient to get the normal vector for the tangent line. With equation $ax +by +C =0$ I will get the equation for the tangent line.
The gradient is always  one dimension lower than the actual function.
Regards

A: No.
The gradient is a trivial case of the Jacobian and is only applicable to functions of the form $f:\mathbb{R}^n\rightarrow\mathbb{R}$, that is, real-valued functions. Specifically, the gradient is computed as $$\nabla f=\left\langle \frac{\partial f}{\partial x_1}, \frac{\partial f}{\partial x_2}, \cdots, \frac{\partial f}{\partial x_n}\right\rangle$$
It should also be noted that there is no such concept as the "dimension" of a function. You can talk about the dimension of the domain, the dimension of the image, the rank of the derivative, and other similar concepts.
A level curve, more generally a level set, is the pre-image of some constant with respect to a real-valued function and is commonly denoted $g^{-1}(c)$ where $g$ is said continuous function and $c$ is a constant.
It is true that the gradient at a point gives the vector orthogonal to the level set at that point and can be used to determine and/or verify a tangent vector at said point.


text:
Q: Commutators and implications of them not equalling 0 I'm struggling to understand the commutator theory for quantum mechanics. I know there's the proof to do with $[P,Q]=0$ therefore there is a set of simultaneous eigenstates for $P$ and $Q$. However, if $[P,Q] \neq 0$, does it also mean that then for all $|\psi\rangle \neq 0$, we have $[P,Q]|\psi\rangle \neq 0$? Or there is a way for it to equal 0?

A: As a counterexample:  in general, the operators $\hat{L}_x$ and $\hat{L}_y$ do not commute, since $[\hat{L}_x, \hat{L}_y] = i \hbar \hat{L}_z$.  However, for any state $|\psi\rangle \neq 0$ which is an eigenvector of $\hat{L}_z$ with $L_z = 0$, we have $[L_x, L_y] |\psi\rangle = 0$.


text:
Q: jquery count elements with a particular class that have value greater than zero Hi say I have some inputs:
<input type="Text" class="myclass" value="0" />
<input type="Text" class="myclass" value="7" />
<input type="Text" class="myclass" />
<input type="Text" class="myclass" value="2" />

And I want to count the number of inputs with class myclass that have a value greater than zero how would I go about that. In the scenario above the output I would want would be 2.
So far I have $(".myclass").filter().length
However I'm not sure what should go in filter or it I should even be using it.

A: Use this:
$(".myclass").filter(function(){
    return +this.value > 0;
}).length;

+ casts the value to a number and then it just returns true if the value is greater than one and false if otherwise.  A function is passed to .filter(), this loops through each match. If the function returns false then the element is removed from the set so you're just left with elements whose value is greater than zero.
Here's a demo: http://jsfiddle.net/88zH3/

A: Try this:
var count=$(".myclass").filter(function(){
     return $(this).val() >0;
}).length

A: $(".myclass").filter(function(el, i){
    return parseInt( $(el).val(), 10 ) > 0;
}).length;


text:
Q: First database with referential integrity constraints -- suggestions, feedback, errors? TARGET_RDBMS: MySQL-5.X-InnoDB ("X" equals current stable release)
BACKGROUND: Building my first database with true referential integrity constraints, in an effort to get feedback, after creating the "real" DDL, I've made an abstraction that I believe covers the "feel" of the database; this is only 3 tables of about 20, all with referential integrity constraints; only pattern I see that is missing is a composite key table, which does not have data to be dumped in right now anyway, so I'm just focus on the first iteration.
Sample Data / Unit Test: One thing I do not know is how to build out a sample data set that will offer 100% coverage of the referential integrity modeled -- AND build "Unit Test" around that sample data and this DDL:
Sample DLL:
(Note: Just to be clear, the LEGEND and naming standards are JUST for this example, which I've abstracted from the "real" database. The column names are robotic in nature, and meant to make the meaning and relationship of a given instance as clear as possible. If you have suggestions on the notation system used, please feel free to comment. I'm open to any suggestions. Thanks!)
CREATE DATABASE sampleDB;

use sampleDB;

# ###############
# LEGEND
# - sID = surrogate key
# - nID = natural key
# - cID = common/shared across tables, but NOT unique/natural-key
# - PK = Primary Key
# - FK = Foreign Key
# - data01 = Sample data (non-key,not-shared-across-tables)
# - data02 = Sample data NOT NULL (non-key,not-shared-across-tables)
#
# - uID = user defined unique/natural key (NOTE: not used)

# ###############
# Behavior
# - create_timestamp (NOT NULL, updated on record creation, NOT update)
# - update_timestamp (NOT NULL, updated on record creation AND updates)

CREATE TABLE `TABLE_01` (
  `TABLE_01_sID_PK` MEDIUMINT NOT NULL AUTO_INCREMENT,
  `TABLE_01_cID` int(8) NOT NULL,
  `TABLE_01_data01` varchar(128) default NULL,
  `TABLE_01_data02`  varchar(128) default NULL,
  `create_timestamp` DATETIME DEFAULT NULL,
  `update_timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY  (`TABLE_01_sID_PK`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `TABLE_02` (
  `TABLE_02_sID_PK` MEDIUMINT NOT NULL AUTO_INCREMENT,
  `TABLE_02_nID_FK__TABLE_01_sID_PK` int(8) NOT NULL,
  `TABLE_02_cID` int(8) NOT NULL,
  `TABLE_02_data01` varchar(128) default NULL,
  `TABLE_02_data02` varchar(128) NOT NULL,
  `create_timestamp` DATETIME DEFAULT NULL,
  `update_timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`TABLE_02_sID_PK`),
  FOREIGN KEY (TABLE_02_nID_FK__TABLE_01_sID_PK) REFERENCES TABLE_01(TABLE_01_sID_PK),
  INDEX `TABLE_02_nID_FK__TABLE_01_sID_PK` (`TABLE_02_nID_FK__TABLE_01_sID_PK`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `TABLE_03` (
  `TABLE_03_sID_PK` MEDIUMINT NOT NULL AUTO_INCREMENT,
  `TABLE_03_nID_FK__TABLE_01_sID_PK` int(8) NOT NULL,
  `TABLE_03_nID_FK__TABLE_02_sID_PK` int(8) NOT NULL,
  `TABLE_03_cID` int(8) NOT NULL,
  `TABLE_03_data01` varchar(128) default NULL,
  `TABLE_03_data02` varchar(128) NOT NULL,
  `create_timestamp` DATETIME DEFAULT NULL,
  `update_timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`TABLE_03_sID_PK`),
  FOREIGN KEY (TABLE_03_nID_FK__TABLE_01_sID_PK) REFERENCES TABLE_01(TABLE_01_sID_PK),
  FOREIGN KEY (TABLE_03_nID_FK__TABLE_02_sID_PK) REFERENCES TABLE_02(TABLE_02_sID_PK),
  INDEX `TABLE_03_nID_FK__TABLE_01_sID_PK` (`TABLE_03_nID_FK__TABLE_01_sID_PK`),
  INDEX `TABLE_03_nID_FK__TABLE_02_sID_PK` (`TABLE_03_nID_FK__TABLE_02_sID_PK`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

SHOW TABLES;

# DROP DATABASE `sampleDB`;

# #######################
# View table definition
# DESC inserttablename;

# #######################
# View table create statement
# SHOW CREATE TABLE example;

Questions:
Any and all feedback on missing, wrong, or "better" ways to do this database build are welcome. If you have questions, just comment -- and I'll respond ASAP. Again, thanks~!
UPDATE (1):
Just added "MEDIUMINT NOT NULL AUTO_INCREMENT" to the PKs -- not sure how I left that off.

A: First of all, I want to applaud you for defining a standard. There is no end to how much it will come to help you in the future.
Having said that, a couple of very subjective opinions from my part:
I don't like to embed type information in names, such as "TABLE_PERSON" or "PERSON_T" because it becomes confusing the second you replace a table with a view instead. At this point you could of course search and replace "PERSON_T" with "PERSON_VW" instead, but it kind of misses the point :)
The same goes for columns (although i can't see this in your example). Think of the "n_is_dead" column that gets changed from numeric to varchar.
Can a row exist in a table without being created (create_timestamp)? Declare columns as NOT NULL if they really can't be null. In fact, I start of having NOT NULL on most of my columns because it makes me think harder about the nature of the data.
I'm a fan of naming the primary key column something other than ID. For example
company(company_id, etc)
person(person_id, company_id, firstname etc)

I've heard some people have problems with O/R mappers that want you to have the primary key named "ID" at all times, but I don't know if this is still true of if this has changed recently.
It's not clear to me if you intented to embed (s,n,c) in the column names to indicate whether they are surrogate, natural or common key. But I also don't think this is a good idea. I feel that would "reveal" some implementation detail that doesn't fit naturally in the logical model.
It looks like you are exposing/embedding the foreign key relationship in the column names. I have never thought of this, but I think you will deeply regret this one. If not only because it makes the column names unbearably uggly :)
When choosing a name for an index. The only time I regret naming an index something is when I look at an execution plan and see "index_01" being used. I always wish I had put the column name in the index to make it visible in the xplan. I don't know the limit for an index name, but I always run into the limit on Oracle. So, try to come up with some rule for how to abbreviate the table name. The column name is the important thing here.
Regarding mixed case. I always (no exceptions) go with either ALL_UPPER_CASE or all_lower_case. The reason is that in the past I've been burned when migrating queries between databases when they treat case differently. Lately, I use all_lower_case because the typical font of our editors makes it easier to spot spelling errors in lower case than in upper case. And when I fail at things, it doesn't seem like the editor is SHOUTING AT ME ;)


text:
Q: jquery multiple pop up with dimmer I have code that works if you want one pop up with dimmer but I would like it to work with multiple on click popups. I'm not really sure on how to rework it to do multiple so some help would be appreciated. I've tried finding other pop up with dimmer jquerys but none of them seem to work for multiple.

//This is the function that closes the pop-up
function endBlackout(){
    $(".blackout").css("display", "none");
    $(".msgbox").css("display", "none");
}

//This is the function that closes the pop-up
function strtBlackout(){
    $(".msgbox").css("display", "block");
    $(".blackout").css("display", "block");
}

//Sets the buttons to trigger the blackout on clicks
    $(document).ready(function(){
    $("#btn1").click(strtBlackout); // open if btn is pressed
    $("#btn2").click(strtBlackout); // open if btn is pressed
    $(".blackout").click(endBlackout); // close if click outside of popup
    $(".closeBox").click(endBlackout); // close if close btn clicked
});
.blackout {
    background-color:#000;
    opacity:.7;
    filter:alpha(opacity=70);
    height:100%;
    width:100%;
    position:fixed;
    top:0;
    left:0;
    z-index:301;
    display:none;
    cursor:pointer;
}
.msgbox {
    background-color:#ccc;
    color:#000;
    width:70%;
    height:60%;
    position:fixed;
    top:20%;
    left:15%;
    border-radius:20px;
    padding:10px;
    z-index:302;
    display:none;
}
.closeBox {
    background-color:#CC0000;
    color:#FFFFFF;
    padding:8px;
    float:right;
    border-radius:3px;
    cursor:pointer;
    text-transform:uppercase;
}

Close

    Message Goes Here

<input type="button" id="btn1" value="Click Here" />

A: My suggestion would be to use the data attribute for your input buttons. This way, you only have 1 blackout box, except the information it displays is dynamic.
My code explained -
<input type="button" id="btn1" class="openBlackout" value="Click Here" data-message="Some Message for Click Here Button" />

The data-message attribute of the button contains some message, also I gave it a class name, so that the function can run whenever an element with that class name is clicked. It does not necessarily have to be a button, you can do the same with an image.
$(document).on('click', '.openBlackout', function(){
  strtBlackout($(this).data('message'));
});

I then added a parameter to your strtBlackout function which will be the message that is displayed.
With the HTML now looking like below -

Close

Message Goes Here

I changed added to your strtBlackout function in order to change that message.
function strtBlackout(message){
    $('.message').html(message);
    $(".msgbox").css("display", "block");
    $(".blackout").css("display", "block");
}

//This is the function that closes the pop-up
function endBlackout(){
    $(".blackout").css("display", "none");
    $(".msgbox").css("display", "none");
}

//This is the function that closes the pop-up
function strtBlackout(message){
    $('.message').html(message);
    $(".msgbox").css("display", "block");
    $(".blackout").css("display", "block");
}

$(document).on('click', '.blackout, .closeBox', endBlackout);

$(document).on('click', '.openBlackout', function(){
  strtBlackout($(this).data('message'));
});

//Sets the buttons to trigger the blackout on clicks
/*    $(document).ready(function(){
    $("#btn1").click(strtBlackout); // open if btn is pressed
    $("#btn2").click(strtBlackout); // open if btn is pressed
    $(".blackout").click(endBlackout); // close if click outside of popup
    $(".closeBox").click(endBlackout); // close if close btn clicked
});*/
.blackout {
    background-color:#000;
    opacity:.7;
    filter:alpha(opacity=70);
    height:100%;
    width:100%;
    position:fixed;
    top:0;
    left:0;
    z-index:301;
    display:none;
    cursor:pointer;
}
.msgbox {
    background-color:#ccc;
    color:#000;
    width:70%;
    height:60%;
    position:fixed;
    top:20%;
    left:15%;
    border-radius:20px;
    padding:10px;
    z-index:302;
    display:none;
}
.closeBox {
    background-color:#CC0000;
    color:#FFFFFF;
    padding:8px;
    float:right;
    border-radius:3px;
    cursor:pointer;
    text-transform:uppercase;
}

Close

Message Goes Here

<input type="button" id="btn1" class="openBlackout" value="Click Here" data-message="Some Message for Click Here Button" />
<input type="button" id="btn1" class="openBlackout" value="Click This" data-message="Some Message for Click This Button" />

A: One solution may be to create a new message box and new blackout element on each button click. So initially no blackout element or msgbox will exist.
var lastDialogZIndex = 0;

function createDialogWrapper(parent) {
    var dialogWrapper = document.createElement('div');
    $(dialogWrapper)
       .addClass('dialog-wrapper')
       .css('z-index', lastDialogZIndex)
       .appendTo(parent);

    return dialogWrapper;
}

function createBlackout(parent) {
    var blackout = document.createElement('div');
    $(blackout)
       .addClass('blackout')
       .css('z-index', lastDialogZIndex)
       .appendTo(parent);

    return blackout;
}

function createMsgBox(parent) {
    var msgBox = document.createElement('div');
    $(msgBox)
       .addClass('msgbox')
       .text('Message Goes Here')
       .css('z-index', lastDialogZIndex)
       .appendTo(parent);

    return msgBox;
}

function createCloseBox(parent) {
    var closeBox = document.createElement('div');
    $(closeBox)
       .addClass('closeBox')
       .text('Close')
       .css('z-index', lastDialogZIndex)
       .appendTo(parent);

    return closeBox;
}

function createDialogButton(parent) {
    var dialogButton = document.createElement('input');
    $(dialogButton)
       .addClass('openBlackout')
       .attr('value', 'Next dialog button')
       .attr('type', 'button')
       .css('z-index', lastDialogZIndex)
       .appendTo(parent);

    return dialogButton;
}

function buildDialog(parent) {
    var wrapper = createDialogWrapper(parent);
    var blackout = createBlackout($(wrapper));
    var msgBox = createMsgBox($(wrapper));
    var closeBox = createCloseBox($(msgBox));
    var nextDialogButton = createDialogButton($(wrapper));

    lastDialogZIndex = lastDialogZIndex + 1;
}

//dynamically create new dialog
function startBlackout() {
    var mainWrapper = $('#main-dialog-wrapper');
    buildDialog(mainWrapper);
}

// Remove the wrapper for the last dialog
function endBlackout() {
    $("#main-dialog-wrapper:last-child").remove();
    lastDialogZIndex = lastDialogZIndex - 1;
}

What's happening above is: you are creating the layout for the new dialog dynamically on each call for startBlackout().
Currently I use css attribute z-index in order to control which dialog is on top. (every other dialog shows on top of the other with higher z-index). If you have not used it, check it here: https://developer.mozilla.org/en-US/docs/Web/CSS/z-index
Since you can not click anywhere outside the dialog, the next button must be inside of it, so I currently create it dynamically with in startBlackout(), just for an example.
So, with this functionality, the html will look like this:

<input type="button" id="btn1" class="openBlackout" value="Open dialog 1" />

And you use your other functionality just as before (onClick methods are the same).
But after all, I would propose that you use a library like that one http://jquerymodal.com/ , no need to reinvent the wheel every day. (:

A: //add class

Close

    Message Goes Here

<input type="button" id="btn1" class="btn" value="Click Here" />

//use class as selector
 $(".btn").click(strtBlackout);

check fiddle: https://jsfiddle.net/giantomakin/yg7ckfpd/1/


text:
Q: ANY possible way to run the clang compiler from a Sandboxed app? OK, the question is fairly straightforward.
I have a sandboxed OSX app.
I want the user to be able to compile some C code (whatever he inputs).
But whenever I'm attempting a call to:
/usr/bin/env clang /the/path/to/the/source.c

I'm getting the following error in the logs:
xcrun: error: cannot be used within an App Sandbox.

Is there any way to circumvent this?

P.S. I've successfully done pretty much the same thing with Ruby, Python and PHP.

A: If you want to keep your app sandboxed you could try to add a Temporary exception key to your entitlements file:
com.apple.security.temporary-exception.files.absolute-path.read-only
More information on that here
Another way to achieve it would be the more troublesome way of creating an helper app (XPC-service) which is not sandboxed. There are also some details about XPC-services here.


text:
Q: Module functions appear undefined in outside scripts This code tells me that the parse function is not a function:
const  MyModule = require('./MyModule.js');

MyModule.parse('...');

In my module script it's defined like this:
MyModule = {};

MyModule.parse = function(data){

};

module.exports.MyModule = MyModule;

What am I doing wrong?

A: You have to understand that you are not exporting MyModule but an object (module.exports to be exact) with a member called MyModule (this is what you assigned to it).
If, in your code that requires MyModule, you console.log the result of your require, it will look like:
{ MyModule: {parse: [Function] } }

which is the module.exports object with a property (object) called MyModule that has a property (function) called parse.
So when you require you are getting the module.exports object that you assigned MyModule to and not just MyModule.
If you were to change your module.exports code to:
module.exports.X = MyModule;

Your code that required MyModule would then log:
{ X: {parse: [Function] } }

and you would call it as
MyModule.X.parse(...).

If you then changed your code to read
const MyFabulousModule = require('./MyModule');

you would then call it like:
MyFabulousModule.X.parse(...);

Finally, if you added another line to your module:
module.exports.Y = 4;

And then in your calling code added:
console.log(MyFabulouseModule.Y);

you would see the value 4 logged to the console.
Code:
MyModule.js
const MyModule = {};
MyModule.parse = function(data) {
    console.log(data);
};

module.exports.X = MyModule;
module.exports.Y = 4;

test.js
const MyModule = require("./MyModule");

console.log(MyModule);

MyModule.X.parse("hello world");

console.log(MyModule.Y);

To run: node test.js

A: First of all, you need to add a keyword in definition object.
const MyModule = {};
And you export the object, which you appoint to constant, so you need to call the object from it like this:
MyModule.MyModule.parse('...')


text:
Q: Quebra de Linha dentro da tag P não funciona Estou fazendo uma animação em JavaScript para que o texto tenha o efeito de estar sendo digitado. Estou usando uma única tag
 para o texto, e gostaria que quebrasse a linha nas tags
, mas elas estão sendo adicionadas como texto no HTML.
Segue código abaixo + Link do Codepen
Link: https://codepen.io/Sr-RIcci/pen/ExWdbBX

function typeWriter(elemento) {
  const textoArray = elemento.innerHTML.split('');
  elemento.innerHTML = "";
  textoArray.forEach((letra, i) => {
    setTimeout(() => elemento.innerHTML += letra, 75 * i);
  });
}

const titulo = document.querySelector('p');
typeWriter(titulo);
p::after {
  content: "|";
  margin-left: 5px;
  opacity: 1;
  animation: pisca 0.7s infinite;
}

@keyframes pisca {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}

Olá mundo
 Olá Universo
 Olá Vida

A: Isso ocorre porque o split() divide o
 também, o que você pode fazer é o uso de uma expressão regular, então ao invés de split() vocë pode usar String.prototype.match, veja como a array fica depois:

console.log("a b c d
 foo bar
 asd".match(/<\w+?>|./g))

A primeira parte da expressão é para pegar as tags <\w+?> e o . depois do pipe (|) é para pegar qualquer outro caractere (até espaços.
No entanto você poderia também fazer um for() bem elaborado para unir os caracteres quando for uma tag, navegando caractere por caractere, e nem precisa de split, exemplo (veja os comentários dentro do código):

const elemento = document.querySelector("p");
const texto = elemento.innerHTML;

let hasOpenTag = false;
let tmpTag;

//Limpa o campo
elemento.innerHTML = '';

for (let i = 0, j = texto.length; i < j; i++) {
    let letra = texto[i];

    /*
      Se o caractere for "<" então executa o continue;
      para que o setTimeout não seja executado e armazenará
      os próximos caracteres até encontrar o ">"
    */
    if (letra === '<') {
      tmpTag = letra;
      hasOpenTag = true;
      continue;
    }

    /*
      Se encontrar o ">" e antes dele teve um "<"
      então junta a tag toda na variável tmpTag e irá
      adicionar ao setTimeout
    */
    if (hasOpenTag && letra === '>') {
        letra = tmpTag + letra;
        hasOpenTag = false;
    }

    /*
      Se a variavel hasOpenTag for true irá armazenar
      todos próximos caracteres para formar a tag, até
      encontrar o ">" (da if anterior)
      adicionar ao setTimeout
    */
    if (hasOpenTag) {
       tmpTag += letra;
       continue;
    }

    setTimeout(() => elemento.innerHTML += letra, 75 * i);
}
p::after {
  content: "|";
  margin-left: 5px;
  opacity: 1;
  animation: pisca 0.7s infinite;
}

@keyframes pisca {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}

Olá mundo
 Olá Universo
 Olá Vida

A: Onde usa a propriedade Element.innerHTML use a propriedade Node.innerText que representa o conteúdo textual "renderizado" de um nó e seus descendentes isso significa que as quebras de linha são convertidas e compreendidas como \n.

function typeWriter(elemento) {
  const textoArray = elemento.innerText.split('');
  elemento.innerText = "";
  textoArray.forEach((letra, i) => {
    setTimeout(() => elemento.innerText += letra, 75 * i);
  });
}

const titulo = document.querySelector('p');
typeWriter(titulo);
p::after {
  content: "|";
  margin-left: 5px;
  opacity: 1;
  animation: pisca 0.7s infinite;
}

@keyframes pisca {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}

Olá mundo
 Olá Universo
 Olá Vida


text:
Q: How do I avoid a strong reference cycle when I need a strong reference in a closure? I currently have a strong reference cycle in my code that in the memory graph looks like:

I have filtered out the possibility that I am missing a [weak self], and I believe that it is another instance that is being captured by the closure shown (closure #3, which appears over and over in leaked SKSpriteNodes relating to my "Circle" class).
I have circles of type Circle captured in closures in various places. For instance:
let sprite = circle.sprite!

let changeTextureAction = SKAction.run
    {
        sprite.texture = newTexture

        if circle.bonusCircleType == .bonus4 || circle.bonusCircleType == .bonus2x
        {
            let oldArrowSprite1 = sprite.childNode(withName: "arrowSprite1")
            oldArrowSprite1?.removeFromParent()

            let oldArrowSprite2 = sprite.childNode(withName: "arrowSprite2")
            oldArrowSprite2?.removeFromParent()

            let (arrowSprite1, arrowSprite2) = getArrowSprites(circle)
            sprite.addChild(arrowSprite1)
            sprite.addChild(arrowSprite2)
            sprite.removeAction(forKey: "animateCircle")
        }

        else if circle.bonusCircleType == .bomb
        {
            let bombLeftEmitter = sprite.childNode(withName: "bombLeftEmitter")
            bombLeftEmitter?.isPaused = false

            let bombRightEmitter = sprite.childNode(withName: "bombRightEmitter")
            bombRightEmitter?.isPaused = false

            let bombTopEmitter = sprite.childNode(withName: "bombTopEmitter")
            bombTopEmitter?.isPaused = false
        }
    }

        sprite.run(SKAction.sequence([SKAction.wait(forDuration: time), SKAction.group([changeTextureAction, expandUpAction, Assets.sharedInstance.fxMatch4]), expandDownAction2]), withKey: "animateNewBonusCircle")

Is there a nice way for me to avoid the strong capture of circle by the closure without capturing it as unowned or weak? It is possible that the circle could be deallocated prior to this closure, in which case I get a crash (or with a weak-strong dance what I want to happen doesn't happen -- assume I have other functions where I do want to use, say, the circle's position, even though it may have just been removed).
My initial thought was I could substitute another object with the same properties that I could set as weak, but wasn't sure of the syntax to manage this.
Below is a screenshot of my allocations data, if it gives anyone a clue as to what I'm dealing with. I was suspicious of that call to add my map header, and allocations cites it as using 542 mb of memory, but when I deleted it that did not seem to recover me much memory usage. My guess is it was just the first instance in which my asset singleton was called, which contains texture atlases for my game. Now I'm thinking perhaps the atlases themselves are for some reason not being deallocated for some reason, but I actually manually deallocate these in code. Argh. Any thoughts appreciated.


text:
Q: Perl index function equivalent in Python The index() in Perl returns the location of a text between a start point and an endpoint. Is there something similar in Python. If not how can this be implemented.
Example :
in Perl, I would write an index function to return the index of a string as follows
start = index(input_text,text_to_search,starting_point_of_search)+off_set_length

What should be the equivalent in Python?

A: In python you can use str.find() to find the index of a sub-string inside a string :
>>> s
'123string 1abcabcstring 2123string 3abc123stringnabc'

>>> s.find('3a')
35

string.find(s, sub[, start[, end]])
  Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure. Defaults for start and end and interpretation of negative values is the same as for slices.

A: Assuming by "text" you mean string,
myString.find(substring)


text:
Q: Python ctypes: OSError: exception: access violation writing Good day!
I'm trying to make my little test dll to work in python code, using ctypes.
Here is my cppmul.cpp:
#include <iostream>

using namespace std;

extern "C" __declspec(dllexport) float cmul(int int_param, float float_param) {
    float return_value = int_param * float_param;
    std::cout << "In cmult: int: " << int_param << ", float: " << float_param << ", returning: " << return_value << std::endl;
    return return_value;
}

extern "C" __declspec(dllexport) void hello() {
    std::cout << "wheee" << std::endl;
    return;
}

Which I build with the next script:
g++ -c cppmul.cpp
g++ -shared -o libcppmul.dll -Wl,-out-implib,libcppmul.a -Wl,--export-all-symbols -Wl,--enable-auto-image-base cppmul.o

Then in the python script I just load dll and trying to call function:
# loads great
lib = ctypes.WinDLL(libname, winmode=1)
lib.hello.restype = None
# exception here
lib.hello()

And get: OSError: exception: access violation writing 0x0000000000009658
OS Windows 10 x64, Python 3.9 x64.
Any suggestions?
I think maybe the problem is a some kind of type mismatch? But there are no types in the hello() function, only a void as return and an empty argument list.

A: I reproduced the crash with winmode=1 and MSVC compiler.  Removing winmode=1 and using a relative path ('./cppmul') works correctly.
Note that CDLL is the correct function to use with default __cdecl calling convention.  WinDLL is for __stdcall calling convention, but both will work 64-bit builds.  It will only matter for 32-bit compatibility.
Here's a complete example calling both functions:
import ctypes as ct

lib = ct.CDLL('./cppmul')
lib.hello.argtypes = ()
lib.hello.restype = None
lib.cmul.argtypes = ct.c_int, ct.c_float
lib.cmul.restype = ct.c_float
lib.hello()
print(lib.cmul(2, 3.4))

Output:
wheee
In cmult: int: 2, float: 3.4, returning: 6.8
6.800000190734863


text:
Q: How to load es6 module into amd architecture I have a requirejs app and I want to append a react module / component into my page. The react module is written in babel / jsx. So I use the AMD transform plugin AND I concat them into one single file.
Now of course each react js file has export default class / function-part.
One of the react files has a function called startUp(html) which expects a html-element as parameter. This html parameter will be used by ReactDOM.render call.
My problem is that I cannot access the startUp-method in my AMD-module:
////////////////////// REACT AND BABEL / ES6 CODE /////////////////////////
// react-module.js
export default class MyReactContainer extends React.Component {
    render() {
        return
Just a DIV

    }
}

// react-main.js
export default function startUp(html) {
  ReactDOM.render(<MyReactContainer />, html);
}

//////////////////// EXISTING AMD MODULE /////////////////////////////////
// reactModuleIncluder.js
define(['./react-main'], function(reactMain) {

  function includeReactModule(html) {
      reactMain(html); // Here I want to call the startUp method
  }

  return includeReactModule;
});

Any idea what I can do? Or is this even possible?
EDIT: Solved the problem. Files were transpiled and concatenated in one single js file. Now I removed the concat-process and it works.

A: Solved the problem. Files were transpiled and concatenated in one single js file. Now I removed the concat-process and it works.


text:
Q: Anchoring GUI components in FireMonkey Just started testing FireMonkey and can't find a way to make dynamically sized/positioned components.
VCL had the Anchor property, FM does not.
Anybody see something I missed
Update:
Simple anchoring is not available in FM.  You have to create TLayouts and align those, then put the controls inside the panel to have them 'stick'.  If you used older version of Builder or Delphi, this will be the same as we used to have to do with TPanels.

A: Drop multiple TLayout components on the form and configure their alignment properties as desired.  Drop other components into these layouts and set their alignment properties relative to the TLayout they are contained in.  Seems to be working for me...

A: Here's the answer you are looking for:  FMX controls do not have anchors.
I imagine this will be a "next version" feature.

A: This is the answer to your question. The anchors property in VCL has apparently been replaced by Margins and Padding (due to performance considerations) and I found some documentation at the XE2 wiki (http://docwiki.embarcadero.com/RADStudio/en/FireMonkey_Application_Design). I doubt if anchors will be put in at a later date. To anchor two buttons (Ok and Cancel) at the bottom of a form on the right side do the following.See images below for the Ok and cancel button.

Place a small panel aligned to the bottom on the form, say about 40 height. Set the 'Margins' on the bottom panel to create a smaller space in which the buttons will live, make sure you set the align the button to alRight. For example the gap between the right edge of the form and the right most button has a margin of 15. The top and bottom margins were set to 12.  That anchors the right most button.
'Padding' is the opposite to a margin, the padding puts space outside the control. To the right most button I added a padding of 20 to the left side, this will be the space between the two buttons. For the second button to the left of the first all we need to do is set the align property to alRight, no need to adjust the padding or margins.

A: A quick look at the align property reveals many more choices than we had in previous Delphi versions:

Doesn't that solve your problem (at least partially).
I remember getting by OK for a long time just using nested panels and align to layout stuff.

A: You can use LiveBindings and expressions to set the properties of your control based on the parent control, though it's a lot of work.
Otherwise, use Margins and Padding (like HTML/CSS).


text:
Q: SwiftUI on macOS: Make subviews in .sheet use the available width I want to show a sheet with a title and action buttons upon clicking on a button in my macOS app. While this works, I do have an issue with the width of the containing buttons: they only use their intrinsically needed width instead of the width of their parent.
Out of the box, without providing any width values, the sheet looks like this:

I am currently hardcoding the width and applying it to the buttons – which works, but is not really sexy. The sheet then looks like this:

That's more like it. Here' my code:
struct ContentView: View {
    @State private var showSheet = false

    var body: some View {
        VStack {
            Text("My View")
            Button {
                showSheet = true
            } label: {
                Text("Show Sheet…")
            }

        }
        .sheet(isPresented: $showSheet) {
            SheetView(showSheet: $showSheet)
        }
    }
}

struct SheetView: View {
    @Binding var showSheet: Bool

    let width = CGFloat(200.0)

    var body: some View {
        VStack {
            Text("FooBar")
            Divider()

            Button {
                showSheet = false
            } label: {
                Label("Foo", systemImage: "paperclip")
                    .frame(width: width)
            }

            Button {
                showSheet = false
            } label: {
                Label("FooBarBuzz", systemImage: "paperclip")
                    .frame(width: width)
            }

            Button {
                showSheet = false
            } label: {
                Label("Cancel", systemImage: "xmark")
                    .frame(width: width)
            }
        }
        .padding()

    }
}

My goal though would be to set the width of all subviews in the sheet to the subview with the biggest width – how can I do that?


text:
Q: Python - Using an operator to assign a file name when using a class I am a somewhat Python/programing newbie, and I am attempting to use a python class for the first time.
In this code I am trying to create a script to backup some files. I have 6 files in total that I want to back up regularly with this script so I thought that I would try and use the python Class to save me writing things out 6 times, and also to get practice using Classes.
In my code below I have things set up for just creating 1 instance of a class for now to test things. However, I have hit a snag. I can't seem to use the operator to assign the original filename and the back-up filename.
Is it not possible to use the operator for a filename when opening a file? Or am I doing things wrong.
class Back_up(object):
    def __init__(self, file_name, back_up_file):
        self.file_name = file_name
        self.back_up_file = back_up_file
        print "I %s and me %s" % (self.file_name, self.back_up_file)

        with open('%s.txt', 'r') as f, open('{}.txt', 'w') as f2 % (self.file_name, self.back_up_file):
            f_read = read(f)
            f2.write(f_read)

first_back_up = Back_up("syn1_ready", "syn1_backup")

Also, line #7 is really long, any tips on how to shorten it are appreciated.
Thanks
Darren

A: If you just want your files backed up, may I suggest using shutil.copy()?
As for your program:
If you want to substitute in a string to build a filename, you can do it.  But your code doesn't do it.
You have this:
with open('%s.txt', 'r') as f, open('{}.txt', 'w') as f2 % (self.file_name, self.back_up_file):

Try this instead:
src = "%s.txt" % self.file_name
dest = "{}.txt".format(self.back_up_file)
with open(src, "rb") as f, open(dest, "wb") as f2:
    # copying code goes here

The % operator operates on a string.  The .format() method call is a method on a string.  Either way, you need to do the operation with the string; you can't have two with statements and then try to use these operators at the end of the with statements line.
You don't have to use explicit temp variables like I show here, but it's a good way to make the code easy to read, while greatly shortening the length of the with statements line.
Your code to copy the files will read all the file data into memory at one time.  That will be fine for a small file.  For a large file, you should use a loop that calls .read(CHUNK_SIZE) where CHUNK_SIZE is a maximum amount to read in a single chunk.  That way if you ever back up a really large file on a computer with limited memory, it will simply work rather than filling the computer's memory and making the computer start swapping to disk.

A: Try simplicity :)
Your line 7 is not going to parse. Split it using intermediate variables:
source_fname = "%s.txt" % self.file_name
target_fname = "%s.txt" % self.back_up_file
with open(source_fname) as source, open(target_fname) as target:
  # do your thing

Also, try hard avoiding inconsistent and overly generic attribute names, like file_name, when you have two files to operate on.
Your copy routine is not going to be very efficient, too. It tries to read the entire file into memory, then write it. If I were you I'd call rsync or something similar via popen() and feed it with proper list of files to operate on. Most probably I'd use bash for that, though Python may be fine, too.


text:
Q: Extract SOAP body as XML from WCF (vb.net) I am to build a client in vb.net that is to contact a JAX-WS web-service.
I intend to use the WCF framework, since this simplified the security setup.
The request is also built in the standard way, however I want to extract the body response directly to an XML (stream) as I need to transform it by an xlst stylesheet.
Furthermore, the response from the web-service will change over time and I do not want to do new builds every time a new property is added to the web-service, but only handle this in the stylesheet.
I have googled for an example, especially looked into these articles :
Custom Message Handling with WCF 1
Custom MEssage Handling with WCF 2
However, it is not clear to me how it works. From other articles I see that the message class seems to play an important role, but I do not see how I can get hold of that object through the WCF.
My competences in C# are limited so an example in vb.net would be appreciated.
Any help?

A: I ended up (as suggested) using the IMessageInspector. I did this by adding the following code to the auto-generated Reference.vb under the Service Reference:
Public Class WindchillResponseInspector 'System.ServiceModel.Description.IEndpointBehavior
    Implements IClientMessageInspector

    Public Sub AfterReceiveReply(ByRef reply As Message, correlationState As Object) Implements IClientMessageInspector.AfterReceiveReply

        Dim buffer As MessageBuffer = reply.CreateBufferedCopy(Integer.MaxValue)
        Dim replycopy As Message = buffer.CreateMessage()
        reply = buffer.CreateMessage

        ResponseStream = New IO.MemoryStream

        'Dim stream As New FileStream("myfile.xml", FileMode.Create)
        Dim xdw As Xml.XmlDictionaryWriter = Xml.XmlDictionaryWriter.CreateTextWriter(ResponseStream)
        '    reply.WriteMessage(xdw)
        replycopy.WriteBodyContents(xdw)
        xdw.Flush()
        'printStream(ResponseStream)
    End Sub

    Public Function BeforeSendRequest(ByRef request As Message, channel As IClientChannel) As Object Implements IClientMessageInspector.BeforeSendRequest
        Dim buffer As MessageBuffer = request.CreateBufferedCopy(Integer.MaxValue)
        Dim requestcopy As Message = buffer.CreateMessage()
        request = buffer.CreateMessage

        Dim requestStream = New IO.MemoryStream

        'Dim stream As New FileStream("myfile.xml", FileMode.Create)
        Dim xdw As Xml.XmlDictionaryWriter = Xml.XmlDictionaryWriter.CreateTextWriter(requestStream)
        '    reply.WriteMessage(xdw)
        requestcopy.WriteMessage(xdw)
        xdw.Flush()
        printStream(requestStream)
        Return Nothing
    End Function

End Class

In order to have this code working, I had to add it to the behavior:
Public Class WindchillInspectorBehavior
    Implements IEndpointBehavior

    Public Sub AddBindingParameters(endpoint As ServiceEndpoint, bindingParameters As BindingParameterCollection) Implements IEndpointBehavior.AddBindingParameters

    End Sub

    Public Sub ApplyClientBehavior(endpoint As ServiceEndpoint, clientRuntime As ClientRuntime) Implements IEndpointBehavior.ApplyClientBehavior
        Dim inspector As New WindchillResponseInspector
        clientRuntime.ClientMessageInspectors.Add(inspector)

    End Sub

    Public Sub ApplyDispatchBehavior(endpoint As ServiceEndpoint, endpointDispatcher As EndpointDispatcher) Implements IEndpointBehavior.ApplyDispatchBehavior

    End Sub

    Public Sub Validate(endpoint As ServiceEndpoint) Implements IEndpointBehavior.Validate

    End Sub
End Class


text:
Q: print file name with number of forms I have number of forms on a page and each one has a file input. When the user chooses a file, I would like to print the name of the selected file in the  that is inside the relevant form.
Why does it always print the file's name in the first form / class="fileNameBox"
?
JS:

HTML:
<form class="form-horizontal" action='#' method="post"  enctype="multipart/form-data">

            <textarea class="form-control comment-field" name="comment[text]" rows="1" ></textarea>

            <input type='file' name='file[]' class=' form-control file-field hideBox' maxlength='1' accept='gif|jpg|png|bmp' id="uploadFile"/>

            <button class="btn btn-primary submit" >SEND</button>

</form>

<form class="form-horizontal" action='#' method="post"  enctype="multipart/form-data">

            <textarea class="form-control comment-field" name="comment[text]" rows="1" ></textarea>

            <input type='file' name='file[]' class=' form-control file-field hideBox' maxlength='1' accept='gif|jpg|png|bmp' id="uploadFile"/>

            <button class="btn btn-primary submit" >SEND</button>

</form>


text:
Q: Execute command in Hudson as Post-build Actions I am new in Hudson.
I would like to execute a 'sourcecodeanalyzer' command in Hudson as Post-build Actions to generate an html report. Please let me know is this at all possible, if yes let me know the Hudson configuration steps to execute the command.
Your earliest response in this regard will be extremely helpful.
Thanks in advance.

A: Yes, it is almost certainly possible.
You will need to configure the Hudson project to have either a post-build action or a build step that runs your source code analyzer.
You've not stated in your question precisely which analyzer - it may be that Hudson already has a plug-in installed for it, in which case it may be listed on the Config page for the project at the bottom under Post-build Actions.
If not, next check to see if there's a plug-in available for the analyzer that hasn't been installed. From the main Hudson page select Manage Hudson, then Manage Plugins, and choose the Available tab. If there is a plug-in available it's definitely a good idea to use it as they are generally very well integrated with Hudson itself.
As a last resort you'll have to configure a build step to run the analyzer. Configure the project, then choose "Add build step". The drop-down that appears depends on your environment (Windows or Linux) but should include the ability to run a shell command or batch file. You can configure your analyzer there.
(If you're building Windows Visual Studio applications, a more flexible way that I've used is to use the MSBuild plug-in for builds, and have an MSBuild script that builds the application and then runs analysis tools. This can automate pretty much everything: mine builds the application, builds an acceptance test database, runs the acceptance tests and copies the result HTML to a page linked from the project.)

A: You could create a new job with a "Execute Shell" build step.  Type in the command you wish to run in the text box.  Then all you have to do is trigger this job by selecting:
"Build after other projects are built"
And select the trigger job from the list.
Hope this helps!

A: As a follow up to Jeremy's post. If you don't see the ability to add post build steps, you might work with maven jobs. In that case you need the Hudson M2 Extra Steps Plugin. This will give you pre and post build steps.

A: I use the 'Post build task' plugin to delete some resources after a build. You could call any shell script or command lines. If you want you could make the call depends on some logging output.

A: there is one best way to solve this:

*

*Upgrade to Fortify SCA 2.6.x (as of writing, latest version is 2.6.5).

*Download the Fortify Maven Plugin version 2.6 from https://customerportal.fortify.com and install it into your Hudson server's Maven repository.

*Update your project's pom to carry out the Fortify scan.  There is an example provided with the Maven plugin.

A: Currently , I am experiment with sonar plug in. It looks great check the details here
http://sonar.codehaus.org/a-new-hudson-plugin-for-a-closer-integration-with-sonar/
http://wiki.hudson-ci.org/display/HUDSON/Sonar+plugin


text:
Q: How to connect SPSS and ASP.Net May I connect SPSS and ASP.Net. I want to create forecast table in ASP.Net for using SPSS. How can I do this?

A: merthsoft's answer on the following stackoverflow posting provides a good starting point for getting spss up and running.
Using 64-Bit SPSS Libraries in C#
Basically copy the dlls provided by SPSS into your system32 folder on your server and wrap up the spssio64.dll's calls so you can call it from your code. If you are using C#, you can use the DLLImport attribute.
The hangups I personally had were including all of the appropriate dlls like... spssio64.dll, icudt32.dll, icuin32.dll and icuuc32.dll
When exporting your data, all columns need to be unique.
I hope by now you got it working, but for those who come across this in the future this may help.


text:
Q: Hot Spot Map in ArcMap and MATLAB I've tried out the Hot Spot Map tutorial for ArcMap, which is working just fine, and I'm now starting to make some modifications so that it fits my data sets.
Instead of aggregating the points as in the tutorial I added a column for the weighting.
The result, using the Hot Spot Analysis (Getis-Ord Gi*) (Spatial Statistics) tool, can be seen in this picture:

What I'm trying to do now is to repoduce these results via MATLAB, just to get an idea of how the algorithm, which is described here, works. If I'm getting it right, the GI-score is calculated from the distance between one feature and all the others and their weighting.
Using these formulas I came to the following result:

As you can see, it looks like all the hot spots and cold spots are located in stripes.
Does ArcMap use a different algorithm from what is stated in the documentation or am I missing out on something else?
FYI, I used the default settings for the Hot Spot Analysis tool.


text:
Q: truncate a Float in java 1.5 excluding setRoundingMode I want to truncate a float value  in Java.
Following are my requirements:

*

*if i have 12.49688f, it should be printed as 12.49 without rounding off

*if it is 12.456 in double, it should be printed as 12.45 without rounding off

*In any case if the value is like 12.0, it should be printed as 12 only.

  Condition 3 is to be always kept in mind.It should be concurrent with
  truncating logic.

P.S: I am using Java 1.5 . So i know how to do it in Java 1.6 i.e using Decimal Format and calling setroundingMode () Method.
I need to know for Java 1.5

A: Multiply, use Math#floor and divide before providing the number to the DecimalFormat. This is the same as cutoff roundig.
// Replace N with the desired number of decimals after the comma
number = Math.floor(1eN * number) / 1eN

This isn't perfect because of rounding errors in floating point calculation, so you will still have to specify N decimals to the DecimalFormat.

A (more expensive, but also more logical) alternative is to use a BigDecimal.
// Given as seperate statements for clarity, but these can be combined into a single line
// Replace "N" with the number of decimals after the comma
MathContext NDecimals = new MathContext(N, RoundingMode.FLOOR);
BigDecimal bdNumber = new BigDecimal(number, NDecimals);
number = bdNumber.doubleValue();

A: Convert it to string and truncate anything after the second digit after the period.
trim "0" and "." if having an "."
String x = Double.toString (12.456); // or Float.toString (12.49688f);

int pos = x.indexOf ('.');  //
if (pos >= 0) {
  int end = Math.min(pos + 2, x.length() - 1); // truncate after 2 digits
  while (x.charAt (end) == '0') end --;  // trim 0
  if (x.charAt (end) == '.') end --; // trim .
  x = x.substring(0, end + 1);       // really truncate
}

(tested, works in my environment)