text:
Q: Firefox resets Javascript's variable's value I'm using Firefox 16.0.2.
I'm using an onload eventlistener to call a script which increases the value of a variable.
I need to get the variable's value before I increase it. Safari and  Chrome (Webkit) give the right result but Firefox always alerts "0"...
This is my Script:
var obj = {
    build: function() {
        var progressCount = 0;
        var otherFunction = function(number) {
                alert(number);
        }
        var finalFunction = function() {
                alert("done");
        }
        var progress = function() {
                alert(progressCount);   //    !  very important line !
                progressCount++;
                otherFunction(progressCount);
                if (progressCount == ARRAY.length) {
                finalFunction();
                }
        }
        ARRAY=document.getElementsByClassName("picture")
        for (var i = 0; i < ARRAY.length; i++)
        ARRAY[i].addEventListener("load", progress);
    }
}
obj.build();

What else could I try?
Thank you very much!


text:
Q: What do I need to add or rearrange so there is another decimal place? I'm in my first year of CS and we use Python3. I managed to code properly and submitted it into gradescope, but it was incorrect because one decimal was missing (the 4 at the end). My professor told me to rearrange the equation, so I tried swapping the numbers around, but it still didn't give me the answer I want.
I swapped the multiplied numbers with the one beside it, but it only threw off the number more.
import math
import stdio
import sys

theta = float(sys.argv[1])
n1 = float(sys.argv[2])
n2 = float(sys.argv[3])

theta1_rad = theta1*math.pi/180
theta2_rad = math.asin(n1*math.sin(theta1_rad)/n2)
theta2 = theta2_rad*180/math.pi

print(theta2)

When I plug in $ python3 snell.py 58 1 1.52 into the terminal, I expect the output of 33.912513998258994, but the actual output I get is 33.91251399825899.

A: As stated in this answer in a similar question, try using numpy.float128. Or you could go for Decimal datatype  as stated in the accepted answer.

A: import math
import sys

theta = float(sys.argv[1])
n1 = float(sys.argv[2])
n2 = float(sys.argv[3])

theta1_rad = round(theta*math.pi/180,15)
theta2_rad = round(math.asin(n1*math.sin(theta1_rad)/n2),15)
theta2 = round(theta2_rad*180/math.pi,15)

print(theta2)

Try this hopefully it will work according to your expectation!

redpajama_set_name: RedPajamaStackExchange


text:
Q: This code only allows the use of Carousel Post style one time I recently learned about web development, and I want to build my own portfolio website using Github Pages. For the 'Portfolio' section, I want to use a slider using Javascript. Then, when I copy paste the code and change the title to 'Blog' section, this new section didn't apply the slider that seen in Portfolio.
I already seen multiple online sources to see where is my problem, and it shows that the getElementById only can be used one time. I try to modify the code to use querySelectorAll but it's still doesn't work.
This is the JS code that I used:
const sliderContainer = document.getElementById('sliderContainer');
const slider = document.getElementById('slider');
const cards = slider.getElementsByTagName('li');

var elementsToShow = 3;
if (document.body.clientWidth < 1000) {
  elementsToShow = 1;
} else if (document.body.clientWidth < 1500) {
  elementsToShow = 2;
}

var sliderContainerWidth = sliderContainer.clientWidth;

var cardWidth = sliderContainerWidth / elementsToShow;

slider.style.width = cards.length * cardWidth + 'px';
slider.style.transition = 'margin';
slider.style.transitionDuration = '1s';

for (var index = 0; index < cards.length; index++) {
  const element = cards[index];
  element.style.width = cardWidth + 'px';
}

function next() {
  if (+slider.style.marginLeft.slice(0, -2) != -cardWidth * (cards.length - elementsToShow)) slider.style.marginLeft = +slider.style.marginLeft.slice(0, -2) - cardWidth + 'px';
}

function prev() {
  if (+slider.style.marginLeft.slice(0, -2) != 0) slider.style.marginLeft = +slider.style.marginLeft.slice(0, -2) + cardWidth + 'px';
}

function autoPlay() {
  prev();

  if (+slider.style.marginLeft.slice(0, -2) === -cardWidth * (cards.length - elementsToShow)) {
    slider.style.marginLeft = '0px';
  }

  setTimeout(() => {
    autoPlay();
  }, 3000);
}

and this is my HTML code. I use TailwindCSS for the CSS framework.

            <button class="bi bi-arrow-left-circle-fill mb-2 ml-2 flex h-9 w-9 items-center justify-center rounded-full border border-slate-300 text-slate-300 hover:border-primary hover:bg-primary hover:text-white"
            onclick="prev()"
            ></button>

Slide 1

Slide 2

Slide 3

            <button
              onclick="next()"
              class="bi bi-arrow-right-circle-fill mr-2 mb-2 ml-2 flex h-9 w-9 items-center justify-center rounded-full border border-slate-300 text-slate-300 hover:border-primary hover:bg-primary hover:text-white slider__btn--right"
            ></button>

Please help me modify the JS code so it can be use multiple times. thanks in advance!


text:
Q: In which option, the diode will make the lm78xx circuit safer
This image was taken from Fairchild's datasheet on lm78xx. I have already built a working example of it, but I am still thinking about adding some additional diode protection (D1, D2). Which option should I go for? Are any of these necessary, or does the short circuit protection cover all backwards current flow dangers? Will any of these diodes add noise to the circuit? Thank you for help.


text:
Q: three.js How to hack OutlinePass to outline all selected objects? I would like to modify the OutlinePass to outline all of the selected objects in the scene, including those contained within the bounds of the other in screen space (I also hope I just used that term correctly).
I am using three.js OutlinePass to indicate objects currently selected in the scene. With ray picking I append to the selected objects array, then update outlinePass.selectedObjects with said array.
The objects I select are PlaneBufferGeometry with MeshBasicMaterial. Each next drawn plane has increasing renderOrder as well as, just slightly, larger z axis offset (which in my case points upwards), so that you can correctly pick them.

*

*If I select two disjoint planes, the outline works correctly.

*If I select two intersecting planes, the outline works okay - it only draws around the two intersecting shapes -- this effect is actually nice, but would collide with fixing the next point anyway.

*If I select two planes, where one is contained within the other (contained in terms of view, looking from where the camera is), then only the outer shape is outlined. Yes, that's probably a feature of OutlinePass, not a bug.

Current outline behaviour matches what it's designed to do (linked easy to understand list of steps it does).
I've spent at least 1-2 hours following the OutlinePass source, but I'm not familiar with the subject of vertex shaders or depth masks and while I would like to learn about them in the future, I can't do that right now. I believe the OutlinePass could be modified to achieve what I need.
The OutlinePass currently overrides the scene material to prepare for the edge detection pass. I'm hoping by modifying that behavior (so different objects have different materials, hence can be detected by edge detection pass) could either be modified by changing one of the used shaders or depth parameters to distinguish different objects to outline (and not only their "encompassing shapes", so to speak).
JS fiddle here, look for the UNCOMMENT line at the bottom of JS to see the issue I described. Once you uncomment that line, I would like both of these planes to be outlined.
I'm aware there are other ways to show object outlines (like enlarging an object copy behind it), but I'm interested in using the OutlinePass :). Thank you!


text:
Q: How to create a Binary Tree in Python? # Binary tree node
class node:

    def __init__(self, data):
        self.left=None
        self.right=None
        self.data=data

# Function to create a new
# Binary node
def newNode(data):
    return node(data)

def t():
    root=newNode("A")
    root.left = newNode("B")
    root.right = newNode("C")
    root.left.left = newNode("D")
    root.left.right = newNode("G")
    root.right.right = newNode("E")
    root.right.right.left = newNode("F")

print(t)

Hi, I have tried to create a Binary Tree above but I did not managed to print out the binary tree when I print "t".
Instead of a Binary Tree, it shows me this:

A: Function t just creates a binary tree. If you want to print a tree you need to traverse it and print it. Depending on the way you want to print a tree, there are different traversal techniques,  the popular of which are Inorder, Preorder and Postorder. Check this wiki link for tree traversal methods.
Your code has to be extended to do the required tree traversal. Sample is below:
# Binary tree node
class node:

    def __init__(self, data):
        self.left=None
        self.right=None
        self.data=data

# Function to create a new
# Binary node
def newNode(data):
    return node(data)

def t():
    root=newNode("A")
    root.left = newNode("B")
    root.right = newNode("C")
    root.left.left = newNode("D")
    root.left.right = newNode("G")
    root.right.right = newNode("E")
    root.right.right.left = newNode("F")
    return root

def in_order(root):
    if root:
        in_order(root.left)
        print (root.data)
        in_order(root.right)

def pre_order(root):
    if root:
        print (root.data)
        pre_order(root.left)
        pre_order(root.right)

def post_order(root):
    if root:
        post_order(root.left)
        post_order(root.right)
        print (root.data)

root = t()

print ("In Order")
in_order(root)
print ("Pre Order")
pre_order(root)
print ("Post Order")
post_order(root)

Output:
In Order
D
B
G
A
C
F
E
Pre Order
A
B
D
G
C
E
F
Post Order
D
G
B
F
E
C
A

A: So two things:
When you do print(t) instead of print(t()), there's a difference. print(t) prints the function object itself, whereas print(t()) prints the result returned by the function.
However, even if you do the latter, you'll print None because t() doesn't return anything. You'll need to return root from t() and also you'll have to write a special function that iterates through the tree to print each node's value (if that's what you want)
Here's an example:
# Binary tree node
class node:

    def __init__(self, data):
        self.left=None
        self.right=None
        self.data=data

# Function to create a new
# Binary node
def newNode(data):
    return node(data)

def t():
    root=newNode("A")
    root.left = newNode("B")
    root.right = newNode("C")
    root.left.left = newNode("D")
    root.left.right = newNode("G")
    root.right.right = newNode("E")
    root.right.right.left = newNode("F")
    return root

def treeToString(root, level=0):
  ret = "\t"*level+repr(root.data)+"\n"
  if root.left != None:
      ret += treeToString(root.left, level+1)
  if root.right != None:
      ret += treeToString(root.right, level+1)
  return ret

print(treeToString(t()))

# if you want to assign the tree to an object then do this:

tree = t()
print(tree.left.data)
print(tree.right.data)

A: # Binary tree node
class node:

    def __init__(self, data):
        self.left=None
        self.right=None
        self.data=data

# Function to create a new
# Binary node
def newNode(data):
    return node(data)

def tree():
    root=newNode("A")
    root.left = newNode("B")
    root.right = newNode("C")
    root.left.left = newNode("D")
    root.left.right = newNode("G")
    root.right.right = newNode("E")
    root.right.right.left = newNode("F")
    return root

