text:
Q: Athena create table from json file with one column contains gzip base64 representation I guess this might sound odd, but I have a use-case where I need to load json files stored in s3 to athena.
However, one of the json fields contains a base64 representation of a gzipped large json file.
Is there a way to indicate that a field is gzipped when creating the athena table?
Or do I just pre-process the files first?


text:
Q: How to query nested hash in Ruby? What is the quickest way in Ruby to retrieve the correct hash by language from the following nested hash:
COUNTRIES = {
  "DE" => {:currency => "EUR", :tax_rates => [19, 7], :languages => ["de-de"]},
  "US" => {:currency => "USD", :tax_rates => [10], :languages => ["en-us"]}
}

I managed to retrieve the correct hash by providing the currency:
COUNTRIES.select{|key, hash| hash[:currency] == "USD" }

But how can I query by a language, for example by en-us?
Thanks for any help.

A: COUNTRIES.select{|key, hash| hash[:languages].include?("en-us")}
of note, if you're only looking for a singular result, it's cheaper to use #detect than it is to use #select.first

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tangential derivative vs covariant derivative My question is basically the same as this, but the answer in that page was not clear to me.
Let me restate the question here: let $\Omega\subset\mathbb{R}^3$ be a domain with boundary $\Gamma$, and let $\mathbf{u}$ be a vector field defined on all $\Omega$.
We define the surface stress as
$$
\mathbf{s}_t = \nabla \mathbf{u}\cdot\mathbf{n} - (\mathbf{n}\cdot\nabla \mathbf{u}\cdot\mathbf{n})\mathbf{n}
$$
Question: can I compute $\mathbf{s}_t$ using only $\nabla_\mathbf{v}\mathbf{u}$, for one or more suitable choices of $\mathbf{v}$? Here, $\nabla_\mathbf{v} \mathbf{u}$ denotes the covariant derivative of $\mathbf{u}$ along the vector $\mathbf{v}$.

A: If you mean the covariant derivative of $\mathbb R^3$, then yes, but since the covariant derivative coincides with the Euclidean derivative it's pretty much just rewriting the formula you already have as $$ {\bf s}_t = {\bf \nabla_n u - n\cdot(\nabla_n u)\;n}.$$
If you mean the covariant derivative of $\Gamma$, the answer is no: ${\bf s}_t$ depends explicitly upon the normal derivative while the covariant derivative of $\Gamma$ only measures changes in tangential directions.
If you define the "$\Gamma$-tangential derivative" of $u$ by $\nabla^\Gamma_v u = v\cdot\nabla u - ({\bf n} \cdot v\cdot \nabla u){\bf n}$ then it's true that ${\bf s}_t = \nabla_{\bf n} \bf u$ and it's also true that $\nabla^\Gamma$ agrees with the covariant derivative where the latter is defined. The issue is that $\bf n$ is not tangent to $\Gamma$, so it's not correct to call $\nabla^\Gamma_\bf nu$ a covariant derivative.


text:
Q: How to send Shortcut Keys using Batch I want to create a batch file, where I automatically press CTRL+s every few minutes.
until now I have
set /a i=0
:start
if /I %i% GEQ 10 goto :next
%SendKeys% "{^}"
%SendKeys% "{s}"
ping 1.1.1.1 -n 1 -w 300000 > nul
goto :start
:next

How can I send them together?

A: %SendKeys% "^s"

Look at http://msdn.microsoft.com/en-us/library/8c6yea83%28v=vs.84%29.aspx for the complete list of keys and modifiers for WshShell.SendKeys.


text:
Q: How do I get the first day of the week of a date in mysql? Suppose I have 2011-01-03 and I want to get the first of the week, which is sunday, which is 2011-01-02, how do I go about doing that?
The reason is I have this query:
select
  YEAR(date_entered) as year,
  date(date_entered) as week,   <-------This is what I want to change to select the first day of the week.
  SUM(1) as total_ncrs,
  SUM(case when orgin = picked_up_at then 1 else 0 end) as ncrs_caught_at_station
from sugarcrm2.ncr_ncr
where
sugarcrm2.ncr_ncr.date_entered > date('2011-01-01')
and orgin in(
'Silkscreen',
'Brake',
'Assembly',
'Welding',
'Machining',
'2000W Laser',
'Paint Booth 1',
'Paint Prep',
'Packaging',
'PEM',
'Deburr',
'Laser ',
'Paint Booth 2',
'Toolpath'
)
and date_entered is not null
and orgin is not null
AND(grading = 'Minor' or grading = 'Major')
 and week(date_entered) > week(current_timestamp) -20
group by year, week(date_entered)
order by year   asc, week asc

And yes, I realize that origin is spelled wrong but it was here before I was so I can't correct it as too many internal apps reference it.
So, I am grouping by weeks but I want this to populate my chart, so I can't have all the beginning of weeks looking like different dates. How do I fix this?

A: select '2011-01-03' - INTERVAL (WEEKDAY('2011-01-03')+1) DAY;

returns the date of the first day of week. You may look into it.

A: If you need to handle weeks which start on Mondays, you could also do it that way. First define a custom FIRST_DAY_OF_WEEK function:
DELIMITER ;;
CREATE FUNCTION FIRST_DAY_OF_WEEK(day DATE)
RETURNS DATE DETERMINISTIC
BEGIN
  RETURN SUBDATE(day, WEEKDAY(day));
END;;
DELIMITER ;

And then you could do:
SELECT FIRST_DAY_OF_WEEK('2011-01-03');

For your information, MySQL provides two different functions to retrieve the first day of a week. There is DAYOFWEEK:

Returns the weekday index for date (1 = Sunday, 2 = Monday, …, 7 = Saturday). These index values correspond to the ODBC standard.

And WEEKDAY:

Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).

A: This is a much simpler approach than writing a function to determine the first day of a week.
Some variants would be such as
SELECT DATE_ADD((SELECT CURDATE() - INTERVAL (WEEKDAY(CURDATE())+1)DAY),INTERVAL 7 DAY) (for the ending date of a query, such as between "beginning date" and "ending date").
SELECT CURDATE() - INTERVAL (WEEKDAY(CURDATE())+1) DAY (for the beginning date of a query).
This will return all values for the current week.  An example query would be as follows:
SELECT b.foo FROM bar b
WHERE b.datefield BETWEEN
(SELECT CURDATE() - INTERVAL (WEEKDAY(CURDATE())+1) DAY)
AND  (SELECT DATE_ADD((SELECT CURDATE() - INTERVAL (WEEKDAY(CURDATE())+1)DAY),INTERVAL 7 DAY))

A: If week starts on Monday
  SELECT SUBDATE(mydate, weekday(mydate));

If week starts on Sunday
  SELECT SUBDATE(mydate, dayofweek(mydate) - 1);

Example:
SELECT SUBDATE('2018-04-11', weekday('2018-04-11'));

2018-04-09
SELECT SUBDATE('2018-04-11', dayofweek('2018-04-11') - 1);

2018-04-08

A: Week starts  day from sunday then get First date  of the Week and Last date  of week
SELECT
  DATE("2019-03-31" + INTERVAL (1 - DAYOFWEEK("2019-03-31")) DAY) as start_date,
  DATE("2019-03-31" + INTERVAL (7 - DAYOFWEEK("2019-03-31")) DAY) as end_date

Week starts  day from Monday then get First date of the Week and Last date  of week
SELECT
  DATE("2019-03-31" + INTERVAL ( - WEEKDAY("2019-03-31")) DAY) as start_date,
  DATE("2019-03-31" + INTERVAL (6 - WEEKDAY("2019-03-31")) DAY) as end_date

A: If the week starts on Sunday do this:
DATE_ADD(mydate, INTERVAL(1-DAYOFWEEK(mydate)) DAY)

If the week starts on Monday do this:
DATE_ADD(mydate, INTERVAL(-WEEKDAY(mydate)) DAY);

more info

A: This works form me
Just make sure both dates in the below query are the same...
SELECT ('2017-10-07' - INTERVAL WEEKDAY('2017-10-07') Day) As `mondaythisweek`

This query returns: 2017-10-02 which is a monday,
But if your first day is sunday, then just subtract a day from the result of this and wallah!

A: If the week starts on Monday do this:
DATE_SUB(mydate, INTERVAL WEEKDAY(mydate) DAY)

A:   SELECT MIN(DATE*given_date*) FROM *table_name*

This will return when the week started at for any given date.
Keep the good work going!


text:
Q: Restoring C drive image from DVD after booting the computer from bootable disc If I take image of C drive and burn it on DVD, can I restore this image after booting the computer from a bootable disk? If yes, then how?
I am supposing that restoring C drive image in this way will bring my computer to the exact state of the time when I took image of C drive. Is It correct?
Thanks in advance.
Picarodevosio

A: The question is kinda stupid, my apologies because as mentioned by Cody Gray, Whatever program you use for taking image of C drive must have a restore option. One such program, which i personally use is "DriveImage XML", available free at http://www.runtime.org/
What you do is you take an image of your C drive or whatever drive you wanna backup (preferably at a time when you believe your system is working absolutely fine). You should create the backup in some external drive. In case your windows later gets corrupted, all you have to do is format C and install a fresh copy of window. Install the above-mentioned or whatever program you used for taking image. select "Restore" and you PC should work as it worked at the time you took the image.
Hope it works for all


text:
Q: Is there an easier way to test argument validation and field initialization in an immutable object? My domain consists of lots of simple immutable classes like this:
public class Person
{
    public string FullName { get; }
    public string NameAtBirth { get; }
    public string TaxId { get; }
    public PhoneNumber PhoneNumber { get; }
    public Address Address { get; }

    public Person(
        string fullName,
        string nameAtBirth,
        string taxId,
        PhoneNumber phoneNumber,
        Address address)
    {
        if (fullName == null)
            throw new ArgumentNullException(nameof(fullName));
        if (nameAtBirth == null)
            throw new ArgumentNullException(nameof(nameAtBirth));
        if (taxId == null)
            throw new ArgumentNullException(nameof(taxId));
        if (phoneNumber == null)
            throw new ArgumentNullException(nameof(phoneNumber));
        if (address == null)
            throw new ArgumentNullException(nameof(address));

        FullName = fullName;
        NameAtBirth = nameAtBirth;
        TaxId = taxId;
        PhoneNumber = phoneNumber;
        Address = address;
    }
}

Writing the null checks and property initialization is already getting very tedious but currently I write unit tests for each of these classes to verify that argument validation works correctly and that all properties are initialized. This feels like extremely boring busywork with incommensurate benefit.
The real solution would be for C# to support immutability and non-nullable reference types natively. But what can I do to improve the situation in the meantime? Is it worth writing all these tests? Would it be a good idea to write a code generator for such classes to avoid writing tests for each one of them?

Here is what I have now based on the answers.
I could simplify the null checks and property initialization to look like this:
FullName = fullName.ThrowIfNull(nameof(fullName));
NameAtBirth = nameAtBirth.ThrowIfNull(nameof(nameAtBirth));
TaxId = taxId.ThrowIfNull(nameof(taxId));
PhoneNumber = phoneNumber.ThrowIfNull(nameof(phoneNumber));
Address = address.ThrowIfNull(nameof(address));

Using the following implementation by Robert Harvey:
public static class ArgumentValidationExtensions
{
    public static T ThrowIfNull<T>(this T o, string paramName) where T : class
    {
        if (o == null)
            throw new ArgumentNullException(paramName);

        return o;
    }
}

Testing the null checks is easy using the GuardClauseAssertion from AutoFixture.Idioms (thanks for the suggestion, Esben Skov Pedersen):
var fixture = new Fixture().Customize(new AutoMoqCustomization());
var assertion = new GuardClauseAssertion(fixture);
assertion.Verify(typeof(Address).GetConstructors());

