text:
Q: Bad request for field slot 0,-1. numRows = 1, numColumns = 1 I keep getting this in my logcat every time I run my code and cannot figure out how to fix it.  When I update I get this error, I use similar code when I delete and that works fine. I used breakpoints on the update, it kept on going to the end of the function.  I thought that at startActivityForResult would go to the next page, but it does not.  The exact same code for startActivityForResult worked in another function
Here is the code for update
    public void edit_to_report_page(final View v) {

    LayoutInflater inflater = LayoutInflater.from(this);
    View addView = inflater.inflate(R.layout.new_vehicle, null);
    idNum = (EditText) addView.findViewById(R.id.deleteRecord);
    new AlertDialog.Builder(this)
            .setTitle("Edit a report")
            .setMessage("Enter the Id number of the report to edit")
            .setView(addView)
            .setPositiveButton("Edit",
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog,
                                int which) {
                            String id = idNum.getText().toString();
                            uniqueID = Long.parseLong(id);
                            newID(uniqueID);
                            info.open();

                            try {
                                boolean correctNumber = info
                                        .Exists(uniqueID);
                                if (!correctNumber) {
                                    Toast.makeText(getApplicationContext(),
                                            "Number not found",
                                            Toast.LENGTH_SHORT).show();

                                    info.close();

                                }else{

                                    info.close();
                                    intent = new Intent(v.getContext(),
                                            report.class);
                                    startActivityForResult(intent, 0);
                                }
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    })
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog,
                                int which) {
                            // TODO Auto-generated method stub

                        }
                    }).show();

}

Here is the code for delete that works
public void delete_db(View v) {

    LayoutInflater inflater = LayoutInflater.from(this);
    View addView = inflater.inflate(R.layout.new_vehicle, null);
    idNum = (EditText) addView.findViewById(R.id.deleteRecord);
    final Dialog d = new Dialog(this);
    final TextView tv = new TextView(this);

    new AlertDialog.Builder(this)
            .setTitle("Delete a report")
            .setMessage("Enter the Id number of the report to delete")
            .setView(addView)
            .setPositiveButton("Delete",
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog,
                                int which) {
                            String id = idNum.getText().toString();
                            long primaryId = Long.parseLong(id);
                            info.open();
                            try {
                                boolean inCorrectNumber = info
                                        .deleteInspection(primaryId);
                                if (inCorrectNumber) {
                                    Toast.makeText(getApplicationContext(),
                                            "Number not found",
                                            Toast.LENGTH_SHORT).show();

                                }
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            info.close();
                            dbInfo();
                        }
                    })
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog,
                                int which) {
                            // TODO Auto-generated method stub

                        }
                    }).show();
}

Here is the code in my dbAdapter for delete and Exists(update)
public boolean Exists(long _id)throws Exception
{

    Cursor c = db.query(DB_TABLE, new String[] { KEY_ROWID},
            "_id=" + _id, null, null, null, null);
     boolean exists=(c.getCount()>0);
    c.close();
    return exists;
}

public boolean deleteInspection(long _id)throws Exception
{
    int numResults = 0;
    numResults = db.delete(DB_TABLE,"_id=" + _id , null);
    return (numResults < 1);
}

Here is what I get in logcat

04-10 09:47:05.006: E/CursorWindow(2961): Bad request for field slot 0,-1. numRows = 1, numColumns = 1
04-10 09:47:05.016: D/AndroidRuntime(2961): Shutting down VM
04-10 09:47:05.027: W/dalvikvm(2961): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
04-10 09:47:05.046: E/AndroidRuntime(2961): FATAL EXCEPTION: main
04-10 09:47:05.046: E/AndroidRuntime(2961): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.signalsetapp/com.signalsetapp.inspectionchecklist.report}: java.lang.IllegalStateException: get field slot from row 0 col -1 failed
04-10 09:47:05.046: E/AndroidRuntime(2961):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-10 09:47:05.046: E/AndroidRuntime(2961):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-10 09:47:05.046: E/AndroidRuntime(2961):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-10 09:47:05.046: E/AndroidRuntime(2961):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-10 09:47:05.046: E/AndroidRuntime(2961):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-10 09:47:05.046: E/AndroidRuntime(2961):     at android.os.Looper.loop(Looper.java:123)
04-10 09:47:05.046: E/AndroidRuntime(2961):     at android.app.ActivityThread.main(ActivityThread.java:4627)
04-10 09:47:05.046: E/AndroidRuntime(2961):     at java.lang.reflect.Method.invokeNative(Native Method)
04-10 09:47:05.046: E/AndroidRuntime(2961):     at java.lang.reflect.Method.invoke(Method.java:521)
04-10 09:47:05.046: E/AndroidRuntime(2961):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-10 09:47:05.046: E/AndroidRuntime(2961):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-10 09:47:05.046: E/AndroidRuntime(2961):     at dalvik.system.NativeStart.main(Native Method)
04-10 09:47:05.046: E/AndroidRuntime(2961): Caused by: java.lang.IllegalStateException: get field slot from row 0 col -1 failed
04-10 09:47:05.046: E/AndroidRuntime(2961):     at android.database.CursorWindow.getString_native(Native Method)
04-10 09:47:05.046: E/AndroidRuntime(2961):     at android.database.CursorWindow.getString(CursorWindow.java:329)
04-10 09:47:05.046: E/AndroidRuntime(2961):     at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:49)
04-10 09:47:05.046: E/AndroidRuntime(2961):     at com.signalsetapp.inspectionchecklist.report.getInfoFromDB(report.java:129)
04-10 09:47:05.046: E/AndroidRuntime(2961):     at com.signalsetapp.inspectionchecklist.report.onCreate(report.java:111)
04-10 09:47:05.046: E/AndroidRuntime(2961):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-10 09:47:05.046: E/AndroidRuntime(2961):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-10 09:47:05.046: E/AndroidRuntime(2961):     ... 11 more

A: Glad to help,
adding so you can mark as answer :)
looks like "report.java:129" is the bad guy here, is that you code ? If so, could you mark it in the in-lined code above. Should help a bit with debugging this :D – erbsman 4 hours ago

A: Aaron i have same Exception and solution is Check your column name you want to access it from cursor is same name as exists in database .And also remove white space and first try to query in SQLITE browser And then try in coding and Make some Debugging ,I mean print query in logcat and copy ,and paste and sqlite Browser thats a key for you otherwise it take more time and difficulty to solve it!


text:
Q: Probability of having at least $j$ collisions when tossing $m$ balls into $n$ bins Suppose that we throw $m$ balls into $n$ bins uniformly and independantly at random. We consider collisions as distinct unordered pairs, e.g., if 3 balls are tossed in one bin, we count 3 collisions.
What is the probability of having at least $j$ collisions when we throw $m$ balls into $n$ bins, such that at least $j$ bins are empty at the end of the process?
##Case $m \leq n$:
As we suppose $m < n$, this question is in fact equivalent to computing the probability that we toss $m$ balls in $m-j$ bins. Indeed, we throw our $m-j$ first balls in distinct bins, and the $j$ remaining balls in these $m-j$ bins.
We can view tossing $m$ balls in $m-j$ as the following equation:
$$x_1 + x_2 + \cdots + x_{m-j} = m$$
where $x_i$ is the number of balls in bin $i$. The number of solutions in $\mathbb{N}$ of this equation is a $m$-combination on a set of size $m-j$, i.e., $\binom{m+m-j-1}{m} = \binom{2m - j - 1}{m}$.
The number of ways to choose $m-j$ bins out of $n$ is $\binom{n}{m-j}$.
The number of possibilities to throw $m$ balls in $n$ bins is $n^m$, thus
$$\mathbb{P}[\text{at least } j \text{ collisions}] = \frac{\binom{2m - j - 1}{m} \cdot \binom{n}{m-j}}{n^m}.$$
What do you think of this approach? Am I overcounting/undercounting something?
##Case $m > n$:
In my opinion, this case is much harder to solve.
As I count collisions as distinct unordered pairs, the total number of collisions is
$$\sum_{i = 1}^n \binom{x_i}{2}$$
where $x_i$ is the number of balls in bin $i$. Hence, to have exactly $j$ collisions, a necessary condition is to have $\sum_{i=1}^{n} \binom{x_i}{2} = j$. Let's tweak this equation a bit.
$$ \begin{align*}
\sum_{i=1}^{n} \binom{x_i}{2} = j & \iff \sum_{i=1}^n \frac{x_i!}{2 \cdot (x_i-2)!} = j\\
& \iff \sum_{i=1}^{n} \frac{x_i!}{(x_i-2)!} = 2j\\
& \iff \sum_{i=1}^n x_i(x_i-1) = 2j\\
& \iff \sum_{i=1}^n x_i^2 = 2j + \sum_{i=1}^n x_i\\
& \iff \sum_{i=1}^n x_i^2 = 2j + m
\end{align*}
$$
where the last equality follows from the fact the sum of the balls in each bins is the number of balls tossed.
Therefore, this problem is equivalent to solving the following problem: how many representations as a sum of $n$ squares does a number have? This problem seems far from trivial to me, as I did not find easy explicit formulas to work with.
However this approach was for finding exactly $j$ collisions, and I am interested in finding at least $j$ collisions. As $m > n$, we will have some collisions. We can express $m = qn + r$ for some $q, r \in \mathbb{N}$. The least collisions we will have is when the balls are uniformly distributed amongst the bins, thus we will have at least
$$C_{min} = \sum_{i=1}^r \binom{q+1}{2} + \sum_{i=1}^{n-r} \binom{q}{2}$$
collisions, which forces $j > C_{min}$. The problem thus becomes, in how many ways can we distribute $m$ balls into $n$ bins such that $\sum_{i=1}^n \binom{x_i}{2} \geq j$.
Here I am stuck, I can't find an easy way with combinatorics to solve this. I am fine with this problem being solved asymptotically, so if you have any ideas and/or references on the subject... :).
Thanks for reading and helping

#Edit
I think both cases above are wrong, because I was undercounting some things.
$m \leq n$" />
This image shows that the probability of having $j$ collisions do not increase nor decrease. I was expecting something like a gaussian, or at least something with a low probabiliy of having a few collisions, a high probability of having an average number of collisions, and a low probability of having a lot of collisions.
I thought about another way of counting, and I think the results I obtain are better. For that, I need the following Lemma, taken from this paper, page 16.
Lemma 1: The probability that exactly $k$ bins are not empty after throwing $m$ balls is $\frac{\binom{n}{k}k!S(m,k)}{n^m}$, where $S(m,k)$ is a Stirling number of the second kind.
With this Lemma, I obtain the following result.
Lemma 2: Let $m$ be the number of balls thrown uniformly and independently ar random into $n$ bins. The probability of having at least $j>1$ collisions and at least $j$ empty bins is
$$ \mathbb{P}[\text{at least } j \text{ collisions}] = \frac{1}{n^{m}} \sum_{i=1}^{n-j} \binom{n}{i} i! S(m,i). $$
Proof: As explained previously, the probability of having at least $j$ collisions and at least $j$ empty bins (or at most $n-j$ non-empty bins) is equal to the probability of tossing $m$ balls in at most $n-j$ bins. Let $A$ be the event "at most $n-j$ bins are not empty" and let $A_i$ be the event "exactly $i$ bins are not empty". Then $A = \cup_{i=1}^{n-j} A_j$ and $A_i \cap A_k = \emptyset$ if $i \neq k$, hence $\mathbb{P}[A] = \sum_{i=1}^{n-j}\mathbb{P}[A_j]$ and Lemma 1 concludes the proof. $\square$
We can see on the next plot that this results already seems closer to reality (this was plotted for $n = 500$, $m = 200$ and $j$ from $1$ to $1000$).

