text:
Q: How do I get the while loop to meet it's looping condition even though it's looping condition was supposed to have been meet by the users input? The Java code I am running is asking the user for their user name(which is stored in the string variable UserNameForLogIn) and password(which is stored in the string variable PasswordForLogIn) and if it is the same as the other UserName and Password that is already stored in a String variable at the beginning of the code the condition for a while loop will be meet and it enters it and starts looping but the problem is even if the user puts the exact User name and password from the UserName and Password String Variables from the start of the code it still doesn't want to the while loop as if the condition has not been meet. Please, anyone, I need help this is a part of my school project that I'm doing and it's due in 3 days theirs still 2 more errors in other parts of my code that I still need to fix before I can put it all together in one file. Thank you in advance to anyone who can help me.
here is the code and what I tried to do
please note it's also doing the same thing in both case 1 and case 2 where they confirm your new password.
import java.util.*;
class Main {
  public static void main(String[] args) {

    StartUp();
  }

  static void StartUp()
  {
    int option;
    String UserName = "KalemJoffe";
    String Password = "Staria01";
    String UserNameForLogIn;
    String PasswordForLogIn;
    String UserNameForSignUp;
    String PasswordForSignUp;
    String PasswordForSignUp2;

    Scanner input = new Scanner(System.in);

    System.out.println("Welcome to the banking app please select a option: ");

    System.out.println("1. Log In");
    System.out.println("2. Sign Up");
    option = input.nextInt();
    //Now I am creating a switch statement that will do specific commands depending on their option: Note the correct password and Email for Log In option is at the top//

    switch(option){

      case 1 :
        System.out.println("Please enter UserName : ");
        UserNameForLogIn = input.nextLine();

        input.nextLine();
        System.out.println("Please enter password: ");
        PasswordForLogIn = input.nextLine();

       while (UserNameForLogIn  == UserName && PasswordForLogIn == Password)
        {
         System.out.println("Weclome");

        }

       System.out.println(" Your Email or password is wrong please try again: ");

         System.out.println("Please enter email : ");
         UserNameForLogIn = input.nextLine();

         System.out.println("Please enter password: ");
         PasswordForLogIn = input.nextLine();

        break;

       case 2 :
        System.out.println("Please enter your new email: ");
         UserNameForSignUp = input.nextLine();
         input.nextLine();
        System.out.println("Please create a password: ");
        PasswordForSignUp = input.nextLine();

        System.out.println("Pleae confirm your password: ");
        PasswordForSignUp2 = input.nextLine();

        while (PasswordForSignUp != PasswordForSignUp2 ){

         System.out.println("Error your passwords do not aline please try again! ");
         System.out.println("Please create a password: ");

         PasswordForSignUp = input.nextLine();
         System.out.println("Pleae confirm your password: ");
         PasswordForSignUp2 = input.nextLine();

        }
    }

   }
}


text:
Q: too long waiting for fence I am using Vulkan with C# and Silk.net. And can't understand why it takes so long to complete even small command queues. Please, look at this CPU timeline:

As you can see, there are too long waitings, while GPU work times are small:

I understand that it is not efficient to wait for fences. But here is something strange, I think. When it was OpenGL, it was possible to synchronize CPU and GPU after every draw. Even with different shaders, textures, and much of work. So, it must be possible without such waiting.
Is it some bug or normal behaviour for Vulkan?

A: Vulkan does not specify behavior in terms of timing. So this is neither a "bug" nor "normal". Performance questions of this sort are not a matter of the API definition. They are a matter of reasonable expectation out of a system.
The delay times you are talking about appear to be on the order of tenths of a millisecond. That is not entirely unreasonable as far as overhead is concerned for waiting on an unsignaled fence. It is not reasonable to expect the CPU thread to be woken up instantly upon the completion of the GPU operation being waited on.
Waiting on an unsignaled fence is only something that should happen if the CPU starts outrunning the GPU. You should only check a fence from a previous frame, and only if you need to use some memory resources or swapchain images used by that frame. And if it is still unsignaled, go do whatever CPU work you can that doesn't require using those resources. Only when you are out of other work to do should you actually wait on the fence with a non-zero time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: D3.JS: multi-line chart with mouseover tooltip I created a multi-series line chart and tried adding tooltips according to this stackoverflow answer but tooltip is not working and i am not able to figure out what is wrong with my code.

var margin = {
    top: 20,
    right: 30,
    bottom: 30,
    left: 40
  },
  width = 960 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom;

var z = d3.scale.category20c();

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%SZ");

var data = [{
  label: "a",
  data: [
    [
      "2016-02-02T11:34:03Z",
      0
    ],
    [
      "2016-02-04T11:34:03Z",
      0
    ],
    [
      "2016-02-06T11:34:03Z",
      0
    ],
    [
      "2016-02-08T11:34:03Z",
      0
    ],
    [
      "2016-02-10T11:34:03Z",
      0
    ],
    [
      "2016-02-12T11:34:03Z",
      0
    ],
    [
      "2016-02-14T11:34:03Z",
      0
    ],
    [
      "2016-02-16T11:34:03Z",
      0
    ],
    [
      "2016-02-18T11:34:03Z",
      0
    ],
    [
      "2016-02-20T11:34:03Z",
      0
    ],
    [
      "2016-02-22T11:34:03Z",
      0.3735178379850471
    ],
    [
      "2016-02-24T11:34:03Z",
      0
    ],
    [
      "2016-02-26T11:34:03Z",
      0
    ],
    [
      "2016-02-28T11:34:03Z",
      0
    ],
    [
      "2016-03-01T11:34:03Z",
      0
    ]
  ]
}, {
  label: "b",
  data: [
    [
      "2016-02-02T11:34:03Z",
      0
    ],
    [
      "2016-02-04T11:34:03Z",
      0
    ],
    [
      "2016-02-06T11:34:03Z",
      0
    ],
    [
      "2016-02-08T11:34:03Z",
      0
    ],
    [
      "2016-02-10T11:34:03Z",
      0
    ],
    [
      "2016-02-12T11:34:03Z",
      0
    ],
    [
      "2016-02-14T11:34:03Z",
      0
    ],
    [
      "2016-02-16T11:34:03Z",
      0
    ],
    [
      "2016-02-18T11:34:03Z",
      0
    ],
    [
      "2016-02-20T11:34:03Z",
      0
    ],
    [
      "2016-02-22T11:34:03Z",
      0.25810614839315693
    ],
    [
      "2016-02-24T11:34:03Z",
      0
    ],
    [
      "2016-02-26T11:34:03Z",
      0
    ],
    [
      "2016-02-28T11:34:03Z",
      0
    ],
    [
      "2016-03-01T11:34:03Z",
      0
    ]
  ]
}];

var x = d3.time.scale()
  .range([0, width]);

var y = d3.scale.linear()
  .range([height, 0]);

var xAxis = d3.svg.axis()
  .scale(x)
  .orient("bottom");

var yAxis = d3.svg.axis()
  .scale(y)
  .orient("left");

var line = d3.svg.line()
  .interpolate("monotone")
  .x(function(d) {
    return x(parseDate.parse(d[0]));
  })
  .y(function(d) {
    return y(d[1]);
  });

var ary = [];
data.forEach(function(d) {
  ary.push(d.data);
});

x.domain(d3.extent(d3.merge(ary), function(d) {
  return parseDate.parse(d[0]);
}));

y.domain([
  d3.min(data, function(c) {
    return d3.min(c.data, function(v) {
      return v[1];
    });
  }),
  d3.max(data, function(c) {
    return d3.max(c.data, function(v) {
      return v[1];
    });
  })
]);

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis);

svg.append("g")
  .attr("class", "y axis")
  .call(yAxis);

var series = svg.selectAll(".series")
  .data(data)
  .enter().append("g")
  .attr("class", "series");

series.append("path")
  .attr("class", "line")
  .attr("d", function(d) {
    return line(d.data);
  })
  .style("stroke", function(d, i) {
    return z(i);
  });

series.append("text")
  .datum(function(d) {
    return {
      label: d.label,
      data: d.data[d.data.length - 1]
    };
  })
  .attr("transform", function(d) {
    return "translate(" + x(parseDate.parse(d.data[0])) + "," + y(d.data[1]) + ")";
  })
  .attr("x", 3)
  .attr("dy", ".35em");

var mouseG = svg.append("g")
  .attr("class", "mouse-over-effects");

mouseG.append("path") // this is the black vertical line to follow mouse
  .attr("class", "mouse-line")
  .style("stroke", "black")
  .style("stroke-width", "1px")
  .style("opacity", "0");

var lines = document.getElementsByClassName('line');

var mousePerLine = mouseG.selectAll('.mouse-per-line')
  .data(data)
  .enter()
  .append("g")
  .attr("class", "mouse-per-line");

mousePerLine.append("circle")
  .attr("r", 7)
  .style("stroke", function(d, i) {
    return z(i);
  })
  .style("fill", "none")
  .style("stroke-width", "1px")
  .style("opacity", "0");

mousePerLine.append("text")
  .attr("transform", "translate(10,3)");

mouseG.append('svg:rect') // append a rect to catch mouse movements on canvas
  .attr('width', width) // can't catch mouse events on a g element
  .attr('height', height)
  .attr('fill', 'none')
  .attr('pointer-events', 'all')
  .on('mouseout', function() { // on mouse out hide line, circles and text
    d3.select(".mouse-line")
      .style("opacity", "0");
    d3.selectAll(".mouse-per-line circle")
      .style("opacity", "0");
    d3.selectAll(".mouse-per-line text")
      .style("opacity", "0");
  })
  .on('mouseover', function() { // on mouse in show line, circles and text
    d3.select(".mouse-line")
      .style("opacity", "1");
    d3.selectAll(".mouse-per-line circle")
      .style("opacity", "1");
    d3.selectAll(".mouse-per-line text")
      .style("opacity", "1");
  })
  .on('mousemove', function() { // mouse moving over canvas
    var mouse = d3.mouse(this);
    d3.select(".mouse-line")
      .attr("d", function() {
        var d = "M" + mouse[0] + "," + height;
        d += " " + mouse[0] + "," + 0;
        return d;
      });

    d3.selectAll(".mouse-per-line")
      .attr("transform", function(d, i) {
        console.log(width / mouse[0])
        var xDate = x.invert(mouse[0]),
          bisect = d3.bisector(function(d) {
            return d[0];
          }).right;
        var idx = bisect(d.values, xDate);

        var beginning = 0,
          end = lines[i].getTotalLength(),
          target = null;

        while (true) {
          target = Math.floor((beginning + end) / 2);
          var pos = lines[i].getPointAtLength(target);
          if ((target === end || target === beginning) && pos.x !== mouse[0]) {
            break;
          }
          if (pos.x > mouse[0]) end = target;
          else if (pos.x < mouse[0]) beginning = target;
          else break; //position found
        }

        d3.select(this).select('text')
          .text(y.invert(pos.y).toFixed(2));

        return "translate(" + mouse[0] + "," + pos.y + ")";
      });
  });