t = tree()

print(t.left.data)
print(t.right.data)
print(t.root)

How do I access the root of the tree from here?
I have tried printing t.root but it seemed to have an error :(


text:
Q: Clarification about this step in matrix proof? Suppose $A$ is a matrix of rank $r$ of order $n \times m$ and suppose it can be partitioned into pieces $A_{11},A_{12},A_{21},A_{22}$, where the leading minor $A_{11}$ is of size $r \times r$ and is non-singular.
In a proof, my textbook uses the following property:

If $A_{11}^-$ is the inverse of $A_{11}$, then by the construction there is a matrix $B$ such that $[A_{21}, A_{22}] = B [ A_{11}, A_{12}]$

It doesn't elaborate/explain, and I'm unsure how exactly this is justified.
Intuitively, I suppose it is because $A$ is of rank $r$, and the sub-matrix $A_{11}$ is also of rank $r$. Could someone explain this step to me?

A: The matrix $A$ is split into two rows $[A_{11}, A_{12}]$ (top) and $[A_{21}, A_{22}]$ (bottom). Since the total rank is $r$ and the top row already has rank $r$, each of the bottom rows is a linear combination of some of the first $r$ rows. Denoting $A_j$ for the $j$th row of $A$, this means for each $i > r$ there are coefficients $b_{ij}$ such that
$$A_i = \sum_{1\leq j \leq r}b_{ij}A_j$$
These coefficients populate a $(n-r)\times r$ matrix $B = (b_{ij})$, with $BA_{11} = A_{21}$ and $BA_{12} = A_{22}$.


text:
Q: django - add l tag - render_to_string in my view.py:
     subject = "Thank you for your payment!"
     template = render_to_string('cart/email_template2.html', {'name':
     request.user.first_name,
          'transaction_id' : transaction_id, 'total':total, 'items': items})

     to = request.user.email
     res = send_mail(subject , template , settings.EMAIL_HOST_USER, [to],
          fail_silently=True)

in my email_template2.html:
Dear {{name}},

Thank you for making your payment towards:

Your Transaction ID is {{transaction_id}}
Total Amount Paid is {{total}} AED

It's been a pleasure doing business with you and below you will see the links to
download your purchased items.

{% for i in items %}

{% endfor %}
Best wishes,

here is the email i receive (output):
Email received from the app
"i" are the links for the items to be downloaded but they are presented as text not links. How to add a link? I tried to add  tag but in the email it stays that way.
Thanks...

A: Probably your template should have proper html structure like:
<!DOCTYPE html>

        <title>Error {{error_code}} occurred.</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">

            {% block content %}
            {% endblock content %}

and add this template as html_message parameter to the send_mail as it is here: How to send html email with django with dynamic content in it?
and here:
https://docs.djangoproject.com/en/4.0/topics/email/


text:
Q: run eclipse/che local image on kubernetes I would like to run the eclipse/che image that i built in my PC.
Step 1: I built che based on the instructions: https://github.com/eclipse/che/wiki/Development-Workflow.
mvn clean install to create the image under assembly-main/target folder as a tar file.
Step 2: tried running the image on kuernetes using:
$ helm upgrade --install che --namespace che --set cheImage=eclipse/che-server:7.0.0-beta-4.0 --set global.cheWorkspacesNamespace="che" --set global.ingressDomain=${CHE_DOMAIN}.nip.io ./
... as shown here: https://che.eclipse.org/running-eclipse-che-on-kubernetes-using-docker-desktop-for-mac-5d972ed511e1
I believe that the above command pulls the image from public image registry (is it docker hub?). I would like to use the image that i built using step #1 shown above.
Please let me know how I can do that?

A: After successfully running mvn clean install you can build the docker image using dockerfiles/che/build.sh like this:
dockerfiles/che/build.sh --organization:myorg --tag:mytag --dockerfile:Dockerfile
This should build image myorg/che-server:mytag. Then you can push this image to any docker registry you are using in your k8s cluster and use it in the helm chart.


text:
Q: JavaScript: match is not a function I am coding a javascript project right now, and getting an error that I wasn't expecting. When I try running:
*There are text inputs going into firstCheck and lastCheck
function firstCheck(FirstName){
    if(FirstName.value != null || (alphaNumCheck(FirstName))){
      return true;
    }
    valCheck = false;
    return false;
}

function lastCheck(LastName){
   if(LastName.value != null || (alphaNumCheck(FirstName))){
      return true;
   }
   valCheck = false;
   return false;
}

function alphaNumCheck(entry) {
   let regex = /^[a-z0-9]+$/i;
   if (entry != null && entry.match(regex)) {
      return true;
   } else {
      return false;
   }
}

I am getting an error that states: Uncaught TypeError: entry.match is not a function
I use the exact same code in another js file of mine and it works perfectly. Does anyone have an idea as to why it isn't working now?

A: You're passing the HTMLInputElement object into alphaNumCheck. You want to pass its value in instead:
if(FirstName.value != null || (alphaNumCheck(FirstName.value))){
// Added .value here ---------------------------------^

Also note that .value on an HTMLInputElement (or other HTML elements with a .value property) will never be null, it's always a string. So there's no need for the != null part of the above (and if there were, you already have it in alphaNumCheck anyway).


text:
Q: How to access component from another view in android I have created a custom dialog and inside it i create a view page which both have different layout file. Method to show the dialog is in MainActivity.
I inflate a layout to my adapter class where i populate the content. In this layout there is a button. My question is "How can i access the button from the layout that i inflate in my adapter class from my MainActivity. The reason I want to do this is because I want to dismiss the dialog when the button is clicked.
Thanks.
Here is the code of what i have done so far.
MainActivity:
public void ShowPromoOverlay(){

    promoOverlay = new Dialog(this);
    promoOverlay.requestWindowFeature(Window.FEATURE_NO_TITLE);
    promoOverlay.setContentView(R.layout.fragment_overlay);

    final List<Promotion> pageArr = new ArrayList<>();
    int maxcounter = 5;
    if (promotionList.size() < maxcounter) {
        maxcounter = promotionList.size();
    }
    for (int counter = 0; counter < maxcounter; counter++){
        pageArr.add(promotionList.get(counter));
    }

    TestPagerAdapter adapter = new TestPagerAdapter(this, pageArr);
    cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager
    pager = promoOverlay.findViewById(R.id.overlayPager);
    pager.setPageMargin(50);
    pager.setAdapter(adapter);

    com.viewpagerindicator.CirclePageIndicator indicator =
    promoOverlay.findViewById(R.id.overlay_page_indicator);
    indicator.setViewPager(pager);
    indicator.setCurrentItem(0);

    promoOverlay.show();

    View inlcudeLayout = findViewById(R.id.my_custom_dialog_layout);
    ImageView closeBtn = (ImageView) inlcudeLayout.findViewById(R.id.closeBtn);
    closeBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            promoOverlya.dismiss();
        }
    });
}

fragment_overlay:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/fragment_over"
android:background="@color/bg_orange"
android:layout_width="match_parent"
android:layout_height="match_parent">

<cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/overlayPager">

    <include layout="@layout/my_custom_dialog" />

</cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager>

<com.viewpagerindicator.CirclePageIndicator
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/overlay_page_indicator"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="70dp">

</com.viewpagerindicator.CirclePageIndicator>
</RelativeLayout>

my_custom_dialog:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/my_custom_dialog_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp">

<android.support.v7.widget.CardView
    android:layout_width="310dp"
    android:layout_height="300dp"
    android:layout_centerInParent="true"
    android:layout_marginTop="40dp"
    app:cardBackgroundColor="@color/white"
    app:cardCornerRadius="15dp">

    <ImageView
        android:id="@+id/closeBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_clear_grey_600_24dp"
        android:layout_marginTop="7dp"
        android:layout_marginRight="7dp"
        android:elevation="5dp"
        android:layout_gravity="right"/>

</android.support.v7.widget.CardView>
</RelativeLayout>

TestPagerAdapter:
public class TestPagerAdapter extends PagerAdapter {

Context context;
LayoutInflater inflater;
List<Promotion> pageArr;

public TestPagerAdapter(Context context, List<Promotion> pageArr){
    this.context = context;
    this.pageArr = pageArr;

    inflater = ((Activity) context).getLayoutInflater();
}

public TestPagerAdapter(Context context){
    this.context = context;

    inflater = ((Activity) context).getLayoutInflater();

}
@Override
public int getCount(){
    return pageArr.size();
}
@Override
public Object instantiateItem(ViewGroup container, int position){
   View view = inflater.inflate(R.layout.my_custom_dialog, container,
false);
    TextView prTitle = view.findViewById(R.id.title_pr);
    TextView prDescription = view.findViewById(R.id.description_pr);
    TextView readMoreBtn = view.findViewById(R.id.readMore);

    view.setTag(position);
    ((ViewPager) container).addView(view);

    final Promotion promotion = pageArr.get(position);

    prTitle.setText(promotion.getTitle());
    prDescription.setText(promotion.getDescription());

    return view;

}

@Override
public boolean isViewFromObject(View view, Object o) {
    return view == ((View) o);
}

@Override
public void destroyItem(View container, int position, Object object) {
    ((ViewPager) container).removeView((View) object);
}
}

A: Nice question. You should have to use the interface. let's try this code.
public interface OnButtonClickListner {
  public void OnButtonClick();
}

Now You need to pass this interface in the adapter. like this
TestPagerAdapter adapter = new TestPagerAdapter(this, pageArr TestPagerAdapter adapter = new TestPagerAdapter(this,new OnButtonClickListner()
{

    @Override
    public void OnButtonClick() {
    // dismiss dialog here
    }
});

Now, You need to change the constructor of Viewpager adapter. like below:
public TestPagerAdapter(Context context, List<Promotion> pageArr,OnButtonClickListner listner){
    this.context = context;
    this.pageArr = pageArr;
    this.onButtonClickListner=listner;
    inflater = ((Activity) context).getLayoutInflater();
}

Now you just need to call this listener method from adapter like onButtonClickListner.OnButtonClick(); and the method of popup will call and you will easily dismiss the dialog. you may also pass the argument if you need to require to pass the position of view page.
Click event of read more button like below :
readMoreBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onButtonClickListner.OnButtonClick();
        }
    });

Hope this will help you.
Happy coding.....


text:
Q: Expand submenu item to fit header (first right then left) I have the following structure:

            Menu

Submenu

and so far the following CSS:
div.wrap {
    background: #eee;
    height: 80px;
}

div.menu {
    margin-left: 50px;
    background: #36e;
}

div.item {
    background: #d00;
    color: #fff;
    line-height: 40px;
    padding: 0px 20px;
    font-size: 16px;
    display: inline-block;
    margin-left: 50px;
}

