text:
Q: Does net charge on a conductor sit only on outer surfaces? Suppose we had a hollow conducting sphere with a net charge q on it. There is no charge in the cavity; the conductor itself has a charge q. The idea is that this net charge would reside on the 'surface', since the conductor has free charges otherwise to make the net field inside the meat of the conductor zero.

*

*My question is with regard to what 'surface' means. Does 'surface' refer to the interface between the conductor and air? If so, why isn't there charge residing on the inner surface of the hollow sphere? Has this something to do with uniqueness theorems?

*Related question:
If there is an external charge q outside an uncharged hollow conductor, why is there no induced charge on the inner 'surface'?

*Also related:
How is it that information of charge inside a cavity is known outside, but that outside is completely unknown inside? In a sense, aren't both regions of air the same and separated by the conductor only? Better put: when there is a charge inside the cavity, the inner surface charge distribution cancels the field in the conductor due to the cavity charge, and residual charge q sits uniformly on the outer surface, thus 'revealing' the presence of q to the outside. Why does the same not happen to a charge outside?

A: Initially, the meaning of the surface for your question is the upper boundary of the sphere which is equivalent to the sphere shell with a thickness infinitesimally small (mathematically, goes to zero). When it comes to the problem of why charges are not residing at the inner surface or in between the layers is, I need to explain how the charges are defined. Charges are defined as points so if you consider the cardinality of the surface of the sphere you will see that it is capable of accomodating uncountably infinite amount of charge. If you have any suspicion about injecting charges to the initially charged surface, a sphere shell can carry all the charges on only the (mathematical) surface. Also, the charges distribute themselves in a fashion that minimizes their potential energy, so if you consider Coulomb's law, for some distribution some charges can reside in the interior of the material but this condition doesn't minimize the potential energy. Applying the same condition for your second question, you will easily see that under an electric field charges distribute themselves (for the spherical shell) symmetrically, and using the minimization of potential energy there will be no charge interior of the material. In addition, if you put a charged sphere under an electric field the distribution for the final state requires a detailed analysis and calculation to carry and I think this may help you to understand the charge distribution from a more general perspective.


text:
Q: How To Create Comments Section for App I am looking to add a comments feature to my application.
Very high level, I was wondering what the best approach would be for layout purposes. My initial inclination is to create a view, which will represent each individual comment, and then use an adapter to add a view each time a new comment is added by an app user.
I wanted to hear of any thoughts on this process and whether or not there are other recommendations (i.e. libraries). Any advice is appreciated!

A: Check out

*

*Socialize SDK

*Disqus android SDK

or implement your own solution

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to put focus on second button on "org.eclipse.jface.dialogs.MessageDialog" I am trying to display a message dialog using the below code :
MessageDialog dialog = new MessageDialog(shell, "My Title", null,
             "Are you Sure?", MessageDialog.CONFIRM,
              new String[] { "Yes","No" }, 0);

The only problem is when the message dialog get displayed it shows the focus on the "Yes" button so if the user hits enter by default "Yes" gets pressed.
How can i put focus on the "No" button so that when ever user hits enter "No" gets pressed.
Please Note that  I don't want to change the order of Buttons. it should be first Yes and Than No.

A: Just set the last constructor argument to the index of the button you wish to be the default.
According to the Javadoc:
public MessageDialog(Shell parentShell,
                 String dialogTitle,
                 Image dialogTitleImage,
                 String dialogMessage,
                 int dialogImageType,
                 String[] dialogButtonLabels,
                 int defaultIndex)

defaultIndex - the index in the button label array of the default button


text:
Q: How can I best implement rollover and rollout events for multiple overlapping elements? Problem:
I'm working on a website where there is a "dial" that displays a number of tabs representing different divisions of an umbrella company:

At the moment I have everything prepared in HTML/CSS (positioning of each of the tabs). The inner circles are on a higher z-index as the tabs will need to animate outward when rolled over (I can achieve this part). The images for the tabs actually look like this:

Unfortunately it didn't occur to me until now that because of the mechanics of rollover and rollout in JavaScript, the boundaries for each item are square, meaning they overlap all over the place. For example, the centre circle's rollover area is actually this:

Which detracts some massive clickable/rolloverable areas on the inner circle of tabs. This effect then stacks with each of the tabs, rendering a standard approach non-viable.

Approach:
This is fine, what I plan to do now is measure the distance and angle of the mouse from the centre of the dial and use these values to determine the relevant tab, and work from there. I'll basically do the following:

*

*Collect angle (using atan2) and distance (using pythag).

*Apply my .click() to the entire dial, and work with these values from there.

*Use setInterval() to constantly check which item is rolled over and work with its animation from there.

Question:
I'm not exactly sure how to implement what I am doing (with JQuery). I know how to do all the Math stuff once I have the coordinates that I need, I'm just not confident in getting the actual coordinates (ensuring the same results cross-browser).
How can I best gather the coordinates of:

*

*The centre of my dial.

*The cursor (assuming that the cursor is within the same axis as the centre of my dial i.e. rolling over the centre of the dial will mean both sets of coordiantes are the same).

Note:
Taking the above, anything that achieves the same result (being able to have proper rollover detection for overlapping elements) is equally as helpful.

A: To get the center:
var dialPos = $( "#Dial" ).offset();
var center = {
     x: dialPos.left + $( "#Dial" ).width() / 2,
     y: dialPos.top + $( "#Dial" ).height() / 2
};

Cursor coordinates:
$( "#Dial" ).mousemove(function( e ) {
    var x = e.pageX - center.x;
    var y = e.pageY - center.y;
});

A: You can define an image map over the stack of layers. The map will define clicking/hovering regions, and the browser will take care of hit detection. With Adobe ImageReady, I have mapped a portion of your reference image so that "Reprise" and "Initiative" are hotspots:

ImageReady produced the following HTML:
<img src="images/Imagemap.png" width="488" height="488" border="0" alt="" usemap="#Imagemap_Map">
<map name="Imagemap_Map">
    <area shape="poly" alt="" coords="82,336, 138,303, 130,287, 123,265, 120,238, 125,206, 136,179, 158,152, 178,136, 209,122, 244,117, 244,55, 215,60, 184,67, 158,77, 122,101, 97,130, 73,169, 62,202, 59,224, 58,253, 61,281, 73,318" href="#">
    <area shape="poly" alt="" coords="73,72, 112,111, 138,89, 161,76, 187,66, 214,59, 244,57, 244,0, 205,4, 165,12, 118,34, 94,51" href="#">
</map>

(As you can see, mapping arbitrary regions can be exausting, and I dare to say virtually impossible without the use of a tool.)
You'd apply the map to a transparent image on top of everything. The final assembly can be imagined as the following stack:

The regions were highlighted just for reference. The real composition should be 100% transparent.
Good luck!


text:
Q: ASP.NET MVC - View with multiple models I am trying to generate such HTML
    <form action="/some/process" method="post">
        <input type="hidden" name="foo.a" value="aaa"/>
        <input type="hidden" name="bar.b" value="bbb"/>
        <input type="submit" />
    </form>

so it can be processed by this Action:
    public ActionResult Process(Foo foo, Bar bar)
    {
        ...
    }

Given the Action code
    public ActionResult Edit()
    {
        ViewData["foo"] = new Foo { A = "aaa" };
        ViewData["bar"] = new Bar { B = "bbb" };

        return View();
    }

what should I write in Edit.aspx view? I don't want to write names 'foo.a' and 'bar.b' manually.

A: String-indexed ViewData is bad. What you probably want to do is make a little wrapper class for your multi-variable view data and pass that to a strongly typed view. IE:
public class FooBarViewData
{
   public Foo Foo {get; set;}
   public Bar Bar {get; set;}
}
public ActionResult Edit()
{
   FooBarViewData fbvd = new FooBarViewData();
   fbvd.Foo = new Foo(){ A = "aaa"};
   fbvd.Bar = new Bar(){ B = "bbb"};
   return View(fbvd);
}

Then your view is just strongly typed to FooBarViewData and you can call members of that object using the Model property.

A: You have a couple of choices.  First, you can reference them from ViewData and use an HtmlHelper extension. Or you could create a view-specific model and use a strongly-typed viewpage for Edit.aspx.
public class EditModel
{
    public Foo foo { get; set; }
    public Bar bar { get; set; }
}

public ActionResult Edit()
{
    var model = new EditModel();

    model.foo = new Foo { A = "aaa" };
    model.bar = new Bar { B = "bbb" };

    return View( model );
}

(Edit.aspx is of type ViewPage<EditModel>)
Either way, the HtmlHelper extension will pick up any initial values.
<form action="/some/process" method="post">
     <%= Html.Hidden( "foo.A" ) %>
     <%= Html.Hidden( "bar.B" ) %>
</form>

A: The solution above may be outdated. This solution seems to work for ASP.Net MVC5+.
You're going to have to use the ViewModel method. This is an excellent tutorial that you can check out.
http://tutlane.com/tutorial/aspnet-mvc/how-to-use-viewmodel-in-asp-net-mvc-with-example
You are going to have to join multiple models into one ViewModel and grab all the properties from each models you want to use into the ViewModel.
BUT, it is HIGHLY advised that you create a new Controller and a new View to accomodate the newly created ViewModel. Read the tutorial.
public class FooBarViewModel
{
   public string A {get; set;}  //Property for Foo
   public string B {get; set;}  //Property for Bar
}

public ActionResult Edit()
{
   FooBarViewModel fooBarVM = new FooBarViewModel();
   fooBarVM.A = "aaa";
   fooBarVM.B = "bbb";

   return View(fooBarVM);
}

But in this case, you should be able to pass the ViewModel into a different view. Just make sure you declare this similar directive correctly in the foobar.cshtml page.
@model FooBar.Models.FooBarViewModel