text.inner-circle {
  font-weight: 400;
  font-size: 12px;
  text-transform: uppercase;
}
text.inner-text {
  font-weight: 400;
  font-size: 36px;
  font-family: 'Metric Regular', 'Metric';
  text-align: center;
  font-style: normal;
  text-transform: uppercase;
}
path {
  stroke: steelblue;
  stroke-width: 2;
  fill: none;
}
.axis path,
.axis line {
  fill: none;
  stroke: grey;
  stroke-width: 2;
  shape-rendering: crispEdges;
}
.grid .tick {
  stroke: lightgrey;
  stroke-opacity: 0.7;
  shape-rendering: crispEdges;
}
.grid path {
  stroke-width: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

JSFIDDLE LINK
Please help me in figuring out what mistake i had made and how to fix it. Any help is appreciated!

A: The bug comes from the line
    var idx = bisect(d.values, xDate);

It should be the following instead:
    var idx = bisect(d.data, xDate);


text:
Q: how the continue statement works in for loop in C? I have the following code in C:
#include <stdio.h>

int main()
{
    int i = 1;
    while(i)
    {
        int index = 0;
        printf("while begin\n");

        for(index = 0; index < 10; index++)
        {
            if(index == 2)
            {
                continue;
            }
            printf("within for\n");
        }
        printf("while end\n");
    }

    printf("returned from while");
}

does the continue effect the for loop or the while loop directly? looks like once the continue is called, for loop will start to run from the beginning, should not the while loop start to run from the beginning?

A: continue will cause the remaining portion of the enclosing for or while loop body to be skipped. In your case, the for is the "enclosing" loop of continue and the while loop is the "enclosing" scope of the for loop.
According to (unofficial) documentation

The continue statement causes a jump, as if by goto to the end of the
  loop body (it may only appear within the loop body of for, range-for,
  while, and do-while loops).

A: To understand what continue is you should know what break does too.
So the following peace of code shows you how break and continue works:
#include <stdio.h>

int main(void){
    int hours = 10;
    int i=0;

    for(i=0;i<hours;i++){
        if(i==5){
            break;
        }

        printf("%d ",i);
    }

    return 0;
}

Output:

0 1 2 3 4

As you can see, when i reaches 5 (i==5) the loop breaks.
Now let's take a look of what does continue if we replace break using the same code:
#include <stdio.h>

int main(void){
    int hours = 10;
    int i=0;

    for(i=0;i<hours;i++){
        if(i==5){
            continue;
        }

        printf("%d ",i);
    }

    return 0;
}

Output:

0 1 2 3 4 6 7 8 9

As you can see it doesn't leave the loop (like when using break), instead when i reach 5 (i==5) ignore the rest of the body making the loop to start over from the point where i was last time seen.
The number 5 *is missing.

A: The simplest way to think about it is to say : "it goes back to the top of the loop" anything AFTER the continue won't be processed.


text:
Q: Godaddy CNAME record does not work with heroku DNS target I have bought the following domain www.rodrigoloza.com from GoDaddy. I have a Django application deployed in heroku https://rodrigo-blog-123456.herokuapp.com/
I wanted to add my www domain to my heroku app, so I edited the CNAME of my DNS and added the following information.
Type: CNAME
Name: www
Value: rodrigoloza.com.herokudns.com
TTL: 1 Hour
When I check heroku domains -a app_name I get that the domain name has been set to the DNS target www.rodrigoloza.com.herokudns.com but when I click on my domain I see the page cannot be found. I don't know what can be wrong.
Pd: I have waited for more than 48 hours so changes should have propagated by now.


text:
Q: Выполнить функцию js при нажатии определенного элемента Подскажите пожалуйста, как я могу выполнить функцию go2 при нажатии на button не выполняя функцию go

function go($i) {
  alert($i);
}
function go2($i) {
  alert($i);
}
div {
  width: 200px;
  height: 200px;
  background: #eaeaea;
}
<div onclick="go('159');">
<button onclick="go2('160');">Go 2</button>
</div>


text:
Q: Python - transform time format in datatime Have dd-mm-yy in "date" column
05-01-15

need yyyy-mm-dd
2015-01-05

Solved with
df['date'] = pd.to_datetime(df.date, format='%d-%m-%y', errors='coerce')

Has it another solution?

A: from datetime import datetime

now = datetime.now()

date_time = now.strftime("%Y-%m-%d")
print("date and time:",date_time)

Or have a closer look at strftime documentation.

A: df['date'] = pd.to_datetime(df['date'])

Will transform your custom format to pandas recognized datetime, which you will be able to use for calculations.


text:
Q: AutoitX.Send is not sending Keystrokes to text field in Windows Sever using C# I am using AutoitX.Send(Filepath) to upload a file in server.
I have written below code
AutoItX.WinActivate("Open");
AutoItX.ControlFocus("[Class:Edit]","", "Edit1");
Thread.Sleep(5000);
Log.Info("FILEPATH BEFORE SEND KEY" + filePath);
AutoItX.Send(filePath);
AutoItX.Send("{Enter}");

This code works in my local, but it's not working on the server.
I am getting the error for find element, which can be found once the upload file is successful, but autoitx.send is not sending any keystroke to file explorer to find specific file.
Can someone please help me on this?


text:
Q: ssh python fabric I don't actually understand how to do that.
I have access to local computer for example 192.168.1.101 with some_user. From that computer i have access to another comp (via vpn) 10.0.132.17 and only from here i can reach access to computer 10.0.132.15 where i need to deploy my script.
so I need to:
$ ssh some_user@192.168.1.101 -> ssh another_user@10.0.132.17 -> ssh another_user@10.0.132.15

may i somehow do: ssh some_user@192.168.1.101 -p 2222 and get access to another_user@10.0.132.15?
or in python fabric to write somehow env variable?

A: Another option than using an explicit tunnel is to set up ssh to transparently forward through your proxies. Put in your ~/.ssh/config something like the following:
Host proxy_midstage
    User another_user
    HostName 10.0.132.17
    ProxyCommand ssh -q some_user@192.168.1.101 nc %h %p

Host proxy_final
    User another_user
    HostName 10.0.132.15
    ProxyCommand ssh -q proxy_midstage nc %h %p

Then the command ssh proxy_final will jump you straight to the deployment server. Presumably fabric can use that, though I'm not positive.


text:
Q: How to package Python Microservice to use in internal for other Services? Im currently building a python project with microservices architecture. Each service consists of different "modules" / folders. Some other microservices can use a client from a service to make calls to the service.
The folder structure is the following

How do I create a package that contains users.users_client, users._users_core ....
The github is used by Github Actions and the requirements.txt and app.yaml are used from Google Cloud App Engine.
The service runs with gunicorn / uvicorn. So I need to make sure the service is still runnable when changing the folder structure.


text:
Q: alternative to fitColumns() in Ext JS 4 I am trying to dynamically fit columns in the grid.
Is there anything in Ext JS 4 which resizes each column to fit the grid like method fitColumns() in Ext JS 3.4?
thanks

A: If any one of grid columns has flex:1 then the columns are resized to fit the grid width.


text:
Q: Python: is there a faster alternative to using numpy's polyfromroots? Using Python, I am looping over a large collection of sets of roots (represented as a 2-dimensional numpy array, essentially), and forming each time the monic polynomial having the set of roots (called roots) as roots, as such:
poly = np.polynomial.polynomial.polyfromroots(roots)

However, my code runs slowly when the number of sets of roots is large (about 40000), even though each set of roots is itself small (containing only 4 roots).
As an example, if I run
import timeit

SETUP_CODE = '''
import numpy as np'''

TEST_CODE = '''
N, n = 40000, 4
collection_roots = np.random.random((N,n)) + 1.j*np.random.random((N,n))
polynomials = np.zeros((N, n + 1), dtype=complex)
for k in range(N):
    roots = collection_roots[k, :]
    polynomials[k, :] = np.polynomial.polynomial.polyfromroots(roots)'''

print(timeit.timeit(setup=SETUP_CODE,
                    stmt=TEST_CODE,
                    number=1))

the output on my relatively old machine is about 2.9 seconds. Is there a way to speed up this piece of code, within Python?
There are other places in my code that could use some optimization. Of course, I could create separate posts, but it would help me (and others) if someone could also post some resources they found useful for optimizing Python code for scientific computing.

A: Sympy can precalculate the general formula for a given number of roots:
from sympy import Symbol, Product, poly, lambdify

num_roots = 4
x = Symbol('x')
roots = [Symbol(f'r{i}') for i in range(num_roots)]
prod = 1
for ri in roots:
    prod *= (x - ri)
print(prod)
print(poly(prod, x).all_coeffs()[::-1])
np_poly_4_roots = lambdify(roots, poly(prod, x).all_coeffs()[::-1])

np_poly_4_roots(*[1, 2, 3, 4])

Calling help(np_poly_4_roots) shows its source code:
def _lambdifygenerated(r0, r1, r2, r3):
    return ([r0*r1*r2*r3,
             -r0*r1*r2 - r0*r1*r3 - r0*r2*r3 - r1*r2*r3,
             r0*r1 + r0*r2 + r0*r3 + r1*r2 + r1*r3 + r2*r3,
             -r0 - r1 - r2 - r3,
             1])

This already works a bit faster, but isn't fully vectorized. But you could use this source to manually create a vectorized version:
def fast_poly_4_roots(r):
    r0, r1, r2, r3 = r[:, 0], r[:, 1], r[:, 2], r[:, 3]
    return np.array([r0 * r1 * r2 * r3,
                     -r0 * r1 * r2 - r0 * r1 * r3 - r0 * r2 * r3 - r1 * r2 * r3,
                     r0 * r1 + r0 * r2 + r0 * r3 + r1 * r2 + r1 * r3 + r2 * r3,
                     -r0 - r1 - r2 - r3,
                     np.ones_like(r0)])

For an input with all 4 roots, this can be executed in a vectorized way:
N, n = 4000, 4
collection_roots = np.random.random((N,n)) + 1.j*np.random.random((N,n))

polynomials = fast_poly_4_roots(collection_roots)

As now there aren't Python for-loops anymore, things are really fast.


text:
Q: How to create a loop in R to count coincidences in a table? I need some help, I have a table in R with so may columns, lets say that I am interested in the columns V111 to V135 and I would like to count the rows in each column that are different to './.'.
I can do this for each column independently (it says to me the number of coincidences different to ./.)
m <-p[p$V111 != './.', ]

but I appreciate I someone could suggest me a  loop to get the number of coincidences for each column.
V110    V111    V112
./. 1/1:0,51:51:99:2136,153,0   1/1:0,28:28:84:1211,84,0
./. ./. 0/1:15,13:28:99:434,0,543
./. ./. ./.
./. ./. ./.
./. ./. ./.
1/1:0,21:21:63:875,63,0 ./. ./.
./. ./. ./.
./. ./. ./.
./. ./. ./.
./. ./. ./.
./. ./. ./.
./. 1/1:0,18:18:54:745,54,0 1/1:0,5:5:15:207,15,0
./. 1/1:0,2:2:6:90,6,0  ./.
./. 1/1:0,2:2:6:90,6,0  ./.
./. ./. ./.
./. ./. ./.
./. ./. ./.
./. 0/1:6,4:10:99:137,0,210 ./.

A: You could count the number of rows without './.' in each column with colSums(). For the data you provided, if you wanted to count rows without './.' in the first two columns, you'd do
colSums(p[,1:2] != "./.")
#V110 V111
#   1    5

If you wanted the rows in each column where there is no './.', you'd do
lapply(p[,1:2], function(x) which(x != "./."))
#$V110
#[1] 6

#$V111
#[1]  1 12 13 14 18

A: If your data frame is p you can check the number of rows different than './.' in every specified column by
 colnames_p <-names(p[, 111:135]) #corresponds to V111 to V135
 for ( i in seq_along(colnames_p)){
   print(names(p[i]))
   m <-length(p[p[i] != './.', ])
   print(m)
}

A: Following code will provide you with the desired output:
colSums(p[,111:135 != "./.")

where, 111:135 is the number of columns.


text:
Q: Make User enter Input Strings in variables of my class through array. I was trying to learn various ways in which arrays can be used and i found an example in book which i tried to modify , my array is being made and i am able to create objects of reference variables in array object but i am not able to make user input values here is my code:
class Information {
     String author, title;
 }

public class Books {

public static void main(String[] args) throws IOException {

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter Number of Books: ");
    int n = Integer.parseInt(bufferedReader.readLine());
    Information myBooks[] = new Information[n];
    for (int i = 0; i < n; i++) {
        myBooks[i] = new Information();
    }
    for (int j = 0; j < n; j++) {
        myBooks[j].author = bufferedReader.readLine();
        myBooks[j].title = bufferedReader.readLine();
    }
    for (int k = 0; k < n; k++) {
        System.out.println("author of " + myBooks[k].title + " is " + myBooks[k].author);
        System.out.println();
    }

}

}

how can i make user input values in myBooks[0].author and myBooks[0].title and so on.

A: Geez i feel stupid :P But i got solution to my problem.
code was working the way it was supposed to work, i just tried adding two sentences and it worked.. basically it was taking me into loop but i didnt know.
        for (int j = 0; j < n; j++) {
        System.out.println("Enter author's name for book "+ (j+1));
        myBooks[j].author = bufferedReader.readLine();
        System.out.println("Enter Title for book"+ (j+1));
        myBooks[j].title = bufferedReader.readLine();

so now when i enter the loop it asks to enter so i can enter :P


text:
Q: Spring AOP Doesn't Apply on Methods with Generic Type Return Values EDIT: Solved, its because of the double asterisks in the beginning, I copied it from The Book: Spring Microservices in Action.
I'm trying to advise some controller methods.
This is the aspect class:
@Aspect
public class PBLogger {

    @Pointcut("execution(** com.sunwell.product..*.*(..))")
    public void standardMethod() {
    }

    @Around("standardMethod()")
    public Object log(ProceedingJoinPoint jp) {
           ...
    }

...
}

This is the target method, I've made sure the package name is correct.
This one doesn't work(advice method isn't called):
@RequestMapping(value = "resources/items", method = RequestMethod.GET,
                    produces = "application/json"
            )
public ResponseEntity<Map<String,Object>> getItems(
                    @RequestHeader(value="Authorization", required = false) String _auth, @RequestParam(value="systemId", required = false) Integer _i ) throws Exception
{ ... }

Without the generic return type, it works:
@RequestMapping(value = "resources/items", method = RequestMethod.GET,
                        produces = "application/json"
                )
public void getItems(@RequestHeader(value="Authorization", required = false) String _auth, @RequestParam(value="systemId", required = false) Integer _i ) throws Exception
{ ... }

It works too using the annotated pointcut instead of execution
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Example
{
    public String msg();
}

@Aspect
public class PBLogger {

        @Pointcut("@annotation(Example)")
        public void standardMethod() {
        }

        @Around("standardMethod()")
        public Object log(ProceedingJoinPoint jp) {
           ...
        }

    ...
}

//target method:
        @RequestMapping(value = "resources/items", method = RequestMethod.GET,
                    produces = "application/json"
            )
        @Example
public ResponseEntity<Map<String,Object>> getItems(
                    @RequestHeader(value="Authorization", required = false) String _auth, @RequestParam(value="systemId", required = false) Integer _ ) throws Exception
{ ... }

A: The target method signature is not the problem, generics or not. Look at my MCVE:
Target classes:
Please note that you cannot put both methods into the same class because they would have the same type erasure. The compiler would complain about this.
package de.scrum_master.spring.q60474362;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Component
public class MyTargetClass {
  @RequestMapping(
    value = "resources/items", method = RequestMethod.GET,
    produces = "application/json"
  )
  public ResponseEntity<Map<String, Object>> getItems(
    @RequestHeader(value = "Authorization", required = false) String _auth,
    @RequestParam(value = "systemId", required = false) Integer _i
  ) throws Exception
  {
    System.out.println("MyTargetClass.getItems");
    return null;
  }
}

package de.scrum_master.spring.q60474362;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Component
public class MyOtherTargetClass {
  @RequestMapping(
    value = "resources/items", method = RequestMethod.GET,
    produces = "application/json"
  )
  public void getItems(
    @RequestHeader(value = "Authorization", required = false) String _auth,
    @RequestParam(value = "systemId", required = false) Integer _i
  ) throws Exception
  {
    System.out.println("MyOtherTargetClass.getItems");
  }
}

Aspect:
Please note that ** in your sample pointcut does not make sense, I changed it to using *. If ** works you are just lucky the syntax check is not strict but my IDE actually complains as it should. Furthermore, you don't really need my.package..*.*(..), my.package..*(..) is enough if both class and method name do not matter.
package de.scrum_master.spring.q60474362;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class PBLogger {
  @Pointcut("execution(* de.scrum_master.spring..*(..))")
  public void standardMethod() {}

  @Around("standardMethod()")
  public Object log(ProceedingJoinPoint jp) throws Throwable {
    System.out.println(jp);
    return jp.proceed();
  }
}

Spring driver application & configuration:
package de.scrum_master.spring.q60474362;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@SpringBootApplication
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class Application {
  public static void main(String[] args) throws Exception {
    try (ConfigurableApplicationContext appContext = SpringApplication.run(Application.class, args)) {
      doStuff(appContext);
    }
  }

  private static void doStuff(ConfigurableApplicationContext appContext) throws Exception {
    MyTargetClass myTargetClass = appContext.getBean(MyTargetClass.class);
    myTargetClass.getItems("x", 11);
    MyOtherTargetClass myOtherTargetClass = appContext.getBean(MyOtherTargetClass.class);
    myOtherTargetClass.getItems("y", 22);
  }
}

Console log:
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.2.RELEASE)

(...)
2020-03-02 09:00:49.712  INFO 24028 --- [           main] d.s.spring.q60474362.Application         : Started Application in 3.554 seconds (JVM running for 5.157)
execution(ResponseEntity de.scrum_master.spring.q60474362.MyTargetClass.getItems(String,Integer))
MyTargetClass.getItems
execution(void de.scrum_master.spring.q60474362.MyOtherTargetClass.getItems(String,Integer))
MyOtherTargetClass.getItems
(...)

If it does not work for you, then you have some other problem such as the problematic target class not being picked up by component scan, e.g. due to a forgotten @Component annotation or whatever.


text:
Q: Facebook Image URL gets expired I am pulling Facebook posts using facebook-graph API, now the problem is Image gets expired after few days.
I have the following URL for a single Image
Old Image URL which got expired

https://scontent-a.xx.fbcdn.net/hphotos-xfp1/v/l/t1.0-9/p180x540/14377_340369866155028_6836158858133154924_n.jpg?oh=7ed0d8818ad54fac851b036d24f5e674&oe=55579EE3

New Image working URL Is

https://scontent-sin1-1.xx.fbcdn.net/hphotos-xfa1/v/l/t1.0-9/14377_340369866155028_6836158858133154924_n.jpg?oh=2f7ad72fa36fc026ad2bdcc1b0284146&oe=55C87432

I am frustrated with this issue, what could be the solution of it?

A: What i came to know from other community about this issue is
"You should not store Facebook CDN URLs for long time use – they can change over time.
Either request the actual image and copy that to your server – or request the current CDN URL regularly.
(You might be tempted to try other workarounds, like extracting the actual image source URL from the CDN link, but I would advise against that – because the format of that might change at any time as well.)"

A: Haven't updated for a long time and don't know if this works as before
You should store the original image URL for sure, and use a 302 redirect parser to get the CDN URL, one example is https://scontent-ort2-1.xx.fbcdn.net/v/t45.1600-4/120202220_23846099766190042_1642096590788171162_n.jpg?_nc_cat=108&ccb=2&_nc_sid=2aac32&_nc_ohc=CE0J2Ao5cYkAX_JJ0Me&_nc_ht=scontent-ort2-1.xx&oh=f48cbb1bec21e685e0cbaaf6782a61a1&oe=5FE056E5 and we can just guess oe=5FE056E5 means the expiration, as 5FE056E5(hexadecimal) -> 1608537829(decimal, in UTC), if you interpret this timestamp you will find the time is about a month later, and maybe we can guess the expiration is about a month after getting the CDN URL? To another similar case, you can refer to: https://stackoverflow.com/a/27596727/4721007

A: you can not store facebook Images url for a long time, it expires for security purpose, so it would be a better solution to store images in your server.


text:
Q: ASP.NET MVC - is it possible to choose between multiple authentcation system We have a ASP.NET MVC + Angular SPA stored in the location in Azure (same AppService).
Actually, when we go to the AppService URL (e.g. myapp.customazure.com) it triggers the WsFederation authentication redirecting to the partner website (external provider). After login successfully, our Home.cshtml can run which is typically our Angular (we're rendering Angular javascript files in there).
Our Home.cshtml looks like this:
<!doctype html>

    <meta charset="utf-8">
    <title>MyApp.Web</title>
    <base href="/">
    <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <META HTTP-EQUIV="Expires" CONTENT="-1">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link type="image/x-icon" href="favicon.ico" rel="icon" />
    <link type="image/x-icon" href="favicon.ico" rel="shortcut icon" />
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    @Styles.Render("~/styles")

    <app-root>

</app-root>
    @Scripts.Render("~/runtime")
    @Scripts.Render("~/polyfills")
    @Scripts.Render("~/scripts")
    @Scripts.Render("~/main")

The WsFederation configuration is present in Web.config such as:
  <location path="FederationMetadata">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>

and of course

  <system.webServer>
  </system.webServer>

  <system.identityModel>
  </system.identityModel>

  <system.identityModel.services>
  </system.identityModel.services>

What we'd like to achieve is to add the possibility to authenticate using another option (Azure AD B2C). Then in the end there would a new view .cshtml giving two buttons to let user choose between 2 authentications methods:

*

*Connect with WsFederation as usual

*Connect with Azure AD B2C (new option)

Is it feasible to achieve this kind of thing ? thank you again for your help !

A: Yes, it is possible. As you said, first page will have two buttons for WsFederation and B2C.
Now, you have to redirect your users to your controller action methods based on the button they press.
For B2C setup in MVC, you can refer Quickstart: Set up sign in for an ASP.NET application using Azure Active Directory B2C.
Further, check out Integrating a web app with Azure AD using WS-Federation if it suits your requirement.


text:
Q: How to represent this matlab code in mathematical notation? I have this code in matlab:
z = linspace(d1,d2,n)*W/t;

I am wondering how to express this operation in mathematical notation?
I was thinking of something like this
[d1 + (N).*((d2 - d1)/(n-1))]*W/t; Where N = 0,1,2,...(n-1)
But is there a fancier or more correct way or clearer way of writing this?

A: That is pretty much it, except that you have to multiply your vector componentwise with $\frac Wt$, so

z = linspace(d1,d2,n)*W/t

produces a vector $v$ of dimension $n$
$$
a_k:=\left[d_1+k\left(\frac{d_2-d_1}{n-1}\right)\right]\frac Wt,k=0,\ldots,n-1
$$
in the following way
$$
v\equiv(a_0,a_1,\ldots,a_{n-1})
$$

A: It depends on the context, but I would write it as,
$$
z = \left\{
\frac{W\cdot d_1}{t}, \frac{W\cdot d_1 + W\cdot(d_2-d_1)/(n-1)}{t}, \cdots, \frac{W\cdot d_2}{t}
\right\}
$$
which is easier to understand than giving an explicit series.


text:
Q: Why am I given the option to also encrypt my home folder after I've selected system encryption? I am installing Ubuntu 13 with full encryption but why am I given the option to also encrypt my home folder. Surely the home folder is covered under the system encryption? I'm confused.

A: These are 2 different ways of encryption. If your /home already resides on encrypted partition, then the second one is redundant. It just encrypts your /home/user with your user's password by putting your /home/user into a virtual device.

A: You are being offered 2 layers of Encryption.
The first is LUKS. With LUKS your entire installation (except /boot) will be encrypted, including your home directory.
The second is ecrptfs and is used to encrypt your home directory.
In general there is no need to use the two together, but, you could if for example you have multiple users and you wish to keep data encrypted between users or from root access.
When you use LUKS, when you boot, the data in your /home will be decrypted and as long as the system is running, the data can be read by root and other users.
https://wiki.ubuntu.com/SecurityTeam/Policies#Permissive_Home_Directory_Access
If you so desire , you can restrict access to the data in your home directory by adjusting the permissions or by encrypting your home directory as well.
If you encrypt your home directory, your personal data will remain encrypted when the system boots and will only be decrypted when you log in.
HTH


text:
Q: Using Insecure TLS in Java version of Eclipse Paho I am trying to connect to an MQTT server without having to validate the TLS certs. I am using the latest version of Eclipse Paho from a Java program. I cannot find a way to turn off the validation.
In the Python version of Eclipse Paho, the vendor who is running the server uses the following code to turn off the validation:
        client = mqtt_client.Client(client_id, transport='websockets')
        client.tls_set("", cert_reqs=ssl.CERT_NONE)
        client.tls_insecure_set(True)

I don't see an equivalent for Java.
Does anyone know how I can accomplish this in Java?

A: You will need to pass a custom SSLSocketFactory as part of the MqttConnectOptions object passed to the Paho client's connect() method.
This will come from on a SSLContext with a custom TrustManager e.g.
TrustManager [] trustAllCerts = new TrustManager [] {new X509ExtendedTrustManager () {
   @Override
   public void checkClientTrusted (X509Certificate [] chain, String authType, Socket socket) {

   }

   @Override
   public void checkServerTrusted (X509Certificate [] chain, String authType, Socket socket) {

   }

   @Override
   public void checkClientTrusted (X509Certificate [] chain, String authType, SSLEngine engine) {

   }

   @Override
   public void checkServerTrusted (X509Certificate [] chain, String authType, SSLEngine engine) {

   }

   @Override
   public java.security.cert.X509Certificate [] getAcceptedIssuers () {
      return null;
   }

   @Override
   public void checkClientTrusted (X509Certificate [] certs, String authType) {
   }

   @Override
   public void checkServerTrusted (X509Certificate [] certs, String authType) {
   }

}};

SSLContext sc = null;
try {
   sc = SSLContext.getInstance ("TLS");
   sc.init (null, trustAllCerts, new java.security.SecureRandom ());
} catch (KeyManagementException | NoSuchAlgorithmException e) {
   e.printStackTrace ();
}

String uri = "ssl://localhost:1884";
String clientId = "client-101";

MqttClient client = new MqttClient(uri, clientId))

final MqttConnectOptions options = new MqttConnectOptions();
options.setSocketFactory(sc.getSocketFactory());

client.connect(options)

This does basically the same as the python code, but you should probably implement some proper checks in the methods in the TrustManager to ensure you are actually connecting to the server you are expecting. Blindly disabling all the checking basically removes a lot of protection of a TLS connection.


text:
Q: How does Amazon CloudFront compare with Limelight or Akamai? Good morning,
I am looking into an inexpensive solution to deliver content to our European customers, I came across Amazon CloudFront. I was wondering if any of you had any experience using this service? If so, what are your thoughts compared to something like Limelight or Akamai?
Thanks!

A: I have no real-world experience using CloudFront, but on paper it strikes me as a viable CDN for medium or small volumes, and possibly high variation of volume over time, compared to Akamai's and LimeLight's offerings which may be better for steadily high volumes.
CloudFront is essentially a "pay per use" arrangement, and pricing is pretty transparent. For example, if in a typical month you serve about a million GETs from Europe and a million GETs from the US, each GET delivering about a megabyte, the data transfer will cost you as follows: $1.00 for the US gets, $1.20 for the Europe gets, $170.00 for each of of the two data transfer volumes (1000 GB each), total $342.20.  "No minimum, no cover", no fixed fees, just pay as you go: if next month your volumes double, so will your costs -- if they halve, so will your costs (lower per-GB tariffs only trigger at very high volumes).
In addition, you do have to pay S3 fees as well, since CloudFront edge servers get your data from S3; for the typical case, storage fees will be pennies (your 2000 GB served probably mean just a few GB stored, being served over and over), GET and transfer costs similar to the CloudFront pricing -- however, you typically won't be paying the S3 to edge transfer costs all that often, only when the "cache" kept at the edge nodes needs to be refreshed (so the extra cost depends essentially on the rate of "churn" of your contents).
A very complete article showing all that's needed to use S3 and CloudFront for a simple Ruby on Rails appliation is here -- don't be daunted if you don't do Ruby, it should be simple enough to follow anyway (hey, I don't do Ruby either, but I could follow along;-).