div.item:hover {
    background: #b00;
}

div.submenu {
    display: none;
    background: #0b0;
    height: 40px;
    position: absolute;
    right: 0%;
    top: 50%;
    min-width: 300px;
}

div.item:hover div.submenu {
    display: inline-block;
}

div.submenuitem {
    line-height: 40px;
    padding: 0px 20px;
    background: #b00;
    color: #fff;
    display: inline-block;
}

JSFiddle
The behaviour I'm after is that the width of submenuitem expands to fit its textual content, but that it can use at most the width of wrap for expanding. It should also be positioned directly under item unless the width of submenuitem will be larger than the distance from its original position to the right end of wrap. Thereafter it should expand to the left until it meets the left edge of wrap.
As you can see this succeeds perfectly when I can know the distance from submenuitem's original position to the right end of wrap by setting right: 0%; min-width: 300px; on submenuitem, but I want to do this in a way that doesn't require knowing that distance.
I have been trying to craft or find a solution to this for the past few days and have not managed to get any closer. Is it even possible with pure CSS to begin with?

A: Is this something you want? check this one nd let me know.
http://jsfiddle.net/zmcEC/9/
div.wrap {
    width: 400px;
    background: #eee;
    position: relative;
    height: 80px;
}

div.submenu {
    display: none;
    background: #0b0;
    height: 40px;
    position: absolute;
    right: 0;
    top: 40px;
    left:0;
}


text:
Q: An internal response header size limit was exceeded
This error occurrs when I perform a redirect to another part of the site in question.
return this.RedirectToActionPermanent("Index", "Dashboard"

The code does not step into the Index method in the Dashboard controller before the error occurs.

I think the Fiddler response header posted is not the >internal< Response header in the error message.
Could anyone explain how best to increase the size limit of the internal response header?
Or, Are we looking at needing to compress the internal response header as a solution?
For your information the call to redirect above was working day in day out for about 3 months until it broke about 5 days ago.
[Edit 1]
The program.cs file is now looking like:
        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args).UseStartup<Startup>().ConfigureKestrel((context, options) => {
            options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(5);
            options.Limits.MaxResponseBufferSize = 1024000;
            options.Limits.Http2.HeaderTableSize = 16384;
        });

However, the same error is still occurring.
[Edit 2 18.03.19 2:28am]
The problem was caused by a User Claim not being filled in (Identity Table) on one of the profile users. I filled the data in manually in SSMS and the error stopped occurring.
TIA.
David

A: I have also faced similar issue, for me
this was caused by a bug in WinHTTP which happened long time ago (core 2.0). When a redirect response occurs, WinHTTP prefers to reuse the same connection to follow the redirect.
The number of response bytes drained is controlled by the WinHttpHandler.MaxResponseDrainSize.
When the response size exceeds MaxResponseDrainSize the request is aborted with specified error.
The issue disappeared when i upgraded to 2.1

*

*Update Timout Issue
The settings you add as KeepAliveTimeout = TimeSpan.FromMinutes(5); applies to Kestrel but not IIS.
There is a reverse proxy setup between IIS and Kestrel. So you made the Timeout of Kestrel to 5 Min. But IIS sits with default timeout which is 120sec. You can change the time out in
IIS->Sites->Select your Site->Advanced Settings ->Limits->Connection Time Out.
Try changing this settings to check whether this error happens.
Also there is another setting available in Configuration Editor


text:
Q: Change default Steam download folder from command line for all users I have a classroom of 35 Ubuntu computers managed by Puppet.  I want to install Steam on them... no prob here.
But student home drives are networked, and I don't want Steam downloading to their networked home drives by default.
Each computer has a 1 TB SSD, and a shared space at /shared.  This is where I want the default download location set to.
Is there a way for me to change Steam's default download folder via the command line, for all users of Steam?


text:
Q: How to embed instance method with link_to text field? On erb:
@student.count  #--> 4

<%= link_to "Show All",   'all'   %>
#-->Show all

I want to show

show All(3)

.
I tried

<%= link_to "Show All"@students.count,   'all'   %>

or

<%= link_to "Show All"+@students.count,   'all'   %>

But all didn't work

A: Use interpolation

<%= link_to "Show All(#{@student.count})", 'all' %>

This doesn't work because you are concatenating a string and a number (TypeError: no implicit conversion of Fixnum into String)
"Show All" + @students.count

This works
"Show All" + @students.count.to_s

A: TRY

<%= link_to "Show All(" + @students.count.to_s + ")" , 'all' %>

OR

<%= link_to "Show All(#{@student.count})", 'all' %>


text:
Q: Angular 2 load data before render template I have the following html code:

            {{ caterory.name }}

            {{room.room_no}}
            {{schedule.firstName}}

When I run I'm getting the following error:

TypeError: Cannot read property 'name' of undefined

After I googled cause is that data is nod loaded while template render. This is my component code: How to load data first and then render template?
ngOnInit() {  this.reservationService.getUserBranch(this.authservice.getUserID()).subscribe(data => {
      this.userBranch = data.json().branch;
      this.brSelectedValue = this.userBranch[0].id
      this.reservationService.getPerson('').subscribe(data => {
        this.persons = data.json().person;
      });
      // TO DO
      this.fillDataRange();
    });
  }

This fillDataRange is my function :
fillDataRange() {
    this.reservationService.getReservation(this.brSelectedValue.toString(), this.intl.formatDate(this.dateFrom, 'yyyy-MM-dd'), this.intl.formatDate(this.dateTo, 'yyyy-MM-dd')).then(data => {
      this.data = data;
      console.log("Start", this.data);

      for (var i = 0; i < this.data.length; i++) { // Loop Through Categories
        if (this.data[i].rooms.length > 0) {
          for (var j = 0; j < this.data[i].rooms.length; j++) { // Loop Through Rooms from Category
            if (this.data[i].rooms[j].reservations.length > 0) {
              var sheduleArray = [];
              var a = 0;
              var d = a;
              var sumDayFiff = 0;
              for (var t = 0; t < this.data[i].rooms[j].reservations.length; t++) {
                var sheduleFrom = new Date(this.data[i].rooms[j].reservations[t].startDate);
                var sheduleTo = new Date(this.data[i].rooms[j].reservations[t].endDate);
                var status = this.data[i].rooms[j].reservations[t].status;
                var oneDay = 24 * 60 * 60 * 1000;
                var diffDays = Math.round(Math.abs((sheduleFrom.getTime() - sheduleTo.getTime()) / (oneDay)));
                for (a; a < this.segment; a++) {
                  var current = new Date(datesArray[d]);
                  if (current >= sheduleFrom && current <= sheduleTo) {
                    sheduleArray[a] = new Schedule(this.data[i].rooms[j].reservations[t].id, status, sheduleFrom, sheduleTo, this.data[i].rooms[j].reservations[t].id, this.data[i].rooms[j].reservations[t].id, this.data[i].rooms[j].reservations[t].id, this.data[i].rooms[j].reservations[t].id, diffDays, current, "reservationModal('" + current + "')", 'false', this.data[i].rooms[j].reservations[t].id, this.data[i].rooms[j].reservations[t].id);
                    a++;
                    d = d + diffDays;
                    sumDayFiff = sumDayFiff + diffDays;
                    break;
                  } else {
                    sheduleArray[a] = new Schedule("", 1, new Date(), new Date(), 1, "", "", "", 1, current, "reservationModal('" + current + "')", 'true', null, null);
                  }
                  d++;
                }
                sumDayFiff--;
              }
              for (a; a < this.segment - sumDayFiff; a++) {
                sheduleArray[a] = new Schedule("", 1, new Date(), new Date(), 1, "", "", "", 1, datesArray[d + 1], "reservationModal('" + 1 + "')", 'true', null, null);
                d++;
              }
              this.data[i].rooms[j].reservations = sheduleArray;
            } else {
              for (var f = 0; f < this.segment; f++) {
                this.data[i].rooms[j].reservations[f] = new Schedule("", 1, new Date(), new Date(), 1, "", "", "", 1, datesArray[f], "reservationModal('" + 1 + "')", '', null, null);
              }
            }
          }
        }
      }
      console.log("End", JSON.stringify(this.data));
    });
  }

A: You can use ?. instead of . to avoid errors in case the value before . is null

        {{ caterory?.name }}

        {{room.room_no}}
        {{schedule?.firstName}}

If you fix the ng-repeat (AngularJS) to the Angular 2 (4) syntax, you don't need ? anymore in this specific example, because Angular won't try to render {{ caterory?.name }} when data is not yet available.


text:
Q: Show/hide working inconsistently on a Jquery imagemap I'm working on an imagemap that not only is hi-lighted, but also does a show/hide on a some additional information on a Drupal site:
http://dev-wateraid.pantheonsite.io/where-we-work
If you hover over countries like Canada you'll see the DIV show up, but if you hover over the United States the area is hi-lighted but it doesn't trigger the show/hide -- similar with Sierra Leone, South Africa, the UK, Papua New Guinea, and a few others.
The code I'm using to do the show hide is:
$('area').on({
   mouseover : function(e){
   var $this = $(this),
   $office = $('#'+$this.prop('alt'));
   $($office).removeClass("hidden");
},
   mouseout : function(e){
   var $this = $(this),
   $office = $('#'+$this.prop('alt'));
   $($office).addClass("hidden");
}
});

The image map holds the alt tag which is then used to show/hide a div:
<area coords="96,67,97,61,76,40,69,45,55,36,55,-20,-4,-31,-40,-15,-41,-12,-20,0,-23,3,-31,2,-31,-1,-47,5,-39,11,-27,11,-20,9,-19,16,-29,21,-33,19,-39,29,-35,33,-37,36,-29,40,-25,38,-23,41,-23,46,-17,44,-12,47,-5,45,-7,52,-35,68,-33,69,-14,61,9,45,5,43,16,32,14,43,29,38,30,34,34,33,45,38,58,40,59,40,60,41,71,48,79,59,81,57,87,67,90,66" shape="poly" href="/" alt="United States">

This is the div that would be toggled to be show with the United States information.

United States

 The America team helps to coordinate and fund operations across our country programs, with Nicaragua a particular focus.

I keep looking for reasons most of the countries might work but others wouldn't -- spelling is consistent -- I don't believe there are any hidden characters.
I've validated the code as much as I could, but I just can't see it.

A: I believe the issue may be the space in the "id", for example
id="United States"

may actually be interpreted as
id="United"

A: jQuery selector can't handle "#United States"... It pretty much ignores the "States". So if you really need the ID to be "United States" you can use:
$("[id='"+$this.attr('alt')+"']")