A: I was struggling for a while trying to get two models to work, and most of the answers I came across was meant for earlier versions of MVC.
I found the following tutorial works best for MVC 5 as suggested by David Lee:
http://tutlane.com/tutorial/aspnet-mvc/how-to-use-viewmodel-in-asp-net-mvc-with-example
I created a join and selected only the columns I needed from both Models.
I had it working with partial views
In view.cshtml
 @model IEnumerable<Test.Models.TestViewModel>
    ...
      @foreach (var item in Model)
                    {

                                @Html.DisplayFor(modelItem => item.TestName)
...


text:
Q: How to set a date variable with several days I need to get a list of dates data. So far I'm only selecting one date at a time but I need it to be multiple days.
declare @evalDate1 as Date
declare @evalDate [date];
set @evalDate1 = '2020-10-20'

I tried this:
declare @evalDate1 as Date
declare @evalDate [date];
set @evalDate1 = ('2020-10-20' or '2020-10-21')

But this doesn't work. Can anyone help? Thank you!

A: you either need to make  temp table
create table #evalDate ( value date)

insert into #evalDate values ('2020-10-20'), ('2020-10-21')

or a table variable
create @evalDate table ( value date)

insert into @evalDate values ('2020-10-20'), ('2020-10-21')


text:
Q: Can you re-purpose built-in laptop keyboard as a hotkey launcher? I have a MacBook Pro - but I don't use the keyboard, I use a (more ergonomic) plugin keyboard.
I have an x-keys (programmable keypad). I'm thinking of getting another one, but it just struck me as ridicilous that I have this whole chunk of hardware on my desk with 91 keys at my fingertips going to waste.
Is there any way way that my laptop keyboard could be recognised as a completely separate set of keys (to my standalone keyboard) so that all the keys (only on my laptop keyboard) could be remapped to a bunch of hotkeys/shortcuts/macros?
Any hotkey apps, Keyboard Maestro, for example just recognise both keyboards as the exact same input. Is there any software that goes a bit deeper and recognises that they're not the same keyboard?
My gut feeling is no. And what I'm looking for probably requires some serious hardware hacking, but... definitely worth asking I think.

A: There are several ways to do this. I remember that you could remap very few keys under 10.4. Back then I always had to launch an instance of X11 in order to remap my keys... (What nonsense...)
Luckily the situation has changed and there are two tools that do the trick:

*

*KeyRemap4MacBook - In my opinion the best AND it is Opensource. :-)

*Then there is DoubleCommand which is also Opensource. I've never tried it, but a friend remapped his Esc key and is really happy with it.


text:
Q: I am new to JSON , is there any way to validate a json- key value pair Line_Of_Business = {
        LOB1           : "LOBAppType=sadfsd",
        LOB2           : "LOBAppType=asdf",
        LOB3           : "LOBAppType=asdf}
        LOB4           : "LOBAppType=sdf",
};

Market = {
        MKTID001       :"MarketName=US||Descr=USA",
        MKTID002       "MarketName=JP||Descr=Japan""
            LOB3           : "LOBAppType=asdf",
        LOB4           : "LOBAppType=sdf",

in this example Market and Line of Business are two json object. Is there any way of validating the syntax of the json object.
In Market json object "MKTID002" key  and in Line of business "LOB3" key the syntax is wrong and the Market object is not closed properly.
Is there any way of finding the find the error using java

A: Well the obvious way to validate the basic syntax of some JSON is to simply try to load / read / parse it using one of the many JSON parser libraries.  (And if the parse / read /load succeeds, you can throw away the resulting data structure).  json.org Lists a number of JSON libraries in a number of languages ... including Java.
If building and throwing away a data structure is a concern, then some of the libraries offer JSON validation separate from loading; e.g. http://www.stringtree.org/stringtree-json.html
And if simply want to do this validation on an ad hoc basis (i.e. not as part of some larger application), then try the jsonlint.com service.

A: Sample syntax-check with Gson (using lombok):
package com.stackoverflow.so13701022;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.google.gson.annotations.SerializedName;

import lombok.Data;

public class CheckJson {
    @Data
    private static class LineOfBusiness {
        @SerializedName("LOB1")
        private String lob1;

        @SerializedName("LOB2")
        private String lob2;

        @SerializedName("LOB3")
        private String lob3;

        @SerializedName("LOB4")
        private String lob4;
    }

    @Data
    private static class Market {
        @SerializedName("MKTID001")
        private String mktid001;

        @SerializedName("MKTID002")
        private String mktid002;

        @SerializedName("LOB3")
        private String lob3;

        @SerializedName("LOB4")
        private String lob4;
    }

    private static final String ONE = "{" +
    "        LOB1           : \"LOBAppType=sadfsd\"," +
    "        LOB2           : \"LOBAppType=asdf\"," +
    "        LOB3           : \"LOBAppType=asdf}" +
    "        LOB4           : \"LOBAppType=sdf\"," +
    "}";

    // I corrected this one on purpose
    private static final String TWO = "{" +
    "        MKTID001       :\"MarketName=US||Descr=USA\"," +
    "        MKTID002       :\"MarketName=JP||Descr=Japan\"," +
    "        LOB3           : \"LOBAppType=asdf\"," +
    "        LOB4           : \"LOBAppType=sdf\"" +
    "}";

    public static void main(String[] args)
    {
        final Gson gson = new GsonBuilder().create();
        System.out.println(tryParse(gson, ONE, LineOfBusiness.class));
        System.out.println(tryParse(gson, TWO, Market.class));
    }

    private static <T> T tryParse(Gson gson, String what, Class<T> clazz)
    {
        try {
            return gson.fromJson(what, clazz);
        } catch (final JsonSyntaxException e) {
            System.err.println(e);
        }
        return null;
    }
}

Output (Err = stderr, Out = stdout):
(Err) com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 159
(Out) null
(Out) CheckJson.Market(mktid001=MarketName=US||Descr=USA, mktid002=MarketName=JP||Descr=Japan, lob3=LOBAppType=asdf, lob4=LOBAppType=sdf)

A: Use any JSON library for java ( org.json.JSONObject)  and you will get all features like parsing and validation inbuilt in API.
These libraries take any String as argument and if it fails to parse the string into JSONObject then throws Exception.
 JSONObject jsob = new JSONObject(StringRepresentationOfJson);


text:
Q: NSFetchedResultsController not Detecting type of Change When an Object is Inserted or Updated I have a collectionView. The second section of the collection is populated by an NSFetchedResultsController. The cells are populated by the Recipients object. On a different viewController I add a video to core data. the video is a relationship to the Recipients Object. It is a one to many relationship. One Recipient can have many videos, but each video can only have one Recipient. The videos are stored as an NSOrderedSet. when using
Edit: This is the declaration of the NSFetchedResultsController
  lazy var fetchedRC: NSFetchedResultsController<Recipient> = {
    let fetchRequest:NSFetchRequest<Recipient> = Recipient.fetchRequest()

    let reversedDescriptor = dateSortDescriptor.reversedSortDescriptor as! NSSortDescriptor

    fetchRequest.sortDescriptors = [dateSortDescriptor]

    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    let managedContext = appDelegate.persistentContainer.viewContext

    let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext:managedContext , sectionNameKeyPath: nil, cacheName: nil)

   fetchedResultsController.delegate = self

    return fetchedResultsController
}()

Edit: Meant to post this method.
 func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {

    switch type {
    case .insert:
        print("I inserted")
        break;
    case .delete:
        print("I deleted")
        break;
    case . update:
        print("I updated")
        break;
    default:
        print("I don't know")
    }

}

It always returns I don't know even though a change is detected.
  let selectedPerson = personsArray[cellSelected] as? Recipient

    guard let currentContext = selectedPerson?.managedObjectContext else {
        print("I AM NOT SET")
        return
    }

    let video = Videos(context: currentContext)
    video.thumbNail = savedImageData
    video.urlPath = url
    video.isVideo = true
    video.isVoiceMemo = false
    video.isWrittenMemo = false
    video.uuID = uuid
    video.creationDate = NSDate()

    if let videos = selectedPerson?.videos?.mutableCopy() as? NSMutableOrderedSet {
        videos.add(video)
        selectedPerson?.latestMemoDate = NSDate()
        selectedPerson?.videos = videos
    }
        do {

        try selectedPerson?.managedObjectContext?.save()
        try video.managedObjectContext?.save()
        self.tableView.reloadData()

    }
    catch let error as NSError {
        print("Could not save. \(error), \(error.userInfo)")
    }


text:
Q: Count distinct values in many-to-many relationship I have one relation many-to-many on my EF.
Select * from [Group]
Select * from [User]
select * from [RelUserGroup] //relation between ground and users

I like know how many districts users I have on table RelUserGroup. This is very simple on SQL but in EF I doesn't have this table.
How I count how many users I have in all groups !
Group
GroupId     Name
----------- ------------------
1           DCE Administrators
2           Dispatcher
3           Team Managers
4           Resolver
5           Requestor

User
UserId      UserName
----------- ---------
1           anderson
2           Fabio

RelUserGrou
GroupId     UserId
----------- -----------
1           1
2           1
4           1

In this case my count is 1, because userId = 2 isn't in any group.

A: Perhaps something like this:
var result = db.Users.Count(u => u.Groups.Any());

Or alternatively
var result = db.Groups.SelectMany(g => g.Users).Distinct().Count();


text:
Q: Connect IdentityServer4 with external authentication I wonder how to wire the connection myself between IdentityServer and an external authentication providers (e.g. Google)? I think this is given when using IdentityServer4 QuickStart UI with implicit grant; e.g. the external log in trigger is wired already.
But I am using Resource owner password grant so that I can use my own log in UI and can't figure out how to connect IS and external authentication.
I tried to add Google and then go to localhost:5001/signin-google but got an error. I think I need more setup but unsure how. Has anyone done this?
I also registered localhost:5001/signin-google in the google console for authrorized origin.
This is my config:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddIdentityServerAuthentication(options =>
                {
                    options.Authority = _authority;
                    options.ApiName = "my-api";
                    options.RequireHttpsMetadata = false;
                    //options.ApiSecret = "secret";
                    options.SupportedTokens = SupportedTokens.Both;
                });

            // add google
            services.AddAuthentication()
                .AddGoogle("Google", options =>
                {
                    options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
                    options.ClientId = "b5lge4nj8djnr63lm25rbl4nl0gct73v.apps.googleusercontent.com";
                    options.ClientSecret = "vfRXJmEXnKuIsSnHxOn_f";

                });

This is the log:
2017-12-30 21:43:50.641 +00:00 [INF] Error from RemoteAuthentication: The oauth state was missing or invalid..
2017-12-30 21:43:50.646 +00:00 [ERR] An unhandled exception has occurred while executing the request
System.Exception: The oauth state was missing or invalid.
   at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.<HandleRequestAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at IdentityServer4.Hosting.FederatedSignOut.AuthenticationRequestHandlerWrapper.<HandleRequestAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.<Invoke>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()
2017-12-30 22:00:38.055 +00:00 [INF] Error from RemoteAuthentication: The oauth state was missing or invalid..
2017-12-30 22:00:38.079 +00:00 [ERR] An unhandled exception has occurred while executing the request
System.Exception: The oauth state was missing or invalid.
   at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.<HandleRequestAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at IdentityServer4.Hosting.FederatedSignOut.AuthenticationRequestHandlerWrapper.<HandleRequestAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.<Invoke>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()