This could be compressed even further:
typeof(Address).ShouldNotAcceptNullConstructorArguments();

Using this extension method:
public static void ShouldNotAcceptNullConstructorArguments(this Type type)
{
    var fixture = new Fixture().Customize(new AutoMoqCustomization());
    var assertion = new GuardClauseAssertion(fixture);

    assertion.Verify(type.GetConstructors());
}

A: In the short term, there's not much you can do about the tediousness of writing such tests. However, there is some help coming with throw expressions due to be implemented as part of the next release of C# (v7), likely due in the next few months:
public class Person
{
    public string FullName { get; }
    public string NameAtBirth { get; }
    public string TaxId { get; }
    public PhoneNumber PhoneNumber { get; }
    public Address Address { get; }

    public Person(
        string fullName,
        string nameAtBirth,
        string taxId,
        PhoneNumber phoneNumber,
        Address address)
    {
        FullName = fullName ?? throw new ArgumentNullException(nameof(fullName));
        NameAtBirth = nameAtBirth ?? throw new ArgumentNullException(nameof(nameAtBirth));
        TaxId = taxId ?? throw new ArgumentNullException(nameof(taxId)); ;
        PhoneNumber = phoneNumber ?? throw new ArgumentNullException(nameof(phoneNumber)); ;
        Address = address ?? throw new ArgumentNullException(nameof(address)); ;
    }
}

You can experiment with throw expressions via the Try Roslyn webapp.

A: I'm surprised no one mentioned NullGuard.Fody yet. It's available via NuGet and will automagically weave those null checks into the IL during compile time.
So your constructor code would simply be
public Person(
    string fullName,
    string nameAtBirth,
    string taxId,
    PhoneNumber phoneNumber,
    Address address)
{
    FullName = fullName;
    NameAtBirth = nameAtBirth;
    TaxId = taxId;
    PhoneNumber = phoneNumber;
    Address = address;
}

and NullGuard will add those null checks for you transforming it into exactly what you wrote.
Note though, that NullGuard is opt-out, that is, it will add those null checks to every method and constructor argument, property getter and setter and even check method return values unless you explicitly allow a null value with the [AllowNull] attribute.

A:
Is it worth writing all these tests?

No, probably not. What is the likelihood that you're going to screw that up? What is the likelihood that some semantics will change out from under you? What is the impact if someone does screw it up?
If you're spending a bunch of time making tests for something that will rarely break, and is a trivial fix if it did... maybe not worth it.

Would it be a good idea to write a code generator for such classes to avoid writing tests for each one of them?

Maybe? That sort of thing could be done easily with reflection. Something to consider is doing code generation for the real code, so you don't have N classes that may have human error. Bug prevention > bug detection.

A: I created a t4 template exactly for this kind of cases. To avoid writing lots of boilerplate for Immutable classes.
https://github.com/xaviergonz/T4Immutable
T4Immutable is a T4 template for C# .NET apps that generates code for immutable classes.
Specifically talking about non null tests then if you use this:
[PreNotNullCheck, PostNotNullCheck]
public string FirstName { get; }

The constructor will be this:
public Person(string firstName) {
  // pre not null check
  if (firstName == null) throw new ArgumentNullException(nameof(firstName));

  // assignations + PostConstructor() if needed

  // post not null check
  if (this.FirstName == null) throw new NullReferenceException(nameof(this.FirstName));
}

Having said this, if you use JetBrains Annotations for null checking, you can also do this:
[JetBrains.Annotations.NotNull, ConstructorParamNotNull]
public string FirstName { get; }

And the constructor will be this:
public Person([JetBrains.Annotations.NotNull] string firstName) {
  // pre not null check is implied by ConstructorParamNotNull
  if (firstName == null) throw new ArgumentNullException(nameof(firstName));

  FirstName = firstName;
  // + PostConstructor() if needed

  // post not null check implied by JetBrains.Annotations.NotNull on the property
  if (this.FirstName == null) throw new NullReferenceException(nameof(this.FirstName));
}

Also there are a few more features than this one.

A: You could always write a method like the following:
// Just to illustrate how to call this
private static void SomeMethod(string a, string b, string c, string d)
    {
        ValidateArguments(a, b, c, d);
        // ...
    }

    // This is the one to use as a utility function
    private static void ValidateArguments(params object[] args)
    {
        for (int i = 0; i < args.Length; i++)
        {
            if (args[i] == null)
            {
                StackTrace trace = new StackTrace();
                // Get the method that called us
                MethodBase info = trace.GetFrame(1).GetMethod();

                // Get information on the parameter that is null so we can add its name to the exception
                ParameterInfo param = info.GetParameters()[i];

                // Raise the exception on behalf of the caller
                throw new ArgumentNullException(param.Name);
            }
        }
    }

At a minimum, that'll save you some typing if you have several methods that require this kind of validation. Of course, this solution assumes that none of your method's parameters can be null, but you can modify this to change that if you so desire.
You can also extend this to perform other type-specific validation. For example, if you have a rule that strings can't be purely whitespace or empty, you could add the following condition:
// Note that we already know based on the previous condition that args[i] is not null
else if (args[i].GetType() == typeof(string))
            {
                string argCast = arg as string;

                if (!argCast.Trim().Any())
                {
                    ParameterInfo param = GetParameterInfo(i);

                    throw new ArgumentException(param.Name + " is empty or consists only of whitespace");
                }
            }