Or you can just change the 'alt' and 'id' to "UnitedStates".


text:
Q: Getting LDAP running with PHP on 2008 R2 I'm having trouble getting the php ldap extension running on my web server, which is running 2008 R2.
Install Notes

*

*Apache: httpd-2.2.16-win32-x86-no_ssl.msi

*PHP : VC6 x86 Thread Safe (2010-Jul-21 20:06:17) (ZIP)

*adLDAP.php

Steps I've taken

*

*Made sure php_ldap.dll is in C:\PHP\ext (I had to get this from http://bugs.php.net/bug.php?id=46971)

*Made sure libeay32.dll and ssleay32.dll are in C:\PHP

*C:\PHP has been added to PATH

*extension=php_ldap.dll is uncommented in php.ini

*extension_dir is set to C:\PHP\ext in php.ini

*ran a phpinfo(); the correct php.ini is being loaded, but ldap is not initialized

I'm really at a loss for what might be happening, when I try and use the extension I get the following error (expected since it didn't load):
exception 'adLDAPException' with message 'No LDAP support for PHP. See: http://www.php.net/ldap' in C:\Website\hmis\adLDAP.php:338 Stack trace: #0 C:\Website\hmis\login.php(10): adLDAP->__construct() #1 C:\Website\hmis\index.php(2): require_once('C:\Website\hmis...') #2 {main}

Does anyone have any advice on what might be going wrong? Thanks.
Edit: So it seems like php_ldap.dll is missing from 5.3.3 VC6 builds, I got my copy from a 5.3.1 VC6 build. Could that be causing issues? I'm using apache so I can't use the official VC9 PHP builds, should I try to use ApacheLounge builds? I don't think it should be necessary because I got LDAP working with the official builds for 5.3.1
Edit 2: So the other thing I've tried is completely removing the php_ldap.dll from C:\PHP\ext . I get the exact same error as before, and apache doesn't crash as I would expect it to. Shouldn't it not be able to start with a missing extension?

A: I had a similar issue on a 2008 box. My problem turned out to be a result of incorrect dll's. Probably worth making sure they are from the thread-safe version. Hope this helps.


text:
Q: Excel how to sum rows that share a common attribute In Microsoft Excel, I have many rows of data that each start with and ID value. I want to sum all rows that have the same ID value into one row. How do I do this?
Example:
ID Fig1 Fig2 Fig 3
1    5    8    2
1    7    2    6
2    4    7    8
2    5    3    0

becomes...
ID Fig1 Fig2 Fig 3
1   12   10    8
2    9   10    8

A: Using your example data then the sum of Fig 1 for ID = 1 will be:
=SUMIF(A2:A5,1,B2:B5)
i.e. sumif(range to filter by, criteria, range to sum)

A: If you have your source data in Sheet 1 ,use the formula in the other sheet in cell B2,
=SUMIF(Sheet1!$A:$A,$A2,Sheet1!B:B)

This is just one formula that you can drag it to right and then downwards to complete the formula for the entire range. Let me know if you need any help.

A: You can do this using a pivot table.  Drag all the columns you need into rows and then the fields you need to sum in values.  By formatting the report layout as tabular and showing all the row labels, you aggregate the fields into single rows.  When you are done, if you would prefer not to have the pivot table functionality, you can copy and paste as values.


text:
Q: Is the runtime complexity of the Unbounded Knapsack problem really O(n×W)? Given a knapsack weight W and a set of n items each with certain value value_i and weight w_i, we need to calculate the maximum value we can get from the items with total weight ≤ W. This is different from classical Knapsack problem, here we are allowed to use unlimited number of instances of an item (adapted from [1]).
There is a standard solution for this problem using dynamic programming: instead of creating a function f: CurrentWeight -> MaxRemainingValue, we create a function g: (CurrentWeight, CurrentItem) -> MaxRemainingValue that iterates through each item. This way we avoid cycles in the implicit graph formed by g, and then we can use dynamic programming. One standard implementation of such function can be seen here in C++:
#include<iostream>
#include<vector>
#include <chrono>
#define INF (int)1e8
using namespace std;
using namespace std::chrono;

const int MAX_WEIGHT = 10000;
const int N_ITEMS = 10;

int memo[N_ITEMS][MAX_WEIGHT + 1];
vector<int> weights;
vector<int> values;

void initializeMemo(){
    for(int i = 0; i < N_ITEMS; i++)
        for(int j = 0; j < MAX_WEIGHT + 1; j++)
            memo[i][j] = -1;
}

// return max possible remaining value
int dpUnboundedKnapsack(int currentItem, int currentWeight){
    if(currentItem == N_ITEMS)
        return 0;

    int& ans = memo[currentItem][currentWeight];
    if(ans != -1)
        return ans;

    int n_taken = 0;
    while(true){

        int newWeight = currentWeight + n_taken * weights[currentItem];
        if(newWeight > MAX_WEIGHT)
            break;

        int value = n_taken * values[currentItem];
        ans = max(ans, dpUnboundedKnapsack(currentItem+1, newWeight) + value);

        n_taken++;
    }

    return ans;
}

int main(){
    initializeMemo();

    // weights equal 1
    weights = vector<int>(N_ITEMS, 1);

    // values equal 1, 2, 3, ... N_ITEMS
    values = vector<int>(N_ITEMS);
    for(int i = 0; i < N_ITEMS; i++)
        values[i] = i+1;

    auto start = high_resolution_clock::now();
    cout << dpUnboundedKnapsack(0, 0) << endl;
    auto stop = high_resolution_clock::now();
    auto duration = duration_cast<microseconds>(stop - start);
    cout << duration.count() << endl;

    return 0;
}

This solution transverses a DAG (we never go back an item, so there is no cycles here, all edges are of the form (item, weight) -> (item+1, new_weight) ). Each edge of the DAG is visited at most once. Hence, the time complexity of this algorithm is O(E), with E being the number of edges of the graph. In the worst case scenario, each weight is equal to 1, so each vertex (item, weigth) connects to, on average, other W/2 vertexes. So we have O(E) = O(W·#vertexes) = O(W·W·n) = O(W^2·n). The problem is, everywhere I look on the internet it is said the runtime complexity of this algorithm is O(W·n) because every vertex is calculated only once [1][2][3]. This explanation does not seem to make sense. Also, if that was the case, the algorithm above should not run so slowly. Here is a table of the algorithm runtime × MAX_WEIGHT value (try this for yourself, just have to run the code above):
MAX_WEIGHT    time (microseconds)
       100                   1349
      1000                  45773
     10000                5490555
     20000               21249396
     40000               80694646

We can clearly see a O(W^2) trend for large values of W, as suspected.
Finally, one may ask: this worst case scenario is pretty dull, as you can just take the greatest value for each repeated weight. Indeed, with this simple pre-processing the worst case scenario now becomes the one with weights = [1, 2, 3, 4, ..., n]. In this case there are around O(W^2·log(n) + W·n) edges (see the image below. I tried my best, hope you understand). So the runtime complexity of the algorithm should be O(W^2·log(n) + W·n) instead of O(W·n) as suggested pretty much every where?
Btw, here is the runtime I obtained for the case weights = [1, 2, 3, 4, ..., n]:
MAX_WEIGHT    time (microseconds)
       100                    964
       200                   1340
       400                   2541
       800                   6878
      1000                  10407
     10000                1202582
     20000                5181070
     40000               18761689

[1] https://www.geeksforgeeks.org/unbounded-knapsack-repetition-items-allowed/
[2] https://en.wikipedia.org/wiki/Knapsack_problem#Dynamic_programming_in-advance_algorithm
[3] Why is the knapsack problem pseudo-polynomial?


text:
Q: .NET WEB API WITH ANGULAR : Unable to navigate to websites by reading data from the server I bring data from the server to the client
And in the model I have a url I want to navigate with the url to websites
The problem is, when I click on the link, it redirects me to the page and does not direct me to the site:
enter image description here
For example:
"id": 1,
"name": "Google",
"url": "www.google.com",

By click a link I want to navigate to Google
Model:
export default class Site{
  id: number = -1;
  name: string = '';
  url: string = '';
}

components.ts:
export class AppComponent implements OnInit{
  sites: Site[] = [];

  constructor(private siteService:SiteService, private router: Router) { }

  ngOnInit(): void {
    this.GetSites();
  }

  GetSites() {
    this.siteService.GetSites()
    .subscribe((sites) => {
        this.sites = sites;
      });
  }
}

HTML:

Id: {{item.id}}

Name: {{item.name}}

  {{item.url}}

A: You are currently passing the plain string "item.url" as the URL to the anchor tag. If you want to pass the attribute of your JSON object to the anchor tag, you should include brackets ([]) in order to bind your object attribute to it:
{{item.url}}

Edit after feedback in comments
You should also include the protocol in your url attribute, e.g. changing
"url": "www.google.com",

to
"url": "http://www.google.com",


text:
Q: Открытие другого jframe при нажатии на jbutton Хочу, чтобы при нажатии на jbutton "Test epta" открывалось 2-ое окно. Реализовал вот так, но так не работает )) Подскажите, что не так делаю

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

Есть 1-ое , основное окно:
public gui() {
    initialize();
}