Update1: When I add CallbackPath, localhost:5001/signin-google returns 404 Not Found now.
// add google
            services.AddAuthentication()
                .AddGoogle("Google", options =>
                {
                    options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
                    options.ClientId = "b5lge4nj8djnr63lm25rbl4nl0gct73v.apps.googleusercontent.com";
                    options.ClientSecret = "vfRXJmEXnKuIsSnHxOn_f";
                    options.CallbackPath = "/home";
                });


text:
Q: React issue - Expected an assignment or function call and instead saw an expression I keep getting the error message "Expected an assignment or function call and instead saw an expression" in my code, I think it is because I have an if inside my map but I have tried a few ways and I cant seem to make the code work.
I am trying to display information returned from my API, but I only want to display messages that have been sent when the ID length is equal to 7.
Example of the information returned from my API
"message_Subjects": [
    {
"subjectId": 1,
        "userId": 1234567,
        "subject": "test subject 1",
        "message_Chain": [
            {
                "messageBody": "TEST",
                "sentFromId": 1234567
            },
            {
                "messageBody": "Reply to the first message from another user",
                "sentFromId": 654321
            }
        ]
    }
}]

This is my code
return (

    {Data?.message_Subjects?.map((sub) => (

Subject = {sub.subject}

        {sub.message_Chain.map((chain) =>
          {if(chain.sentFromId.length=== 7) (

message = {chain.messageBody}

sent by = {chain.sentFromId}

 )}
        )}

    ))}

);

A: You need to add return after your condition.
{
  if(chain.sentFromId.length === 7) {
    return (

message = {chain.messageBody}

sent by = {chain.sentFromId}

)
  }
}

By the way, it's also better to explicitly handle the else case, by returning null for instance.

A: You should use conditional rendering for this cases:
return (

        {Data?.message_Subjects?.map((sub) => (

Subject = {sub.subject}

                {sub.message_Chain.map(
                    (chain) =>
                        chain.sentFromId.length === 7 && (

message = {chain.messageBody}

sent by = {chain.sentFromId}

                        )
                )}

        ))}

);

Anything else, let me know

A: You cannot mix javascript and jsx this way
return (

    {Data?.message_Subjects?.map((sub) => (

Subject = {sub.subject}

        {sub.message_Chain.map((chain) => {
          if(chain.sentFromId.length=== 7) (

message = {chain.messageBody}

sent by = {chain.sentFromId}

           )
          }
        )}

    ))}

);

When not used as an arrow function body, the following is not a proper javascript instruction, but an expression (has a value but does nothing, so it cannot be the body of an if statement):

message = {chain.messageBody}

sent by = {chain.sentFromId}

Just add a return for making it an expression (as expected in an if block) and allow the code to compile properly:
      return (

message = {chain.messageBody}

sent by = {chain.sentFromId}

       );

A: In your code using if () is not a valid conditional rendering. Try like
return (

    {Data?.message_Subjects?.map((sub) => (

Subject = {sub.subject}

        {sub.message_Chain.map(
          (chain) =>
            chain.sentFromId.length === 7 && (

message = {chain.messageBody}

sent by = {chain.sentFromId}

            )
        )}

    ))}

);


text:
Q: When should we use run loop recursively in IOS? I read the "IOS Developer Library" about the "Run Loops" theme, in the article, one sentence says "It is possible to run a run loop recursively". My question is in which scenario should use the recursive run loop please?
My another question is about the statement "The purpose of a run loop is to keep your thread busy when there is work to do and put your thread to sleep when there is none.". How can a run loop sleep, can the main thread's run loop sleep when no event comes? What about the second thread's situation?
one example of the nested run loop that I found from Internet is that like
below:
 [NSThread detachNewThreadSelector:@selector(runOnNewThread) toTarget:self withObject:nil];
 while (!end) {
    NSLog(@"runloop…");
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    NSLog(@"runloop end.");
 }

The current thread will be blocked until the work in another thread has finished. But why this happen, how the current thread can be blocked?
Can anyone answer my question?

A: maybe an analogy is, pretend a run loop is an infinite while loop (which it basically is), then if you made another infinite while loop inside that one, the outer while loop would never loop again because the inner one is infinite, so what they have done is made it so when you make an inifinite while loop in another, it instead goes out of the outer one, and runs along beside it (on another thread)
in response to your update:
surely it will be blocked for no other reason than the while loop doesnt have an end condition
while (!end) {

if end is controlled from another thread, then that thread would have to set end to true before the current thread can move on from this while loop.
this code just seems really bad, it keep restarting the current runloop, probably defeating it purpose


text:
Q: Let $M$ be a finitely generated $R$-module and $I \subset R$ an ideal such that $IM = M$. If $M'$ is a particular submodule, does $IM '= M'$?
Suppose $R$ is a commutative ring, $I$ an ideal, and $M$ a finitely generated $R$-module with generators $\{m_1, \ldots, m_n\}$; suppose further that $IM = M$. Let $M'$ be the submodule of $M$ generated by $\{m_2, \ldots, m_n\}$. I would like to prove that $IM' = M'$.

$IM' \subseteq M'$ is of course trivial, following from the closure of submodules under scalar multiplication by elements of $R$; I am having some difficulty proving containment in the opposite direction.

A: Since $M=IM$, we can write $m_1=a_1m_1+a_2m_2+\dots+a_nm_n$, for $a_i\in I$.  Rearranging terms, we find $(1-a_1)m_1\in IM'$.  Now use this to show that $(1-a_1)m_i\in IM'$ for $i=2,\dots,n$ as well.  Since $a_1\in I$, conclude that in fact $m_i\in IM'$ for $i=2,\dots,n$.

A: This is essentially a corollary of Nakayama's Lemma. This states that $IM=M$ is equivalent to $(1-a)M=0$ for some $a \in I$. Now, if $M'$ is any submodule of $M$, it follows $(1-a)M'=0$ and hence $IM'=M'$.


text:
Q: Calculate date based on given time I went through a project which I need to set a recall time for an event. the recall time is set to 1 day and some hours before the event happen. I  calculate event date and recall time like this:
$now = time();
$days_to_event = 24 ; //(I set an input for it in form)
$event_time = $now + $days_to_event * 3600;
$difference = 24*3600 + time('h')*3600 + time('i')*60;
$recall_time = $event_time - $difference;

I was wondering if I could create a function which takes $recall_time and calculates the date and outputs it.
Any useful idea for simplifying the project is a great help for me.
Thank you my friends.

A: I think the answer you are looking for maybe is
 echo date('Y-m-d H:i',$recall_time);

A: time() function return timestamp format, You need date() function to get hour and minute.
$now = time();
$days_to_event = 24; //(I set an input for it in form)
$event_time = $now + $days_to_event * 3600;
$difference = 24 * 3600 + date('h') * 3600 + date('i') * 60;
$recall_time = $event_time - $difference;

echo date('Y-m-d H:i', $now) . '
';
echo date('Y-m-d H:i', $event_time) . '
';
echo date('Y-m-d H:i', $recall_time) . '
';


text:
Q: JBoss EJB 3 issue DeploymentException I am deploying a EJB3 Jar with several beans in it. The jar works fine on other instances and is deployed correctly. However if I try that on my machine, I get the DeploymentException.
I am on JBoss 5.1.0
Please help!!
Here is the stack trace:

*** DEPLOYMENTS IN ERROR: Name -> Error
vfszip:/D:/jboss-5.1.0.GA/server/default/deploy/Enhanced-QC-ejb.jar/ -> org.jboss.deployers.spi.DeploymentException: org.jboss.deployers.spi.DeploymentException: Error deploying: Factory$org.jboss.aspects.remoting.InvokeRemoteInterceptor
DEPLOYMENTS IN ERROR:
  Deployment "vfszip:/D:/jboss-5.1.0.GA/server/default/deploy/Enhanced-QC-ejb.jar/" is in error due to the following reason(s): java.lang.IllegalStateException: Factory$org.jboss.aspects.remoting.InvokeRemoteInterceptor is already installed.
    at org.jboss.deployers.plugins.deployers.DeployersImpl.checkComplete(DeployersImpl.java:993)
    at org.jboss.deployers.plugins.deployers.DeployersImpl.checkComplete(DeployersImpl.java:939)
    at org.jboss.deployers.plugins.main.MainDeployerImpl.checkComplete(MainDeployerImpl.java:873)
    at org.jboss.system.server.profileservice.repository.MainDeployerAdapter.checkComplete(MainDeployerAdapter.java:128)
    at org.jboss.system.server.profileservice.hotdeploy.HDScanner.scan(HDScanner.java:369)
    at org.jboss.system.server.profileservice.hotdeploy.HDScanner.run(HDScanner.java:255)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
    at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:317)
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:150)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(ScheduledThreadPoolExecutor.java:98)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.runPeriodic(ScheduledThreadPoolExecutor.java:181)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:205)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)

A: Try to clean the tmp directory (D:/jboss-5.1.0.GA/server/default/tmp in your case) and restart JBoss.


text:
Q: Android SwipeListView library I'm using SwipeListView.
My back view is just a button alling to the right and i can not figure out how to swipe my row list just enough to show the button not all the row.
Now i can just set the offset of the swipe by :
my_list_view= (SwipeListView) findViewById(R.id.lista_produse);

my_list_view.setOffsetLeft()

But i need a way to swipe the row enough to show the button in the back view
Thanks

A: Did you try the xml attribute "swipeOffsetLeft" ?

A: I tried SwipeListView before. If you want to show the back view in appropriate width, you need to call my_list_view.setOffsetLeft(); programmatically. Of course you need to get the width of your Button in the back view. Then call my_list_view.setOffsetLeft();.


text:
Q: When accessing /index.html in a Vite + React project, a 404 page pops up After building and deploying on the web composed of Vite + react, when accessing www.mypage.com/index.html, not found appears.
On web configured with Webpack + react, it redirects to /.
How do I redirect to / when accessing www.mypage.com/index.html in vite + react?
Router uses react-router-dom browser router. Using a hash router solves it, but I don't want the # in the url.
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </BrowserRouter>

In React + Webpack project, when accessing /index.html, it is redirected to /, but when using Vite, the redirect is not.


