text:
Q: How to purge messages for Service Bus Topic Subscription Just wondering the best way (even if via Portal, Powershell, or C#) to purge the messages off of a Service Bus Topic's Subscription.
Imagine we have a topic with 4 subscriptions, and we only want to purge the messages from one of the subscriptions.
I have a feeling the only way may be to read the messages in a while loop, but hoping for something better.
UPDATE:
Apart from using code, you can use the Server Explorer as suggested in the answer - right click subscription and purge messages:

A: You can most certainly do it via code. If you're using Service Bus SDK, you could do something like the following:
    static void PurgeMessagesFromSubscription()
    {
        var connectionString = "Endpoint=sb://account-name.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=access key";
        var topic = "topic-name";
        var subscription = "subscription-name";
        int batchSize = 100;
        var subscriptionClient = SubscriptionClient.CreateFromConnectionString(connectionString, topic, subscription, ReceiveMode.ReceiveAndDelete);
        do
        {
            var messages = subscriptionClient.ReceiveBatch(batchSize);
            if (messages.Count() == 0)
            {
                break;
            }
        }
        while (true);
    }

What this code will do is fetch messages from the subscription (100 at a time) in Receive & Delete mode so that as soon as messages are fetched, they are deleted from the subscription automatically.
I believe Service Bus Explorer tool also has the capability to purge messages. You can use that as well instead of writing the code.

A: If you have a lot of messages and can tolerate a bit of downtime on subscriber side, it might be faster to just drop the subscription and create a new one with the same name.

A: Thank you @Gaurav Mantri, I used slightly changed code without the batch option with version 5.2.0 of Microsoft.Azure.ServiceBus Nuget Package:
var connectionString = "Endpoint=sb://";
var topic = "topic";
var subscription = "subscription";
var subscriptionClient = new SubscriptionClient(connectionString, topic, subscription, ReceiveMode.ReceiveAndDelete);

subscriptionClient.RegisterMessageHandler(
  (message, token) =>
    {
     Console.WriteLine($"Received message: SequenceNumber:
             {message.SystemProperties.SequenceNumber}");

      return Task.CompletedTask;
     },
   (exceptionEvent) =>
    {
     Console.WriteLine("Exception = " + exceptionEvent.Exception);
     return Task.CompletedTask;
    });


text:
Q: How to transition between Activity classes in Android?
Possible Duplicate:
How to save user state in Android?

My application's first activity is login1 in which i am asking user to enter password,confirm password,security question and answer(security question and answer is taken in case of retrive password to user in the form of sms or email.)
second activity is login2  having only one field to enter that is password.
third activity is main activity of my application that is setting.
Now the question is that when user enters information of all fields which are in first activity login1 then he should move to directly to setting activity.
if  user close application after setting password and  open it again he must get second activity that is login2 where he just have to enter password to login.
if he remove that application from phone and then install again he must get first activity that is login1  .
So tell me code for doing it .please replay.

A: You could add a 0th activity to your list as a splashscreen, or license agreement, or something, and there you could write code to chose proper activity (1st or 2nd).
Or you can merge 1st and 2nd activities to a single activity with the help of ViewFlipper and write your "choose code" there.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to show condition for travelling wave solution to Fisher's equation? I don't know how to to do this one part of a problem from my (non-PDE) math course. It's about the Fisher's equation. I've never encountered it before.
$$\frac{\partial P}{\partial t} = D \frac{\partial^2 p}{\partial x^2} + ap(1-p) $$
How do I (1) show that the travelling wave solutions to this ($S(z)=p(x,t)$, where $z=x-vt$) must satisfy:
$$\frac{dP}{dz} = S$$
$$\frac{dS}{dz} = -\frac{a}{D} P(1-P) - \frac{v}{D}S$$
and (2) deduce the minimum travelling speed.
Thanks.


text:
Q: Java's instanceof odd behavior Can anybody explain why the if statement below evaluates false?
public void addShapeToWhiteboard(PolyLine shape)
{
   Window.alert("2");
   if(shape instanceof PolyLine)
   {
      Window.alert("3");
      this.whiteboard.add((PolyLine)shape);
      Window.alert("3.5");
   }
   this.whiteboard.draw();
   Window.alert("4");
}

it takes in a "PolyLine" object, but instanceof returns false because I get an alert of "2" followed by an alert of "4" and have no clue how it's even possible.

A: Maybe shape is null? instanceof returns false in such a case.

A: I bet shape is passed as null, and null is not an instance of any class.


text:
Q: Eclipse C++ Indexing Boost Takes Forever If I include both headers:
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/topological_sort.hpp>

It takes forever. In this way, what I am doing is everytime I have to comment one by one, for example:
#include <boost/graph/adjacency_list.hpp>
//#include <boost/graph/topological_sort.hpp>

and let it index as showed in the Figure bellow. Then I remove the comment and let it index for the second one.

What should I do to fix it? I tryed everything (even other eclipse versions).

A: Seems like updating gcc/g++ on Ubuntu can solve the problem.
I don't know the reason but, seems like that with the gcc/g++ version that comes with Ubuntu 16.04 this problem may appear. The problem was occurring on both my laptop and at my virtual ubuntu on my desktop pc.
Before updating gcc and g++ I had to comment all the boost libraries, and uncomment one per time to allow the indexing procedure to process on per time.
After the updating, the gcc to 7.2 I made several tests with different projects and the indexing is occurring normally without problems.


text:
Q: Is there any developer tools to debug javascript error in IE 6? see my question on title.
note that I understand how to debug javascript in any browsers (including IE 7++) other than IE 6.

A: IE Developer Toolbar really good to have for any developer.
IE Developer Toolbar

A: Microsoft script debugger can provide a bit of information.
But in general - it's a pain in * * *.
Last time figured out what's wrong by gradually commenting out javascript code. :D

A: You can also use firebug lite.

A: Personally I'm a big fan of FireBug Lite which is perfect for IE.

Firebug is an extension for Firefox, but what happens when you need to test your pages in Internet Explorer, Opera, and Safari?
The solution is Firebug Lite, a
  JavaScript file you can insert into
  your pages to simulate some Firebug
  features in browsers that are not
  named "Firefox".
Firebug Lite creates the variable
  "firebug" and doesn't affect or
  interfere with HTML elements that
  aren't created by itself.

A: Firebug Lite has helped me out quite a lot =)


text:
Q: Razorpay quick payment integration with contact form 7 I tried to send the form via E-mail after customer done the successful payment via Razorpay.
I used the Razorpay quick payments plugin for payment gateway and contact form 7, the issue is there will be two buttons for Payment button (Razorpay) and submit button (to send a mail-form submission) and I would like to have a single button as Payment.
When the user done the payment the user filled form should be triggered to send a mail as we configured in contact form 7.
Please give a solution, how can I get it


text:
Q: Cast to ObjectId failed for value \'param\' when using a certain route declaration above other routes in Mongoose and MongoDB When I place the following function in front of my other route declarations it causes an error:
postRouter.get('/:postId', (req, res, next) => {
  Post.findOne({ _id: req.params.postId })
    .populate([
      {
        path: 'comments',
        options: { sort: { createdAt: 1 } },
        populate: { path: 'user' },
      },
    ])
    .exec((err, populatedPost) => {
      if (err) {
        res.status(500);
        return next(err);
      }
      return res.status(200).send(populatedPost);
    });
});
// these all receive errors when being called
postRouter.get('/popular', getPostsByPopularity);
postRouter.get('/user', getCurrentUserPosts);

the error:
// for /popular endpoint
    "errorMessage": "Cast to ObjectId failed for value \"popular\" (type string) at path \"_id\" for model \"Post\""

//for /user endpoint
    "errorMessage": "Cast to ObjectId failed for value \"user\" (type string) at path \"_id\" for model \"Post\""

//for endpoint that doesnt exist in my route declarations /anything
    "errorMessage": "Cast to ObjectId failed for value \"anything\" (type string) at path \"_id\" for model \"Post\""

every other path that is not defined gets the same error because of this GET method. Why does ('/:postId') act as the catch-all? It is acting the same way '*' would act. When it's placed below the others everything seems to be fine except the routes that should be returning 404 instead they are returning errors.


text:
Q: Simplifying code for testing directory content/files I have the following test code which checks the content of a particular directory structure
assertThat(install_should_not_fail).isDirectory().satisfies(isnf -> {
  assertThat(new File(isnf, "maven-metadata-local.xml")).isNotEmpty();
  assertThat(new File(isnf, "1.0")).isDirectory().satisfies(v10 -> {
    assertThat(v10).satisfies(file -> {
      assertThat(new File(file, "install_should_not_fail-1.0.jar")).isNotEmpty();
      assertThat(new File(file, "install_should_not_fail-1.0.pom")).isNotEmpty();
      assertThat(new File(file, "_remote.repositories")).isNotEmpty();
    });
  });
});

and I have several tests which do very similar things. The question is: Can that be made simpler  (I know I could refactor out a method which contains exactly that code) but I'm interested more in getting the above code simpler using AssertJ if it's possible?

A: I would suggest an approach that does not use satisfies to avoid the nested blocks:
assertThat(install_should_not_fail).isDirectory();
assertThat(new File(install_should_not_fail, "maven-metadata-local.xml")).isNotEmpty();

File v10 = new File(install_should_not_fail, "1.0");
assertThat(v10).isDirectory();
assertThat(new File(v10, "install_should_not_fail-1.0.jar")).isNotEmpty();
assertThat(new File(v10, "install_should_not_fail-1.0.pom")).isNotEmpty();
assertThat(new File(v10, "_remote.repositories")).isNotEmpty();

I feel this makes the code a bit lighter and more readable (to me at least).
Moreover, I think this is a good candidate for soft assertions so that all the assertions errors are reported instead of failing at the first one.

A: If you don't need to check whether the files are non-empty, Files::fileNamesIn may come handy. You could do something like:
assertThat(Files.filesNamesIn(dir, /* recursive */ true)).contains(
  basePath + "/maven-metadata-local.xml",
  basePath + "/1.0/install_should_not_fail-1.0.jar",
  basePath + "/1.0/install_should_not_fail-1.0.pom",
  basePath + "/1.0/_remote.repositories")

Otherwise you may refactor this pattern into your own custom assertion. For example, here is an assertion that verifies that the given paths represent non-empty, readable files inside a directory:
public class MyAssertions extends Assertions {
    public static MyFileAssert assertThat(File actual) {
        return MyFileAssert.assertThat(actual);
    }
}

public class MyFileAssert extends AbstractFileAssert<MyFileAssert> {
    public MyFileAssert(File actual) {
        super(actual, MyFileAssert.class);
    }

    public static MyFileAssert assertThat(File actual) {
        return new MyFileAssert(actual);
    }

    public MyFileAssert containsReadableNonEmptyFiles(String... paths) {
        isDirectory();

        List<String> nonExistent = new ArrayList<>();
        List<String> nonFiles = new ArrayList<>();
        List<String> nonReadable = new ArrayList<>();
        List<String> empty = new ArrayList<>();

        for (String path : paths) {
            File file = new File(actual, path);

            if (!file.exists()) {
                nonExistent.add(path);
                continue;
            }

            if (!file.isFile()) {
                nonFiles.add(path);
                continue;
            }

            if (!file.canRead()) {
                nonReadable.add(path);
                continue;
            }

            if (file.length() == 0) {
                empty.add(path);
            }
        }

        if (!(nonExistent.isEmpty() && nonFiles.isEmpty() && nonReadable.isEmpty() && empty.isEmpty())) {
            StringBuilder failMessage = new StringBuilder()
                    .append("Expected directory '")
                    .append(actual)
                    .append("' to contain the following readable, non-empty files:\n");

            for (String path : paths) {
                failMessage.append("  ")
                        .append(path)
                        .append("\n");
            }

            if (!nonExistent.isEmpty()) {
                failMessage.append("The following files don't exist:\n");

                for (String path : nonExistent) {
                    failMessage.append("  ")
                            .append(path)
                            .append("\n");
                }

            }

            // The rest left out for brevity.

            failWithMessage(failMessage.toString());
        }

        return this;
    }
}

The example usage of the above is as follows:
assertThat(install_should_not_fail).containsReadableNonEmptyFiles(
  "maven-metadata-local.xml",
  "1.0/install_should_not_fail-1.0.jar",
  "1.0/install_should_not_fail-1.0.pom",
  "1.0/_remote.repositories")

You may read more about AssertJ's custom assertions here.

A: Late answer but could always help future users, since 3.13.0 of assertj you have can use isEmptyDirectory and isDirectoryContaining to check directory content and since 3.19.0 isEmptyFile that checks if your file is empty


text:
Q: Oracle Date Time strig format I have the following oracle table, where datetime is in a single column & has datatype as string
f_ID      f_type    f_date

1001      A         3/30/14 12:20:00 PM

1001      B         3/30/14 10:20:00 AM

1002      A         2/3/14 11:0:00 AM

1002      B         2/3/14 9:00:00 AM

1003      A         2/13/14 10:00:00 AM

1003      B         12/13/14 10:00:00 AM

1111      B         12/13/14 10:00:00 AM

I wish to calculate average time taken for all shipments which have count > 1. So time difference in shipment of 1001 is 2 hours, 1002 is 2 hours, 1003 is 10 Months (303 x 24=7272) hours. 1111 has count =1 so it can be excluded from average.
So the average result should be (2+2+7272)/3 = 2425.33 hours.
How do I query that?

A: This one should work:
WITH t AS
    (SELECT f_ID, ABS(b.f_date-a.f_date)*24 AS duration
    FROM my_table a
        JOIN my_table b USING (f_ID)
    WHERE a.f_type = 'A'
        AND a.f_type = 'B')
SELECT AVG(duration)
FROM t;


text:
Q: Ubuntu 15.10 Unity white border around windows I am using 15.10, and out of blue i started getting a whitish border around my window (all the windows i open).
I have nVidia graphics card with a updated driver.
Everything was fine, no changes were made to any X11 or any system file. Rebooted the machine too. any help ?


text:
Q: c++: how to make a tcp client listen on a socket in non-blocking way I'm trying to have a TCP-Client that listens on a socket but without being blocked by it.
meaning - if something is waiting, read it.
if not, do something else and come back and check later.
I couldn't find any reference to this question.
The best thing, obviously would be to have a "peek" ability the client knows if something is waiting, and how many bytes.
I guess this capability is not implemented in TCP, but if there anything that might help me with that?


text:
Q: How to wrap an element in a html string var? If I use the following code:
var output = '
468 (58247)
';
var span = $(output).find('span.bus-number').text();
console.log(span);

I can see the value

468 (58247)

in the console, but if I try to use the wrap() method with the following code:
var output = '
468 (58247)
';
$(output).find('span.bus-number').wrap('');
console.log(output);

I can't obtain this html code:

468 (58247)

How can I obtain the string with the wrapped element?

A: You are not updating the string just updating the jQuery object so grab HTML content from jQuery object using html() method.

var output = '
468 (58247)
';
// create a div element with html content
output = $('
', {
    html: output
      // get span
  }).find('span.bus-number')
  // wrap the span
  .wrap('')
  // back to previous selector
  .end()
  // get the html content
  .html();