The GetParameterInfo method I refer to basically does the reflection (so that I don't have to keep typing the same thing over and over, which would be a violation of the DRY principle):
private static ParameterInfo GetParameterInfo(int index)
    {
        StackTrace trace = new StackTrace();

        // Note that we have to go 2 methods back to get the ValidateArguments method's caller
        MethodBase info = trace.GetFrame(2).GetMethod();

        // Get information on the parameter that is null so we can add its name to the exception
        ParameterInfo param = info.GetParameters()[index];

        return param;
    }

A: Is it worth writing all these tests?
No.
Because I am pretty sure you have tested those properties through some other tests of logic where those classes are used.
For example, you can have tests for Factory class which have assertion based on those properties (Instance created with properly assigned Name property for example).
If those classes are exposed to the public API which used by some third part/end user (@EJoshua thanks for noticing), then tests for expected ArgumentNullException can be useful.
While waiting for C#7 you can use extension method
public MyClass(string name)
{
    name.ThrowArgumentNullExceptionIfNull(nameof(name));
}

public static void ThrowArgumentNullExceptionIfNull(this object value, string paramName)
{
    if(value == null)
        throw new ArgumentNullException(paramName);
}

For testing you can use one parameterized test method which use reflection to create null reference for every parameter and assert for expected exception.

A: You can get a bit of improvement with a simple refactoring that can ease the problem of writing all those fences.  First, you need this extension method:
internal static T ThrowIfNull<T>(this T o, string paramName) where T : class
{
    if (o == null)
        throw new ArgumentNullException(paramName);

    return o;
}

You can then write:
public class Person
{
    public string FullName { get; }
    public string NameAtBirth { get; }
    public string TaxId { get; }
    public PhoneNumber PhoneNumber { get; }
    public Address Address { get; }

    public Person(
        string fullName,
        string nameAtBirth,
        string taxId,
        PhoneNumber phoneNumber,
        Address address)
    {
        FullName = fullName.ThrowIfNull(nameof(fullName));
        NameAtBirth = nameAtBirth.ThrowIfNull(nameof(nameAtBirth));
        TaxId = taxId.ThrowIfNull(nameof(taxId));
        PhoneNumber = phoneNumber.ThrowIfNull(nameof(fullName));
        Address = address.ThrowIfNull(nameof(address));
    }
}

Returning the original parameter in the extension method creates a fluent interface, so you can extend this concept with other extension methods if you wish, and chain them all together in your assignment.
Other techniques are more elegant in concept, but progressively more complex in execution, such as decorating the parameter with a [NotNull] attribute, and using Reflection like this.
That said, you may not need all these tests, unless your class is part of a public-facing API.

A: I do not suggest throwing exceptions from the constructor. The problem is you will have a hard time to test this as you have to pass valid parameters even they are irrelevant for your test.
For example: If you want to test if the third parameter throws an exception you have to pass in the first and the second correctly. So your test is not isolated anymore. when the constraints of the first and second parameter change this test case will fail even it tests the third parameter.
I suggest to use the java validation API and externalize the validation process. I suggest to have four responsibilities (classes) involved:

*

*A suggestion object with Java validation annotated parameters with a validate method that returns a Set of ConstraintViolations. One advantage is you can pass around this objects without the assertion to be valid. You can delay validation until it is neccessary without having a try to instantiate the domain object. The validation object can be used in different layers as it is a POJO with no layer specific knowledge. It can be part of you public API.

*A factory for the domain object that is responsible for creating valid objects. You pass in the suggestion object and the factory will call the validation and create the domain object if everything is fine.

*The domain object itself which should be mostly inaccessible for instantiation for other developers. For testing purposes I suggest to have this class in package scope.

*A public domain interface to hide the concrete domain object and make misusage hard.
I do not suggest to check for null values. As soon as you get into the domain layer you have get rid of passing in null or returning null as long as you do not have object chains that have ends or search functions for single objects.
One other point: writing as less code as possible is not a metric for code quality. Think about 32k games competitions. That code is the most compact but also the messiest code you can have because it does only care about technical issues and does not care about semantics. But semantics are the points that make things comprehensive.


text:
Q: How to get GitHub repository Default Branch name with GraphQL? Is there a way to use GitHub's GraphQL API to retrieve the default branch name of a repository? I can build a query to get all the branch names, but none of the properties I see reference the default branch name. Some repositories I deal with have 'master' for their default, and others have 'main'.
I am aware I can use the HEAD in some commands to workaround this. Such as "HEAD:README.md" for fetching the README.md file, like in this example query below. This repository's default branch is 'main', and I only know that from manual trial and error.
query {
  repository(owner: "newrelic", name: "newrelic-ruby-agent") {
    object(expression: "HEAD:README.md") {
      ... on Blob {
        text
      }
    }
  }
}

But when I check the local cloned copy of that repository, the .git/HEAD file points to ref: refs/heads/dev. So it seems I am actually pulling the README.md file from the dev branch, and not the default branch?
So is there a nice way to get the name of the default branch for a GitHub repository using their GraphQL API?

A: There's a field defaultBranchRef on the repository object:
query {
  repository(owner: "newrelic", name: "newrelic-ruby-agent") {
    defaultBranchRef {
      name
    }
  }
}


text:
Q: How to better design the delete operation in an Android CRUD I am having some questions about how to better design a crud application (specifically the delete operation) on a basic Android CRUD app
The workflow that I'm using is a RecyclerView in my MainActivity, and when I click a fab, I go to a new activity and handle the Add operation there. The same goes for the Edit operation, when I click an item in the list it goes to a new activity and I handle the deletion there.
The problem with the delete operation is that I want to implement a long item click, open a popup and do the deletion. I don't need a new activity.
So, is it better to create a new Acitivity to handle the deletion, don't display any layout, and redirect back to the MainActivity after? Or should I put the deletion logic on the MainActivity inside a onClickListener? I'm really confused on how to do this in a clean way


text:
Q: C# WebRequest POST Parameters are not coming through I'm trying to post to a webpage using WebClient in C#.
Somehow the parameters are not coming through.
The page itself is a php page.
I've tested the same page with a regular browser/html page and then it works, so I'm expecting that it is a client issue
Can anybody tell me what I might be doing wrong?
        WebClient myClient = new WebClient();
        myClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
        try
        {
            NameValueCollection keyvaluepairs = new NameValueCollection();
            keyvaluepairs.Add("request", "foo");
            byte[] responseArray = myClient.UploadValues("http://www.motio.com/test.php?id=7", "POST", keyvaluepairs);
            string response = Encoding.ASCII.GetString(responseArray);
        }
        catch (Exception e)
        {
        }

A: Did you try doing a GET instead of a POST just to make sure it is something wrong with the web request itself?

A: I'm very sorry for taking up your time. After further investigation, it turned out that the url I used was using http and the server redirected me to http, losing the post variables.


text:
Q: Change Text in Array in Javascript I have the following list:
    var submenu = localStorage.getItem('SubMenu')
    var submenuList = submenu.split(',');

0: "Ownership"
1: "Skills
Dev"
2: "Financing
and ESD"
3: "Socio-Economic
Dev"
4: "Access to
Financial Services"
5: "Board Participation"
6: "Employee Structure"
7: "Preferential Procurement"
8: "Enterprise Development"
9: "Supplier Development"

What I want to do is write a forEach statement in Javascript to replace some certain words with my own hard coded work. For example, where Dev appears I want to change it to Development and where Financing
and ESD I want to change it to Empowerment Financing
I tried the replace method of my list but that gives me errors because i am getting confused with my forEach statement
This is what i have tried
submenuList.forEach(word =>{allMenuItems = allMenuItems.replace('Dev','Development')})

A: forEach doesn't allow you to modify each element like that. Put simply, the word value in your handler is just a value, not a reference to the item in the array. You can either use a for loop to actually get a reference to each element in the array (not recommended), or you can use map to modify each word instead.
submenuList = submenuList.map(
  word => word.replace(
    'Dev',
    'Development'
  )
)

A: Refer to MDN:

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.

replace() method return new replaced string, not actual replace on the source string, so you should use map instead of forEach because map will take all of the output and return them in new array.
And also, because you want to replace every occurence of 'Dev' or 'Financing
and ESD', you should use replace with regular expressions with global flag. Replace by string pattern will only replace first occurence.
Example code:
var submenu = localStorage.getItem('SubMenu')
var submenuList = submenu.split(',');
var result = submenuList.map(element => element.replace(/Dev/g, 'Development').replace(/Financing
and ESD/g, 'Empowerment Financing'));

Improvement:
You should replace the string before do split. So you don't need to forEach or map and improve performance.
Example code:
var submenu = localStorage.getItem('SubMenu')
var replacedSubmenu = submenu.replace(/Dev/g, 'Development').replace(/Financing
and ESD/g, 'Empowerment Financing');
var result = replacedSubmenu.split(',');

A: const arr = [
 "Ownership",
 "Skills
Dev",
 "Financing
and ESD",
 "Socio-Economic
Dev",
 "Access to
Financial Services",
 "Board Participation",
 "Employee Structure",
 "Preferential Procurement",
 "Enterprise Development",
 "Supplier Development"
]

const newArr = [];

for(let item of arr) {
  if(item.endsWith("Dev")) {
    console.log("Dev found");
    newArr.push(item.replace("Dev", "Development"));
  } else {
    newArr.push(item);
  }
}

console.dir(newArr);


text:
Q: Comparing relative velocities and kinetic energy If object one is moving $0\frac{m}{s}$ relative to the Earth and object two is moving $1\frac{m}{s}$ and they both have $1kg$ of mass, then object one has no kinetic translational energy (relative to the Earth?) but object two has $\frac12$ joules of kinetic translational energy.
Which should mean that if I add in their kinetic energies due to the speed at which the Earth is rotating, object two should half of a joule more kinetic energy?  But upon doing the calculations, the fact that kinetic translational energy is given as $K=\frac12mV^2$ means that by moving $1\frac{m}{s}$ faster than object one, object two has much more kinetic energy.
Could someone explain what happened?

A: The initial calculations of kinetic energy are correct in the local rest frame (the Earth).  However the relative energy differences are not the same in other rest frames.
One way of thinking about this is to remember that work is "force times distance".   Imagine you want to "push" two objects to accelerate them each by 1 $\frac{m}{s}$, but one is at rest and the other is already travelling 1 $\frac{m}{s}$.  You will have to exert the same force on the two objects - but that force will be exerted over a longer distance for the object which is already moving - thus it will accumulate more kinetic energy going from 1 $\frac{m}{s}$ to 2 $\frac{m}{s}$ than the object which goes from 0  $\frac{m}{s}$ to 1 $\frac{m}{s}$.


text:
Q: Real method is called instead of SpyOn method in Nest JS unit test I am implementing unit test in the framework NestJS using Jasmin. And I have a problem with testing one of my service. After long time of debugging I have no idea what's wrong with my code. It looks like my service does't use Spy function and uses real method.
I'm using these versions of packages:
package.json
"jasmine": "3.1.0"
"@nestjs/testing": "4.6.6"
"@nestjs/common": "4.6.6"
"typescript": "2.6.2"
"node": "8.8.1"

I had a problem during testing one method - prepareOrderDataOnCreate.
In this method I invoke 2 methods from other services.
order.service.ts
@Component()
export class OrdersServiceComponent {
  constructor(
    private userService: UsersServiceComponent,
    private orderStatusService: OrderStatusServiceComponent,
    ...) {}

  async prepareOrderDataOnCreate(user): Promise<Order> {
    const status = await this.orderStatusService.getStatus();
    const user = await this.userService.getOne(user.id);

    return {
      ...
    };
  }
}

I mocked both services and created SpyOn for both methods to check if they toHaveBeenCalled. But when I run test get an error:

Error:  : Expected a spy, but got Function.

After debugging I found out that unit test uses usersService.getOne not from SpyOn, but from mock file (see below user.service.mock.ts), despite the fact that orderStatusService.getStatus is used from SpyOn.
order.service.spec.ts
describe('OrdersServiceComponent', () => {
  let ordersService: OrdersServiceComponent;
  let usersService: UsersServiceMock;

  beforeEach(async() => {
    const module = await Test.createTestingModule({
      controllers: [OrdersController],
      components: [
        OrdersServiceComponent,
        {provide: UsersServiceComponent, useClass: UsersServiceMock},
        {provide: OrderStatusServiceComponent, useClass: OrderStatusServiceMock},
        ...
      ]
    }).compile();

    ordersService = module.get<OrdersServiceComponent>(OrdersServiceComponent);
    orderStatusService = module.get<OrderStatusServiceMock>(OrderStatusServiceComponent as any);
    usersService = module.get<UsersServiceMock>(UsersServiceComponent as any);
  });

  it('prepareOrderDataOnCreate method returns order on success', () => {
    spyOn(orderStatusService, 'getStatus').and.stub();
    spyOn(usersService, 'getOne').and.callFake(() => console.log('SPY'));

    ordersService.prepareOrderDataOnCreate({...}).then(res => {
      expect(usersService.getOne).toHaveBeenCalled();
      expect(orderStatusService.getStatus).toHaveBeenCalled();
    });
  });
});

Instead of Spy unit test uses this mock method:
user.service.mock.ts
@Component()
export class UsersServiceMock {
  async getOne(): Promise<any> {
    return Promise.resolve({});
  }
}

It's really strange, because in case when I invoked usersService.getOne() in this unit test before prepareOrderDataOnCreate() I got console.log from callFake.
UPDATE
I found out that when I run my test and invoke service method prepareOrderDataOnCreate, at first userService.getOne is Spy function and after any code inside the method userService.getOne is changed to real function.
async prepareOrderDataOnCreate(user): Promise<Order> {
    /*  this.userService.getOne is SPY FUNCTION */

    const status = await this.orderStatusService.getStatus();

    /*  this.userService.getOne is REAL MOCK FUNCTION */

    const user = await this.userService.getOne(user.id);

    ...
  }

A: I am not a Jasmine expert, but I believe you have to keep references to your spies in variables and run your assertions on those spy objects. Bellow is what it could look like.
it('prepareOrderDataOnCreate method returns order on success', () => {
  const getStatusSpy = spyOn(orderStatusService, 'getStatus').and.stub();
  const getOneSpy = spyOn(usersService, 'getOne').and.callFake(() => console.log('SPY'));

  ordersService.prepareOrderDataOnCreate({...}).then(res => {
    expect(getOneSpy).toHaveBeenCalled();
    expect(getStatusSpy).toHaveBeenCalled();
  });
});

You can also use async/await, for a cleaner style.
it('prepareOrderDataOnCreate method returns order on success', async () => {
  const getStatusSpy = spyOn(orderStatusService, 'getStatus').and.stub();
  const getOneSpy = spyOn(usersService, 'getOne').and.callFake(() => console.log('SPY'));

  await ordersService.prepareOrderDataOnCreate({...})

  expect(getOneSpy).toHaveBeenCalled();
  expect(getStatusSpy).toHaveBeenCalled();

});


text:
Q: dc.js send dimension data to node.js server in json format, then using java to process the data {"Account":"789","Date":"2013-07-31","Unique Id":"2013073101","Tran Type":"TFR OUT","Cheque Number":"","TranCode":"MB TRANSFER","ThirdPartyAccount":"123","Amount":"-20","formatedDate":"2013-07-30T12:00:00.000Z"}
{"Account":"789","Date":"2013-07-30","Unique Id":"2013073005","Tran Type":"TFR IN","Cheque Number":"","TranCode":"MB TRANSFER","ThirdPartyAccount":"123","Amount":"20","formatedDate":"2013-07-29T12:00:00.000Z"}
{"Account":"789","Date":"2013-07-30","Unique Id":"2013073004","Tran Type":"TFR OUT","Cheque Number":"","TranCode":"MB TRANSFER","ThirdPartyAccount":"123","Amount":"-20","formatedDate":"2013-07-29T12:00:00.000Z"}
{"Account":"789","Date":"2013-07-30","Unique Id":"2013073003","Tran Type":"CREDIT","Cheque Number":"","TranCode":"CREDIT","ThirdPartyAccount":"123","Amount":"20","formatedDate":"2013-07-29T12:00:00.000Z"}
{"Account":"789","Date":"2013-07-30","Unique Id":"2013073002","Tran Type":"TFR OUT","Cheque Number":"","TranCode":"MB TRANSFER","ThirdPartyAccount":"123","Amount":"-160","formatedDate":"2013-07-29T12:00:00.000Z"}
{"Account":"789","Date":"2013-07-30","Unique Id":"2013073001","Tran Type":"CREDIT","Cheque Number":"","TranCode":"CREDIT","ThirdPartyAccount":"123","Amount":"160","formatedDate":"2013-07-29T12:00:00.000Z"}

This is the output of the dimension of crossfilter.js with dc.js, I want to sent this string to a java program to convert this to json object, then I want to read the data and extract some data. Sent string in json format back to client side.
This is how to create the output
var dimData = accountDim.top(Infinity);
var dddata = [];
dimData.forEach(function (x) {
    console.log(JSON.stringify(x));
    dddata.push(JSON.stringify(x));
});
$.get(window.location.href + "toJSON?files=" + dddata.join(), function (){});

My JAVA program:
public static void main(String[] args) throws IOException, ParseException {
    JSONParser parser = new JSONParser();
    JSONObject jsons = (JSONObject) parser.parse(args[0]);
    PrintWriter writer = new PrintWriter("res.json", "UTF-8");
    writer.println(jsons);
    writer.close();
}

This is my http server in node.js
var express = require('express');
var app = express();

app.use('/JS',express.static(__dirname + '/JS'));
app.use('/CSS',express.static(__dirname + '/CSS'));
app.use('/', express.static(__dirname + '/'));

app.get('/', function (req, res) {
    // res.sendFile("/index.html");
}).listen(8080);

app.get('/toJSON', function(req, res, next) {
    process.stdout.write('Extracting data to JSON...... ');
    var files = req.query.files;
    var spawn = require('child_process').spawn;
    var child = spawn('java',  ['-cp', 'Jarfile/CSVExtractor.jar:.', 'toJSON.ToJSON', files]);
    process.stdout.write("done.\n");

    child.stderr.on('data', function (data) {
    process.stderr.write(data);
    }).on('end', function() {
        res.end();
    });

    child.stdout.on('data', function (data) {
        res.write(data);
    }).on('end', function() {
        res.end();
    });
});

My question is are there any better way to sent the dimension data to java via node.js, if not, how can I convert the string to json like this, then retrieve the data?
Can anybody help me? Any help would be appreciated.

A: You can use org.json.JSONObject library for converting string into json object and then retrieve the elements.
String json1 = "{\"Account\":\"789\",\"Date\":\"2013-07-31\",\"Unique Id\":\"2013073101\",\"Tran Type\":\"TFR OUT\",\"Cheque Number\":\"\",\"TranCode\":\"MB TRANSFER\",\"ThirdPartyAccount\":\"123\",\"Amount\":\"-20\",\"formatedDate\":\"2013-07-30T12:00:00.000Z\"}";

    JSONObject jsonObject = new JSONObject(json1);
    if (jsonObject.has("ThirdPartyAccount")) {
        String thirdPartyAccount = jsonObject.getString("ThirdPartyAccount");
        System.out.println(thirdPartyAccount);
    }

Try it.

A: Try gson, you can parse from string to json very simple
private static JsonParser jp = new JsonParser();
String data = "......." // your data string here
JsonObject = jp.parse(data).getAsJsonObject();

A: You can use Gson library from Google.
   Gson gson = new GsonBuilder();
   Transaction transaction = gson.fromJson(args[0], Transaction.class);

Transaction is plain Java that describes your Json. In your case it can be:
public class Transaction {

   private String Account;
   private Date date;
...
}

A: {"Account":"789","Date":"2013-07-31","Unique Id":"2013073101","Tran Type":"TFR OUT","Cheque Number":"","TranCode":"MB TRANSFER","ThirdPartyAccount":"123","Amount":"-20","formatedDate":"2013-07-30T12:00:00.000Z"}
{"Account":"789","Date":"2013-07-30","Unique Id":"2013073005","Tran Type":"TFR IN","Cheque Number":"","TranCode":"MB TRANSFER","ThirdPartyAccount":"123","Amount":"20","formatedDate":"2013-07-29T12:00:00.000Z"}
{"Account":"789","Date":"2013-07-30","Unique Id":"2013073004","Tran Type":"TFR OUT","Cheque Number":"","TranCode":"MB TRANSFER","ThirdPartyAccount":"123","Amount":"-20","formatedDate":"2013-07-29T12:00:00.000Z"}
{"Account":"789","Date":"2013-07-30","Unique Id":"2013073003","Tran Type":"CREDIT","Cheque Number":"","TranCode":"CREDIT","ThirdPartyAccount":"123","Amount":"20","formatedDate":"2013-07-29T12:00:00.000Z"}
{"Account":"789","Date":"2013-07-30","Unique Id":"2013073002","Tran Type":"TFR OUT","Cheque Number":"","TranCode":"MB TRANSFER","ThirdPartyAccount":"123","Amount":"-160","formatedDate":"2013-07-29T12:00:00.000Z"}
{"Account":"789","Date":"2013-07-30","Unique Id":"2013073001","Tran Type":"CREDIT","Cheque Number":"","TranCode":"CREDIT","ThirdPartyAccount":"123","Amount":"160","formatedDate":"2013-07-29T12:00:00.000Z"}

If you assured about order of your dimension not changed and to large amount dimension, Then you can go for below json (Note: null not acceptable)
{
  "Account": [
    789,
    789,
    789
  ],
  "Date": [
    "2013-07-31",
    "2013-07-30",
    "2013-07-31"
  ],
  "Unique Id": [
    2013073101,
    2013073102,
    2013073103
  ]
}

And you can parse it easily from java client side, Each index applicable for all JSONArray, I choose few keys and values for showing my JSON structure.

A: The answer I found is the combination of the answers above. Thanks all helping, I want to mark all your reply as answer but the stackoverflow does not allow this. Sorry about that.
So the answer I found is that:
In javascript:
$.get(window.location.href + "toJSON?data=" + JSON.stringify(accountDim.top(Infinity)), drawForceLayout);

(accountDim.top(Infinity))This will get all dimension data as json object array before you filter or after, then use JSON.stringify to convert the json object array to string in json format, then send the request to server.
This is the code in java:
JSONArray jsonArray = new JSONArray(args[0]);
for (int i = 0; i < jsonArray.length(); i++){
        JSONObject jsonObj = jsonArray.getJSONObject(i);
        accounts.put(jsonObj.getString("Account"), jsonObj.getDouble("Amount"), jsonObj.getString("ThirdPartyAccount"));
    }

The accounts is my object. Using JSONObject to retrieve the data.
The java library is org.json.JSONArray;
Thanks again for all your help!!!


text:
Q: How to split resolvers for Query type in Hot Chocolate I am trying to achieve a standard GraphQL implementation, using the Hot Chocolate library for .net core, where the resolvers for reading data belong to the root Query object.
Like this:
{
  Query {
    GetTodo {
      Id
    }
  }
}

This is what I made trying to follow the documentation, but it doesn't work as I expect:
startup.cs
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ChocodotContext>();
            services.AddGraphQL(
                SchemaBuilder.New()
                .AddQueryType<QueryType>()
                .BindResolver<TodoQueries>()
                .Create()
            );
        }