text:
Q: Make layer with TileStache from MySQL database I am unsuccessful in attempt to make layer with TileStache whitch gets data from MySQL. I found simple MySQL table structure (http://howto-use-mysql-spatial-ext.blogspot.com/):
create table Points (
name VARCHAR(20) PRIMARY KEY,
location Point NOT NULL,
description VARCHAR(200),
SPATIAL INDEX(location)
);

and then
INSERT INTO Points (name, location) VALUES ( 'point1' , GeomFromText( ' POINT(31.5 42.2) ' ) )

For TileStache in tilestache.cfg I got:
"data":
    {
        "provider": {"name": "vector", "driver": "MySQL",
                     "parameters": {"dbname": "gis", "port": "3306",
                     "user": "root", "password": "root",
                     "table" : "points"}}
    },

When I go to http://localhost:8080/data/ I get in console:

*

*GET http://localhost:8080/data/10/167/395.png 500 (Internal Server
  Error);

*GET http://localhost:8080/data/null 400 (Bad Request).

Same internal error when going to http://localhost:8080/data/0/0/0.geojson
NOTE: http://localhost:8080/osm/ works fine.
I think problem is global, because I tried making layer from .json file, but same result

A: Why changing ports. make sure when you start tilestache-server it listens to the correct port and make sure that by going to localhost:port_of_tilestatche it shows.
 belows tilestache

A: Try running tilestache on a different port. Port 8080 has many things running on it. What OS are you using
    tilestache-server.py -c your config file  -p 9000
Then you can run localhost:9000 and you should get the


text:
Q: Simple custom UI in Maya using Python Hi I am learning about creating custom UI for Maya using Python. I am trying to achieve few things which I am unable to do. I searched around but couldn't find my answers.
import maya.cmds as cmds

def main():

    cmds.window(title='Test Window')
    cmds.columnLayout()
    cmds.textFieldGrp('obj1', label='Name', text ="Please enter your name")
    cmds.textFieldGrp('obj2', label='Address', text = "Please enter your address")
    cmds.rowLayout(nc=3)
    cmds.button(label="Lock", width=100, c='disable_texts()')
    cmds.button(label="Edit", width=100, c='change_texts()')
    cmds.button(label="Reset", width=100, c='default()')
    cmds.showWindow()

def disable_texts():
    # disable the text fields

def change_texts():
    # enable the text fields

def default():
   # change the text fields back to default ie like above

A: This might answer your question, if I understand..
cmds.window(title='Test Window')
cmds.columnLayout()
cmds.textFieldGrp('obj1', label='Name', text ="Please enter your name")
cmds.textFieldGrp('obj2', label='Address', text = "Please enter your address")
cmds.rowLayout(nc=3)
cmds.button(label="Lock", width=100, c=disable_texts)
cmds.button(label="Edit", width=100)
cmds.button(label="Reset", width=100)
cmds.showWindow()

def disable_texts(*args):
    #The e=True is for edit, so I'm 'editing' 'obj1' which is the name of the textFieldGrp
    cmds.textFieldGrp('obj1', e=True, enable=False)

As a side note, it's better to pass the function object to the command flag. Check this out if you're unsure why. As for the cmds functions you should check the docs to see what other commands there are.

A: After you made your experiences with layouting UIs with the Maya builtin possibilities I recommend you to setup PyQT for Maya.
If you are using Maya Version below 2014, than you need to install the compiled PyQt from here: http://nathanhorne.com/?s=pyqt
Since Maya integrated PyQT with 2014 (therefore 2015 also) you don't need to install anything for this version.
Here some starting tutorials:
http://zurbrigg.com/maya-python/category/pyqt-projects-for-maya
Have fun!!!


text:
Q: What are the benefits of declaring an object as interface?
Possible Duplicate:
What does it mean to "program to an interface"?

I noticed that some people like to declare an object as one of the interfaces it implements even though, within the scope of the variable, it is not necessary to look at it as the interface, e.g. there is no external API that expect an interface.
For example:
Map<String, Object> someMap = new HashMap<String, Object>();

Or you can just do
HashMap<String, Object> someMap = new HashMap<String, Object>();

and avoid importing java.util.Map altogether.
What are the advantages of declaring it through an interface (first above) as opposed to the class itself (second above)?
Thanks

A: An interface such as Map<A, B> declares what an object can do. On the other hand, a class such as HashMap<A, B> defines how an object does what the interface declares it does.
If you declare a variable (or field, or whatever) a Map<A, B>, you are stating that your code depends only on the contract defined by that interface, it does not depend on the specifics of an implementation.
If you declare it a HashMap<A, B>, it is to be understood that you need that specific version of a map (for whatever reason), and it cannot be replaced for something else.
I tend to dislike the common answers like "because you can change the implementation" simply because, after years and years of practice, you will see that it won't happen as frequently as that, and the major benefits are really this subtle (but clear) expression of your intents.

A: Since it's not part of API, it is implementation detail. It's better to be specific in implementations, there's no point to be abstract here.
my prev answer
Use interface or type for variable definition in java?

A: If the variable is not used later, there is no advantage/disadvantage.  The reason you would use an interface rather than an object is to allow for more flexibility, but if that variable isn't used, there is no difference from a performance persepective.

A: If you use Map<String, Object> someMap, you are designing to an interface rather than implementation.. So you can switch between other implementation easily..
So, your Map can point to a HashMap, LinkedHashMap, or any other object, that is a subclass of Map.
So, if you have: -
Map<String, Integer> someMap = new HashMap<>();

You can change the implementation later on(If you want) to point to a LinkedHashMap: -
someMap = new LinkedHashMap<>();

Whereas if you use HashMap on LHS, you can only make it point to an object of type HashMap..
But, as such there is no difference in performance.. But it is suggested to always design to an interface rather than implementation..

A: A interface defines, which method a class has to implement.
This way - if you want to call a method defined by an interface - you don't need to know the exact class type of an object, you only need to know that it implements a specific interface.
Example:
interface Printer {
    public void print(String text);
}

class FilePrinter implements Printer {
    public void print(String text) {
       //append the text to a file
    }
}

class ScreenPrinter implements Printer {
    public void print(String text) {
       //write the text on the screen
    }
}

class SomeClass {
    public printSomething(Printer myPrinter) {
        myPrinter.print("Hello");
    }
}

If you call SomeClass.printSomething(...) it does not matter if you pass an instance of FilePrinter or ScreenPrinter, because the method just does not care. It knows that the object implements the interface Printer and also implements it's methods.
Another important point about interfaces is that a class can implement multiple interfaces.


text:
Q: XFCE - Autohide Animations I am running Ubuntu with Unity. I also have an xfce panel installed on top of it. I have set it to autohide, but when it does it is blinks in/out of existence. I have tried setting an animation for the window class in compiz, with no luck. How can I add some decent animations to the xfce panel?

A: In Xfce, there is no option for animation like what can be done in GNOME, KDE and Cinnamon. However, it is possible to introduce some delays to autohide the Xfce panel.
Delay autohide for Xfce panel
To delay autohide for Xfce panel, edit the .gtkrc-2.0 file and add the code block of style "xfce-panel-window-style" as noted in this Xfce Docs (archived).
Step by step instructions as follows.

*

*Open the file manager and go to the Home directory of current user /home/USERNAME.

*Go to View > Show Hidden Files (or use keyboard shortcut Ctrl+H).

*Find a file named .gtkrc-2.0 and open with a text editor. If the file doesn't exist, create an empty file and rename accordingly.

*Then, paste the following codes into the file.
style "xfce-panel-window-style"
{
  # Time in miliseconds before the panel will unhide on an enter event
  # original value: 225
  XfcePanelWindow::popup-delay = 225

  # Time in miliseconds before the panel will hide on a leave event
  # original value: 350
  XfcePanelWindow::popdown-delay = 900

  # Size of autohide window in pixels
  # original value: 3
  XfcePanelWindow::autohide-size = 10
}

class "XfcePanelWindow" style "xfce-panel-window-style"

*Save and close the file.

*Finally, restart Xfce panel.
To restart Xfce panel, user can do either one of these:

*

*Run xkill (or use keyboard shortcut Ctrl+Alt+Esc), the mouse cursor will change to X icon, then bring the X cursor and click on the Xfce panel, then Xfce panel will disappear and restart automatically.

*Open Terminal, run killall xfce4-panel; xfce4-panel & and finally close Terminal.
There is no need to logout or reboot at all.
Delay isn't animation
It is important to understand that delay is not animation, vice versa. Delay is to make something happen after certain time, usually given in miliseconds (1000 miliseconds = 1 second). By introducing some delays, user will less likely to go panic and less likely to lose track of autohide panel.
False animation: Delay autohide 100 miliseconds (top) and 900 miliseconds

While delay is nothing fancy, I found that 900 miliseconds of delay is comparable alternative to standard animation of hiding a dock.
True animation: Dock

An example is Plank, a simple and lightweight dock. This dock features animation that can be noticed when autohide, as well as options for hide delay and unhide delay. See the screenshot below.

I mentioned this dock as a good example to show the difference between animation and delay. Animation is usually hardcoded and not configurable, which is exactly why user will not see any option for animation, unlike delay.
Disclaimer: I have modified value for popdown-delay to 900 and also autohide-size to 10 for more optimal experience, which will make user aware of the panel existence prior to hiding the panel and even after it hides. User experience may vary and GIF images are more or less accurate.
Tested working in Xubuntu 14.04 (Xfce 4.10).

Answerer's note: This answer was written when Xfce still had GTK+ 2 components, which means the delay autohide will not work in Xfce 4.12 and newer.


text:
Q: Angular material auto complete should show options if the value matches with starting letter(s) of any word The first typed letter should match the first letter of every word of the result in the drop down.
Currently I am matching with any letter in the option like below but I should be match only starting letter(s) of any word in the option.
My current logic is below,
return this.allUniversities.filter(university => university.toLowerCase().indexOf(filterValue) > -1);
If the entry in the list is Industrial Designer, then this entry should show up if a candidate types the letter I or the letter D. It should not show up if the candiate types the letters 'N, D, U, S' etc.

A: All you need to do is split the string and then check if the substrings start with the typed characters:
return this.allUniversities.filter(university => {
    return university.toLowerCase().split(' ').some(substr => substr.startsWith(filterValue));
  });

Here
  is a stackblitz that shows it in action.


text:
Q: when i write external css the background color does not work but if i use the inline css or internal css the bg color work fine

            body{

                 background-color: limegreen;
            }

            hr{

                border-style: none;
                border-top-style:dotted;
                border-color:darkred;
                border-width: 5px;
                width: 5%;

            }
            h3{
                color: #64DFDF;
            }
            h1{
                color: #64DFDF;
            }


text:
Q: Permanent network drive mount in fstab not working (due to network not being online whilst attempting to mount) I have a network drive hosted on a Windows10 Machine, it mounts fine to my CentOS7 machine through the command:
sudo mount -t cifs //ipaddress/sharedfoldername /mountpoint --verbose -o credentials:/credential/file/location,file_mode=0666,dir_mode=0777