Moreover, with this approach, we don't need to separate the cases $m \leq n$ and $m > n$ (at least I think, you might need to correct me on this).
The downside is that now we have to work with a sum... and Stirling numbers of the second kind...
Do you guys have any idea to remove the sum and obtain an upper bound of this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Implementing jQuery hoverZoom in AngularJS ng-Repeat I am trying to implement jQuery hoverZoom in my project. It works fine in a normal html jquery app but when i try to run it in angular app using ng-repeat it breaks.
My guess is due to DOM & jQuery. I think I have to create a directive or something.
The working code is:
HTML
<link rel="stylesheet" href="assets/css/zoom_style.css?v=2">

<link rel="stylesheet" href="assets/css/jquery.hoverZoom.css">

Javascript

But when I chnage the HTML to:

It displays the images but hover effect is gone.
Please guide.
Not: Tried to replicate the code on jsFiddle

A: Yes you need to create a directive,
 .directive('hoverZoom', function() {
    return {
      link: function(scope, element){
           $(element).hoverZoom({speedView:600, speedRemove:400, showCaption:true, speedCaption:600, debug:true, hoverIntent: true, loadingIndicatorPos: 'center'});
       }
    };
  });

And in HTML,

Depending on your requirement you can try to improve this directive to pass the options for hoverZoom as well. https://docs.angularjs.org/guide/directive


text:
Q: Writing a list to a file more efficiently in Racket I want to write to a file the numbers from some lists (nested in a big list), e.g. for:
'((33 62 42 -19 30)
  (-22 -15 60 -55 24)
  (4 -48 22 -63 5))

To output in a text file:
33 62 42 -19 30
-22 -15 60 -55 24
4 -48 22 -63 5

I've written something that works, but I feel like it's a bit slow. Here's the code:
#lang racket

(define lists
  (build-list 100000
              (λ _  (for/list ([i (in-range 5)])
                      (random -100 100)))))