console.log(output);

Or use outerHTML property of dom element.

var output = '
468 (58247)
';
// create jQuery object
output = $(output)
  // get span element
  .find('span.bus-number')
  // wrap span with b
  .wrap('')
  // back to previous selector and get dom object
  // using [0] after get html content from dom
  .end()[0].outerHTML;

console.log(output);

A: You can use the html() function.
Note that the html() function returns the INNER html of the element, so you need to wrap it with another element to get the html:

var output = '
468 (58247)
';
var span = $(output).find('span.bus-number').text();
console.log(span);

var span = $(output).find('span.bus-number').wrap('');
console.log(span.parent('b').html());
console.log(span.parents('div.info').html());
console.log($('
').append(span.parents('div.info')).html());

A: Because output is just a string which is immutable.
For example you can do
var output = '
468 (58247)
';
$output = $(output);
$output.find('span.bus-number').wrap('');
console.log($output.text());


text:
Q: Unable to archive project I am unable to archive my Swift project. When it's archiving, it fails at 90% of the progress. Showing the following error.

The project runs well in the simulator and on my device. But suddenly i am getting this error when archiving... It all worked well before.. Does anyone have any idea?

A: The path to the binary contains spaces ([...]/ArchiveIntermediates/Trusti - Release/[...]). This should be the problem. The error message displays the path cut before the first space.
I think you should use another product name, and adapt it in InfoPlist.strings if necessary.

A: I got this problem with cocoapods, you should edit the file "YourTarget-framework.sh" in Pods > Target Support Files > Pods-Your Target.
You need to locate this line:
local code_sign_cmd="/usr/bin/codesign --force --sign {EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements "$1""
Replace it by :
local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements '"$1"'"


text:
Q: Remove many UIImages with a single button I am using a source code to load/rotate/zoom/move a UIImage from this blog.
I need to remove all the images at once with a single button, I tried this:
[holderView removeFromSuperview];

But it only delete the last one created not all of them.
EDIT
I have another subviews in the app that i don't want them to be removed "Buttons, UIImageView, UIScrollView ..etc".

A: Try this code
NSArray *viewsToRemove = [self.view subviews];
for (UIView *v in viewsToRemove)
{
    [v removeFromSuperview];
}

Hope it helps you
EDIT :-
More efficient removal
NSArray *viewsToRemove = [self.view subviews];
    for (UIView *v in viewsToRemove)
    {
        NSArray *imagesToRemove = [v subviews];
        for (UIImageView *i in imagesToRemove)
        {
            [i removeFromSuperview];
        }
        [v removeFromSuperview];
    }

SECOND EDIT :-
NSArray *viewsToRemove = [self.view subviews];
    for (UIView *v in viewsToRemove)
    {
        NSArray *imagesToRemove = [v subviews];
        for (UIImageView *i in imagesToRemove)
        {
            i.image = nil;
        }
        //[v removeFromSuperview];
    }

A: I think you can use NSMutableArray to store list of UIView's
Embed this code to .h
@property (nonatomic, retain) NSMutableArray *imgList;

Im .m file
@synthesize imgList;

After view loading
NSMutableArray *imgList = [[NSMutableArray alloc] init];

In the end of "imagePickerController:didFinishPickingMediaWithInfo:" add
[imgList addObject:holderView];

When you need to remove use
for(UIView *tempView in imgList) {
    [tempView removeFromSuperview];
}


text:
Q: Getting the javascript "document HTML DOM" info within Google Apps Script I'm having a Google spreadsheet embedded in an (Episerver) page and the spreadsheet is editable. I also have a trigger onEdit in the sheet. When running that script 'onEdit' I'd like to get the info from current page using "document.getElementsByClassName().innerHTML" to get the context of the current situation, meaning fetching the username that is currently logged in that is displayed in the  section within an element.
I'm getting the error 'document is not defined' and I got the reason. This is working just running the script as a pure javascript on the site. There is no success using GAS URLFetchApp since it not fetching the current page with the current user logged in. As I see it I have two possible options:
a) Is there anyway to use HTML DOM (document...) within Google Apps Script?
b) Can I fetch current page instead of fetching a new URL in Google Apps Script?

A: A) I think your only option here is to us the XML service.
B) I don't believe so, as the script is self contained, and doesn't have the ability to interact with the browser. You need to know a URL in order to fetch it.
However, you mention that part of what you'd like to do is fetch the user that is currently logged in, so perhaps you might be interested in the '.getActiveUser()' method? It might be a potential solution.


text:
Q: My code Thread.sleep works but not Implicit Wait? So I understood fluent and explicit waits but I could never get the implicit statements to work in the past. I managed to not deal with them using explicits but I then designed a test that was fairly simple but it would only work with Thread.sleep and I absolutely HATE that method and try to avoid it at all costs. So I attempted the implicit wait function again... fail.
The code below with Thread.Sleep works as intended and is great
package myPackages;

import java.util.concurrent.TimeUnit;

//  Unit test testing the Main User Drop Down Menu
//  This tests the following:
//      - changing status to Online, Away, Busy, Invisible via Left menu
//      - Going to Settings
//      - Logging out

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class statusTest {

  private static WebDriver driver = new SafariDriver();

  public static String HOME_URL = "http://localhost:3000";
  public static String currentUserStatus;

  private static By usernameOrEmailFieldLocator = By.id("emailOrUsername");
  private static By passwordFieldLocator = By.id("pass");
  private static By loginButtonLocator = By.cssSelector("button.button.primary.login");

  private static By openMenuLocator = By.cssSelector("span.arrow.bottom");

  private static By onlineButtonLocator = By.cssSelector("button.status.online");
  private static By awayButtonLocator = By.cssSelector("button.status.away");
  private static By busyButtonLocator = By.cssSelector("button.status.busy");
  private static By invisibleButtonLocator = By.cssSelector("button.status.offline");
  private static By userStatus = By.className("thumb");

  @BeforeClass
  public static void beforeClass() {
    driver.get(HOME_URL);
    driver.findElement(usernameOrEmailFieldLocator).sendKeys("adrian");
    driver.findElement(passwordFieldLocator).sendKeys("adrian");
    driver.findElement(loginButtonLocator).click();
  }

  @Before
  public void before() throws Exception {
    Thread.sleep(100);
    new WebDriverWait(driver, 3).until(ExpectedConditions.presenceOfElementLocated(openMenuLocator)).click();
    Thread.sleep(100);
    new WebDriverWait(driver, 3).until(ExpectedConditions.presenceOfElementLocated(onlineButtonLocator)).click();
  }

  @AfterClass
  public static void doEnd() {
    driver.quit();
  }

  private static void changeStatusTo(By statusLocator) throws Exception {
    Thread.sleep(100);
    new WebDriverWait(driver, 3).until(ExpectedConditions.presenceOfElementLocated(statusLocator)).click();
    Thread.sleep(100);
    currentUserStatus = driver.findElement(userStatus).getAttribute("data-status");
  }

  @Test
  public void setAway() throws Exception {
    changeStatusTo(awayButtonLocator);
    Assert.assertEquals("away", currentUserStatus);
  }

  @Test
  public void setOnline() throws Exception {
    changeStatusTo(onlineButtonLocator);
    Assert.assertEquals("online", currentUserStatus);
  }

  @Test
  public void setBusy() throws Exception {
    changeStatusTo(busyButtonLocator);
    Assert.assertEquals("busy", currentUserStatus);
  }

  @Test
  public void setInvisible() throws Exception {
    changeStatusTo(invisibleButtonLocator);
    Assert.assertEquals("invisible", currentUserStatus);
  }

}