private void initialize() {
    frm = new JFrame();
    frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frm.setIconImage(Toolkit.getDefaultToolkit().getImage(gui.class.getResource("/PFP/drop_logo.png")));
    frm.setResizable(false);
    frm.setTitle("Protector of Fair Play");
    frm.getContentPane().setBackground(Color.WHITE);
    frm.setBounds(100, 100, 350, 169);
    ActionListener actionListener = new mysql();
    frm.getContentPane().setLayout(null);

    JButton TestEpta = new JButton("TEST EPTA");
    TestEpta.setBounds(255, 48, 89, 23);
    TestEpta.addActionListener(new Second());
    frmAnticheat.getContentPane().add(TestEpta);

Есть обработка
 class Second implements ActionListener
 {
 public void actionPerformed(ActionEvent e)
  {

      Servers.frame.setVisible(true);
  }
 }

Есть 2-ое окно
 public class Servers extends JFrame{

JFrame frame;
public static void main(String[] args) throws URISyntaxException {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Servers window = new Servers();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

}
public Servers() throws URISyntaxException {
    initialize();
}
private void initialize() throws URISyntaxException {
     final URI uri = new URI("");
        class OpenUrlAction implements ActionListener {
          @Override public void actionPerformed(ActionEvent e) {
            open(uri);
          }
        }
    frame = new JFrame();
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setTitle("Test Servers");
    frame.setBounds(100, 100, 200, 169);
    frame.setIconImage(Toolkit.getDefaultToolkit().getImage(gui.class.getResource("logo.png")));
    frame.getContentPane().setLayout(null);

    JLabel lblNewLabel_1 = new JLabel("\r\n");
    lblNewLabel_1.setBounds(0, 0, 196, 144);
    lblNewLabel_1.setIcon(new ImageIcon(gui.class.getResource("/2222.png")));
    frame.getContentPane().add(lblNewLabel_1);
}
 private static void open(URI uri) {
        if (Desktop.isDesktopSupported()) {
          try {
            Desktop.getDesktop().browse(uri);

          } catch (IOException e) {  }
        } else {  }
      }
 }

A: Servers.frame.setVisible(true); - ты пытаешься обратиться к классу как к статическому, который на деле таковым не является.
class Second implements ActionListener
 {
 public void actionPerformed(ActionEvent e)
  {
      Servers newFrame = new Servers ();
      newFrame.setVisible(true);
  }
 }


text:
Q: Applications included as part of operating system or not - what's the difference? A question I've been given to study with is this:
Q: Should an operating system include common applications such as web browsers and mail programs or not?
The answer I was given to this question is: Pros: better performance and integration if it is included as part of the OS. Cons: The OS is burdened with additional functionality.
I am clearly lacking understanding of something here, because I don't see what the difference would be. In the end, I don't see what the difference is between making a browser "part of the operating system", or making is separate. I suppose I don't really understand what it means to be "part of the operating system". I don't understand why an OS would be burdened more in one situation that the other.
Any help would be greatly appreciated.
Thanks

A: I'm not sure this is the correct stackexchange for this question, perhaps http://programmers.stackexchange.com
First off, what makes up an "Operating System" is a little bit nebulous, one might argue that the Browser is not "part of" the OS, but merely bundled with it.
For the purposes of this question, I think part of the operating system means it comes out of the box with that app installed (regardless of whether the app is "part of the operating system" in a deeper sense).
The automatic update mechanism, for example, might treat the app as seperate and update it separate from the OS, or even allow it to be uninstalled from the system, but that doesn't change the fact that the machine came with that app.

A: If an application is included in an OS it

*

*is convenient for the average user who doesn't have to choose and install software

*is sometimes inconvenient to remove (like system apps in some mobile OS which you can't unistall easily)

*can be tightly coupled with other application that are included (like browser + pdf viewer or media player) that wouldn't necessarily be available on other systems, increasing its functionality

*probably doesn't need to support other OS and development is concentrated on integration with the OS it is bundled with

*takes up disc/disk space - which was more a problem when OS used to be delivered on floppy disks or CDs and hard disk space was expensive

The main reason to include software probably is to tie the customers to the product. The application maybe is developed by the OS manufacturer or they got paid to include it. There have been lawsuits because of this, which resulted for example in the Windows N editions (without the windows media player) or the web browser choice screen in european versions of the Internet Explorer.


text:
Q: React App, remove debug code from production build I'm creating a React App in npm environment.
In my JS code I have something like this in many JS files:
...
let url = loc.protocol + "//" + loc.hostname + (loc.port ? ":" + loc.port : "") + "/" + baseUrl;
if (DEBUG) {
  url = "http://myTestPlatform.com/webapp";
}
...

When I run my WebApp in my dev environment (using npm start) I want the debug code to be enabled but when I'm creating the production build (using npm build) I would like to remove all debugging code.
How can I do that?
Thanks,
Sebastien

A: In your app.js (or main server file), you can set up your logging middleware before creating any routes, which will only be used if you're not in production. This will be the only time you need to do this.
'use strict'

const express = require('express');
const app = express();
const morgan = require('morgan') // or your logging middleware

if (process.env.NODE_ENV !== 'production') {
  // Logging middleware (non-production only)
  app.use(morgan('dev'));
}

...

module.exports = app;


text:
Q: codeception custom directory structure I am in the process of trying to implement codeception in a fairly large project at the moment and the default flat directory layout that codeception uses is not viable as we will have too much tests squashed into one directory.
Codeception uses the following structure:

tests/
- _data
- _output
- _support
- acceptance
- functional
- unit

We are trying include the tests in our mvc application structure so we could have the following:

application/
-  controllers/
       - folder1/
            - controller1.php
            - test.php
       - folder2/
            - controller2.php
            - test.php
-  views/
      - view1/
            - view1.php
            - test.php
      - view2/
            - view2.php
            - test.php

This way the structure makes it a bit easier to follow for us as otherwise we will end up with 1000s of tests in one folder. I am aware that we can define sub namespaces within the main codeception.yml however it still uses the same flat directory layout which we don't want to use.
What would a codeception bootstrap look like to get it to look into the top level folder and just run any test within directories below it and include it in the main runner?

A: I would recommend NOT to include the tests into your application business code, because they simply offer no functionality to you app. Tests should always be in their own scope.
You find the default codeception structure confusing with a larger amounts of tests. I ran into the same problem, but for the solution you have to remember one thing: You're not bound to the structure:

*

*acceptance

*functional

*unit

You can create as many test suites as it suits your need (the defaults are only suggestions). Feel also free to mix unit and functional test in one suite. I ended up creating many small suites for the different cases i want to test:

*

*suite1/

*

*controllertest1.php

*viewtest1.php

*suite2/

*

*controllertest2.php

*viewtest2.php
If this suites end up to small I would put the tests for 1 module of your application into 1 suite. Don't forget to name the testcases with expressive names. It make your life a lot easier.

Simply create a new suite with ./codecept g:suite suite1
http://codeception.com/docs/reference/Commands#GenerateSuite


text:
Q: Connection Time out when accessing MWAA UI I created MWAA environment on the main default VPC where every service is running .I used the (private network) option to access the webserver. When accessing the airflow UI using my user the connection times-out and the site is not reached. The user have MWAA full access and access to the VPC
I added the MWAA ENVIROMENT to the main default VPC  to avoid two VPC pairing but I am afraid that's the reason for the error.


text:
Q: Handling empty results on findAll(): Is there a orElseThrow() for lists? I am creating a little Spring REST service. I have a findById() call:
@GetMapping("/items/{id}")
MyItem one(@PathVariable String id) {
    return repository.findById(id).orElseThrow(() -> new MyItemNotFoundException(id));
}

If there is no MyItem object with the given id, I am throwing an exception using the Optional<T>.orElseThrow() method. This is very useful and quite simple.
Now I added a findAll() call from the PagingAndSorting<T, ID> repository:
@GetMapping("/items")
List<MyItem> all() {
    return repository.findAll();
}

Is there a simple way to handle empty list outputs in a similar way as it can be done with single items? Or do I need to create something like:
@GetMapping("/items")
List<MyItem> all() {
    List<MyItem> items = repository.findAll();
    if  (items.isEmpty())
        throw new MyItemNotFoundException();

    return items;
}

(The real use case handles some request parameters to filter the whole list)

A: The reasoning behind the Optional in findById is that it avoids returning a null.
Empty collections on the other hand are safe to iterate and handle, so there's no special .throwIfEmpty() mechanism built-in. An empty collection is essentially an Optional in itself. It's not null, and may or may not contain elements.
If in your business logic no results means error, then it's up to you to handle it.

A: You could stream the list, get an Optional with findAny and map back to the list if the result is non-empty:
items.stream().findAny().map((e) -> items).orElseThrow(NotFoundException::new);

But you should consider if this really needs to result in an Exception. My expectation as consumer of a search function would be an empty result, of no element matches my criteria.

A: The solution could be a utility fuction wrapping the findAll call.
public class MyItemNotFoundException ... {
    public static <T> List<T> requireNotEmpty(List<T> items) throws MyItemNotFoundException {
        if (items.isEmpty()) {
            throw new MyItemNotFoundException();
        }
        return items;
    }
}

@GetMapping("/items")
List<MyItem> all() {
    return MyItemNotFoundException.requireNotEmpty(repository.findAll());
}

Placing the function in the MyItemNotFoundException is not very readable.
A better name still feels artificial:
    return MyItemNotFoundException.whenEmpty(repository.findAll());

But you'll find a place, maybe in some base class/interface.
(In some systems the repository findAll may return null (very ugly), and with such a wrapping function that can be dealt with too.)

A: By REST this is what you should return:

*

*Single element not found: throw an exception - 404 response code mapped

*Empty list: return empty list with - 200 status code


text:
Q: EVE Online - questions about station trading I've got an alt that's engaged solely in station trade, I had a few questions maybe some other more experienced traders could answer:

*

*Do you put all the money in your possession into buy orders, or do you leave a little in your wallet? My plan was to have this alt generating income with which to fund other activities, but I can see that I'm not making the most of my ISK. What do you do with your money?

*Is there any way to be notified of which orders have been completely filled? Would I need to rely on an external application to do so? I ask because I've run into times where I fill up my buy orders with stuff, but I don't remember the exact quantities that I'd set so when I get back, I see lots of goods in my hangar but no buy order. It'd be great if I had some way to refer both to the quantity set in the original order as well as the price (aside from the in-game transaction journal)

A: *

*Yes! The more ISK you have tied up in Buy orders (which should be a combination of high-quantity+low-price orders and low-quantity+high-price orders), the faster you'll be acquiring the goods you need.  Having lots of input goods should mean you can then use those to create a lot of large Sell orders.  Which is what will generate all the sweet iskies.

*EveMon will do this (and much more!) for you.  There's a tab that notifies you of recent changes in your buy and sell orders.  The notification type changes based on whether the order was partially or completely filled.  Much easier to read than the transaction journal.


text:
Q: RowEditing is fired when update button is clicked in GridView I have created a GridView as below:
protected void Page_Load(object sender, EventArgs e)
{
    GridView gv = new GridView();
    gv.ID = pId.ToString();
    gv.AutoGenerateEditButton = true;
    gv.DataKeyNames = ids;
    gv.RowEditing += gv_RowEditing;
    gv.RowUpdating += gv_RowUpdating;
    bindGv(pId, gv);
}

I have also written the following methods:-
RowUpdating:
void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    GridView gv = sender as GridView;
    GridViewRow row = (GridViewRow)gv.Rows[e.RowIndex];
    ProductCategory pc = context.ProductCategories.First(s => s.Name ==gv.ID );
    TextBox txtName = row.FindControl("txtName") as TextBox;
    pc.Name = txtName.Text;
}

RowEditing:
void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridView gv = sender as GridView;
    gv.EditIndex = e.NewEditIndex;
    bindGv(Convert.ToInt32(gv.ID), gv);
}

But when I ran the codes in debugging mode, clicking on the update button invokes gv_RowEditing method instead of gv_RowUpdating. What is the problem?

A: The Sequence of firing the events of gridview when you click on edit button to update any record it calls rowediting event and after that when you click on update button it calls rowupdating event.
rowediting event always invokes first then rowupdating.