(define (list->file lst path)
  (let loop ([clone lst] [out (open-output-file path #:exists 'replace)])
    (if (empty? clone)
        (close-output-port out)
        (begin
          (for ([i (in-range (length (first clone)))])
            (display (list-ref (first clone) i) out)
            (when (< (+ i 1) (length (first clone))) (display " " out)))
          (unless (empty? (rest clone)) (display "\n" out))
          (loop (rest clone) out)))))

(time (list->file lists "test.txt"))

First I just generated a list of 100000 sublists, each with 5 random numbers, then in the list->file function I just output for each sublist each number followed by a space then move on recursively to the next sublist. Is there a way to make this more efficiently?

A: On my machine this is between 50ms - 100ms faster than your solution, preserving the exact same behavior:
(define (print-tuple tuple out)
  (cond [(empty? (rest tuple))
         (display (first tuple) out)]
        [else
         (display (first tuple) out)
         (display " " out)
         (print-tuple (rest tuple) out)]))

(define (list->file lst path)
  (call-with-output-file* path #:exists 'replace
   (lambda (out)
     (let loop ([clone lst])
       (cond [(empty? (rest clone))
              (print-tuple (first clone) out)]
             [else
              (print-tuple (first clone) out)
              (newline out)
              (loop (rest clone))])))))

I replaced the code for accessing the elements in a list using an index for something more idiomatic in Scheme - you should avoid using list-ref and length, those are expensive operations when working with lists! I also extracted the display logic to its own procedure (we could in-line it to shave a few milliseconds, but it's not worth it). And it's better to use call-with-output-file* or with-output-to-file, they're simpler because we don't need to explicitly close the output port.
I did a few mini-benchmarks and found that my code is faster than yours and also faster than Sorawee's solution - but it was pretty fast to begin with, so maybe there's no need for premature optimizations, you know they're the root of all evil.

A: I measure the time that your program runs. It's about 300ms, which is really fast already. How long do you expect it to take? Why do you think it is inefficient? Without a concrete objective or evidence that this is the bottleneck of your application, it's just a premature optimization.
Also, if performance really matters in your application, perhaps Racket might not the best fit. Racket (implementation) is not slow, but it's not aimed to be incredibly fast.
In any case, if I were to write this program, I would write it like this:
#lang racket

(define lists
  (build-list 100000
              (λ _  (for/list ([i (in-range 5)])
                      (random -100 100)))))

(define (list->file lst path)
  (with-output-to-file path #:exists 'replace
    (λ ()
      (for ([line (in-list lst)])
        (for ([e (in-list line)] [i (in-naturals)])
          (unless (zero? i) (display " "))
          (display e))
        (newline)))))

(time (list->file lists "test.txt"))

This program takes about 230ms to run, so it is faster than yours by about 70ms. I haven't carefully measured what causes the difference, but one thing I want to point out is that length and list-ref is a  linear time operation, so we usually want to avoid them. However, for a list of fixed, small size (length 5), it should be fine.


text:
Q: Document.location.href Problem in IE while developing a we app my requirement is to open outlook to send mail.
iam using using follwing code
document.location.href="mailTo:"+variable
Above code opens outlook in both firefox n IE but IE also redirects to document.location.href as its URL which is not possible to be opened in browser. This behavior is not found in Firefox it just opens outlook page to send mail.
Can anyone provide a fix for IE to avoid this URl redirection.

A: Do to a lack of a real code that you are using, I'm guessing you are using a link ( element), and you yre not returning false in the onclick event handler:
send email

A: Another possibility is that IE has the default e-mail client (which it presumably would invoke for a mailto URL) defined differently than Firefox does.


text: Q: Add to compare and wishlist not showing for custom module products Why are the 'Add to compare' and 'Add to wishlist' option not coming for the products in frontend when i hover the mouse over the product.


text:
Q: Nested computation of Cartesian-product of dice rolls I'm working on a Python program where I have to come up with all the ways to roll 9 4-sided dice. I've been trying to come up with a more concise way to write this line:
for n in [sum([a, b, c, d, e, f, g, h, i]) for a in range(1, 5) for b in range(1, 5) for c in range(1, 5) for d in range(1, 5) for e in range(1, 5) for f in range(1, 5) for g in range(1, 5) for h in range(1, 5) for i in range(1, 5)]:

I've seen syntax similar to:
for n in [sum([a, b, c, d, e, f, g, h, i]) for a, b, c, d, e, f, g, h, i in range(1, 5)]:

but this gives the error:
TypeError: 'int' object is not iterable

What's going on?

A: As Calum noted, you should use the built-in itertools for these common loops.
In your case, you would want:
import itertools
results = [sum(x) for x in itertools.product(range(1,5),repeat=9)]

range(1,5) represents the 4 sides of the die
repeat=9 represents the 9 dice you want to roll
See itertools.product for doc

A: you should look at itertools specifically looking at combinations and permutations

A: The simplest method is to use the itertools module. So in your particular case, we could do:
import itertools
itertools.combinations_with_replacement(range(1, 5), 9))

Which would produce a generator. If we were to iterate over it, we would see that it contains:
[(1, 1, 1, 1, 1, 1, 1, 1, 1),
 (1, 1, 1, 1, 1, 1, 1, 1, 2),
 (1, 1, 1, 1, 1, 1, 1, 1, 3),
 (1, 1, 1, 1, 1, 1, 1, 1, 4),
 (1, 1, 1, 1, 1, 1, 1, 2, 2),
 (1, 1, 1, 1, 1, 1, 1, 2, 3),
 ...
 (3, 3, 4, 4, 4, 4, 4, 4, 4),
 (3, 4, 4, 4, 4, 4, 4, 4, 4),
 (4, 4, 4, 4, 4, 4, 4, 4, 4)]

If we wanted the possible sums, we could easily extend this via sum and set:
>>> set(sum(dice) for dice in itertools.combinations_with_replacement(range(1, 7), 9))
set([9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54])

But we also know (via math!) that the range will be the closed set of [1*9, 4*9].


text:
Q: Difference between TFLite output multiplier and my manual calculation for a filter I am trying to understand the calculation process of TFLite inference. For Conv2D, I can calculate manually with same processes of TFLite inference with my input, filter and bias data.
But only one thing that I can't understand is 'output multiplier' value.
My quantized filter data is [[-89, 13, -84], [-36, -50, -127], [40, 105, 112]] and the scale of this is 0.001700334. From these values, I've got 0.870571017 and -9 with std::frexp() and the output multiplier is 1869537024 (=0.870571017 * (1<<31)).
But from tflite file, I've got 1738375644.
Why are these two different ? What am I missing ?


text:
Q: Restrict access for users on Windows 7
Possible Duplicate:
How to apply group policy settings to specific local accounts in Windows

The internet cafe where I've just started working has just received some new Windows 7 computers. We currently have no Windows Server /Active Directory in place but would like to restrict users from accessing features like changing the theme, accessing control panel etc.
I have tried changing user settings in the local group policy, but policy is applied, it seems to affect the main Administrator account aswell.
Is it possible to to 'lock down' features and settings for standard users without affecting the administrator account using built in Windows functionality?
Or if not, is there any (preferably free or discounted for a non-profit) 3rd party software that could achieve this?

A: Create a new group and insert the user that will be in login to it.
then change only the group policy.

A: Just create an Organizational unit an attach a new GPO to it.

A: I don't believe this is an exact duplicate of How to apply group policy settings to specific local accounts in Windows
When there's no domain, there are no shared groups or users for all the machines.
You could generate a policy file in the method described, and distribute it manually.
Another method is do generate .reg files containing the equivalent modifications.
this link points to documentation of all the group policy parameters, and their equivalent registry key. each setting can apply to users or the whole machine - so you can choose between

*

*restricting specific users, but not the administrator

*restricting the whole machine and disabling these restrictions to the administrator


text:
Q: InfoPath Secondary WCF Data Source's XML Structure I'm developing a WCF Service to be consumed by InfoPath 2007 forms. After adding the Service as a secondary Datasource, InfoPath itself will autogenerate a certain Structure. for example:

my Problem with this are the generated xpaths. displayname's xpath for example:
/dfs:myFields/dfs:dataFields/ns3:whoamiResponse/ns3:whoamiResult/q1:displayname

Since my Webservice has to replace an older one which is implemented in many forms with logic refferencing exactly a certain xpath i have to get the exact same xpath generated in my new Webservice.
How can i influence these generated prefixes like ns3:whoamiResult/q1:displayname ?
I noticed that q1 appeared after i changed the return type of my Operation from DataSet to a custom Class. And tns/ns1/ns2/ns3 .. is depending on Namespaces i changed in the [ServiceContract], [ServiceBehaviour] and some other Attributes.
[ServiceContract(Name="Webservice", Namespace = "BestNamespaceToBeEnteredHere")]
public interface IWebservice
{

    [OperationContract]
    //...
}

Could someone point me into the right direction? Can i somehow pass a cusstom Schema with the Webservice Response where i can define how the structure should look like?
cheers! phil

A: The Namespace property on your ServiceContract and DataContracts effect the namespaces used in the SOAP response.  The prefixes are typically arbitrary, and I think it is rather queer that InfoPath displays them, but there are a great many articles on how to influence them.
While I don't typically support link only answers, I list them below as I could not explain it as well as they already have:

*

*Changing prefixes in XML responses for WCF services

*Customize WCF Envelope and Namespace Prefix
Duplicates:

*

*Customize SOAP Header namespace prefixes in WCF

*Change namespace Prefix WCF Envelope


text:
Q: Animate button click and color
I made this button in Photoshop. I have plenty of graphic UI experience, but not much coding besides python and html/css.
I figured I would use javascript to animate the button being clicked and change color. I am very much a beginner and do not know my next step. Such as if I shouldn't create the button in photoshop but make it from scratch with code?
Or if I make a separate image that's red and it changes back and forth between images? But I'm not sure if that process would look smooth when it's clicked. This is all for a dashboard gui web app. I was playing around just trying to get a simple button to change colors using only code but I'm lost. I haven't been able to find anything related to what I'm doing which I think is crazy because how common UI's are created in Photoshopped and animated with code.
Javascript
    var button = document.querySelector('.button');

    button.onclick = function () {
      if (backgroundColor == green) {
        document.getElementById(id).style.backgroundColor = red";
}

CSS
.button {
  &:hover {
    background-color: green;
    cursor: pointer;
    cursor: hand;
  }
  width: 100px;
  height: 50px;
  background-color: green;
  color: white;
  text-align:center;
  line-height:50px;
  border-radius: 30px;
}

A: I would first attempt to do this with HTML & CSS since it'll be the easiest to maintain down the line (i.e. need a different size color? just a tweak a value in CSS).
From your description it sounds like you are effectively making a styled checkbox. You want to use semantic elements (i.e. not
 and ) wherever possible to improve the experience for screen readers and keyboard-only users. So create a checkbox in HTML, hide it, then style the element after it based on the value of the hidden checkbox.

/* hide the native element */
.your-button input {
  opacity: 0;
}

/* disable user selection */
.your-button,
.your-button * {
    -webkit-user-select: none;
       -moz-user-select: none;
        -ms-user-select: none;
            user-select: none;
}

/* The grey button */
your-button-elem {
  display: inline-block;
  width: 100px;
  height: 100px;
  background: linear-gradient(hsl(0, 0%, 100%), hsl(0, 0%, 80%));
  border-radius: 50%;
  position: relative;
  cursor: pointer;
  box-shadow: 0 6px 6px hsla(0, 0%, 0%, 0.3);
  transition: 60ms;
}

/* The colored status ring */
your-button-elem::before {
  content: '';
  position: absolute;
  top: -16px;
  right: -16px;
  bottom: -16px;
  left: -16px;
  background: hsl(162, 0%, 69%);
  border-radius: 50%;
  box-shadow: inset 0 0 4px hsla(0, 0%, 0%, 0.3);
  z-index: -1;
}

/* The dimple ontop of the button */
your-button-elem::after {
  content: '';
  position: absolute;
  top: 26px;
  right: 26px;
  bottom: 26px;
  left: 26px;
  background: linear-gradient(hsl(0, 0%, 80%), hsl(0, 0%, 98%));
  border-radius: 50%;
  box-shadow: inset 0 1px 6px hsla(0, 0%, 0%, 0.3);
}

/* The checked state */
input:checked ~ your-button-elem::before {
  background: hsl(162, 52%, 69%);
}

/* The pressed state */
input:active ~ your-button-elem,
your-button-elem:active {
  box-shadow: 0 1px 1px hsla(0, 0%, 0%, 0.3);
}

/* The focused state */
.your-button input:focus {
  outline: none;
}
input:focus ~ your-button-elem::before {
  box-shadow: inset 0 0 4px hsla(0, 0%, 0%, 0.3),
                    0 0 0 4px hsla(200, 100%, 50%, 0.3);
}
input:focus ~ your-button-elem:hover::before {
  box-shadow: inset 0 0 4px hsla(0, 0%, 0%, 0.3);
}

/***** Setup *******************/
* { margin:0; padding:0 }
html, body { height:100% }
body {
  display: flex;
  justify-content: center;
  align-items: center;
}

    <input type="checkbox">
    <your-button-elem></your-button-elem>

A: Here is an idea how you can create this button using CSS then you can easily adjust color, dimension, apply smooth effect, animation, etc:

.button {
  display: inline-block;
  margin: 20px;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: radial-gradient(circle at top, #f2f2f2, #ccc, #b3b3b3);
  position: relative;
  border: 12px solid #96c9b9;
  cursor: pointer;
  transition:0.5s;
}

.button:before {
  content: "";
  position: absolute;
  top: 22%;
  bottom: 22%;
  right: 22%;
  left: 22%;
  border-radius: 50%;
  border:1px solid #cecece;
  background: radial-gradient(circle at bottom, #f2f2f2, #ccc, #aaa);
}

.button:after {
  content: "";
  position: absolute;
  top: -1px;
  bottom: -1px;
  right: -1px;
  left: -1px;
  border-radius: 50%;
  border: 1px solid #b4b4b4;
  box-shadow: 0px 6px 9px #757373;
}

.button:hover {
 border-color:#9fdecb;
}

A:

 function btnclick() {
   var glow = document.getElementById("gldiv");
   var dimp = document.getElementById("dimple");
   var d = document.getElementById("dlght")
   if (dimp.style.display == "block") {
    glow.style.background = "#c9969d";
    dimp.style.display = "none";
    d.style.display = "none";
   }
   else {
    glow.style.background = "#96c9b9";
    dimp.style.display = "block";
    d.style.display = "block";
   }
  }
 body {
   overflow-x: hidden;
   background: #e7dede;
  }

  .mainbg {
   background: #e7dede;
   padding: 20px;
  }

  .gdiv {
   width: 100%;
   height: 100%;
   border-radius: 50px;
   background-color: #fff0;
   padding: 10px;
   transition: .5s all ease;
  }

  .glowdiv {
   margin: 100px auto;
   width: 100px;
   height: 100px;
   background: #c9969d;
   box-shadow: inset 0px 0px 3px #00000055;
   border-radius: 50px;
   transition: .5s all ease;
  }

  .gdiv:hover {
   background-color: #fff3;
  }

  .btninshadow {
   box-shadow: inset -1px -1px 3px #6d81a5;
   width: 100%;
   height: 100%;
   border-radius: 50px;
   padding: 15px;
  }

  .btndiv {
   height: 100%;
   width: 100%;
   background: linear-gradient(115deg, #f3f3f7, #b1bace);
   border-radius: 50px;
   box-shadow: -1px 3px 10px #00000099;
  }

  .btndimple {
   height: 100%;
   width: 100%;
   background: linear-gradient(115deg, #f3f3f7, #b1bace);
   border-radius: 50px;
   box-shadow: inset 2px 2px 3px #6d81a5cc;
   display: none;
   transition: .5s all ease;
  }

  .btndimlgt {
   width: 100%;
   height: 100%;
   box-shadow: 0px 0px 3px #fff;
   border-radius: 50px;
   display: none;
   transition: .5s all ease;
  }
<!DOCTYPE html>

 <meta charset="utf-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

A: You don't need JavaScript you can use css:
 .button {
  padding: 15px 25px;
  font-size: 24px;
  text-align: center;
  cursor: pointer;
  outline: none;
  color: #fff;
  background-color: #4CAF50;
  border: none;
  border-radius: 15px;
  box-shadow: 0 9px #999;
}

.button:hover {background-color: #3e8e41}

.button:active {
  background-color: #3e8e41;
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}

A: For normal button, your codes are very closed, just need to fix some syntax issues.
If you'd like to change the color of the image button, you can use the filter of css. But be aware of css:filter only being supporeted by mordern browser.
Update:
@Temani Afif already implemented one perfect css button, so I considered using SVG to do same thing. It might not be a good solution, just share what I tried.
PS: I don't have many aesthetics cells, so the SVG looks ugly, lol.
Below is one sample:

// for normal button
var button = document.querySelector('.button');
button.style['background-color'] = "green"; // or button.style.backgroundColor
button.onclick = function () {
  console.log(this.style['background-color']);  // or this.style.backgroundColor
  if (this.style['background-color'] == 'green') {
    this.style.backgroundColor = 'red';
  }
  else {
    this.style.backgroundColor = 'green';
  }
}

//for image button
const imageStyles = ['saturate', 'grayscale', 'invert'];
var imageIndex = 0;
document.querySelector('.imgbutton').onclick = function() {
  console.log(this.className);
  this.className =imageStyles[imageIndex++%imageStyles.length];
}
.button {
  width: 100px;
  height: 50px;
  background-color: green;
  color: white;
  text-align:center;
  line-height:50px;
  border-radius: 30px;
}

.button:hover {
  cursor: pointer;
  cursor: hand;
}

.saturate {
  filter: saturate(4);
}
.grayscale {
  filter: grayscale(90%);
}

.invert {
  filter: invert(90%);
}

input[type="checkbox"]:checked ~ svg circle:nth-child(1) {
  fill: black;
}
input[type="checkbox"]:checked ~ svg circle:nth-child(2) {
  fill: yellow;
}

Click me

 <input type="checkbox" style="display:none"/>
 <svg width="100" height="100">
   <circle id="circle1" cx="50" cy="50" r="40" stroke="#8dbab1" stroke-width="9" fill="#eaf2f0"></circle>
   <circle id="circle2" cx="50" cy="50" r="20" stroke="#edf9f5" stroke-width="2" fill="#d1d6d4"></circle>
 </svg>

A: You just want to alternate between two colors using the DOM:
        button.onclick = function () {
           const color = document.getElementById(id).style.backgroundColor;
           if (color =="green") document.getElementById(id).style.backgroundColor ="red";
else  document.getElementById(id).style.backgroundColor ="green";
    }


text:
Q: Funny observation about Experts-Exchange and Stack Overflow I was searching Google for a question about JavaScript string byte length and opened some of the results in a bunch of tabs without looking at the URLs. One of the pages was an Experts-Exchange question that was exactly what I was looking for.
(In my defense, I had searched Stack Overflow earlier and hadn't found a good enough answer, and was getting ready to ask the question myself, but thought I'd do some more Google digging first).
I scrolled down to the bottom of the page to actually see the answers, and what do I find?
The best answer on Experts Exchange... was a link to a question on Stack Overflow!
Haha. I literally lolled for a few seconds and then came here to share this wonderful find.
See it on EE directly or via Google.
Scroll down to the very last answer posted by andrejonker. Classic!

A: I'm not sure if the question is asking how to find the byte value of a string, or how many bytes it contains.  Either way, the accepted answer:

No can do in JavaScript, it's a highlevel language it's not C.

is the real "WTF?" here.

A: I've seen a few of those.
Experts-Exchange may be winning the battle of top results, but we're winning the war:

(source: buddycremeans.com)

A: If EE can get people to pay for links to SO, then kudos to them. As they say, there's one born every minute.
The silver lining is that EE visitors will discover a better resource. Sadly, however, we cannot help them change back to their original gender.


text:
Q: PDFTK server issues. Pdf file can't be sent to print in Chrome I'm using PDFTK server to generate pdf files in a website. Is a Linux environment and it was working fine until now. The pdf file is generated but when the user is using Chrome to view the pdf file, the print button doesn't do anything. If the user uses Firefox, no problem.
Any ideas?

A: Add allow printing in your pdftk command :
https://www.pdflabs.com/docs/pdftk-cli-examples/

pdftk 1.pdf output 1.128.pdf owner_pw foo user_pw baz allow printing


text:
Q: Extracting images from presentation file I am working on python-pptx package. For my code I need to extract all the images that are present inside the presentation file. Can anybody help me through this ?
Thanks in advance for help.
my code looks like this:
import pptx

prs = pptx.Presentation(filename)
for slide in prs.slides:
    for shape in slide.shapes:
        print(shape.shape_type)

while using shape_type it is showing PICTURE(13) present in the ppt. But i want the pictures extracted in the folder where the code is present.

A: The solution by scanny did not work for me because I had image elements in group elements. This worked for me:
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE

n=0
def write_image(shape):
    global n
    image = shape.image
    # ---get image "file" contents---
    image_bytes = image.blob
    # ---make up a name for the file, e.g. 'image.jpg'---
    image_filename = 'image{:03d}.{}'.format(n, image.ext)
    n += 1
    print(image_filename)
    with open(image_filename, 'wb') as f:
        f.write(image_bytes)

def visitor(shape):
    if shape.shape_type == MSO_SHAPE_TYPE.GROUP:
        for s in shape.shapes:
            visitor(s)
    if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
        write_image(shape)

def iter_picture_shapes(prs):
    for slide in prs.slides:
        for shape in slide.shapes:
            visitor(shape)

iter_picture_shapes(Presentation(filename))

A: A PowerPoint Presentation is just a zip file. Rename the .pptx to .zip, and you have the following:

Unzip the file, locate the media folder, and get the image files from media folder, in few lines code. Done. (No need to use python-pptx, its great lib to create pptx files)

A: A Picture (shape) object in python-pptx provides access to the image it displays:
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE

def iter_picture_shapes(prs):
    for slide in prs.slides:
        for shape in slide.shapes:
            if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
                yield shape

for picture in iter_picture_shapes(Presentation(filename)):
    image = picture.image
    # ---get image "file" contents---
    image_bytes = image.blob
    # ---make up a name for the file, e.g. 'image.jpg'---
    image_filename = 'image.%s' % image.ext
    with open(image_filename, 'wb') as f:
        f.write(image_bytes)

Generating a unique file name is left to you as an exercise. All the other bits you need are here.
More details on the Image object are available in the documentation here:
https://python-pptx.readthedocs.io/en/latest/api/image.html#image-objects

A: Use this PPTExtractor repo for reference.
ppt = PPTExtractor("some/PowerPointFile")
# found images
len(ppt)
# image list
images = ppt.namelist()
# extract image
ppt.extract(images[0])

# save image with different name
ppt.extract(images[0], "nuevo-nombre.png")
# extract all images
ppt.extractall()

Save images in a diferent directory:
ppt.extract("image.png", path="/another/directory")
ppt.extractall(path="/another/directory")


text:
Q: I want to upload an image from JSP page using BufferedOutputStream but object is not getting created an object of BOS @RequestMapping("/addImageAdmin")
public String addImageAdmin(@RequestParam("fname") String fname, @RequestParam("imgupload") MultipartFile file, ModelMap model) {
    if (!file.isEmpty()) {
        try {
            ImageUpload du = new ImageUpload();
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            String rootPath = System.getProperty("catalina.home");
            File dir = new File("Important" + File.separator);
            if (!dir.exists())
                dir.mkdirs();

            // Create the file on server
            File serverFile1 = new File(dir.getAbsolutePath() + File.separator);
            System.out.println("Before Stream");
            BufferedOutputStream stream1 = new BufferedOutputStream(new FileOutputStream(serverFile1));
            System.out.println("After Stream");
            stream1.write(bytes);
            stream1.close();
            du.setFname(fname);
            du.setImgupload(bytes);

            if (imageUploadSerImpl.saveImage(du)) {
                model.addAttribute("msg", "1");
            } else {
                model.addAttribute("msg", "0");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {

    }

    return "add/photogal";
}

Because of not creating an object of BufferedOutputStream save method is not getting called.. Please suggest.


text:
Q: css keyframes animation on modal when closing This the css for my modal overlay and the container
  .overlay {
    position: fixed;
    background-color: rgba(20, 20, 21, 0.5);
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    animation-name: fadeIn;
    animation-iteration-count: 1;
    animation-fill-mode: forwards;
    animation-duration: 350ms;
    animation-timing-function: ease-in-out;

  }

  .container {
    background: var(--color-white);
    max-height: 94vh;
    max-width: 62.5rem;
    z-index: 2;
    transform: none;
    border-radius: 4px;
    overflow: hidden;
    animation-name: slideUp;
    animation-iteration-count: 1;
    animation-fill-mode: forwards;
    animation-duration: 350ms;
    animation-timing-function: var(--animation-sharp);
  }

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(50%);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

Basically, the overlay will fade in and at the same time the container will slide up. At moment, when the modal is being opened, animation is working as expect but there's no animation at all when it's being closed. How can I make sure that there will be reverse animation when closing? So when closing, the container will slide down and overlay will fade out.


text:
Q: What is the difference between the different types of residuals in survival analysis (Cox regression)? I am fairly new to survival analysis. I was advised to look up and learn Schoenfeld residuals as part of a model diagnosis to see if the proportional hazard assumption has been satisfied.  Whilst looking this up I've seen references to many different types of residuals including:

*

*Cox-Snell

*Deviance

*Martingale

*Score

*Schoenfeld

What are the differences between these residuals and when is it recommended to use one over another? (I am happy for answers which are simply links to papers to go read.)

A: Cox-Snell residuals $r_{Ci}$, are used to assess a model's goodness-of-fit. By plotting the Cox-Snell residual against the cumulative hazard function a model's fit can be assessed. A well fitting model will exhibit a linear line through the origin with a unit gradient. It should be noted that it will take a particularly ill-fitting model for the Cox-Snell residuals to deviate significantly from this. It is also not uncommon to see some slight jumps occurring at the extremities of the graph. One criticism of Cox-Snell residuals is that they do not account for censored observations, therefore the adjusted Cox-Snell residuals were devised by Crowley & Hu (1977) whereby the standard Cox-Snell residual, $r_{Ci}$ could be used for uncensored observations and $r_{Ci} + \Delta$ whereby $\Delta = \log (2) = 0.693$, is used to adjust the residual.
Martingale residuals $r_{Mi}$ can be defined as $r_{Mi} = \delta_i - r_{Ci}$ where $\delta_i$ is a switch taking the value 0 if observation $i$ is censored and 1 if observation $i$ is uncensored. Martingale residuals take a value between $[1, - \infty]$ for uncensored observations and $[0,- \infty]$ for censored observations. Martingale residuals can be used to assess the true functional form of a particular covariate (Thernau et al. (1990)). It is often useful to overlay a LOESS curve over this plot as they can be noisy in plots with lots of observations. Martingale residuals can also be used to assess outliers in the data set whereby the survivor function predicts an event either too early or too late, however, it's often better to use the deviance residual for this.
A deviance residual, $r_{Di} = sgn(r_{Mi})\sqrt{-2 r_{Mi} + \delta_i \log{(\delta_i-r_{Mi})}}$ where the $sgn$ takes a value of 1 for positive martingale residuals and -1 for a negative martingale residual. A residual of high absolute value is indicative of an outlier. A positively valued deviance residual is indicative of an observation whereby the event occurred sooner than predicted; the converse is true for negatively valued residual. Unlike Martingale residuals, deviance residuals are mean centered around 0, making them significantly easier to interpret than Martingale residuals when looking for outliers. One application of deviance residuals is to jackknife the dataset with just one parameter modeled and test for significant difference in parameter coefficients as each observation are removed. A significant change would indicate a highly influential observation.
Schoenfeld residuals are slightly different in that each residual corresponds to a variable, not an observation. The use of Schoenfeld residuals is to test the proportional hazards assumption. Grambsch and Thernau (1994) proposed that scaled Schoenfeld residuals may be more useful. By plotting event time against the Schoenfeld residual for each variable, the variables adherence to the PH assumption can be assessed by fitting a LOESS curve to the plot. A straight line passing through a residual value of 0 with gradient 0 indicates that the variable satisfies the PH assumption and therefore does not depend on time. Schoenfeld residuals can also be assessed through a hypothesis test.


text:
Q: Find pointer/class using raw memory address Before I ask my question, I want to say I realize there are some "similar" questions but nothing (that I  can find) that specifically answers my question, so here goes.
I'm wondering if the following is possible. Lets say I create a new instance of a class, like so:
MyClass* classInstance = new MyClass();

I'm wondering if it's possible to store the raw memory address in say, a primitive type like an int. Then, somewhere in C++ no-mans-land where I do not have a pointer to classInstance, I can do something like this:
MyClass* myClassInstanceSomewhereInMemory = (MyClass*)0x12345678;
myClassInstanceSomewhereInMemory->workPlzKThx(); //Yay, it works!

In the case that this is possible, are there any risks involved? Is there any significant cost in overhead for such thing? I realize this pretty poor design, but unfortunately I am at the mercy of a third party here. So please do not chastise me for this, but feel free to chastise them. :)
An Explanation For This Madness
So just to explain a little further just why I have to do something as silly as this. I'm porting box2D over to an AIR Native Extension and as I referenced earlier, I am at the mercy of the AIR Runtime. The way it handles association between the native side and the Actionscript side is... messed up and further that, there are a ton of ridiculous rules for doing this association.
One such rule makes a real problem for situations like b2World->createBody(), which returns a pointer to a b2Body type (which has a private constructor). During this association I cannot simultaneously create a context to associate the new b2Body pointer with it, because during this call I am stuck within the context of b2World. So rather than slapping a bunch of dirty hacks together within classes like b2World and b2Body, I'm wondering if I can just use a primitive type like an int to store and return the memory address of the new b2Body.
I cannot return a pointer or a structure typed from C++ back to the Actionscript side. I can only associate with contexts... but I can return primitive types.

A: By far the easiest solution is a std::map<unsigned int, MyClass*>. Pretty much the only drawback is that after UINT_MAX allocations you'll have to go hunt for reusable values.

A: Many third party api will force you to use this type of pattern to pass data around.  The only issue that you will have is that if you use a primitive type of int like you have suggested then if you ever compile for a 64 bit platform then this code will not be portable as the primitive type int will not hold the maximum address available on a 64 bit platform.  You could use the built in type int_ptr which when compiled for 32 bit platforms is 32 bits and for 64 bit platforms is 64 bit to avoid this problem or you could use void* as the primitive type like the win32 CreateThread function or pthread_create function.

A: The appropriate value to be cast is intptr_t or uintptr_t, but I don't think that Adobe has these...
So putting C++ portability aside and just being practical, if you are in a 32-bit architecture, then an unsigned int should be fine, and in a 64-bit, an unsigned long, that is an integer long enough to hold the value of a pointer. The unsigned part is just to play safe, but you should be able to play without it also.
The main thing that you must be aware of is that the pointer types casted from and to the integer type must be identical. That is, the following is undefined behavior:
class  A {  };
class B : public A {};

B b;
A *pa = &b;
unsigned x = reinterpret_cast<unsigned>(&a);
B *pb = reinterpret_cast<B*>(x); //UB!

The last line should be:
A *pb = reinterpret_cast<A*>(x);

Or else:
B *pb = static_cast<B*>(reinterpret_cast<A*>(x));

A: Did you think of tagging this "AIR Native Extension" as well as C++? With the caveat that I don't know either box2d or AIR Native Extension it strikes me that you're probably trying to do something that others have attempted before and maybe something that Adobe prefer you not to do - possibly with good reason. For example:

I cannot return a pointer or a structure typed from C++ back to the
  Actionscript side. I can only associate with contexts... but I can
  return primitive types

Could you actually use a pointer within Actionscript or are you just retaining it in a primitive type so you can pass it back into the interface?
Maybe in this case you could store the pointer in an associative collection like a map and return the key as a handle. When you pass the handle back in, the C++ side could look up the pointer and cast appropriately given the context. That way you'd never pass the pointer per-se through the interface so you wouldn't be vulnerable to any pointer related issues.
Apologies if you were already thinking on these lines.


text:
Q: Create sObject dynamically I ve tried this script to create accounts from excel file and it works,but if this file had more fields ,I would have to store their values one by one.Is there a way to do this mapping using something like acc.put(fieldname,value) inside a loop?.
            String[] filelines = new String[]{};
            List<Account> accstoupload;
            StaticResource srObject = [select id,body from StaticResource
            Where Name = 'AccountUploadTemplate'];
            String contents = srObject.body.toString();

            filelines = contents.split('\n');

            accstoupload = new List<Account>();
            for (Integer i=1;i<filelines.size();i++)
            {
                String[] inputvalues = new String[]{};
                inputvalues = filelines[i].split(',');

                Account a = new Account();
                a.Name = inputvalues[0];
                a.ShippingStreet = inputvalues[1];
                a.ShippingCity = inputvalues[2];
                a.ShippingState = inputvalues[3];
                a.ShippingPostalCode = inputvalues[4];
                a.ShippingCountry = inputvalues[5];

                accstoupload.add(a);
            }
     insert accstoupload;

A: Put exact field API names in the header of excel which will be 0 index. Collect the fieldNames and the do as following (will work for any number of fields):
    filelines = contents.split('\n');
    accstoupload = new List<Account>();

    String[] fieldNames = filelines[0].split(',');
    for (Integer i=1, linesCnt=filelines.size() ; i<linesCnt ; i++) {
        String[] inputvalues = filelines[i].split(',');
        Account newAccount = new Account();
        for(Integer c=0, fCount=fieldNames.size() ; c<fCount ; c++) {
            newAccount.put(fieldNames[c],inputvalues[c]);
        }

        accstoupload.add(newAccount);
    }
    insert accstoupload;

A: Yes, you can do that. You can go through sObject class salesforce documentation wherein you can search for put method which serves your purpose.
public Object put(String fieldName, Object value)

So, if you want to create an Account object dynamically and set its value dynamically, you can probably store the mapping of the csv column label with the field names, object names, data type etc in custom settings or custom metadata and then use this custom setting data to set the values of sObject using put method of sObject class.
Here is an example where custom setting holds the mapping between Account object's API names with its corresponding column name in CSV file
//here you can have a key as the csv column header name
//if you have multiple objects, then you can create a unique key and then get the data object wise
//and use the map to get all fields
Map<String_dataset_name, CustomSettingName__c> mcs = CustomSettingName__c.getAll();

filelines = contents.split('\n');
for (Integer i=1;i<filelines.size();i++)
{
    String[] inputvalues = new String[]{};
    inputvalues = filelines[i].split(',');

    sObject acc = Schema.getGlobalDescribe().get('Account').newSObject();
    for(CustomSettingName__c cs : mcs.values()){
        acc.put(mcs.get(cs.csvColumnName__c).fieldAPIName__c,inputvalues[cs.csvColumnName__c]);
    }
    accstoupload.add(a);
}

A: Store the name of the field API's which are in the header, in a list. Make sure the name of the field in the header are field API name.
filelines = contents.split('\n');
List<String> fieldNames = filelines[0].split(',');

for (Integer i=1;i<filelines.size();i++)
{
    String[] inputvalues = new String[]{};
    inputvalues = filelines[i].split(',');

    Account a = new Account();

    for(Integer data=0;data<inputvalues.size();data++)
    {
        String api = fieldNames[data];
        String value = inputvalues[data];
        a.put(api, value);
    }

    accstoupload.add(a);
}


text:
Q: Filling vector with primes in a certain way I was asked to fill a given vector with prime numbers, I can't use any other vectors, arrays or collections. I've come up with something like this, but it doesn't work properly and I can't figure out why.
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

bool isPrime(int n){
    if (n<=1){return false;}
    for (int i = 2; i < n; i++){
        if (n % i == 0){
            return false;
        }
    }
    return true;}

int fillWithPrimesVec(vector<int>& vec){
    for (int i = 0; i < vec.size(); i++){
        for (int j = 0; j<INT_MAX; j++){
            if (isPrime(j)){
                vec.push_back(j);}
            else{continue;}
            }
        }

    return vec[0];
}

int main(){

int c[15];
size_t szc = sizeof(c)/sizeof(*c);
vector<int> d(szc,0);

cout << fillWithPrimesVec(d);

return 0;
}

Could anyone please help me?


text:
Q: Unable to git commit from crontab job I'm trying to do a git commit using a bash script.
I've setup a cron job to execute this script periodically. Everything works as expected if I execute the script directly.
For some reason, when the script is invoked from the crontab, the git commit fails. Here's the script :
#!/bin/bash
cd /mnt/ebs2/sitemap
echo "Calling java application to generate sitemap"
java -jar SiteMap-1.0-jar-with-dependencies.jar -i sitemapconfig.xml -o /mnt/ebs2/sitemap/website_sitemaps -url ADSKContentURL
echo "sitemap generation complete.."
cd website_sitemaps
chmod 750 *
echo "Updated file permission, commiting to git..."
git commit -am 'automated weekly update'
git push -u
echo "git commit done..."
cd ..

This is the output from the crontab :
Calling java application to generate sitemap
sitemap generation complete..
Updated file permission, commiting to git...
/mnt/ebs2/sitemap/WeeklyUpdate.sh: line 10: git: command not found
/mnt/ebs2/sitemap/WeeklyUpdate.sh: line 11: git: command not found
git commit done...

As you can see, it fails to execute git commit and git push, which works when the script is run directly.
Here's the crontab entry.
0 2 * * 2 /bin/bash /mnt/ebs2/sitemap/WeeklyUpdate.sh

I'm making sure that both crontab and the script is executed in bash.
I'm using CentOS 5.11.
Any pointers will be appreciated.
-Thanks,
Shamik
************ EDITED SOLUTION **************
Based on @CholNhial and @Marc, crontab needs the complete git path to execute the command. I've updated the script to use the full path.
#!/bin/bash
cd /mnt/ebs2/aknsitemap
echo "Calling java application to generate sitemap"
java -jar ADSKSiteMap-1.0-jar-with-dependencies.jar -i sitemapconfig_Elvis.xml -o /mnt/ebs2/aknsitemap/aknwebsite_sitemaps -url ADSKContentURL
echo "sitemap generation complete.."
cd aknwebsite_sitemaps
chmod 750 *
echo "Updated file permission, commiting to git..."
/usr/local/bin/git commit -am 'automated weekly update'
/usr/local/bin/git push -u
echo "git commit done..."
cd ..

A: As you can see from the output, the problem here is that when your script is running, it cannot find your git command. You should add the full path to all of your commands.
When bash is given a command, it first looks for built-in commands and then begins checking the for the command in $PATH. It is a common and easy mistake to assume that if your script runs when you run it directly from your shell that it will run the same anywhere, but this is not the case as you see here. The reason is that when you enter a login shell, you acquire a lot of extras as part of your environment. In particular, .bash_login is typically executed on login shells. This causes makes running commands more convenient, but it is a luxury that your cron job will not have.
As with any programming, it is best to not many any additional assumptions about your environment. If it is something that your script depends upon, it is best to state it explicitly. This goes for full paths to any command.
If you need to locate the path for a command, from your shell, you can run something like:
which git

This should give you the full path, which you could then add to your script. Then simply replace git with /your/full/path/to/git in your script.


text:
Q: Hudson/jenkins: disable the failed build What is the preferred way to disable the periodical build when it has failed? Quick search showed that there is a Prerequisite build step plugin, but that fails the build, and I need the build to be completely disabled until manual intervention.
Thanks.

A: There is a button "Disable project" on the project status page. I simulate button click by HTTP POST message with data "Submit=\"Disable Project\"" like this
wget  --post-data  "Submit=\"Disable Project\"" ${JOB_URL}disable

right from the bash script which runs the build (project). The whole code can look like this
set +e
#  Run test/build
#  ....
if [ $? -ne 0 ];
then
  wget  --post-data  "Submit=\"Disable Project\"" ${JOB_URL}disable
#  Or you can use following to disable one job from another
#  wget  --post-data  "Submit=\"Disable Project\"" http://<Server>/job/$JOB_NAME/disable
  exit -1
fi

This is a rather old question, so I guess there was no Disable/Enable button in Jenkins GUI than. If Jenkins is protected by a password you will need to make wget to login first, store cookies in some file and in the second file add the cookie.

A: Okay, I think I managed to find a solution.

*

*Retry Failed Builds plugin didn't work because it could not override the default project schedule, so the failed project got built again and again.

*Naginator plugin didn't work because the delay is not configurable.

*Prerequisite build step plugin is not suitable.

The solution is to install the Groovy Postbuild Plugin, which is run under the Jenkins JVM and exposes the Jenkins instance publically. So it is possible to programmatically disable the current build directly in the Project configuration:
if (manager.build.result.isWorseThan(hudson.model.Result.SUCCESS)) {
  manager.build.project.disabled = true
}


text:
Q: Building an Identity Management System using Microsoft Azure I'm looking to build an identity management system with role based access control using Microsoft azure and .net.
I was just wondering if anyone could provide some pointers about it. I want to setup authentication, with access control depending on a users role such as admin.
Any help would be appreciated.

A: http://identityserver.codeplex.com/


text:
Q: How to increase width of easy ui tooltip I want to display a tooltip on an image. The width of the tooltip is not enough to include all the contents of the tooltip. How to increase its width so that the tooltip contents can be fit into tooltip.
Images and Tooltip contents are generated dynamically.

A: <a href="#" class="easyui-tooltip" data-options="
            content: $('

'),
            onShow: function(){
                $(this).tooltip('arrow').css('left', 20);
                $(this).tooltip('tip').css('left', $(this).offset().left);
            },
            onUpdate: function(cc){
                cc.panel({
                    width: 500,
                    height: 'auto',
                    border: false,
                    href: '_content.html'
                });
            }


text:
Q: Mysql insert and select id of inserted I am inserting 1 row in mysql table that has auto_increment id value and want to get id of that row.
Do you know some construction like
{
 INSERT INTO some_table (`name`) VALUES ('test name')
 ON SUCCESS RETURN id
}

Table structure:
id: int not null auto_increment Primary key
name: Varchar (20)

I read about LAST_INSERT_ID, but if my script was called simultaneously, there is a change of 2 different inserts and LAST_INSERT_ID can return wrong value.
I am using php and prepared statements that does not allow several commit and/or rollback.
Thanks for ideas.

A: You have wrong assumptions about multiuser use of PHP PDO. Last insert ID is stored in PDO object created upon connection. So this "last insert ID" value is stored per connection. This way simultaneous calls will not interfere with each other.
Here's manual reference.

A: First do the insert
INSERT INTO some_table (`name`) VALUES ('test name');

Then immediately after do
SELECT id FROM some_table WHERE name = 'test name';

And make sure you capture the output of latter one (this may vary depending on how you connect to your DB).
EDIT: Alternatively, you could do this right after the insert:
SELECT id FROM some_table WHERE name = 'test name' ORDER BY id DESC LIMIT 1

This way you can avoid getting an earlier input with the same name.

A: try this
$sql = "INSERT INTO some_table (`name`) VALUES ('test name')";
$result = mysql_query($sql);
$last_id =  mysql_insert_id();


text:
Q: Titanium ScrollView does not scroll left to right I am building an app on Titanium. Well the idea is we want the scrollview to scroll from left to right or vice versa.
    <ScrollView id="svForm" backgroundColor="green" top="10" width="100%" height="200"
        scrollType = "horizontal" layout="horizontal" >

            <View width="23%" height="90%" top="0" borderColor="#FFFFFF" borderWidth="1" backgroundColor="brown">
                <Label>
                    1
                </Label>
            </View>
            <View width="23%" height="90%" top="0" borderColor="#FFFFFF" borderWidth="1" backgroundColor="orange">
                <Label>
                    2
                </Label>
            </View>
            <View width="23%" height="90%" top="0" borderColor="#FFFFFF" borderWidth="1" backgroundColor="yellow">
                <Label>
                    3
                </Label>
            </View>
            <View width="50%" height="90%" top="0" borderColor="#FFFFFF" borderWidth="1" backgroundColor="blue">
                <Label>
                    4
                </Label>
            </View>

    </ScrollView>

But it doesn't do that. the last view (since it doesnt fit anymore) goes down. How can i implement this right? Is there a setting to be set that all the views need to sit side by side? I also tried to put this on a view and still dont work.
Your help will be appreciated. Thanks!

A: This works for me:
<ScrollView id="svImage" height="Ti.UI.SIZE" width="Ti.UI.FILL" scrollType = "horizontal" layout="horizontal"></ScrollView>

Use this in alloy xml file and add views from alloy xml or from js file using add method.

A: i added scrollview properties
<ScrollView id="svForm" backgroundColor="green" top="10" height="200"
scrollType = "horizontal"
contentWidth =  'auto'
contentHeight = 'auto'
showVerticalScrollIndicator = "true"
showHorizontalScrollIndicator = "true">

and it works fine now.


text:
Q: Undefined dynamic lookup in cx_oracle installation on Mac OSX 10.10 I am trying to install cx_oracle for use with python. I have followed these two guides (1) (2) and have done some trial and error with the different steps that each take as well as uninstalling all and trying each guide on their own. Regardless I am still stuck with a bunch of warnings at the build and then get this error upon actually trying to install:

cc -bundle -undefined dynamic_lookup -arch x86_64 -arch i386 -Wl,-F. -arch x86_64 build/temp.macosx-10.10-intel-2.7-11g/cx_Oracle.o -L/Users//oracle/instantclient_11_2 -lclntsh -o build/lib.macosx-10.10-intel-2.7-11g/cx_Oracle.so -shared-libgcc
ld: library not found for -lclntsh
clang: error: linker command failed with exit code 1 (use -v to see invocation)
error: command 'cc' failed with exit status 1

The python error that accompanies it that is generated by pip is

Command "/usr/bin/python -c "import setuptools, tokenize;file='/private/var/folders/vn/12yxd3j51zq6srt57txjnkssfm4bvn/T/pip-build-71LWsF/cx-Oracle/setup.py';exec(compile(getattr(tokenize, 'open', open)(file).read().replace('\r\n', '\n'), file, 'exec'))" install --record /var/folders/vn/12yxd3j51zq6srt57txjnkssfm4bvn/T/pip-M7g1qH-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/vn/12yxd3j51zq6srt57txjnkssfm4bvn/T/pip-build-71LWsF/cx-Oracle

I am thinking this might have to do with the architecture tags but I have no experience in how to fix that. Thanks for your help!

A: I had a similar problem and this helped,
export ARCH=x86_64


text:
Q: Contagem de Resultados na BD para paginação Estou com um problema, eu quero saber quantos dados existem na Base de Dados, mas com este código está a retornar -1 já utilizei este código para outros trabalhos (só que com mysql), neste caso é com SQL Server
$pag = (isset($_GET['pag'])) ? strip_tags((int)$_GET['pag']) : '1';

                                $maximo = '6';//produtos por pagina

                                $stmt2 = $conn->prepare("SELECT * FROM cl");
                                $stmt2->execute();
                                $totalRegistros2 = $stmt2->rowCount();
                                $paginas2 = ceil($totalRegistros2/$maximo);

                                if(isset($_GET['pag'])){
                                    if (($_GET['pag']>$paginas2)||($_GET['pag']<1)){
                                        $pag=1;
                                    }
                                }

                                $inicio = ($pag * $maximo) - $maximo;
                        echo $totalRegistros2;
                        echo $count;

A: Da documentação do PHP em relação à função rowCount()

If the last SQL statement executed by the associated PDOStatement was
  a SELECT statement, some databases may return the number of rows
  returned by that statement. However, this behaviour is not guaranteed
  for all databases and should not be relied on for portable
  applications.

Se a última instrução for um SELECT não é garantido que o rowCount() devolva o número de registos. Depende do SGBD.
Se queres saber o número total de registos podes sempre fazer
$sql = "SELECT count(*) AS total_records FROM cl";
$rs_result = $db_connection->query($sql);
$total_records = $rs_result->fetch_assoc()['total_records'];

A: Você pode usar SELECT count(*) FROM cl para saber quantas linhas/registros essa tabela possui.

A: Aqui fica direitinho com PDO
$stmt2 = $conn->prepare("SELECT count(*) AS total_records FROM cl");
$stmt2->execute();
$total_records = $stmt2->fetch(PDO::FETCH_ASSOC)['total_records'];


text:
Q: Python sum of classes I want to define a class AorB, such that all A's are AorB's, and all B's are AorB's, and these are all the AorB's. Of course, A and B should be subclasses of AorB. The problem is in AorB.__init__, when I can't convince self it should be something else. I can define an AorB factory, but I'd rather have AorB constructor if possible.
class AorB:
    def __init__(self,par):
        if par: self=A(par) #!
        else: self=B()      #!
    @staticmethod
    def from_par(par):
        if par: return A(par)
        else: return B()
class A(AorB):
    def __init__(self,par):
        self.par=par
class B(AorB):
    def __init__(self):
        pass
print(
    AorB.from_par(5),
    AorB.from_par(0),
    AorB(5),
    AorB(0),
    sep="\n")

I know assignment to self doesn't work here, but I just wanted to show intention. As I said, factory (from_par) works fine, I just want to call it as AorB, not as AorB.from_par.
PS. I know, __init__ is probably too late, type of self is already determined. Feel free to use metaclasses in your answer. It's time I learn something useful about them. :-)

A: You can't, not with __init__. Once __init__ is being called, the instance is already created.
You want a factory function instead:
class AorB: pass

class A(AorB):
    def __init__(self,par):
        self.par=par

class B(AorB):
    def __init__(self):
        pass

def AorB(par):
    return A(par) if par else B()

From an API point of view, there is no difference; AorB is a callable that produces either an A() or a B() instance.
The other possible route involves defining a __new__ function instead; this is the class constructor:
class AorB:
    def __new__(cls, par=None):
        if cls is not AorB: return super().__new__(cls)
        return super().__new__(A) if par else super().__new__(B)

class A(AorB):
    def __init__(self, par):
        self.par = par

class B(AorB):
    def __init__(self, par=None):
        pass

Which is just a more involved factory function, really. Note that the __new__ method returns the result of super().__new__ of one of the subclasses based on par, so both A and B will be passed a par parameter, wether they want one or not.
The if cls is not AorB line is needed to allow instantiating A() or B() directly; you can omit that line if that is not a requirement and only the AorB factory class is used.


text:
Q: C++ cross compile WxWidgets with MXE using CMAKE I am trying to make a CMAKE file that allows me to cross compile a WxWidgets application From Ubuntu For Windows.
My tools are all installed correctly, and I am able to run:
i686-w64-mingw32.static-gcc main.cpp $(i686-w64-mingw32.static-wx-config --cxxflags --libs) -o main.exe -std=c++11 -lstdc++

and produce a working output.
But I have been unsuccessful in finding a way to convert this into a CMAKE file. Does anyone have any resources or even examples of a working example?
Here is an example of my non-working file:
cmake_minimum_required(VERSION 3.11)

SET (PROJECT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
SET(PROJECT_NAME "WxWidgets")
SET(CMAKE_C_COMPILER i686-w64-mingw32.static)
project(
  ${PROJECT_NAME}
  VERSION 1.0
  LANGUAGES CXX)

  SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} (i686-w64-mingw32.static-wx-config --cxxflags --libs) -L /home/kevin/wxWidgets/include/ -Wall -std=gnu++2a -static -g")

  file(GLOB all_SRCS
        "${PROJECT_SOURCE_DIR}/src/*.h"
        "${PROJECT_SOURCE_DIR}/src/*.hpp"
        "${PROJECT_SOURCE_DIR}/src/*.c"
        "${PROJECT_SOURCE_DIR}/src/*.cpp"
        "${PROJECT_SOURCE_DIR}/src/**/*.c"
        "${PROJECT_SOURCE_DIR}/src/**/*.cpp"
        "${PROJECT_SOURCE_DIR}/src/**/*.hpp"
        )

  add_executable(${PROJECT_NAME} ${all_SRCS})

I am running the command:
i686-w64-mingw32.static-cmake ..

within my build directory.
By removing:
**(i686-w64-mingw32.static-wx-config --cxxflags --libs) -L /home/kevin/wxWidgets/include/**

...I am getting the error:
fatal error: wx/wxprec.h: No such file or directory
    8 | #include "wx/wxprec.h"

I have this file I checked with locate:
$ locate wx/wxprec.h
/home/kevin/mxe/usr/i686-w64-mingw32.static/include/wx-3.1/wx/wxprec.h
/home/kevin/wxWidgets/include/wx/wxprec.h
/usr/local/include/wx-3.3/wx/wxprec.h

EDIT:
Thanks to @vre's comment, I have updated my CMakeLists.txt file and have moved closer, it seems now that I just need to link correctly Here is what I have:
cmake_minimum_required(VERSION 3.11)

SET (PROJECT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
SET(PROJECT_NAME "WxWidgets")
SET(CMAKE_C_COMPILER i686-w64-mingw32.static)
project(
  ${PROJECT_NAME}
  VERSION 1.0)

  SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -std=gnu++2a -static -g")

  file(GLOB all_SRCS
        "${PROJECT_SOURCE_DIR}/src/*.h"
        "${PROJECT_SOURCE_DIR}/src/*.hpp"
        "${PROJECT_SOURCE_DIR}/src/*.c"
        "${PROJECT_SOURCE_DIR}/src/*.cpp"
        "${PROJECT_SOURCE_DIR}/src/**/*.c"
        "${PROJECT_SOURCE_DIR}/src/**/*.cpp"
        "${PROJECT_SOURCE_DIR}/src/**/*.hpp"
        )

  add_executable(${PROJECT_NAME} ${all_SRCS})

  include( "${wxWidgets_USE_FILE}" )
  find_package(wxWidgets REQUIRED)
  target_include_directories(${PROJECT_NAME} PUBLIC /home/kevin/mxe/usr/i686-w64-mingw32.static/include/wx-3.1/ /home/kevin/mxe/usr/i686-w64-mingw32.static/lib/wx/include/i686-w64-mingw32.static-msw-unicode-static-3.1/)
  target_link_directories(${PROJECT_NAME} PRIVATE /home/kevin/mxe/usr/i686-w64-mingw32.static/lib/)

But sadly, I have many linker errors such as:
undefined reference to `wxFrame::GetDefaultIcon() const'


text:
Q: Render Value Only After Error Handling and Fetch is complete I am new to React JS and still struggling in mastering a few concepts.
I am trying to do error handling for my code and only display the API response only after the Fetch is complete.
Below I have my code which is what I have done.
import React, { useState, useEffect } from "react";

function Transaction({ response }) {
  const [transaction, setTransaction] = useState([]);
  const token = "2c506c6b-d880-36bb-bdba-a035d1464b35";

  const requestOptions = {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`
    },
  };

  useEffect(() => {
    fetch(
      "https://api.flash-internal.flash-group.com/ecommerceManagement/1.0.0/api/transaction/5KISDW53",
      requestOptions
    )
      .then((response) => response.json())
      .then((data) => setTransaction(data));
  }, []);

//   console.log(transaction.result.details[0].vouchers[0].result);

  return (
    <>

            Hello
            Transaction Status: {transaction.status}

    </>
  );
}

export default Transaction;

And below is how I am trying to do some clean error handling. Can someone help me, or at least refer me to where I can learn how to do this properly.
import React, { useState, useEffect } from "react";

function Transaction({ response }) {
  const [transaction, setTransaction] = useState([]);
  const token = "2c506c6b-d880-36bb-bdba-a035d1464b35";

  const requestOptions = {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
  };

  function handleErrors(response) {
    if (!response.ok) {
      throw Error(response.statusText);
    }
    return response;
  }

  useEffect(() => {
    fetch(
      "https://api.flash-internal.flash-group.com/ecommerceManagement/1.0.0/api/transaction/5KISDW53",
      requestOptions
    )
      .then(handleErrors)
      .then((response) => console.log("ok"))
      .catch((error) => console.log(error))
      .then((response) => response.json())
      .then((data) => setTransaction(data));
  }, []);

  //   console.log(transaction.result.details[0].vouchers[0].result);

  return (
    <>

        Transaction Status: {transaction.status}

    </>
  );
}

export default Transaction;

A: An issue I see is that you are implicitly returning the void result of a console log in the Promise chain, so later thenables aren't receiving the unpacked JSON response value.
useEffect(() => {
  fetch(
    "......",
    requestOptions
  )
    .then(handleErrors)
    .then((response) => console.log("ok")) // <-- returns undefined!
    .catch((error) => console.log(error))
    .then((response) => response.json()) // <-- can't call `json()` of undefined!
    .then((data) => setTransaction(data));
}, []);

It seems like you are asking about the fetch processing. I would suggest checking for the ok response before returning the json, right there inline. If you want to conditionally wait to display any fetched content then use a loading state.
Example:
function Transaction({ response }) {
  const [loading, setLoading] = useState(true);
  const [transaction, setTransaction] = useState();

  const requestOptions = {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
  };

  useEffect(() => {
    setLoading(true);
    fetch(
      ".....",
      requestOptions
    )
      .then((response) => {
        if (!response.ok) {
          throw Error(response.statusText);
        }
        return response.json();
      })
      .then((data) => {
        setTransaction(data)
      })
      .catch((error) => {
        console.log(error)
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  if (loading) {
    return null; // or loading spinner/etc
  }

  return (
    <>
      {transaction
        ? (

            Transaction Status: {transaction.status}

        )
        :
No transaction data

      }
    </>
  );
}

If you want to display any errors then add some error state and some conditional rendering logic to display it, similar to the transaction state.

A: you can use conditional rendering in react.
return (
    {
      transaction.length === 0 ? <></> :
        <>

            Transaction Status: {transaction.status}

        </>

    }
)

you can use loading or anything that you want instead of <></> and also any other proper condition for data existence.


text:
Q: Can anyone see edits which occured before the 5 minute mark after posting? I have noticed some people in Stack Overflow who write answers just for the sake of adding an answer, and maybe answering first. And when warned by others, and additionally flagging them, that's when they try improving their answers.
All these happen before the 5 minute mark where there is no "edits" history.
And so I wonder if anyone can see, especially the moderators, the "mistakes" within the 5 minute mark.
Situation:
I flagged a poor answer (very short, or just a link, or totally non-sense) at one moment, when seconds later someone warned the poster and the poster changed it (stunningly with a detailed version). I flagged a "late correct edit" answer as poor - which could reject my flag.

A: Nobody, including moderators, and (probably) excluding developers, can see the edits done during the grace period; if you have flagged a post, the moderators would not see any evidence of what you are saying. This is the reason why it has been suggested to make visible the first version of the post, which means that when a post is edited at least once (during the grace period) after creating it, the revision page would show 2 revisions, instead of none as it is actually done.
Consider that the "very low quality" flag is probably going to be rejected in any case. That flag should be used for answers that cannot be fixed by editing them; if it is not possible to edit them to make clear what they mean, then the answer is not a real answer.

A: I typically down-vote and/or comment and give the user the opportunity to improve their answer (whether it is a "first post" placeholder or just a terrible answer). There is little point to try and punish someone after they've done this, and mods aren't going to delete an answer that is good even if it didn't start so good.
Rather than trying to punish the behavior, I think it should simply be deterred. As illustrated on a question already pointed out:
Make first draft of a new answer part of the permanent revision history

*

*if we get rid of the enlightened badge there will be much less incentive to rush in with a garbage placeholder and fill it in with a proper answer later. There will still be some incentive, as the earlier answers usually get a higher percentage of the votes, and it gets harder and harder over time to earn the enlightened badge anyway (only very simple questions seem to yield answers with > 10 up-votes anymore).

*barring 1., if the original placeholder garbage is part of the permanent history of a question, it becomes easy to demonstrate when a user has done this. Nothing needs to automatically happen because of this, and there shouldn't necessarily repercussions even if it is pointed out (unless it is outright plagiarism, and again, yes, this has happened). But the fact that the poster soon learns that their original cutting into line is clearly visible in the revision history, I would hope that is enough of a deterrent.
As others suggest both here and elsewhere, the end result is not the problem. These users usually end up posting a final answer that is decent even if the path they took there was not 100% honest (and clearly has motives outside of the spirit and intent of the site). So I do identify with the unfavorable opinion cast upon the behavior - it just feels scammy to cut in line with nonsense just to be first in line.


text:
Q: case-insensitive validation using phalcon validation class In validation class my intiialize function is like this
public function initialize()
{
    $this->add('gender',new InclusionIn(array(
           'message' => 'Please enter a valid Gender',
           'domain' => array('Male','Female'),
           'case_insensitive' => false
    )));
}

Problem is, InclusionIn makes a case-sensitive validation so if user enter "male" application throws an error Please enter a valid Gender. I want this validation should be case-insensitive but I did not find any way to do it.

A: InclusionIn uses in_array which is case sensitive. You would have to write your own Validator in order to get the functionality you would need. Here is the implementation of the class so you can see what options are available.
Another option is just to format the input before the validator is fired. e.g. if they type in male or MALE convert it to Male so the validation will pass.

A: As @M2sh & @honerlawd guided, finally I ended with writing a new validator for 'inclusion` sharing the code here
<?php

namespace library\app\validators;

use Phalcon\Validation;
use Phalcon\Validation\Validator;
use Phalcon\Validation\Exception;
use Phalcon\Validation\Message;

class InclusionIn extends Validator
{

    /**
     * Executes the validation
     */
    public function validate(Validation $validation, $attribute)
    {

        $value = $validation->getValue($attribute);

        if ($this->isSetOption("allowEmpty") && empty($value)) {
            return true;
        }

        /**
         * A domain is an array with a list of valid values
         */
        $domain = $this->getOption("domain");
        if (!is_array($domain)) {
            throw new Exception("Option 'domain' must be an array");
        }
        $refinedDomain = array_map('strtolower', $domain);

        $strict = false;
        if ($this->isSetOption("strict")) {
            if (!is_bool($strict)) {
                throw new Exception("Option 'strict' must be a boolean");
            }

            $strict = $this->getOption("strict");
        }

        /**
         * Check if the value is contained by the array
         */
        if (!in_array(strtolower($value), $refinedDomain, $strict)) {

            $label = $this->getOption("label");
            if (empty($label)) {
                $label = $validation->getLabel($attribute);
            }

            $message = $this->getOption("message");
            $replacePairs = ['field' => $label, 'domain' => join(", ", $domain)];
            if (empty($message)) {
                $message = $validation->getDefaultMessage("InclusionIn");
            }

            $validation->appendMessage(new Message(strtr($message, $replacePairs), $attribute, "InclusionIn"));
            return false;
        }

        return true;
    }

}

A: In case of validating model, you can use beforeValidation(), beforeValidationOnCreate() or beforeValidationOnUpdate() to lowercase/uppercase value:
function beforeValidation() {
    $this->gender = ucfirst($this->gender);
}

If validating via Forms, you can apply addFilter(lower) and validate for lowercase eg.

A: You can now use filter see phalcon Filtering and Sanitizing https://docs.phalconphp.com/en/latest/reference/filter.html
In controller like this: note filter need to be added to services initialisation
$gender = $this->filter->sanitize($gender, "lower");

OR
In your customValidation class:
class MyValidation extends Validation
{
    public function initialize()
    {
       $this->add('gender',new InclusionIn(array(
         'message' => 'Please enter a valid Gender',
         'domain' => array('male','female'),
       )));

       $this->setFilters('gender', 'lower');
    }
}


text:
Q: Remove the comma between family name and given name I'm using biblatex with biber in the numeric-comp style.
I'm calling biblatex as follows:
\usepackage[sorting=none,style=numeric-comp,giveninits=true,terseinits=true]{biblatex}
    \DeclareNameAlias{default}{family-given}

With this I get almost what I want. But I would like to remove the comma between the family name and the initials. Can you help me with that?
Edit: I know how this works with the old version "last-first" and I would like to do the same with the newer "family-given".
Thanks in advance!


text:
Q: WPF binding with master-view layout I have a question regarding WPF binding using master-detail layout.
The master view contains a DevExpress GridControl with a TreeListView.
The detail view content is updated when the TreeListView selected item is changed (trough the binding).
The detail view contains just a ContentControl, with it's Content property bound to the current selected item of the TreeListView.
In order to display the detail view in a way that correspond to the type of the selected item, several DataTemplates are registered to the current application resources.
In my case, the DataTemplates are just one user control.
When the selection is changed in the master view TreeListView, the corresponding DataTemplate is correcly diplayed.
One of my detail view contains a DevExpress ListBoxEdit. The SelectedIndex is bound with UpdateSourceTrigger=PropertyChanged.
My problem is that the setter of the bound property is called with the value -1 when another item is selected in the master view.
It seems that the -1 default value is received when the control is unloaded or disposed or unbound. This screw up my view model.
Is there a proper way to avoid to be notified in the ViewModel when the control is unloaded?
[update]
The ContentControl that contains the detail view is defined like this:
<ContentControl Grid.Column="1" Content="{Binding CurrentApplicationSettings}" Margin="10,0,0,0"/>

In the corresponding view model (the SetValue method calls OnPropertyChanged):
public IApplicationSettingsViewModel CurrentApplicationSettings
{
    get { return GetValue<IApplicationSettingsViewModel>(); }
    set { SetValue(value); }
}

In the detail view where I have the problem, the ListBoxEdit is defined like this:
<dxe:ListBoxEdit ShowBorder="False" ItemsSource="{Binding AllLoggingLevels, Mode=OneTime}" SelectedIndex="{Binding Path=LoggingLevel, Mode=TwoWay, Converter={StaticResource LogLevelConverter}, UpdateSourceTrigger=PropertyChanged}">
    <dxe:ListBoxEdit.StyleSettings>
        <dxe:RadioListBoxEditStyleSettings/>
    </dxe:ListBoxEdit.StyleSettings>
</dxe:ListBoxEdit>

In the corresponding ViewModel:
public LoggingLevel LoggingLevel
{
    get { return GetValue<LoggingLevel>(); }
    set { SetValue(value); }
}

The DataTemplates are registered by code:
public void RegisterDataTemplate(DataTemplate dataTemplate)
{
    object dataTemplateKey = dataTemplate.DataTemplateKey;
    if (dataTemplateKey == null)
    {
        throw new InvalidOperationException("The data template has an invalid key");
    }
    System.Windows.Application.Current.Resources.Add(dataTemplateKey, dataTemplate);
}

Thank you very much
Philippe

A: I have receive an answer from DevExpress support and this works for me.
"Having researched it, I found that this behavior occurs because of the internal editor's synchronization.When the editor loses its items source because of changing the focused row in the tree, it resets its properties such as EditValue, Text, SelectedItem, etc.
To prevent these properties from being synchronized, set the editor's AllowUpdateTwoWayBoundPropertiesOnSynchronization property to false."


text: Q: Are there any constraints on the undefined behavior caused by signed integer overflow? Signed integer flow produces undefined behavior in C++. However, in practice, what is the nature of this undefined behavior? Is it limited to an undefined value of the result? Or can it do arbitrary things like changing other variables or even the control flow of the program?


text:
Q: How do I prevent generic arguments from being messed up by VS2008 unit testing I have two classes like this (in the actual project):
namespace app {
    internal class A {
    }

    internal class B {
        private List<A> list;
        private void SomeMethodToTest() {
            list = new List<A>() { new A() };
        }
    }

The I have my Unit test looking something like
[TestClass()]
public class ATest {
    [TestMethod()]
    public void TestSomeMethod() {
        B_Accessor b = new B_Accessor();
        b.SomeMethodToTest();
        Assert.AreEqual(1, b.list.Count); // ERROR ON THIS LINE
    }
}

On the marked line I get an InvalidCastException saying something like "unable to cast object of type System.Collections.Generic.List'1[app.A] to type System.Collections.Generic.List'1[app.A_Accessor]
The problem is that, because A is internal, the auto-generated class B_Accessor looks like
[Shadowing("app.B")]
public class B_Accessor : BaseShadow {
    ... stuff ...

    [Shadowing("list")]
    public List<A_Accessor> list { get; set; }

    ... stuff ...
}

Note that, in the Accessor class, the list is of type List<A_Accessor> and not List<A>. I have specified the InternalsVisibleTo attribute on the application, so the test project can access the type A, but for some reason VS replaces it with the accessor type, which makes the type incompatible with the wrapped type.
How can I work around this other than making A public?

A: I've deleted my previous answer because I hadn't noticed that you were already using InternalsVisibleToAttribute.
What's generating these "accessor" classes? When you say "VS replaces it with the accessor type" do you mean it changes your source code? That sounds very odd - what happens if you put it back to just use A and B instead of A_Accessor and B_Accessor?
If you can possibly get rid of autogenerated classes which are meant to look like the real ones, but don't quite, then do get rid of them. I suspect this is just one situation where they'll cause problems.
I've never had any problems just using InternalsVisibleTo and testing internal members directly. (Well, R# sometimes got confused in a previous version, but apart from that...)

A: It is possible to replace the test project with something like
internal static class AccessorExtensionMethods {
    internal static List<A> Get_list(this PrivateObject po) {
        return (List<A>)po.GetField("list");
    }
}

[TestClass()]
public class ATest {
    [TestMethod()]
    public void TestSomeMethod() {
        PrivateObject bpo = new PrivateObject(new B());
        B_Accessor b = new B_Accessor(bpo);
        b.SomeMethodToTest();
        Assert.AreEqual(1, bpo.Get_list().Count);
    }
}


text:
Q: "no 'Access-Control-Allow-Origin' header is present" error with Cherrypy I have the following javascript in a HTML page
<script>
    function getContent(page)
    {
        var xmlhttp;
        if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
            }
        else
            {// code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
             {
                var json = xmlhttp.responseText;
                obj = JSON.parse(json);
                document.getElementById("content").innerHTML=obj.content;
                document.getElementById("title").innerHTML=obj.title;
             }
        }
    xmlhttp.open("GET","http://differentserver.com:8080?page="+page,true);
    xmlhttp.send();
}
</script>

and a python script using cherrypy that serves JSON, the code of which is:
import cherrypy
import json

class ContentGeneratorService(object):
exposed = True
@cherrypy.tools.accept(media='text/plain')
def GET(self, page='home'):
    file_title = open(page + '.title', 'r')
    file_content = open(page + '.content', 'r')
    return json.dumps({"title": file_title.read().replace('\n', ''), "content":     file_content.read().replace('\n', '') })

def CORS():
cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"

if __name__ == '__main__':
conf = {
    '/': {
        'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
        'tools.sessions.on': True,
        'tools.response_headers.on': True,
        'tools.response_headers.headers': [('Content-Type', 'text/plain')],
        }
    }

cherrypy.server.socket_host = '0.0.0.0'
cherrypy.tools.CORS = cherrypy.Tool('before_handler', CORS)
cherrypy.config.update({'server.socket_port': 8080})
cherrypy.quickstart(ContentGeneratorService(), '/', conf)

However, I get a "no 'Access-Control-Allow-Origin' header is present" error. Is there a way to enable CORS with cherrypy?
Thanks.

A: It seems to work now. I added
'tools.CORS.on': True

to conf.

A:
cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"

is very risky because now any site can make an AJAX call to your server and get the content served by the python script. Instead using

cherrypy.response.headers["Access-Control-Allow-Origin"] = "your site
  domain"

is a much secure option.


text:
Q: cropping tools for admin panel cms Is there any tools (JS & PHP) that can crop image and upload and save it based on what of width and height that we specify?
Most of them only tools for resize and not cropping of what inserted width and height that we specify.
Is there any good tool for this (JS & PHP) that I can use for my web admin panel / CMS.
Thanks.

A: This is what I am looking for.. Works perfectly!!!
http://net.tutsplus.com/articles/news/working-with-the-jcrop-plugin/