text:
Q: trying to find the biggest negative and smallest positive from given input im trying to build an algorythm which input is 10 numbers (positive and negative) and the output is the smallest positive number and the biggest negative number.
im getting the right answer for the smallest positive, but not for the biggest negative.
code and output are inserted.

A: If you have a collection, say, int[] numbers you can just query it with a help of Linq:
  using System.Linq;

  ...

  int[] numbers = ...

  ...

  // Either biggest negative or 0 (if we don't have any negative values)
  int biggestNegative = numbers
    .Where(x => x < 0)
    .DefaultIfEmpty() // <- we don't want exception on empty input
    .Max();

  // Either smallest positive or 0 (if we don't have any positive values)
  int smallestPositive = numbers
    .Where(x => x > 0)
    .DefaultIfEmpty()  // <- we don't want exception on empty input
    .Min();

If you prefer to compute the values in a for loop:
  int biggestNegative = 0;
  int smallestPositive = 0;

  for (int i = 0; i < 10; ++i) {
    ...
    // Simplest, you may want to check user input
    int value = int.Parse(Console.ReadLine());

    ...
    if (value > 0)
      smallestPositive = smallestPositive == 0
        ? value
        : Math.Min(smallestPositive, value);
    else if (value < 0)
      biggestNegative = biggestNegative == 0
        ? value
        : Math.Max(biggestNegativee, value);
  }

Let's print the values out:
Console.WriteLine(
  $"Biggest negative: {(biggestNegative == 0 ? "???" : biggestNegative.ToString())}");

Console.WriteLine(
  $"Smallest positive: {(smallestPositive == 0 ? "???" : smallestPositive.ToString())}");

A: if (num>negMax)

There is a mistake in this condition. As your initial negMax value is 0, no negative number will meet the condition, and therefore negMax value will never be updated.

A: You're initializing negMax as 0.
There is no negative number that is bigger than 0.
Depending on what exactly you want to accomplish, you could do one of the following:

*

*Initialize negMax as int.MinValue
This would be okay if it's guaranteed that there's at least one negative number, since the first negative input is guaranteed to be equal or greater. If negative input isn't guaranteed, you cannot tell if there were any and your output may end up incorrect.

*

*Modify the condition for assigning a new value to negMax
You could instead modify the condition for assigning a new value to negMax to if (num > negMax || negMax >= 0).
Since you usually don't treat 0 as a negative number (and if you do, you can initialize negMax with any positive number instead), you'd know that there were no negative numbers if the output ends up as 0.
To do the same with posMin, you'd have to initialize it as something less than 0 and adjust the if-condition for assigning a value to that variable accordingly.
Alternatively, you could also declare negMax and posMin as int?s and check for null instead of >= 0.
If you choose this way, you can check the values for both variables and output, for example, that no negative or no positive numbers were entered instead of outputting whichever placeholder you chose.


text:
Q: Validation and data persistence in a domain model My (first and current) workplace (a .NET shop) suffers from an over-abundance of anemic domain models, to the extent that I don't really know how validation and data persistence should be handled in a proper domain model.
Data Persistence
One option would be to give the domain model a way to do persistence itself. You could, for example, inject an IFooRepository via constructor injection, and have that resolved by an IoC container to ensure you don't create a dependency on it (à la onion architecture). But I'm not sure if the code that uses the domain model should be responsible for calling methods to save the data, etc., or if it should be done implicitly behind the scenes on a background thread. Perhaps this breaks that purity of the domain model and is more along the lines of the active record pattern.
The other option I see is to not tie the domain model to data persistence at all and instead have a coordinating service layer responsible for that aspect.
What are the best practices for data persistence in the domain model pattern?
Validation
Another problem I don't know how to solve with a proper domain model is how to indicate to the UI why the current model state is invalid without coupling to (or at least catering to) the UI. For example, let's say I have a form an user fills out with various fields. We want to validate that input, and if something is wrong, indicate an error on that specific field with a message.
How would we handle validation with that level of granularity without adding significant complexity to the domain model, or doing hack-ish stringly-typed things (like throwing an validation exception with the property's name and a message)?

A: I could be mistaken in my understanding, but I believe your trying to redesign your Domain Model so that it isn't riddled with anemia.  A couple of really, really great books on the matter are:

*

*Martin Fowler - Patterns of Enterprise Application Architecture

*Eric Evans: Domain-Driven Design: Tackling Complexity in the Heart Of Software

*Vaughn Vernon: Implementing Domain Driven Design

They have a lot of content which answers quite a few questions on your goal.  One of which is:

A rich Domain Model can look different from the database design, with
  inheritance, strategies, and other Gang of Four patterns, and complex
  webs of small interconnected objects.  A rich Domain model is better
  for more complex logic, but is harder to map to the database.
A simple Domain Model can use Active Record, whereas a rich Domain
  Model requires a Data Mapper.  Since the behavior of the business
  subject to alot of change, it's important to be able to modify, build,
  and test this layer easily.

That is an excerpt from Fowler.  He will go into details about the model being anemic and bloated models as well.  The scope of the question to me appears quite large; so I'm not sure I could delve far into it.  Those books should point you in the right direction; also will allow you to gauge your current project and implementation to refactor it quickly.
From a relatively basic understanding:
You should be able to abstract your model, which will allow a brief overlay of the UI and Data Access into your Domain Model.  But otherwise the model should allow a clear, clean, concise implementation which will help separate responsibility.
Sorry I couldn't be more help.

A: The question arises what your UI is using to get the data and how it sends the data to be persisted. I'm afraid since you mentioned you have no service layer and you suffer with finding the right place for your validation, that your UI works directly with your domain classes. That could be the way to go, however it does not sound like a very complex application and you can do persistance work and querying right in the UI code. You can check posts of Ayende Rahien and many others who talk about getting rid of repositories. In relatively simple scenarios ORM is capable to provide enough isolation of domain model from the persistance itself. Also it is a questionable matter if modern ORMs can be seen purely as DAL. Look at NHibernate, it can do so much more than just mapping simple tables to simple classes. And if you look at your repositories you might find a bunch of methods called GetByThis and GetByThat, which issue a simple query to the ORM (if you use one of course) and just play a silly role of unneeded abstraction to make an impression that you do DDD.
Concerning your comment about "not creating" dependencies by injecting repositories - you will onvert control but you will have dependency as soon as you use repository class instance in your domain object. It does not matter how it gets there. So this is the worse choice of all.
To your validation question I would recommend you to look closely to your validation as such and decide what validation is domain specific and what is more data entry specific. Data entry validation like mandatory fields should not be checked by the domain model. It is a simple job and UI layer is perfectly capable of doing that. Even more, most of modern UIs are able to do this validation very easily. However you need to find a way to inform your UI about the data input rules (I will get back to it below). Your domain model need to perform more business-oriented validation, like if customer with such name already exists. But you, again, cannot do this inside your domain class since you are unable to query existing data from there because it is not the domain object responsibility to care about anything outside of its own aggregate.
So if you want to go to deal DDD journey I would recommend you to look at CQRS principle. It is often bound to event sourcing but you can just skip that. Concentrate on this scenario, when using RDBMS with or without ORM or NoSQL for persistence:

*

*Create input models and view models to be used solely by the UI.

*Decorate your input models with data attributes for client-side validation.

*Send commands from the UI to your backend to do business validation and persistence.

*Send queries to your backend from the UI to get the data to show. Returned data should be placed in view models.

*Use domain events to communicate between different bounded contexts

It does not necessarily require the backend logic to be put in an application server (although it is very desirable to enable having multiple UIs with the same backend). You can use in-memory events to send commands and queries too.
But again, look at what you really need, don't try to overscale your abstractions just because the book says so. Remember that very often abstractions are put in place just because someone heard this is a good thing. Repositories is a classic example, when people say it makes their system persistence ignorant and they can change their ORM but in fact no one does that. When ORM is changed it means almost full redesign and repositories get scrapped equally well together with all other code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: VBA: String indices in multi-dimensional arrays From what I've read, it doesn't look possible to use string indices in arrays. However, the topic seems to summarize what I am trying to do.
I have a table showing student and course information in Excel, and from that table I need to create something like
x(StudentID, CourseID) (equals 1 if student is taking the course, 0 otherwise)
I've been Googling for two days now but I'm lost. I've come across with collections and dictionaries but I don't know which one is more suitable or if they are suitable at all. What would you recommend?
Thanks in advance.

A: I agree with the other comments but believe there cam only be one unique key in a dictionary and as such suggest you fashion one by using the student and course.
Dim s
Set s = CreateObject("Scripting.Dictionary")
s.Add "student a-course a", "1"
s.Add "student b-course b", "1"
s.Add "student c-course c", "1"

If s.Exists("student c-course c") Then
    MsgBox s("student c-course c") 'displays 1
End If

If s.Exists("student c-course a") Then
    a.add "student c-course a", "1"
End If

Two points; the value of 1 is pointless as the s.exists(...) method exists, and as the dictionaries are used you can create a loop to add all your student and course information.


text:
Q: iOS : warning: changing property masksToBounds in transform-only layer, will have no effect I already go though
<CATransformLayer: 0x14fea3710> - changing property masksToBounds in transform-only layer, will have no effect
"changing property masksToBounds in transform-only layer, will have no effect" in Xcode 7
CATransformLayer : changing property masksToBounds in transform-only layer, will have no effect
but still confused about this warning
i get this warning on
 [self presentViewController:alertViewController animated:YES completion:nil];

here i am adding UIAlertViewController in ViewController
1. how can i remove this warning.
2. should i ignore it.
or there is some other way to show UIAlertViewController in viewcontroller

A: Its a known issue in iOS comes in various scenarios like:

*

*Presenting Custom Keyboard

*Presenting UIActivityViewController
etc.

So you simply need to ignore it


text:
Q: Fluid covers the floor of a container I know this formal definition of a fluid:
1.) It is a continuum.
2.) It cannot absorb shear stress.
But how can you explain with that, that a fluid covers under the influence of gravity the whole bottom of a container? How does it correspond with the shear stress?

A: Shear stress is a volume quality. When you apply different forces inside different layers of a continuous solid, there will develop forces between these two layers (so inside the volume between these layers). For a continuous fluid, no such forces can arise, so no shear stress can develop. So even though there are different forces at work when water covers the floor, there will never be shear stress present. By the very definition of a continuous liquid.