A: A content delivery network will be anything but "inexpensive". You will need a server in Europe with good connectivity all around. My take would be a UK VPS with 478east, but i'm biased, since i'm with them right now.
Silverlight is a technology, not a content delivery network. Akamai will run you out of house and home unless you're planning to deliver 10TB per month, and can jump into a one year contract.
You haven't mentioned if you will deliver static or streaming content, as that counts, since you might have a harder time using a VPS/server in Europe as you will need to setup a lot more stuff for streaming as opposed to static/progressive streaming.

A: If you're still in the market, you should look at Aryaka. Their architecture for delivering application seems quite different than traditional CDN. Aryaka's architecture allows for private middlemile transport without ISP peering and TCP op. I hope this helps.


text:
Q: ggplot data with missing months and blue shade for spring period in R? I have the following data.frame where I am missing winter months (Nov, Dec, Jan, and Feb). When I ggplot the data, I see that the lines are connected even though there is no data for the winter months. I would like to avoid having those missing months drawn on the graph. Also, I would like to draw a blue shade for the spring months (March, April, May) that would indicate spring period.
library(tidyverse)
library(lubridate)

DF <- data.frame(Date = seq(as.Date("2001-01-01"), to = as.Date("2005-12-31"), by = "day"),
                  Obs = runif(1826,1,5), Sim = runif(1826,1,5)) %>%
   separate(Date, into = c("Year", "Month", "Day")) %>%
  filter(between(Month, 3,10)) %>%
  mutate(Date = make_date(Year, Month, Day))