Query.cs
using HotChocolate.Types;

namespace Queries
{
    public class QueryType : ObjectType
    {
        protected override void Configure(IObjectTypeDescriptor descriptor)
        {

        }
    }
}

TodoQueries.cs
using System.Threading.Tasks;
using HotChocolate;
using HotChocolate.Types;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using Models;

namespace Queries
{
    [GraphQLResolverOf(typeof(Todo))]
    [GraphQLResolverOf("Query")]
    public class TodoQueries
    {
        public async Task<Todo> GetTodo([Service] ChocodotContext dbContext) {
            return await dbContext.Todos.FirstAsync();
        }
    }

    public class TodoQueryType : ObjectType<TodoQueries> {

    }
}

What am I not getting right?

A: You need to change it a little:
query {
  todo {
    id
  }
}

startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ChocodotContext>();
    services.AddGraphQL(serviceProvider =>
        SchemaBuilder.New()
            .AddServices(serviceProvider)
            .AddQueryType<Query>()
            .AddType<TodoQueries>()
            .Create()
    );
}

Query.cs
using HotChocolate.Types;

namespace Queries
{
    public class Query
    {

    }
}

TodoQueries.cs
[ExtendObjectType(Name = "Query")]
public class TodoQueries
{
    // Side note, no need for async/await while it returns Task<>
    //
    public Task<Todo> GetTodo([Service] ChocodotContext dbContext) {
        return dbContext.Todos.FirstAsync();
    }
}

Tested with HotChocolate 10.5.2
Source of solution - ChilliCream Blog, HotChocolate 10.3.0 article, TypeAttributes section.


text:
Q: PC communication with android through USB I need some guidance..
I have an application (.net) on my PC (windows) that needs to send some data or file (JSON format) through USB to android tablet (4.4.2). I want to design a new app which could accept this data.
I did some research over internet and found some options to implement this but still all of it is not so clear for me:

*

*My first option to do this is – port forwarding by adb shell. My PC need to have adb installed and some drivers. Is it right? Is it possible that .net exe will use this way on pc side?

*Second option – my PC should be "USB host" and android tablet should be "USB accessory". Is it better way? And again, is it possible that .net application will implement it?

*Last option is use WPD api.. https://github.com/geersch/WPD/blob/master/src/part-3/README.md
Which one is better?
I'll be glad to hear some clarifications on this subject or any recommendations or if there is some other way to do this.
Thanks a lot


text:
Q: How to query in EF core with OrderByDescending, Take, Select and FirstOrDefault So I've got a table named Summaries, it looks like this
I need to get to sum the latest entries of TotalPieces based on CoveredDate and should be grouped by ServiceCode and queried by month
for example, ServiceCode 'A' has entries on 2020-01-01, 2020-01-02, 2020-01-03, 2020-01-31, 2020-02-01, 2020-02-28, 2020-02-29
and ServiceCode 'B' has entries on 2020-01-01, 2020-01-02, 2020-01-31, 2020-02-20, 2020-02-21,
i need to get the sum based on month, lastest entry on 'A' on January is on 2020-01-31,  and 'B' has latest entry on 2020-01-31, I need to sum their 'TotalPieces', so I should get 25 + 25 = 50.
basically i need to do is

*

*Get all the lastest entries based on CoveredDate and month/year

*Sum the TotalPieces by ServiceCode
i got a working query, but this is just a workaround because i can't get it right on query.
            int sum_totalpieces = 0;
            foreach (var serviceCode in service_codes)
            {
                var totalpieces = _DbContext.ActiveSummaries.Where(acs =>
                                    acs.CoveredDate.Date.Month == query_month
                                    && acs.CoveredDate.Date.Year == query_year
                                    && acs.service_codes == serviceCode
                                    )
                    .OrderByDescending(obd => obd.CoveredDate)
                    .Take(1)
                    .Select(s => s.TotalPieces)
                    .ToList()
                    .FirstOrDefault();

                sum_totalpieces += totalpieces;
            }

the service_codes is just a List of string
If you guys could just get rid of the foreach block their and make it services_codes.Contains() on query, or another workaround to make the result faster that would be great. Thanks a lot.

A: This will do it, but I don't think it will translate to SQL and run at the server:
    _DbContext.ActiveSummaries
            .Where(b =>
                b.CoveredDate >= new DateTime(2020,1,1) &&
                b.CoveredDate < new DateTime(2020,2,1) &&
                new [] { "A", "B" }.Contains(b.ServiceCode)
            )
            .GroupBy(g => g.ServiceCode)
            .Sum(g => g.OrderByDescending(gb=> gb.CoveredDate).First().TotalPieces);

If you want to do it as a raw SQL for best performance it would look like:
SELECT SUM(totalpieces)
FROM
  x
  INNER JOIN
  (
    SELECT servicecode, MAX(covereddate) cd
    FROM x
    WHERE x.servicecode IN ('A','B') AND covereddate BETWEEN '2020-01-01' AND '2020-01-31'
  )y ON x.servicecode=y.servicecode and x.covereddate = y.cd


text:
Q: rand() function in C is not random even when seeded This is most likely a machine dependent issue but I can't figure out what could be wrong.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char** argv) {

  srand(time(NULL));
  int r1 = rand();
  int r2 = rand();
  printf("%d %d\n", r1, r2);
}

I compile the above piece of code using
gcc randd.c

Then running it a few times manually and the first numbers seem incredibly similar while the second ones seem random:
1025720610 1435057801
1025737417 1717533050
1025754224 2000008299
1025771031 134999901
1025787838 417475150

This first call to rand() seems strongly co-related to the time and is strictly increasing as time passes. Any ideas as to why this occurs or how to resolve it?
This happens on OSX 10.11

A: *

*rand() is quite bad, avoid it if possible.  In any good RNG the first values will be indistinguishable from random even when the seed is close (hamming distance).  In rand this is not the case.

*If you must use rand then seed it, preferably with something higher entropy than time, and call rand() multiple times instead of reseeding-calling-reseeding.

For example of 2, consider:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char** argv) {
  int t=time(NULL);
  srand(t);

  for(int i=0; i < 10; i++) {
    float r = (float)rand()/(float)(RAND_MAX);
    printf("%f\n", r);
  }
}