text:
Q: What's the current status of the Casimir force $\leftrightarrow$ vacuum energy controversy? Most textbooks explain the Casimir force by using the infinitely large ground state energy associated with quantum fields. Since the total energy between two conducting plates is different from the total outside of the plates, there is a net energy difference and thus a force acting on them. This force is known as Casimir force and was observed in experiments. The effect therefore seems to confirm that the ground state energy of quantum fields is nonzero and leads to measurable effects.
On the other hand, it's sometimes argued that the Casimir force "is just the van der Waals force derived in a different language." In particular:

Conceptually, saying that "the plates force the electric field to vanish" is the same as saying "electronic fluctuations in the two plates become synchronized", which is how we describe the origin of the van der Waals force.

Moreover, this highly cited paper concludes that

Still, no known phenomenon, including the Casimir effect, demonstrates that zero point energies are "real".

What's the exact relationship between the two explanations? Is one of them wrong or is the standard derivation in terms of ground state energies really just a derivation of the van der Waals force in disguise?


text:
Q: Simple speech recognition from scratch The most alike question I found related to my question is this (simple speech recognition methods) but since had passed 3 years and the answers are not enough I will ask.
I want to compute, from scratch, a simple speech recognition system, I only need to recognize five words.
As much as I know, the more used audio features for this application are the MFCC, and HMM for classification.
I'm able to extract the MFCC from audio but I still have some doubts about how to use the features for generating a model with HMM and then perform classification.
As I understand, I have to perform vector quantization. First I need to have a bunch of MFCC vectors, then apply a clustering algorithm to get centroids. Then, use the centroids to perform vector quantization, this means that I have to compare every MFCC vector and label it with the name of the centroid most alike.
Then, the centroids are the 'observable symbols' in the HMM. I have to introduce words to the training algorithm and create a HMM model for each word. Then, given an audio query I compare with all models and I say is the word with the highest probability.
First of all, is this procedure correct? Then, how do I deal with different sized words. I mean, If I have trained words of 500ms and 300ms, how many observable symbols do I introduce to compare with all the models?
Note: I don't want to use sphinx, android API, microsoft API or other library.
Note2: I would appreciate if you share more recent information for better techniques.

A:
First of all, is this procedure correct?

The vector quantization part is ok, but it's rarely used these days. You describe so-called discrete HMMs which nobody uses for speech. If you want continuous HMMs with GMM as probability distribution for emissions you don't need vector quantization.
Then, you focused on less important steps like MFCC extraction but skipped most important parts like HMM training with Baum-Welch and HMM decoding with Viterbi which are way more complex part of the training than initial estimation of the states with vector quantization.

Then, how do I deal with different sized words. I mean, If I have trained words of 500ms and 300ms, how many observable symbols do I introduce to compare with all the models?

If you decode speech you usually select the symbols which correspond to parts phonemes perceived by the human. Its traditional to take 3 symbols per phoneme. For example word "one" should have 9 states for 3 phonemes and word "seven" should have 15 states for 5 phonemes. This practice is proven to be effective. Of course you can vary this estimation slightly.


text:
Q: Generating PDF from a third-party HTML on java I'm trying to generate a PDF version of a third-party HTML (actually it is an HTM file). This HTML may change in future and I have absolutely no control over it. All I wanna do is convert it to a PDF.
I already tried 2 solutions: iText (with XmlWorker) and Flying-Saucer, but no success so far.
My problem is that the HTML file is very out of default patterns. Examples:
    <link rel=File-List href="040602_inds_files/filelist.xml">

    <meta http-equiv=Content-Type content="text/html; charset=windows-1252">

The first one has no close tag (iText crashes) and the second one has no double quotes on 'http-equiv' value (Flying-Saucer crashes).
I have found a lot of posts about this issue, but all of them are handling their own HTML, so they can fix it and try again. But i can't do this.
This is the page I'm trying to convert.
Here is my iText convert method:
        public static void convert(PdfWriter writer, Document document, String siteUrl) throws MalformedURLException, IOException {
            XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                    new BufferedReader(new InputStreamReader(new URL(siteUrl).openStream())));
        }

And here is my Flying-Saucer convert method:
        public static void convertFS(String siteUrl, String fileName) throws com.lowagie.text.DocumentException, IOException {
            OutputStream os = new FileOutputStream(fileName);
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocument(siteUrl);
            renderer.layout();
            renderer.createPDF(os);

            os.close();
        }

Any tips? I accept other libs if they are decently usable. Thx in advance.

A: You can first parse HTML file by jsoup and then convert content to a standard HTML file, finally you can use iText to generate PDF


text:
Q: Why JQuery library of append method is not working on partial AngularJS? This library is working fine in index file, but when I use it on a partial, it is not working. Here is my partial code:

This is another paragraph.

List item 1

List item 2

List item 3

    <button id="btn1">Append text</button>
    <button id="btn2">Append list item</button>

A: Try:
var app = angular.module('firstApp', []);