The file and dir modes are for the permissions on the mount. Anyway, that mounts fine, but when I try to do an /etc/fstab mount, I get an error back.
I will supply my entire fstab file contents and the exact error below. The error appears on startup, it boots to emergency mode and shows the error and gives me the option to use CTRL + D to continue.
The fstab mount I am trying to get to work is:
//ipaddress/sharedfoldername /mnt cifs credentials=/etc/smbcredentials,uid=1001,gid=1001,_netdev 0 0

My /etc/fstab contents:
#
# /etc/fstab
# Created by anaconda on Thu Dec 13 09:33:55 2018
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
UUID=4f3871fe-a798-4d51-ad90-c40b095a2bd0 /                       ext4    defaults        1 1
UUID=1bb03b6d-3a76-4979-aa63-ff3e0eb4cc5f /boot                   ext4    defaults        1 2
UUID=f89fdb96-6dbf-4865-aa6b-1d5cc74f2d48 /home                   ext4    defaults        1 2
UUID=86f38c73-f9e0-490b-8c96-3321f9413c0d swap                    swap    defaults        0 0
//ipaddress/sharedfoldername /mnt cifs credentials=/etc/smbcredentials,uid=1001,gid=1001,_netdev 0 0

The error appears on startup and you can find it below:
You're looking at the CIFS bit, the bad mount option huge needs sorting anyway, that was there before the fstab cifs mount. Thanks

@telcoM's answer response
I rebooted and get the following error on startup:

Then when I login after seeing the error, I get a shortcut appear in the left of my file browser, when I click it, I get this error:
Unable to mount 'shared-folder-name', mount: only root can mount //ipaddress/sharedfoldername on /mountpoint

MY FSTAB FILE AFTER @TELCOM'S SUGGESTION
#
# /etc/fstab
# Created by anaconda on Tue Dec 11 14:28:31 2018
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
UUID=4d48ab0d-e1ab-4d7e-9f64-8481a7690060 /                       ext4    defaults        1 1
UUID=a7fad550-81d7-4150-8b76-e89584e4cfdf /boot                   ext4    defaults        1 2
UUID=0baabbc4-2dc0-4971-9d2b-c123e5ad7355 /home                   ext4    defaults        1 2
UUID=7756eafb-382c-46b3-aae8-e44d7e2cfe06 swap                    swap    defaults        0 0
#
//ipadress/sharedfoldername /mount/location cifs x-systemd.after=network-online.target,credentials=/credentials/location,vers=3.0,file_mode=0666,dir_mode=0777,uid=1001,gid=1001 0 0

A: The tmpfs: Bad mount option huge turns out to be a kernel bug: see this link.
The "Error connecting to a socket" means the system is trying to mount the Windows share before network interfaces have been fully enabled. It should not be happening, but you could add a new systemd-style mount option to be explicit about it: x-systemd.after=network-online.target. The _netdev option used to be an old way to do the same, but apparently it does not work any more after CentOS moved to systemd in version 7.0.
As i wrote in my answer to your earlier question, if you want everyone to be able to access the share, you'll need to supply the mount options file_mode=0666,dir_mode=0777. And if you do this, then the uid=1001,gid=1001 options will probably be unnecessary, but you can still use them if you want.
And to silence an ugly warning about a changed default version of the SMB protocol (since the aftermath of the WannaCry ransomware infestation back in May 2017), you'll want to add vers=3.0 mount option too, if the share is provided by a reasonably modern version of Windows.
So, the /etc/fstab entry should probably be like this (split to multiple lines for readability):
//ipaddress/sharedfoldername /mnt cifs
x-systemd.after=network-online.target,credentials=/etc/smbcredentials,
vers=3.0,file_mode=0666,dir_mode=0777,uid=1001,gid=1001 0 0

An fstab entry should always have exactly 6 fields separated by whitespace - no more and no less.

A: The working line in /etc/fstab:
//ipadress/sharedfoldername /mountpoint cifs x-systemd.after=network-online.target,noauto,x-systemd.automount,credentials=/credentials/location,vers=3.0,file_mode=0666,dir_mode=0777,uid=1001,gid=1001 0 0

@telcoM has helped loads with getting to this result.


text:
Q: CSS: increase width for list items I am new to css and am currently trying to split the screen in two parts and place text on the left and the right side. However, for some reason the right "box" doesn't cover the whole right part of the screen, only like 200-300 px...
JSFiddle:
https://jsfiddle.net/19mw8hzL/
The black text should reach to the right side of the screen.

Strategy

Visioning

Strategic Analysis

Strategy Formulation

Business Model Innovation

Financial Modeling

A: Change your css for #two, to add in the 20% of #one, to make 100%:
#two {
    float: left;
    overflow: hidden;
    width: 76%; /* this is completing the width with the 4% padding */
    padding-top: 17px;
    padding-right: 4%;
}

A: Hi please modify these
Lets make the parent element as 100% and make the children div as 50% each
.wrapper {
   width : 100%;
}

#one {
  float:left;
  width:50%;
}

width to 46% because we have given padding right as 4% so (46+4 = 50)
#two {
  float: right;
  width: 46%;
  padding-top: 17px;
  padding-right: 4%;
}

:)

A: Flexbox can do that.

.w-text-1 {
  font-family: 'Garamond', serif;
  color: rgba(163, 42, 46, 1);
  font-size: 35px;
}
.wrapper {
  display: flex;
}
.wrapper div {
  color: #fff;
}
#one {
  width: 20%;
}
#two {
  flex: 1;
  background: lightblue;
  text-align: right;
}
#two a {
  text-decoration: none;
  font-family: 'Gotham', sans-serif;
  font-size: 17px;
  color: #000;
  border: 1px solid grey;
}
#two ul {
  overflow: hidden;
  padding: 0;
}
#two li {
  display: inline-block;
  margin: 5px 0 0 0;
}

Strategy

Visioning

Strategic Analysis

Strategy Formulation

Business Model Innovation

Financial Modeling

A: *{
  box-sizing: border-box;
}

This will remove padding as part of the width of all elements. Don't use '*' as a selector as it's quite heavy on the DOM.
#two {
  width: 80%;
}

Because 20% + 80% = 100%
#two li {
    display: inline-block;
}

This will add a width and a height to the li's


text:
Q: Why is pattern recognition often defined as an ill-posed problem? A Well-posed problem should have the following properties:

*

*a solution exists

*the solution is unique

*the solution's behavior changes continuously with the initial conditions.

A problem which is not well-posed is called ill-posed.
In some research papers, like this, pattern recognition is defined as an ill-posed problem.
Why do they define pattern recognition as an ill-posed problem?

A: Quoting Wikipedia

Inverse problems are often ill-posed. For example, the inverse heat equation, deducing a previous distribution of temperature from final data, is not well-posed in that the solution is highly sensitive to changes in the final data.

In pattern recognition (aka machine learning), the solutions would also depend on the choice of algorithm, hyperparameters, or even random seeds used for training.
Moreover, with pattern recognition it is not even guaranteed that the solution exists, e.g. if you are conducting cluster analysis, or classification given some data, there is no guarantee that this data is suitable for such analysis. Surely, the algorithms will try their best with finding some pattern given any data, but that doesn't mean that there was any real pattern.


text:
Q: Deuteron wave function The deuteron wave function is given by $$|\psi _d\rangle  = a|^3S_1\rangle+b|^3D_1\rangle$$
where all states are normalized. How do we find $b^2$ s.t. the wave function reproduces the magnetic moment of the deuteron:
$$\mu = 0.857 \mu _N$$ ?

A: One can write the magnetic momentum operator in the following form:
$$\mu=g_p\bf{s_p} +g_n\bf{s_n}+\frac{l}{2}$$ where $\bf l$ is a angular momentum, $g_p$ and $g_n$ are gyromagnetic ratio for proton and neutron respectively, $\bf{s}_p$ and $\bf{s}_n$ are sin operators.The coefficient $\frac{1}{2}$ in front of $\bf l$ is appear because of the contribution in magnetic momentum is given by $[r_p\times p_p]=\frac{1}{2}[r\times p]=\frac{1}{2}\bf l$.
Let's rewrite this formula via full deuteron momentum $J$.
$$\mu=\frac{g_p+g_n}{2}\bf{S}+\frac{g_p-g_n}{2}(s_p-s_n)+\frac{1}{2}\bf l$$
$$<\mu>=\frac{g_p+g_n}{2}\bf{<S>}-\frac{g_p+g_n-1}{2}\bf{<l>}$$
$$\mu=(\mu_p+\mu_n)\bf{J}-(\mu_p+\mu_n-\frac{1}{2})\frac{<Jl>}{J(J+1)}$$
$$\mu=(\mu_p+\mu_n)-(\mu_p+\mu_n-\frac{1}{2})\frac{3}{2}b^2$$
Where $\mu_p=g_p/2$.After substituting numbers we will set b^2=0.04
But it is not exactly number because of we use magnetic momentum operator is used for free nucleons.There is relativistic corrections for magnetic momentum operator.


text:
Q: Applying withColumn only when column exists in the dataframe I am using spark-sql-2.4.1v with Java 8. I have a scenario where I will be passed the columns names as list/Seq, for those columns only i need to do perform certain operations like sum, avg, percentages etc.
In my scenario, let's say I have column1, column2, column3 columns. First time I will pass column1 name.
Will pull/select "column1" data and perform some operation based on "column1". Second time I will pass column2 name, but earlier column1 not pulled this time so my dataset does not contain "column1" hence earlier conditions are breaking with error "AnalysisException: cannot resolve 'column1' given input columns".
Hence I need to check the columns, if some column exists then only perform that column related operations else ignore those operations.
How to do this in Spark?
Sample data which is in database.
val data = List(
  ("20", "score", "school", "2018-03-31", 14 , 12 , 20),
  ("21", "score", "school", "2018-03-31", 13 , 13 , 21),
  ("22", "rate", "school", "2018-03-31", 11 , 14, 22),
  ("21", "rate", "school", "2018-03-31", 13 , 12, 23)
 )
    val df = data.toDF("id", "code", "entity", "date", "column1", "column2" ,"column3")
.select("id", "code", "entity", "date", "column2") /// these are passed for each run....this set will keep changing.

  Dataset<Row> enrichedDs = df
             .withColumn("column1_org",col("column1"))
             .withColumn("column1",
                     when(col("column1").isNotNull() , functions.callUDF("lookUpData",col("column1").cast(DataTypes.StringType)))
                  );