but when I end up trying to use the implicit (such as below) it doesn't work. I ensure to declare it once (in this case the @beforeclass) right after the driver is declared. The tests would fail within the Before class. I included the trace stack at the very bottom on this page:
package myPackages;

import java.util.concurrent.TimeUnit;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class statusTest {

    private static WebDriver driver = new SafariDriver();

    public static String HOME_URL = "http://localhost:3000";
    public static String currentUserStatus;

    private static By usernameOrEmailFieldLocator = By.id("emailOrUsername");
    private static By passwordFieldLocator = By.id("pass");
    private static By loginButtonLocator = By.cssSelector("button.button.primary.login");

    private static By openMenuLocator = By.cssSelector("span.arrow.bottom");

    private static By onlineButtonLocator = By.cssSelector("button.status.online");
    private static By awayButtonLocator = By.cssSelector("button.status.away");
    private static By busyButtonLocator = By.cssSelector("button.status.busy");
    private static By invisibleButtonLocator = By.cssSelector("button.status.offline");
    private static By userStatus = By.className("thumb");

    @BeforeClass
    public static void beforeClass(){
        driver.manage().timeouts().implicitlyWait(100, TimeUnit.MILLISECONDS);
        driver.get(HOME_URL);
        driver.findElement(usernameOrEmailFieldLocator).sendKeys("adrian");
        driver.findElement(passwordFieldLocator).sendKeys("adrian");
        driver.findElement(loginButtonLocator).click();
    }

    @Before
    public void before() throws Exception {
        driver.findElement(openMenuLocator).click();
        driver.findElement(onlineButtonLocator).click();
    }

    @AfterClass
    public static void doEnd() {
        driver.quit();
    }

    private static void changeStatusTo(By statusLocator) {
        driver.findElement(statusLocator).click();
        currentUserStatus = driver.findElement(userStatus).getAttribute("data-status");

    }

    @Test
    public void setAway() {
        changeStatusTo(awayButtonLocator);
        Assert.assertEquals("away", currentUserStatus);
    }

    @Test
    public void setOnline() {
        changeStatusTo(onlineButtonLocator);
        Assert.assertEquals("online", currentUserStatus);
    }

    @Test
    public void setBusy() {
        changeStatusTo(busyButtonLocator);
        Assert.assertEquals("busy", currentUserStatus);
    }

    @Test
    public void setInvisible() {
        changeStatusTo(invisibleButtonLocator);
        Assert.assertEquals("invisible", currentUserStatus);
    }

}

org.openqa.selenium.NoSuchElementException: An element could not be located on the page using the given search parameters. (WARNING: The server did not provide any stacktrace information)
  Command duration or timeout: 999 milliseconds
  For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
  Build info: version: 'unknown', revision: '1969d75', time: '2016-10-18 09:43:45 -0700'
  System info: host: 'Adrians-iMac.local', ip: '10.0.2.15', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.1', java.version: '1.8.0_111'
  Driver info: org.openqa.selenium.safari.SafariDriver
  Capabilities [{applicationCacheEnabled=true, rotatable=false, databaseEnabled=true, handlesAlerts=true, version=12602.2.14.0.5, cleanSession=true, platform=MAC, nativeEvents=true, locationContextEnabled=false, webStorageEnabled=true, browserName=safari, javascriptEnabled=true, cssSelectorsEnabled=true}]
  Session ID: DADE0351-039B-4C06-BC65-05FB90E08202
  *** Element info: {Using=css selector, value=span.arrow.bottom}
      at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
      at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
      at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
      at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
      at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:216)
      at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:168)
      at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:635)
      at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:368)
      at org.openqa.selenium.remote.RemoteWebDriver.findElementByCssSelector(RemoteWebDriver.java:465)
      at org.openqa.selenium.By$ByCssSelector.findElement(By.java:430)
      at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:360)
      at myPackages.statusTest.before(statusTest.java:53)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
      at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
      at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
      at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
      at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
      at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
      at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
      at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
      at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
      at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
      at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
      at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
      at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
      at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
      at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
      at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
      at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

A: Use TimeUnit.SECONDS in your implicit waits instead of milliseconds. Quick glance through your code indicates that you have used 100 milliseconds in  implicit wait which is very nominal compared to 3 seconds assigned in explicit wait.
 driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);//waits for 3 seconds

Note:unit for explicit wait is in seconds.
 new WebDriverWait(driver, 10) //will wait for 10 seconds

1000ms=1s
You should be using 3000ms in implicit wait if timeunit HAS to be in milliseconds.


text:
Q: Firefox Add-on How to Link context menu and panel widget I want open/show my panel widget by click on my context-menu item to send some data from the dom position click to my panel.
I'm open for lot of solutions !

A: I don't know if this works but try it out, its sdk style
var panels = require("sdk/panel");
var self = require("sdk/self");

var panel = panels.Panel({
  contentURL: self.data.url("panel.html")
});

var cm = require("sdk/context-menu");
cm.Item({
  label: "Edit Image",
  context: cm.SelectorContext("img"),
  contentScript: 'self.on("click", function () {' +
                 '  self.postMessage(null);' +
                 '});',
  onMessage: function (msg) {
  panel.show({
    //position: button //set position to some anchor
  });
  }
});


text:
Q: web app on top of a REST API - how to persist data between page requests? I'm starting with web development these days and I would prefer so called client side rendering. In practice that ajax request needed data and add them to the html file ( which has already the static content, and dynamic data is added via 2nd request ). I like this approach, cause of a clean seperation between client and server. You just need to define an API and you can seperate the work.
So if you don't create the dynamic content on server side, how dou you persist data between page requests.
For example, you are on a overview for a list of adresses. You can click a button to edit a specific adress with id "25". That will requiere a new html file for that task, which will be loaded and rendered. How does the javascript included in that html file know, which adress should be loaded. How can it access the id "25"?

A: Approach 1. You don't persist anything on the client and simply reload everything as you go back and forth between the list page and the editor page. Editor page gets the id "25" and loads corresponding item either using AJAX, as you want, or on the server.
Approach 2. You do everything on the same page (SPA). You use JavaScript and probably some framework like Angular to maintain your page state.


text:
Q: Using Hadoop for storing stock market tick data
I'm having fun learning about Hadoop and the various projects around it and currently have 2 different strategies I'm thinking about for building a system to store a large collection of market tick data, I'm  just getting started with both Hadoop/HDSF and HBase but hoping someone can help me plant a system seed that I won't have to junk later using these technologies. Below is an outline of my system and requirements with some query and data usage use cases and lastly my current thinking about the best approach from the little documentation I have read. It is an open ended question and I'll gladly like any answer that is insightful and accept the best one, feel free to comment on any or all of the points below. - Duncan Krebs
System Requirements  - Be able to leverage the data store for historical back testing of systems, historical data charting and future data mining. Once stored, data will always be read-only, fast data access is desired but not a must-have when back testing.
Static Schema - Very Simple, I want to capture 3 types of messages from the feed:

*

*Timestamp including date,day,time

*Quote including Symbol,timestamp,ask,askSize,bid,bidSize,volume....(About 40 columns of data)

*Trade including Symbol,timestamp,price,size,exchange.... (About 20 columns of data)

Data Insert Use Cases - Either from a live market stream of data or lookup via broker API
Data Query Use Cases - Below demonstrates how I would like to logically query my data.

*Get me all Quotes,Trades,Timestamps for GOOG on 9/22/2014

*Get me all Trades for GOOG,FB BEFORE 9/1/2014 AND AFTER 5/1/2014

*Get me the number of trades for these 50 symbols for each day over the last 90 days.
The Holy Grail - Can MapReduce be used for uses cases like these below??

*

*Generate meta-data from the raw market data through distributed agents. For example, Write a job that will compute the average trading volume on a 1 minute interval for all stocks and all sessions stored in the database. Create the job to have an agent for each stock/session that I tell what stock and session it should compute this value for. (Is this what MapReduce can do???)

*On the classpath of the agents can I add my own util code so that the use case above for example could publish its value into a central repo or Messaging server? Can I deploy an agent as an OSGI bundle?

*Create different types of agents for different types of metrics and scores that are executed every morning before pre-market trading?
High Frequency Trading
I'm also interested if anyone can share some experience using Hadoop in the context of high frequency trading systems. Just getting into this technology my initial sense is Hadoop can be great for storing and processing large volumes of historic tick data, if anyone is using this for real-time trading I'd be interested in learning more! - Duncan Krebs

A: Based of my understanding of your requirements, Hadoop would be really good solution to store your data and run your queries on it using Hive.
Storage: You can store the data in Hadoop in a directory structure like:
~/stock_data/years=2014/months=201409/days=20140925/hours=01/file

Inside the hours folder, the data specific to that hour of the day can reside.
One advantage of using such structure is that you can create external tables in Hive over this  data with your partitions on years, months, days and hours. Something like this:
Create external table stock_data (schema) PARTITIONED BY (years bigint, months bigint, days bigint, hours int) ROW FORMAT DELIMITED   FIELDS TERMINATED BY '\t' LOCATION
  '~/stock_data'

Coming to the queries part, once you have the data stored in the format mentioned above you can easily run simple queries.
Get me all Quotes,Trades,Timestamps for GOOG on 9/22/2014
select * from stock_data where stock = 'GOOG' and days = 20140922

Get me all Trades for GOOG,FB BEFORE 9/1/2014 AND AFTER 5/1/2014
select * from stock_data where stock in ('GOOG', 'FB') and days > 20140501 and days < 20140901)

