text:
Q: Confused about class method syntax How do I pass first_number and second_number to the +add_function?
I am currently getting math undeclared.
Additionally, I have placed the pound include math_class in the -addButtonClicked: IBAction.
Also, I realize that I can simply add the two numbers in the IBAction, but for learning purposes I would like to pass them to my math_class.
-(IBAction)addButtonClicked
{
    double total;
    double first_number = [firstNumberField.text doubleValue];
    double second_number = [secondNumberField.text doubleValue];

    total = [math_class.add_function number_one:first_number number_two:second_number];
    answerField.text =  [NSString stringWithFormat:@"%.2f", total];

    [answerField setHidden:NO];
}

@interface math_class : NSObject

+ (double) add_function: (double) number_one: (double) number_two;

@end

@implementation math_class

+(double) add_function: (double) number_one: (double) number_two
{
    double total;
    total = number_one + number_two;
    return total;
}

@end

A: There are several problems with the code you posted.
First of all, the convention in Cocoa Touch is that class names use camel-case and start with a capital letter: MathClass, not math_class.  Method names use camel-case and each keyword starts with a lower-case letter.  If you stick to the naming convention, it will be easier for other people to understand your code, so it will be easier for you to get help when you have a problem.
Now, in your math_class class, you have declared a method like this:
+ (double) add_function: (double) number_one: (double) number_two;

But you've put in spaces and left out spaces in an unusual way.  The usual way to write it, keeping exactly the same method name, looks like this:
+ (double)add_function:(double)number_one :(double)number_two;

The name of this method is add_function::, not add_function number_one:number_two: (which is what you used to try to call it).
This method name has two keywords.  The first keyword is add_function: and takes a double argument named number_one.  The second keyword is just : and takes a double argument named number_two.
You could call this method like this:
total = [math_class add_function:first_number :second_number];

However, using a method name with a keyword of just : is almost always very bad style.
There are lots of ways to write your class in good style.  Here's one way:
@interface MathClass : NSObject

+ (double)sumWithNumber:(double)firstNumber number:(double)secondNumber;

@end

@implementation MathClass

+ (double)sumWithNumber:(double)firstNumber number:(double)secondNumber {
    return firstNumber + secondNumber;
}

@end

When a method is used primarily for its return value, and not for side effects, we name it after the thing it returns.  So I called it sumWithNumber:number: because it returns a sum.
The method name has two keywords.  The first keyword is sumWithNumber: and takes a double argument named firstNumber.  The second keyword is number: and takes a double argument named secondNumber.  You can call it like this:
total = [MathClass sumWithNumber:first_number number:second_number];

A: It looks like you're trying to access a function using the objective-c dot property syntax.  If add_function is defined as:
+(void) add_function: ...

.. and math_class is the class name you should use
[match_class add_function number_one:.......

Note space rather than dot.
edit now you've posted the code:
Your definition for the add_function is wrong - in obj-c you need to give the name of the parameter AND the name of the variable unlike in most other languages.
Here's what add_function signature could look like:
+(double) add_function_number_one: (double) number_one  number_two: (double) number_two

There's a convention in cocoa that the name of the function includes the name of the first parameter, hence why it's now called add_function_number_one.

A: You should probably be calling [math_class add_function:first_number:second_number]; Your class is called math_class, not math.


text:
Q: Strange error when using the Count property for an array´/ object enumeration I try to use this script to purge some log files of my exchange server.
I made just one small change and added the following line so that all Exchange objects are available.
add-pssnapin *exchange* -erroraction SilentlyContinue

When I run the script I get an error when the following lines are executed:
# Get a list of all Exchange 2013 servers
$Ex2013 = Get-ExchangeServer | Where {$_.IsE15OrLater -eq $true} | Sort-Object Name
$logger.WriteEventLog("Script started. Script will purge log files on: $($Ex2013)")
# Lets count the steps for a nice progress bar
$i = 1
$max = $Ex2013.Count * 2 # two actions to execute per server

The last line fires an error. As that the Count property isn't available.
I have only one server, and if I execute exact those lines in my Exchange Management Shell this code executes without error.
What is the cause for the different behaviour?
PS: I currently have a workaround just to count the objects. And this works always:
$max = 0
foreach ($E15Server In $Ex2013) {
    $max++
}
$max *= 2

redpajama_set_name: RedPajamaStackExchange


text:
Q: What could have caused this SMD capacitor failure? I have an 0805 capacitor that has failed short circuit on a board. The maximum voltage it would see should be 16V. It has value 4.7uF, is rated to 25V and is X7R.
I don't understand why it might have failed.
Has anyone seen something like this before and would like to pass on their experience?
It could be physical damage, but then perhaps the damage seen below is from the current when short circuited.

A: It could have been physically damaged- either big cracks or it could have had micro-cracks. It could simply be a random failure from a latent manufacturing defect.
From murata.com:

MLCC capacitors are available with "soft" electrodes for higher resistance to cracking. Image from tdk.com


text:
Q: How do I create an editable databound combo box in a DataGrid in WinForm? I have a noob question.
I have a WinForm (.net 2.0 in VS 2008) on my form I have a DataGrid. One of the fields in that DataGrid is a combo box that is bound to a separate table. This works, but I am unable to edit or add. I cannot add a value that is not on the list.
I want to create a lookup box (for lack of a better term).
The form is for Parts Order Entry. In the DataGrid Data Source is PartsOrder_table, the Work order Field is an int in the PartsOrder_table, and the combo box is bound to the WorkOrder_table. The WorkOPRder_Table has WorkOrd_ID int and WrkOrd nvarchar(10)
The Combo Box Data Source is WorkOrd_Table Display Member is WorkOrd Value Member is WorkOrder_ID.
This works great with the problem that I cannot add or select anything not in WorkOrder_table.
Any help would be greatly appreciated.

A: Seems you cannot in a straight forward manner. This thread shows a way of doing this, by adding the needed values during the Validation of the ComboBox control. See the URL for more details.
http://social.msdn.microsoft.com/forums/en-US/winformsdatacontrols/thread/31a28e99-6f9f-4cce-b256-9b7cf1ddf69a/


text:
Q: how to filter a listView in an Activity i want to filter the tasks to show by what the user will choose in the check boxes,but when i run this code there is an error.
this is the functions in the filter activity
enter code here
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_filter);
    INITIALIZE();
    DONE();
}

public void INITIALIZE()
   {

Go=(Button)findViewById(R.id.go);
ProH=(CheckBox)findViewById(R.id.pro1);
ProM=(CheckBox)findViewById(R.id.pro2);
ProL=(CheckBox)findViewById(R.id.pro3);
Finished=(CheckBox)findViewById(R.id.finished);
NotFinished=(CheckBox)findViewById(R.id.notfinished);
Past=(CheckBox)findViewById(R.id.past);
Future=(CheckBox)findViewById(R.id.future);

}
public void DONE()
{
final AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
Go.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub

        if((proH==1&&proM==1)||(proM==1&&proL==1)||(proH==1&&proL==1))
        {
            alertbox.setTitle("Error!");
            alertbox.setMessage("Please Choose one Priority");
            alertbox.setNeutralButton("ok",new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                }
            });
             alertbox.show();
             ProH.setChecked(false);
             ProM.setChecked(false);
             ProL.setChecked(false);
        }
    }
});}}

what it the error here?

A: Judging by your error in the comments, the problem is you're using an Intent that isn't caught by any intent-filter.
"No Activity found to handle Intent { act=com.example.todolist.FILTER }"
Fix your intent-filters, or launch your FilterActivity a different way.
You can explicitly launch Activities with something like
Intent intent = new Intent(context, FilterActivity.class);
context.startActivity(intent);

Where 'context' might be your Activity (this)


text:
Q: How do you prove $P(A) \cup P(B) = P(A \cup B) \Rightarrow (A \subseteq B) \lor (B \subseteq A)$ I'm learning proofs on my own and I'm on the section about cases.  I have to prove the following but don't how to do this.  Can someone tell me how you would prove this? (where $P()$ represents the power set):
$P(A) \cup P(B) = P(A \cup B) \Rightarrow (A \subseteq B) \lor (B \subseteq A)$
Your help is greatly appreciated! :)

A: Try to prove this with contraposition (meaning $(A \Rightarrow B) \equiv (\neg B \Rightarrow \neg A)$):
Assume neither $A \subseteq B$ nor $B \subseteq A$ holds, hence you get elementes $a \in A \setminus B$ and $b \in B \setminus A$. Now consider the subset $\{a,b\} \in P(A \cup B)$. Is this in $P(A) \cup P(B)$ (hence in $P(A)$ or $P(B)$)?

A: A similar way without the need for the contrapositive: get an arbitrary $x$ such that $x\in A$ and an arbitrary $y$ such that $y\in B$, then the set $\{x,y\}\in\mathcal P(A\cup B)$, by definition of the power set.
But now it must hold that $\{x,y\}\in\mathcal P(A)\cup\mathcal P(B)$, this mean that $\{x,y\}\in\mathcal P(A)$ or $\{x,y\}\in\mathcal P(B)$.
If $\{x,y\}\in\mathcal P(A)$ then $y\in B$, and because $y$ was arbitrary we have that $B\subseteq A$. In an analogous way if $\{x,y\}\in\mathcal P(B)$ we have that $A \subseteq B$.
EDIT: well, we need to formalize this proof a bit more to be a valid proof. Suppose an arbitrary $X\subseteq\mathcal P(A\cup B)$. If $A=B$ we are done. If $A\neq B$ then we divide four cases for $X$:

*

*$X$ is empty

*$X$ is composed of points exclusively of $A$

*$X$ is composed of points exclusively of $B$

*$X$ is composed of points of $A$ and points of $B$

Now we can check that when the four cases hold then the statement of the question hold.


text:
Q: Python sys.argv utf-8 to unicode not working I have the following code which is acting very weirdly.
When I do the following, the utf-8 got converted into unicode nicely.
print u'\xE1\x80\x96\xE1\x80\xBB\xE1\x80\xB1\xE1\x80\xAC\xE1\x80\xBA\xE1\x80\x9B\xE1\x80\x8A\xE1\x80\xBA'.encode('raw_unicode_escape')

This works fine. However, when I get the utf-8 string from sys.argv, it doesn't work.
import sys

if __name__ == "__main__":
    args = sys.argv

    input_string = args[1]

    if type(input_string) is not unicode:
        input_string = unicode(input_string, "utf-8")

    print type(input_string)
    print input_string

When I run like the following,
python test_print.py "\xE1\x80\x96\xE1\x80\xBB\xE1\x80\xB1\xE1\x80\xAC\xE1\x80\xBA\xE1\x80\x9B\xE1\x80\x8A\xE1\x80\xBA"

I got the following same string, it doesn't get converted into unicode.
<type 'unicode'>
\xE1\x80\x96\xE1\x80\xBB\xE1\x80\xB1\xE1\x80\xAC\xE1\x80\xBA\xE1\x80\x9B\xE1\x80\x8A\xE1\x80\xBA

I need to convert the input from sys.argv into unicode chars.
Please help.
Thanks.