With the result:
0.460600
0.310486
0.339473
0.519799
0.258825
0.072276
0.749423
0.552250
0.665374
0.939103

It's still a bad RNG but at least the range is better when you allow it to use the internal state instead of giving it another similar seed.

A: This is exactly what you should expect. There's no such thing as "a random number". There are only sequences of numbers with a random distribution. The rand() function generates such sequences, but you're not giving it a chance to, because you keep re-seeding it.  The first number generated by rand() may very well be just some function of the seed, or the seed itself. Some rand() functions might hash the seed to hide this, but that doesn't really make them any better, because the contract of rand() is to produce a random sequence.
If you need a sequence of random numbers that survives running multiple programs, you'll have to do something like (a) Write a program that calls srand() once, then calls rand() many times, and have your other programs ask for random numbers from that program over IPC; (b) Use something like /dev/urandom; (c) Use something like random.org.


text:
Q: ERRO System.InvalidOperationException: A sequência contém mais de um elemento Possuo um sistema que funciona em diversas maquinas, porém em uma maquina ocorre o erro:
`A sequência contém mais de um elemento
Descrição: Ocorreu uma exceção sem tratamento durante a execução da atual solicitação da Web. Examine o rastreamento de pilha para obter mais informações sobre o erro e onde foi originado no código.
Detalhes da Exceção: System.InvalidOperationException: A sequência contém mais de um elemento
Erro de Origem:
Exceção sem tratamento foi gerada durante a execução da atual solicitação da Web. As informações relacionadas à origem e ao local da exceção podem ser identificadas usando-se o rastreamento de pilha de exceção abaixo.
Rastreamento de Pilha:
[InvalidOperationException: A sequência contém mais de um elemento]
   System.Linq.Enumerable.SingleOrDefault(IEnumerable1 source) +4098162
   System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__2(IEnumerable1 sequence) +40
   System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle(IEnumerable`1 query, Expression queryRoot) +60
   System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider ´
O sistema acessa a seguinte action
string Login = GetUser();
        Ramal ramal = db.Ramais.SingleOrDefault(r => r.sCodFunc == Login);

        if (ramal == null)
        {
            Session["UserAdm"] = false;
        }
        else
        {
            Session["UserAdm"] = ramal.bAdmSist;
        }

        ViewBag.ListaMes = MontaListaMes();
        ViewBag.Area = (from c in db.Area orderby c.sNome select c).ToArray();

        //return View();

        //Exibir os aniversariantes do mês

        string MesAniversario = DateTime.Today.ToString("MM");
        string DiaAniversario = DateTime.Today.ToString("dd");

        //Coloca em primeiro o aniversariante do dia, e em seguida do mes.
        Ramal[] RamalAniver = (from c in db.Ramais
                               where c.sAniversario.Contains("/" + MesAniversario) && c.bAtivo == true
                               orderby c.sAniversario
                               select c
                               ).ToArray();

        RamalAniver = RamalAniver.OrderByDescending(x => x.sAniversario == DiaAniversario
            + "/" + MesAniversario).ThenBy(x => x.sAniversario).ToArray();

        return View(RamalAniver.ToList());

        //return View(AniverDia.Union(AniverMes).ToList());

    private string GetUser()
    {

        var Aux = User.Identity.Name.Split('\\');
        return Aux[1];
    }

Alguem já viu este problema?


text:
Q: handling null pointer exception in talend in OR statement I have this code.  it is the row exception filter in the right hand map of a tMap:
row2.method.equals("Twitter") && (
    row2.last_notified.equals(null) ||
    row2.frequency.equals("Everytime") ||
    (row2.frequency == "Hourly" && TalendDate.diffDate(TalendDate.addDate(row2.last_notified,1,"HH"), TalendDate.parseDate("yyyy-MM-dd HH:mm:ss", TalendDate.getDate("yyyy-MM-dd HH:mm:ss")), "HH") > 0) ||
    (row2.frequency == "Daily" && TalendDate.diffDate(TalendDate.addDate(row2.last_notified,1,"dd"), TalendDate.parseDate("yyyy-MM-dd HH:mm:ss", TalendDate.getDate("yyyy-MM-dd HH:mm:ss")), "dd") > 0)
)

I have a nullPointerException.  I know that frequency is not null, as is method.  I know that last_notified is null.  based on my logic, all rows with "Twitter" as a value with no last_notified should pass.  However, it looks like I failed with this.
I understood that OR statements go from left to right.  If the first value comes back True, then the OR SHOULD return true?  What am I missing?

A: Regarding
row2.last_notified.equals(null)

Don't test for null with the equals method as that risks throwing the NPE exception since you'll be attempting to call a method on a null variable.  Always use == instead since you're not testing the notified reference's value but rather whether the reference itself is null.
So do
row2.last_notified == null

Also regarding
row2.frequency == "Daily"

It's the exact opposite here as you're comparing Strings wrong -- use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two object references are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here.
Instead do:
row2.frequency.equals("Daily")


text:
Q: Java ASM AdviceAdapter not instrumenting all methods I am trying to capture the invocation of each method call by implementing onMethodEnter() from AdviceAdapter. The problem I am running into is, my instrumentation code is not being added to all the methods. In fact it is added to only the first method after the "<init>" and rest of the methods are skipped. Please let me know what am I doing wrong in the code below.
Thanks.
Ash.
public class FunctionLevelDependency extends AdviceAdapter implements Opcodes {
    String className;
    String methodName;
    int currentThread_idx, threadId_idx, stringBuffer_idx, output_idx;

    protected FunctionLevelDependency(int api, MethodVisitor mv, int access,
            String methodName, String desc, String className) {
        super(api, mv, access, methodName, desc);
        this.className = className;
        this.methodName = methodName;
    }

    @Override
    protected void onMethodEnter() {
        currentThread_idx = newLocal(Type.getType(Thread.class));
        mv.visitMethodInsn(INVOKESTATIC, "java/lang/Thread", "currentThread",
                "()Ljava/lang/Thread;", false);
        mv.visitVarInsn(ASTORE, currentThread_idx);
        mv.visitVarInsn(ALOAD, currentThread_idx);
        threadId_idx = newLocal(Type.getType(String.class));
        mv.visitTypeInsn(NEW, "java/lang/String");
        mv.visitInsn(DUP);
        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/String", "<init>",
                "()V", false);
        mv.visitVarInsn(ASTORE, threadId_idx);
        mv.visitVarInsn(ALOAD, currentThread_idx);

        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Thread", "getName", "()Ljava/lang/String;",
                false);
        mv.visitVarInsn(ASTORE, threadId_idx);

        stringBuffer_idx = newLocal(Type.getType(StringBuffer.class));
        mv.visitTypeInsn(NEW, "java/lang/StringBuffer");
        mv.visitInsn(DUP);
        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuffer", "<init>",
                "()V", false);
        mv.visitVarInsn(ASTORE, stringBuffer_idx);
        mv.visitVarInsn(ALOAD, stringBuffer_idx);
        mv.visitVarInsn(ALOAD, threadId_idx);
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuffer", "append",
                "(Ljava/lang/String;)Ljava/lang/StringBuffer;", false);
        mv.visitInsn(POP);
        mv.visitVarInsn(ALOAD, stringBuffer_idx);
        mv.visitLdcInsn(",[" + className + "][" + methodName + "]");
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuffer", "append",
                "(Ljava/lang/String;)Ljava/lang/StringBuffer;", false);
        mv.visitInsn(POP);
        mv.visitVarInsn(ALOAD, stringBuffer_idx);

        output_idx = newLocal(Type.getType(String.class));
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuffer", "toString",
                "()Ljava/lang/String;", false);
        mv.visitVarInsn(ASTORE, output_idx);
        mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out",
                "Ljava/io/PrintStream;");
        mv.visitVarInsn(ALOAD, output_idx);
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println",
                "(Ljava/lang/String;)V", false);

    }

}

public class FunctionDependencyPrinter extends ClassVisitor {
    private String className;
    private boolean isInterface;

    public FunctionDependencyPrinter(ClassWriter writer, String className) {
        super(Opcodes.ASM5, writer);
        this.className = className;
    }

    @Override
    public void visit(int version, int access, String name, String signature,
            String superName, String[] interfaces) {
        super.visit(version, access, name, signature, superName, interfaces);
        isInterface = (access & ACC_INTERFACE) != 0;
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String desc,
            String signature, String[] exceptions) {
        MethodVisitor mv = super.visitMethod(access, name, desc, signature,
                exceptions);
        if (!isInterface && mv != null && !name.equals("<init>") && !name.equals("<clinit>")) {
            System.out.println("Transforming " + name + " for " + className);
            mv = new FunctionLevelDependency(Opcodes.ASM5, mv, access, name,
                    desc, className);
        }
        return mv;
    }
}


text:
Q: syntax error with KeyError in python 3.2 I'm a beginner using python 3.2 and i have a book whos code is all in python 2.6. i wrote part of a program and keep getting:
Syntax Error: invalid syntax
Then python's IDLE highlights the comma after KeyError in my code:
from tank import Tank

tanks = { "a":Tank("Alice"), "b":Tank("Bob"), "c":Tank("Carol")}
alive_tanks = len(tanks)

while alive_tanks > 1:
    print
    for tank_name in sorted( tanks.keys() ):
        print (tank_name, tanks[tank_name])

    first = raw_input("Who fires? ").lower()
    second = raw_input("Who at? ").lower()

    try:
        first_tank = tanks[first]
        second_tank = tanks[second]
    except KeyError, name:
        print ("No such tank exists!", name)
        continue

A: Instead of
except KeyError, name:

try
except KeyError as name:

Its a difference between Python 2.x and Python 3.x. The first form is no longer supported.


text:
Q: Training neural network for XOR in Ruby I am trying to train a feedforward network to work to perform an XOR operations with the Ruby Library AI4R. However,
when I evaluate for the XOR after training it. I am not getting the correct output. Has anyone used this library before
and gotten it to learn the XOR operation.
I am using two input neurons, three neurons in a hidden layer, and one layer for the output, as I saw a precomputed
XOR feed forward neural network like this before.
require "rubygems"
require "ai4r"

# Create the network with:
 #   2 inputs
 #   1 hidden layer with 3 neurons
 #   1 outputs
 net = Ai4r::NeuralNetwork::Backpropagation.new([2, 3, 1])

 example = [[0,0],[0,1],[1,0],[1,1]]
 result = [[0],[1],[1],[0]]

 # Train the network
 400.times do |i|
   j = i % result.length
   puts net.train(example[j], result[j])
 end

 # Use it: Evaluate data with the trained network
puts "evaluate 0,0: #{net.eval([0,0])}"  # =>  evaluate 0,0: 0.507531383375123
puts "evaluate 0,1: #{net.eval([0,1])}"  # =>  evaluate 0,1: 0.491957823618629
puts "evaluate 1,0: #{net.eval([1,0])}"  # =>  evaluate 1,0: 0.516413912471401
puts "evaluate 1,1: #{net.eval([1,1])}"  # =>  evaluate 1,1: 0.500197884691668

Ted

A: You haven't trained it for enough iterations. If you change 400.times to 8000.times you'll come much closer (and closer still at 20000.times).
At 20000.times, I get
puts "evaluate 0,0: #{net.eval([0,0])}"  # =>  evaluate 0,0: 0.030879848321403
puts "evaluate 0,1: #{net.eval([0,1])}"  # =>  evaluate 0,1: 0.97105714994505
puts "evaluate 1,0: #{net.eval([1,0])}"  # =>  evaluate 1,0: 0.965055940880282
puts "evaluate 1,1: #{net.eval([1,1])}"  # =>  evaluate 1,1: 0.0268317078331645

You can also increase net.learning_rate (but not too much).