The above logic is only applicable when in select columns "column1" is available. This is failing in the second set as "column1" is not select, so I need some understanding why this only applicable when selected columns as "column1" is available. I need some logic to achieve this.

A: check if this is helpful-
you can filter out columns, and process only valid columns
df.show(false)
    /**
      * +---+-----+------+----------+-------+-------+-------+
      * |id |code |entity|date      |column1|column2|column3|
      * +---+-----+------+----------+-------+-------+-------+
      * |20 |score|school|2018-03-31|14     |12     |20     |
      * |21 |score|school|2018-03-31|13     |13     |21     |
      * |22 |rate |school|2018-03-31|11     |14     |22     |
      * |21 |rate |school|2018-03-31|13     |12     |23     |
      * +---+-----+------+----------+-------+-------+-------+
      */
    // list of columns
    val cols = Seq("column1", "column2" ,"column3", "column4")
    val processColumns = cols.filter(df.columns.contains).map(sqrt)
    df.select(processColumns: _*).show(false)

    /**
      * +------------------+------------------+-----------------+
      * |SQRT(column1)     |SQRT(column2)     |SQRT(column3)    |
      * +------------------+------------------+-----------------+
      * |3.7416573867739413|3.4641016151377544|4.47213595499958 |
      * |3.605551275463989 |3.605551275463989 |4.58257569495584 |
      * |3.3166247903554   |3.7416573867739413|4.69041575982343 |
      * |3.605551275463989 |3.4641016151377544|4.795831523312719|
      * +------------------+------------------+-----------------+
      */

A: Not sure if i fully understand your requirement, but are you simply trying to perform some conditional operation depending on what columns are available in your dataframe which is not know prior to execution?
if so, Dataframe.columns returns a list of columns which you can parse and select accordingly
i.e
df.columns.foreach { println }


text:
Q: Invalid Root In Registry Key in reading IExplorer VBA I have a code that tries to run an IExplorer that would load a google map. Anyways, It bugs everytime it tries to run the code where it reads the HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\" & "App Paths\IEXPLORE.EXE\
with the error: Invalid Root in registry key

Dim obj_FSO As Object
Dim obj_Shell As Object
Dim str_IEVersion As String
Dim StrArray() As String
Dim iVersion As Integer

Set obj_FSO = CreateObject("scripting.filesystemobject")
Set obj_Shell = CreateObject("wscript.shell")