text:
Q: Controlling visibility of HTML controls through javascript based on security model For example:
Server side is Asp.net MVC,
Client side is KnockoutJS.
From a security and standards perspective:
Is it acceptable for the server to output an edit link and the client side code then set the visibility of the control based on javascript viewmodel property such as "HasEditPermission"?
Or should the MVC Razor syntax selectively output the controls based on the viewmodel?
Traditionally this would all be done server side, however with most databinding now occurring on the client it is mixing concerns by having conditional logic in Razor and KnockoutJS.
It goes without saying that the server validates all postbacks based on permissions, so escalation of privileges is not possible. Its also fair to point out that the concept of "Obscurity is not security" does come into play here. Just because an edit link does not exist does not mean that it isn't obvious for an attacker to attempt yourwebsite/users/edit/1

A: My pragmatic take on this is that if you can output conditional Knockout view models and data binding expressions etc via Razor at page generation time in a fairly clean way without too many hacks and design tradeoffs, then do so. But so long as you are not stashing security related data in your Javascript or the DOM (passwords, secret tokens etc) then I wouldn't lose too much sleep over using client side logic to decide whether to make something like an Edit link visible or not. As you say, anyone can modify an existing URL which they have been given rightful access to anyway - which is why the resource itself does the appropriate checks when requested.
Often with a Knockout style UI you might make certain links / buttons available based on dynamic client side conditions anyway - and the distinction between what is an actual "security breach" and what is someone cheekily exposing insufficient server guard code and buggering up your application logic by hacking things with Firebug becomes a bit blurred. I would say do what's sensible and is in proportion to the risks / stakes of your specific business context.


text:
Q: FOL Paradox Translation I'm working on a translation exercise for FOL using existential and universal quantifiers, but it's proving rather tricky. Below I'll attach the expressions and the question.
P(x) : ___x is person
D(x) : ___x drinks beer
(The domain is the bar.)
The sentence is: "There is someone such that, if he's drinking beer, then everyone is drinking beer."
So I'm a bit unsure of where to start. I'm sorry this probably isn't the best use of the math stack exchange but my teacher isn't being very helpful. I would be thankful for some help with this problem!
My thinking:
∃x (D(x)→∀y D(y))
I'm not sure if (or how) I should be integrating P(x)...

A: You're definitely off to a good start with $\exists x (D(x) \to \forall y D(y))$. The question is related to the notion of restricted quantifiers.
What you want to say is "there exists a person $x$ such that $(D(x) \to $ for every person $y$, $D(y))$". In other words, you want to switch from $\exists x$ to "$\exists$ a person $x$", and $\forall y$ to "$\forall$ persons $y$".
To be more precise, we interpret "there exists a person $x$ such that $Q(x)$" to mean "there exists $x$ such that $(x$ is a person and $Q(x))$. And we interpret "for all persons $y$, $Q(y)$" to mean "for all $y$, $(y$ is a person $\to Q(y))$".
I can't say too much more without totally giving the answer away.


text:
Q: Received HTTP response headers after- 503 for health check client handler In our dotnet6 project we have implemented health checks in our application and we have deployed our application AzureKubernatiesServices. Recently we started facing some facing some issue. We are able to see the output of health checks correctly but in logs we are getting the fallowing error
we have implemented health check  as bellow.
health service
        {
            services.AddHealthChecks()
                .AddCheck<DatabaseHealthCheck>("db_health_check")
            .AddCheck<XXXXXAPI_HealthCheck>("XXXXX_health_check")
            .AddAzureServiceBusTopic(configuration["ServiceBusConnString"], configuration.GetValue<string>("ServiceBusConfig:TopicName"), "servicebus_topic_health_check")
            .AddAzureServiceBusSubscription(configuration["ServiceBusConnString"], configuration.GetValue<string>("ServiceBusConfig:TopicName"), configuration.GetValue<string>("ServiceBusConfig:SubscriptionName"), "subscription_health_check");
            services.AddHealthChecksUI().AddInMemoryStorage();
            return services;
        }

ConfigureMethod
{
app.UseEndpoints(endpoints =>
            {
                endpoints.MapHealthChecks("health", new HealthCheckOptions()
                {
                    Predicate = _ => true,
                   ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
                });
                endpoints.MapHealthChecksUI();
            });
}

AppConfig
"HealthChecksUI": {
    "HealthChecks": [
      {
        "Name": "HealthChecks",
        "Uri": "http://xxxxx:80/health"
      }
    ],
    "EvaluationTimeInSeconds": 5,
    "MinimumSecondsBetweenFailureNotifications": 60
  }


text:
Q: Adobe Air Desktop App hanging-up (not responding) i am doing networking in my app.. the data sent by the PCs (with the app installed) are about 3KB simultaneously (real-time computations are done in my app).. i was wondering why did my app is not responding when sending the data to different PCs? most platform affected are Ubuntu 12.04 (precise pangolin)
2nd question : how can i achieve multithreading in adobe air desktop apps?
sorry for my english...

A: For your 2nd question, to have multi-threading in Adobe AIR Desktop Apps, you will require Flash Player 11.4 and AIR 3.4. There is a new concurrency API with Worker class.
Post codes for 1st question before we can help.


text:
Q: Jquery expand and collapse menu is not working I am working on a sidebar menu navigation which expands and collapses when user clicks on the menu. On top of that, I want the menu to stay expanded if the link on the sub menu is active when the page loads.
This is the code sample that I am working on right now. Can someone please help me check the issue on my code?

jQuery(document).ready(function(e) {
  {
    var m = e("ul.menu li.sidebar ul.sub-menu");
    e("li")
  }
  e("ul.menu > li.sidebar > a").click(function(e) {
      e.preventDefault()
    }),
    e(document).mouseup(function(i) {
      var n = e("li.sidebar");
      n.is(i.target) || 0 !== n.has(i.target).length || m.hide("fast")
    });
});
.sidebar {
  padding: 0 !important;
  margin-top: 2%;
}
.sidebar a {
  background-color: #122842;
  padding: 3%;
  color: white !important;
}
.sidebar .sidebar-submenu a {
  color: #6e6e6e !important;
  background-color: #e1ecf1 !important;
  display: block;
}
.sidebar .current-menu-item a {
  color: #22374f !important
}
.sidebar .sub-menu {
  display: none;
}
.current-menu-ancestor .sub-menu {
  display: block;
}

Menu A ▶

submenu 1

submenu 2

submenu 3

Menu B ▶

submenu 4

submenu 5

submenu 6

Menu C ▶

submenu 7

submenu 8

These are the behavior that I want to achieve:

*

*Submenu 1, submenu 2, and submenu 4 are on the same page but different 'menu'. If the page is selected, both menu A and menu B expand while menu C stay collapse.

*If user clicks on submenu 3 which is under menu A, when the page loads, menu A expands while menu B and C collapse.

*Whenever a submenu is active, class "current-menu-item" is added to
the li tag and class "current-menu-ancestor" is added to the ul tag

The issue that I have right now:

*

*The menu is automatically expanded when any sub-menu is active, but the menu is not clickable