A: If you want to consider Neuroevolution, you may check up the neuroevo gem. Run the specs to see it fit XOR in 15 iterations ([2,2,1] feed-forward network, XNES optimizer):
https://github.com/giuse/neuroevo/blob/master/spec/solver_spec.rb
Full disclosure: I'm the developer (hi there!).
I just recently began published my code and am looking for feedback.


text:
Q: Need help with vectors and the dot product I've got a homework question:
$\vec{a} = \vec{i} + 2 \vec{j} + t \vec{k},$
$\vec{b} = 3 \vec{i} + 2 \vec{j} + \vec{k}$
Find $t$ such that $\vec{a}$ and $\vec{b}$ are perpendicular to each other.
I assume I have to use the dot product to find if the vectors are perpendicular to each other, and I end up with $t = 7$. Was wondering if this is correct and if i'm on the right path. Cheers!

A: $\vec{a} \cdot \vec{b} = 1*3 + 2*2 + t*1 = 7 + t$
The vectors are perpendicular when the dot product equals zero. Therefore, $t = -7$.


text:
Q: Using networksetup to connect to WPA2 Enterprise with AD not authenticating When using networksetup to connect to a WiFi network, the WiFi symbol appears with an exclamation mark over it. It also shows that there is no 802.1x authentication in the network preferences.
I have tried the following command:
networksetup -setairportnetwork $INTERFACE "$SSID"

I have tried unlocking the keychain prior to setting the network and tried adding the password as the last parameter.
I have also tried setting the password in the keychain to allow all applications access to it with no restrictions.
I expect the network to be connected in the same way as when manually switching networks. However, when looking in the network preferences after connecting via networksetup, the authentication does not appear to be there.
Under network preferences, after switching manually, the status is Connected and has the message "Wi-Fi is connected to XXXX and has the IP address XXXXXXX". It also shows "802.1X: Default" and "Authenticated via EAP-PEAP (MSCHAPv2)
However, after switching with the script, the status is "On" and has the message "Wi-Fi does not have an IP address and cannot connect to the internet." There is also no message regarding 802.1X authentication.

A: I ended up solving this using Applescript inside a bash script instead. This mimicks the way that the user would manually switch a WiFi network.
In case anyone else has this problem in the future, here's the bash function I created to do this for me.
switchWiFi () {
osascript \
-e'tell application "System Events"' \
    -e 'tell process "SystemUIServer"' \
        -e 'click (menu bar item 1 of menu bar 1 whose description contains "Wi-Fi")' \
        -e "click menu item $1 of menu 1 of result" \
    -e 'end tell' \
-e 'end tell'
}


text:
Q: Trying to do a left join merge in R but want to select specific columns. Receiving error message Both unique_id for x and y are chr data types. Both are spelled the same exact way.
When i run the script like here it works. However I don't want to join all values. I want to join specific values.
results2<-merge(x=results2, y=machine, by = "SR_Num", all.x= TRUE)

However when i want to select the two specific columns as specified below. I get an error message.
results2<-merge(x=results2, y=machine[ , c("narrative", "date")], by = "unique_id",all.x=TRUE)

The error message says
Error in fix.by(by.y, y) : 'by' must specify a uniquely valid column


text:
Q: Grub rescue error problem! Grub rescue error
 I got an error on deleting partition (i divided this partition into two partition) of Ubuntu by using easeus partition master
I checked all the partition one by one for grub loader couldn't find...pc says Unknown filesystem
How can I solve this problem!?
I don't have USB or CD!


text:
Q: Integrating a function of tan inverse How would I carry out the following integration?
$$\int_0^12\arctan x^2$$
I tried to substitute $x^2 = \tan\theta$
From there I wrote the integral as:
$$\int_0^{\pi/4}\theta\cdot \frac{\sec^2\theta}{\sqrt{\tan\theta}}\ d\theta$$
Now, is my only option to use integration by parts? Or is there a better method to solve this integral?

A: By integrating by parts:
$$\int_0^1\arctan(x^2)dx=x\arctan(x^2)\Big|_0^1-2\int_0^1\frac{x^2}{1+x^4}dx$$
and we compute the last integral by the usual ways.

A: Notice,you can use integration by parts as follows
$$\int_0^1 2\tan^{-1}(x^2)\ dx=2\int_0^1  \tan^{-1}(x^2)\cdot 1\ dx$$
$$=2\left(\tan^{-1}(x^2)\int 1\ dx-\int \left(\frac{d}{dx}(\tan^{-1}(x^2))\int 1\ dx \right)\ dx\right)_0^1$$
$$=2\left(x\tan^{-1}(x^2)-\int \frac{2x^2}{1+x^4}\ dx\right)_0^1$$
$$=2\left(x\tan^{-1}(x^2)-\int \frac{2}{x^2+\frac{1}{x^2}}\ dx\right)_0^1$$
$$=2\left(x\tan^{-1}(x^2)-\int \frac{\left(1+\frac{1}{x^2}\right)+\left(1-\frac{1}{x^2}\right)}{x^2+\frac{1}{x^2}}\ dx\right)_0^1$$
$$=2\left(x\tan^{-1}(x^2)-\int \frac{\left(1+\frac{1}{x^2}\right)}{x^2+\frac{1}{x^2}}\ dx-\int \frac{\left(1-\frac{1}{x^2}\right)}{x^2+\frac{1}{x^2}}\ dx\right)_0^1$$
$$=2\left(x\tan^{-1}(x^2)-\int \frac{\left(1+\frac{1}{x^2}\right)dx}{\left(x-\frac{1}{x}\right)^2+2}-\int \frac{\left(1-\frac{1}{x^2}\right)dx}{\left(x+\frac{1}{x}\right)^2-2}\right)_0^1$$
$$=2\left(x\tan^{-1}(x^2)-\int \frac{d\left(x-\frac{1}{x}\right)}{\left(x-\frac{1}{x}\right)^2+(\sqrt 2)^2}-\int \frac{d\left(x+\frac{1}{x}\right)}{\left(x+\frac{1}{x}\right)^2-(\sqrt 2)^2}\right)_0^1$$
$$=2\left(x\tan^{-1}(x^2)-\frac{1}{\sqrt 2}\tan^{-1}\left(\frac{x-\frac 1x}{\sqrt 2}\right)-\frac{1}{2\sqrt 2}\ln\left|\frac{x+\frac 1x-\sqrt 2}{x+\frac 1x+\sqrt 2}\right|\right)_0^1$$
$$=2\left(x\tan^{-1}(x^2)-\frac{1}{\sqrt 2}\tan^{-1}\left(\frac{x^2-1}{x\sqrt 2}\right)-\frac{1}{2\sqrt 2}\ln\left|\frac{x^2+1-x\sqrt 2}{x^2+1+x\sqrt 2}\right|\right)_0^1$$
$$=2\left(1\cdot \frac{\pi}{4}-\frac{1}{\sqrt 2}\tan^{-1}\left(0\right)-\frac{1}{2\sqrt 2}\ln\left|\frac{2-\sqrt 2}{2+\sqrt 2}\right|-0-\frac{1}{\sqrt 2}\cdot \frac{\pi}{2}+0\right)$$
$$=\color{blue}{\frac{\pi}{2}-\frac{\pi}{\sqrt 2}-\frac{1}{\sqrt 2}\ln(3-2\sqrt 2)}$$

A: By using the Taylor series of the arctangent function, $\arctan(x)=\sum_{n\geq 0}\frac{(-1)^n x^{2n+1}}{2n+1}$, we get:
$$ \int_{0}^{1}\arctan(x^2)\,dx = 2\sum_{n\geq 0}\frac{(-1)^n}{(4n+2)(4n+3)}=2\sum_{n\geq 0}(-1)^n\left(\frac{1}{4n+2}-\frac{1}{4n+3}\right),$$
where the series
$$\sum_{n\geq 0}\frac{(-1)^n}{4n+3} = \sum_{n\geq 0}\left(\frac{1}{8n+3}-\frac{1}{8n+7}\right)$$
can be computed through the identity
$$ -\log(1-z) = \sum_{n\geq 1}\frac{z^n}{n} $$
with $z$ being a root of $\frac{z^8-1}{z-1}$, i.e. through the discrete Fourier transform. By collecting the pieces,

$$ \int_{0}^{1}\arctan(x^2)\,dx = \color{red}{\frac{\pi}{4}-\frac{\pi}{2\sqrt{2}}+\frac{1}{\sqrt{2}}\,\log(1+\sqrt{2})}.$$

As an alternative, you may notice that the problem is equivalent, by integration by parts, to computing $\int_{0}^{1}\frac{x^2}{1+x^4}\,dx$, but $$1+x^4 = (1+2x^2+x^4)-2x^2 = (1+x^2)^2-(\sqrt{2} x)^2 $$
gives
$$ \frac{x^2}{1+x^4} = \frac{1}{2\sqrt{2}}\cdot\left(\frac{x}{x^2-\sqrt{2}\,x+1}-\frac{x}{x^2+\sqrt{2}\,x+1}\right)$$
and the primitive of $\frac{x}{x^2\pm\sqrt{2}\,x+1}$ is just:
$$ \frac{1}{2}\,\log(x^2\pm\sqrt{2}\,x+1)\mp\arctan\left(\frac{2x\pm\sqrt{2}}{2}\right).$$


text:
Q: Trying to keep user loggedIn in my android app after first login but not working I am developing an android app, my app have a login activity. What i want to do is once a user is logged in for the first time it will remain logged in even if the app is closed.
I tried a way out but it didn't worked well.
Any help will b appreciated.
Thanks!
1) Login.java
private Snackbar snackbar;
private ProgressDialog pd;
private TextInputLayout mTiEmail;
private TextInputLayout mTiPassword;
private CompositeSubscription mSubscriptions;
private SharedPreferences mSharedPreferences;
private Boolean loggedIn = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    mSubscriptions = new CompositeSubscription();
    mSubscriptions = new CompositeSubscription();

    loginUserName = (EditText) findViewById(R.id.email_edit);
    loginPassword = (EditText) findViewById(R.id.pass_edit);
    pd = new ProgressDialog(Login.this);
    mTiEmail = (TextInputLayout) findViewById(R.id.email1);
    mTiPassword = (TextInputLayout) findViewById(R.id.password);
    loginButton = (TextView)findViewById(R.id.btn_login);
    initSharedPreferences();
    loginButton.setOnClickListener(view -> login());

    }
    @Override
    protected void onResume() {
        super.onResume();
        //In onresume fetching value from sharedpreference
        SharedPreferences sharedPreferences = getSharedPreferences(Constants.SHARED_PREF_NAME, Context.MODE_PRIVATE);

        //Fetching the boolean value form sharedpreferences
        loggedIn = sharedPreferences.getBoolean(Constants.LOGGEDIN_SHARED_PREF, false);

        //If we will get true
        if (loggedIn) {
            //We will start the Profile Activity
            Intent intent = new Intent(Login.this, Dashboard.class);
            startActivity(intent);
        }
    }