ggplot(data = DF, aes(x = Date))+
  geom_line(aes(y = Sim, col = "red"))+
  geom_line(aes(y = Obs, col = "blue"))

Desired output: I am looking for a plot like below where the spring period is highlighted with blue shade.

A: Try this approach:
library(tidyverse)
library(lubridate)
#Data
DF <- data.frame(Date = seq(as.Date("2001-01-01"), to = as.Date("2005-12-31"), by = "day"),
                 Obs = runif(1826,1,5), Sim = runif(1826,1,5)) %>%
  separate(Date, into = c("Year", "Month", "Day")) %>%
  filter(between(Month, 3,10)) %>%
  mutate(Date = make_date(Year, Month, Day))
#Create springs var
DF <- DF %>% mutate(Spring=ifelse(Month %in% c('03','04','05'),'Spring',NA)) %>%
  filter(!Month %in% c('11','12'))
#Plot
ggplot(data = DF, aes(x = Date,group=Year))+
  geom_line(aes(y = Sim, col = "red"))+
  geom_line(aes(y = Obs, col = "blue"))+
  geom_bar(stat = 'identity',aes(x=Date,y=5,fill=Spring),alpha=0.25)+
  scale_color_manual(values=c('red','blue'),
                     labels=c('Sim','Obs'))+
  scale_alpha_manual(values=c(0.5,0.5))+
  scale_fill_manual(values=c('blue','pink'),
                    limits='Spring')+
  scale_y_continuous(limits = c(NA,5),expand = c(0,0))+
  scale_x_date(breaks = as.Date(paste0(unique(format(DF$Date,'%Y-%m')),'-01')),
               date_labels = '%Y-%m',expand = c(0.05,0))+
  theme_bw()+labs(color='',fill='')+
  theme(axis.text.x = element_text(angle=90),
        strip.background = element_blank(),
        strip.text = element_blank(),
        panel.spacing = unit(-0.5, "lines"),
        panel.border = element_blank())+
  facet_wrap(.~Year,scales = 'free_x',nrow = 1)