app.controller('myCtrl', function($scope) {
    $scope.appendText = function(text) {
        angular.element(document.querySelectorAll("p")).append(text);
    };
    $scope.appendListElement = function(listElement) {
        angular.element(document.querySelectorAll("ol")).append('
' + listElement + '
');
    };
});

HMTL:

This is another paragraph.

List item 1

List item 2

List item 3

        <button id="btn1" ng-click="appendText('some Text')">Append text</button>
        <button id="btn2" ng-click="appendListElement('some element')">Append list item</button>

Working Plunker: http://plnkr.co/edit/CbudpwhIngYHkMxoqiC2?p=preview


text:
Q: SOLID vs. Avoiding Premature Abstraction I understand what SOLID is supposed to accomplish and use it regularly in situations where modularity is important and its goals are clearly useful.  However, two things prevent me from applying it consistently across my codebase:

*

*I want to avoid premature abstraction.  In my experience drawing abstraction lines without concrete use cases (the kind that exist now or in the foreseeable future) leads to them being drawn in the wrong places.  When I try to modify such code, the abstraction lines get in the way rather than helping.  Therefore, I tend to err on the side of not drawing any abstraction lines until I have a good idea of where they would be useful.

*I find it hard to justify increasing modularity for its own sake if it makes my code more verbose, harder to understand, etc. and doesn't eliminate any duplication.  I find simple, tightly coupled procedural or God object code is sometimes easier to understand than very well-factored ravioli code because the flow is simple and linear.  It's also much easier to write.
On the other hand, this mindset often leads to God objects.  I generally refactor these conservatively, adding clear abstraction lines only when I see clear patterns emerging.  What, if anything, is wrong with God objects and tightly coupled code if you don't clearly need more modularity, don't have significant duplication and the code is readable?
EDIT:  As far as individual SOLID principles, I meant to emphasize that Liskov Substitution is IMHO a formalization of common sense and should be applied everywhere, since abstractions make no sense if it isn't.  Also, every class should have a single responsibility at some level of abstraction, though it may be a very high level with the implementation details all crammed into one huge 2,000 line class.  Basically, your abstractions should make sense where you choose to abstract.  The principles I question in cases where modularity isn't clearly useful are open-closed, interface segregation and especially dependency inversion, since these are about modularity, not just having abstractions make sense.

A: The following are simple principles you can apply to helping you understand how to balance your system design:

*

*Single Responsibility Principle: the S in SOLID.  You can have a very large object in terms of number of methods or the amount of data and still be upholding this principle.  Take for instance the Ruby String object.  This object has more methods than you can shake a stick at, but it still only has one responsibility: hold a string of text for the application.  As soon as your object starts to take on a new responsibility, start thinking hard about that.  The maintenance issue is asking yourself "where would I expect to find this code if I had problems with it later?"

*Simplicity counts: Albert Einstein said "Make everything as simple as possible, but not simpler."  Do you really need that new method?  Can you accomplish what you need with the existing functionality?  If you really think there needs to be a new method, can you change an existing method to satisfy all of what you need?  In essence refactor as you build new stuff.

In essence you are trying to do what you can to not shoot yourself in the foot when it comes time to maintain the software.  If your large objects are reasonable abstractions, then there is little reason to split them up just because someone came up with a metric that says a class should be no more than X lines/methods/properties/etc.  If anything, those are guidelines and not hard and fast rules.

A: I think for the most part you have answered your own question. SOLID is set of guidelines on how to refactor your code, when concepts needs to be move up levels of abstractions.
Like all other creative disciplines there are no absolutes - just tradeoffs. The more you do it the "easier" it becomes to decide when is enough for your current problem domain or requirements.
Having said that - abstracting is the heart of software development - so if there is no good reason not to do it, then practice will make you better at it, and you will get a gut feel for the tradeoffs. So favor it unless it becomes detrimental.

A: I want to avoid premature abstraction.In my experience drawing abstraction lines without concrete use cases...

This is partially right and partially wrong.
Wrong  This is not a reason to prevent one from applying OO principles/SOLID.  It only prevents applying them too early.
Which is...
Right  Do not refactor code until it is refactorable; when it is requirements complete.  Or, when the "use cases" are all there as you say.
I find simple, tightly coupled procedural or God object code is sometimes easier to understand than very well-factored...

When working alone or in a silo
The problem with not doing OO isn't immediately obvious.  After you write the first version of a program:

Code is fresh in your head
Code is familiar
Code is easy to mentally compartmentalize
You wrote it

3/4 of these good things quickly die over a short time.
Finally, you recognize that you have God objects (Objects with many functions), so you  recognize individual functions.  Encapsulate.  Put them in folders.  Use interfaces once in a while.  Do yourself a favor for long term maintenance.  Especially since non-refactored methods tend to bloat infinitely and become God methods.
In a team
The problems with not doing OO are immediately noticeable.  Good OO code is at least somewhat self-documenting and readable.  Especially when combined with good green code. Also, lack of structure makes it difficult to separate tasks and integration much more complex.

A: There's nothing wrong with large objects and tightly coupled code when they're appropriate and when nothing better-engineered is required.  This is just another manifestation of a rule of thumb turning into dogma.
Loose coupling and small, simple objects tend to provide specific benefits in a lot of common cases, so it's a good idea to use them, in general.  The problem lies in people who don't understand the rationale behind the principles blindly trying to apply them universally, even where they don't apply.

A: I tend to approach this more from the You Ain't Gonna Need It standpoint. This post will focus on one item in particular: inheritance.
In my initial design I create a hierarchy of things I know there will be two or more of. Chances are they will need much of the same code, so it's worth designing that it from the start. After the initial code is in place, and I need to add more features/functionality, I look at what I have and think, "Does something I have already implement the same or similiar function?" If so, that's most likely a new abstraction begging to be released.
A good example of this is an MVC framework. Starting from scratch, you create one big page with a code behind. But then you want to add another page. However, the one code behind already implements a lot of the logic the new page requires. So, you abstract out a Controller class/interface that will implement the logic specific to that page, leaving the common stuff in the original "god" code-behind.

A: If YOU know as a developer when to NOT apply the principles because of the future of the code, then good for you.
I hope SOLID remains in the back of your mind to know when things do need to be abstracted to avoid complexity and improve the quality of the code if it's beginning to degrade in the values you stated.
More importantly though, consider that the majority of developers are doing the day job and don't care as much as you. If you initially set out long running methods, what are the other developers that come in to the code going to think when they come to maintain it or extend it?... Yes, you guessed, BIGGER functions, LONGER running classes, and MORE god objects, and they don't have the principles in mind to be able to catch the growing code and correctly encapsulate it. You're "readable" code now becomes a rotting mess.
So you may argue that a bad developer is going to do that regardless, but at least you have a better advantage if things are kept simple and well organised from the start.
I don't particularly mind a global "Registry Map" or a "God Object" if they're simple. It really depends on the system design, sometimes you can get away with it and remain simple, sometimes you can't.
Let us also not forget that large functions and God Objects can prove extremely difficult to test. If you want to remain Agile and feel "Safe" when re-factoring and changing code, you need tests. Tests are difficult to write when functions or objects do many things.

A: I use a simpler guideline: if you can write unit tests for it, and have no code duplication, it's abstract enough.  Plus, you're in a good position for later refactoring.
Beyond that, you should keep SOLID in mind, but more as a guideline than a rule.

A: The problem with a god object is that you can usually profitably break it into pieces. By definition, it does more than one thing. The whole purpose of breaking it into smaller classes is so that you can have a class that does one thing well (and you shouldn't stretch the definition of "one thing" either). This means that, for any given class, once you know the one thing it's supposed to do, you should be able to read it fairly easily and say whether or not it's doing that one thing correctly.
I think there is such a thing as having too much modularity, and too much flexibility, but that's more of an over-design and over-engineering problem, where you're accounting for requirements that you don't even know the customer wants. A lot of design ideas are oriented around making it easy to control changes to how the code is run, but if nobody expects the change, then it's pointless to include the flexibility.

A: I share your concerns about excessive and inappropriate abstraction, but I'm not necessarily so concerned about premature abstraction.
That probably sounds like a contradiction, but using an abstraction is unlikely to cause a problem so long as you don't overcommit to it too early - ie as long as you are willing and able to refactor if necessary.
What this implies is some degree of prototyping, experimentation and backtracking in the code.
That said, there's no simple deterministic rule to follow that will solve all problems. Experience counts for a lot, but you have to gain that experience by making mistakes. And there's always more mistakes to make that previous mistakes won't have prepared you for.
Even so, treat the textbook principles as a starting point, then learn programming lots and seeing how those principles work out. If it were possible to give better, more precise and reliable guidelines than things like SOLID, someone would probably have done so now - and even if they had, those improved principles would still be imperfect, and people would be asking about the limitations in those.
Good job too - if anyone could provide a clear, deterministic algorithm for designing and coding programs, there'd only be one last program for humans to write - the program that would automatically write all future programs without human intervention.

A:
What, if anything, is wrong with God objects and tightly coupled code if you don't clearly need more modularity, don't have significant duplication and the code is readable?

If the application is small enough, anything is maintainable.  In larger applications, God objects quickly become a problem.  Eventually implementing a new feature requires modifying 17 God objects.  People don't do very well following 17-step procedures.  The God objects are constantly being modified by multiple developers, and those changes have to be merged repeatedly.  You don't want to go there.

A: Drawing the appropriate abstraction lines is something one draws from experience.  You will make mistakes in doing so that is undeniable.
SOLID is a concentrated form of that experience that is handed to you by people who gained this experience the hard way.  You pretty much nailed it when you say you would refrain from creating abstraction before you see a need for it.  Well the experience SOLID provides you will help you solve problems you never new existed. But trust me... there are very real.
SOLID is about modularity, modularity is about maintainability, and maintainability is about allowing you to keep a humane work schedule once the software reach production and client start noticing bugs you have not.
The biggest benefit of modularity is testability.  The more modular your system is the easier it is to test and the faster you can build solid foundations to get on with the harder aspects of your problem.  So your problem may not demand this modularity but just the fact it will allow you to create better testing code faster is a no brainer to strive for modularity.
Being agile is all about attempting to strike the delicate balance between shipping fast and providing good quality.  Agile does not mean that we should cut corner, in fact, the most successful agile projects I have been involved with are the ones that paid close attention to such guidelines.

A: An important point that seems to have been overlooked is that SOLID is practiced along with TDD. TDD tends to highlight what is "appropriate" in your particular context and help alleviate a lot of the equivocation that appears to be in the advice.


text:
Q: Running shell commands from a specific directory Ruby seems to use /bin/sh as the shell interpreter, which on a *nix machine doesn't understand /bin/bash commands such as pushd.  This is what irb tells me:
1.9.3-p327 :011 > `pushd /tmp; echo foo`
sh: 1: pushd: not found
=> "foo\n"

On OSX, /bin/sh is an alias for bash, so the above snippet runs fine there. Is there a way to force Ruby on a *nix machine to use /bin/bash for interpreting shell commands?

A: Using Bash commands like pushd in Ruby is pointless, because those commands affect Bash's internal state of the Bash interpreter, and when you Run a shell command from Ruby using backticks or system, it creates a new subprocess, runs the command, and then closes that subprocess.
That means that even if you somehow manage to run pushd as a Bash command from Ruby, what will happen is that the the Bash subprocess will start, push the directory to the directory stack, and then exit. The changes you've made to the directory stack will be erased with all the other subprocess' data - and the next time you use a shell command you won't be at that directory.
You are scripting in Ruby, not in Bash - internal Bash commands have no meaning here, so you need to use the Ruby equivalents. For example, instead of writing:
system 'pushd /tmp'
system 'touch file_in_tmp'
system 'popd'

Which wouldn't work, what you want to do is:
Dir.chdir '/tmp' do
    system 'touch file_in_tmp'
end

A: /bin/sh is hardcoded in the ruby source. So there is no way to change the default shell. You could use one of the other suggested approaches.

A: Do
Dir.chdir("/bin")

and then do your commands:
`pushd /tmp; echo foo`


text:
Q: How can I access each element of a list of input matrices on a shiny server? I am trying to access output values inside the server on my shiny app.
The values are inputed by the user in a loop: depending on the number 'n_matrizes', the user inputs 'n_matrizes' number of matrices. The server then collects all these matrices in a list, using lapply:
lapply(1:(n_matrizes()),function(i){
             matrixInput(inputId = paste0("W_",i),
                         label = paste("Matriz espacial de ordem", i),
                         value = matrix(0,nrow=n_radares(),ncol=n_radares()))})

In the server, I need to access each of these matrices on the list. I've tried using reactive and reactiveValues but since I'm new to this programming, I haven't succeeded.
On normal R coding, I have done this before:
To create the list of matrices:
w_1 <- matrix(1,nrow=4,ncol=4)
w_2 <- matrix(2,nrow=4,ncol=4
w_3 <- matrix(3,nrow=4,ncol=4
W <- list(w_1,w_2,w_3)

To access one of them:
W[[1]]

How do I do that on the shiny server?

A: You can access any input element within the server using it's inputId. If the inputId is a combination of strings and numbers you already know to use paste(). Let us say you have a list of widgets with a name pattern W_1, W_2, W_3 ... you can access them easily with input[[paste0("W_", 1L)]]. Of course, you can replace the number by any integer variable.
From your sample I assume that you have a function that creates several instances of inputMatrix. Your code also suggests that when I call that function repeatedly, I get multiple instances with the same inputId W_1, W_2, .... That will cause an error. Make sure your inputIds are unique.


text:
Q: Error when converting JSON to Dataset in C# I'm using JSON.Net to retrieve the following JSON formatted data.

{"Pagination":{"CurrentPage":1,"PageSize":20,"NumberOfPages":3796,"totalCount":75913},"Data":[{"SalesOrderNumber":"003119"},{"SalesOrderNumber":"003336"},{"SalesOrderNumber":"003410"},{"SalesOrderNumber":"003520"}]}

I can successfully retrieve the data and load it into a C# textbox.  What I want to do is load it into a dataset.  I'm using the following statement to try and load the dataset.
DataSet dsSalesOrders = JsonConvert.DeserializeObject<DataSet>(response.Content);

When I run the program I get the following error

Newtonsoft.Json.JsonSerializationException: 'Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path 'Pagination', line 1, position 15.'

As this is my first time using JSON how do I fix this??
Thanks

A: Try with this class as receiving class
public class YourMainObject
{
    public Pagination Pagination { get; set; }
    public Datum[] Data { get; set; }
}

public class Pagination
{
    public int CurrentPage { get; set; }
    public int PageSize { get; set; }
    public int NumberOfPages { get; set; }
    public int totalCount { get; set; }
}

public class Datum
{
    public string SalesOrderNumber { get; set; }
}

and deserialize to this, then populate the dataset separately.
PS: On the discussion below, fellow programmers are suggesting that you might not really need to use a DataSet

A: Liquid Core
Thanks for the class definitions, that is what I was looking for.
As for the discussion of my dataset comment, they are correct I don't need a dataset.  I mostly work with SQL data so I'm used to using datasets in WinForms projects for presenting my data.  Once I got my Dataum class loaded I just assigned the datasource to the array.


text:
Q: Can we do Hideandshow for an entire class using react native In my App.js I have two classes. So, when I click on add button in one class then the second classes view should be displayed by hiding the first classes view.

A: If you are talking about classes then you can do it like this:

  const Foo = () => {
     const [showClass, setShowClass] = useState(false);
     return (

              Only show after click

              Show when not clicked

          <button onClick={() => setShowClass(true)}>Click me</button>

     )
  };

However in react the convention is to not use classes but instead do conditional rendering:
  const Foo = () => {
     const [showElement, setShowElement] = useState(false);
     return (

          {
            showElement ?

                  Only show after click

            :

                  Show when not clicked

          }

          <button onClick={() => setShowElement(true)}>Click me</button>

     )
  };


text:
Q: Cordova App shows "Connection Type Unknown" while wifi is on Hey I am trying to check my network state on cordova. When my state is   4g, 3g, No Network my app gives the correct alert however on wifi it says connection unknown.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="format-detection" content="telephone-no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, minimum-scale=1, maximum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi">
    <title>Our Application</title>
    <link rel="stylesheet" href="css/themes/default/jquery.mobile-1.3.2.css">
    <link rel="stylesheet" href="css/main.css">

interestingly I've tried full example given on API documentation (even though my code is almost same as the example )
http://cordova.apache.org/docs/en/3.1.0/cordova_connection_connection.md.html#Connection
same error happens here too.
just in case I am sharing my device information too.
My Phone : Sony Xperia Z
Model : C6603
Android Version : 4.2.2
Compile Number : 10.31.A.2.67


text:
Q: Copy black pixels from image and paste in same image with offset I've been trying to get some masking to work in my pictures, but I guess there has to be an easier way to do this:
a) I have an BW picture (photo) showing numbers from a display, "test.png" ( 1000x300 px)
b) I want to copy (only) the black pixels and paste them in the same image
c) When pasting, I want the paste to be offset by its "original" place by 20px (both x/y)
I try running the code below but get an error:
import cv2
test = Image.open('test.png')
np = Image.new('1', (1000, 300), 255)
mask = np.bitwise_and(test, np.roll(test, 20, (0,1)))
mask.save('mask.png')

I get AttributeError: 'Image' object has no attribute 'bitwise_and'

A: If image is logical (0/1) then:
res=np.bitwise_and(image, np.roll(image, 20, (0,1)))

A: You can do it like this:
from PIL import Image
import numpy as np

# Load image and make Numpy array
im = Image.open('image.png').convert('L')
na = np.array(im)

# Get x,y coordinates of black pixels
Y, X = np.where(na==0)

# Make pixels 30 across and 30 down from them black
na[Y+30, X+30] = 0

# Convert back to PIL Image and save
Image.fromarray(na).save('result.png')


text:
Q: Referring To MessageBox VB.NET I'm writing a program that kids can use to code from within my application instead of a console-based approach
So I have a lesson that teaches them about message boxes, they are given a sample line of code and what it creates and are told to create their own by entering code into a textbox to create their own that says "Hey Dude!", the problem is, I'm having trouble getting the system to check if what they entered was correct or not... eg:
Private Sub btnShowMsgBox_Click(sender As Object, e As EventArgs) Handles btnShowMsgBox.Click
        If txtUserInput.Text = MessageBox.Show("I can code!") Then
            MessageBox.Show("I can code!")
        Else
            MessageBox.Show("That's not quite right, try again!")
        End If

I've tried adding " " around the relevent code on the first line of the if statement but no joy, as well as trying a variable approach
So basically the problem is the program is getting confused and doesn't understand why I'm checking to see if code for a message box is present, the syntax of the messagebox code doesn't fit well either
Does anyone have any suggestions as to how I would get this working? The logic is so straightforward but it's driving me nuts!
Thanks a million in advance

A: I believe you want the code to look more like...
Private Sub btnShowMsgBox_Click(sender As Object, e As EventArgs) Handles btnShowMsgBox.Click
    If txtUserInput.Text = "MessageBox.Show(""I can code!"")" Then
        MessageBox.Show("I can code!")
    Else
        MessageBox.Show("That's not quite right, try again!")
    End If

The double quotes will return as single quotes within the string between the single quotes.


text:
Q: How to convert a synchronous function to an asynchronous function in python using callbacks? I'm using the tornado framework and all of my functions have been written synchronously. How would I make these async?
class AuthLoginHandler(BaseHandler):
    @tornado.web.asynchronous
    def get(self):

        self.render("login.html")

    def post(self):
        username = self.get_argument("UserName",strip = True)
        password = self.get_argument("Password",strip = True)
        user = auth_actions.login(username,password)
        if not user:
            self.redirect("/auth/login")
            return

        #user = user_actions.get_my_data(self.db,user['_id'])

        self.set_secure_cookie("userdata", tornado.escape.json_encode(dumps(user.to_mongo())))
        self.redirect("/")

def login(username,password,callback=None):
    m = hashlib.md5()
    m.update(password)
    hashed = m.hexdigest()
    login = User.objects(UserName=username.lower(),Password=hashed).exclude("Password","Wall","FriendsRequested","Friends","FriendsRequesting")
    if login.first() is None:
        login = User.objects(Email=username.lower(),Password=hashed).exclude("Password","Wall","FriendsRequested","Friends","FriendsRequesting")
        if login.first() is None:
            return None
    logger.info(username + " has logged in")
    if callback != None:
        return callback(login.first())

    return login.first()

A: As andy boot mentions, you are going to need a separate thread. The code below uses the generator-coroutine approach from tornado-gen.
Also note the run_async decorator that wraps your function up in its own thread.
import tornado.ioloop
import tornado.web
import tornado.gen
import time
from threading import Thread
from functools import wraps

def run_async(func):
  @wraps(func)
  def async_func(*args, **kwargs):
    func_hl = Thread(target = func, args = args, kwargs = kwargs)
    func_hl.start()
    return func_hl

  return async_func

@run_async
def login(username,password,callback=None):
  m = hashlib.md5()
  m.update(password)
  hashed = m.hexdigest()
  login = User.objects(UserName=username.lower(),Password=hashed).exclude("Password","Wall","FriendsRequested","Friends","FriendsRequesting")
  if login.first() is None:
    login = User.objects(Email=username.lower(),Password=hashed).exclude("Password","Wall","FriendsRequested","Friends","FriendsRequesting")
    if login.first() is None:
      return None
  logger.info(username + " has logged in")
  if callback != None:
    return callback(login.first())
  return login.first()

class AuthLoginHandler(BaseHandler):
  @tornado.web.asynchronous
  def get(self):
    self.render("login.html")

  @tornado.web.asynchronous
  @tornado.gen.coroutine
  def post(self):
    username = self.get_argument("UserName",strip = True)
    password = self.get_argument("Password",strip = True)
    user = yield tornado.gen.Task(auth_actions.login, username, password)
    if not user:
      self.redirect("/auth/login")
      return
    self.set_secure_cookie("userdata", tornado.escape.json_encode(dumps(user.to_mongo())))
    self.redirect("/")

A: If you are going to be hashing passwords you are best of doing it in a separate thread. This is because a hash takes a long time to execute and will block the main thread.
Here is an example of hashing on a separate thread
Note that Tornado's maintainer Ben Darnell recommends using a separate thread to do password hashes: see this google group.


text:
Q: MongoDB search using $in array not working I'm using MongoDB shell version: 2.4.8, and would simply like to know why a nested array search doesn't work quite as expected.
Assume we have 2 document collections, (a) Users:
{
    "_id" : ObjectId("u1"),
    "username" : "user1",
    "org_ids" : [
        ObjectId("o1"),
        ObjectId("o2")
    ]
}
{
    "_id" : ObjectId("u2"),
    "username" : "user2",
    "org_ids" : [
        ObjectId("o1")
    ]
}

and (b) Organisations:
{
    "_id" : ObjectId("o1"),
    "name" : "Org 1"
}
{
    "_id" : "ObjectId("o2"),
    "name" : "Org 2"
}

Collections have indexes defined for
Users._id, Users.org_id, Organisations._id

I would like to find all Organisations a specific user is a member of.
I've tried this:
> myUser = db.Users.find( { _id: ObjectId("u1") })
> db.Organisations.find( { _id : { $in : [myUser.org_ids] }})

yet it yields nothing as a result.  I've also tried this:
> myUser = db.Users.find( { _id: ObjectId("u1") })
> db.Organisations.find( { _id : { $in : myUser.org_ids }})

but it outputs the error:
error: { "$err" : "invalid query", "code" : 12580 }

(which basically says you need to pass $in an array) ... but that's what I thought I was doing originally ?  baffled.
Any ideas what I'm doing wrong?

A: db.collection.find() returns a cursor - according to documentation. Then myUser.org_ids is undefined, but $in field must be an array. Let's see the solution!

_id is unique in a collection. So you can do findOne:
myUser = db.Users.findOne( { _id: ObjectId("u1") })
db.Organisations.find( { _id : { $in : myUser.org_ids }})

If you are searching for a non-unique field you can use toArray:
myUsers = db.Users.find( { username: /^user/ }).toArray()

Then myUsers will be an array of objects matching to the query.


text:
Q: Is it possible to specify a --prefix alike option when using yum to install? yum install subversion

Scripts like the above has no control of where software will be installed.
How can I specify the installation path like --prefix when installing from source?

A: No, it is not.

A: What are you trying to do? In general you can't alter where individual packages dump their files.
You can make yum install/update a different root directory by using --installroot, which is useful for working with e.g. chroot environments.


text:
Q: play framewoerk & scala Future(s) chain. make it more pretty I use WSClient to make rest requests. Each request return some Future.
as result I need to make request 1 and get some data. Then I need to make request 2 with data from result of request 1. Then I need to make request 3 with data from result of request 2. and so on
in my code it's looks like
def wsChain(data: Data): Future[NewData] = {
    getOne(data).flatMap(data2 => {
      getTwo(data2).flatMap(data3 => {
        getThree(data3).flatMap(data4 => {
          getFour(data4).map(result => foo(result))
        })
      })
    })
  }

It's very primitive sample without any modification of responses and requests. but I think that even it is difficult to read.
I now about Await for Future, but it's anti-pattern
May be I can do this more pretty? Without N inner functions.

A: This is precisely the kind of situation that Scala's for-comprehensions are designed to help. You can replace your code with the following:
def wsChain(data: Data): Future[NewData] = for {
  data2  <- getOne(data)
  data3  <- getTwo(data2)
  data4  <- getThree(data3)
  result <- getFour(data4)
} yield foo(result)

…and it will be desugared by the compiler to exactly the same thing. You can read more about for-comprehensions here, but in short, any time you find yourself with a long chain of flatMap calls (and maybe a map at the end), you should consider rewriting them as a for-comprehension, which makes your code more readable by collapsing the deep nesting.


text: Q: Embedding Metadata in a File(Visual C++) I have written a simple MFC text editor in Visual C++ and I was wondering how I might go about embedding metadata into a file. For eg. author, date of creation, etc. Don't need you to tell me step by step, just need you to guide me in the right direction. Thanks.


text:
Q: Past simple transforms to past perfect? I had a leg injury. Past simple.
I had had a leg injury. Past perfect.
But if I add word "until" past simple transforms to past perfect:
I had a leg injury until I was 15.
Is this sentence correct?
So, I'm stuck. Seems that sentence means the same as
I had had a leg injury until I was 15.

A: They do mean the same thing. But without further context, the use of the past perfect in your second example is unnecessary, because there is no clear reference to some action in the past tense which is preceded by the leg injury.
For instance, in this example sentence:
My running coach was shocked to learn that I had had a leg injury until I was 15.
The coach was shocked at some time in the past, and it is  clear that the leg injury occurred in the more distant past because of the use of the past perfect.