private void initSharedPreferences() {

    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(Login.this);
}
private void login() {

    setError();

    String email = loginUserName.getText().toString();
    String password = loginPassword.getText().toString();

    int err = 0;

    if (!validateEmail(email)) {

        err++;
        mTiEmail.setError("Email should be valid !");
    }

    if (!validateFields(password)) {

        err++;
        mTiPassword.setError("Password should not be empty !");
    }

    if (err == 0) {

        loginProcess(email,password);

    } else {

        Toast.makeText(this, "Enter valid details", Toast.LENGTH_SHORT).show();
    }
}
private void setError() {

    loginUserName.setError(null);
    loginPassword.setError(null);
}
private void loginProcess(String email, String password) {

    mSubscriptions.add(NetworkUtil.getRetrofit(email,password).login()
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(this::handleResponse,this::handleError));
}
private void handleResponse(Response response) {

    SharedPreferences.Editor editor = mSharedPreferences.edit();
    editor.putString(Constants.TOKEN,response.getToken());
    editor.putString(Constants.EMAIL,response.getMessage());
    editor.apply();

   loginUserName.setText(null);
    loginPassword.setText(null);
    Intent in = new Intent(Login.this,Dashboard.class);
    startActivity(in);
    Toast.makeText(this, "REGISTERED-->>", Toast.LENGTH_LONG).show();
}
private void handleError(Throwable error) {

    if (error instanceof HttpException) {

        Gson gson = new GsonBuilder().create();

        try {

            String errorBody = ((HttpException) error).response().errorBody().string();
            Response response = gson.fromJson(errorBody,Response.class);
            Toast.makeText(this, response.getMessage(), Toast.LENGTH_SHORT).show();

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

        Toast.makeText(this, error.getMessage(), Toast.LENGTH_SHORT).show();
    }
}

}

Here in my onResume() method i tried a way out but didn't work, Any Suggestions?
2) Constants.java
public class Constants {

public static final String BASE_URL = "http://192.168.2.145:8080/api/v1/";
public static final String TOKEN = "token";
public static final String EMAIL = "email";
//This would be the name of our shared preferences
public static final String SHARED_PREF_NAME = "myloginapp";

//This would be used to store the email of current logged in user
public static final String EMAIL_SHARED_PREF = "email";

//We will use this to store the boolean in sharedpreference to track user is loggedin or not
public static final String LOGGEDIN_SHARED_PREF = "loggedin";

}
UPDATE
Login.java
public class Login extends AppCompatActivity {
TextView loginButton;
EditText loginUserName, loginPassword;

private Snackbar snackbar;
private ProgressDialog pd;
private TextInputLayout mTiEmail;
private TextInputLayout mTiPassword;
private CompositeSubscription mSubscriptions;
private SharedPreferences mSharedPreferences;
private Boolean loggedIn = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    mSubscriptions = new CompositeSubscription();
    mSubscriptions = new CompositeSubscription();

    loginUserName = (EditText) findViewById(R.id.email_edit);
    loginPassword = (EditText) findViewById(R.id.pass_edit);
    pd = new ProgressDialog(Login.this);
    mTiEmail = (TextInputLayout) findViewById(R.id.email1);
    mTiPassword = (TextInputLayout) findViewById(R.id.password);
    loginButton = (TextView)findViewById(R.id.btn_login);
    initSharedPreferences();
    loginButton.setOnClickListener(view -> login());

    }
@Override
protected void onResume() {
    super.onResume();
    //In onresume fetching value from sharedpreference
    mSharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);
    if(mSharedPreferences.getBoolean("LoggedIn", false)){
        Intent intent = new Intent(Login.this,Dashboard.class);
        startActivity(intent);
    } else {
        loginButton.setOnClickListener(view -> login());

        //Do other stuff
    }
}
private void initSharedPreferences() {

    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(Login.this);
}
private void login() {

    String username = loginUserName.getText().toString();
    String password = loginPassword.getText().toString();

    loginProcess(username,password);

    int err = 0;

    if (!validateFields(username)&& !validateFields(password)) {

        err++;
        mTiEmail.setError("Username should not be empty !");
    }

    if (err == 0) {

        loginProcess(username,password);

    } else {

        Toast.makeText(this, "Enter valid details", Toast.LENGTH_SHORT).show();
    }

}

private void loginProcess(String username,String password){

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RetrofitInterface requestInterface = retrofit.create(RetrofitInterface.class);

    User user = new User();
    user.setUsername(username);
    user.setPassword(password);
    ServerRequest request = new ServerRequest();
    request.setOperation(Constants.LOGIN_OPERATION);
    request.setUser(user);
    Call<ServerResponse> response = requestInterface.operation(request);

    response.enqueue(new Callback<ServerResponse>() {
        @Override
        public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
            if(response.isSuccessful()) {
                ServerResponse serverResponse = response.body();
                if(serverResponse.getMessage().equals(Constants.SUCCESS)) {
                    SharedPreferences.Editor editor = mSharedPreferences.edit();
                    editor.putBoolean("LoggedIn",true);
                    //editor.putString(Constants.EMAIL,serverResponse.getUser().getEmail());
                    editor.putString(Constants.USERNAME,serverResponse.getUser().getUsername());
                    editor.putString(Constants.BUSINESSNAME,serverResponse.getUser().getBusinessname());
                    editor.apply();

                    Toast.makeText(Login.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    goToProfile();
                } else {
                    Toast.makeText(Login.this, serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
                }
            } else {
                Gson gson = new Gson();
                ServerResponse errorResponse = null;
                try {
                    errorResponse = gson.fromJson(response.errorBody().string(), ServerResponse.class);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Toast.makeText(Login.this, errorResponse.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<ServerResponse> call, Throwable t) {

            Log.d(Constants.TAG,"failed");
            Toast.makeText(Login.this,t.getLocalizedMessage() , Toast.LENGTH_SHORT).show();
        }
    });
}

private void goToProfile(){

    Intent intent = new Intent(this,Dashboard.class);
    startActivity(intent);
}

}

A: Put this code in your onCreate()
SharedPreferences pref = getSharedPrefrences("login", Context.MODE_PRIVATE); //Opening 'login' sharedPreference
if(pref.getBoolean("LoggedIn", false)){ //checking if 'LoggedIn' exist in SharedPreference if no exist it returns false. if it exist fetches its value
   //Move to Next Screen
} else {
   loginButton.setOnClickListener(view -> login());
   //Do other stuff
}

Then in your handleResponse().. Add these lines
//Lets suppose if User is logging in for the First time.. Below lines will add 'LoggedIn' to shared preference so user logged in directly next time

   SharedPreferences.Editor editor = pref.edit();
   editor.putBoolean("LoggedIn", true);
   editor.apply();

A: Set LOGGEDIN_SHARED_PREF in your void handleResponse() as below :
editor.putBoolean(Constants.LOGGEDIN_SHARED_PREF,true);

Set your sharedPreferences globally
SharedPreferences sharedPreferences = getSharedPreferences(Constants.SHARED_PREF_NAME, Context.MODE_PRIVATE);

And edit on the same in your handleReponse()
SharedPreferences.Editor editor = sharedPreferences.edit();

I updated your code:
private Snackbar snackbar;
private ProgressDialog pd;
private TextInputLayout mTiEmail;
private TextInputLayout mTiPassword;
private CompositeSubscription mSubscriptions;
private SharedPreferences sharedPreferences;
private Boolean loggedIn = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    mSubscriptions = new CompositeSubscription();
    mSubscriptions = new CompositeSubscription();

    loginUserName = (EditText) findViewById(R.id.email_edit);
    loginPassword = (EditText) findViewById(R.id.pass_edit);
    pd = new ProgressDialog(Login.this);
    mTiEmail = (TextInputLayout) findViewById(R.id.email1);
    mTiPassword = (TextInputLayout) findViewById(R.id.password);
    loginButton = (TextView)findViewById(R.id.btn_login);

    loginButton.setOnClickListener(view -> login());

    }
    @Override
    protected void onResume() {
        super.onResume();
        //In onresume fetching value from sharedpreference
        sharedPreferences = getSharedPreferences(Constants.SHARED_PREF_NAME, Context.MODE_PRIVATE);

        //Fetching the boolean value form sharedpreferences
        loggedIn = sharedPreferences.getBoolean(Constants.LOGGEDIN_SHARED_PREF, false);

        //If we will get true
        if (loggedIn) {
            //We will start the Profile Activity
            Intent intent = new Intent(Login.this, Dashboard.class);
            startActivity(intent);
        }
    }

private void login() {

    setError();

    String email = loginUserName.getText().toString();
    String password = loginPassword.getText().toString();

    int err = 0;

    if (!validateEmail(email)) {

        err++;
        mTiEmail.setError("Email should be valid !");
    }

    if (!validateFields(password)) {

        err++;
        mTiPassword.setError("Password should not be empty !");
    }

    if (err == 0) {

        loginProcess(email,password);

    } else {

        Toast.makeText(this, "Enter valid details", Toast.LENGTH_SHORT).show();
    }
}
private void setError() {

    loginUserName.setError(null);
    loginPassword.setError(null);
}
private void loginProcess(String email, String password) {

    mSubscriptions.add(NetworkUtil.getRetrofit(email,password).login()
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(this::handleResponse,this::handleError));
}
private void handleResponse(Response response) {

    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(Constants.TOKEN,response.getToken());
    editor.putString(Constants.EMAIL,response.getMessage());
    editor.putBoolean(Constants.LOGGEDIN_SHARED_PREF,true);
    editor.apply();

   loginUserName.setText(null);
    loginPassword.setText(null);
    Intent in = new Intent(Login.this,Dashboard.class);
    startActivity(in);
    Toast.makeText(this, "REGISTERED-->>", Toast.LENGTH_LONG).show();
}
private void handleError(Throwable error) {

    if (error instanceof HttpException) {

        Gson gson = new GsonBuilder().create();

        try {

            String errorBody = ((HttpException) error).response().errorBody().string();
            Response response = gson.fromJson(errorBody,Response.class);
            Toast.makeText(this, response.getMessage(), Toast.LENGTH_SHORT).show();

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

        Toast.makeText(this, error.getMessage(), Toast.LENGTH_SHORT).show();
    }
}

}


text:
Q: use net instread of cdrom. linux, aptitude install Got debian installed finally but during install I think I choose to use the local media over the internet for packages. needed to do that as was not sure if will try to connect right away (my modem needs a login).
Now I want to install/ enable sudo and install other programs like thunderbird eclipse, and chrome. but I do not have sudo
when I type the command,
aptitude install sudo

Get this message:
The following NEW packages will be installed:
  sudo  0 packages upgraded, 1 newly installed, 0 to remove and 0 not
upgraded. Need to get 0 B/842 kB of archives. After unpacking 1,882 kB
will be used. Media change: Please insert the disc labeled 'Debian
GNU/Linux 7.1.0 _Wheezy_ - Official amd64 CD Binary-1 20130615-23:06'
into the drive '/media/cdrom/' and press [Enter].

Do not have a cdrom. What to do? Have root user password though logged in as another user.

A: If you have access to root, you can edit the /etc/apt/sources.list file as described on the debian site here
use
su
enter root password
then with an editor (nano is easy to use as it has menus if you have it installed otherwise vi is most likely to be present, see a manual for vi here )
nano /etc/apt/sources.list
or
vi /etc/apt/sources.list


text:
Q: If $X$ follows a binomial distribution, then what is $P(1.25Do I understand it correctly that $$P(1.25 < X < 1.75) = P (X <1.75) - P(X < 1.25)= P(X \le 1) -P(X \le 1)=0?$$
Another question : Is $$P(0.5 < X <1.5) = P(X =1)?$$
Thanks in advance.

A: Yes.  If $X \sim \operatorname{Binomial}(n,p)$, then $\Pr[1.25 < X < 1.75] = 0$, because the support of $X$ is on the set $X \in \{0, 1, \ldots, n\}$.  Since there are no integers between $1.25$ and $1.75$, the desired probability is zero.

A: Another way to look at it is that the event
$1.25<X<1.75$ is an empty event since the only possible values of $X$ are integers $k$, $0\leq k\leq n$. Hence
$$P(1.25<X<1.75) = P(\varnothing) = 0.$$
For the second part, notice
$$\{.5<X<1.5\}\iff \{X = 1\}$$
and hence
$$P(.5<X<1.5) = P(X=1).$$


text:
Q: What are the complexity classes of these problems about divisibility and coprimality? The problems

*

*'Given $0<a<b$ and a prime $p<a$ is there an integer $\ell\in[a,b]$ such that $p|\ell$?'

*'Given $0<a<b$ and an integer $q\not\in[a,b]$ is there an integer $\ell\in[a,b]$ such that $q$ is coprime to $\ell$?'
are in $\mathsf{NP}$.
Are these problems in $\mathsf{BPP}$ or at least in $\mathsf{P/poly}$?

A: Both problems are provably in P. For the first one, this is immediate - using division with remainder (which is polynomial time), write $a=qp+r,b=q'p+r'$ with $0\leq r,r'<p$. Then there is $\ell$ divisible by $p$ in this interval iff $r=0$ or $q'>q$. For the record, this doesn't depend on $p$ being prime.
For the second problem is less trivial. We use the following fact due to Iwaniec (see the reference here combined with the fact $\omega(n)=O(\log n)$): there is a constant $C>0$ such that in any interval of length at least $C(\log q\log\log q)^2$ there is an element coprime to $q$. Once we prove that, the problem becomes easy - if $b-a>C(\log q\log\log q)^2$ the answer is yes, otherwise we can just check every $\ell\in[a,b]$ using the Euclidean algorithm.


text:
Q: C# Удалить повторяющиеся символы из строки Имеется, допустим, 5 текстбоксов. И один главный. По мере заполнения тех пяти текстбоксов, в главном формируется имя. Между значениями текстбоксов используются знаки нижнего подчеркивания "_".
Например:
текстбокс1: 123

текстбокс2: 456

текстбокс3: 789

текстбокс4: аа

текстбокс5: бб

Главный тексбокс отобразит: 123_456_789_аа_бб
В чем проблема: для создания имени не всегда нужно заполнять все тексбоксы. Иногда достаточно одного или двух.
Тогда мы видим следующее: 123_456___ или __789__
Каким образом можно сделать, чтобы в строке при наличии двух подряд и более нижних подчеркиваний оставалось только одно. Исходя из примеров выше вывело бы 123_456 и 789.
К тому же тут для примера указал,что их 5. В реальности их может быть 10-15.
Что пробовал: Методы Trim(), Replace(), Remove() и т.д.
Но решения так и не нашел. Либо удаляет нужные, либо не верно срабатывают.
UPDATE:
Для формирования итогового имени использую подобную структуру:
string fileName = tb_1.Text + "_" + tb_2.Text + "_" + tb_3.Text + "_" + tb_4.Text + "_" + cb_1.Text + "_" + cb_2.Text + "_" + cb_3.Text + "_" + cb_4.Text + "_" + cb_6.Text + "_" + tb_5.Text + "_" + tb_6.Text + "_" + tb_7.Text;

tb_FullName.Text = fileName;

Может есть более простой и правильный способ заполнения,чтобы потом не пришлось удалять нижние подчеркивания?

A: Например так.
Берете список
List<string> lines = new List<string>();

Добавляете в него все нужные значения
lines.Add(textBox1.Text);
lines.Add(textBox2.Text);
//...

Дальше у вас 2 варианта:
Либо сразу использовать Linq
string result = string.Join("_", lines.Where(s => s?.Length > 0));

Либо предварительно императивно в цикле надо удалить пустые строки
for (int i = 0; i < lines.Count; i++)
{
    if (string.IsNullOrEmpty(lines[i]))
    {
        lines.RemoveAt(i);
        i--;
    }
}
string result = string.Join("_", lines);

То есть задача эта сводится к тому, чтобы не допустить появления этих дубликатов, а не грамотно их удалить.

Однострочник для вашего конкретного случая, с использованием массива вместо списка, но разницы нет.
tb_FullName.Text = string.Join("_", new string[] { tb_1.Text, tb_2.Text, tb_3.Text, tb_4.Text, cb_1.Text, cb_2.Text, cb_3.Text, cb_4.Text, cb_6.Text, tb_5.Text, tb_6.Text, tb_7.Text }.Where(s => s?.Length > 0));


text:
Q: displaying nested json in ag-grid I am using Angular Grid (ag-grid) to display data. i am trying to display nested json data in my angular grid. but i was unsuccessful.
below is the sample json data and colDefs. please suggest that why dot operator is not working unlike jqgrid, to map grid columns with nested json fields.
var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl', ['$scope', '$http',
function($scope, $http) {
$scope.myData = [{
"defaultColumns1": {"region":"PA"},
"defaultColumns2": {"LocationName": "loc1",
"LegalName": "legName1"
}
},
{
"defaultColumns1": {"region":"PB"},
"defaultColumns2": {"LocationName": "loc2",
"LegalName": "legName2"
}
}];

$scope.gridOptions = {
  data: 'myData',
  columnDefs: [{
    field: 'defaultColumns1.region',
    displayName: 'Region'
  }, {
    field: 'defaultColumns2.LocationName',
    displayName: 'Location',
    headerGroup: 'address'
  }, {
    field: 'defaultColumns2.LegalName',
    displayName: 'Legal Name',
    headerGroup: 'address'
  }],
  enableColumnResize: true,
  groupHeaders : true
}
}]);

index.html
<!DOCTYPE html>

<meta charset="utf-8" />
<title>Custom Plunker</title>
<link  rel="stylesheet" href="../dist/ag-grid.css" />

<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"   rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="style.css" />

A: ag-grid field attribute can only refer to a property of the data row, but the valueGetter attribute allows expressions. So, while
field: 'defaultColumns1.region'
won't work, switching to
valueGetter: 'data.defaultColumns1.region'
will work fine. Sample plunker forked from yours is at http://plnkr.co/edit/8enzrjt2MQwfa8VjGaIy?p=preview

A: There were a few issues with the way you went through your data.
$scope.myData is an array of objects, therefore you need to either iterate over it or dig data by index.
Also your $scope.gripOptions was not quite right. I just followed the ag-grid docs
Take a look at this updated plunker. The code is pretty basic but it does what I think you want. You can always create a function to iterate over the array (leave that as homework :-))
$scope.myData = [{
  "defaultColumns1": {
    "region": "PA"
  },
  "defaultColumns2": {
    "LocationName": "loc1",
    "LegalName": "legName1"
  },
  "name": "name1"
}, {
  "defaultColumns1": {
    "region": "PB"
  },
  "defaultColumns2": {
    "LocationName": "loc2",
    "LegalName": "legName2"
  },
  "name": "name2"
}];