Output:


text:
Q: Issue while restoring a Database Backup file I get the below mentioned while restoring a database back-up file to my system. Actually the back-up has been taken in other system and I'm trying to restore that file to my systems' sql server. Could anybody assist me in explaining what the error is and how to rectify? Please...
Error:
"System.Data.SqlClient.SqlError: The database was backed up on a server running version 10.50.1600. That version is incompatible with this server, which is running version 10.00.2531. Either restore the database on a server that supports the backup, or use a backup that is compatible with this server. (Microsoft.SqlServer.Smo)"
Thank You.

A: You SQL Server where you want to restore the database is older then the origin.
So to restore this database, you have to use a newer version.
Go to downloads.microsoft.com and get the SQL Express version of the latest, install it on any machine and restore. You can even install on the same machine.
If you cant udpate your SQL Server, you can connect both DB's then and use DTS to move the data back to your "old sql system".


text:
Q: Why are post requests not working and getting redirected? I am a beginner with laravel and vue and I have a problem with routes
when I make post requests to the server it tells me that the request was redirected, and I don't know where the problem is since the get requests work normally, please help me
vue code
 await this.form.post('/api/add_tramite/').then(response=>{
                console.log(response.data);
                this.fecthtramitesper();
                this.close();
          })

my route in laravel
Route::post('add_tramite',[tramiteController::class,'agregar_tramite']);