str_IEVersion = obj_FSO.GetFileVersion(obj_Shell.RegRead("HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\" & "App Paths\IEXPLORE.EXE\"))


text:
Q: How prove this $\frac{af(a)+bf(b)}{a+b}\ge f(a+b)$ Assume that
$f(x)$ has two derivatives  on $(0,2)$ and $0<a<b<a+b<2$.
I have to prove that, if $f(a)\ge f(a+b)$ and $f''(x)\le 0$, then:
$$\dfrac{af(a)+bf(b)}{a+b}\ge f(a+b).$$

I think we also have
$$f(b)\ge f(a+b)$$
so
$$af(a)+bf(b)\ge af(a+b)+bf(a+b)=(a+b)f(a+b)$$
But if this true, then we can prove it.

A: $f$ is a concave function in virtue of $f''(x)\leq 0$.
Assuming $f(b)<f(a+b)$, somewhere between $b$ and $a+b$ we must have $f'(\xi)>0$.
Moreover, somewhere between $a$ and $b$ we have $f'(\eta)<0$, since $f(a)>f(b)$.
So, somewhere between $\eta$ and $\xi$ we have $f''(\nu)>0$, contradiction.
This proves $f(b)\geq f(a+b)$.

A: Let's $l(x)=cx+d$ be the line that passes through points $(a,f(a))$ and $(a+b,f(a+b))$.
As $f(a)\ge f(a+b)$(therefore $l(a)\ge l(a+b)$) we have that for every $a\le x\le a + b$ $l(x)\ge l(a+b)$, in particular $l(b)\ge l(a+b)$.
But since $f$ is concave $f(b)\ge l(b)\ge l(a+b)= f(a+b).$


text:
Q: Using header files in C I'm having a couple of issues including custom libraries in my program
I have my main.c file and a library.c (where all the functions are stored) and library.h (where all the prototypes are stored).
In main.c I'm placing #include "library.h" but the functions don't get recognized when I try to compile.
Am I doing something wrong?
I'm using GCC to build the file.
test.c:
#include "library.h"

int main()
{
    int num = 5;
    sum(num);
}

library.c
#include "library.h"

int sum(int num)
{
    return num + 5;
}

library.h
#ifndef LIBRARY_H
#define LIBRARY_H

#include <stdio.h>

int sum(int num);

#endif

Getting error:

C:\Users\Gabriel\Desktop\test.o:test.c|| undefined reference to `sum'|

A: Including the header file is not sufficient. The prototype in the header file just tells the compiler that there should be a function.
You have to actually add the function to the program. That is done when linking. the simplest way would be
gcc -o myprog test.c library.c

There are more sophisticated option. If you want to add several files actually to a library you can compile them independently and build the archive. Here are some commmands that show the basic idea.
gcc -o library.o library.c
gcc -o someother.o someother.c
ar a libmy.a library.o someother.o

gcc -o myprog test.c -l my


text:
Q: Network instance error Here is my code in vb.net below. The problem with this connection string is that the system reads it, compiles it but when I'm trying to pass any input into the database it tells me network instance error.
You see here the original code for the connection:
  Module MyFunction
Public cnn As SqlClient.SqlConnection
Public Sub MakeConnection()
    cnn = New SqlClient.SqlConnection
    If Not cnn.State = ConnectionState.Open Then

        cnn.ConnectionString = System.IO.File.ReadAllText(Application.StartupPath & "\cnn.txt")
        cnn.Open()
    End If

This gives me error that "executereader is not initialized"
So I changed it like this:
    Public cnn As SqlClient.SqlConnection
Public Sub MakeConnection()
    cnn = New SqlClient.SqlConnection("Data Source=USARES-PC\SQLEXPRESS;Initial Catalog=HotelDB;Integrated Security=True")
    cnn.Open()
    '  MessageBox.Show("Connection opened!")
End Sub

I also tried this way:
       Public cnn As SqlClient.SqlConnection
    Public Sub MakeConnection()
     If cnn.State = ConnectionState.Open Then
        cnn.ConnectionString = "Data Source=USARES-PC\SQLEXPRESS;Initial       Catalog=HotelDB;Integrated Security=True"
          cnn.Close()
        End If


text:
Q: Apply/Register conflicting plugins to different charts I have defined two slightly different Chart.js plugins and I have a page with two different charts. I want to apply the first plugin to the first chart and the second to the second chart.
According to the source, there are a register and unregister function for plugins, but you register them to some global variable 'Chart.plugins'.
I have tried a solution like this:
Chart.plugins.register(plugin1);
window.myBar = new Chart(...);
Chart.plugins.unregister(plugin1);

Chart.plugins.register(plugin2);
window.myBar2 = new Chart(...);
Chart.plugins.unregister(plugin2);

but it appears this unregisters both plugins before anything happens. And if I do not unregister the plugins, the second overrides anything the first plugin does.
In addition it does not seem possible to register a plugin directly to a specific chart, as for example 'windows.myBar.plugins' is undefined.
Does anybody know if there exists a different solution?
Edit1: I thought of a possible workaround, namely by specifying the different behaviours of the plugins as options of the individual charts, and then define a single plugin that acts based on the specific options of a chart. But I would still like to know if there exists a way to apply plugins to a specific chart.

A: Currently Chartjs v2.9.4, from the chartjs documentation, if you have multiple charts, each chart's plugin can be defined in the chart's config, like this:
var ctx = document.getElementById("myChart").getContext('2d');
var chart = new Chart(ctx, {
    type: 'line',
    plugins: [{ //plugin added for this chart
        beforeInit: function(chart, options) {
            //Add statements here
        }
   }],
   options: {
      responsive: true, // Instruct chartjs to respond nicely.
      maintainAspectRatio: false
   },
   // And any other config options as you wish
});

A: I think a solution is to assign a specific property in your chart options for each plugin. Each chart will fill a different attribute to use each plugin. In your case, you have plugin1 and plugin2.
Then, in each definition you will check for different attributes to see if that chart is using that plugin or not. For example, your definitions will be something like:
Chart.pluginService.register({
  afterDraw: function(chart) {
    if (chart.config.options.plugin_one_attribute) {
      // Plugin code here...
    }
  }
});

To use this plugin, your chart will have to fill the plugin_one_attribute, in its options. Like this:
optionsUsingPlugin1 = {
  plugin_one_attribute: // Your variable to be used in the plugin goes here!
  responsive: true,
  maintainAspectRatio: true,
  title: {
    display: true
  }
  // And any other config options you are already using
}

And use this when creating your chart:
var myBar = new Chart(ctx, {
  type: 'bar',
  data: data,
  options: optionsUsingPlugin1
});

So, in order to use plugin2, your myBar2 chart will need a specific attribute for plugin2 (which will check for it when registering). This way you can control which plugins will be active in each chart.
Hope that helps!

A: This question is five years old. Nowadays, we can achieve this using plugins and hook calls in this case beforeTooltipDraw to capture the tooltip.caretX. Also we can use the build-in interaction option to achieve this.
This implementation works with versions 4.0.1 of ChartJS

const plugin = {
  id: 'customText',
  afterDraw: (chart, args, options) => {
    const {ctx} = chart
    texts = options.texts

    if (!texts || texts.length === 0) return

    ctx.save();
    for (const text of texts) {
        const align =  text.align || 'center'
        const size = text.size || '20px'
        const family = text.font || 'Arial'
        const color = text.color || 'black'
        const str = text.str ?? null
        const x = text.x || 0
        const y = text.y || 0

        if (!str) continue

        ctx.textAlign = align
        ctx.font = `${size} ${family}`
        ctx.fillStyle = color
        ctx.fillText(str, x, y)
    }

    ctx.restore();
  }
}

const data = {
  labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"],
  datasets: [{
    data: [12, 3, 2, 1, 8, 8, 2, 2, 3, 5, 7, 1]
  }]
}

const config = {
  type: 'line',
  data,
  options: {
    maintainAspectRatio: false,
    plugins: {
      customText: {
        texts: [{
            x: 300,
            y: 50,
            str: 'Custom',
            size: '30px',
            font: 'Arial black'
          },
          {
            x: 300,
            y: 120,
            str: 'Text',
            color: 'red',
          }
        ]
      }
    }
  },
  plugins: [plugin]
}

const $chart = document.getElementById('chart')
const chart = new Chart($chart, config)
<div class="wrapper" style="width: 98vw; height:180px">
  <canvas id="chart"></canvas>
</div>

<script src="https://npmcdn.com/chart.js@4.0.1/dist/chart.umd.js"></script>


text:
Q: Trouble groking cython memoryviews ... how do I implement here? Two functions: one which creates a 32-million integer array and another which uses it for a lookup millions of times.
from cpython cimport array as c_array
from array import array

def get_lut(file_location):
    cdef c_array.array lut
    with open(file_location, "rb") as f:
        lut = array("I", f.read())
    return lut

def use_lut(int[:] lut):
    // Do a whole bunch of lookups.

Compiling with the following command:
c:\Users\Michael\Documents\Poker>set DISTUTILS_USE_SDK=1
c:\Users\Michael\Documents\Poker>python setup.py build_ext -i --compiler=msvc

Produces the following output:
Compiling handeval.pyx because it changed.
Cythonizing handeval.pyx
warning: View.MemoryView:288:5: Cannot profile nogil function.
warning: View.MemoryView:763:5: Cannot profile nogil function.
warning: View.MemoryView:899:5: Cannot profile nogil function.
warning: View.MemoryView:1063:5: Cannot profile nogil function.
warning: View.MemoryView:1070:5: Cannot profile nogil function.
warning: View.MemoryView:1124:5: Cannot profile nogil function.
warning: View.MemoryView:1131:5: Cannot profile nogil function.
warning: View.MemoryView:1142:5: Cannot profile nogil function.
warning: View.MemoryView:1163:5: Cannot profile nogil function.
warning: View.MemoryView:1223:5: Cannot profile nogil function.
warning: View.MemoryView:1295:5: Cannot profile nogil function.
warning: View.MemoryView:1317:5: Cannot profile nogil function.
warning: View.MemoryView:1352:5: Cannot profile nogil function.
warning: View.MemoryView:1362:5: Cannot profile nogil function.
running build_ext
building 'handeval' extension
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\Bin\amd64\cl.exe /c /nolo
go /Ox /MD /W3 /GS- /DNDEBUG -IC:\Users\Michael\Anaconda3\include -IC:\Users\Mic
hael\Anaconda3\include /Tchandeval.c /Fobuild\temp.win-amd64-3.4\Release\handeva
l.obj
handeval.c
handeval.c(2391) : warning C4244: '+=' : conversion from 'Py_ssize_t' to 'long',
 possible loss of data
handeval.c(2420) : warning C4244: '+=' : conversion from 'Py_ssize_t' to 'int',
possible loss of data
handeval.c(2449) : warning C4244: '+=' : conversion from 'Py_ssize_t' to 'int',
possible loss of data
handeval.c(2478) : warning C4244: '+=' : conversion from 'Py_ssize_t' to 'int',
possible loss of data
handeval.c(2507) : warning C4244: '+=' : conversion from 'Py_ssize_t' to 'int',
possible loss of data
handeval.c(2536) : warning C4244: '+=' : conversion from 'Py_ssize_t' to 'int',
possible loss of data
handeval.c(2565) : warning C4244: '+=' : conversion from 'Py_ssize_t' to 'int',
possible loss of data
handeval.c(12955) : error C2275: 'PyGILState_STATE' : illegal use of this type a
s an expression
        C:\Users\Michael\Anaconda3\include\pystate.h(191) : see declaration of '
PyGILState_STATE'
handeval.c(12955) : error C2146: syntax error : missing ';' before identifier '_
_pyx_gilstate_save'
handeval.c(12955) : error C2065: '__pyx_gilstate_save' : undeclared identifier
handeval.c(13026) : error C2065: '__pyx_gilstate_save' : undeclared identifier
handeval.c(13052) : error C2275: 'PyGILState_STATE' : illegal use of this type a
s an expression
        C:\Users\Michael\Anaconda3\include\pystate.h(191) : see declaration of '
PyGILState_STATE'
handeval.c(13052) : error C2146: syntax error : missing ';' before identifier '_
_pyx_gilstate_save'
handeval.c(13052) : error C2065: '__pyx_gilstate_save' : undeclared identifier
handeval.c(13125) : error C2065: '__pyx_gilstate_save' : undeclared identifier
handeval.c(13152) : error C2275: 'PyGILState_STATE' : illegal use of this type a
s an expression
        C:\Users\Michael\Anaconda3\include\pystate.h(191) : see declaration of '
PyGILState_STATE'
handeval.c(13152) : error C2146: syntax error : missing ';' before identifier '_
_pyx_gilstate_save'
handeval.c(13152) : error C2065: '__pyx_gilstate_save' : undeclared identifier
handeval.c(13242) : error C2065: '__pyx_gilstate_save' : undeclared identifier
handeval.c(13909) : error C2275: 'PyGILState_STATE' : illegal use of this type a
s an expression
        C:\Users\Michael\Anaconda3\include\pystate.h(191) : see declaration of '
PyGILState_STATE'
handeval.c(13909) : error C2146: syntax error : missing ';' before identifier '_
_pyx_gilstate_save'
handeval.c(13909) : error C2065: '__pyx_gilstate_save' : undeclared identifier
handeval.c(13935) : error C2065: '__pyx_gilstate_save' : undeclared identifier
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\Bin\\
amd64\\cl.exe' failed with exit status 2

Whereas removing the int[:] type declaration from the use_lut signature compiles fine.
What am I doing wrong here?


text:
Q: Fit A Curve to a Histogram
Is there any possibility to fit a curve to that histogram above in Matlab?
The histogram is not normalized or anything like that.
I know that there is a function called histfit,but can i use it here?

A: Try this FileExchange submission:
ALLFITDIST - Fit all valid parametric probability distributions to data.
--- UPDATE ---
ALLFITDIST is no longer available on the MATLAB File Exchange.
You can try this instead:
FITMETHIS - finds best-fitting distribution to data vector, including non-parametric.

A: If you know the underlying distribution (i.e. skewed gaussian etc.), you can manually do a maximum likelihood estimate for the parameters of the distribution and then plot the resulting distribution on top of your histogram. However, you need to normalize your histogram so that you see empirical probabilities instead of the numbers.

A: I think what you want it to fit a distribution, not any curve that might not have finite area under the curve. Data looks like it's censored on the right tail, but over all it may fit log normal distribution or Gamma distribution pretty well. If you have stats toolbox, try gamfit or lognfit for starter.

A: See also Kernel density estimation
http://en.wikipedia.org/wiki/Kernel_density


text:
Q: create array they having same value for different label I create form in drupal to find a area.in which we have same value for differet key.when we write following array they will take only last key of same value like for family law it takes only Restraining Orders so how we can create array they will take same value for different label.
function form_test_form($form,&$form_state)
{
$area_one=array(
'Bankruptcy' =>'Bankruptcy',
'Criminal Defense' =>'Criminal Defense',
'Criminal Defense' =>'Driving Under Influence (of Drugs and or Alcohol)',
'Expungement' =>'Expungement',
'Family Law' =>'Family Law',
'Family Law' =>'Alimony',
'Family Law'=>'Child Custody',
'Family Law' =>'Child Visitation',
'Family Law' =>'Divorce',
'Family Law'=>'Restraining Orders',
'Employment' =>'Employment',
'Immigration'=>'Immigration',
'Immigration'=>'Deportation Defense',
'Personal Injury' =>'Personal Injury',
'Real Estate' =>'Real Estate',
'Taxation' =>'Taxation',
'Workers' Compensation Applicant'=>'Workers' Compensation',
'Wills, Trusts & Probate' =>'Wills, Trusts & Probate',
 );

$a=array_search('Family Law', array_reverse($area_one));
$form['Lawyername'] = array(
'#title' => t('Select Practice Areas'),
'#type' => 'select',
'#options' => $a,
'#required' => TRUE,
);

$form['Location'] = array(
'#title' => t('California County'),
'#type' => 'textfield',
'#autocomplete_path' => 'form_test-autocomplete-engine',
'#required' => TRUE,
);

 $form['submit'] = array(
 '#value' => 'Submit',
 '#type' => 'submit',
 );
 return $form;
 }

A: You could array_reverse() the array, and then use array_search() to retrieve the key, eg:
echo array_search('Family Law', array_reverse($area_one)); // 'Restraining Orders'

Demo


text:
Q: why click event is not working when its created on server I have:
On the client:
<asp:imagebutton id="icon2" runat="server" visible="false" imageurl="images/icon_info.gif" width="16" height="16" imagealign="AbsMiddle" style="cursor:pointer;" alternatetext=""></asp:imagebutton>

On the server:
System.Web.UI.WebControls.ImageButton icon2 = (System.Web.UI.WebControls.ImageButton)e.Item.FindControl("icon2");
icon2.AlternateText = string.Format(Sales.Common.Res.key("basket.message.material.change") + ". ", line.altMaterial, line.materialCode);
icon2.AlternateText = "";
icon2.Click += icon2_Click;

public void icon2_Click(object sender, ImageClickEventArgs e)
{
    //todo
}

But icon2_click is not working when i click this imagebutton.
Why?
I know about onClick on the client, but I should add this event on server because this image is not always clickable.


text:
Q: Google PUBSUB API: When a binding is made through IAM (for a specific resource), will same member get all access of that role? The is in reference to code at official page, where we want to give access to a user for a specific PUBSUB subscription: https://cloud.google.com/pubsub/docs/access-control#setting_a_policy
In the above code:

*

*Role roles/pubsub.editor is binded to member allUsers for specific resource like 'pubsub.your-subscription-id'; the resource policy is updated in same terms.

*As far as I know 'roles/pubsub.editor' role has all access to PUBSUB subscriptions and policies.

Q)After executing the above code, can we conclude that allUsers get all accesses that  role roles/pubsub.editor has? Or is this binding only specific to this resource's policy? As I am a newbie here, please help if my understandings are wrong here.

A: In Pub/Sub, access control can be configured at the project level and at the individual resource level.
If you assign IAM roles at the project level, that grants specific permissions to all Pub/Sub resources.
You can also grant access on a per-topic or per-subscription basis instead of granting access at the project level.

Q)After executing the above code, can we conclude that allUsers get
all accesses that role roles/pubsub.editor has? Or is this binding
only specific to this resource's policy?

The documentation link that you provided is granting a role at the resource level for a Subscription ID and not for all subscriptions in the project. The member all users is being granted the role roles/pubsub.viewer and not the role roles/pubsub.editor. This role is granted only for the Subscription ID and not for other Subscription IDs.
Note: the documentation is slightly wrong. It is using the term all users where it is actually granting permission to all authenticated users in the google.com domain which means anyone who is logged into Gmail, Google Cloud, etc.

As far as I know 'roles/pubsub.editor' role has all access to PUBSUB
subscriptions and policies.

That is not correct. The role roles/pubsub.editor is a collection of permissions. Those permissions can then be attached to resources via IAM bindings. If the resource is a project, then yes, all Pub/Sub resources under the project. If the resource is a subscription ID, then the permissions are granted only for that subscription ID.


text:
Q: Getting twice GCM PUSH notification when application is closed or application is in background I have implemented gcm push notification in my application. Everything is working fine and i am getting notifications as well.
Problem:

*

*When app is in background or terminated state i am getting 2 notifications at a time.

*When app is in foreground getting only 1 notification as i want.

App should get only 1 notification as requirement but unfortunately facing undefined situation.

My code below:
GCMPushReceiverService class for receiving message.
public class GCMPushReceiverService extends GcmListenerService {

//This method will be called on every new message received
@Override
public void onMessageReceived(String from, Bundle data) {
    //Getting the message from the bundle
    String message = data.getString("message");
    //Displaying a notiffication with the message
    Log.e("MeSs",""+message);
    sendNotification(this,message, "Traccar App");
    sendNotification(message);

}

//This method is generating a notification and displaying the notification  //When in front
private void sendNotification(Context context, String notificationText,
                              String notificationTitle) {

    PowerManager pm = (PowerManager) context
            .getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = pm.newWakeLock(
            PowerManager.PARTIAL_WAKE_LOCK, "");
    wakeLock.acquire();

    Intent intent = new Intent(this, Home.class);
    intent.putExtra("ChatFragment", "newChatFound");
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    int requestCode = 0;
    PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_ONE_SHOT);
    Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
            context)
            .setSmallIcon(R.drawable.bug_log_two)
            .setColor(Color.RED)
            .setContentTitle(notificationTitle)
            .setContentText(notificationText)
            .setDefaults(Notification.DEFAULT_ALL)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0, notificationBuilder.build()); //0 = ID of notification

    wakeLock.release();
}

private void sendNotification(String message) {
    Intent intent = new Intent(this, Home.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    int requestCode = 0;
    PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_ONE_SHOT);
    Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentText(message)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0, noBuilder.build()); //0 = ID of notification
}

}

manifest file code:
 <!-- GCM -->

    <receiver
        android:name="com.google.android.gms.gcm.GcmReceiver"
        android:exported="true"
        android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />

            <category android:name="com.vk.trackeruser" />
        </intent-filter>
    </receiver>

    <!-- GCM Receiver Service -->
    <service
        android:name=".Notification.GCMPushReceiverService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        </intent-filter>
    </service>

    <!-- GCM Registration Intent Service -->
    <service
        android:name=".Notification.GCMRegistrationIntentService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.android.gms.iid.InstanceID" />
        </intent-filter>
    </service>

GCMRegistrationIntentService class:
public class GCMRegistrationIntentService extends IntentService {
//Constants for success and errors
public static final String REGISTRATION_SUCCESS = "RegistrationSuccess";
public static final String REGISTRATION_ERROR = "RegistrationError";
public static final String SenderId = "my id with numeric number ex 9897979";
//Class constructor
public GCMRegistrationIntentService() {
    super("");
}

@Override
protected void onHandleIntent(Intent intent) {
    //Registering gcm to the device
    registerGCM();
}

private void registerGCM() {
    //Registration complete intent initially null
    Intent registrationComplete = null;

    //Register token is also null
    //we will get the token on successfull registration
    String token = null;
    try {
        //Creating an instanceid
        InstanceID instanceID = InstanceID.getInstance(getApplicationContext());

        //Getting the token from the instance id
        token = instanceID.getToken(SenderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

        //Displaying the token in the log so that we can copy it to send push notification
        //You can also extend the app by storing the token in to your server
        Log.w("GCMRegIntentService", "token:" + token);
      String  tokan = token;
        //on registration complete creating intent with success
        registrationComplete = new Intent(REGISTRATION_SUCCESS);

        //Putting the token to the intent
        registrationComplete.putExtra("token", token);
    } catch (Exception e) {
        //If any error occurred
        Log.w("GCMRegIntentService", "Registration error");
        registrationComplete = new Intent(REGISTRATION_ERROR);
    }
    //Sending the broadcast that registration is completed
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
    }

GCMTokenRefreshListenerService class:
public class GCMTokenRefreshListenerService extends InstanceIDListenerService{
  //If the token is changed registering the device again
    @Override
    public void onTokenRefresh() {
        Intent intent = new Intent(this, GCMRegistrationIntentService.class);
        startService(intent);
    }
}

Class for getting my GCM token:
   in oncreate {
    //Initializing our broadcast receiver
    mRegistrationBroadcastReceiver = new BroadcastReceiver() {

        //When the broadcast received
        //We are sending the broadcast from GCMRegistrationIntentService

        @Override
        public void onReceive(Context context, Intent intent) {
            //If the broadcast has received with success
            //that means device is registered successfully
            if(intent.getAction().equals(GCMRegistrationIntentService.REGISTRATION_SUCCESS)){
                //Getting the registration token from the intent
                String token = intent.getStringExtra("token");
                StaticContents.Gcm_token=token;
                Log.e("Token",""+token);
                //Displaying the token as toast
                Toast.makeText(getApplicationContext(), "Registration token:" + token, Toast.LENGTH_LONG).show();

                //if the intent is not with success then displaying error messages
            } else if(intent.getAction().equals(GCMRegistrationIntentService.REGISTRATION_ERROR)){
                //        Toast.makeText(getApplicationContext(), "GCM registration error!", Toast.LENGTH_LONG).show();
            } else {
                //          Toast.makeText(getApplicationContext(), "Error occurred", Toast.LENGTH_LONG).show();
            }
        }
    };

    //Checking play service is available or not
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());

    //if play service is not available
    if(ConnectionResult.SUCCESS != resultCode) {
        //If play service is supported but not installed
        if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            //Displaying message that play service is not installed
            //        Toast.makeText(getApplicationContext(), "Google Play Service is not install/enabled in this device!", Toast.LENGTH_LONG).show();
            GooglePlayServicesUtil.showErrorNotification(resultCode, getApplicationContext());

            //If play service is not supported
            //Displaying an error message
        } else {
            //          Toast.makeText(getApplicationContext(), "This device does not support for Google Play Service!", Toast.LENGTH_LONG).show();
        }

        //If play service is available
    } else {
        //Starting intent to register device
        Intent itent = new Intent(this, GCMRegistrationIntentService.class);
        startService(itent);
    }
}
 //Registering receiver on activity resume
@Override
protected void onResume() {
    super.onResume();
    Log.w("MainActivity", "onResume");
    LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
            new IntentFilter(GCMRegistrationIntentService.REGISTRATION_SUCCESS));
    LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
            new IntentFilter(GCMRegistrationIntentService.REGISTRATION_ERROR));
}

    //Unregistering receiver on activity paused
@Override
protected void onPause() {
    super.onPause();

LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);

}

Output 1: When the app in visible (foreground) only one notification is received.

Output 2: When app is closed or app is in background Getting 2 notifications.

A: 1. onMessageReceived function inside GCMPushReceiverService class is called once you receive a message from GCM.
Using  this
String message = data.getString("message");

you are parsing and storing the message in a variable called message.
The problem is that you are passing message to two functions
sendNotification(this,message, "Traccar App");
sendNotification(message);

and both the functions are building a notification and are showing the message you are passing to these two functions as 2 separate notifications.
Just comment out either of these two functions and check.
2. And to avoid duplicate notification, there is a way we can handle it.
Try Changing this -
PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_ONE_SHOT);

to
PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

If the problem is still there, please post the payload you are getting. And I would suggest to use FCM instead of GCM

A: You can use FCM Downstream not Upstream


text:
Q: How to unmarshal JSON into durations? What is the idiomatic way to unmarshal into time.Duration in Go? How can I make use of time.ParseDuration?

A: The lack of JSON marshaling and unmarshaling methods on time.Duration was an unfortunate oversight. This should hopefully be resolved in Go2 (see issue #10275).
You can, however, define your own type around time.Duration that supports marshaling to the string representation of the duration and unmarshaling from either the numeric or string representations. Here is an example of such an implementation:
package main

import (
    "encoding/json"
    "errors"
    "fmt"
    "time"
)

type Duration struct {
    time.Duration
}

func (d Duration) MarshalJSON() ([]byte, error) {
    return json.Marshal(d.String())
}

func (d *Duration) UnmarshalJSON(b []byte) error {
    var v interface{}
    if err := json.Unmarshal(b, &v); err != nil {
        return err
    }
    switch value := v.(type) {
    case float64:
        d.Duration = time.Duration(value)
        return nil
    case string:
        var err error
        d.Duration, err = time.ParseDuration(value)
        if err != nil {
            return err
        }
        return nil
    default:
        return errors.New("invalid duration")
    }
}

type Message struct {
    Elapsed Duration `json:"elapsed"`
}

func main() {
    msgEnc, err := json.Marshal(&Message{
        Elapsed: Duration{time.Second * 5},
    })
    if err != nil {
        panic(err)
    }
    fmt.Printf("%s\n", msgEnc)

    var msg Message
    if err := json.Unmarshal([]byte(`{"elapsed": "1h"}`), &msg); err != nil {
        panic(err)
    }
    fmt.Printf("%#v\n", msg)
}

https://play.golang.org/p/Zm6hpNR-ZJ2

A: Just to extend the previous answer. There is another way (very close to Tim's)
type Duration time.Duration

func (d Duration) MarshalJSON() ([]byte, error) {
    return json.Marshal(time.Duration(d).String())
}

func (d *Duration) UnmarshalJSON(b []byte) error {
    var v interface{}
    if err := json.Unmarshal(b, &v); err != nil {
        return err
    }
    switch value := v.(type) {
    case float64:
        *d = Duration(time.Duration(value))
        return nil
    case string:
        tmp, err := time.ParseDuration(value)
        if err != nil {
            return err
        }
        *d = Duration(tmp)
        return nil
    default:
        return errors.New("invalid duration")
    }
}


text:
Q: Linking Azure HDInsight spark application to a Azure EventHub using Java code How do I write a code to read messages from 1 EventHub to another after some processing in Azure HDInsight spark cluster application using JAVA code ?

A: I don't have an exact sample for what you need however a Databricks Spark cluster should not be so different than an HDI Spark cluster to setup. Look at this sample and see if you can move it to HDI - https://lenadroid.github.io/posts/connecting-spark-and-eventhubs.html