var columnDefs = [{
  headerName: 'Region',
  field: 'region'
}, {
  headerName: 'Location',
  field: 'location'
}, {
  headerName: 'Legal name',
  field: 'legal_name'
}]

var rowData = [{
  region: $scope.myData[0].defaultColumns1.region,
  location: $scope.myData[0].defaultColumns2.LocationName,
  legal_name: $scope.myData[0].defaultColumns2.LegalName
}, {
  region: $scope.myData[1].defaultColumns1.region,
  location: $scope.myData[1].defaultColumns2.LocationName,
  legal_name: $scope.myData[1].defaultColumns2.LegalName
}, ]

$scope.gridOptions = {
  columnDefs: columnDefs,
  rowData: rowData
};

Take a look at the way $scope.gridOptions is now constructed ( as suggested in the docs.)
Hope it helps.


text:
Q: matlab remove for loop in matrix computation I'm working on a problem on Matlab according to Matrix. I think my code could be improved by remove the for loop. But I really don't know how to fix this one. Can anyone help me, please?
the code is:
K = 3;
X = [1 2; 3 4; 5 6; 7 8];
idx = [1;2;3;1];
for i = 1:K
    ids = (idx == i);
    centroids(i,:) = sum(bsxfun(@times, X, ids))./ sum(ids);
end

in this code, data points X is 4x2. There are K=3 centroids, so the centroids is a matrix of 3x2. This code is part of a K-mean function, which is using data points and their closest centroids to find new position of centroids.
I want to make the code as something without the FOR loop, maybe beginning like this:
ids = bsxfun(@eq, idx, 1:K);
centroids = ..............

A: You could apply accumarray. Note that accumarray only works when X is a column. So, if X has two columns, you can call accumarray twice:
centroids(:,1) = accumarray(idx, X(:,1), [], @mean)
centroids(:,2) = accumarray(idx, X(:,2), [], @mean)

Alternatively, if X contains two columns of real numbers, you can use complex to "pack" the two columns into one complex column, and then unpack the results:
centroids = accumarray(idx, complex(X(:,1),X(:,2)), [], @mean);
centroids = [ real(centroids) imag(centroids)];

If X has an arbitrary number of columns, possibly with complex numbers, you can loop over columns:
centroids = NaN(K, size(X,2)); %// preallocate
for col = 1:size(X,2);
    centroids(:,col) = accumarray(idx, X(:,col), [], @mean);
end

A: You can avoid the bsxfun by using logical indexing, this seems to be a worthwhile performance increase, at least for small matrices X. It is best for small K, and for a small number of rows of X.
K = 3;
X = [1 2; 3 4; 5 6; 7 8];
idx = [1;2;3;1];
centroids=zeros(K,2);
for i = 1:K
    ids = (idx == i);
    centroids(i,:) = sum(X(ids,:),1)./sum(ids);
end

If X has a large number of rows, this method is fastest:
K = 3;
X = [1 2; 3 4; 5 6; 7 8];
idx = [1;2;3;1];
centroids=zeros(K,2);
t=bsxfun(@eq,idx,1:K);
centroids=bsxfun(@rdivide,t.'*X,sum(t).');

And if K is very large, Luis' accumarray method is fastest.


text:
Q: How can I retrieve the image which is stored in bytea column of a pg_toast schema? I have a table called photo, that contains 3 columns

*

*chunk_id oid

*chunk_sq int

*chunk_data bytea

How can I see the stored image?
The (bytea) type column contains data like
'034\350sec\302\340s\221\\030seq\301\037\022\034seq`uence!V!\364s\030ett\241\376\001\310sho\214rt\224\204\002Tize\001\240\370sloDR#\024\002\020\023\273\003\240\360ourc\324\.................'

select * from pg_toast.photo

A: Certain graphical DB clients will show you the image when going to the table data view.  In plain query output (for example in psql), though, you cannot expect images to appear.  Otherwise, you have to 'decode' the bytea.
Here is an example solution (written in PHP) on gis.stackexchange.com:
$conn = pg_connect("...");
$res = pg_query($conn, "SELECT chunk_data AS photo FROM photo WHERE ...");
$raw = pg_fetch_result($res, 'photo');
header('Content-type: image/jpeg');
echo pg_unescape_bytea($raw);

Note:
pg_toast is not usually a schema you query directly from.  What is stored there has a 'parent' table, do your queries against it instead.  Then you can possibly use sane column names in your queries, and so on.


text:
Q: SEO of print pages I'm interested in SEO of print pages. I have a page with an article and a link to the same address with the suffix /print/, which then shows the came content, but with a print-like stylesheet.
This creates duplicities in search results, because both pages are the same, just the address is a bit different.
I already did a little research on this topic and there are a few options to use:

*

*set rel=canonical to the original page from the print pagee

*meta noindex for the print page

*rel=nofollow for links

What do you think is the best solution?

A: *

*As suggested above, use a special stylesheet for the printing of your pages. Good tutorial here. This is the preferred method as you don't have to make two pages just so one can be printer friendly. That means no duplicate content issues and less pages for you to maintain.

*Use rel="canonical" on the print version of the page. No need to use noindex or nofollow if the canonical URL is specified.

A: You can also use a javascript to change your stylesheet. This way you'll have an actual link people can click on.
If you want to hide your menu, ads etc just use display: none for those elements in the print stylesheet.
Here's a link to the script:
http://www.dynamicdrive.com/dynamicindex9/stylesheetswitcher.htm