*when I replace the jQuery with the code below, the menu is clickable
and automatically expanded when any sub-menu is active, BUT the sub
menu is not clickable (not opening the link)
jQuery(document).ready(function(e){
 jQuery('.sidebar a').click(function(e){
      e.preventDefault();
 if (jQuery(('.sidebar').children('.sub-menu:first').is(':visible')) {
           jQuery(('.sidebar').children('.sub-menu:first').hide();
      } else {
           jQuery(('.sidebar').children('.sub-menu:first').show();
      }

});
});
Thank you in advance!

A: Please add jquery cookies library in your head just after jquery

check this for more info stack-cookie-is-not-function


text:
Q: Return warning in addition to reply in mvc kendo grid I created kendo grid in view which gets its data from a controller method. If there are no errors the rows are returned to view. If there is an error the error is returned using event onError.
In controller:
        public ActionResult LoadgridData([DataSourceRequest] DataSourceRequest request, string arg)
    {
        var result = SomeApiCall();

        if (result.Count == 0)
        {
            return this.Json(new DataSourceResult
            {
                Errors = "Some error occured"
            });
        }

        //TODO: send warning if result.Count > 1000

        return Json(result.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
    }

This method LoadgridData is used in kendo grid read.Action
I want to send back a warning from this method when data size is more than a threshold.
Does anyone know how I can do it

A: You can throw an error right there in that TODO throwing an Exception or returning a BadRequest().
Then in your DataSource error event you can handle it and show a message.
Example:
public ActionResult LoadgridData([DataSourceRequest] DataSourceRequest request, string arg)
{
    var result = SomeApiCall();

    if (result.Count == 0)
    {
        return this.Json(new DataSourceResult
        {
            Errors = "Some error occured"
        });
    }
    else if (result.Count >= 1000)
    {
        // Option #1
        throw new Exception("Too many records");

        // Option #2
        return BadRequest();
    }

    return Json(result.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}

DataSource:
$('#grid').kendoGrid({
    data: {
        url: ...
        error: () => {
            window.alert('Too many records');
        }

UPDATE:
To show both data and error, you can customize the ajax request, so you will be able to intercept the result before its displayed. Then you return both error and data in the same result:
kendo.data.DataSource({
  transport: {
    read: function(options) {
      $.ajax({
        url: "https://demos.telerik.com/kendo-ui/service/products",
        dataType: "json",
        success: function(result) {
          // Show message to user
          window.alert(result.error);

          // Print data to grid
          options.success(result.data);
        }
      });
    }
  }
});

Demo


text:
Q: jQuery: replace() class name / regex I am trying to write line of jquery that finds an input that has a class that begins with "a\d" (the letter a and a number) and replace the number with another number.
This is what I have tried, does anyone notice why this would not work?
$('form').find('input[class^="a\d"]').replace(/a\d+/,'a22');

Please note: this is one line out of many, I have extracted this line because it is where I am having trouble.

A: You'll need to do it more like this:
$('form').find('input[class^="a"]').attr('class', function(i,cls) {
    if( /a\d/.test( cls ) ) {
        return cls.replace(/a\d+/,'a22');
    }
});

When using .attr() to set the class (or any attribute), you can pass it a function which has 2 parameters. The i is the current index in the iteration. The cls is the current value of class.
The return value will be used to update the class. If nothing is returned, nothing will be changed.

A: Try this
var regExp = /(a\d+)(.*)?/;
$('form').find('input[class^="a"]').each(
    function()
    {
        var el = this;
        var className = el.replace(regExp, "a22$2");
        el.className = className;
    }
);


text:
Q: What is the work around for a weird javascript form submit bug in Safari 5? I am not sure if this is an existing bug, but after debugging a web application I am working on, I have discovered some weird behavior in Safari 5. Here is the scenario:
Page A ---- HTTP POST ----> Page B ---- HTTP POST ----> Page C
Page A:
<body onload="document.forms[0].submit()">
        <form method="post" action="pageB.php">
                <input type="hidden" name="display" value="ABC" />
        </form>
</body>

Page B:
<body onload="document.forms[0].submit()">
        <form method="post" action="pageC.php">
                <input type="hidden" name="display" value="123" />
                <input type="hidden" name="extra" value="XXX" />
        </form>
</body>

Page C:
<body>
<?php

        print_r($_REQUEST);
?>
</body>

Of all the browsers I have tested so far only Safari 5 (Mac version) will display the value "ABC" for name="display" and I still can see the value "XXX" for the field "extra". All other browsers (Including Safari 3, 4) will display the value "123" which is the correct value.
For some reasons I still need to submit the form using  for Page A and Page B, with this condition, what is the workaround for Safari 5? (To make it submit the correct value at Page B, which should be 123 instead of sort like forwarding the value from Page A to Page C)
Many Thanks!

*

*Edit1: Only happens on Mac OS (Snow Leopard, Lion) Safari 5

*Edit2: Make example more clear

A: Safari is filling in the form field using autofill behaviour. You probably have the "Other forms" option enabled in your preferences. Even Apple recommend you turn this feature off since it can be used for stealing private information.
To workaround this for people who have it turned on anyway try <form autocomplete="off">

A: Fire up a proxy like Fiddler http://www.fiddler2.com/ and watch the post data move between forms.  If it only happens on this one browser on this one machine, it seems more likely like a browser cache thing than a form post error.  What if you start at pageB?  What if you clear your cache first?


text:
Q: AudioKit generates two small `caf` files on temporary folder I use AudioKit in my app.
Since I implemented AKNodeRecorder and exportAsynchronously method on my app, AudioKit generates two small caf files on temporary folder when the app is launched.
A size of each file is 4KB, so it's not a serious problem but is there any way to avoid it?
a snapshot of the temporary folder of the simulator
I use Xcode version 9.1, swift version 4, AudioKit version 4.0.3, iPhone 6, iOS 11.0.2


text:
Q: Поворот объекта в Unity Необходимо повернуть объект в юнити. В Inspector видно, что он повёрнут, но в показе камеры это не заметно, т.е. материал не поворачивается вместе с объектом. В коде я сначала присваиваю объекту материал, и только потом поворачиваю следующим кодом:
obj.transform.rotation = Quaternion.Euler(0, 90*k, 0);

где k - рандомное число от 0 до 3
Потом пробовал через:
obj.transform.Rotate(0, 90*k, 0);

но результат тот же

A: Проблему решил. Оказалось, что код рабочий, и надо лишь в объекте в Inspector открыть Static и убрать там галочку с компонента BatchingStatic. Всё заработало.


text:
Q: Not able to scroll down while drag and drop if the page has more than one vertical scroll bar The canvas area not getting scroll down
Hi,
I am not able to scroll down the canvas to drop my dragged value.Actually i done
my code while draggable as below . But in my page i have two scroll bars vetically.How to scroll down my canvas to drop. See my screen shot
$(".dnd-preview-draggable-answer").draggable({
revert: "invalid",
tolerance: "pointer",
appendTo: "body",
scroll : "true",
cursorAt: { top: 0, left: 0 },
});

A: You can use the traditional way, your code will look like this:
$(".draggable").draggable({
                 revert: "invalid",
                 tolerance: "pointer",
                 appendTo: $(".inner-content-that-will-be-scrolled"),
                 scroll : "true",
                 cursorAt: { top: 0, left: 0 },
                 drag: function( event, ui ) {
                     var draggableY = parseInt($('.draggable').css('top'));
                     var scrolled = $('.inner-content-that-will-be-scrolled').innerHeight();
                     if (draggableY + 50 >= y2) {
                         //Start scrolling
                         $('.page').animate({
                            scrollTop:  scrolled},
                            {duration: 5000,
                            step: function() {
                                var x = parseInt($('.draggable').css('left'));
                                var y = parseInt($('.draggable').css('top'));
                                //detect stop scrolling
                                if ((y + 20 < y2) || y > y2 + 20 || x > x2 || x < x1) {
                                    //cancel animation
                                    $(this).stop();
                                 }
                               }
                         });
                     }
                 }
             });
         });


text:
Q: How does Java prevent an as yet unassigned instance from being garbage collected? Example:
public void foo() {
    A a = new A();
}

What if there is this sequence of events?

*

*Java allocates memory for A.

*The A() constructor runs. Now there is an instance in the heap.

*The GC runs.

*There are no refs to the object and it is removed before being assigned to a.

How does it prevent this from occurring? I would greatly appreciate links to article where it is explained.

A: This is easy to answer once you know that the call stack is traversed by the garbage collector (GC). So when it traverses the stack of the method foo, it simply knows that there are references (a) pointing to that heap memory.
In order to know what is garbage, the GC has to first scan everything that is alive. Since there are references pointing to that memory (the new A()); that is treated alive, at least until a is used, somewhere, by some thread.


text:
Q: The use of Lastindexof and Remove in C# for database confusion Ok iv tried everything i cant get this to work it shows me nothing:
        foreach (DataRow dr in dt.Rows)
        {
            keyNameTextBox.Text = dr["KeyName"].ToString().Remove(keyNameTextBox.Text.LastIndexOf("_") + 1); ;

            keyTextBox.Text = dr["Key"].ToString();

        }

if I change after .Remove (0
it then gives me the result which is good but only everything after _
But My goal is to see everything before _ excluding the _
Iv seen a Stack Overflow posts which helped me find out about indexof and remove but for some reason both not working for me is it because im in a for each ? how would i get around it ? any help would be awesome!
Source i used:
Remove characters after specific character in string, then remove substring?

A: Here
dr["KeyName"].ToString().Remove(keyNameTextBox.Text.LastIndexOf("_") + 1);

you search in one string (keyNameTextBox.Text) and remove from another (dr["KeyName"].ToString()).
What you really need is something like this:
var keyName = dr["KeyName"].ToString();
keyNameTextBox.Text = keyName.Remove(keyName.LastIndexOf("_") + 1);


text:
Q: What does the checkbox "Trust access to the VBA Project Model" mean? "Trust access to the VBA project model" is something I instinctively click on right after "Enable all macros", simply because I don't have time to workout whether or not it will break the code I would like to run.
This is naughty - I should know what I'm doing and the implications. Assuming I've enabled all macros already, what extra features/dangers are exposed to me when I open the Pandora's Box of trusting access to the VBA project model?
This line of code runs without trusting access:
VBAProject.Sheet1.Calculate

Please would you post some code that requires trusted access?

A: It allows your code to access the VBA project by doing such things as reading and altering other code or changing the codenames of objects. Basically it controls access to the properties and methods of anything you access via the Workbook.VBProject property.


text:
Q: Inplace Datatable modification instead of using "Defaultview.ToTable" I am working on an Algorithm that is very convenient to use datatables for it's implementation.
As part of the Algorithm I keep sorting the datatable by it's first columns using:
dt.DefaultView.Sort = dt.Columns[0].ColumnName + " ASC";
dt = dt.DefaultView.ToTable(); // This is the Evil line

The problem is, that it seems that dt.DefaultView.ToTable(); is relatively a heavy operation Memory and Time wise (It takes nearly 60 percent of the algorithm's time!), and soon enough this algorithm will have to handle big amounts of data.

I am aware I can sort it manually, but I would hate to reinvent the wheel...
So, is anyone aware of a way to get the job done without relocating the full tables each and every time, and without reinventing the wheel?

A fuller sample of code:
var dt = new DataTable();
/*Populating dt...*/
for (int i = 0; i < input.Length; i++)
{
    /*Some more code here that includes modifying first column*/

    dt.DefaultView.Sort = dt.Columns[0].ColumnName + " ASC";
    dt = dt.DefaultView.ToTable();
}


text:
Q: C++ uniform initialization in C arrays and structs I've seen some old code that looks like this: char foo[100] = { 0 };. Something similar happens with structs, like so: STRUCT st = { 0 };. The intention in both cases is clear, namely to zero-initialize the respective variables. As such, char foo[100] {}; and STRUCT st {}; would have been more idiomatic.
My question is: should the code with <variable> = { 0 } be expected to achieve the same outcome? I've tested this with release-build binaries and the elements appear to be zero-initialized, but is this guaranteed by the standard? It seems to me that <variable> = { 0 } should only guarantee for the first element of the variable (array element or struct member) to be zero.
Also, what behavior is indicated by the similar declarations char foo[100] = {}; and STRUCT st = {}?
(Motivation behind this question is that I'd change all the declarations to the idiomatic form, but if there is no guarantee of zero-initialization then the issue is something more serious and worth opening a ticket over.)

A:
It seems to me that <variable> = { 0 } should only guarantee for the first element of the variable (array element or struct member) to be zero.

That syntax, for POD types, is the same as <variable> = {};
Anything that is not explicitly specified is initialized to zero. Use of <variable> = { somve_value } makes a difference only when some_value is other than zero.
Even though the same syntax can be used for non-POD types, the elements that are of non-POD type that are not explicitly initialized are initialized using their default constructors.
From 8.5.1 Aggregates/7:

If there are fewer initializer-clauses in the list than there are members in the aggregate, then each member not explicitly initialized shall be initialized from an empty initializer list  ([dcl.init.list]). [ Example:
struct S { int a; const char* b; int c; };
S ss = { 1, "asdf" };

initializes ss.a with 1, ss.b with "asdf", and ss.c with the value of an expression of the form int(), that is, 0.  — end example ]


text:
Q: NSString returning jibberish Totally lost with this one. Here's my code:
theColor = [NSString stringWithFormat:@"white"];
NSLog(@"%s", theColor);

Which is returing:
†t†å

I must be doing something stupid, but can not figure it out for the life of me.

A: Change your print to:
NSLog(@"%@", theColor);

Hope it helps.
The thing is that %s expects a C-string (char array with a NULL terminator) and you are passing a NSString instance which is not the same as a C-string. The modifier you need in a format to print NSString content is %@.

A: %s is for printing C-style strings.
%@ is for printing Objective-C objects (like NSString).

A: BTW: "theColor = [NSString stringWithFormat:@"white"];" – why not "theColor = @"white";"?
Greetings


text:
Q: can't able to call controller method based on the given url I am using Laravel framework. I have a problem while calling the method of controller class.
routes.php :
 Route::get('/', function()
{
  return View::make('hello');
});

It should call the view page of hello. It worked fine when giving the url http://example.com/laravel.
Route::get('home','HomeController@showWelcome')

When am provide the url like http://example.com/laravel/home it doesn't call the method of HomeController class.
HomeController.php :
 <?php

    class HomeController extends BaseController {

       public function showWelcome()
       {
           return View::make('hello');
       }

    }

 ?>

can anyone help me findout what mistake i did.. Thanks in advance.
routes code look like below :
 <?php
   Route::get('/', function()
   {
        return View::make('hello');
   });

   Route::get('home','HomeController@showWelcome');

?>

A: The text below is from the Laravel Documentation:
Apache
The framework ships with a public/.htaccess file that is used to allow URLs without index.php. If you use Apache to serve your Laravel application, be sure to enable the mod_rewrite module.
If the .htaccess file that ships with Laravel does not work with your Apache installation, try this one:
Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

Nginx
On Nginx, the following directive in your site configuration will allow "pretty" URLs:
location / {
    try_files $uri $uri/ /index.php?$query_string;
}

Source: http://laravel.com/docs/4.2/installation#pretty-urls


text:
Q: How to get total rows in Drupal 8 view with pagination? In Drupal 8, I use a view with pagination. There are 10 items per page.
In hook_views_pre_render(ViewExecutable $view) {..} I want to get the number of items to use in another function. However, $result = 10 and $total_rows = 10 due to the pager setting. The actual item number is between 500 and 2000.
As a workaround I tried a temporary view.
$view2 = Views::getView('my_view');
$view2->setDisplay('page_1');
$view2->setItemsPerPage(15000);
$view2->execute();

This works. view2->total_rows returns the desired value. But I don't want to use a fixed value in setItemsPerPage. 0 or null (for unlimited items per page) returns no result for total_rows.
What can I do to get the correct number of views-items?

A: In your hook_views_pre_render function, instead of calling view->SetDisplay and view->setItemsPerPage, you can execute the view (even with pager settings) and get the total rows/results:
  $view = Views::getView('my_view');
  $view->execute('page_1');
  $rows = $view->total_rows;

$rows will provide the total count that you are looking for.

A: And get_total_rows needs to be set to true for total_rows to operate.
$view = Views::getView('my_view');
$view->get_total_rows = TRUE;
$view->execute('page_1');
$rows = $view->total_rows;


text:
Q: Is it allowed to create a paid Facebook client using Facebook Graph API? I'm planning to build an alternative Facebook client for Android using Facebook Android SDK.
And do we have to get an api key/token/whatever for the graph api first?


text:
Q: Code-first Entity Framework not picking up web.config connection string when initializing I have been using code-first entity framework. I have defined a connection in the web.config, with name matching the class name of my DbContext (in this example 'MyDbContext').
EF uses this connection with no problems when the database exists.
However, if I delete the database (to force EF to re-create it) EF creates the database on the local Sql Express server instead.
If I specify the full connection string in the DbContext class constructor like
    public class ReykerSCPContext : DbContext
{
public ReykerSCPContext() :
    base("Server=tcp:MyDBSErver.database.windows.net,1433;Database=MyDB;User ID=#######;Password=#######;Trusted_Connection=False;Encrypt=True;MultipleActiveResultSets=True;PersistSecurityInfo=True;") { }
}

then the database is created correctly on the server of choice. Great!
Can anyone tell me if this is correct behaviour as I am bashing my brains out. I would like it all to work from the web.config, so I don't need to necessarily rebuild and remember to change settings in code etc..

A: This should do it:
public class EFDbContext : DbContext {
    public EFDbContext() : base("EFDbContext") {

    }

    public DbSet<Product> Products { get; set; }
}

You should have the connection string by the name of your context class in the web.config and that will do it. The web.config should be in root.
<connectionStrings>
    <add name="EFDbContext" connectionString="Data Source = .; Initial Catalog = ITSDB; Integrated Security = true" providerName="System.Data.SqlClient"/>
</connectionStrings>

A: If you do
update-database -v

and it shows it is using IIS express instance instead of the value from the Web.Config , it means EF is confused when the local IIS express instance is running.
I had the same issue and was resolved by stop/delete IIS express.
"sqllocaldb.exe stop v11.0"

"sqllocaldb.exe delete v11.0"

Hop that helps someone!


text:
Q: SharePoint 2013 + Office Web Apps: Cannot view PDFs on mobile devices I am working on a SharePoint 2013 solution on premise with office web apps on premise.
When users are on a mobile device and try to open a pdf document from search they are greeted with the following message: "Viewing of .pdf files has been disabled in Microsoft Word Mobile viewer".
I have tried both enable and disable: New-SPWOPIBinding –ServerName "Server.corp.Contoso.com" -Action "MobileView" –Application "WordPDF" -AllowHTTP from this article https://social.technet.microsoft.com/Forums/office/en-US/ebb2cc99-2cdf-44a9-964a-e922b1ae11e8/cannot-open-pdf-on-mobile-device?forum=sharepointgeneral. This does nothing.
I found this https://support.microsoft.com/en-au/kb/2912639 which says "This problem occurs because PDF viewing on mobile browsers is not supported in Office Web Apps or Office Online Server."
If this is true, do anybody have some workaround solutions or alternatives?
The use case is technicians driving around doing jobs need to view PDFs on tablets and phones but not download them on the device.

A: The default OWA action is to open PDF files in WordPDF Application. To overcome this behavior, we can remove the WordPDF binding from OWA and let it open by Ifilter as default. Run the following command in SharePoint Application server where you configured OWA WOPI Binding. This command will remove the WordPDF Application Binding from your SharePoint farm. This won't harm any other applications such as Word, Excel or PPTX.
Get-SPWOPIBinding -Action "view" -Application "WordPDF" | Remove-SPWOPIBinding
Removing the Binding for the WordPDF application will allow all the mobile devices to open PDF files from the browser normally without utilizing OWA WORD Application.
Reference: https://manojviduranga.wordpress.com/2016/04/13/unable-to-open-pdf-files-stored-in-sharepoint-using-mobile-browsers/


text: Q: How to integrate mozilla open badges with our website? I want to integrate Mozilla open badges with my website? what steps should i follow to integrate open badges with my website. I googled alot but didn't get any success, if some one will help, Million of thanks in advance...


text:
Q: Laravel 5.5.24 not showing css, javascripts and images I have a problem with a Laravel installed in a AWS Ubuntu machine. I was working on my computer via localhost (using the server via PHP in the public folder) I could see everything on the page. The bootstrap works perfect. All the CSS libraries, images and js are called and the page works like a charm.
When I deployed to my repository and my server I was surprised to see that the styles were not working.
First I thought maybe was the reading permission in the public folder, so I give it reading permission, this didn't work. After trying I gave all the Laravel folder 777 permission (I know that it is not ideal, but I'm kinda of desperate).
I was searching for another way to call the libraries. In the beginning I had this:
<link rel="stylesheet" type="text/css" href="/css/custom.css">

After some research, in some pages mentioned that it will be better if I use:
<link rel="stylesheet" type="text/css" href="{{asset('css/custom.css')}}">

This didn't work. So I have tried this other options:
<link rel="stylesheet" href="{{ URL::asset('assets/css/somestylesheet.css') }}" />
{ HTML::style('css/css.css'); }}

Both of them don't work either. I have tried this with all the js and images also but none of the are loading.
I have a similar page in another Instance in a AWS with Ubuntu and Apache, same configuration and it works.
The weird thing is that when I installed the Laravel in the server it displayed the home page of Laravel, but after I made the changes it stopped working
I'm looking in the developer tools to see what the problem is and I'm getting this.

It is like the Laravel its not letting the libraries to be accessed, but I have no idea how to make it work.
If you gals and guys need any extra information, I will be glad to let you know.

A: Well I find the error. It was the apache in the VirtualHost.
When declaring the DocumentRoot I made it pointing to the /public/index.php.
It has to be declared just in the public folder.

A: It seems it can't find your style files (404's in your screenshot of the network log). Are you sure they are present in the public directory? If you can't access them directly (e.g. yoururl.com/css/style.css). It's likely that they aren't present. Maybe you need to run npm run prod?


text:
Q: How to find return type of a method from an XML documentation file I'm trying to write a console app that will generate documentation pages based on the XML documentation file Visual Studio generates. So here's the problem, look at the XML generated by Visual Studio:
<?xml version="1.0"?>
<doc>
<assembly>
    <name>Assembly-CSharp</name>
</assembly>
<members>
    <member name="M:Utility.ScaleRange(System.Single,System.Single,System.Single,System.Single,System.Single)">
        <summary>
        Scales x from inA-inB to outA-outB
        </summary>
        <param name="_x">Value to scale</param>
        <param name="_inA">Input range min</param>
        <param name="_inB">Input range max</param>
        <param name="_outA">Output range min</param>
        <param name="_outB">Output range max</param>
        <returns>Scaled value</returns>
    </member>
</members>
</doc>

As you can see there's no way to know what type the method returns unless I write it in <returns> when commenting my code (which is something I don't want to do).
Is there a way to make VS output the type of the method? If not then I'm guessing I'm gonna have to use Reflection to help me out with this project.
Thanks in advance!


text:
Q: Magento 2: I need to run observer in crontab.xml. But it is not working I am running observer in crontab.xml. This is not working.
Here is my code
    <?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
    <group id="default">
        <job name="abandon_cron_run" instance="Abc\Abandon\Observer\Abandon" method="execute">
            <schedule>* * * * *</schedule>
        </job>
    </group>
</config>

Abandon.php
namespace Abc\Abandon\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class Abandon  implements ObserverInterface
{

    protected $scopeConfig;

    public function __construct(

        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig

    )
    {
      $this->scopeConfig = $scopeConfig;
    }

    public function execute(Observer $observer)
    {

            $productName=array();
            $productNames='';
             $itemsArray = $observer->getCart()->getQuote()->getItems();
            foreach($itemsArray as $item) {
                $productName[] = $item->getName();
            }
                 if(is_array($productName)){
                    $productNames .= implode(';',$productName);
                }

                $abdata['productNames'] = $productNames;
            return $abdata;
    }
}

A: I'm not fully sure what you are trying to achieve in your model, but as Dava suggests you won't be getting an observer passed into your method. You should change your model to something like:
namespace Abc\Abandon\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class Abandon  implements ObserverInterface
{
    protected $scopeConfig;

    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    ){
      $this->scopeConfig = $scopeConfig;
    }

    public function execute()
    {
        // do something here
    }
}

If you want to confirm it is running you could do something like:
namespace Abc\Abandon\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class Abandon  implements ObserverInterface
{
    protected $scopeConfig;

    protected $logger;

    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
        \Psr\Log\LoggerInterface $logger
    ){
        $this->scopeConfig = $scopeConfig;
        $this->logger = $logger;
    }

    public function execute()
    {
        $this->logger->debug(__METHOD__);
    }
}


text:
Q: How to use a List from a different SP2013 site as a web part? I'm brand new to SharePoint 2013, and only have a basic working knowledge so far.
My manager would like to take a List of projects from one site group, and use it on our department's home page.  I have tried using a Web Part > Page Viewer, but I want to display just the list, not the whole page.
Is this doable through the browser?  Or do I need to use SPDesigner and/or some scripting?

A: as a quick fix you can use script editor and use REST API to achieve your goal
here you  can read and learn about  REST API

A: If you just need to use the same list structure to add your own department projects, so you can use save the list as a template in list setting.

Then create a new one in your department site from this template.
If you need to display the same list content and both departments can use and add items in the same list so, check

*

*Display a SharePoint List from Parent Site in Sub Site

*SP 2016 - Display list from Parent site in sub-site


text:
Q: Mathematical objects determined by their network of relationships Let me quote Barry Mazur from his essay When is one thing equal to some other thing?:

"mathematical objects [are] determined by the network of relationships
  they enjoy with all the other objects of their species"

I always took this slogan literally, but recently I was overcome by doubts whether I missed something.
Have a look at the toy category of graphs over two fixed vertices and an arrow whenever there is a graph homomorphism. Compositions and identities are omitted:

The numbers are derived from the adjacency matrices: 0 = 00|00, 1 = 10|00, ..., 15 = 11|11.
Among others, the graphs #6 and #9 are not isomorphic (i.e. "essentially the same") but indistinguishable with respect to the network of relationships they enjoy (i.e. conjugate):
graph #6  graph #9
What is the grain of salt I have to take Mazur's slogan with? Or is there something wrong with my toy category?

A: I think the point is that there are two kind of equivalences between objects in a category: the first one is the relation of isomorphism between objects in the category, the second is the relation of conjugation through a given functor (here I'm using the notation of this thread).
It seems to me that the difference between these two kind of equivalences becomes clear if you see categories from a logical point of view: you can think a category as a theory in which the objects are the sorts of the theory (which can be considered set-types for the theory or unary predicates) while the morphisms can be seen as relations (or binary predicates) between this sorts. From this point of view functors are just interpretations of one theory into another one: they send sorts of one theory in sorts of the other one and relations between two sorts of the first theory in relations between the corresponding sorts of the second theory.
(Note:) categories have to be regarded as theories without identity.
From this point of view isomorphic objects are sorts which can be proven to be equivalent in the theory, that means that exists a proof that every given sentence that holds for one sort holds also for the other sort.
Because categories are theories without identity isomorphism is the only way that we have to distinguish sorts (objects) into the theory (category).
Conjugation instead is a different relation, it says that two given objects can be seen as the same via a suitable invertible interpretation of theories: that means that up to rename sorts and relations every sentence that holds for one sort also holds for the corresponding sort.
Conjugation of two sorts says that we can reinterpret each sort in the other without changing the logic of the theory.
So while the first relation says something just about the theory the second one is a relation the deals with the theory and an interpretation of the theory in itself. They're both meta-relations, meaning that they say something about theories, but they says different things at logical level.
I hope this answer could help you.


text:
Q: Clustered elasticsearch setup (two master nodes) We are currently setting up an environment with two elasticsearch instances (clustered servers).
Since it's clustered, we need to make sure that data (indexes) are synched between the two instances.
We do not have the possibility to setup an additional (3rd) server/instance to act as the 'master'.
Therefore we have configured both instances as master and data nodes. So instance 1 is master & node and instance 2 is also master & node.
The synchronization works fine when both instances are up and running. But when one instance is down, the other instance keeps trying to connect with the instance that is down, which obviously fails because the instance is down. Therefore the node that is up is also not functioning anymore, because it can not connect to his 'master' node (which is the node that is down), even though the instance itself is also a 'master'.
The following errors are logged in this case:

*

*org.elasticsearch.cluster.block.ClusterBlockException: blocked by: [SERVICE_UNAVAILABLE/2/no master];

*org.elasticsearch.transport.ConnectTransportException: [xxxxx-xxxxx-2][xx.xx.xx.xx:9300] connect_exception

*Caused by: io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: xx.xx.xx.xx/xx.xx.xx.xx:9300

In short: two elasticsearch master instances in a clustered setup. When one is down, the other one does not function because it can not connect to the 'master' instance.
Desired result: If one of the master instances is down, the other should continue functioning (without throwing errors).
Any recommendations on how to solve this, without having to setup an additional server that is the 'master' and the other 2 the 'slaves'?
Thanks

A: To be able to vote, masters must be a minimum of 2.
That's why you must have a minimum of 3 master nodes if you want your cluster to resist to the loss of one node.
You can just add a specialized small master node by settings all other roles to false.
This node can have very few resources .
As describe in this post :
https://discuss.elastic.co/t/master-node-resource-requirement/84609
Dedicated master nodes need persistent storage, but not a lot of it. 1-2 CPU cores and 2-4GB RAM is often sufficient for smaller deployments. As dedicated master nodes do not store data you can also set the heap to a higher percentage (75%-80%) of total RAM that is recommended for data nodes.

A: You should not have 2 master eligible nodes in the cluster as its a very risky thing and can lead to split brain issue.
Master nodes doesn't require much resources, but as you have just two data nodes, you can still live without having a dedicated master nodes(but please aware that it has downsides) to just save the cost.
So simply, remove master role from another node and you should be good to go.

A: If there are no options to increase 1 more node then you can set
minimum_master_nodes=1 . This will let your es cluster up even if 1 node is up. But it may lead to split brain issue as we restricted only 1 node to be visible to form cluster.
In that scenario you have to restart the cluster to resolve split brain.
I would suggest you to upgrade to elasticsearch 7.0 or above. There you can live with two nodes each master eligible and split brain issue will not come.


text:
Q: semantic web services search engine I am searching for a set of semantic web services to test my work.
Does anybody know a public web services search engine, or any web services repository in which web services are semantically described (e.g., using OWL-S)?

A: Check out these resources
OWL for Services (OWL-S) - Examples
Collection of OWL-S Web Services


text:
Q: How do I print out the cookies that Mechanized has stored? I'm using mechanize to login into a website and then retrieve a page. I'm running into some problems and I suspect this is due to some values in the cookies. When Mechanize logs into a website I assume it stores the cookies.
How do I print out all the data stored in the cookies by Mechanize?

A: The agent has a cookies methods.
agent = Mechanize.new
page = agent.get("http://www.google.com/")
agent.cookies
agent.cookies.to_s

The cookies return is a Mechanize::Cookies object


text:
Q: Permissions problems reading users from azure AD with User.ReadBasic.All? I am trying to get azure users and i am getting permissions error, even if instead of Users i place ME, why ? shouldnt it be something that i had no need to have admin consent? Any help is appreciated!!

            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                .Create("****")
                .WithTenantId("****")
                .WithClientSecret("***")
                .Build();

            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
            // Create a new instance of GraphServiceClient with the authentication provider.
            GraphServiceClient graphClient = new GraphServiceClient(authProvider);

            var user = await graphClient.Users
                .Request()
                .WithScopes(graphScopes)
                .Select(u => new {
                    u.DisplayName
                })
                .GetAsync();
    ```

A: For this problem it seems you do not have permission to get the users. You can refer to the document of the graph api, you need the permission shown as below:

So please go to the application which registered in your azure ad, and click "API permissions", then add the permission into it.

After add the permissions, please do not forget click "Grand admin consent for xxx".
For the question why it still failed when you change the Users to me. You use client credential flow to do authentication to request the graph api, you just provide the information of clientId, tenantId and clientSecret. So it doesn't contain a user(or yourself) information. So you can't use .Me. If you want to use .Me, you can use password grant flow. It contains the user information, so system know who is .Me.
================================Update==============================
If you want to use delegated permission(such as User.ReadBasic.All), you can't use client_credential. Now your code use client_credential flow, the access token doesn't contain user identity. I provide a sample of username/password flow(and use delegated permission User.ReadBasic.All) below for your referencef:
In the "API permissions" tab of the registered app, I just add one permission User.ReadBasic.All.

The code shown as below:
using Microsoft.Graph;
using Microsoft.Graph.Auth;
using Microsoft.Identity.Client;
using System;
using System.Security;

namespace ConsoleApp3
{
    class Program
    {
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
            .Create("<clientId>")
            .WithTenantId("<tenantId>")
            .Build();

            string[] scopes = new string[] { "https://graph.microsoft.com/.default" };

            UsernamePasswordProvider authProvider = new UsernamePasswordProvider(publicClientApplication, scopes);

            GraphServiceClient graphClient = new GraphServiceClient(authProvider);

            var str = "<your password>";
            var password = new SecureString();
            foreach (char c in str) password.AppendChar(c);

            var users = await graphClient.Users.Request().WithUsernamePassword("<your account/email>", password).GetAsync();

            Console.WriteLine(users.Count);
        }
    }
}

And before run the code, you need to do "consent to use the application" once. You need to browse the url as this: https://login.microsoftonline.com/<tenantId>/oauth2/v2.0/authorize?client_id=<clientId>&response_type=code&redirect_uri=<redirectUri>&response_mode=query&scope=openid https://graph.microsoft.com/.default&state=12345 in your browser and the page will show as:

Click "Accept", then you can run the code to get user list success.


text:
Q: GROUP BY and WHERE clause in one query I am trying to get all rows where the states are greater than 1.
My table:
user_id|state
--------------
1000000|Active
1000000|Created
1000001|Active
1000000|Deleted
1000002|Active
1000001|Created
1000003|Active

My query:
select user_id, count(state) from docs group by user_id order by count(state) desc;

Result is:
user_id | count(state)
1000000 |      3
1000001 |      2
1000002 |      1
1000003 |      1

But I need print only values where is count(state) greater than 1
I am trying this, but it doesn't work:
select user_id, count(state) from docs where count(state) > 1 group by user_id;

My example:
http://www.sqlfiddle.com/#!9/b2716b/2

A: HAVING can filter unnecessary rows for you when there is GROUP BY applied. Try this following query for your purpose. WHERE clause is used for filtering rows and it applies on each and every row, while HAVING clause is used to filter groups in SQL
SELECT user_id,
COUNT(state)
FROM docs
GROUP BY user_id
HAVING  COUNT(state) > 1
ORDER BY COUNT(state) DESC;

A: You probably need to use the "having" clause.
select user_id, count(state)
from docs
group by user_id
having count(state) > 1
order by count(state) desc;

A: Going by your code;
select user_id, count(state) from docs group by user_id order by count(state) desc;
it will be easy and simple to modify.

Try this:
select user_id, count(state) from docs group by user_id where count(state) > 1 order by count(state) desc;

This should work fine and perfect. Your feedback would help me make more research further. Good luck!!!

A: You can also use the concept of Sub-query. You can read more about sub-query here.
Here in the below query, the inner query will fetch the count of state and their corresponding user_id, whereas the outer query will filter those results to display results where count >=1.
 SELECT * FROM (select user_id, count(state) as count from docs group by user_id) WHERE count>1 order by count desc;

A:
select user_id,state from docs where state =
(select state from(select state,count(state) 'count' from docs group by state having count(state)!=1)as temp where temp.state=Docs.state )

A: select *
from (select user_id, count(state) as [count]
      from docs
      group by user_id)
where count > 1
order by count(state) desc;

Should do the trick


text:
Q: Select row in custom list view and add action bar item I have an android application with a custom list view. I would like to realize the following situation...
I have in my fragment view an OnItemLongClickListener method:
CustomListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            Log.e("-->", "HELLO WORLD");
            return false;
        }
    });

If a long click will be detected, I would like to show the options to select multiple rows, - little bit like on the following screenshot:

And I also would like to make an ActionBar Item visible, which is hidden the whole time.
How can I implement this?

A: for doing work with check book you have to use a flag in array list which by default should be true for every list item when you long pressed you will set falg false for all the list item and call setdatanotifychanged method of adapter and when you select each item then you should set flag value true.
Action Bar – Hide and Show
To hide Action Bar, invoke hide() method using getSupportActionBar( ) [getActionBar( ) in case of minSDKVersion is 11 or higher] as shown below:
getSupportActionBar().hide();
// If your minSdkVersion is 11 or higher, instead use:
//getActionBar().hide();

To show Action Bar, invoke show() method using getSupportActionBar( ) [getActionBar( ) in case of minSDKVersion is 11 or higher] as shown below:
getSupportActionBar().show();
// If your minSdkVersion is 11 or higher, instead use:
//getActionBar().show();


text:
Q: Big Data Xml file (file size over 20GB) convert to Json File I have an XML file. I want to convert it to JSON with C#. However, the XML file is over 20 GB.
I have tried to read XML with XmlReader, then append every node to a JSON file. I wrote the following code:
var path = @"c:\result.json";
TextWriter tw = new StreamWriter(path, true, Encoding.UTF8);
tw.Write("{\"A\":");

using (XmlTextReader xmlTextReader = new XmlTextReader("c:\\muslum.xml"))
{
    while (xmlTextReader.Read())
    {
        if (xmlTextReader.Name == "A")
        {
            var xmlDoc = new XmlDocument();
            var v = xmlTextReader.ReadInnerXml();

            string json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xmlDoc, Newtonsoft.Json.Formatting.None, true);

            tw.Write(json);
        }
    }
}

tw.Write("}");
tw.Close();

This code not working. I am getting error while converting json. Is there any best way to perform the conversion?

A: I would do it the following way

*

*generate classes out of xsd schema using xsd.exe

*open file and read top level ( i e your document level ) tags one by one  (with XmlTextReader or XmlReader)

*serialize each tag into object using generated classes

*deserialize resulting object to json and save to whatever

*consider saving in batches of 1000-2000 tags

*you are right about serialize/deserialize being slow. still doing work in several threads, preferably using TPL will give you good speed. Also consider using json.net serializer, it is really a lot faster than standard ones ( it is standard for web.api though)
I can put some code snippets in the morning if you need them.
We are processing big ( 1-10gigs) files this manner in order to save data to sql server database.


text:
Q: npm build:aot --prod Duplicate source map file for dist/main-xxx.css I'm using webpack and Angular 6. Since yesterday and without apparent changes in css files, I did not compile the npm run build: aot: prod for a problem in the creation of main-xxx.css, the bugsnag informs me that it is trying to rewrite a file that already exists and does not complete the build successfully.
It's funny that on the server deploy if it compiles correctly, but on my computer it does not, I get the following error:
Conflict (409) - duplicate source map file for dist / main-f751fc480956a7a013da.css. There was a moment this morning when he did complete the build but most times not. I found a solution to configure the override: true in BugsnagSourceMapUploaderPlugin, but I do not like it since before this error had never been reproduced.
It seems that it tries to compile the css (created with sass) twice.
If someone encountered the same problem or knows how to debug to find the fault, it will help me a lot.
Thank you very much in advance.
This is my webpack-prod configuration

/**
 * @author: @AngularClass
 */
const helpers = require('./helpers');
const buildUtils = require('./build-utils');

/**
 * Used to merge webpack configs
 */
const webpackMerge = require('webpack-merge');
/**
 * The settings that are common to prod and dev
 */
const commonConfig = require('./webpack.common.js');

/**
 * Webpack Plugins
 */
const SourceMapDevToolPlugin = require('webpack/lib/SourceMapDevToolPlugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HashedModuleIdsPlugin = require('webpack/lib/HashedModuleIdsPlugin');
const PurifyPlugin = require('@angular-devkit/build-optimizer').PurifyPlugin;
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const {BugsnagSourceMapUploaderPlugin} = require('webpack-bugsnag-plugins');

function getUglifyOptions(supportES2015) {
  const uglifyCompressOptions = {
    pure_getters: true, /* buildOptimizer */
    // PURE comments work best with 3 passes.
    // See https://github.com/webpack/webpack/issues/2899#issuecomment-317425926.
    passes: 3         /* buildOptimizer */
  };

  return {
    ecma: supportES2015 ? 6 : 5,
    warnings: false,    // TODO verbose based on option?
    ie8: false,
    mangle: true,
    compress: uglifyCompressOptions,
    output: {
      ascii_only: true,
      comments: false
    }
  };
}

module.exports = function (env) {
  const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
  const supportES2015 = buildUtils.supportES2015(buildUtils.DEFAULT_METADATA.tsConfigPath);
  const METADATA = Object.assign({}, buildUtils.DEFAULT_METADATA, {
    host: process.env.HOST || 'localhost',
    port: process.env.PORT || 8080,
    ENV: ENV,
    HMR: false
  });

  // set environment suffix so these environments are loaded.
  //METADATA.envFileSuffix = METADATA.E2E ? 'e2e.prod' : 'prod';
  METADATA.envFileSuffix = METADATA.envFileSuffix || 'pre';

  return webpackMerge(commonConfig({env: ENV, metadata: METADATA}), {

    /**
     * Options affecting the output of the compilation.
     *
     * See: http://webpack.github.io/docs/configuration.html#output
     */
    output: {

      /**
       * The output directory as absolute path (required).
       *
       * See: http://webpack.github.io/docs/configuration.html#output-path
       */
      path: helpers.root('dist'),
      /**
       * Specifies the name of each output file on disk.
       * IMPORTANT: You must not specify an absolute path here!
       *
       * See: http://webpack.github.io/docs/configuration.html#output-filename
       */
      filename: '[name].[chunkhash].bundle.js',

      /**
       * The filename of the SourceMaps for the JavaScript files.
       * They are inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
       */
      sourceMapFilename: '[file].map',

      /**
       * The filename of non-entry chunks as relative path
       * inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
       */
      chunkFilename: '[name].[chunkhash].chunk.js'
    },

    module: {

      rules: [
        /**
         * Extract CSS files from .src/styles directory to external CSS file
         */
        {
          test: /\.css$/,
          use: [MiniCssExtractPlugin.loader, 'css-loader'],
          include: [helpers.root('src', 'styles')]
        },

        /**
         * Extract and compile SCSS files from .src/styles directory to external CSS file
         */
        {
          test: /\.scss$/,
          use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
          include: [helpers.root('src', 'styles')]
        }
      ]
    },

    /**
     * Add additional plugins to the compiler.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: [

      new SourceMapDevToolPlugin({
        filename: '[file].map[query]',
        moduleFilenameTemplate: '[resource-path]',
        fallbackModuleFilenameTemplate: '[resource-path]?[hash]',
        sourceRoot: 'webpack:///'
      }),
      new MiniCssExtractPlugin({ filename: '[name]-[hash].css', chunkFilename: '[name]-[chunkhash].css' }),
      new PurifyPlugin(), /* buildOptimizer */
      new HashedModuleIdsPlugin(),
      /**
       * Plugin: UglifyJsPlugin
       * Description: Minimize all JavaScript output of chunks.
       * Loaders are switched into minimizing mode.
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
       *
       * NOTE: To debug prod builds uncomment //debug lines and comment //prod lines
       */
      new UglifyJsPlugin({
        sourceMap: false,
        parallel: true,
        uglifyOptions: getUglifyOptions(supportES2015)
      }),
      new BugsnagSourceMapUploaderPlugin({
        apiKey: METADATA.bugsnagKey,
        publicPath: 'dist'
      })

    ],

    /**
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      global: true,
      crypto: 'empty',
      process: false,
      module: false,
      clearImmediate: false,
      setImmediate: false
    }
  });
};

A: Yes, Xavier is right. I had the same issue. It was under webpack.prod.js file. By default overwrite is not enabled. I searched with appVersion in the project.
new BugsnagSourceMapUploaderPlugin({
  apiKey: 'YOUR_API_KEY',
  appVersion: '4.0.0.038',
  overwrite: true
})

Details can be found here in the BugSnag GitHub page.


text:
Q: disabling file_browser_callback on insert/edit video on tinymce 4 I want to disable/hide browse button for source and other parameters in insert/edit video screen. At present I son't have back end implementation to provide the list of videos but I want this option available for insert/edit image. I am using file_browser_callback in tiny init but it looks to me that a same file_browser_callback is used to handle the browse for all the screen. Can someone suggest me a way to hide the browse for "insert/edit" video plugins but allow in "insert/edit image"?
Please check Fiddle

A: There is indeed one file_browser_callback but within the callback you can target different types. In my implementation I've done the following:
   file_browser_callback: function(field_name, url, type, win) {
        if (type == 'file') {
            diaTitle = 'Insert link';
            browser = '/linkmanager/index.php'+'?field_id='+field_name;
        } else if (type == 'image') {
            diaTitle = 'Insert image';
            browser = '/filemanager/dialog.php?type=1&field_id='+field_name;
        }
        tinymce.activeEditor.windowManager.open({
            title: diaTitle,
            url: browser,
            width: 860,
            height: 600
        },{
            oninsert: function(url) {
                win.document.getElementById(field_name).value = url;
            }
        });
    }

Hope this can help you!

A: TinyMCE has provided a way to do this by using file_picker_types. You will need to add this to the tinymce.init, maybe right above your "file_browser_callback:"
file_picker_types: 'image',

https://www.tinymce.com/docs/configure/file-image-upload/#file_picker_types


text:
Q: How to execute cordova callback (success or error) twice in java I have the following issue, I receive from cordova 2 callbacks (success and error), and i need to trigger the success callback many times.
The problem is that cordova doesn't seems to allow execute a callback twice, it's only executed once.
//Will be executed once, whatever i do, only 1 time
callbacks.sendPluginResult(new PluginResult(PluginResult.Status.OK, contenedor.toString()));
// It doesn't trigger anymore of anyway :(
 callbacks.success(contenedor.toString());
 callbacks.sendPluginResult(new PluginResult(PluginResult.Status.OK, contenedor.toString()));
 callbacks.success(contenedor.toString());

For some reason i need to send a string many times every x time (i want to achieve this executing the succcess callback) and i need to repeat the callback :(
I tried this and this without success, the success callbacks stills firing just once ! Is there a way to execute a callback easily twice ?
SOLVED (facepalm)
If someone have this problem , quick solution :
PluginResult resulta = new PluginResult(PluginResult.Status.OK, "first response");
resulta.setKeepCallback(true);
callbacks.sendPluginResult(resulta);

PluginResult resultb = new PluginResult(PluginResult.Status.OK, "2nd response");
resultb.setKeepCallback(true);
callbacks.sendPluginResult(resultb);

remember that if is an async call we need to return NO_RESULT first
PluginResult pluginResult = new  PluginResult(PluginResult.Status.NO_RESULT);
        pluginResult.setKeepCallback(true); // Keep callback

        return true; // in execute method

A: Today I jumped into the same issue and then came across this post, so I thought of answering it again for better understanding.
So if you want to receive the callback twice or more then Don't use the success() method I repeat Don't use the success() method. This is where I was stuck. So only use the following
 PluginResult result = new PluginResult(PluginResult.Status.OK, <Your Result>);
 result.setKeepCallback(true);
 callback.sendPluginResult(result);


text:
Q: ssh + screen : how to ? I am trying to launch a software through ssh :
I can do :
ssh -t user@xx.xx.xx.xx
screen -S datanode -d -m ~/hadoop/bin/hdfs datanode

But
ssh -t user@xx.xx.xx.xx screen -S datanode -d -m ~/hadoop/bin/hdfs datanode

Doesn't work
I tried several options with quotes :
ssh -t user@xx.xx.xx.xx screen '-S datanode -d -m ~/hadoop/bin/hdfs datanode'

or
ssh -t user@xx.xx.xx.xx screen -S datanode -d -m '~/hadoop/bin/hdfs datanode'

or
ssh -t user@xx.xx.xx.xx screen ' -S datanode -d -m ~/hadoop/bin/hdfs datanode'

but I can't find the correct one :-(

A: Its better to group the options together
ssh -t username@host "screen -dmS 'NAMEofSCREEN' command"

You can then reattach with
screen -r NAMEofSCREEN

Just keep in mind that this won't be a re-attachable screen if command exits. For example:
ssh -t username@host "screen -dmS 'NAMEofSCREEN' echo | wall"

Will give you the wall message ...
Broadcast message from user@host (pts/15) (Tue Jan 16 12:04:07 2018):

.. but the screen will immediately close after the command ran successful

A: I see two (potential) problems with your incantation of
ssh -t remote screen -S datanode -d -m ~/hadoop/bin/hdfs datanode

*

*The client/local shell (the one executing ssh) is the one expanding ~ and replacing with the value of $HOME, which may be different from that of the remote server.  Suggest you use either a relative path (e.g. ./hadoop/bin/hdfs) or a fully-qualified path or quote the remote command with single quotes (e.g. '~/hadoop/bin/hdfs datanode') to prevent expansion on the client.

*Because the screen command is starting a detached instance, but is still a child process of the shell started by ssh, it is terminated when the remote shell exits.

Moreover, since screen creates it's own tty, you don't need the -t option to ssh.
Try instead using -f to tell ssh to go into the background just before command execution.  i.e.:
ssh -f remote screen -S datanode -d -m ./hadoop/bin/hdfs datanode

Equally valid alternative using nohup:
ssh remote nohup screen -S datanode -d -m ./hadoop/bin/hdfs datanode


text:
Q: How can I have a smaller indentation in description with IEEEtran? I'd like to use a description environment together with the IEEEtran document class.  One of the labels is actually quite long (three words) so I need to use \IEEEsetlabelwidth to avoid having the text and the label overlap.  As apparently it determines the indentation of the whole text and not just the text on the first line, I get a skinny column that spans over a large number of lines.
\begin{description}[\IEEEsetlabelwidth{Very long label}\IEEEusemathlabelsep]
  \item[Very long label] this text is spanning over multiple lines.  Since the label was very long and the label determined the indent of the text it really covers a large number of lines.
\end{description}

The result is something like
Very long label   this text is spanning over
                  multiple lines. Since the
                  label was very long and
                  the label determined the
                  indent of the text it
                  really covers a large
                  number of lines.

While I would like something like
Very long label   this text is spanning over
    multiple lines. Since the label was very
    long and the label determined the indent
    of the text it really covers a large
    number of lines.

I don't have specific requirements for the body of the text, but it'd be nice if it was consistent across the several descriptions of the document (it is not the case at the moment).  I have tried to read the documentation of IEEEtran, but I'm quite confused.

A: You can use the LaTeXdescription environment; compare the result of description and LaTeXdescription:
\documentclass{IEEEtran}

\begin{document}

\begin{description}[\IEEEsetlabelwidth{Very long label}\IEEEusemathlabelsep]
  \item[Very long label] this text is spanning over multiple lines.  Since the label was very long and the label determined the indent of the text it really covers a large number of lines.
\end{description}

\begin{LaTeXdescription}%[\IEEEsetlabelwidth{Very long label}\IEEEusemathlabelsep]
  \item[Very long label] this text is spanning over multiple lines.  Since the label was very long and the label determined the indent of the text it really covers a large number of lines.
\end{LaTeXdescription}

\end{document}


text:
Q: NodeJS - Cannot set headers after they are sent - Multiple Calls I'm trying to write an app that find a city in a MongoDB collection and uses the latitude and longitude it returns to find all zip codes within a certain distance.  It seems to work, but the problem is that I'm getting an error that I can't set headers after they've already been sent.  However, I've separated the to routes into different requests I don't understand why I'm still getting this error.  What is the best way to make multiple calls to the API?
Here is my router in Node/Express:
// route to get city
app.get('/cities/:zip', function(req, res) {
    // use mongoose to get the city in the database
    console.log(req.params.zip);
    var query = City.find({"zip" : req.params.zip});
    query.exec(function(err, city) {
        if (err)
            res.send(err);
        res.json(city);
    });
});

// route to find cities within 50 miles
app.get('/matches/:latMin/:latMax/:lonMin/:lonMax', function(req, res) {
    console.log(req.params.latMin + req.params.latMax + req.params.lonMin + req.params.lonMax);
    var matches = City.find({latitude: {$gt: req.param.latMin, $lt:req.params.latMax }, longitude : {$gt :req.param.lonMin, $lt : req.param.lonMax}});
    matches.exec(function(err, match){
        if(err)
            res.send(err);
        console.log(match);
        res.json(match);
    });
});

app.get('*', function(req, res) {
    res.sendfile('./public/views/index.html'); // load our public/index.html file
});

Here is my Angular Controller
$scope.update = function (zip) {
    City.get({zip : zip}).success(function(response){
        $scope.weather = response
    }).then(function(response){
        $scope.weather = response.data;
    })

    if(zip.length = 5){
        $http.jsonp('http://api.openweathermap.org/data/2.5/weather?zip='+ zip +',us&callback=JSON_CALLBACK&units=imperial').success(function(data){
            $scope.data=data;
        });

        var box = getBoundingBox([$scope.weather[0].latitude, $scope.weather[0].longitude], 50);
        City.matches(box[1], box[3], box[0], box[2]).success(function(response){
            $scope.matches = response
        }).then(function(response){
            $scope.matches = response.data;
            console.log($scope.matches);
        })
    }

A: res.send does not return; the call continues to res.json. And please use braces. Please. Maybe they don't look cool or whatever. Just use them.
if (err) { handleError(res, err); return; }
res.status(200).json(city);

Further down, keeping things DRY:
function handleError(res, err) {
  res.status(500).json(err);
}


text:
Q: How to make a oauth authentication from salesforce mobile app? Web Tabs are not showing Allow Access? Pop up (iFrame Issue) I have done a Device Flow Oauth using a ESP8266. Now i want to have the salesforce mobile app to authenticate my IoT device into salesforce.
When the IoT device generates a OTP(User_Code), I open login.salesforce.com/setup/connect and put in my OTP. Then the Allow Access Page opens up which I created using a connected app. Then I click on Allow to authenticate the device.
I want to do the same login process in salesforce mobile app.
So i created a web tab with hyperlink to login.salesforce.com/setup/connect  but it is facing iFrame issue

A: Your issue is more likely that from a mobile app, you'll need to use myDomain.com/setup/connect instead of login.salesforce.com/setup/connect. Knowing more about how you have your OAuth2 configured and whether Salesforce is the idp would allow a more thorough diagnosis of your issue. Generally speaking though, mobile apps can only login to MyDomain URLs.


text:
Q: Google login api error I am implementing google native login in my ionic app using this plugin. In google console I have a previous project xyz . I created a client ID using web application as application type (Authorized JavaScript origins and Authorized redirect URIs fields left blank).
I am able to login and view user data.
Now I followed the same approach with another project using different google account. This time I am getting an error code 10 in response.
P.S. Google+ API is enabled in both cases.
Here is my code where I am putting my client id for reference
    window.plugins.googleplus.login(
{
  'scopes': 'email',
  'webClientId': 'XXXX.apps.googleusercontent.com',
  'offline': true,
},
function (obj) {
 alert(obj.email + "+++" + obj.displayName + "+++" + obj.userId); // do something useful instead of alerting
},
function (msg) {
  alert('error: ' + msg);
})

P.S. Google+ API is enabled in both cases.

A: Same problem is stated here error code 10
Make sure that your webClientId is correct
As described link above

You need to pass in a Web Application type client ID to the login
  function

A: check following things.
1. The problem occurs if you created sha1 fingerprint with different  system and building your app in different system.
make sure you are building the app in the same system which you generated sha1 fingerprint to add in google developer console.
2. you no need to add webClientId id but you have to use webClientId while installing the plugin.
like
cordova plugin add https://github.com/EddyVerbruggen/cordova-plugin-googleplus --save --variable REVERSED_CLIENT_ID=myreversedclientid


text:
Q: insert data to database using enter button i want to add new comment to my database by using input text, but i don't want to use form or onclick. here's is my input text structure
<input type="text" class="comment_input" ng-model="comment" ng-model-options="{updateOn : 'change blur'}" placeholder="To enter" />

When i try to using bind, it show my comment when i push enter button, but i want to insert it to my database API.. Here's is my function for inserting the data.
    $scope.insertData=function(){
  console.log($scope.comment);
  console.log($scope.lang_code);
  console.log($scope.user_id);
  console.log($scope.product_id);
  var dataPromise = Data.setData("API_URL","user_id="+$scope.user_id+"&product_id="+$scope.product_id+"&comment="+$scope.comment+"&lang="+$scope.lang_code);
    dataPromise.then(function(greeting) {
        console.log(greeting);
        if (greeting.data.result == true) {
          $scope.requestProductDetail(1,5,1);
          $timeout(function () {
            window.scrollTo(0,document.body.scrollHeight);
          }, 0, false);
        }
    }, function(reason) {
    }, function(update) {
    });
}}]);

anyone?
ah, and how to refresh this page after i doing something? *insertdata / onclick button

A: You can use this directive to trigger enter key event
app.directive('enterKeyPressed', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                scope.$apply(function (){
                    scope.$eval(attrs.enterKeyPressed);
                });
                event.preventDefault();
            }
        });
    };
});

Use it from html as below
<input type="text" class="comment_input" ng-model="comment" enter-key-pressed="insertData()" placeholder="To enter" />

If you are using ng-repeat to display comments, just push the new comment into comments array
To reload the page, you can use the reload method of the $route service. Inject $window in your controller and then call $window.location.reload() at the end of insertData() function
Hope it helps


text:
Q: multiple pivot on same column in tsql How can I have pivot define on same column in tsql?
for example:
 SELECT * FROM (
 SELECT CAST(start_time AS DATE) AS [Date],
 DATEPART(hour,start_time) AS [Hour],
 Count(is_sale)AS  [Sales Count]
 ,Count(is_not_sale)AS  [No Sales Count]
 FROM  prov_sales WITH(NOLOCK)
 GROUP BY CAST(start_time AS DATE), DATEPART(hour,start_time)) AS HourlySalesData

 PIVOT( SUM([Sales Count]) FOR [Hour] IN ([0], [1], [2], [3], [4], [5], [6], [7],
     [8], [9], [10],[11], [12], [13], [14], [15], [16],
     [17], [18], [19], [20], [21], [22], [23])) AS DatePivot1

 PIVOT( SUM([No Sales Count]) FOR [Hour] IN ([0], [1], [2], [3], [4], [5], [6], [7],
     [8], [9], [10],[11], [12], [13], [14], [15], [16],
     [17], [18], [19], [20], [21], [22], [23])) AS DatePivot2

My above tsql is not working as I am getting error for the hour column which has repeated values from [1] to [23].

A: As PIVOT creates Column names from the IN list, you cannot define same column like [1] twice. Although the following solution is not a standard one, but it may server your purpose-
SELECT * FROM (
SELECT CAST(start_time AS DATE) AS [Date],
--Created the hour column twice for Pivoting twice
'Sales_' + CAST(DATEPART(hour,start_time) AS VARCHAR) AS [Hour_Sales],
'NoSales_' + CAST(DATEPART(hour,start_time) AS VARCHAR) AS [Hour_NoSales],
Count(is_sale)AS  [Sales Count]
,Count(is_not_sale)AS  [No Sales Count]
FROM  prov_sales WITH(NOLOCK)
GROUP BY CAST(start_time AS DATE), DATEPART(hour,start_time)) AS HourlySalesData

PIVOT( SUM([Sales Count]) FOR [Hour_Sales] IN ([Sales_0], [Sales_1], [Sales_2], [Sales_3], [Sales_4], [Sales_5], [Sales_6], [Sales_7],
     [Sales_8], [Sales_9], [Sales_10],[Sales_11], [Sales_12], [Sales_13], [Sales_14], [Sales_15], [Sales_16],
     [Sales_17], [Sales_18], [Sales_19], [Sales_20], [Sales_21], [Sales_22], [Sales_23])) AS DatePivot1

PIVOT( SUM([No Sales Count]) FOR [Hour_NoSales] IN ([NoSales_0], [NoSales_1], [NoSales_2], [NoSales_3], [NoSales_4], [NoSales_5], [NoSales_6], [NoSales_7],
     [NoSales_8], [NoSales_9], [NoSales_10],[NoSales_11], [NoSales_12], [NoSales_13], [NoSales_14], [NoSales_15], [NoSales_16],
     [NoSales_17], [NoSales_18], [NoSales_19], [NoSales_20], [NoSales_21], [NoSales_22], [NoSales_23])) AS DatePivot2


text:
Q: canvas would not draw in java there seem to be something that i miss. or that i did not fully understand how canvas work in java. the problem is that canvas did not create anything. in the code below i know that canvas are working and showing because the background color have change into light blue but it should have also add a small red box inside that canvas. My goal for now is to have the canvas to show that small box.
// frame
    private static JFrame frame;
private static BufferStrategy bs;
private static Graphics g;
private static JPanel jp;
private static Canvas canvas;
private static int width = 1000;
private static int height = 1000;

public static void main(String[] args)  {
    // TODO Auto-generated method stub

    locX.clear();
    locY.clear();

    loadData();

    createFrame();

}

public static void createFrame() {
    frame = new JFrame("Title");
    frame.setSize(width, height);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(true);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    canvas = new Canvas();
    canvas.setPreferredSize(new Dimension(width,height));
    canvas.setMaximumSize(new Dimension(width,height));
    canvas.setMinimumSize(new Dimension(width,height));
    canvas.setBackground(Color.cyan);
    //jp.setSize(new Dimension(width,height));

    //frame.add(jp);
    frame.add(canvas);
    frame.pack();

    bs = canvas.getBufferStrategy();
    if(bs == null) {
        canvas.createBufferStrategy(1);
        return;
    }

    g =  bs.getDrawGraphics();
    // clear screen
    //g.clearRect(0, 0, width, height);

    g.setColor(Color.red);
    g.fillRect(400, 50, 100, 100);
    bs.show();
    g.dispose();
}


text:
Q: How to update/delete sqlite table row knowing its index So I want to be able to update only one row knowing the index of it for example the second row or third row but all tutorials I find use conditions that use set values from the columns, is there no way to use the Index?
One answer I found was to add an ID column that just holds the number of the row starting from 1 and updates with each new row, but that quickly went downhill when I started deleting rows because the IDs stay the same for example if I had IDs like {1, 2, 3, 4, 5} and 3 is deleted the column would remain as {1, 2, 4, 5} which would ruin other operations. Any tips?

A: have a look at this:
CREATE TABLE if NOT EXISTS table(
    custom_id INTEGER NOT NULL,
    name TEXT NOT NULL);

Now insert some values into it and run SELECT rowid,* FROM table;
rowid  custom_id     name
1      1              a
2      2              b
3      3              c
4      4              d
5      5              e

Delete some rows:
DELETE FROM table WHERE rowid = 3;
DELETE FROM table WHERE rowid = 4;
SELECT rowid,* FROM table;
rowid  custom_id     name
1      1              a
2      2              b
5      5              e

Run special command VACUUM;
SELECT rowid, * FROM table;
rowid  custom_id     name
1      1              a
2      2              b
3      5              e

Now your rowid, which could act as an index for you, has been updated.
Let me know if that helped :)


text:
Q: Use VBA to search for a list a values in column A, and when found update the cell in column B Using VBA, I am trying to search for each value in column A of sheet 1, and match it with column A of sheet 2. If a value is found in sheet 2, update column B to "Yes"
Sheet 1

Sheet 2

So far I have:
Sub UpdateStatus()

  Dim list() As Variant
  Dim item As Integer

  'Assign range to a variable
  list = Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row)

  'Loop Through Rows
  For item = 1 To UBound(list)
    'this is where I am stuck
  Next item

End Sub

Sheet 2 should look like this afterwards:

A: Why loop if you can use Excel's engine?
Solution using Excel formulas
Sub Update_Status()

    Dim Formula    As String
    Dim searchRng  As Range
    Dim valueRng   As Range
    Dim statusRng  As Range
    Dim ws1        As Worksheet
    Dim ws2        As Worksheet

    Set ws1 = Worksheets("Sheet1")
    Set ws2 = Worksheets("Sheet2")

    Set valueRng = ws1.Range("A2:A" & LastRow("A", ws1)) ' A2, since you have header
    Set searchRng = ws2.Range("A1:A" & LastRow("A", ws2))
    Set statusRng = valueRng.Offset(0, 1)

    ' =IF(COUNTIFS(Sheet2!$A$2:$A$4,Sheet1!A2),"Yes","No")
    Formula = "=IF(COUNTIFS(" & _
        searchRng.Address(True, True) & "," & _
        valueRng.Cells(1, 1).Address(False, False) & _
        "),""Yes"",""No"")"

    statusRng.Formula = Formula

    ' In case calculation is turned off
    Application.Calculate

    ' If we prefer hardcoded values
    statusRng.Copy
    statusRng.PasteSpecial xlPasteValues
    Application.CutCopyMode = False ' Flush clipboard

End Sub

Private Function LastRow(Col As String, Ws As Worksheet) As Long
    LastRow = Ws.Range(Col & Rows.Count).End(xlUp).Row
End Function

A: This seems to work:
Sub UpdateStatus()

  Dim list() As Variant
  Dim item As Integer
  Dim FoundCell As Range
  Dim SearchValue As String
  Dim Sheet2 As Worksheet

  Set Sheet2 = Worksheets("Sheet2")

  'Assign range to a variable
  list = Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row)

  'Loop Through Rows
  For item = 1 To UBound(list)
    SearchValue = list(item, 1)
    Set FoundCell = Sheet2.Range("A2:A6").Find(What:=SearchValue)
      If Not FoundCell Is Nothing Then
        Sheet2.Range("B" & FoundCell.Row).Value = "Yes"
      Else
        MsgBox (SearchValue & " not found")
      End If
  Next item

End Sub