You can run any such aggregation queries once in a day and use the output to come up with the metrics before pre-market trading. Since Hive internally runs mapreduce these queries won't be very fast.
In order to get faster results, you can use some of the in memory projects like Impala or Spark. I have myself used Impala to run queries on my hive tables and I have seen a major improvement in the run time for my queries (around 40x). Also you wouldn't need to make any changes to the structure of the data.
Data Insert Use Cases : You can use tools like Flume or Kafka for inserting data in real time to Hadoop (and thus to the hive tables). Flume is linearly scalable and can also help in processing events on the fly while transferring.
Overall, a combination of multiple big data technologies can provide a really decent  solution to the problem you proposed and these solution would scale to huge amounts of data.


text:
Q: How to restrict access to some public websites I am new to cloud computing. Sorry if this is a silly question. I have created a VM from azure portal. My requirement is not to allow the user using the VM to access public website. Can anyone help me how to achieve this functionality?
Thanks

A: You probably have a Network Security Group that was created when you created the VM. In there you can specify rules for inbound and outbound data traffic.
Find the NSG and add a rule that blocks all outbound traffic from the VM. You should still be able to connect to the VM, it just can't connect anywhere. You can also make the rule only block traffic bound to the internet if you still wish for it to have access to other machines in the same virtual network.
Network Security Groups documentation: https://learn.microsoft.com/en-us/azure/virtual-network/virtual-networks-nsg

A:
My requirement is not to allow the user using the VM to access public
  website.

According to your description, you just want user can't access the public website, as we know website common listen on 80 and 443, so we can add outbound rules to deny port 443, 80 and port 8080 to achieve this functionality.
I deny port 80, 443 and 8080, then my VM can't access https://google.com and http://google.com.

Update:


text:
Q: how to completely sign out from google plus from different Activity in android? I have implemented google plus in my application and when I sign in via google plus then my app show all the google account which are sync in my android device. My problem is that when I sign out from google plus and again sign in then my app doesn't ask for choose account(do not show all the google accounts sync in my android device), It only shows for the first time I install the application and my app directly sign in to the account I choose at the first time of login. I am attaching my logout code. I have spent lot of time on this issue but didn't find any solution.
private void signOutFromGplus() {
    if (SignInActivity.mGoogleApiClient.isConnected()){
        Plus.AccountApi.clearDefaultAccount(SignInActivity.mGoogleApiClient);
        SignInActivity.mGoogleApiClient.disconnect();
        SignInActivity.mGoogleApiClient.connect();
    }
 }


text:
Q: Will ElasticSearch rest client find out the cluster nodes automatically?
I am using Rest Client of Elastic Search and Elastic Search will have
  Nodes in a cluster.
If I connect to one node then will it automatically find other nodes
  of cluster while processing the request and do load balancing ?

Or I need to take care of that while creating the Rest Client?

A: If "sniffer" is active, before the request (in background) the client will update your internal list of node data. It works for default client and Rest Client.
The master node (defined in the cluster configuration) will do the load balancing.


text:
Q: Why do I have such field names in my laravel project, despite all others are OK? I'm trying to configure simple laravel booking form for my project, but the names of fields are like this "quickadmin.bookings.fields.first_name*" but not like I want them to be, like this "first name".
I've tried to look through all files of project, where those forms could be configured, but due to lack of experience I can't find anything.
Here's some code from create.blade.php file

        {!! Form::label('first_name', trans('quickadmin.bookings.fields.first_name').'*', ['class' => 'control-label']) !!}
        {!! Form::text('first_name', old('first_name'), ['class' => 'form-control', 'placeholder' => '', 'required' => '']) !!}

        @if($errors->has('first_name'))

            {{ $errors->first('first_name') }}

        @endif

I want the field to be named more common, like "First name".

A: That's not a field name but an item from the translation files. So you should have in the resources/lang/en (en, or whatever language you use) a quickadmin.php file that contains an array like this:
return [
    'bookings' => [
        'fields' => [
            'first_name' => 'First name'
        ]
    ]
];

If you want to simplify this, then remove some of the arrays.
And you get this "quickadmin.bookings.fields.first_name*" on the screen because the file and the array that I mentioned above are probably missing. So you can avoid that by creating what I just said, or create your own, just remember the first part is the filename, then it follows the items from the array.


text:
Q: Why is Minkowski spacetime in polar coordinates treated in texts as flat spacetime? Taking 3-D Minkowski spacetime line element in General Relativity:
$$ds^2=-c^2dt^2+dx^2+dy^2+dz^2, $$
when considering a change into spherical coordinates leads to:
$$ds^2=-c^2dt^2+dr^2+r^2\left(d\theta^2+\sin^2\theta\,d\phi^2\right).$$
In several books, it is said that this is still Euclidean flat-space time, for it is only a change of coordinates speaking about the same as in Euclidean plane... but my big inquiry is under what point of view is this still flat, since the Levi-Civita connection $\Gamma^{\alpha}_{\,\,\beta\lambda}$ for this new space-time is not zero for some components. Are these symbols equal to zero a necessary condition for giving flat space-time?
I have not computed the components of the Riemann tensor for the polar coordinates spacetime, yet. But it is easy to see that for Cartesian coordinates they are equal to zero. If they were nonzero, does this assume that the deviation of geodesics equal to zero is still obeyed? From since I can remember, if the components of the Riemann tensor $R^{\alpha}_{\,\,\beta\mu\nu}$ are all zero, you get deviation zero and you can talk about Euclidean, flat space-time. Also, I can remember that if the Ricci scalar $R=0$ if and only if flat space-time is given. Am I correct?

A: Under a coordinate change, the metric may change form, but it is fundamentally the same manifold you are dealing with, and curvature scalars are diffeomorphism invariants.
While $\Gamma^a_{bc} \neq 0$, Minkowski space in any set of coordinates has $R^a_{bcd} = 0$. To convince yourself without calculating, see a coordinate change as a relabelling of positions. Rather than a grid, you might use a spherical coordinate system, but the points you are labelling on the surface are not being moved. The distance between any two is still the same.
The notion of curvature has to be independent of any coordinate system, since that is something we impose on the manifold and is not an intrinsic property.


text:
Q: Parenthesis Operation in PEMDAS Python This function works as the Parenthesis operation in PEMDAS. I already have the PEMDAS Function working okay for the EMDAS operations, and this is the only operation I need to correct for my PEMDAS function to work okay.
It works for nested cases (1+(1+1)) as we well as multiple, separated cases (1+1) + (1+1). However, it doesn't work with the combination of the two (1+(1+1)) + (1+1). How can I modify the code so that it can take the last case into account? Note: We're not allowed to use regex.
def paren(equation):
    for i in range(len(equation)):
        if equation[i] == "(":
            for j in range(i + 1, len(equation)):
                if equation[j] == ')':
                    return equation[i + 1:j]
                elif equation[j] == '(':
                    for x in range(len(equation) - 1, -1, -1):
                        if equation[x] == ')':
                            return equation[i + 1:x]
                else:
                    continue

SAMPLES:

*

*Input1: (1+(1+1))

*Output1: 1+(1+1)

*Input2: (1+1) + (2+2)

*Output2: 1+1 (outputted the eq from the first bracket so that it can be solved first)

*Input3: (1+(1+1)) + (1+1)

*EXPECTED Output3: 1+(1+1)