A: You should remove the trailing / in your URI.
await this.form.post('/api/add_tramite').then(response=>{

many servers redirect any url with trailing slash to the version without the slash for different reasons, one of them being SEO.


text:
Q: My button is not re-rendered when using await/asnc I am new to React Native and do a project in school. I am trying to play the audio from url by using react-native-audio-recorder-player and await/aysnc function. Everything is oke until when i want to show the loader (Activity Indicator) while user is waiting for the audio is downloaded from url
My solution is create the isLoading in state, when user click on the button, in the onPress function i will setState for isLoading is true and add a callback for that setState to call another async function. In that async function i will use await to get the audio from url and then when the respone will be received i will setState for isLoading is true. Howerver, my component is not re-rendered even isLoading state is true. I have checked very carefully on componentWillUpdate, Render, componentDidUpdate. My isLoading state works fine exepting my component. Below is my code, sorry for my bad English. Thanks !
    <View style={styles.parentViewStyle}
          <Button
            title='Click on me'
            onPress={()=>{
              //set state for isloading true and call async function
              this.setState({isLoading:true},()=>{this.play()
              });}}
          />
          //this text depends on the isLoading state.
          <Text>
            {this.state.isLoading?'is loading':'play'}
          </Text>
        </View>

     play=async()=>{
    console.log(this.state.isLoading);
    //isLoading here is true but my text shows 'playing'
    await sounder.startPlayer("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3");
    this.setState({isLoading:false});
  }

A: The first problem should be that you put a function in a anonyme state and never launch it. To launch the play() function you can do like this:
this.setState({isLoading:true});
this.play();

The second problem is that await just don't... wait until the end of sounder.startPlayer(). You can see this by doing:
console.log('START');
await sounder.startPlayer("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3");
console.log('END');

I don't know why await don't work... I hope it help you.


text:
Q: Why my HTML/JQuery form dont send POST request? I'm wondering why my form doesn't redirect to the chosen link using POST request and how to fix that?
In general what i'm planing to do is to prevent to access those links directly so i'm planing to check for the Request method if it wasn't POST then i will do a redirect, but my only problem at the moment is to access those links via that form using POST.

<form id="dropdownredirect" name="dropdownredirect" method="post">
<select class="marketplace_list" id="dropdownredirectselect">
      <option value="geschenkformular/">Amazon Germany</option>
      <option value="gift-form/">Amazon UK</option>
      <option value="gift-form/">Amazon France</option>
      <option value="gift-form/">Amazon Italy</option>
      <option value="gift-form/">Amazon Spain</option>
</select>

<input class="marketplace_submit" name="submit" type="submit" value="Weiter  /  Submit" />
</form>

Thanks

A: Do not use javascript use the the method attribute like this

<form action="/your-url" method="post">

</form>


text:
Q: How can I make a public static class "secure"? I'm looking to create a secure wrapper for a public class with public static methods, so let's say the class is very simply:
public class MyClass {
      public static int Add (int first, int second)
      {
          return first + second;
      }
}

I want to have a client needing to access this via some secure other class that will call MyClass. At the end of the day I'm expecting to have all this code in a single dll for clients to use. The intention is to have some behaviour like:
public class SecureMyClassWrapper
{
    bool _isUnlocked;
    private static readonly List<string> validIds = new List<string>(){"only me", "and them"};

    public SecureMyClassWrapper(string id)
    {
        if (validIds.Contains(id))
        {
            _isUnlocked = true;
        }
        else
        {
            _isUnlocked = false;
        }
    }

    public int Add(int first, int second)
    {
        if (_isUnlocked)
        {
            return MyClass.Add(first, second);
        }
        else
        {
            // throw security exception etc.
        }
    }
}

There's a fair possibility that someone with more hacking ability than me is going to want to get at my static methods, so please can somebody suggest why this might be a bad approach or what I should be concerned about here? Some ideas would be that

*

*MyClass methods can easily be called through reflection

*somebody could ildasm.exe code, change the list of validIds or _isUnlocked logic (or even their values at runtime?)

*possible to read a valid ID and then use it as their own

How could I guard against reflection or decompilation in these cases? Is there a standard approach for this you would recommend, e.g. Code Access Security?

A: Host the code you want to protect in a service run on another machine. And expose the api with a Interface.

A: The only way to protect your .Net code is to use an Obfuscator. However it only does so much so it is still crack-able. Even non-.Net code is easy to crack, to have its heaps and stacks altered etc. usually for the purpose of bypassing electronic registration process with commercial software.
If you're dealing with some very sensitive code you can always put it on a cloud server but of course that implies monthly costs. In that case you may also want secured traffic (https) which is just as costly.
Ultimately, you would have to do a cost vs. benefits consideration when dealing with your code's security. It is always best practice to write your code in such a way that it can be open-source and still not compromise your users security or data.


text:
Q: How to make gnome-calculator accept comma as thousand separator? I want to make gnome-calculator works with an input number that has commas inside as thousands separator, currently, gnome-calculator auto subtracts all the numbers following the first comma.
My LC_NUMERIC config here:
decimal_point="."
thousands_sep=""
grouping=-1
numeric-decimal-point-wc=46
numeric-thousands-sep-wc=0
numeric-codeset="UTF-8"

A: GNOME-Calculator reads the , and . as a decimal.  It is something that is hard coded into the app itself.  If you would like that as a feature you will have to file a feature request by ubuntu-bug gnome-calculator.
However, the comma can be automatically inserted for you. Do not press the comma , as the calculator will assume it is a decimal.
Click on the Gear and select Preferences.

Then turn on the Thousands Separators.

Then when you are typing in the numbers like 10000 the comma will be added automatically.


text:
Q: Django missing 1 required positional argument I am trying to make a view that i can use in multiple apps with different redirect urls:
Parent function:
def create_order(request, redirect_url):
    data = dict()
    if request.method == 'POST':
        form = OrderForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect(redirect_url)
    else:
        form = OrderForm()
    data['form'] = form
    return render(request, 'core/order_document.html', data)

Child function:
@login_required()
def admin_order_document(request):
    redirect_url = 'administrator:order_waiting_list'
    return create_order(request, redirect_url)

When i'm trying to call admin_order_document function i'm getting:
Traceback (most recent call last):
  File "/home/project/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/home/project/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/project/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
TypeError: create_order() missing 1 required positional argument: 'redirect_url'

If i remove redirect_url from both functions and manually add 'administrator:order_waiting_list' to redirect() it works, but i need to redirect to multiple urls. So, why am i getting this error?

A: url(r'^orders/create/', views.create_order, name='create_order')

This clearly is not going to work, since create_order requires redirect_url but there is no redirect_url kwarg in the regex r'^orders/create/'.
Perhaps you want to use the admin_order_document view here instead:
url(r'^orders/create/', views.admin_order_document, name='create_order')

Note you should add a trailing dollar, i.e. r'^orders/create/$' unless you want to match orders/create/something-else as well as orders/create/.

A: If you didn't changed the regular url
urlpatterns = [
    url(r'^admin/', admin_site.urls),
    ...
]

of your admin site you need to call your function like that:
@login_required()
def admin_order_document(request):
    redirect_url = 'admin:order_waiting_list'
    return create_order(request, redirect_url)

That should fix your problem.


text:
Q: What would the destructor for this class look like? class Equipment
{
    std::vector<Armor*> vEquip;
    Weapon* mainWeapon;
    int totalDefense;
    int totalAttack;

public:

    unsigned int GetWeight();

    int * GetDefense();

    bool EquipArmor(Armor* armor);
    bool UnequipArmor(Armor* armor);

    bool EquipWeapon(Weapon* wep);
    bool UnequipWeapon(Weapon* wep);

    Equipment();
    virtual ~Equipment();
};

It seems like there should be no destructor. The vector of pointers will take care of itself when it goes out of scope, and the actual objects the pointers point to don't need to be deleted as there will be other references to it.
All of the objects in this refer to the main Container:
class Container
{
    int weightLimit;
    unsigned int currWeight;
    std::vector<Item*> vItems;

public:

    bool AddItem(Item* item);
    bool RemoveItem(Item* item);

    Container();
    Container(int weightLim);
    Container(int weightLim, std::vector<Item*> items);
    ~Container();
};

Now here I can see it being necessary to delete all objects in the container, because this is where all the objects are assigned via AddItem(new Item("Blah"))
(Armor and Weapon inherit from Item)

A: If you need to delete the items, then:
Container :: ~Container() {
   for ( unsigned int i = 0; i < vItems.size(); ++i ) {
      delete vItems[i];
   }
}

Note that for this to work correctly, the Item class must have a virtual destructor, if the array really contains pointer to Armour and Weapon instances.

A: Non-pointer types will take care of themselves. So, ints, floats, objects, etc. will take care of themselves, and you don't have to worry about deleting them.
Any pointers that are managed by the class need to be deleted by that class' destructor. So, if the memory pointed to by the pointer was allocated in the class or if it was given to that class with the idea that that class would manage it, then the destructor needs to delete the pointer.
If the pointer is to memory that another class is managing, then you obviously don't want your destructor to delete it. That's the job of the class that is in charge of the memory pointed to by that pointer.
Standard containers do not manage the pointers that they hold if they hold pointers. So, if you have a container of pointers, whichever class is supposed to manage them needs to delete them. Odds are that that's the class that holds the container, but that depends on what your code is doing.
So, typically, for a class that has a container of pointers, you'll need something like this in the destructor:
for(containerType<T*>::iterator iter = container.begin(),
                                end  = container.end();
    iter != end;
    ++iter)
{
    delete *iter;
}

Every pointer that has memory allocated to it has to have something (generally a class, but sometimes the function that it's allocated in) who effectively owns that memory and makes sure that it is freed. When talking about classes, that's usually the same class that the memory is allocated in, but of course, it's quite possible for one class or function to allocate the memory and then effectively pass on the ownership of that memory to another class or function. Regardless, whoever "owns" the memory needs to deal with cleaning it up. That's what your destructor needs to worry about: cleaning up any resources that that class owns.

A: If I understand you correctly, you're asking how to delete items from the vItems vector in the main container destructor?
for(std::vector<Item*>::iterator i=vItems.begin(),ie=vItems.end();i!=ie;++i)
    delete *i;

Is that what you are asking for?

A: If your vector would be
std::vector<std::tr1::shared_ptr<Item> >

, then you wouldn't need a destructor.  As it is now, the destructor would have to iterate over the vector to delete all items.  Easiest with BOOST_FOREACH.

A: It depends on how you implement it. If the items you add are managed from outside your object (i.e. the body of addItem() looks something like this: { vItems.push_back(items); }), then you won't need a destructor for that one. However, if the items are managed by the object (i.e. addItem() looks like this: { vItems.push_back(new Item(item)); }, then you will need to delete all items in the destructor, because nobody will do that for you.


text:
Q: Can I manually put an external hard disk to sleep? Is it possible to manually put an external hard disk to sleep? Right now, I've already got "Put the hard disks to sleep when possible" checkmarked in the Energy Saver preference pane, and so they should sleep after 10 minutes of inactivity, but I'm wondering if it's also possible to do this manually whenever I want.
I just bought an external hard drive and it's already spinning constantly, compared to my current external which is completely quiet, so I'm wondering if I can put it to sleep when I need to to stop it from spinning all the time.

A: Not an exact answer to your question, but when using Terminal.app there is an option to even further reduce hard disk sleep time from 10 minutes to 1 minute, with this command:
$ sudo pmset -a disksleep 1

A: On macOS, there's isn't a way to do so from the command line.  To put your drives to sleep (aka spin down) you need to send an ATA command to the drive.  This becomes problematic when trying to do this to USB drives because it would be dependent on what the USB to ATA bridge (controller in/on the USB enclosure/interface, not in the Mac) was capable of supporting (this is also why you can't reliably get SMART status from USB drives).

*

*In Linux, you can use the hdparm -Y /dev/sdX

*In Windows, there is an app called RevoSleep

*BSD has the atacontrol and camcontrol utilities to send ATA commands

*SpindownHD was a utility with Apple's CHUD tools, but it's last release was in 2006

Unfortunately, at current for macOS,  there is nothing that allows sending ATA commands directly to drives.  It would need to be embedded into something like diskutil or a 3rd party app to get the functionality you are looking for.  Though (IMO) it's unlikely because with the increasing prevalence of SSDs, there's really no more need to "spin down" a drive.
For more info, see this post on SuperUser: Ways to shut down/sleep and wake up hard drives on command?
Your best bet is to either eject the disk or set the sleep timer to 1 minute.


text:
Q: Vuetify equivalent of a UINavigationController I am trying to create a component that has a view stack much like a UINavigationController for iOS and MacOS. I need to be able to push views onto the stack and let the user pop them from the stack by pressing a back button. Does Vuetify have a web component similar to this?

A: Vuetify is a UI framework.
You need something like Vue Router


text:
Q: Google Search Result - URL mapping Searching from google.com, like www.abc.com
Search Result Rank the pages like
Title.....
Description...
www.abc.com
Title...
Description...
www.abc.com/Aboutus.aspx
Title...
Description...
www.abc.com/contactus.aspx
What I need is, when user click www.abc.com/Aboutus.aspx, it should be redirected to www.abc.com rather www.abc.com/Aboutus.aspx
How can be accomplish this?
Many Thanks

A: That seems like an odd requirement to me, and one which isn't in the interest of users. If you have a page with some information on, and the user has searched for that information and found that page, why would you want to serve them a different page?
Speaking as a user, that would frustrate me. Why do you want to frustrate potential customers?
The point of search engines is to let people get at the information they want - not to get to company home pages quicker.
If the user wants to get to the home page, I'm sure they'll be able to do so very easily from your "about us" page.


text:
Q: How do I install psycopg2 in a virtualenv that seems to not have gcc access? I'm trying to install psycopg2 in a virtualenv but it seems that I don't have access to gcc.
Is there a way to activate gcc from inside the virtualenv? If not, is there any other library that works with PostgreSQL that does not use gcc?
My attempt to install psycopg2 at A2hosting.com gives me this error:
running install
running build
running build_py
creating build
creating build/lib.linux-x86_64-2.4
creating build/lib.linux-x86_64-2.4/psycopg2
copying lib/errorcodes.py -> build/lib.linux-x86_64-2.4/psycopg2
copying lib/__init__.py -> build/lib.linux-x86_64-2.4/psycopg2
copying lib/extensions.py -> build/lib.linux-x86_64-2.4/psycopg2
copying lib/pool.py -> build/lib.linux-x86_64-2.4/psycopg2
copying lib/tz.py -> build/lib.linux-x86_64-2.4/psycopg2
copying lib/psycopg1.py -> build/lib.linux-x86_64-2.4/psycopg2
copying lib/extras.py -> build/lib.linux-x86_64-2.4/psycopg2
creating build/lib.linux-x86_64-2.4/psycopg2/tests
copying tests/types_extras.py -> build/lib.linux-x86_64-2.4/psycopg2/tests
copying tests/types_basic.py -> build/lib.linux-x86_64-2.4/psycopg2/tests
copying tests/test_psycopg2_dbapi20.py -> build/lib.linux-x86_64-2.4/psycopg2/tests
copying tests/test_dates.py -> build/lib.linux-x86_64-2.4/psycopg2/tests
copying tests/bugX000.py -> build/lib.linux-x86_64-2.4/psycopg2/tests
copying tests/test_copy.py -> build/lib.linux-x86_64-2.4/psycopg2/tests
copying tests/test_async.py -> build/lib.linux-x86_64-2.4/psycopg2/tests
copying tests/test_notify.py -> build/lib.linux-x86_64-2.4/psycopg2/tests
copying tests/extras_dictcursor.py -> build/lib.linux-x86_64-2.4/psycopg2/tests
copying tests/test_lobject.py -> build/lib.linux-x86_64-2.4/psycopg2/tests
copying tests/test_connection.py -> build/lib.linux-x86_64-2.4/psycopg2/tests
copying tests/test_green.py -> build/lib.linux-x86_64-2.4/psycopg2/tests
copying tests/bug_gc.py -> build/lib.linux-x86_64-2.4/psycopg2/tests
copying tests/dbapi20_tpc.py -> build/lib.linux-x86_64-2.4/psycopg2/tests
copying tests/__init__.py -> build/lib.linux-x86_64-2.4/psycopg2/tests
copying tests/test_quote.py -> build/lib.linux-x86_64-2.4/psycopg2/tests
copying tests/testutils.py -> build/lib.linux-x86_64-2.4/psycopg2/tests
copying tests/dbapi20.py -> build/lib.linux-x86_64-2.4/psycopg2/tests
copying tests/test_cursor.py -> build/lib.linux-x86_64-2.4/psycopg2/tests
copying tests/test_cancel.py -> build/lib.linux-x86_64-2.4/psycopg2/tests
copying tests/test_transaction.py -> build/lib.linux-x86_64-2.4/psycopg2/tests
copying tests/testconfig.py -> build/lib.linux-x86_64-2.4/psycopg2/tests
running build_ext
building 'psycopg2._psycopg' extension
creating build/temp.linux-x86_64-2.4
creating build/temp.linux-x86_64-2.4/psycopg
gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fPIC -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.4 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x080309 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/usr/include/python2.4 -I. -I/usr/include -I/usr/include/pgsql/server -c psycopg/psycopgmodule.c -o build/temp.linux-x86_64-2.4/psycopg/psycopgmodule.o -Wdeclaration-after-statement
unable to execute gcc: Permission denied
error: command 'gcc' failed with exit status 1

UPDATE:
I've discovered that the machine on which I'm trying to install psycopg2 doesn't have PostgreSQL. The webhosting company has PostgreSQL installed on another server. What can be done in a situation like this?

A: You don't need PostgreSQL, you need the PostgreSQL client libraries and development files. You can try asking the host to install them, or failing that you can build it on a similar platform and copy the package manually.


text:
Q: Mysql, SELECT only available companies and exclude the rest of the companies by one or more datetime ranges ( when they do not work ) I need to improve the search engine of my project.
The general idea: it's a system where clients can find easy available cleaning companies.

*

*Table "clients" - general table with all clients

*Table "companies" - general table with all cleaning companies

*Table "calendar" - here all companies can specify one or many different DATETIME ranges when they DO NOT take client requests

Here are the mysql tables
http://sqlfiddle.com/#!9/5c7034/1
The system has almost ~ 10000 clients and ~ 500 companies.
By default, all companies are always available for client requests. That's why we are using this calendar, where the companies can disable ( put date time ranges in future as 'not working' ) and the clients wont be able to make request if a company already specified that their services are closed on the choose date time period by the client.
If a client wants cleaning services on 2017-10-24 12:00:00 ( for 2 hours )
1. he choose date : 2017-10-24 and start time 12:00:00
2. he specifies duration : 2 hours
3. the system must find all companies which are available between 2017-10-24 12:00:00 and 2017-10-24 14:00:00.
AS you can see the example data in table "calendar" now, the only available result should be Company 2, because they are working on the date choosen by the client ( 2017-10-24 12:00:00 ) .
My problem is that I'm forced to:

*

*To find all companies who cannot take the client request between 2017-10-24 12:00:00 and 2017-10-24 14:00:00

*To use the result of the first query with NOT IN where clause and finally to find the available companies.

SELECT
    *
FROM
    companies
WHERE
    companies.company_id NOT IN
(
    **SELECT
        calendar.company_id
    FROM
        calendar
    WHERE
        calendar.not_available_from = '2017-10-24 12:00:00'
    OR
        calendar.not_available_from = '2017-10-24 14:00:00'**
);

So, is there a better way to find these available companies ?
All of the companies right now are constantly modifying their closed( not working ) datetime ranges in future and this table calendar is huge, but without this table I cannot exclude the companies who cannot handle client requests.
Any advice about the current logic is very welcome.
Obligatory things to keep: all companies are always available by default for the clients and that's why they need manually to keep up to date when they do not want to work.
Everything else can be modified ...
Thanks!

A: If I understand correctly, you can do:
SELECT c.*
FROM companies c
WHERE NOT EXISTS (SELECT 1
                  FROM calendar ca
                  WHERE ca.company_id = c.company_id AND
                        ca.not_available_to >= '2017-10-24 12:00:00' AND
                        ca.not_available_from <= '2017-10-24 14:00:00'
                 );

This is the correct way to implement an overlap.  The above assumes that the end points are inclusive.  So if a not-available period ends at 2017-10-24 12:00:00, then then the company would be filtered out.  Change <= to < and >= to > for exclusive ranges.
For performance, you want an index on calendar(company_id, not_available_to, not_available_from).

A: You may use an outer join and then check for the NULL values like this
select cs.company_id,
       cs.company_name
from companies cs
left join calendar cr on cr.company_id = cs.company_id AND
                         cr.not_available_to >= '2017-10-24 12:00:00' AND
                         cr.not_available_from <= '2017-10-24 14:00:00'
where cr.company_id is null

As mentioned by Gordon the following index is necessary on calendar table for reasonable performance:
create index ix_calendar_company_notavailable on
      calendar(company_id, not_available_to, not_available_from)

The InnoDB already has a clustered index on companies.company_id since it is a primary key, therefore, the query should be quite fast.

A: --To find all companies who cannot take the client request between
--2017-10-24 12:00:00 and 2017-10-24 14:00:00
SELECT *
  FROM #companies
 WHERE company_id
        NOT IN ( --overlap of start time/end time with
                 --availability and 'not working'
                 SELECT company_id
                   FROM #calendar
                  WHERE not_available_from <= '2017-10-24 14:00:00' --@endtime
                    AND not_available_to >= '2017-10-24 12:00:00'   --@starttime
                    AND type = 'not working'
               )

The above selects the company names that do not have an unavailability overlapping the start and endtime where the record type is 'not working'. I put 'not working' because I notice in the sqlfiddle you are putting client requests in the same table and putting a record type 'client request'.
Anyway...
In your question you ask if there's a different way to do it other than NOT IN.
 You could do NOT EXISTS equivalent, but the Actual Execution Plan is identical hence performance is identical.

A: Try using between on dates when you can and notice that it gets different results too.
SELECT
    *
FROM
    companies
WHERE
    companies.company_id NOT IN
(
    SELECT
        calendar.company_id
    FROM
        calendar
    WHERE
        calendar.not_available_from BETWEEN '2017-10-24 12:00:00' AND '2017-10-24 12:00:00'
    OR
        calendar.not_available_from BETWEEN '2017-10-24 14:00:00' AND '2017-10-24 14:00:00'
);

This thread linked below has a good explanation of why using between is good, and is generally informative. Aside from what they say and they example they give, MySQL and SQL-Server (to my knowledge) will also handle date formats much better if you use between.
Why use the BETWEEN operator when we can do without it?


text:
Q: How to get the Term-Doc frequency from many fields combined? I have written an index with lucene, from a collection of documents. My documents have 2 fields and were added to the index like so:
Document doc = new Document();
doc.add(new TextField("Title", "I am a title", Field.Store.NO));
doc.add(new TextField("Text", "random text content", Field.Store.NO));
indexWriter.addDocument(doc);

I want to read the index and get the Term-Frequency for every (term, doc) pair.
If I only had 1 field, lets say "Text", I would use the following code:
IndexReader indexReader = ...;
Terms terms = MultiFields.getTerms(indexReader, "Text"); // get all terms of this field
TermsEnum termsIterator = terms.iterator();
BytesRef term;
// For every term in the "Text" Field:
while ((term = termsIterator.next()) != null) {
    String termString = term.utf8ToString(); // The term
    PostingsEnum postingsEnum = MultiFields.getTermDocsEnum(indexReader,
        "Text", term, PostingsEnum.FREQS);
    int i;
    // For every doc which contains the current term in the "Text" field:
    while ((i = postingsEnum.nextDoc()) != PostingsEnum.NO_MORE_DOCS) {
        Document doc = indexReader.document(i); // The document
        int freq = postingsEnum.freq(); // Frequency of term in doc
    }
}

However, since I have 2 fields ("Title" and "Text"), in order to get the total term-frequency for a (term, doc) pair, I firstly need to get every (term, doc) pair frequency for the "Title" field and save them in memory, then get every (term, doc) pair frequency for the "Text" field and combine them manually for each unique (term, doc) pair that was returned.
So, this method is very likely to iterate through the (term, doc) pairs more than once, because the same (term, doc) pair could exist in both "Title" and "Text" fields (if a document had the same term in his "Title" and "Text").
Is there any way with Lucene API to iterate through all fields combined instead ? (to avoid iterating through the same pairs more than once)

A: You have two fields and you need the frequencies of all token per document as sum of the frequencies per field and document.
Please remember that BytesRef (and Integer) implements the Comparable-interface: Your stream of tokens (TermsEnum) and each associated stream of documents (PostingEnum) are ordered.
So you have two times to merge two ordered streams. You don't have to save more than each head of the streams in memory.


text:
Q: Change order user tabs through div elements Below is the code I'm using in my ASP MVC view. I'd like the tab order to go from the first to last text box inputs in the fieldsets below in this order:

*

*AgentTypeFields

*BasicFields

*AddressFields

*CommunicationFields

*DistributionFields

*DRMFields

*DSSAgentIds

*DSSFields

Right now when the focus of the page is on the first input box of AgentTypeFields, which is the fieldset in the leftDiv of the topDiv. When the user is done tabbing through this fieldset, the focus then shifts to the first input of DistributionFields. Basically I need the tab index to move from the leftDiv fieldsets going from the topDiv, middleDiv, to the bottomDiv, and then back up through the rightDiv elements of the same top/middle/bottom divs.
I've tried puttint a tabindex property on the div and fieldset elements but this simply puts the focus on the element itself, not the inputs contained within it. Not the greatest when it comes to HTML/CSS so any suggests/help would be greatly appreciated. Thanks!

    @Html.HiddenFor(model => model.CreatedDate)
    @Html.HiddenFor(model => model.CreatedOperator)
    @Html.HiddenFor(model => model.ReferenceNumber)
    @Html.HiddenFor(model => model.ReferenceType)
    @Html.HiddenFor(model => model.ExtRepType)
    @Html.HiddenFor(model => model.Region)
    @Html.HiddenFor(model => model.INDDist)

            <fieldset id="AgentTypeFields" style="width: 400px;">...</fieldset>

            <fieldset id="DistributionFields" style="width: 400px;">...</fieldset>

            <fieldset id="BasicFields" style="width: 400px;">...</fieldset>

            <fieldset id="DRMFields" style="width: 400px;">...</fieldset>

            <fieldset id="AddressFields" style="width: 400px;">...</fieldset>

            <fieldset id="CommunicationFields" style="width: 400px;">...</fieldset>

            <fieldset id="DSSAgentIds" style="width: 400px;">...</fieldset>

            <fieldset id="DSSFields" style="width: 400px;">...</fieldset>

        <input type="submit" value="Save" />

        @Html.ActionLink("Back to Search", "Index", "Agent")

A: Put the tabindex on the first field in those fieldsets rather than the fieldset itself. However, this is really going to screw with the blind individuals who come to your site.


text:
Q: Add gutters between columns in Bootstrap 5 I am trying to add gutters between my columns in Bootstrap 5. I followed the documentation as to how to implement it but for some reason I cannot add gutters between my columns.
I'm using g-3 to add gutters to my row and per the documentation this should add gutters in between my rows and columns. I've tried using gap-3 but then it moves the 3rd column to the next row.
What am I missing here?

Services

Lorem ipsum, dolor sit amet consectetur adipisicing elit.

Title Here

Some more info here

Title Here

Some more info here

Title Here

Some more info here

Title Here

Some more info here

Title Here

Some more info here

Title Here

Some more info here

A: So this issue was that I had to create another div inside my col div which should have the classes of bg-white border rounded p-3 and it should not be inside the col div.
check the code down below.
I replaced this

Title Here

Some more info here

With this

Title Here

Some more info here

A: Your first column is taking the entire row - all 12 columns.  If you change the first column to
 does it give what you want?


text:
Q: Very slow Riak writes and this error: {shutdown,max_concurrency} On a 5-node Riak cluster, we have observed very slow writes - about 2 docs per second. Upon investigation, I noticed that some of the nodes were low on disk space. After making more space available and restarting the nodes, we are see this error (or something similar) on all of the nodes inside console.log:
 2015-02-20 16:16:29.694 [info] <0.161.0>@riak_core_handoff_manager:handle_info:282 An outbound handoff of partition riak_kv_vnode 182687704666362864775460604089535377456991567872 was terminated for reason: {shutdown,max_concurrency}

Currently, the cluster is not being written to or read from.
I would appreciate any help in getting the cluster back to good health.
I will add that we are writing documents to an index that is tied to a Solr index.
This is not critical production data, and I could technically wipe everything and start fresh, but I would like to properly diagnose and fix the issue so that I am prepared to handle it if it should happen in a production environment in the future.
Thanks!


text:
Q: I can't stream live video from youtube, but normal video are working in android I can't stream live video from youtube, but normal video are working in android.
    public class ShowYoutube extends YouTubeFailureRecoveryActivity {

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

    YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
    youTubeView.initialize(Key, this);
  }

  public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
      boolean wasRestored) {
    if (!wasRestored) {
      player.cueVideo("fsDUeIkbePQ");
    }
  }

  @Override
  protected YouTubePlayer.Provider getYouTubePlayerProvider() {
    return (YouTubePlayerView) findViewById(R.id.youtube_view);
  }

}

But using this code i can stream normal video files but not live youtube video files.

A: try VideoView instead to stream videos a sshown below:
        videoView = (VideoView)findViewById(R.id.app_video_view);
    videoView.setOnCompletionListener(new OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {
            // TODO Auto-generated method stub
            VideoStreamActivity.this.finish();
        }
    });

    MediaController mc = new MediaController(VideoStreamActivity.this);
    videoView.setMediaController(mc);
     String str = "VIDEO URL";
        Log.d(TAG, "url: "+str);
        Uri uri = Uri.parse(str);

        videoView.setVideoURI(uri);

        videoView.requestFocus();
    videoView.start();

and in your layout file add this:
<VideoView
        android:id="@+id/app_video_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentTop="true"
        android:layout_centerInParent="true" />

Let me know if it works or not.
Regards,
Tahir

A: I've got a slightly different problem. I am able play some of the live videos. I've looked into the stream details and I haven't found anything. I have something in mind that might cause "unsupported video format" - DRM. Some of the videos can have DRM implemented in some way that cannot be verified by the api. The other possible reason: the live video id that you'd like to play does not exist in a valid video format(This is the most reasonable cause for the error but I could not find any related docs).


text:
Q: JDBC connection to remote server without installing SQL Server Say I have a small inventory based software in Java connected to a SQL Server database. SQL server is not installed on that place where it is to be deployed and those people hav nothing to do with databases. We know that it takes a lot of time to install SQL Server.
Simply speaking, I need a light software which can be installed easily and provide JDBC connectivity to my Java application.

A: Use an embedded version of java Derby. It runs inside the JVM and does not need installation.
This works assuming of course that the you're not trying to connect to a common database across different client instances. Each instance runs it's own Derby and persists data to a persistence store.


text:
Q: GNU Screen hangs in ConEmu I just did an update of Cygwin on a Windows 7 box.  When I open ConEmu to a Cygwin Bash terminal, everything seems fine.  However, if I run GNU Screen, the terminal locks up until I forcibly kill screen.exe using a Task Manager.  This was not happening before the update.
I tried other updates with other mirrors but it doesn't seem to help.  I tried removing my .screenrc file, it also didn't help.  I tried downgrading my version Screen to 4.3.1-1 and it didn't help either.  I tried the newest version of ComEmu and it didn't help.  I tried running Screen from MinTTY and it works okay (but MinTTY has some other problems with Screen so it's not a good solution for me).
I had another Window 7 machine and it also broke as soon as I updated Cygwin.  It must be some sort of new version of some sub-library that causes this issue.  Anyone have this same issue?  Any ideas on how to fix it?

A: I did test it with cmd.exe and and everything is fine.  It's probably something wrong with ConEmu.  There really is nothing special about my setup, so anyone reading this is welcome to try it themselves.
I just ended up switching to ConsoleZ. Also, This blog showed how to get started.  It took five minutes to download and install.  Problem solved.
It's too bad ConEmu is a really wonderful product and full of features, but all I really need is Screen to work again.  Maybe I'll try again later.


text:
Q: IF statement not resolving correctly The code outputs "I will be going to Los Angeles. The journey will be a distance of 300 miles. We will need to make 2 stop." when it should pull the plural or singular of the word "stop" depending on the number defined in my IF statement (in that case, it should be the plural). I'm guessing that the IF doesn't work as I expected it to because of the way I have constructed the class. Any help fixing it would be appreciated.
class trip {

  public $destination;
  public $distance;
  public $unit;
  public $stops = null;
  public $transport = null;

  function __construct($destination, $distance, $unit, $stops, $transport) {
    $this->destination = $destination;
    $this->distance = $distance;
    $this->unit = $unit;
    $this->stops = $stops;
    $this->transport = $transport;
  }

  function getTrip() {
    $a = "I will be going to " . $this->destination . ". ";
    $a .= "The journey will be a distance of " . $this->distance . " " . $this->unit . ". ";
    $a .= "We will need to make " . $this->stops;
    if ($this->stops = 1) {
      $a .= " stop.";
    } else {
      $a .= " stops.";
    }
    $a .= "\n";
    echo $a;
  }
}

$first = new trip('Los Angeles',300,'miles',2,'airplane');
$first->getTrip();

A: You seem to have overlooked a small detail.
if ($this->stops = 1)

should be
if ($this->stops == 1)

A: your IF statement seems wrong.
In fact, it should be:
if( $this->stops == 1){ ...
You have to use two == signs to make a comparison, otherwise is an assignment. So in your case, one = sign will not really test the condition you expect.


text:
Q: Box doesn't seem to separate user name into FirstName and LastName When a user signs up for Box, he is asked to enter FirstName and LastName as separate fields. But Box doesn't keep these as separate fields, so when our app queries the Box API to get a user's name, we get both the FirstName and the LastName as one concatenated string as FirstName, with nothing in LastName.
We confirmed this problem simply by looking at https://app.box.com/profile: if you want to edit your user name, you get the entire name within a single text box.
This presents problems for us in terms of mailing our users: we want to address people by FirstName since this greatly increases the odds that someone will read their email e.g. "Hi John" rather than "Hi John Smith".
This problem needs to get solved with Box, rather than a third-party app, because there is no easy way for an app to write a regex that can accurately split a string into FirstName and LastName.
Latin American names, for example, frequently have double first names and double last names, e.g. "Maria Anna Ramirez Fernandez". A third-party app cannot simply take the first part of the string ("Maria") and get a complete FirstName out of this; we need Box to tell us that "Maria Anna" is the FirstName and "Ramirez Fernandez" is the "LastName".


text:
Q: Multiple Objective-C objects for iPhone app? I'm sure this is going to sound very weird, but I'll ask anyway. I have made multiple working applications for the iPhone, but I have to add everything to the original view controller. If I don't do so, the app crashes. Here is my example:
In the view controller:
- (IBAction) someAction: (id) sender {
    NSLog(@"lajkrbgl");

}

This works just fine. But, if I do the "Add File" and I choose "Objective-C Class", and put the same code in, the app just crashes whenever I press the button. How can I add more objects and have them function like they do for OS X?
EDIT: Below are the steps I took to make the new object. These steps worked for me when making an OS X application.

*

*I right clicked on the "Classes" folder in Xcode.

*I selected "Add > New File".

*I selected "Objective-C Class" and "NSObject".

*I made an action, "- (IBAction) someAction: (id) sender;"

*In Interface Builder, I connected the action to a UIButton, and used "Touch Up Inside".

*I clicked the "Build and Run" button.

After that, I clicked the button, and the application quit (almost as if i clicked the Home button). I did not get any errors. I then decided that it was because I didn't put the code in for the action, so I did that next.
- (IBAction) someAction: (id) sender; {
    NSLog(@"lajkrbl");
}

Even after this, it crashed in the exact same way, and without an error message. Can anybody see what I did wrong?
EDIT2: I just got Xcode 4 running, and when I clicked the button, it told me that this code is giving me the problem (I put "**" before the line that had the green line).
int main(int argc, char *argv[]) {

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    **int retVal = UIApplicationMain(argc, argv, nil, nil);
    [pool release];
    return retVal;

}
How in the world did that go wrong? That is created by Xcode when I make projects!

A: It is indeed different in iOS. This note in the View Controller Programming Guide:

Whenever you add objects to the top-level of your nib file, you should always connect those objects to outlets somewhere else in the nib file. [...] because top-level objects are retained and then autoreleased, if you did not retain the object, it might possibly be released before you had a chance to use it.

and, more definitively, Table 1-1 in the Resource Programming Guide:

Objects in the nib file are created with a retain count of 1 and then autoreleased. [...] If you define outlets for nib-file objects, you should always define a setter method (or declared property) for accessing that outlet. Setter methods for outlets should retain their values, and setter methods for outlets containing top-level objects must retain their values to prevent them from being deallocated.

both indicate that you should add an IBOutlet for the object which implements the button's action method to your view controller, and have the view controller retain that object (a property makes this easy):
@interface ButtonCrashViewController : UIViewController {
    IBOutlet ButtonActioner * myButtonActioner;
}

@property (retain, nonatomic) IBOutlet ButtonActioner *myButtonActioner;

@end

In ButtonActioner.m:
- (IBAction)someAction:(id)sender {
    NSLog(@"This didn't crash!");
}

You then hook the view controller's outlet and the button's action up as usual in Interface Builder.

A: If you're connecting an IBAction to a method in some discrete object, that object needs to exist when the action is called. Make sure that your object that contains the IBAction code has been instantiated and is retained by whatever entity (likely a viewcontroller) contains the button.
This will probably result in that entity retaining an instance variable of type MyObject, where MyObject is your NSObject subclass containing the IBAction code.
Code example:
MyObject.m contains:
- (IBAction) someAction: (id) sender {
    NSLog(@"lajkrbgl");
}

MyViewController.xib contains a UIButton whose TouchUpInside is linked to someAction.
MyViewController.h contains:
@interface MyViewController : UIViewController {
    MyObject *myObject_;
}

MyViewController.m contains (in initWithNibName:bundle:):
myObject_ = [[MyObject alloc] init];

You could optionally make myObject a property to make this all way prettier, but that's your call.


text:
Q: Ubuntu one (application) on ubuntu software center I went on the ubuntu software center to get ubuntu one (application), found it and clicked it. Then shows "NOT FOUND   There isn't a software package called "ubuntuone-control-panel-qt" in your current software sources."
I have ubuntu 14.04 LTS.

A: Ubuntu one has ended it no longer exists. I recommend dropbox.
https://www.dropbox.com/install?os=lnx
or you can install dropbox from software center it is already in the repositories.


text:
Q: Camera preview failing- queueBuffer fail I am trying to write an app that continuously takes pictures. I have an activity and a preview class. I figured it out using an AsyncTask class.
private class CaptureTask extends AsyncTask<Boolean,Integer,Integer>
    {

        @Override
        protected Integer doInBackground(Boolean... arg0) {
            // TODO Auto-generated method stub
            while(running)
            {
                if(!takingPicture&&getPreviewState()&&!p.checkCamera())
                    takePicture();
                else if(!takingPicture&&!p.getPreviewState())
                    clearPic();
            }
            return picCounter;
        }
        protected void onPostExecute(Integer pics)
        {
            t.setText("Pics taken: "+pics);
        }

    }

This works fine on one device, a Motorola Droid running CM7. However, when I load it on my Samsung Epic running ACS 2.3.4, I get the following error continuously until I quit the app. There is no preview shown, just black.

11-08 11:42:28.207: ERROR/CameraHardwareSec(76): ERR(int android::CameraHardwareSec::previewThread()):overlay queueBuffer fail
  11-08 11:42:28.238: ERROR/v4l2_utils(76): Error = Invalid argument from qbuf

I've tried looking for this issue but only found a few unresolved ones.

A: If you are trying to record video do not use
mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));

to set up your media recorder even if you are working with SDK >= 8
Do the usual instead:
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);

And you will stop seeing

android::CameraHardwareSec::previewThread()):overlay queueBuffer fail

Source of this error is mismatch between size of default camera preview and MediaRecorder video size as the error disappears when you make the sizes same with:
CamcorderProfile camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
parameters.setPreviewSize(camcorderProfile.videoFrameWidth, camcorderProfile.videoFrameHeight);
mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));