A: Actual Python level string literals (for str and unicode) are the only place character escapes are parsed by Python automatically. If you want to convert outside strings that use literal escapes like this, you'd do something like this to explicitly invoke the literal escape interpretation machinery:
# Converts from str to str interpreting escapes, then decodes those bytes
# using the UTF-8 encoding
input_string = args[1].decode('string_escape').decode('utf-8')

The exact steps are slightly different in Python 3 (you have to use unicode_escape and the codecs module, and add an extra step to convert the literal decoded str to latin-1 bytes before decoding as utf-8 because text->text encoding and decoding isn't supported), but it's a similar process.


text:
Q: What is the purpose of using MatchIt in R with nearest neighbors for estimation of ATE if it does not report which pairs are matched? I am currently using the matchit function in MatchIt in R. For example, in the call:
m.out1 <- matchit(treat ~ age + educ + black + hispan + nodegree + married + re74 + re75, method = "nearest", data = lalonde)
> head(match.data(m.out1))
    treat age educ black hispan married nodegree re74 re75       re78
NSW1     1  37   11     1      0       1        1    0    0  9930.0460
NSW2     1  22    9     0      1       0        1    0    0  3595.8940
NSW3     1  30   12     1      0       0        0    0    0 24909.4500
NSW4     1  27   11     1      0       0        1    0    0  7506.1460
NSW5     1  33    8     1      0       0        1    0    0   289.7899
NSW6     1  22    9     1      0       0        1    0    0  4056.4940
      distance weights
NSW1 0.6387699       1
NSW2 0.2246342       1
NSW3 0.6782439       1
NSW4 0.7763241       1
NSW5 0.7016387       1
NSW6 0.6990699       1

no where does it display which treated units are paired with which control units. It seems to just be a jumble of the original data, but now with some removal of control units that could not be paired.
I fail to see the purpose of matchit in this case. If I want to find the ATE after matching, how would I go about this?

A: There are two components to matching: creating matched samples and pairing units.
Creating matched samples involves pruning away individuals in the control group that are dissimilar from units in the treated group. We assign weights of 0 to these pruned units and weights of 1 or more to the remaining units. match.data() creates a new data set that removes everyone with a weight of 0. Effect estimation on the matched sample involves applying these weights in a weighted independent samples t-test of the outcome on the treatment. This is the technique recommended by Stuart (2010) and others, mostly from Rubin's camp.
Pairing units involves creating subsets of the matched sample, where each subset contains at least one treated and at least one control. Effect estimation in a paired sample involves performing a related measures t-test or a regression that accounts for the clustering of units (i.e., either by including pair membership as a fixed or random effect or using them in cluster-robust standard errors). This technique is recommended by Austin (2011) and others, mostly from Rosenbaum's camp.
Propensity score matching yields some controversy here. You perform the act of pairing in order create matched samples, but as I mentioned above, there is debate about whether you should retain the pair membership of the units in your analysis or just use the matched samples and their weights to estimate the treatment effect.
The authors of MatchIt, which include Stuart, recommend using the matched samples approach (not the paired units approach) to estimating treatment effects after matching. Therefore, if you did 1:1 matching without replacement, you can just do a t-test on the remaining units resulting after match.data(). Otherwise, you need to include the weights generated by matchit() in a weighted analysis (which will also work with 1:1 matching without replacement). Regardless, it would be advisable to use robust standard errors, though this hasn't been recommended explicitly in the literature.
However, if you want to move forward with a paired analysis, you will have to do some work. The pair membership is in the m.out1 object, in the match.matrix component. This is a matrix where the row names are the indices of the treated units, and the values in the columns are the indices of the control units that are paired with each treated unit. You can extract the pairs and create the pair subsets with a bit of R finagling, and then run a paired analysis on these pairs. (Note that if you're doing k:1 matching and not all treated units have k matches, there will be NAs in the match.matrix, which can be ignored.)
One final thing to note is that the ATE cannot be estimated from matched data resulting from a call to matchit(). Only the ATT can be estimated. This is because the covariate distribution of the matched samples will be similar to that of the treated group, and therefore the estimated effect is not generalizable to the population at large.
Edit 2022/01/05:
MatchIt now includes pair membership in the matched dataset for all matching methods that involve pairing. The MatchIt vignettes explain how to incorporate pair membership in effect estimation after matching, which is now considered best practice. Also, the ATE is available for some matching methods (full matching, subclassification, etc.)


text:
Q: Downgrade tar package to particalar version Dears,
Under Ubuntu/Linux I want to downgrade "tar" package from 1.27-1 version to 1.26ver.
per apt-cache showpkg tar I have:
Package: tar
Versions:
1.27.1-1ubuntu0.1 (/var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty-updates_main_binary-amd64_Packages.gz) (/var/lib/apt/lists/security.ubuntu.com_ubuntu_dists_trusty-security_main_binary-amd64_Packages.gz) (/var/lib/dpkg/status)
 Description Language:
                 File: /var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty_main_binary-amd64_Packages.gz
                  MD5: 48033bf96442788d1f697785773ad9bb

1.27.1-1 (/var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty_main_binary-amd64_Packages.gz)
 Description Language:
                 File: /var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_trusty_main_binary-amd64_Packages.gz
                  MD5: 48033bf96442788d1f697785773ad9bb

Reverse Depends:
  dpkg,tar 1.23
  dpkg,tar 1.23
  vfu,tar 1.20-1
  pristine-tar,tar 1.27-3
  patool,tar 1.26
  dump,tar 1.13.92-3
  amanda-common,tar 1.12
  dpkg,tar 1.23
  backuppc,tar 1.13
Dependencies:
1.27.1-1ubuntu0.1 - libacl1 (2 2.2.51-8) libc6 (2 2.17) libselinux1 (2 1.32) bzip2 (0 (null)) ncompress (0 (null)) xz-utils (0 (null)) tar-scripts (0 (null)) cpio (1 2.4.2-38) dpkg-dev (3 1.14.26) cpio (3 2.4.2-39)
1.27.1-1 - libacl1 (2 2.2.51-8) libc6 (2 2.17) libselinux1 (2 1.32) bzip2 (0 (null)) ncompress (0 (null)) xz-utils (0 (null)) tar-scripts (0 (null)) cpio (1 2.4.2-38) dpkg-dev (3 1.14.26) cpio (3 2.4.2-39)
Provides:
1.27.1-1ubuntu0.1 -
1.27.1-1 -
Reverse Provides:

I do this
apt-get install tar=1.26
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Version '1.26' for 'tar' was not found

I need to help on correct way to downgrade particular package. Per Ubuntu documentation:
sudo apt-get install [packagename]=[version]
I have specified version which I want to downgrade to 1.26.
How to correctly downgrade to specified version?

A: Look at https://launchpad.net/ubuntu/+source/tar for the available versions of tar for your distribution. You will find a tar 2.16 version at https://launchpad.net/ubuntu/+archive/primary/+files/tar_1.26-4ubuntu1.1_i386.deb or https://launchpad.net/ubuntu/+archive/primary/+files/tar_1.26-4ubuntu1.1_amd64.deb depending on your architecture.
Download the .deb file and try to install it with sudo dpkg install
I hope you won't have problems with unsatisfied dependencies.


text:
Q: how to explain couple of points on Kubernetes Calico Networking routing table? Below is the output from ip route command in one of the worker nodes of Kubernetes cluster (aws based):
$ip route
default via 10.6.16.1 dev eth0
10.6.16.0/21 dev eth0 proto kernel scope link src 10.6.22.111
111.97.95.0/26 via 10.6.145.224 dev tunl0 proto bird onlink
111.98.108.64/26 via 10.6.144.128 dev tunl0 proto bird onlink
111.98.163.0/26 via 10.6.147.100 dev tunl0 proto bird onlink
111.101.172.128/26 via 10.6.86.141 dev tunl0 proto bird onlink
111.103.57.192/26 via 10.6.17.44 dev eth0 proto bird
111.103.80.128/26 via 10.6.85.178 dev tunl0 proto bird onlink
111.105.231.0/26 via 10.6.23.120 dev eth0 proto bird
111.115.208.128/26 via 10.6.80.11 dev tunl0 proto bird onlink
blackhole 111.126.117.128/26 proto bird
111.126.117.129 dev cali8934275ty scope link
111.126.117.132 dev cali983hfsdf4 scope link
111.126.117.140 dev cali443gfby45 scope link

I am quite new to Kubernetes and would like to understand a couple of things related to this output and Calico networking in general:

*

*what kind of ip address is 10.6.16.1 if eth0 has IP of 10.6.22.111/21 - is it Internet Gateway ?

*Another worker node has two pods with the same IP=10.6.145.224 (pods calico-node-74hde и kube-proxy-internal) - how this is working/possible?

*Why do we need blackhole route?

A:
what kind of ip address is 10.6.16.1 if eth0 has IP of 10.6.22.111/21 - is it Internet Gateway ?

Yes, you are correct, this is indeed default(internet) gateway. So for example on your local computer default route would hold an IP of your home router.

Another worker node has two pods with the same IP=10.6.145.224 (pods calico-node-74hde и kube-proxy-internal) - how this is working/possible?

This is possible beacause they have set hostNetwork: true. Check it yourself running e.g.:
kubectl get po -n kube-system calico-node-74hde

and look for hostNetwork field. If this field is set to true, the pod (more specificaly containers within the pod) will not be network isolated and will have access to the host network interface, and this is why these pod have host IP.

Why do we need blackhole route?

I belive this calico issue may give us some answers.
I will try to explaint it. Imagine situation when there are 2 pod running and sending data over the network to each other.
When one of these pods gets deleted, the other pod may not recognise it and keep sending data to the IP address that does not exist (and because there is no pod, there is also no interface with the address).
So what shoud the node do if receives a packet with destination address that no longer exists?
Normally it would forward the packet according to the route rules. Now that there is no route rule associated with the pod (that just got deleted), the packet will get send according to the best match rule. If the blackhole rule exists, the packet will be dropped, but if there is no blackhole, packet will get forwarded (according to the best match rule) through the default gateway and you don't usually want this.

Let me know if it answers your questions.


text:
Q: Use dynamic segments on redirect_uri microsoft application Live SDK JavaScript library I am building a feature where the user can import his contacts form his hotmail, outlook, live emails.
I am using Live SDK javascript library to make it possible, I have to create a new app and set a redirect url. When user trigger an action the browser promt a window where the user log in an autorize the access to contact information.
I have the follow uri structure:
www.example.com/pools/12
www.example.com/pools/13
www.example.com/pools/{pool_id}

I set the redirect uri, to www.example.com, so when I trigger the event the browser prompt a window with the follow error:
The provided value for the input parameter 'redirect_uri' is not valid. The expected value is 'https://login.live.com/oauth20_desktop.srf' or a URL which matches the redirect URI registered for this client application.

but if i change the redirect uri from microsoft developer center to:
www.example.com/pools/12

and try again from this page the code works perfect.
I need set the redirect uri to accept all kind of uri, I also try to use a regex patter with out luck. This is the code that I use
<%= content_for :javascript do %>
  <script src="//js.live.net/v5.0/wl.js"></script>
  <script type="text/javascript">
    WL.init({
      client_id: '<%= ENV["LIVE_CLIENT"] %>',
      scope: ["wl.basic", "wl.contacts_emails"],
      response_type: "token"
    });

    $("#import-contacts-live").on("click", function(event) {
      event.preventDefault();
      WL.login({
        scope: ["wl.basic", "wl.contacts_emails"],
        redirect_uri: '<%= request.original_url %>',
      }).then(function (response){
        WL.api({
          path: "me/contacts",
          method: "GET"
        }).then(function (response) {
          console.log(response.data);
        },
        function (responseFailed) {
          console.log(responseFailed);
        });
      },
      function (responseFailed){
        console.log("Error signing in: " + responseFailed.error_description);
      });
    });
  </script>
<% end %>


text:
Q: Reference type of HashMap in jsp:useBean I have a HashMap that I want to pass to my view but I'm not able to get the HashMap correctly with jsp:useBean. So here is how I construct my HashMap and put in scope request :
HashMap<String, ArrayList<HAVerification>> hash = d.getVerificationByWF(dem2);
request.setAttribute("hash", hash);

My HashMap has a String as key and an ArrayList of object HAVerification as value. Now I want to get this hash in my view so I tried with this jsp:useBean
<jsp:useBean id="hash" type="java.util.HashMap<String, Arraylist<HAVerification>>" scope="request"/>

But this doesn't work, I also tried with
<jsp:useBean id="hash" type="java.util.HashMap<java.lang.String, java.util.List<servlet.HAVerification>>" scope="request"/>

And didn't work too
How can I do to reference the type of the HashMap ?


text:
Q: Query posts and filter at query time by value of custom meta I have a wordpress query for a custom post type, but I want to filter the results depending on the value of a custom meta.
    <?php $my_query = new WP_Query('post_type=prizes&showposts=3&orderby=rand');
while ($my_query->have_posts()) : $my_query->the_post();
$do_not_duplicate = $post->ID; $my_meta = get_post_meta($post->ID,'_my_meta',TRUE); ?>

<?php if(($calctotalnew - number_format($cart->total,2)) >= $my_meta['pointsvalue']){ ?>

        <a href="<?php the_permalink();?>"><?php the_title();?>

<?php echo $my_meta['pointsvalue'];?>

            <a href="<?php the_permalink();?>"><?php the_post_thumbnail('thumb');?>

<?php }

Thats my code. Bascially the IF statement in the loop filters the results, but I need them filtering as they are queried because it doesnt always show exactly 3 posts (as some posts will have a value above what if filtered in the IF statement.
Any thoughts?
Thanks

A: This is super easy to do with meta_querys:
$args = array(
    //basics
    'post_type'      => 'prizes',   // from question
    'post_status'    => 'publish',  // you didn't have this, but it's good practice
    'posts_per_page' => 3,           // I don't know where you got 'showposts', but that's WAY old

    //order
    'orderby'        => 'rand',

    //meta query
    'meta_query'     => array(
        array(
            'key'     => $my_meta['pointsvalue'],
            'value'   => ( $calctotalnew - number_format( $cart->total, 2 ) ),
            'compare' => '<=',
            'type'    => 'NUMERIC'
        )
    )
);

$my_query = new WP_Query( $args );

Also, your $do_not_duplicate is completely non-sensical. It's setup but never called, you probably want to address that.
I filled in some of the details for you, they may not be right. The documentation on WP_Query will help you get everything correct.


text:
Q: How to Wrap a REST API POST nested object with GraphQL I am trying to figure out how to wrap mutate a nested object with graphql mutations, if possible. For instance I have the following schema:
type Equipment{
  assetId: ID
  assetName: String
  assetTag: String
  createdAt: String
  updatedAt: String
  available: Boolean
  category: Category
  purchaseAt: String
  purchaseCost: Float
  serial: String
  notes: String

}

type Category{
  categoryId: ID,
  name: String
}

type Mutation {
    equipamento( e: EquipmentInput): Equipment
  }

input EquipmentInput{
  assetName: String
  assetTag: String
  available: Boolean
  purchaseAt: String
  category: CategoryInput
  purchaseCost: Float
  serial: String
  notes: String

}
input CategoryInput{
   categoryId: ID
   name : String
}

This is the POST call on REST. This call works
    {

        "assetName": "Dell Laptop E5570",
        "assetTag": "A0001",
        "available": false,
        "category":{
         "categoryId": 1
        } ,
        "purchaseAt": "2018-09-10",
        "purchaseCost": 1200.00,
        "serial": "Serial",
        "notes": "Novo"

    }

I am trying to do a equivalent on GraphQL using graphql-yoga, but category is a nested object and the create call fail on REST service.
  equipamento: (parent, args) => {
      const equipment = {
        assetName: args.e.assetName,
        assetTag: args.e.assetTag,
        available: args.e.available,
        category: args.e.category.categoryId,
        purchaseAt: args.e.purchaseAt,
        purchaseCost: args.e.purchaseCost,
        serial: args.e.serial,
        notes: args.e.notes
      }
      return fetch(`${equipmentURL}/`, {
        method: 'POST',
        body: JSON.stringify(equipment),
        headers: { 'Content-Type': 'application/json' }
      }).then(res => res.json());
    }```

Console Log for the GraphQL is
```{"assetName":"Dell Laptop E5570","assetTag":"A0001","available":false,"category":1,"purchaseAt":"2018-09-10","purchaseCost":1200,"serial":"Serial","notes":"Novo"}```

So the question is, how can i format my mutation to have nested object?


text:
Q: Authentication Google Cloud APIs I am trying to use BigQuery client and am getting authentication error:
        <groupId>com.google.apis</groupId>
        <artifactId>google-api-services-bigquery</artifactId>
        <version>v2-rev397-1.23.0</version>

com.google.api.client.googleapis.json.GoogleJsonResponseException: 401
  Unauthorized

I don't have service account in path as I am an owner of the project and am logged in to my account via gcloud auth login. When I try gcloud auth list I see I am logged in with the credentials which has owner granted in my project. Why I am getting this error?

A: Even if you are logged via gcloud auth login, it doesn't mean your application is going to use those credentials. You still need to authenticate using OAuth 2.0.
If you wish to authenticate with your user account, you can try generating an access token and passing it to the GoogleCredential class (keep in mind tokens expire).
To generate the access token for your user credentials, use the gcloud tool:
gcloud auth application-default print-access-token

Pass the generated token to the GoogleCredential class:
GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);

I'm not very familiar to the google-api-services-bigquery API, but I think this is how you would use the credential:
Bigquery bigquery = Bigquery.builder(HTTP_TRANSPORT, JSON_FACTORY).setHttpRequestInitializer(credential).build();


text:
Q: Why the props in react become the next argument in function return a function When we pass a function in a function  as an argument, the function that we pass in it has own parameter, but why the parameter become an argument of next returning function ?
function combineStyles(...style){
   return function CombineStyles(theme){}
}

const s1 = theme => ({
  toolbar: {
    backgroundColor: theme.palette.primary.main,
    color: '#fff',
    ...theme.mixins.toolbar,
  },
});

const combinedStyles = combineStyles(s1);

export default withStyles(combinedStyles)(MyComponent);

// While i am log it, i got same result

const s1 =  theme => console.log(theme);

// Same as :

function combineStyles(...style){
   return function CombineStyles(theme){ console.log (theme) }
}


text:
Q: How to make simplest servlet filter respect setted character encoding It feels like I'm stuck.
I'm trying to write the simplest servlet Filter (and deploy it to tomcat). It's a groovy code, but actually I'm heavily using java approaches here, so it is almost copy-paste, that's the reason I've added java tag as well.
My question is - how can I insert UTF-8 string to filter?
Here is the code:
public class SimpleFilter implements javax.servlet.Filter

{
    ...
    public void doFilter(ServletRequest request, ServletResponse response,
           FilterChain chain)
           throws java.io.IOException, javax.servlet.ServletException
    {
            PrintWriter out = response.getWriter()
            chain.doFilter(request, wrapResponse((HttpServletResponse) response))

            response.setCharacterEncoding('UTF-8')
            response.setContentType('text/plain')

            def saw = 'АБВГДЕЙКА ЭТО НЕПРОСТАЯ ПЕРЕДАЧА ABCDEFGHIJKLMNOP!!!'
            def bytes = saw.getBytes('UTF-8')
            def content = new String(bytes, 'UTF-8')

            response.setContentLength(content.length())
            out.write(content);
            out.close();
    }

    private static HttpServletResponse  wrapResponse(HttpServletResponse response) {
        return new HttpServletResponseWrapper(response) {
            @Override
            public PrintWriter getWriter() {
                 def writer  = new OutputStreamWriter(new ByteArrayOutputStream(), 'UTF-8')
                 return new PrintWriter(writer)
            }
        }
    }
}

Content-Type of the filtered page is text/plain;charset=ISO-8859-1.
So, content type have changed, but charset is ignored.
As you can see, I've take some measures (I guess quite naive) to make sure content is UTF-8, but none of these steps actually was helpful.
I've also tried to add URIEncoding="UTF-8" or useBodyEncodingForUri="true" attributes to
Connector in tomcat conf/server.xml
It would be nice if somebody explained me what I'm doing wrong.
UPD: just a bit of explanation - I'm writing XSLT-applying filter, that is the real reason I'm trying to discard whole request.

A: def saw = 'АБВГДЕЙКА ЭТО НЕПРОСТАЯ ПЕРЕДАЧА ABCDEFGHIJKLMNOP!!!'
def bytes = saw.getBytes('UTF-8')
def content = new String(bytes, 'UTF-8')

Does not change a thing between saw and content. What you want is to do (using the outputstream and not the writer, this is why the charset is reset to ISO-8859-1 See tomcat doc):
out.write(saw.getBytes("UTF-8);

Your code looks okay to set the charset as UTF-8.
I don't understand what you are doing with HttpResponseWrapper.
To make it clear, this will work:
public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain chain)
   throws java.io.IOException, javax.servlet.ServletException
{
    OutputStream out = response.getOutputStream()

    response.setCharacterEncoding('UTF-8')
    response.setContentType('text/plain')

    def saw = 'АБВГДЕЙКА ЭТО НЕПРОСТАЯ ПЕРЕДАЧА ABCDEFGHIJKLMNOP!!!'

    response.setContentLength(saw.length())
    out.write(content.getBytes("UTF-8"));

}

A: This might be the problem you're having, or at least it's one part of the problem. As the documentation of setCharacterEncoding() says:

This method has no effect if it is called after getWriter has been
  called or after the response has been committed.

You should set the encoding, and only after, get the writer.

A: You are trying to set the content type after committing the response by calling getWriter.
See the documentation on getWriter and setCharacterEncoding for details.
To fix you code just move the setting of content type and encoding a few lines earlier.
    response.setCharacterEncoding('UTF-8')
    response.setContentType('text/plain')
    PrintWriter out = response.getWriter()


text:
Q: Iterating over object results in infinite loop I have an object that I am trying to recursively iterate over, but get stuck in an infinite loop. I suspect that the issue is that the variable i in my for loop does not increase, but why?
My code:
var failsafe = 0;
function iter(obj) {
    for (i = 0; i < obj.length; i++) {
        console.log("Now #"+i);
        if (typeof obj[i].contains == "object") {
            console.log(obj[i].command);
            iter(obj[i].contains);
        } else {
            console.log(obj[i].command);
        }
        if (failsafe==20) return false;
        failsafe++;
    }
}
iter(parsed);

Console input:
Now #0
do (5)
Now #0
move.up()
Now #1
move.left()
Now #2
if (check.up() == "item")
Now #0
move.down()
Now #2
if (check.up() == "item")
Now #0
move.down()
Now #2
if (check.up() == "item")
Now #0
move.down()
... and so on

Object:
[
    {
        "command":"do (5)",
        "contains":[
            {
                "command":"move.up()",
                "contains":false
            },
            {
                "command":"move.left()",
                "contains":false
            },
            {
                "command":"if (kind == \"item\")",
                "contains":[
                    {
                        "command":"move.down()",
                        "contains":false
                    }
                ]
            },
            {
                "command":"move.right()",
                "contains":false
            }
        ]
    }
]

A: The problem is you never declare var i. So when you do for (i=0;...) the variable i is in fact attached to the window (you can easily check that by logging window.i).
The result is you use the same variable for all your loops and the problem is it restarts at 0 everytime!
Easy fix : for(var i = 0;...)


text:
Q: Cannot execute a command with 'init' in it without triggering /sbin/init so I have this node package I want to run with npx, the command is the following:
npx @pika/init --help

This should just download the package, execute it, and print the help.
What it does, however, is try to execute /sbin/init.
I've tried this on my Desktop running Arch, up to date, a server running Ubuntu 18.04, and another server running CentOS 6.10 - all exhibiting the same behavior.
I've also tried surrounding the argument in quotes or escaping the /, neither of which worked.
Anyone know whats going on here and how I can avoid it?
Thanks!
Oh and for what its worth I was using bash as my shell on all three systems.

A: This behavior is described by the official npm documentation:
"By default, npx will check whether  exists in $PATH, or in the local project binaries, and execute that. If  is not found, it will be installed prior to execution."
In your case, this simply means that anything installed locally in $PATH has precedence over any remote packages.
You can use the option --ignore-existing to ignore existing binaries in $PATH, or in the local project. This forces npx to do a temporary install and use the latest version.
The resulting command looks like this:
npx --ignore-existing @pika/init --help


text:
Q: Disable side by side DatePicker How do I disable side by side DatePicker shown in my activity (running under KitKat/ Android 4.4, I'm using Sony Xperia to run it), I've been struggling so much finding this one, the left side contains scrolled part and the right side contains full calender, I want only the full calender shown:

import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.TextView;

public class versi2 extends Activity {
    private TextView textViewTanggal;
    private DatePicker datePicker;
    private int year;
    private int month;
    private int day;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.versi2);
            setCurrentDateOnView();

    }

    // display current date
    public void setCurrentDateOnView() {

        textViewTanggal = (TextView) findViewById(R.id.tvDisplayDate);
        datePicker = (DatePicker) findViewById(R.id.dpResult);

        final Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);

        // set current date into textview
        textViewTanggal.setText(new StringBuilder()
                // Month is 0 based, just add 1
                .append(month + 1).append("-").append(day).append("-")
                .append(year).append(" "));

        datePicker.init(year, month, day, dateSetListener);
    }

    private DatePicker.OnDateChangedListener dateSetListener = new DatePicker.OnDateChangedListener() {

        public void onDateChanged(DatePicker view, int year, int monthOfYear,
                                  int dayOfMonth) {
            textViewTanggal.setText(new StringBuilder()
                    // Month is 0 based, just add 1
                    .append(dayOfMonth + 1).append("-").append(monthOfYear).append("-")
                    .append(year).append(" "));

        }
    };
}

And layout :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

 ....
 ....
    <DatePicker
        android:id="@+id/dpResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

A: DatePicker has a datePickerMode attribute.
Use android:datePickerMode="calendar" to show just the calendar.


text:
Q: Dialog TextView in AsyncTask always null i've got a Dialog in my AsyncTask to show the loading of some images. In the DIalog there is a TextView that need to be updated for every image that get loaded but it always return a NullPointerException.
Can somebody help me please?
Here's the code of the AsyncTask class:
private class addCartRealms extends AsyncTask<Void, Integer, Void> {

        AlertDialog.Builder mBuilder = new AlertDialog.Builder(mainMenu.this);
        AlertDialog dialog;
        View mView = getLayoutInflater().inflate(R.layout.download_loading_dialog, null);
        TextView numberP = findViewById(R.id.loading_number);
        ProgressBar downloadProgress = findViewById(R.id.download_progress_bar);

        @Override
        protected Void doInBackground(Void... params) {

            final OkHttpClient client = new OkHttpClient();
            Realm myRealm = Realm.getDefaultInstance();

            for (int i = 0; i < downloadedCardList.size(); i++) {

                publishProgress(i);

                myRealm.beginTransaction();
                //ADDING CARDS TO REALM
                Card card = myRealm.createObject(Card.class);
                card.setDankness(downloadedCardList.get(i).getDankness());
                card.setExpansion(downloadedCardList.get(i).getExpansion());
                card.setId(downloadedCardList.get(i).getId());
                card.setImgpath(downloadedCardList.get(i).getImgpath());
                card.setLitness(downloadedCardList.get(i).getLitness());
                card.setName(downloadedCardList.get(i).getName());
                card.setRarity(downloadedCardList.get(i).getRarity());
                card.setValue(downloadedCardList.get(i).getValue());

                Request request = new Request.Builder()
                        .url(downloadedCardList.get(i).getImgpath())
                        .build();

                Response response = null;
                Bitmap image = null;
                try {
                    response = client.newCall(request).execute();

                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (response.isSuccessful()) {

                    image = BitmapFactory.decodeStream(response.body().byteStream());
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    image.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    byte[] byteArray = stream.toByteArray();
                    card.setCardImage(byteArray);

                }

                myRealm.commitTransaction();

                //cardImgUrl.add(new cardImagesAndLink(downloadedCardList.get(i).getImgpath(), downloadedCardList.get(i).getId()));

            }

            return null;
        }
        @Override
        protected void onPostExecute(Void result) {

            dialog.dismiss();
            Toast.makeText(mainMenu.this, "Download completato, scaricate " + downloadedCardList.size() + " carte.", Toast.LENGTH_LONG).show();

        }

        @Override
        protected void onPreExecute() {

            mBuilder.setView(mView);
            dialog = mBuilder.create();
            dialog.show();

        }

        @Override
        protected void onProgressUpdate(Integer... values) {

            numberP.setText(values[0] + " / "  + downloadedCardList.size()); // HERE IS THE ERROR

        }

    }

And the error is this one:
Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

A: Instead of
TextView numberP = findViewById(R.id.loading_number);

You should use the view of you dialog
TextView numberP = mView.findViewById(R.id.loading_number);

And probably do the same for the ProgressBar view if it is included in the dialogs layout

A: Utilize the dialogs findViewById like this:
TextView numberP = mView.findViewById(R.id.loading_number);
ProgressBar downloadProgress = mView.findViewById(R.id.download_progress_bar);


text:
Q: Vertical line/Separator I am trying to add a vertical line between these two items. But unable to figure out how to do so. Here are my two items.
  ${"City"}
  ${"Description"}

A: You could use the | character. or:
You can create a

 tags and then transform and rotate the line by 90deg.
Sorry for not knowing the exact CSS transform.


text:
Q: jquery remove specific div without id I need to remove with jquery one div with class name 'form-group', the third 'form-group' div in my form.
Problem is there are several divs with the same class.

             Orders Detail

 Formulaire

                                        This div is to remove

Would appreciate your expertise.
Thank you in advance, cheers, Marc

A: Use the nth-child(3) psuedo-selector to select the third .form-group in its container:

$('.form-group:nth-child(3)').remove();

         Orders Detail

 Formulaire

                  This div is to remove

Note that there's absolutely no need to include a big library like jQuery for something this simple, you can achieve it very easily with vanilla JS:
document.querySelector('.form-group:nth-child(3)').remove();

A: You can use eq(n) method for form-group divs to remove your desired div. See below code snippet
jQuery eq(n) API documentation

$(function(){
  $("#panel-form-ordersdetail .panel-body.child-form-area .form-group:eq(2)").remove();
});

             Orders Detail

 Formulaire

                                        This div is to remove


text:
Q: Which Adapter to Use - BaseAdapter or ArrayAdapter? I have a JSON string with the multiple instances of the following

*

*Name

*Message

*Timestamp

*Profile photo url

I want to create a ListView where each list will have the above. Which is the better Adapter I need to extend for this particular case, to create a Custom Adapter?

A: My assumption is that you have parsed the JSON string into an object model prior to considering either case... let's call this class Profile.
Strategy 1
An ArrayAdapter is sufficient with an overriden getView(..) method that will concatenate your multiple fields together in the way you wish.
ArrayAdapter<Profile> profileAdapter = new ArrayAdapter<Profile>(context, resource, profiles) {
   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
      View v;
      // use the ViewHolder pattern here to get a reference to v, then populate
      // its individual fields however you wish... v may be a composite view in this case
   }
}

I strongly recommend the ViewHolder pattern for potentially large lists:
https://web.archive.org/web/20110819152518/http://www.screaming-penguin.com/node/7767
It makes an enormous difference.

*

*Advantage 1. Allows you to apply a complex layout to each item on the ListView.

*Advantage 2. Does not require you to manipulate toString() to match your intended display (after all, keeping model and view logic separate is never a bad design practice).

Strategy 2
Alternatively, if the toString() method on your representative class already has a format that is acceptable for display you can use ArrayAdapter without overriding getView().
This strategy is simpler, but forces you to smash everything into one string for display.
ArrayAdapter<Profile> profileAdapter = new ArrayAdapter<Profile>(context, resource, profiles)


text:
Q: Update fragment TextView after database update I am looking to update a textview in a fragment after a database update has been made.
I have MainActivity which hosts MainFragment
MainFragment has a TextView in it which is the SUM of column a in my database.
In MainActivity I have a button which i press that opens a dialog where i can add a value to the column a in the database.  The dialog appears over the top of the fragment, but when I press OK and send that new value to the database, and then try to update the textview it is not updating.
I have the following in my fragment but I guess it is never getting called.
@Override
    public void onResume() {
        super.onResume();
        Log.d("onResume", "here");
        int balance = db.getSum();
        tvBalanceDollar.setText(Integer.toString(balance));
    }

Where could I put the db.getSum(); and the setText to update that field after the dialog is closed?
EDIT:
Does the fragment ever get paused, or the view recreated after a dialog from the activity is closed?

A: As you say, onResume() is not the best way to place that. I think the best way should be starting the dialog window using startActivityForResult(intent, your_requestCode).
Then, in the dialog when you finish adding the value to your database and want to return to your activity, do:
setResult(RESULT_OK);
finish();

And back in your main activity use onActivityResult() to update the textview:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case your_requestCode: {
            //...
            DO YOUR STUFF HERE
        }
        break;
    }
}

To update fragment's textview from main activity, you should implement a callback interface.
public interface FragmentCallback {
    public void modifyTextView(String text);
}

Then:
FragmentCallback fragCall;

An inside the previously commented onActivityResult:
fragCall.modifyTextView(yourText);

Finally you implement the callback listener on your fragment:
public class YourFragment extends Fragment implements FragmentCallback {

And inside the method you change the textview's text:
@Override
public void modifyTextView(String text) {
    yourTextView.setText(text);
}

A: just override the onStart method of fragment and call the particular textView to update text in that method.
@Override
public void onStart() {
    super.onStart();
    textView.setText(/* update method */);
    //TODO call your method here.
}


text:
Q: regular expression for ipv4 address in CIDR notation I am using the below regular expression to match ipv4 address in CIDR notation.
[ \t]*(((2(5[0-5]|[0-4][0-9])|[01]?[0-9][0-9]?)\.){3}(2(5[0-5]|[0-4][0-9])|[01]?[0-9][0-9]?)(/(3[012]|[12]?[0-9])))[ \t]*

I have tested the above using [http://regexpal.com/][1]
It seems to match the following example 192.168.5.10/24
However when I use the same example in flex it says "unrecognized rule".Is there some limitation in flex in that it does not support all the features? The above regex seems pretty basic without the use of any extended features.Can some one point out why flex is not recognizing the rule.
Here is a short self contained example that demonstrates the problem
IPV4ADDRESS [ \t]*(((2(5[0-5]|[0-4][0-9])|[01]?[0-9][0-9]?)\.){3}(2(5[0-5]|[0-4][0-9])|[01]?[0-9][0-9]?)(/(3[012]|[12]?[0-9])))[ \t]*
SPACE [ \t]

%x S_rule S_dst_ip

%%

%{
    BEGIN S_rule;
%}

<S_rule>(dst-ip){SPACE}   {
           BEGIN(S_dst_ip);
        }

<S_dst_ip>\{{IPV4ADDRESS}\}  {
       printf("\n\nMATCH [%s]\n\n", yytext);
       BEGIN S_rule;
     }

. { ECHO; }

%%

int main(void)
{
    while (yylex() != 0)
        ;
    return(0);
}

int yywrap(void)
{
    return 1;
}

When I try to do flex test.l it give "unrecognized rule" error.I want to match
dst-ip { 192.168.10.5/10 }

A: The "/" in your IPV4ADDRESS pattern needs to be escaped ("\/").
An un-escaped "/" in a flex pattern is the trailing context operator.


text:
Q: jQuery data() pass this & object into it (function($){
    var defaults = {
        name : 'benjamin'
    };

    function EasyZoom(target, options) {
        this.$target = $(target);
        this.opts = $.extend({}, defaults, options, this.$target.data()); //why extend this.$target.data()?
        this._init();
    }

    EasyZoom.prototype._init = function() {
        this.printout();
    };

    EasyZoom.prototype.printout = function(){
        console.log(this.opts);
    };

    $.fn.easyZoom = function(options){
        $.data(this, 'easyZoom', new EasyZoom(this, options));  //isn't $.data(name, value) only?, why $.data(this, 'name', object)?
    };
})(jQuery);

$(document).ready(function(e) {
    $('div').easyZoom({name: 'benny'});
});

I'm new in create jQuery plugin, I try to learn the style of easyZoom plugin. However I got few question I don't understand

*

*$.data(); ins't data param should be name & value, why in easyZoom plugin use this, name, object

*$.extend(); why extend $target.data(); object into defaults?

*why store new object inside of data? why not just var foo = new EasyZoom(this, options);

A: First, it is $.data(elem, key, value) but not $.data(name, value).
Second, $.extend() likes merge.
For an example,
$.extend({}, {'foo': '1'}, {'hoge': '2'}) => {'foo': '1', 'hoge': '2'}

You can check the docs of jQuery.
$.data()
$.extend()


text:
Q: Determine the truth value with proof I've been stuck on these two propositions for a while especially how to prove their truth value.
Note that $x$ and $y$ belong to $\mathbb{N}$.
Any idea how to solve this??
$\forall x ~ \forall y ~~ (x \ne 1) \to (xy \ne y)$
$\forall x ~ \forall y ~ \exists z ~~ (x > y) \to (x - y = z)$

A: As you define $\mathbb N$ to include $0$, the first one is false:
Setting $y = 0$ and say, $x = 10$ we find that $x \neq 0$ but $0 = xy = y = 0$.
The second statement holds basically by definition; it is hard to "prove" this without also giving some actual definition of the $<$ relation (which is usually done by saying that $x > y$ if there exists some positive $z$ such that $x = y + z$, or equivalently, $x - y = z$).


text:
Q: Hide view on scroll in NestedScrollView and take it's place I would like the yellow LinearLayout to hide as I'm scrolling the NestScrollView. Preferably with the parallax effect. What I was able to achieve already was increase alpha and set visibility to gone on appBar scroll. But I want the recyclerView below it to take it's space as I'm scrolling. Thanks

A: How I got it to work perfectly.
1. Be above RecyclerView
Added as a row with different layout, used getItemViewType() to specify different view for that first row.
2. Disappear on RecyclerView scroll with parallax effect
Had to override AppBar's addOnOffsetChangedListener() which provided me with verticallOffset variable which I used to translate just the first row in recyclerView
recyclerView.getChildAt(0).setTranslationY(verticallOffset / 2);

3. RecyclerView take its place when it dissapears
Still using the verticallOffset:
 if (alpha < -200) {
            readingsRecyclerAdapter.hideFirstRow();
        }

and then inside the readingsRecyclerAdapter I removed the row
public void hideFirstRow() {
        if (headerShowing) {
            appsList.remove(0);
            notifyItemRemoved(0);
            headerShowing = false;
        }
    }

notifyItemRemoved(0); is important here as it causes the recyclerview to take the first rows empty space.


text:
Q: Get XML node children using a variable Given the following file:
<environments>
  <dev>
    <property1>23</property1>
    <property2>blue</property2>
    <property3>apple</property3>
  </dev>
  <prod>
    <property1>27</property1>
    <property2>red</property2>
    <property3>orange</property3>
  </prod>
</environments>

And the following code:
$environmentsFile = [System.Xml.XmlDocument](Get-Content "environments.xml");
$envs = $environmentsFile.environments;

$envName = "prod"

How would I access the "prod" children and iterate through them?  I'm already iterating through the environments using ForEach ($env in $envs.ChildNodes) {} and I know I oculd do $envs.prod
I tried this:
$test = $envs.SelectNodes("//$envName")
ForEach ($ele in $test) {
    Write-Host $ele.value
}

But it didn't output anything. Inspecting reveals that it looks like $test has a single node that contains all the nodes I want, so I tried $test[0] and that didn't work either.

A: I had done a couple things wrong.  This functions as desired:
$test = $envs.SelectNodes("//$envName")[0]
ForEach ($ele in $test.ChildNodes) {
    Write-Host "$($ele.Name): $($ele.InnerText)"
}


text:
Q: How to assign a function reference to a variable? I would like to handle functions references and lambda in consistent way in PHP, but I have trouble when assigning a function reference to a variable.
function foo()
{
  echo "hi\n";
}

$here = function() { echo "hello\n"; };
$here = foo;

The last line gives me a warning. I could use string literal, but I am afraid of two things -- using it later as string by mistake, and problems with name resolution when passing such string-reference over namespace boundaries.
Is there any way to grab that reference without using strings?

A: One way is to create it as an anonymous function:
$foo = function()
{
  echo "hi\n";
};

$foo();


text:
Q: How to generate a random normal distribution of a fixed number of positive integers that sum up to a fixed value The problem is: randomly generate n positive integers that sum up to a fixed value sum and follow a normal distribution.
How can I achieve this in Python?

A: One approach might be the following: Think of an array of (sum − 1) bits. Choose (n − 1) of them as 1, the rest 0. Now between the ones, as well as before the first one and after the last, you have runs of zero or more zeros. Take the length of each run, add 1 (to turn non-negative into positive) and you have n positive integers that add up to sum.
From an implementation point of view, you don't really need that array; all you need is the positions of the ones. Make sure they are distinct, and make sure they are in the range between 0 and sum − 1 exclusive.
def random_partition(n, sum):
  indices = [-1] + sorted(random.sample(range(sum - 1), n - 1)) + [sum - 1]
  return [indices[i + 1] - indices[i] for i in range(n)]

The resulting integers will not follow a normal distribution. As comments already indicated, a normal distribution is a continuous distribution, while you are requesting integers so you need a discrete distribution. I guess it's not exactly a binomial distribution either. But since you seem to be kind of fuzzy on what distribution you need exactly, maybe this is close enough to a normal distribution to serve your needs. I honestly don't know a name for the distribution you'd get; might want to check Cross Validated about that.


text:
Q: Formula lookup wildcards When I give the command:
FormulaLookup["sphere"]

I get no results even though I know there are formulas involving spheres. Do I need to use some kind of wild card format? What is the principle here, are these "entities" or what?

A: There are formulas for spheres but probably not the ones you're looking for:
Select[FormulaLookup[], StringContainsQ[#, "sphere", IgnoreCase -> True] &]
(* {"ChargedSphere", "SphereMomentOfInertia",
"UniformDensitySphereGravitationalBindingEnergy"} *)

There are formulas for other geometric objects:
Select[FormulaLookup[], StringContainsQ[#, "area", IgnoreCase -> True] &]
(* {"AnnulusAreaMomentOfInertia", "CircleArea", \
"CircleAreaDiameter", "CircleSectorArea", "EarthquakeRuptureArea", \
"EllipseArea", "HalfDiskAreaMomentOfInertia", \
"HexagonAreaMomentOfInertia", "PentagonAreaMomentOfInertia", \
"QuarterDiskAreaMomentOfInertia", "RectangleArea", \
"RectangleAreaMomentOfInertia", "RegularNGonArea", "TrapezoidArea", \
"TrapezoidAreaMomentOfInertia", "TriangleAreaBH", \
"TriangleAreaMomentOfInertia", "TriangleAreaSSS"} *)

"Volume" yields "Spheroid" but not "Sphere"
Select[FormulaLookup[],
 StringContainsQ[#, "volume", IgnoreCase -> True] &]
(* {"EllipsoidVolume", "SpheroidVolume", "TorusVolume"} *)

but searching for spheroid doesn't yield anything more than the above "SpheroidVolume".
FormulaData["SpheroidVolume"]
(* QuantityVariable["V","Volume"] ==
 4/3 π QuantityVariable["a","Length"]^2 QuantityVariable["c","Length"] *)


text:
Q: Variance covariance matrix of regression coefficients with a probit link Suppose we are performing ordinal regression using a probit link function. The data are doses (log transformed) and responses. The responses are ordinal and can be from 0 to 4. Suppose that some of the responses are not seen in the data (e.g. 1 and 3). The variance covariance matrix from R looks like:
                        0|2      2|4             log10(dataframe[, 1])
0|2                   3           4                     8
2|4                   57          59                    25.3434
log10(dataframe[, 1]) 37         36                     18

Note that there is no  0|1 ,  1|2 , or  2|3  since there were no ones and threes in the data set. I am interested in the variance of the intercept, the variance of the probit slope, and the covariance between the intercept and the probit slope.
In the above matrix, would these values be the $(1,1)$, $(3,3)$ and $(1,3)$ entries respectively?

A: An ordinal regression model has multiple intercepts describing the baseline frequency of each outcome. In your case, you only had values 0, 2, and 4, so you have two intercepts denoted 0|2 and 2|4. So your question about the variance of the intercept cannot be interpreted unless you tell the which intercept are you talking about. So element $(1,1)$ is the variance of the first intercept that separates 0 from above 0, and element $(2,2)$ is the variance of the second intercept which separates 2 and below from above 2.
There is only one slope per predictor, however, so its variance is element $(3,3)$ of the matrix.


text:
Q: How to Pick property based if is substring of given string in Typescript My goal is to type removeUrl function:
type MyType = {
  name: string;
  last_name: string;
  children_url: string;
  children2_url: string;
  children3_url: string;
  // ...
}

function removeUrls(target: MyType): MagicType {
  const result = {}
  for (const key in target) {
    if (!key.includes('_url')) {
      result[key] = target[key]
    }
  }

  return result;
}

This may be a simple question but I'm new to typescript generics world and it's quite difficult to find any good google results to this problem :/

A: This is not possible on typescript 4.0.

But on the unreleased 4.1 beta via Template Literal Types you have some options!
If you're new to typescript this will look a bit strange:
type UrlKeys<T> = {
  [K in keyof T]: K extends `${infer Prefix}_url` ? K : never
}[keyof T]

type RemoveUrls<T> = Omit<T, UrlKeys<T>>

The UrlKeys type iterates over an objects properties. For each key, if the key K has some Prefix followed by a _url at the end, then return that key name, else return never. The [keyof T] at the end gets a union of all the keys that were not assigned to never.
Then RemoveUrls simply takes a type and Omits any keys that would be considered _urls.
You would use those types like this:
function removeUrls<T>(target: T): RemoveUrls<T> {
  const result: Partial<T> = {}

  for (const key in target) {
    if (!key.includes('_url')) {
      result[key] = target[key]
    }
  }

  return result as T;
}

const result = removeUrls({ a: 123, b_url: 'http://example.com' }) // type: { a: number }

Note that this function is now has the T generic parameter to accept any type. And the return value is the the same type, minus the url properties.
Also, when building an object one property at a time like this, you would need to type the in progress object as a Partial to make it okay that not all properties are present while being constructed. Then in the return statement, you can cast it back to a full T since you know you have processed all the properties.
Playground


text:
Q: array does not fetch the data in HTML? I'm trying to make the news list more dynamic , so i tried to make it in array and loop on the categories but unfortunately the function getw  () does not fetch the data ?

    Navbar
    <button class="navbar-toggler d-lg-none" type="button" data-toggle="collapse" data-target="#collapsibleNavId"
      aria-controls="collapsibleNavId" aria-expanded="false" aria-label="Toggle navigation">

    </button>

java script code

var list = ["General", "Entertainment", "Health", "Science", "Sports", "Technology"];

function getw() {

    var lines = "";

    for (var i = 0; i < list.length; i++) {
        lines += `

                ` + list[i] + `

`
    }

    document.getElementById("line").innerHTML = lines; (not working i don't know why ?)
}

getdata("general")

var links = document.getElementsByClassName("nav-link");
for (var i = 0; i < links.length; i++) {
    links[i].addEventListener("click", function (e) {
        var currentCat = e.target.text;
        getdata(currentCat.toLowerCase())
    })

}

var data;

function getdata(category) {
    var httpReq = new XMLHttpRequest();
    httpReq.open("GET", "http://newsapi.org/v2/top-headlines?country=eg&category=" + category + "&apiKey=d4f87946d7fc4322be9c2089316d5625");

    httpReq.send();

    data = [];

    httpReq.addEventListener("readystatechange", function () {

        if (httpReq.readyState == 4) {
            data = JSON.parse(httpReq.response).articles;
            Display();
        }

    })
}

function Display() {

    var temp = "";

    for (var i = 0; i < data.length; i++) {

        temp += `

                <img src=`+ data[i].urlToImage + ` class='img-fluid'>

`+ data[i].title + `

`+ data[i].description + `

`
    }
    document.getElementById("posts-row").innerHTML = temp;
}

.............................................................................................///////////////////////////////////////////

A: At least in the code you posted, you are not invoking the getw function.
Try adding getw() at the end of your JavaScript.


text:
Q: Recreating bugs in cocos2d iphone I guess someone must have asked a similar question before, but here goes.
It would be useful to be able to record games so that if a bug happened during the game, the recorded play can be reused later with a fixed build to confirm if the bug is fixed or not. I am using box2d as well and from what I remember it seems as if box2d is not really deterministic, but at least being able to recreate most of the state from the first time would be OK in many cases. Recreating the same randomized values would take reinstating the same time etc I assume. Any insight?

*

*I have been fiddling with calabash-ios with various success. I know it's possible to record plays, and playback them there later. I just assume it wouldn't recreate random values.

*A quick look at box2d faq and I think box2d is deterministic enough

For the same input, and same binary, Box2D will reproduce any
  simulation. Box2D does not use any random numbers nor base any
  computation on random events (such as timers, etc).
However, people often want more stringent determinism. People often
  want to know if Box2D can produce identical results on different
  binaries and on different platforms. The answer is no. The reason for
  this answer has to do with how floating point math is implemented in
  many compilers and processors. I recommend reading this article if you
  are curious:
  http://www.yosefk.com/blog/consistency-how-to-defeat-the-purpose-of-ieee-floating-point.html

A: If you encapsulate the input state the player gives to the world each time step (eg. in a POD struct) then it's pretty straightforward to write that to a file. For example, suppose you have input state like:
struct inputStruct {
    bool someButtonPressed;
    bool someOtherKeyPressed;
    float accelerometerZ;
    ... etc
};

Then you can do something like this each time step:
inputStruct currentState;
currentState.someButtonPressed = ...; // set contents from live user input

if ( recording )
    fwrite( &currentState, sizeof(inputStruct), 1, file );
else if ( replaying ) {
    inputStruct tmpState;
    int readCount = fread( &tmpState, sizeof(inputStruct), 1, file );
    if ( readCount == 1 )
        currentState = tmpState; //overwrite live input
}

applyState( currentState ); // apply forces, game logic from input

world->Step( ... ); // step the Box2D world

Please excuse the C++ centric code :~) No doubt there are equivalent ways to do it with Objective-C.
This method lets you regain live control when the input from the file runs out. 'file' is a FILE* that you would have to open in the appropriate mode (rb or wb) when the level was loaded. If the bug you're chasing causes a crash, you might need to fflush after writing to make sure the input state actually gets written before crashing.
As you have noted, this is highly unlikely to work across different platforms. You should not assume that the replay file will reproduce the same result on anything other than the device that recorded it (which should be fine for debugging purposes).
As for random values, you'll need to ensure that anything using random values that may affect the Box2D world go through a deterministic random generator which is not shared with other code, and you'll need to record the seed that was used for each replay. You might like to use one of the many implementations of Mersenne Twister found at http://en.wikipedia.org/wiki/Mersenne_twister
When I say 'not shared', suppose you also use the MT algorithm to generate random directions for particles, purely for rendering purposes - you would not want to use the same generator instance for that as you do for physics-related randomizations.


text:
Q: Mercure 0.14 configuration behind Nginx reverse proxy with supervisor - server not responding I need help configuring Mercure 0.14 to run on port 3000 on a production server, which nginx will proxy to behind the path /mercure/.
To install Mercure, I did the following:

*

*Grabbed Mercure 0.14 linux x86_64 binary from the release page on github. https://github.com/dunglas/mercure/releases

*Unpacked the tarball and moved the mercure binary to /usr/bin/mercure
I set up supervisor with the following configuration (with sensitive info redacted):
    # file: /etc/supervisor/conf.d/mercure.conf
    [program:mercure]
    command=/usr/bin/mercure run
    process_name=%(program_name)s_%(process_num)s
    numprocs=1
    environment=HOME="/home/[redacted]",USER="[redacted]",JWT_KEY=[redacted],SUBSCRIPTIO\
NS="1",CORS_ALLOWED_ORIGINS="[redacted]",USE_FORWARDED_HEADERS="1",PUBLISH_ALLOWED_ORIGIN\
S="http://localhost:3000",directory=/tmp,SERVER_NAME=:3000
    autostart=true
    autorestart=true
    startsecs=5
    startretries=10
    user=[redacted]
    redirect_stderr=false
    stdout_capture_maxbytes=1MB
    stderr_capture_maxbytes=1MB
    stdout_logfile=/var/log/mercure.out.log
    stderr_logfile=/var/log/mercure.error.log

Note that I set SERVER_NAME=:3000 in order to run it on port 3000.
Supervisor was able to start the process and shows it as running.
$ sudo supervisorctl status
mercure:mercure_0                RUNNING   pid 1410254, uptime 0:09:30

However, I'm not able to curl the server...
$ curl localhost:3000/.well-known/mercure
curl: (7) Failed to connect to localhost port 3000: Connection refused

Finally, I have Nginx set up to proxy requests on port 80 to the mercure server on port 3000. This is my Nginx configuration:
    location /mercure/ {
        proxy_pass http://127.0.0.1:3000/;
        proxy_read_timeout 24h;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

However, going to (servername)/mercure/.well-known/mercure results in a 502.
Mercure's logs only show:
{"level":"info","ts":1675706204.7100313,"logger":"admin","msg":"admin endpoint started","address":"localhost:2019","enforce_origin":false,"origins":["//localhost:2019","//[::1]:2019","//127.0.0.1:2019"]}
{"level":"info","ts":1675706204.7100613,"msg":"serving initial configuration"}

But there is no error message in the logs.
I think the Nginx part is correct, but for some reason the server is just not running/responding on port 3000. Can anyone help?


text:
Q: How can I improve my code so I don't get timing errors? I am writing code to interface with this DAC to make a sine wave. I have a sine LUT that generates values just fine, along with a DAC controller. The controller brings CS to low, feeds in the 16-bit integer bit by bit, and pulses CS to high after 16 counts. As it does pulses, it also sends an enable pulse to the sin LUT to count up one more number. This code seems to not work very well, as I'm getting spikes in output. This is because the clock reads CS as low when it is supposed to be high (figure 1), causing the DAC to read in 17 bits (in other words, read the current number's MSB as the previous number's LSB), which causes the awkward spikes (figure 2).
How could I better organize this code so that I minimize the risk of running into this timing issue?
module DAC_Control(
  input [15:0]data_in,
  input counter_enable,
  input clk,
  input rst,
  output data_out,
  output reg cs,
  output reg enable
  );

//bit counter
  reg [3:0] bit_counter;

//to help with shifting
  reg [15:0] shifter;

//shifter
  always @(posedge (clk)) begin
    if (rst) begin
      bit_counter <= 4'b0;
      shifter <= 0;
      end
    else if (counter_enable == 1) begin
        shifter <= data_in;
        bit_counter <= 4'b0;
    end
    else begin
      shifter <= shifter << 1; // shifting
      bit_counter <= bit_counter + 1'b1; // counter
    end
  end

  reg cs_hold;

  always @(posedge (clk)) begin
    if (rst) begin
      enable <= 1'b0;
      cs <= 1'b1;
      end
    else if (bit_counter == 4'b1110) begin
      enable <= 1'b1;
      cs <= 1'b0;
    end
    else if (bit_counter == 4'b1111) begin
      enable <= 1'b0;
      cs <= 1'b1;
    end
    else if (cs_hold == 1) begin
      enable <= 1'b0;
      cs <= 1'b1;
    end
    else begin
      enable <= 1'b0; // generate enable signals
      cs <= 1'b0;
    end
  end

  assign data_out = shifter[15];

endmodule

Figure 1. Yellow is DIN, Blue is CS, green is clock

Figure 2. The output of the DAC

A: DAC is using rising edge to sample the data:
http://www.analog.com/media/en/technical-documentation/data-sheets/AD5541A.pdf
Serial Data Input. This device accepts 16-bit words. Data is clocked into the serial input register on the rising edge of SCLK.

You might want to try to generate data_out and cs on the falling edge of the clk.

A: I don't know which vendor your FPGA is from, however, most have timing constraints which allow you to define the relationship between your clock and the data.  They use the idea of virtual clocks.  Think of it like there is an external clock and you get to say what the differential is between the clocks.  If the clock is directly generated from the FPGA, and not from some external source I think you can set some of the CLKs values to 0.
By setting these kind of constraints, you make it so the data output is moved relative to the clk and it will be "consistent and controlled".
+----------+                +--------+
| FPGA     |----Data_out--->|  DAC   |
+----------+                +--------+
     CLKs /\               CLKd /\
          |                      |
          +-------sys_clk--------+

Here is solution for Altera devices using SDC to time an output.
#specify the maximum external clock delay to the FPGA
set CLKs_max 0.200
#specify the minimum external clock delay to the FPGA
set CLKs_min 0.100
#specify the maximum external clock delay to the external device
set CLKd_max 0.200
#specify the minimum external clock delay to the external device
set CLKd_min 0.100
#specify the maximum setup time of the external device
set tSU 0.125
#specify the minimum setup time of the external device
set tH 0.100
#specify the maximum board delay
set BD_max 0.180
#specify the minimum board delay
set BD_min 0.120
#create a clock 10ns
create_clock -period 10 -name sys_clk [get_ports sys_clk]
#create the associated virtual input clock
create_clock -period 10 -name virt_sys_clk
#create the output maximum delay for the data output from the FPGA that
#accounts for all delays specified
set_output_delay -clock virt_sys_clk \
    -max [expr $CLKs_max + $BD_max + $tSU - $CLKd_min] \
    [get_ports {data_out[*]}]
#create the output minimum delay for the data output from the FPGA that
#accounts for all delays specified
set_output_delay -clock virt_sys_clk \
    -min [expr $CLKs_min + $BD_min - $tH - $CLKd_max] \
    [get_ports {data_out[*]}]

Alternately, if you can NOT control the relationship between data and clock with constraints, which seems cheesy to even suggest (And if true, please tell me the vendor so I can stay from them) you could make the situation better by following the suggestion of the previous answer, by changing your posedge to negedge.  Just bear in mind, this could be flexible from build to build as the output may not be constrained the way you want.


text:
Q: Convert varchar2 column to number in Oracle I have a table emp_details.
The column emp_salary is of type varchar2 in which certain rows are null:
emp_salary
100,34
null
20,2
30,3
null

I need a result in which the column type is number:
emp_salary
100.34
null
20.2
30.3
null

My attempt in code is:
select emp_salary
from emp_details
where emp_salary = to_number(emp_salary ,'9999D99','nls_numeric_characters=,.');

Error:

ORA-01722: invalid number
  01722. 00000 -  "invalid number"
  *Cause:    The specified number was invalid.
  *Action:   Specify a valid number.

How can I fix it?
I don't mean to compare the values. I just want to change the varchar to number. I will use it in a small part of my bigger function, using TO_NUMBER.

A: You are sort of almost there. You sound like you're doing a conversion of a selected value rather than a filter and you need to cater for NULLs so:-
SELECT TO_NUMBER(NVL(emp_salary,'0'),'9999D99','nls_numeric_characters=,.')
FROM emp_details


text:
Q: Meteor.js database Simple Schema question I have a collection called Elections which stores each election and all the participants in it. Each election has a field called "numberOfContenders" .
Since each election can have different number of contenders running for a position, I need to have a SimpleSchema which allows for entry of information (name, number of votes received etc) about each contender based on the 'n' number of contenders under each election.
I don't know how I can define the SimpleSchema for the variable bit.
Any help/resources will be deeply appreciated.

A: Have three schemas like this
Election
_id name location date
Contenders
_id name address
Voter
_id name address
ElectionVotes
_id election_id contender_id voter_id


text:
Q: Using ObjectMarshaller to return a RESTful paginated list I'd like to use a customized DomainClassMarshaller/ObjectMarshaller class in grails to get a nice paginated list.
I'd like the full like to appear something like this:
> GET /api/company/1/bookings
< 200 OK
{
  "url": "/api/company/1/bookings",
  "size": 42,
  "pageSize": 10,
  "nextPage": "/api/company/1/bookings/?page=2,
  "prevPage": null,
  "items": [
    { ... // booking 1
    },
    ...
    { ... // booking 10
    },
  ]
}

Whereas if there's has_a relationship between domain objects, and you get the parent object you'll just get the URL, which you can then dive into if necessary.
> GET /api/company/1
< 200 OK

{
  "url": "/api/company/1"
  ...
  "bookings": "/api/company/1/bookings"
}

However, if you're faced with a list of simple types, just go ahead and output them:
> GET /api/user/1
< 200 OK
{
  "url": "/api/user/1",
  "name" "Bob,
  "favoriteThings": [
    "Raindrops on roses",
    "Whiskers on kittens",
    "Bright copper kettles",
    "Warm woolen mittens"
  ]
}

DomainClassMarshaller has a very nice little method called asShortObject which seems like it would do the trick.
My first thought would be to register a DomainClassMarshaller that only accepts Lists of domain classes, and another one that accepts simple lists. Is that the best approach?
Are there any resources out there on doing something similar to this? I can't believe I'm the first one to have this requirement.
Thanks for all your help,
David


text:
Q: How to truncate menu label in wordpress? I want to truncate the menu label to 10 characters, and if the header label is more then it will show 10 characters followed by ...
For example:
Menu Title: ABCDEFGHIJKLMN
It should display the label as ABCDEFGHIJ...

A: Looks like the filter nav_menu_item_title is what you're after. Here's an example to use that to truncate the title to 10 characters. This is untested, but should do what you want, added to e.g. your functions.php
    function filter_nav_menu_item_title( $title, $item, $args, $depth ) {
        $truncLength = 10;
        if (strlen($title) > $truncLength) {
            return substr($title, 0, $truncLength) . "...";
        } else {
            return $title;
        }
    }

    // add the filter
    add_filter( 'nav_menu_item_title', 'filter_nav_menu_item_title', 10, 4 );

Does that do it?


text:
Q: xarray MissingDimensionsError when reading remote dataset (NBM) When reading a remote dataset of NBM (https://vlab.ncep.noaa.gov/web/mdl/nbm) I get a xarray.core.variable.MissingDimensionsError. I'm sure i'm missing some arg settings in the open_dataset.
You can see the structure of the data here: https://thredds-jumbo.unidata.ucar.edu/thredds/dodsC/grib/NCEP/NBM/CONUS/TwoD.html. The full structure is shown here using ncdump -h https://thredds-jumbo.unidata.ucar.edu/thredds/dodsC/grib/NCEP/NBM/CONUS/TwoD
vars which use time1:

*

*Precipitation_type_surface_probability_between_1p0_and_2

import xarray as xr
url = "https://thredds-jumbo.unidata.ucar.edu/thredds/dodsC/grib/NCEP/NBM/CONUS/TwoD"
ds = xr.open_dataset(url)

If you drop this variables it then goes to the next time dim
ds = xr.open_dataset(url, drop_variables="time1")
xarray.core.variable.MissingDimensionsError: 'time2' has more than 1-dimension and the same name as one of its dimensions ('reftime4', 'time2'). xarray disallows such variables because they conflict with the coordinates used to label dimensions.

full traceback
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/ray.bell/miniconda/envs/test_env/lib/python3.8/site-packages/xarray/backends/api.py", line 575, in open_dataset
    ds = maybe_decode_store(store, chunks)
  File "/Users/ray.bell/miniconda/envs/test_env/lib/python3.8/site-packages/xarray/backends/api.py", line 471, in maybe_decode_store
    ds = conventions.decode_cf(
  File "/Users/ray.bell/miniconda/envs/test_env/lib/python3.8/site-packages/xarray/conventions.py", line 600, in decode_cf
    ds = Dataset(vars, attrs=attrs)
  File "/Users/ray.bell/miniconda/envs/test_env/lib/python3.8/site-packages/xarray/core/dataset.py", line 630, in __init__
    variables, coord_names, dims, indexes, _ = merge_data_and_coords(
  File "/Users/ray.bell/miniconda/envs/test_env/lib/python3.8/site-packages/xarray/core/merge.py", line 467, in merge_data_and_coords
    return merge_core(
  File "/Users/ray.bell/miniconda/envs/test_env/lib/python3.8/site-packages/xarray/core/merge.py", line 594, in merge_core
    collected = collect_variables_and_indexes(aligned)
  File "/Users/ray.bell/miniconda/envs/test_env/lib/python3.8/site-packages/xarray/core/merge.py", line 278, in collect_variables_and_indexes
    variable = as_variable(variable, name=name)
  File "/Users/ray.bell/miniconda/envs/test_env/lib/python3.8/site-packages/xarray/core/variable.py", line 154, in as_variable
    raise MissingDimensionsError(
xarray.core.variable.MissingDimensionsError: 'time1' has more than 1-dimension and the same name as one of its dimensions ('reftime', 'time1'). xarray disallows such variables because they conflict with the coordinates used to label dimensions.

You can test locally
wget https://ftp.ncep.noaa.gov/data/nccf/com/blend/prod/blend.20210214/00/core/blend.t00z.core.f001.co.grib2

A: If you want to access these "TwoD" datasets from THREDDS Forecast Model Run Collection (FRMC) virtual datasets in Xarray, you can slice them first with the NetCDF library, then pass the sliced variable to Xarray.  And if you wrap the NetCDF variable with Dask, you can keep things lazy.
Here's an example of extracting a "best time series" for the last 60 values of the HRRR, but using 1-hour forecast data (instead of the default "analysis" 0-hour forecast you would with the FMRC Best Time Series):
import netCDF4
import xarray as xr
from dask import array as da
import hvplot.xarray

url = 'https://thredds.unidata.ucar.edu/thredds/dodsC/grib/NCEP/HRRR/CONUS_2p5km/TwoD'
nc = netCDF4.Dataset(url)
arr = da.from_array(nc['Temperature_height_above_ground'])
tau = 1
da = xr.DataArray(arr[-60:,tau,0,:,:], dims=['time','y','x'], name='temp')

Here's the time series plot to prove it worked:


text:
Q: How do I go about displaying this information in rails? I'm trying to make a rails app that tests some ports of a hostname I provide. This is what I have so far:
routes.rb:
Diagnostics::Application.routes.draw do
    match 'port_testing/test', :controller => :port_testing, :action=> :test
end

index.html.haml:
= stylesheet_link_tag 'user'

.spacey
  %h1 Port Testing
  = form_tag('port_testing/test', method: 'get') do
    = text_field_tag :hostname, 'localhost', size: 50
    - @models.each do |key,value|
      %input{:type=>"checkbox", :name=>"#{key}", :value=>1, :checked=>value}
      =key

    %input{:type => :submit, :value => "Test"}

port_testing_controller.rb:
require 'socket'

class PortTestingController < ApplicationController
    def index
        @models = {"80" => false, "443" => false, "2195" => true, "28009" => false}
    end
    def test
        puts "\n"

        hostname = params["hostname"]
        puts hostname

        ports = ["80", "443", "2195", "28009"]
        ports.each do |key|
            #puts key
            if params.has_key?(key)
                port = key.to_i
                is_port_open?(hostname, port)
            end
        end

        redirect_to("#/port_testing")
    end

    def is_port_open?(ip, port)
        begin
            Timeout::timeout(1) do
                begin
                    s = TCPSocket.new(ip, port)
                    puts "Successful"
                    s.close
                    return true
                rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
                    puts "Error"
                    return false
                end
        end
        rescue Timeout::Error
            puts "Timeout"
        end

        return false
    end
end

Right now, what I have works. I can put in a hostname in the text field, check which ports I want tested, and I get the results printed to the screen.
However, what I would like to do is to be able to save the most recent parameters I entered. Right now, after I click test, the page reloads so it resets to the default hostname and the default port. I would like it to keep the same hostname and port as I had before. How would I do this?
Also, I would like to have the results be put in a table and displayed on the same webpage. How would I go about doing this?

A: Controllers should never print to the screen. To output information, you need to create a view file. For the test controller action the view file would be app/views/port_testing/test.html.haml. Put your table there. You'll have to create some instance variables in your controller, these will be available for use in your view.
For replacing the form with the host and ports, I suggest, in the controller action, saving the params to the session. Then use the session variables to set the values of your HTML inputs.


text:
Q: HttpOnly and secure cookies with Apache mod_header for all cookies I'm using Apache 2.2.29 for a website. The apache works both to serve pages from Drupal, and as reverse proxy to an internal application server. For security reasons we want to add the flags HttpOnly and secure to all cookies send to the clients. In order to do that I've setup the following rules in the apache
Header edit Set-Cookie "(?i)^((?:(?!;\s?HttpOnly).)+)$" "$1; HttpOnly"
Header edit Set-Cookie "(?i)^((?:(?!;\s?secure).)+)$" "$1; secure"

And that works fine, for some cookies, but others are not being modified. Looking at the reponse header I see the following:
HTTP/1.1 200 OK
Date: Thu, 20 Nov 2014 22:50:01 GMT
Expires: Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified: Thu, 20 Nov 2014 22:50:01 GMT
Cache-Control: store, no-cache, must-revalidate
Cache-Control: post-check=0, pre-check=0
Set-Cookie: SESSbfb02014bca2e49545c2cacd8a8cfcfa=perqn1l3mn2saselmabnn4vla7; expires=Sun, 14-Dec-2014 02:23:21 GMT; path=/; domain=.www6.server.com; HttpOnly; secure
Set-Cookie: textsize=100; expires=Fri, 20-Nov-2015 22:50:02 GMT; path=/; HttpOnly; secure
X-Cnection: close
Content-Type: text/html; charset=utf-8
Set-Cookie: TS01bd748d=015ca10fb56fc0a5579c6ad014a58a39be63cd86225d41d272c4e99ff818001921bf8a6afe8ff8786edc26a530281a2446ac250c26; Path=/
Set-Cookie: TS01ccb021=015ca10fb57273008302fba8649a42c6cd81f3c49f372d5d34fa4c31fc345f6be3c40dff1b5db114bd54174903e671f755744110dd; path=/; domain=.server.com
Set-Cookie: TS01bd748d_28=01d8892cb5da9e13891c7af98cab63f3bea0d8549b995c92d87d9b10240fcf906df41411935b1d5db889e1e5178debe05972be3916; Path=/
Content-Length: 39891

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

Only the first two cookies are being modified in order to have the flags. The other three are not. They seem to be set later, or at least they appear after the first two. I don't know why that makes a difference, but it seems to do. Any suggestions on how to fix them?

A: Maybe the problem is that the Header edit directive runs before your application produces a response, so if the application is producing the header you want to edit, that header won't yet exist at the time the directive runs.
According documentation:

Header [condition] set|append|merge|add|unset|echo|edit header [value] [replacement] [early|env=[!]variable]
The optional condition argument determines which internal table of
  responses headers this directive will operate against. Other
  components of the server may have stored their response headers in
  either the table that corresponds to onsuccess or the table that
  corresponds to always. "Always" in this context refers to whether
  headers you add will be sent during both a successful and unsucessful
  response, but if your action is a function of an existing header, you
  will have to read on for further complications.
The default value of onsuccess may need to be changed to always under
  the circumstances similar to those listed below. Note also that
  repeating this directive with both conditions makes sense in some
  scenarios because always is not a superset of onsuccess with respect
  to existing headers:

*

*You're adding a header to a non-success (non-2xx) response, such as a    redirect, in which case only the table corresponding to always is
  used in the ultimate response.

*You're modifying or removing a header generated by a CGI script, in    which case the CGI scripts are in the table corresponding to always
  and not in the default table.

*You're modifying or removing a header generated by some piece of the    server but that header is not being found by the default
  onsuccess    condition.

REF: http://httpd.apache.org/docs/2.2/mod/mod_headers.html
You can fix this by using Header always edit.
Eg.
Header always edit Set-Cookie "(?i)^((?:(?!;\s?HttpOnly).)+)$" "$1; HttpOnly"
Header always edit Set-Cookie "(?i)^((?:(?!;\s?secure).)+)$" "$1; secure"

I hope this help.


text:
Q: How to block a person from typing user input in Java during Thread.sleep So, in this code, the main method keeps on repeating itself. I know the reason why, but I don't know how to fix it.
To be specific, the thing that's happening is that there's a Thread.sleepafter the answer has been given(I'm making a calculator, so the answer could be like "sum: 4") and the user can spam within the Thread.sleep. The program thinks their still trying to type a type of math question(because you type addition, subtraction, or multiplication) and then it repeats the main question twice.
Here's the addition method:
private static void Addition() {

    Scanner inputa = new Scanner(System.in);

    System.out.println("How many numbers would you like to add?");
    int outputa = inputa.nextInt();

    int sum = 0;
    for(int countera = 0; countera < outputa; countera++) {

        try  {
            System.out.println("Number " + (countera + 1) + ":");

            sum += inputa.nextInt();
        }
        catch(InputMismatchException ex) {

            System.out.println("Not a valid integer.");

            try {

                Thread.sleep(2000);

            }
            catch (InterruptedException e) {

                System.out.println("Error occured.");

            }

            String[] args = {};
            MiriMain.main(args);

        }

    }

    System.out.println("Sum: " + sum);

    try {

        Thread.sleep(2500);

    }
    catch(InterruptedException Ex) {

        Thread.currentThread().interrupt();

    }

    String[] args = {};
    MiriMain.main(args);//MiriMain is the main method

}

So within the sleep, the user can still type. How can I block the person from typing when the Thread.sleep is still activated? Any answer is helpful.
Thanks.

`


text:
Q: Backbone event attachment:compat:ready can't hook I want to ask question about events in backbone. I have problem to run some function when hook is triggerd.
I want to
      wp.media.view.AttachmentCompat.prototype .on("attachment:compat:ready", function (e) {
            console.log("READYY");
        });

But this isn't working. What object handle the events of AttachmentCompat ?
Maybe i do it to early ?
I was able to run my function by extending , but for me isn't best way.
           var AttachmentCompatNew = wp.media.view.AttachmentCompat.extend({
            postSave: function () {
                this.controller.trigger('attachment:compat:ready', ['ready']);

            }
        });

        wp.media.view.AttachmentCompat.prototype = AttachmentCompatNew.prototype;

Can some one help me to understand how i can trigger my functions on diffrent events ??

A:      if (wp.media) {
            wp.media.view.AttachmentCompat.prototype.on("ready", function (e) {
                console.log("Kompat Ready mokor 12");
            });
}

This event name is "ready" :) works now fine . Maybe this will help someone.


text:
Q: Python. What does this expression actually do? [f for f in (lambda x: x, lambda x: x**2) if f(1) == 1]

A: It creates a list with every function in (lambda x: x, lambda x: x**2) that returns '1' for the parameter '1'.
Of course, they both do, so this expression is kind of useless. Where did you see it?


text:
Q: Are download usage statistics available through the iPhone API? You're my last hope stackoverflowers.

A: No that is not possible on iphone.

A: No.
You need to go through the itunes connect web site for that


text:
Q: Kernel source: Submitting patch I am trying to work on Linux stock kernel (linus tree). But due to some limitation on my Linux box, I cannot pull the tree through git. So I am downloading the latest rc candidate source archive from kernel.org and then creating my own git repository treating the base source as master. Now I created a branch from it and tries to fix some sources. I have been able to create a patch through git format-patch and wanted to submit it. Again due to no internet connection availability, I have to transfer the patch file to other machine and issue the git send-email command. My questions:
1. Am I doing the right way? I mean the patch generated not directly git clone sources but on my local repository (but yes the base source is same as linus tree)
2. I have seen that in the generated patch the last line has some numbers.
For example
--
1.7.7.3
Not sure what it is all about and does it affect in applying at the base source if my changes are approved by maintainer?

A: It is fine to send a patch that is generated against something other than the main git tree, as long as the patch applies cleanly against the tree you expect the maintainer to apply it to.  The one case where I could see you having problems with your workflow is if you download a final release (say 3.6) and then send a patch during the merge window (the time between when Linux releases 3.6 and when he releases 3.7-rc1).  In the merge window, many changes are added to Linus's tree, and if some of them touch the same place you're patching, then you may need to adjust your patch.
In any case, git format-patch is an excellent choice for creating the patch that you send out, since you will avoid many patch formatting problems that beginners hit.  Also, using git send-email to send it is a great idea for the same reason -- you avoid having your mail client mess up whitespace, convert it to HTML, or whatever other annoying stuf it might do.
The last two lines like
--
1.7.7.3

just show the git version that generated the patch file.  When the patch is applied with git apply, git am, patch -p1 or whatever, those two lines are ignored and dropped, so they have no effect.
With all that said, I would suggest working on updating your development environment so that you can download a full git tree.  Having years of history is very useful for understanding code, and updating to the latest state of the tree is much faster and when you just have to download incremental changes.  The ketchup tool for downloading and patching sources is also useful, although not quite as good as using git directly in my opinion.
Good luck submitting your patch!