*Output3: 1+(1+1)) + (1+1

A: This works for your test case. I count the numbers of open parentheses to find where to close the first equation.
def paren2(equation):
    equation = equation.replace(' ', '')
    open_parentheses_index_ = -1
    open_parentheses_count_ = 0
    close_parentheses_count_ = 0
    for i in range(len(equation)):
        if equation[i] == "(":
            if open_parentheses_index_ == -1:
                open_parentheses_index_ = i
            open_parentheses_count_ += 1
        elif equation[i] == ")":
            close_parentheses_count_ += 1
            if open_parentheses_count_ == close_parentheses_count_:
                return equation[open_parentheses_index_+1 : i]


text:
Q: Flutter http.get My problem is, that when I try to map the brands I need to declare brandsData as a Map<String, dynamic> but in that case jsonDecode(s) is red because it could be null

A: You can change your Model to this .
// To parse this JSON data, do
//
//     final album = albumFromJson(jsonString);
import 'dart:convert';

List<Album> albumFromJson(String str) => List<Album>.from(json.decode(str).map((x) => Album.fromJson(x)));

String albumToJson(List<Album> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Album {
    Album({
        this.userId,
        this.id,
        this.title,
    });

    int userId;
    int id;
    String title;

    factory Album.fromJson(Map<String, dynamic> json) => Album(
        userId: json["userId"],
        id: json["id"],
        title: json["title"],
    );

    Map<String, dynamic> toJson() => {
        "userId": userId,
        "id": id,
        "title": title,
    };
}

and use the function that @Ravindra via link like this
 Future<List<Album>> fetchPost() async {
      String url =
          'https://jsonplaceholder.typicode.com/albums/1';
      var response = await http.get(Uri.parse(url), headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      });
      if (response.statusCode == 200) {
        // If the call to the server was successful, parse the JSON
        return Album.fromJson(json
            .decode(response.body));
      } else {
        // If that call was not successful, throw an error.
        throw Exception('Failed to load post');
      }
    }

Hope it helps you. Lastly you can use this link https://app.quicktype.io/ to create your model class.


text:
Q: I dont know whats wrong with this simple javascript code, I have checked this over and over again but does not work Simple image expanding on mouseover and opposite on mouseout, I checked the code over and over, putting alert messages at each line to see if its working, alert message work all the way to the end but there is no effect on the image. I am so confused, I dunno whats wrong.

var side = 200;
var a = 20;
var t = 0;

function expand() {
  console.log("expand is ok");
  clearInterval(t);
  t = setInterval(grow, 20);

}

function grow() {
   console.log("Entered grow");
  if (side < 300) {
    console.log("entered if loop");
    side = side + a;
    document.getElementById("new").style.width = side;
    console.log("After statement")
  } else
    clearInterval(t);
  console.log("clear")
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Zoom in Zoom out</title>
</head>

<body>
  <img src="../images/women.jpg" id="new" alt="Women" onmouseover="expand()" width=2 00px>
</body>

</html>

A: To expand on my comment:
The issue is you're trying to assign a raw number such as 200 to the width CSS property.
If you look at CSS, you'd spell "200 pixels" as
foo {
  width: 200px;
}

so similarly you'll need to endow the dynamic manipulation with an unit (pixels here):
foo.style.width = `${width}px`;


text:
Q: How to create image of SKSpriteNode? I have a SKSpriteNode with a lot of child nodes.
I use that node with all the children very frequently in my game.
A better approach would be to build this node once with all the children, create an image (SKTexture) and use the created texture, as opposed to recreating the SKSpriteNode and all its children.
Is there any way to do this?

A: SKEffectNode & shouldRasterize
You can us SKEffectNode and set shouldRasterize to true.
let effectNode = SKEffectNode()
effectNode.shouldRasterize = true
scene.addChild(effectNode)

The SKEffectNode's output is rasterized and cached internally. This cache is reused when rendering.

Now just add your sprites to effectNode
effectNode.addChild(sprite0)
effectNode.addChild(sprite1)
effectNode.addChild(sprite2)

The first time the effectNode is rendered, the produced image will be automatically cached.
And the cached version will be used for the next frames.

A: There is actually a very easy way to do this.. I do this all the time to convert ShapeNodes to SpriteNodes (because shapes need 1 draw call per shape, and sprites dont)
let texture = SKView().texture(from: desiredNode)
let newSprite = SKSpriteNode(texture: texture)
or, in your gamescene for brevity:
let newSprite = SKSpriteNode(texture: view!.texture(from: desiredNode))


text:
Q: Getting error java.lang.NoClassDefFoundError: org/openqa/selenium/interactions/internal/Locatable at com.tests
java.lang.NoClassDefFoundError:
  org/openqa/selenium/interactions/internal/Locatable at com.tests.

Am getting this error when creating a driver instance for chrome or remote webdriver also.

A: You are getting this error as one of jar file is missing in your build path.From the error I could see that the 'Locatable' class is missing.

This 'Locatable' class is available in
  'org.openqa.selenium.interactions.internal' package inside
  'client-combined-3.6.0.jar'

However,I would recommend you to reimport all selenium related jars to your project,to make sure you wont be getting any such dependency issues down the line.
1.You can download selenium for java client 3.6.0 from http://www.seleniumhq.org/download/
2.Make sure you added all jars from selenium directory to your build path.
3.Rerun your project.
Cheers!

A: After updating to 3.6.0 with latest jar's its working .


text:
Q: sql pivot two columns to same column values I'm trying to transform data, and have somewhat succesfully done it so far but have now hit a dead-end and looking for some help on my issue.
I have four columns in my data. Cat1 (old category), val1 (old value), cat2(new or current category) and val2 (its current value.
What I want is for each combination of cat 1 and cat 2 the val2, negative for the old category in its respective column, and positive for the new category.
example data:
 cat1   cat2   val1   val2
 A      B      10     30
 A      A      5      20
 C      A      33     15
 B      C      23     20
 B      A      14     5
 C      B      18     20
 A      B      14     0

The outcome I'm looking for is:
change     A     B    C
AtoB      -30   +30
AtoC       0          0
BtoA      -5     +5
BtoC             -20  +20
CtoA      +15        -15
CtoB            +20  -20

I've succesfully by using pivot&unpivot with the help of the CASE clause created a table that takes into consideration only one of the columns. So I only get one value per row:
select * from (select
cat1
SUM(
    CASE WHEN cat1 = A AND cat2 = B THEN val2*-1 ELSE 0 END
  ) AtoB,
SUM(
    CASE WHEN cat1 = A AND cat2 = C THEN val2*-1 ELSE 0 END
  ) AtoC,
SUM(
    CASE WHEN cat1 = B AND cat2 = C THEN val2*-1 ELSE 0 END
  ) BtoC,
SUM(
    CASE WHEN cat1 = C AND cat2 = B THEN val2*-1 ELSE 0 END
  ) CtoB,
SUM(
    CASE WHEN cat1 = C AND cat2 = A THEN val2*-1 ELSE 0 END
  ) CtoA,
SUM(
    CASE WHEN cat1 = B AND cat2 = A THEN val2*-1 ELSE 0 END
  ) BtoA
 FROM table
  group by cat1,cat2)
  unpivot (
  value for cat in
 (AtoB,AtoC,BtoC,CtoB,CtoA,BtoA)) up
pivot (
sum(value) for cat1 in ('A','B','C')

the problem here is that I only get the value on cat1, and not on cat2, despite them sharing the values. One solution I can think of is to create some complicated join, or to save this table and then do a new CASE clause on each row to duplicate the value times -1, but feel like both of those solutions are not very good, and that there is some better solution which I am missing.
After the unpivot clause I end up with:
cat1     cat   value
A        AtoB   -30
A        AtoC    0
B        Bto    0
B        AtoB   0
...      ...    ...

which the PIVOT statement transforms to
cat        A     B    C
AtoB      -30
AtoC
BtoA              -5
BtoC             -23
CtoA                 -15
CtoB                 -20


text:
Q: Android / Java: Arraylist return value which contains a word I'm building an app where i load an arraylist of URLs from an external XML (the arraylist is created by JSoup parsing).
Then, i need to:

*

*Check if a certain word is present in one of the string in arraylist
(the URLs);

*Return the string which contains the given value (the URL which
contain my word).

For managing the Arraylist.contains() i found the following sample code, that i'm implementing; but the following codes will return a printout sentence, not the value.
How can i set the code to return the string which contains the given word?
public class MyArrayList extends ArrayList<String> {
    private static final long serialVersionUID = 2178228925760279677L;

    @Override
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

    @Override
    public int indexOf(Object o) {
        int size = this.size();
        if (o == null) {
            for (int i = 0; i < size ; i++) {
                if (this.get(i) == null) {
                    return i;
                }
            }
        } else {
           for (int i = 0; i < size ; i++) {
                if (this.get(i).contains(String.valueOf(o))) {
                    return i;
                }
            }
        }
        return -1;
    }
}

Here to use it:
MyArrayList arrayList = new MyArrayList();
arrayList.add("http://www.google.com");
arrayList.add("https://www.stackoverflow.com");
arrayList.add("http://pankajchunchun.wordpress.com");

if (arrayList.contains("google")) {
    System.out.println("ArrayList Contains google word");
}

I need the result to be: System.out.println("The URL which contains my word");
Thanks for your availabiliy

A: You have to check for the whole length of the arraylist:-
for(i=0;i<arrayList.size();i++)
{
if (arrayList.get(i).contains("google"))
{
System.out.println(arrayList.get(i));
}
else
{//your code
 }}

i am assuming here that your arraylist contains string elements

A: As i commented here is the code for that:
for (String string : arrayList) {
        if (string.contains("stackoverflow")) {
        System.out.println(string);
        }
    }


text:
Q: PyTorch DataLoader uses identical random transformation across each epoch There is a bug in PyTorch/Numpy where when loading batches in parallel with a DataLoader (i.e. setting num_workers > 1), the same NumPy random seed is used for each worker, resulting in any random functions applied being identical across parallelized batches. This can be resolved by passing a seed generator to the worker_init_fn argument like so.
However the issue persists across multiple epochs.
Minimal example:
import numpy as np
from torch.utils.data import Dataset, DataLoader

class RandomDataset(Dataset):
    def __getitem__(self, index):
        return np.random.randint(0, 1000, 2)

    def __len__(self):
        return 4

dataset = RandomDataset()
dataloader = DataLoader(dataset, batch_size=1,
                        num_workers=2,
                        worker_init_fn = lambda x: np.random.seed(x))

for epoch in range(3):
    print(f'\nEpoch {epoch}')
    for batch in dataloader:
        print(batch)

As you can see, while parallelized batches within an epoch now produce different results, the results are identical across epochs:
Epoch 0
tensor([[684, 559]])
tensor([[ 37, 235]])
tensor([[629, 192]])
tensor([[908,  72]])

Epoch 1
tensor([[684, 559]])
tensor([[ 37, 235]])
tensor([[629, 192]])
tensor([[908,  72]])

Epoch 2
tensor([[684, 559]])
tensor([[ 37, 235]])
tensor([[629, 192]])
tensor([[908,  72]])

How can this be behaviour be fixed?

Using an empty argument e.g. worker_init_fn = lambda _: np.random.seed() appears to fix this - are there any issues with this workaround?

A: The best way I can think of is to use the seed set by pytorch for numpy and random:
import random
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader

def worker_init_fn(worker_id):
    torch_seed = torch.initial_seed()
    random.seed(torch_seed + worker_id)
    if torch_seed >= 2**30:  # make sure torch_seed + workder_id < 2**32
        torch_seed = torch_seed % 2**30
    np.random.seed(torch_seed + worker_id)

class RandomDataset(Dataset):
    def __getitem__(self, index):
        return np.random.randint(0, 1000, 2)

    def __len__(self):
        return 4

dataset = RandomDataset()
dataloader = DataLoader(dataset, batch_size=1,
                        num_workers=2,
                        worker_init_fn = worker_init_fn)

for epoch in range(3):
    print(f'\nEpoch {epoch}')
    for batch in dataloader:
        print(batch)

Output:
Epoch 0
tensor([[593, 191]])
tensor([[207, 469]])
tensor([[976, 714]])
tensor([[ 13, 119]])

Epoch 1
tensor([[836, 664]])
tensor([[138, 836]])
tensor([[409, 313]])
tensor([[  2, 221]])

Epoch 2
tensor([[269, 888]])
tensor([[315, 619]])
tensor([[892, 774]])
tensor([[ 70, 771]])

Alternatively, you can use int(time.time()) to seed numpy and random, assuming each epoch takes more than 1 second to run.

A: As stated in the blog post you linked, what you did write will produce the same random number for each worker at each epoch:

Iterating over the dataset three times produces the same random numbers at each epoch. This happens because all changes to random states are local to each worker. By default, the worker processes are killed at the end of each epoch, and all worker resources are lost. At the same time, the random state in the main process hasn't changed, and it's used to initialize each worker process again.

The solution is given:

Therefore you need to change the NumPy's seed at every epoch, for example by np.random.seed(initial_seed + epoch).

But I personally prefer to only use Torch random instead of Numpy's one to avoid issues as Torch handles randomness in parallel code by default.

Additional Note
According to the blog post:

PyTorch takes care of these by setting the [...] seeds to seed + worker_id automatically.

This means that using a Pytorch random function in your Dataset class or training loop should not replicate randomness across batches or epochs. For instance the minimal example you wrote could be fixed like this:
import torch
from torch.utils.data import Dataset, DataLoader

class RandomDataset(Dataset):
    def __getitem__(self, index):
        return torch.randint(0, 1000, (2,))

    def __len__(self):
        return 4

dataset = RandomDataset()
dataloader = DataLoader(dataset, batch_size=1, num_workers=2)

for epoch in range(3):
    print(f'\nEpoch {epoch}')
    for batch in dataloader:
        print(batch)

Most of the time Numpy can be replaced by Torch random (or Python random). here is another example with a random transformation for image segmentation:
class RandomHorizontalFlip:

    def __init__(self, prob=0.5):
        self.prob = prob

    def __call__(self, input, target):
        if torch.randn(1).item() < self.prob:
            return F.hflip(input), F.hflip(target)
        else:
            return input, target


text:
Q: How to express exclusive intersections? I have a function $f:\mathbb{R}^2 \rightarrow\mathbb{R}, \ \mathbf{x} \mapsto \sum_{i = 1}^{n} w_i \mathbf{1}_{A_i}(\mathbf{x})$ for $w_i \in \mathbb{R}$ and the $A_i$s are allowed to intersect. Thus for the case of $n=3$ we might have something like:

($A_1 = A, A_2 = B, A_3 = C$ here)
where at each exclusive intersection e.g. $AB = A \cap B \setminus C$, $f$ takes the value $w_A + w_B$. Now, I would like to express $f$ as the sum of indicators over non-intersecting sets (i.e. a partition of the underlying space):
$$f(\mathbf{x}) = (w_A + w_B + w_C) \mathbf{1}_{ABC}(\mathbf{x}) + (w_A + w_B) \mathbf{1}_{AB}(\mathbf{x}) + (w_A + w_C) \mathbf{1}_{AC}(\mathbf{x}) + \ldots$$
How to express this for general $n$? (In the same vein as XOR, the notion of exclusive intersection would really help here, but I'm unsure of its notation.)

A: Let $X=\{A_1,A_2,\ldots, A_n\}$.
For each $S\in\mathcal P(X)$ denote $M(S)=\bigcup S\setminus \bigcup(\mathcal P(X)\setminus S)$ and $W_S=\sum_{A\in S}w_A$. Then
$$f(x)=\sum_{S\subseteq X} W_S\mathbf 1_{M(S)}$$ is such a sum. Note that $M(S)$ is the "exclusive intersections" of all $A_i\in S$.
Alternatively, we have a map $\phi\colon\mathbb R^2\to X$, $\mathbb x\mapsto \{A\in X\mid x\in A\}$ and can write $\phi^{-1}(S)$ isntead of $M(S)$ above.


text:
Q: Unable to switch on Bluetooth I can't switch on the Bluetooth, nor the visibility. Every button in this page doesn't respond. The only thing I can do is to check the box, but no Bluetooth status is shown.
I checked my /etc/bluetooth/main.conf. AutoEnable=true
I also tried commands:
rfkill block bluetooth
rfkill unblock bluetooth  #Nothing changed or showed up

as well as
sudo rmmod btusb
>rmmod: ERROR: Module btusb is not currently loaded

Edit: adding the output of lspci -nnk | grep -iA3 net; lsusb as suggested
$ lspci -nnk | grep -iA3 net; lsusb
00:1f.6 Ethernet controller [0200]: Intel Corporation Ethernet Connection (2) I219-LM [8086:15b7] (rev 31)
    Subsystem: Dell Ethernet Connection (2) I219-LM [1028:06b9]
    Kernel driver in use: e1000e
    Kernel modules: e1000e
01:00.0 VGA compatible controller [0300]: Advanced Micro Devices, Inc. [AMD/ATI] Oland XT [Radeon HD 8670 / R7 250/350] [1002:6610] (rev 83)
Bus 002 Device 003: ID 0424:5744 Standard Microsystems Corp.
Bus 002 Device 002: ID 0424:5744 Standard Microsystems Corp.
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 004: ID 413c:301a Dell Computer Corp.
Bus 001 Device 003: ID 0424:2744 Standard Microsystems Corp.
Bus 001 Device 002: ID 0424:2744 Standard Microsystems Corp.
Bus 001 Device 005: ID 2516:003c
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Does it mean I don't have Bluetooth adapter?


text:
Q: laravel 5.4 auth register custom error message Im sorry i am new for laravel, but this is strange,
i want to use custom error message in validation of error register,
in my registercontroller :
$messages = [
        'vbadminEmail.required'      => 'Email has already been taken this is customize error.',
    ];

    $result = Validator::make($data, [
        'vbadminEmail' => 'required|email|max:255|unique:admin_user,user_email',
        'vbadminPassword' => 'required|min:6|confirmed',
    ],$messages);

when i test and debug the result :
debug the error arrays
it still used the general format, not the "Email has already been taken this is customize error"
please help me how to fix it
thank you

A: Try below code
   $messages = [
    'vbadminEmail.unique'      => 'Email has already been taken this is customize error.',
   ];

in your current code you are applying custom message on required rule, so you need to add custom message on unique rule not on required


text:
Q: Error in stream-delim when exporting to CSV I'm trying to write this StatsBomb Data into a CSV but I keep on getting the following error message:
Error in stream_delim_(df, path, ..., bom = bom, quote_escape = quote_escape) :
  Don't know how to handle vector of type list.
I'm lost (tried multiple things) and not sure what I did wrong here. Is there anyone out here who knows how to solve this? I've included my code below.
library(StatsBombR)
library(tidyverse)

### Read in all free events and matches from the FAWSL
data <- StatsBombFreeEvents()
matches <- FreeMatches(Competitions = 72)

### Clean and separate all data loaded above
dataclean <- allclean(data)

### Filter event data to include only FAWSL data.
data1 <- dataclean %>%
  filter(dataclean$competition_id == 72)

### Join event and match data by "match_id"
data1 <- left_join(data1, matches, by = "match_id")

FullData <- data1 %>%
  select(-c(related_events, tactics.lineup, shot.freeze_frame, location, pass.end_location, shot.end_location, goalkeeper.end_location))

setwd()
write_csv(FullData, "StatsBomb_FullData.csv")

A: I had the same problem. Unlisting the column fixed mine.
df$listcolumn <- sapply(df$listcolumn, function(x) paste0(unlist(x), collapse = "\n"))


text:
Q: AES crypt function with C# and decrypt using javascript I'm trying to code a C# crypt function that I can decrypt with JavaScript,
is there a possible way to do that?

A: For applications that require higher security I usually encode and decode using C#, and use $.ajax in JS, but there is an easy way using JS to decode  a pre-encrypted string .
You can use Base64String...
C# :
string encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(str));

JS :
function decode(str) {
  var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  var output = "";
  var chr1, chr2, chr3;
  var enc1, enc2, enc3, enc4;
  var i = 0;

  do {
     enc1 = keyStr.indexOf(str.charAt(i++));
     enc2 = keyStr.indexOf(str.charAt(i++));
     enc3 = keyStr.indexOf(str.charAt(i++));
     enc4 = keyStr.indexOf(str.charAt(i++));

     chr1 = (enc1 << 2) | (enc2 >> 4);
     chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
     chr3 = ((enc3 & 3) << 6) | enc4;

     output = output + String.fromCharCode(chr1);

     if (enc3 != 64) {
        output = output + String.fromCharCode(chr2);
     }
     if (enc4 != 64) {
        output = output + String.fromCharCode(chr3);
     }
   } while (i < str.length);

  return output;
}


text:
Q: why % sign used in pdf strcuture I have one question regarding the pdf structure, why % sign is used in pdf.
I got some results where they mentioned % sign is used for comments but if we use % sign for comments then what about % sign used in %PDF-1.5 and %%EOF?
%PDF-1.5 which defines the header of the file and
%%EOF which defines the end of the pdf structure.
then why is the % sign used for PDF-1.5 and why is the % sign used 2 times in EOF?
From the results I knew that % sign is used for comments, so why it is different for above two terms?
Your help will be appreciated - Thank you

A: I actually know nothing about pdf structure or using % correctly, but it seems to have the same reasons as the shebang #! followed by an executable is required in shell scripts, like bash, perl, or even python.
More can be read at this stack overflow answer here for why bash scripts need the #! at the beginning of scripts: https://stackoverflow.com/a/8968514/6037755

A:
why is the % sign used for PDF-1.5 and why is the % sign used 2 times in EOF?
From the results I knew that % sign is used for comments, so why it is different for above two terms?

You can consider those entries actually to be comments (after all they do not contain any PDF objects as such to use for PDF rendering) which you are required to put at certain positions of a PDF file.
According to the specification ISO 32000-1:

7.5.2 File Header
The first line of a PDF file shall be a header consisting of the 5 characters %PDF– followed by a version number of the form 1.N, where N is a digit between 0 and 7.

and

7.5.5 File Trailer
The trailer of a PDF file enables a conforming reader to quickly find the cross-reference table and certain special objects. Conforming readers should read a PDF file from its end. The last line of the file shall contain only the end-of-file marker, %%EOF.

As the use of "shall" here indicates, these are requirements.

And it indeed makes sense that these markers in all other respects are comments.
Only for the purpose of identifying the start and the end of a PDF these markers have a special meaning, before a PDF processor starts working with actual PDF objects. As soon as start and end are identified, these markers have to be ignored. So, making these markers comments is an obvious choice.
This is true for unusual processing types, too. E.g. if for some reason the cross references of a PDF are broken and some program tries to re-create them by searching for indirect PDF objects, it does not need to specially treat these markers, it automatically ignores them as comments.

PS According to Adobe's Implementation Notes in the Annex H of their PDF Reference, their tools also accept an alternative header:

3.4.1, "File Header"
[...]
14.Acrobat viewers also accept a header of the form
%!PS−Adobe−N.n PDF−M.m

If you want to find out why the marker comment contents were chosen exactly like they they are, therefore, you should look into the history of PDF and Postscript


text:
Q: namespace troubles with enums Having a problem using enumerations with namespaces.
Below is the function call:
object->writeMessage(tmpZone->getLineOne(), tmpZone->getLine(), tmpZone->getPosition());

the problem from the compiler comes from
tmpZone->getLine()

the prototype for getLine() from the Zone class(which is in the insight namespace)is:
Line getLine();

which returns an enum type in the insight namespace. This function call is in a cpp file under a using namespace insight; line.
the compiler errors are

C:/WindRiver/workspace/SimpleTemplate/InsightLT.cpp: In static member
  function static int
  insight::InsightLT::taskFunction(insight::InsightLT*)':
  C:/WindRiver/workspace/SimpleTemplate/InsightLT.cpp:161: error: no
  matching function for call to
  insight::InsightLT::writeMessage(std::string, Line, int)'
  C:/WindRiver/workspace/SimpleTemplate/InsightLT.cpp:82: note:
  candidates are: void insight::InsightLT::writeMessage(std::string,
  insight::Line, int)

I can't think of why this is happening. The Zone class is defined with in the insight namespace as well. Any ideas guys?

A: Compiler can't resolve Line from insight namespace, you could provide full namespace in function definition, also wrap cpp inside namespace insight.
Try:
namespace insight {
  void InsightLT::writeMessage(std::string, insight::Line, int)
  {
  }
}

A: I was able to get this to compile, though I don't know why what I did worked. For the sake of completeness and closure I wanted to put it here.
I was declaring the Line enum and another enum inside the namespace scope along with another class. I removed the enums and put them in their own header files within the same namespace as before and it now compiles.
I am not sure what I was missing that this fixed the issue. If someone has any considerations please comment as to what this might have fixed.
Thanks for those that tried to help and sorry I wasn't able to put together an example the displayed the error.


text:
Q: How to reshape scanned input of pairs of data from data set with unequal numbers of columns I have pairs of data scanned where the number of pairs on a line is variable in number.
R code:
x <- scan(paste0(dirdata,"df.txt"), what = "", sep = " ")

Lines in data set look like
 v1  v2  v3   v4   v5  v6   V7  V8
"A" "35" "B" "32" "Z" "67"  "F" 17
"F" "17"  NA  NA   NA  NA   NA  NA

I want to reshape it to look like
 v1  v2
"A" "35"
"B" "32"
"Z" "67"
"F" "17"

Can this be done in base R? How? in reshape package? How?
I am doing things two ways (1) using base R code and (2) using a package such as reshape.
Output from an unlist function is given below.
d1 <- data.frame(v1 = unlist(df1[,c(TRUE, FALSE)]),
                 v2 = unlist(df1[,c(FALSE, TRUE)]))
data.frame(lapply(d1, na.omit))

   head(d1)
      v1 v2
V21    A  1
V22    B 50
V23    Z 74
V24    F  3

Can someone explain what the unlist function is doing and is column one of the output line numbers?
Can you help, please? Thanks.
MM

A: If it is data.frame
d1 <- data.frame(v1 = unlist(df1[,c(TRUE, FALSE)]),
                v2 = unlist(df1[,c(FALSE, TRUE)]))
data.frame(lapply(d1, na.omit))
#  v1 v2
#1  A 35
#2  F 17
#3  B 32
#4  Z 67
#5  F 17

or using reshape from base R
na.omit(reshape(transform(df1, rn = seq_len(nrow(df1))),
   direction = 'long', idvar = 'rn',
  varying = list(seq(1, ncol(df1),  by = 2), seq(2, ncol(df1), by = 2)))[3:4])

data
df1 <- structure(list(v1 = c("A", "F"), v2 = c(35L, 17L), v3 = c("B",
NA), v4 = c(32L, NA), v5 = c("Z", NA), v6 = c(67L, NA), V7 = c("F",
NA), V8 = c(17L, NA)), row.names = c(NA, -2L), class = "data.frame")


text:
Q: How to make a switch statement loop? import java.util.LinkedList;
import java.util.Scanner;

public class Enrollment {
public static void main(String[] args) {
    LinkedList<Student> studentData = new LinkedList<Student>();
    LinkedList<Faculty> facultyData = new LinkedList<Faculty>();
    LinkedList<Course> courseData = new LinkedList<Course>();
    Scanner input = new Scanner(System.in);

    System.out.println("Enter 1 to add a student, 2 to add a faculty, 3 to add a course");
    int userChoice = input.nextInt();
    input.nextLine();
    switch (userChoice) {

    case 1:
        System.out.println("Enter student full name ");
        String sName = input.nextLine();

        System.out.println("Enter student age ");
        int sAge = input.nextInt();

        System.out.println("Enter student id ");
        int sID = input.nextInt();
        input.nextLine();

        System.out.println("Enter student address(only address number and street name) ");
        String sAddress = input.nextLine();

        System.out.println("Enter city, state, and zip code ");
        String sCityStateZip = input.nextLine();

        System.out.println("Enter student gender ");
        String sGender = input.nextLine();

        Student studentInfo = new Student(sName, sAge, sID, sAddress, sCityStateZip, sGender);
        studentData.add(studentInfo);

        for (Student testClass : studentData) {
            System.out.println(testClass);
        }

        break;
    case 2:
        // code to add faculty
        System.out.println("Enter faculty name ");
        String fName = input.nextLine();

        System.out.println("Enter faculty age ");
        int fAge = input.nextInt();

        System.out.println("Enter faculty id ");
        int fID = input.nextInt();
        input.nextLine();

        System.out.println("Enter faculty degree ");
        String fDegree = input.nextLine();

        System.out.println("Enter faculty major ");
        String fMajor = input.nextLine();

        System.out.println("Enter faculty address ");
        String fAddress = input.nextLine();

        System.out.println("Enter faculty gender ");
        String fGender = input.nextLine();

        Faculty facultyInfo = new Faculty(fName, fAge, fID, fDegree, fMajor, fAddress, fGender);
        facultyData.add(facultyInfo);

        for (Faculty testClass : facultyData) {
            System.out.println(testClass);
        }
        break;
    case 3:
        // code to add course
        System.out.println("Enter course name ");
        String courseName = input.nextLine();

        System.out.println("Enter course ID ");
        int cID = input.nextInt();

        System.out.println("Enter number of credits ");
        int numOfCred = input.nextInt();

        System.out.println("Enter intstructor/faculty ID ");
        int instructorID = input.nextInt();

        System.out.println("Enter course year ");
        int year = input.nextInt();
        input.nextLine();

        System.out.println("Enter semester ");
        String semester = input.nextLine();

        System.out.println("Enter classroom size ");
        int size = input.nextInt();

        System.out.println("Enter course capacity ");
        int capacity = input.nextInt();

        Course courseInfo = new Course(courseName, cID, numOfCred, instructorID, year, semester, size, capacity);
        courseData.add(courseInfo);

        for (Course testClass : courseData) {
            System.out.println(testClass);
        }

        break;

    default:
        System.out.println("Invalid entry");
        break;
    }

}

I am trying to make an enrollment system. Right now I have made the program so that it prompts the user to choose if they want to add a student, faculty, or course. Once the user picks an option and fills out the questions asked, the program ends. How can I make it loop so that after the user answers the questions, it brings them back to the first prompt where they are given the three choices of what they want to do?

A: Put a loop around the entire switch, for example:
while(true){
  //entire switch statement here
}

I'd also break your code up a bit with methods. If code is like a recipe, methods are small parts of the process that always perform the same, though might have different inputs - for example, you can beat an egg, beat cream, stir soup, stir sauce, stir flour - methods are typically named with something that sounds like an action (a verb) so if you hired a new young chef, who'd never seen cream before but knew how to beat things, you could hand him your cream and your eggs and tell him to beat them.. that's the idea of a method, that you take a small part of code that always does the same thing, though the inputs and outputs change, and make it a method. Input.nextLine() is a method of scanner. It always reads from the console (when the console is attached to the scanner) and gives a line of text, whatever text was typed.
Here's an example from your code:
private Student getStudentFromInput(Scanner input){
        System.out.println("Enter student full name ");
        String sName = input.nextLine();

        System.out.println("Enter student age ");
        int sAge = input.nextInt();

        System.out.println("Enter student id ");
        int sID = input.nextInt();
        input.nextLine();

      //  ... blah blah and so on right the way to the bit where you make the student
        Student studentInfo = new Student(sName, sAge, sID, sAddress, sCityStateZip, sGender);

        return studentInfo;
}

That's a Method. It takes input parameters, does something with them, gives something back
You can now tidy up your switch statement to:
   case 1:

        Student studentInfo = getStudentFromInput(input);
        studentData.add(studentInfo);

        for (Student testClass : studentData) {
            System.out.println(testClass);
        }
        break;

"But it's not really any different to before" you mit say - no it's not, because your code only ever calls the method from one place. The good part is, you could call that method from another place, to read in a student, without have to repeat all the lines of code again. It also stops our main (which is also a method) ending up ten thousand lines long by the time we've extended our program to handle entire towns of kinds of people and organisations. Try to always follow a rule that a method shouldn't be more than a couple of screens long. If it is, it's an indication your code needs breaking up into more methods, smaller units of work per se

A: you can make
while(userChoice!=4){.........your code.........
 System.out.println("Enter 1 to add a student, 2 to add a faculty, 3 to add a course");
  userChoice = input.nextInt();
}


text:
Q: How to call a function when angularjs accordion open only Hi I am using angularjs ui bootstrap accordion. Here i want to call when user click on accordion call one function and get user
Here is the code please help me thnks in advance

$scope.load_userdata= function(user_id) {
     console.log(user_id);
    }
<uib-accordion close-others="oneAtATime">

     <uib-accordion-heading ng-click="load_userdata(user.id)">

           @{{user.name}}

          Load user data

       </uib-accordion-heading>

</uib-accordion>

data and display it

A: I don't really understand what the problem is. I copied your template in the snippet below and added a simple controller with a working example.
The angular-bootstrap module is not included so you don't get the proper rendering. But it shows you how to define the function in your controller for your template to work.

function ctrl($scope) {
    // dummy users data for the snippet purpose
    $scope.users = [{
            name: 'Joe',
            id: '1',
            data : 'Married to Jane',
        },
        {
            name: 'John',
            id: '2',
            data : 'Has 3 children',
        },
        {
            name: 'Jack',
            id: '3',
            data : 'Owns a boat',
        },
        {
            name: 'Bob',
            id: '4',
            data : 'Speaks swedish',
        }
    ];

    $scope.load_userdata = function(user_id) {
        console.log("Loading user#%s data", user_id);

        // looking for the right user :
        let user = $scope.users.find(x => x.id === user_id);

        // and toggling the dataLoaded property in the user object
        user.dataLoaded = true;
    }
}
<!DOCTYPE html>

      <meta charset=utf-8 />
      <title>Angular JS Demo</title>

      <uib-accordion close-others="oneAtATime">

            <uib-accordion-heading ng-click="load_userdata(user.id)">

                     @{{user.name}}

                     Load user data

            </uib-accordion-heading>

               User's details :
               {{user.data}}

      </uib-accordion>


text:
Q: In XHTML 1.1: element 'input' cannot be nested within element 'form'. Why? This below code is forbidden in XHTML 1.1 strict mode:
<form method="post" action="index">
    <input id="_method" name="_method" type="hidden" value="" />
</form>

If you want it to be valid then you need to wrap it with a div (or p, etc..) like:
<form method="post" action="index">
    <div>
         <input id="_method" name="_method" type="hidden" value="" />
    </div>
</form>

How does this make any sense at all?

A: According to the W3C and this site the <form> element in XHTML 1.1 may only contain block level elements and <fieldset>.

As for why ... I believe that the reason that form may only contain block-level elements is because it is not considered an element in itself, but rather a wrapper around other elements.  There was some discussion of this in the w3c's mailing lists some years ago that I was able to dig up -- but nothing that actually answered the question.

A: Welcome to the wacky world of standards. Sometimes it seemed like the folks writing XHTML standards thought the language would be better if it had more rules.
HTML5 is here now.


text:
Q: print text on my R plots I am having a hard time to print text on my R plots.
I have 3 plots, and for each of them I would like to add a label (p-value).
Then for each of the 5 values that allowed me to draw a curve, print the value on the graphic.
In fact I would like to make my figure looks like the following figure (see bellow).
Using my following script.
Any help?
Thanks in advance,
Best,
df <-  structure(list(lowerA = c(4.1, 4.6, 5.5, 4.7, 5), Group1 = c(4.8,5.4, 6.4, 5.5, 5.7),
                      upperA = c(5.7, 6.3, 7.3, 6.3, 6.6), lowerB = c(6.2, 7.1, 8.7, 7.4, 8.2),
                      Group2 = c(7.3, 8.3, 10, 8.6, 9.5), upperB = c(8.6, 9.6, 11.4, 9.9, 10.8),
                      lowerC = c(18.3, 19.5, 24.3, 22.9, 25.5), Group3 = c(21.4, 22.5, 27.6, 26.3, 29),
                      upperC = c(24.7, 25.8, 31, 29.8, 32.7)),
                 .Names = c("lowerA", "Group1", "upperA", "lowerB","Group2", "upperB", "lowerC", "Group3", "upperC"),
                 row.names = c("year1", "year2", "year3", "year4", "year5"), class = c("tbl_df", "tbl", "data.frame"))

class(df)
df <- as.data.frame(df)

#### Data Base

colnames(df) <- gsub("A","1",colnames(df))
colnames(df) <- gsub("B","2",colnames(df))
colnames(df) <- gsub("C","3",colnames(df))

colors <- c("#000099", "#CC0000", "#808080")
labels <- c("red line", "black line","black line")

#########
lablist<-as.vector(c("2010","2011","2012","2013","2014"))
axis(1, labels = FALSE)

#########

library(scales)
plot(df$Group1, type = "n",ylim = c(0,40),frame.plot = FALSE, main = "", xlab = "", ylab = "Survival at hospital discharge (%)",labels = FALSE)
axis(1, at=1:5, labels=c("2011-2012","2012-2013","2013-2014","2014-2015","2015-2016"))
axis(2, at=c(0, 10, 20, 30, 40), labels=c("0","10","20","30","40"))

for(i in 1:3){
  lines(df[,paste0("Group",i)], col = colors[i])

  polygon(x = c(1:nrow(df),nrow(df):1),
          y = c(df[,paste0("lower",i)],rev(df[,paste0("upper",i)])),
          col = alpha(c("white","white","white"), 0.1),
          # si tu veux garder les couleur des IC le long des courbes mets commande si après:
          # col = alpha(colors[i], 0.1),
          border = NA)

  arrows(x0 = c(1:nrow(df)),
         x1 = c(1:nrow(df)),
         y0 = df[,paste0("lower",i)],
         y1 = df[,paste0("upper",i)],
         col = colors[i],
         angle = 90,
         length = 0.05,
         code = 3)
}

A: Here's an example getting the point labels. I'll leave the P value labels as an exercise for the reader.
plot(df$Group1, type = "n",ylim = c(0,40),frame.plot = FALSE, main = "", xlab = "", ylab = "Survival at hospital discharge (%)", axes = F)
axis(1, at=1:5, labels=c("2011-2012","2012-2013","2013-2014","2014-2015","2015-2016"))
axis(2, at=c(0, 10, 20, 30, 40))

for(i in 1:3){
  lines(df[,paste0("Group",i)], col = colors[i])

  arrows(x0 = c(1:nrow(df)),
         x1 = c(1:nrow(df)),
         y0 = df[,paste0("lower",i)],
         y1 = df[,paste0("upper",i)],
         col = colors[i],
         angle = 90,
         length = 0.05,
         code = 3)

  points(df[,paste0("Group",i)], col = "white", pch = 15, cex = 2)
  text(df[,paste0("Group",i)], labels = df[,paste0("Group",i)], col = colors[i], cex = 0.7)
}

I set axes = F instead of labels = F in plot() to get rid of the warning, and I deleted the polygon code because it wasn't doing anything. You may want to further adjust the cex of the text and the points so it is sized nicely.


text:
Q: C++: exiting a for loop push_back command with a specific command I was learning to push_back vectors in C++, and I got to where I can use it. However, the code I made, pasted below, asks the user every time the loop ends if the user wants to continue the loop or not. I found this very inconvenient, so I wanted to change the code to where when the user inputs ("EXIT"), it would break the for loop. How would I have to change the code in this case?
I pasted the whole code just in case I may have to change the portions besides the for loop.
#define all student_marks.begin(), student_marks.end()

using namespace std;

int main()
{
    vector<double> student_marks; //create container

    double mark;
    char more_students = 'y'; //set default to yes ('y')

    while (more_students=='y' || more_students=='Y') {
        cout<<"Enter mark for student #"<<student_marks.size()+1<<":";
        cin>>mark; //enter mark

        student_marks.push_back(mark); //push_back

        cout<<"More students?(y/n)";
        cin>>more_students; //user selects to break or continue the loop
    }

    double sum = accumulate(all, 0.0), average = sum/student_marks.size(); //sum and ave

    cout<<endl
    <<"Total mark:\t\t"<<sum<<endl
    <<"Average mark:\t"<<average<<endl
    <<"Highest mark:\t"<<*max_element(all)<<endl
    <<"Lowest mark:\t"<<*min_element(all)<<endl<<endl;

    cout<<"-----Score list-----"<<endl;
    sort(all,greater<double>()); //sort list

    for (size_t i=0; i<student_marks.size(); i++)
        cout<<"#"<<i+1<<". "<<student_marks[i]<<endl; //outputs results as list

    return 0;
}

A: You could just stay in the loop as long as the user inputs valid marks:
cout << "Enter mark for student #1:"

while(cin >> mark) {
    students_marks.push_bak(mark);
    cout << "Enter mark for student #" << marks.size() + 1;
}

The loop will exit as soon as the user enters something other than a double, e.g. the EOF flag.


text:
Q: GRUB does not wait for me to choose between systems When my netbook boots, the GRUB menu does not wait me to choose between systems.  It goes automatically into Ubuntu system.  How can I solve this problem?

A: My suggestion is to get into Linux if you aren't fast enough with the escape key and the, as root (using su command ). Go to /boot/grub and edit grub.conf using a Linux editor (Vim, vi, nedit, etc) and change timeout=0 to timeout=10.  The hiddenmenu command in the config file below it keep the menu hidden until you hit the escape key.   All this does is delay booting for 10 seconds before bringing up the formal Linux booting screen (OS is loading up). I use 5 seconds since it's obvious I want to jump into Windows (I have a dual boot machine).  Hitting escape brings up the menu and gives me the classic selection of available bootable configurations I've defined in grub.conf.  My grub configuration contains the current kernel, the previous kernel and Windows.
If you don't know the intricacies of grub/grub.conf then be very careful. Only change that one numeric value—nothing else.
Make certain you save it back in Linux format (LF (Linux) and not CR/LF (DOS) format).
In Vim, it would be the ZZ command to write the file back and exit Vim (text) or just use the graphical and save and then exit. Problem solved.

A: Set the timeout value, I use "timeout 9":
http://www.howtogeek.com/howto/ubuntu/change-the-grub-menu-timeout-on-ubuntu/

A: In grub2, just press the key "shift"

A: The default key to get to the Grub menu is "Escape".  Even if Grub is set with a timeout of 0 seconds, as long as you multi-tap Escape quickly down when starting up (after the BIOS page) you can bring up the Grub menu to change operating systems.
If Grub is always loading the wrong OS for you, you can modify it to a different entry or to use the last used entry (with the option "saved").  Modifying Grub depends on your Grub version, so it's useful to know what version of Ubuntu you are running.

A: Here is the recommended way to change the grub configurations. Change the GRUB_TIMEOUT value in /etc/default/grub file and regenerate /boot/grub/grub.cfg using following commands.
To edit the file
# vim /etc/defaults/grub

Change
GRUB_TIMEOUT=10

Take backup of current grub.cfg file
# cp /boot/grub/grub.cfg /boot/grub/grub.bkup

Regerate the grub.cfg file with updated value
# grub-mkconfig -o /boot/grub/grub.cfg


text:
Q: (Puppeteer) Is there a way to get element query by x, y? I would like to get elements query selector by passing x,y coordinates.
Or maybe few elements that satisfy the coordinates.
Maybe I can do mouse.click(x, y) and then get clicked element but I don't want page to take any actions just get the query of the element.
Is there possibility to do that?

A: If you just need a topmost element by viewport coordinates, you can try DocumentOrShadowRoot.elementFromPoint(). If you need to compose a unique selector, you can try to process element array from the DocumentOrShadowRoot.elementsFromPoint() (add more checks to the example below — classes, ids, attributes, children count and order etc.):
'use strict';

const puppeteer = require('puppeteer');

(async function main() {
  try {
    const browser = await puppeteer.launch();
    const [page] = await browser.pages();

    await page.goto('https://example.org/');

    console.log(await page.evaluate(() => {
      return document.elementFromPoint(100, 100).tagName;
    }));

    console.log(await page.evaluate(() => {
      return document.elementsFromPoint(100, 100)
                     .map(({ tagName }) => tagName).reverse().join(' > ');
    }));

    await browser.close();
  } catch (err) {
    console.error(err);
  }
})();

DIV
HTML > BODY > DIV

A: You have to consider first that you might get many elements on the same position, including the main HTML element.
First, you need to get all the elements:
Array.prototype.slice.call(document.getElementsByTagName("*"))

Then, we now that each element has a function called getClientRects, which will return an array of "boxes".
Based on that, we can filter all the elements having one box in the coordinate you need:
var x = 150;
var y = 1250;
Array.prototype.slice.call(document.getElementsByTagName("*")).filter(e =>
     Array.prototype.slice.call(e.getClientRects()).find(rect =>
         rect.top <= x && rect.bottom >= x && rect.left <= y && rect.right >= y))

You could do something like that in your evaluate call in Puppeteer.


text:
Q: PHP Functions, null default parameters I have a PHP function signature that looks like this, where I want the 4th param to be NULL by default if nothing is supplied.
testfunction($param1, $param2, $param3, $param4=NULL) {
    //do stuff
}

I can also call using 4 params as such
x = testfunction('100', 'abc', 'xxx', null);

Why is it that I can also call the function using 3 parameters without any errors?
x = testfunction('100', 'abc', 'xxx');

Is what i'm doing even correct (using 3 params)? Any thoughts about how this relates to traditional method overloading where separate function signatures are defined?
My question is general in nature. Hope someone can shed some light on and around it.

A: When you declare a function like this:
testfunction($param1, $param2, $param3, $param4=NULL) {
    //do stuff
}

You're telling PHP that $param4 already has a value, so when that function is called, a value is already assigned to it. It doesn't expect you to send an argument for that parameter because a default one has already been assigned.
It therefore knows the function will be able to operate (to a certain extent) as it should.
It's useful for making optional parameters.
However when you declare a function as this:
testfunction($param1, $param2, $param3, $param4) {
    //do stuff
}

PHP Expects you to send through that argument ($param4), because without it, the function won't be able to accomplish what you've set it out to do, at least so PHP assumes, because you would never create a function with 4 parameters where not one of them are used in the function body.
Make sense?