Q: Why am I getting a CSRF 403 from OAuth2 Proxy when running on GKE but not locally? I have a simple setup that is using OAuth2 Proxy to handle authentication. It works fine locally using minikube but when I try to use GKE when the oauth callback happens I get a 403 status and the the following message...

Login Failed: Unable to find a valid CSRF token. Please try again.

The offending url is http://ourdomain.co/oauth2/callback?code=J_6ao0AxSBRn4bwr&state=r_aFqM9wsSpPvyKyyzE_nagGnpNKUp1pLyZafOEO0go%3A%2Fip
What should be configured differently to avoid the CSRF error?

A: In my case it was because I needed to set the cookie to secure = false. Apparently I could still have secure true no problem with http and an IP but once I uploaded with a domain it failed.


Q: Local voltage regulatıon on large board with 12V - 24V power input - is it a good idea? I am designing a board for my Bachelors thesis. The board takes 12V - 24V as an input. The dimensions are 100mmx100mm. It will be a 4 layer board and has an onboard antenna, multiple sensors and a Raspberry Pi compute module 4 as well. I am thinking of reserving 1 layer as a power rail and 1 layer for GND. My question is:

*

*Should I regulate the 24V voltage into 3.3V & 5V near the VCC, use wide track width and then just use low pass filters near the Vin of ICs?

or

*Should I feed 24V into the power rail and regulate the voltage locally at multiple points on the board?

A: A single regulator for 5 volts and a single regulator for 3.3 volts is all you'll need by the sounds of it. Use your power layer to route 5 volt and 3.3 volt supplies but, try and place those regulators reasonably close to where they are needed. Don't forget to calculate heat dissipation of these regulators if linear types are used. I might consider using a buck regulator to generate the 5 volt and then tee-off 5 volts with a linear regulator for 3.3 volts.
The on-board antenna may require removal of any copper on all layers directly below it.

use wide track width and then just use low pass filters near the Vin
of ICs

Local decoupling capacitors to ground is probably all that is needed. Rarely, something like a ferrite bead or small value series resistor can improve things and a bit more rarely, a series inductor can help. It really depends on what the chips are and what the data sheets say about supply filtering.

A: Just a single 5V and 3V3 regulator, as Andy suggested. 5V is often better as a switcher unless current is very low, because a linear 5V regulator will have 19V across it, which tends to make it get hot. Decoupling caps are key - look at the data sheets for your chips. More is better, you can always leave a few unfitted if you go over the top. Insufficient decoupling leading to power rails being too noisy causes horrible problems and is equally horrible to diagnose and debug, usually requires another board spin with modern SMD devices. So be generous.
(EDIT) Another thing to keep in mind is that you generally want to power all your digital logic from one common supply at each voltage. Why?
Let's say you have a bunch of devices at nominal 5V, +/-10% (old fashioned example). However, let's say that the maximum voltage on a digital input is (Vcc + 0.6V)
If you power them from two separate regulators which are also 5V +/- 10%, you could be unlucky and have half your board running on 4.5V and the other half at 5.5V. Individual devices will not have a problem, but if a 5.5V device drives a 4.5V device, you just violated a constraint. So in general, try to keep things running off a common rail to avoid having to think about this.


Q: Centering images horizontally in container div when height is set to 100% Sorry if this has been answered - I've tried virtually all the tips I've already come across so far on centering images without any luck. This image just refuses to center horizontally!
JSFiddle here
HTML: (Note: images are note mine, just taken from google as examples)
Each image either receives "height:100%;" or "width:100%;" when loading depending on whether the height to width ratio is within or outside of the 4:3 ratio in landscape orientation.
This is done to ensure the image completely fills the containing div no matter what size and shape it is.

CSS:
The main outer div is set to conform to the constant aspect ratio of 4:3
The inner div adds a border internally to the outer div which must remain specifically sized.
div.imgOuter{
    float: left;
    position: relative;
    width: 33.3333%;
    padding-bottom: 25%;
    overflow:hidden;
    clear:none;
}
div.imgInner{
    position:absolute;
    top:0;bottom:0;left:0;right:0;
    overflow:hidden;
    text-align:center;
    border:2px solid #444;
    cursor:pointer;
}
div.imgInner>img{
    display:block;
    position:absolute;
    top:0;bottom:0;left:0;right:0;
    margin:auto;
}

.imgInner: I have tried text-align:center; tried additionally dimensioning with height and width @ 100%...
You'll notice in the fiddle that the second image is in a portrait orientation and sits perfectly as expected centered vertically.
If you take a landscape image and set the width to 100% instead of height, it also centers vertically without issue, leaving white space above and below its ratio is wider than 4:3.
Only when the height is 100% does the image default to left alignment seemingly ignoring the left and right positioning.
My only suspicion is that the div.imgOuter does not have a height, only a padding value. If thats the case then I'm stuck attempting to solve both scaling aspect ratios and center alignment :(
Any suggestions?

A: Fairly sure you can't do this with CSS alone--because any negative margin workarounds for horizontal and vertical centering only works when you can used fixed sizes (as using a negative percentage margin will take the percentage from the parent container rather than the element's original size.)
However, you can do this with JS.
http://jsfiddle.net/HkuMW/7/
So, we apply the percentage left and top to sit exactly in the middle (but from the image's top-left corner):
div.imgInner>img {
    display:block;
    position:absolute;
    top:50%;
    left:50%;
}

Then we use jQuery to re-position the image by finding out the exact pixel dimensions, halving it, and popping that in:
$('.imgInner > img').each(function (i) {
    var imgWidth = ((0 - parseInt($(this).css('width'))) / 2);
    var imgHeight = ((0 - parseInt($(this).css('height'))) / 2);

    $(this).css('margin-top', imgHeight);
    $(this).css('margin-left', imgWidth);
});

A: See if this answers your question.
http://jsfiddle.net/HkuMW/17/
You can change the background-size:100% auto; to background-size:auto 100%; if you need to swap the resizing method.


Q: Determining the 'weak link' in a Wireless Network When copying a file from my laptop to my PC or vice-versa on my wireless G network I only use about 20% of the available bandwidth (according to Windows Performance).  Both are connected at 54mbps though and the signal strength is 'full' on both the laptop and the PC.
I know that, in practice, nobody gets the full 54mbps from their network but as I'm working to setup a home streaming-media solution for multiple PCs, getting that 20% up to 40% or 50% will make a world of difference.
How do I tell which device is imposing the 20% or so limit - is it my PC's wireless card that is the 'slow one' or is it my laptop?  Is there anyway to test the speed of just one device at a time with some sort of networking tool?

A: You can use an internet speed-test such as this on both computers, to find if there are any differences between the two.
If no appreciable differences are found, then the router is the candidate. If the router has an ethernet connection, connect one computer via an ethernet cable and redo the test. If it's much better, then it's the wireless network that's the problem. If it's not better, then it's either a very slow router or more likely simply the line speed of your ISP.
Please note that the performance percentage as reported by Windows Performance is relative to your network card only, and not to your possible maximum network speed.

A: I found a possible option, although all I did was google search, and haven't tried it.
These should at least give you a starting place.

*

*WireShark http://www.wireshark.org/ - used at our office...

*PassMark's PerformanceTest
http://www.passmark.com/products/pt.htm - free trial


Q: i want to formate date using jquery or javascript I just want to know how can i format date in java script.
I have date string is.
2015-04-21T09:31:04+05:00

I need to convert this 21 April, 2015
Can any one help me ?
Thanks

A: Use JavaScript Date object.
var date = new Date("2015-04-21T09:31:04+05:00");
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
console.log(date.getDate() + ' ' + months[date.getMonth()] + ', ' + date.getFullYear());

A: If you are open to libraries and you plan to "heavily" use Date you have MomentJS which would do it easily:
moment().format('MMMM Do YYYY');  // April 22nd 2015
//or
moment("2015-04-21T09:31:04+05:00").format('MMMM Do YYYY'); // April 21nd 2015


Q: Deserialize/Parse JSON in Java I am searching a good and dynamic way to parse JSON in Java.
I've seen things such as:
List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("test");
for(int i = 0 ; i < array.length() ; i++){
    list.add(array.getJSONObject(i).getString("testKey"));
}

But that's not what I'm searching. In C# I had something like that:
dynamic results = JsonConvert.DeserializeObject<dynamic>(json);
info.Text = results["test"]["testKey"];

Here's an example of my JSON:
{"date":"07.05.2017 11:44",
"monday":{"1":{"subject":"test","room":"test","status":"test"}}}

So for example I would like to make:
results["monday"]["1"]["subject"];

I hope someone understands my problem and can help me.
Thanks in advance!

A: The core Java runtime does not offer a JSON parser (edit: technically, it does, see bottom of answer), so you will need a library. See Jackson, Gson, perhaps others.
Even with that, you will not get the dynamic features you want, because Java is statically typed. Example with Jackson:
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue(json, new TypeReference<Map<String, Object>>(){});

    map.get("monday").get("1").get("subject");
                      ^^^
                      This fails because the result of get("monday") is Object, not Map

The "right" approach in Java-land, would be to create a class (or set of classes) that represents your JSON model, and pass it to the JSON parser's "object mapper". But you said "dynamic" so I'm not exploring this here.
So you'll need to cast to Map when you know it's not primitive values:
      ((Map<String,Map<String,String>>)map.get("monday")).get("1").get("subject");
This works but with a warning about unchecked cast...
All in all, Java is not a dynamic language and I see no way to do exactly what you want (perhaps I'm missing approaches that are still slightly easier than what I have suggested).
Are you limited to Java-the-language or Java-the-platform? In the latter case you can use a dynamic language for the Java platform, such as Groovy, who has excellent features to parse JSON.
EDIT: a funny alternative is to use Java's own JavaScript implementation. This works and is easy and dynamic, but I don't know if it's "good":
    String json = "{\"date\":\"07.05.2017 11:44\",\n" +
            "\"monday\":{\"1\":{\"subject\":\"test\",\"room\":\"test\",\"status\":\"test\"}}}";
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
    engine.put("data", json);
    System.out.println(engine.eval("JSON.parse(data)['monday']['1']['subject']"));

A: If you are sure about the value you want to get then you can do following as well :
String str = "{\"date\":\"07.05.2017 11:44\", \"monday\":{\"1\":{\"subject\":\"test\",\"room\":\"test\",\"status\":\"test\"}}}";
JSONObject results= new JSONObject(str);
String str1 = results.getJSONObject("monday").getJSONObject("1").getString("subject");
System.out.println(str1);

For array kind of results, we have to write logic for that. In this case org.json library is used.

A: You can use GCON library:
https://github.com/google/gson
Very good for parsing JSON objects.


Q: What is the proper way to write assert statements in javascript in development that is meant to be easily stripped away in production? There are functions and methods in my javascript code base that need to have assert statements to check for invalid arguments passed in. But these assertion statements should be stripped away when in production.
How are these assertion statements written in modern ES6 in development and how are they stripped away in production?


Q: multiple instances of the same sound on iOS i'm making a bubble popping game and hit a bit of a snag :/
i have a sound (pop.mp3), this sound needs to play EVERY time one of the bubbles are tapped
all the bubbles are buttons that call the same method (-(IBACTION)bubblePop)
i initialised an AVAudioPlayer in the Viewdidload method
and call it's play function inside the bubblePop method
this clearly did not work however because the bubble's pop sound only plays one at a time, it doest overlap like i would expect it to
does anybody know how i can resolve this?
Extra info
if i initialise the audio player inside bubblePop i get no sound at all

A: You should initialize AVPlayer inside bubblePop and keep strong reference to it.
Try this:
@interface ViewController()
@property (strong, nonatomic) NSMutableDictionary *players;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.players = [[NSMutableDictionary alloc] init];
}

- (void)bubblePop {
    NSURL *URL = your sound URL;

    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:URL];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:playerItem];

    AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
    self.players[playerItem] = player;

    [player play];
}

-(void)itemDidFinishPlaying:(AVPlayerItem *)sender {
    [self.players removeObjectForKey:sender];
}
@end


Q: Entity framework - Return to list error? I got the problem - return to list from the entity framework. I need to return as a object. Here is my code:
Public Function GetHardwareDetail() As List(Of HardwareDetailApp)
        Dim idList As New List(Of String)
        Dim Data = (From p In DB.TT_HARDWARE Select New HardwareDetailApp With {.InternalNum = p.INTERNAL_NUM, .Description = p.DESCRIPTION, .TerminalModel = p.HARDWARE_MODEL, .HardwareInternalNum = p.HARDWARE_ID, .Status = p.ISACTIVE, .Firmware = Nothing, .SerialNum = Nothing})

       If Data.Count > 0 Then
            For Each row In Data
                idList.Add(row.InternalNum)
            Next
       End If

       Dim Data2 = (From p In DB.TT_TERMINAL_HARDWARE Where idList.Contains(p.HARDWARE_INTERNAL_NUM)
              Select New HardwareDetailApp With
              {.Firmware = p.HARDWARE_FIRMWARE, .SerialNum = p.HARDWARE_SERIAL_NUM, .InternalNum = Data.FirstOrDefault.InternalNum, .Description = Data.FirstOrDefault.Description, .TerminalModel = Data.FirstOrDefault.TerminalModel, .HardwareInternalNum = Data.FirstOrDefault.HardwareInternalNum, .Status = Data.FirstOrDefault.Status})

       Return Data2.ToList
End Function

This is the error which I get:

The type 'HardwareDetailApp' appears in two
  structurally incompatible initializations within a single LINQ to
  Entities query. A type can be initialized in two places in the same
  query, but only if the same properties are set in both places and
  those properties are set in the same order.

A: in your code, you have created from HardwareDetailApp in two place, in every creation of that you must set the same property with same order.
for example if in linq to entity you Select something like:
Place1:

...
Select new MyClass()
{
    PropA: 1,
}
...

and in that query you need to another Select from MyClass but with some other properties like PropB, Like:
Place2:

...
Select new MyClass()
{
    PropB: 2,
}
...

you must change all Select from MyClass into same, and set the properties you dont need to them, to its default, and set the properties in same order like:
Place1:

...
Select new MyClass()
{
    PropA: 1,
    PropB: default(int),
}
...

and
Place2:

...
Select new MyClass()
{
    PropA: default(int),
    PropB: 2,
}
...

my codes are in c#..
in this part of your code Dim Data = (From p In DB.TT_HARDW .... try to set Firmware and SerialNum at first like the second select, (i have not checked other properties carefully)


Q: Asp.Net MVC and Strategy pattern I have an MVC application that uses Entity Framework.  I am using a repository, unit of work and unity as dependency injection.
The problem I have is that I have different authentication types, and each type I want a different class, so I decided to use the Strategy pattern
    public interface IAuthStrategy
    {
        OperationResponse<AuthenticationMechanismDTO> GetAuthenticationMechanism(string userName);
    }

    public class AuthStrategy
    {
        readonly IAuthStrategy _authStrategy;

        public AuthStrategy(IAuthStrategy authStrategy)
        {
            this._authStrategy = authStrategy;
        }

        public OperationResponse<AuthenticationMechanismDTO> GetAuthenticationMechanism(string userName)
        {
            return _authStrategy.GetAuthenticationMechanism(userName);

        }

    }

    public class UserNamePasswordMechanism : IAuthStrategy
    {

        private IInstitutionRepository _institutionRepository;

        public UserNamePasswordMechanism(IInstitutionRepository institutionRepository)
        {
            this._institutionRepository = institutionRepository;
        }

        public OperationResponse<AuthenticationMechanismDTO> GetAuthenticationMechanism(string userName)
        {

            throw new NotImplementedException();
        }
    }

My problem is that I am injecting IAuthStrategy into the controller, and it gives me an error, because instead of implementing IAuthStrategy, I am passing that to AuthStrategy constructor, as you can see that in my code.
How can I fix this error?
Here is my controller
 public class EmployeeController : ApiController
        {

            private IAuthStrategy _auth;

            public EmployeeController(IAuthStrategy auth)
            {
                this._employeeBL = employeeBL;
                this._auth = auth;

            }}
    }

Here is unity config where i am registering my types
public class UnityConfig
    {
        #region Unity Container
        private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
        {
            var container = new UnityContainer();
            RegisterTypes(container);
            return container;
        });

        /// <summary>
        /// Gets the configured Unity container.
        /// </summary>
        public static IUnityContainer GetConfiguredContainer()
        {
            return container.Value;
        }
        #endregion

        /// <summary>Registers the type mappings with the Unity container.</summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to
        /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>

   public static void RegisterTypes(IUnityContainer container)
    {
        // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
        // container.LoadConfiguration();

        // TODO: Register your types here

        container.RegisterType<IInstitutionRepository, InstitutionRepository>();

        container.RegisterType<IAuthStrategy, AuthStrategy>();

        GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);

    }
}

A: Your unit registrations and classes look a little off.
From what I can gather, this is what you really want to do.
Setup a factory that will determine at runtime which IAuthStrategy should be used:
public interface IAuthStrategyFactory
{
    IAuthStrategy GetAuthStrategy();
}

public class AuthStrategyFactory : IAuthStrategyFactory
{
    readonly IAuthStrategy _authStrategy;

    public AuthStrategy(...)
    {
        //determine the concrete implementation of IAuthStrategy that you need
        //This might be injected as well by passing
        //in an IAuthStrategy and registering the correct one via unity  at startup.
        _authStrategy = SomeCallToDetermineWhichOne();
    }

    public IAuthStrategy GetAuthStrategy()
    {
        return _authStrategy;
    }
}

This is your existing AuthStrategy:
public interface IAuthStrategy
{
    OperationResponse<AuthenticationMechanismDTO> GetAuthenticationMechanism(string userName);
}

public class UserNamePasswordMechanism : IAuthStrategy
{

    private IInstitutionRepository _institutionRepository;

    public UserNamePasswordMechanism(IInstitutionRepository institutionRepository)
    {
        this._institutionRepository = institutionRepository;
    }

    public OperationResponse<AuthenticationMechanismDTO> GetAuthenticationMechanism(string userName)
    {

        throw new NotImplementedException();
    }
}

Register the factory with unity:
container.RegisterType<IAuthStrategyFactory, AuthStrategyFactory>();

In your controller:
public class EmployeeController : ApiController
{
    private IAuthStrategy _auth;

    public EmployeeController(IAuthStrategyFactory authFactory)
    {
        this._employeeBL = employeeBL;
        this._auth = authFactory.GetAuthStrategy();
    }
}

A: Actually i missed implemented IAuthStrategyFactory on AuthStrategyFactory, once i implemented and register in unity container that worked.
Thanks


Q: Validating the inequality. $x-\frac{x^2}{2}+\frac{x^3}{3(1+x)}<\log(1+x)<x-\frac{x^2}{2}+\frac{x^3}{3}$, $x>0$
Here I can only see that the right side of second inequality i.e. $x-\frac{x^2}{2}+\frac{x^3}{3}$ comes in the expansion of $\log(1+x)$.
We have done the Lagrange's mean value theorem and intermediate value theorem, do these have anything to do with the inequality.
Kindly provide some hint.

A: defining $$f(x)=x-\frac{x^2}{2}+\frac{x^3}{3}-\ln(1+x)$$ for $x=0$ we get $$f(0)=0$$ and $$f'(x)=1-x+x^2-\frac{1}{x+1}=\frac{(1-x+x^2)(1+x)-1}{x+1}=\frac{x^3}{1+x}>0$$ for $x>0$ thus our function is monotonously increasing and we get $$f(x)>0$$ for all $$x>0$$

A: I expand my comment into an answer.

We have for $t > 0$ $$\frac{1}{1 + t} = 1 - t + \frac{t^{2}}{1 + t}$$ and hence if $0 < t < x$ then $$1 - t + \frac{t^{2}}{1 + x} < \frac{1}{1 + t} < 1 - t + t^{2}$$ and integrating the above with respect to $t$ on interval $[0, x]$ we get $$x - \frac{x^{2}}{2} + \frac{x^{3}}{3(1 + x)} < \log(1 + x) < x - \frac{x^{2}}{2} + \frac{x^{3}}{3}$$


Q: Using reflection throws error in EF Core 3 We formerly used reflection to create linq queries, e.g. for the GetById method:
private IQueryable<T> GetQueryById(TKey id)
{
    var query = _dbset; //DbSet<T>

    var keyNames = _context.Model
            .FindRuntimeEntityType(typeof(T))
            .FindPrimaryKey()
            .Properties
            .Select(x => x.Name)
            .ToList();

    if (keyNames.Count() == 1)
    {
        query = query.Where(e => e.GetType().GetProperty(keyNames[0]).GetValue(e, null)
           .Equals(id)); //throws error
    }

    return query;
}

This does not seem to work any more in EF Core 3:

The LINQ expression 'DbSet
.Where(c => c.GetType().GetProperty(__get_Item_0).GetValue(
obj: c,
index: null).Equals((object)__id_1))' could not be translated.

Is it possible to rewrite the query so that EF Core does not complain?

A: You have to create predicate dynamically:
private IQueryable<T> GetQueryById(TKey id)
{
    IQueryable<T> query = _dbset; //DbSet<T>

    var keyNames = _context.Model
            .FindRuntimeEntityType(typeof(T))
            .FindPrimaryKey()
            .Properties
            .Select(x => x.Name)
            .ToList();

    if (keyNames.Count == 1)
    {
        var keyExpression = Expression.Constant(id);
        var entityParam   = Expression.Parameter(typeof(T), "e");
        var body          = Expression.Equal(Expression.PropertyOrField(entityParam, keyNames[0]), keyExpression);
        var predicate     = Expression.Lambda<Func<T, bool>>(body, entityParam);

        query = query.Where(predicate);
    }
    else
      // better to throw exception
      throw new Exception($"Cannot find entity key.");

    return query;
}


Q: Android: App crashes when doing httpclient.execute in AsyncTask i'm having problems with httpclient. I debugged the app and it crashes when calling execute function. Here's the code:
public class MyAsyncTask extends AsyncTask<String, String, String> {
GridView mGridView;
Activity mContex;

public MyAsyncTask(Activity contex) {
    this.mContex = contex;
}

@Override
protected String doInBackground(String... params) {

    //fetch data

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("localhost:3000/api/send");

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("email", params[1]));
        nameValuePairs.add(new BasicNameValuePair("name", params[0]));
        nameValuePairs.add(new BasicNameValuePair("gender", "male"));
        nameValuePairs.add(new BasicNameValuePair("result", "lazy bee"));
        nameValuePairs.add(new BasicNameValuePair("age", "28"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }

    return "success";
}
}

I call MyAsyncTask here, from a fragment and passing the activity:
public class SendResultPageFragment extends Fragment implements View.OnClickListener {

EditText name, email;
MyAsyncTask task;

public static SendResultPageFragment newInstance() {
    return new SendResultPageFragment();
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_screen_slide_send_result, container, false);

    rootView.findViewById(R.id.result_next_button).setOnClickListener(this);

    name = (EditText)rootView.findViewById(R.id.name_txt);
    email = (EditText)rootView.findViewById(R.id.email_txt);

    return rootView;
}

@Override
public void onClick(View view) {
    this.task = new MyAsyncTask(getActivity());
    this.task.execute(this.name.getText().toString(), this.email.getText().toString());
    return ;
    }
}

Does anybody know the solution ? Thanks

A: new HttpPost("localhost:3000/api/send"); every http request needs to be fully qualified. also do not use local host.Android wont recognize your endpoint that way. I always use ngrok to broadcast to internet. switch to
new HttpPost("http://your_domain");

also switch to retrofit2, it uses java annotations to compose its request. Highly recommended. here is a great link to start:https://futurestud.io/tutorials/retrofit-getting-started-and-android-client


Q: what option controls numeric brace expansion in zsh? I'm getting a really weird bug on one of my zsh installations. I can do this:
for k in {1..6}; do echo $k; done
# 1
# 2
# 3
# 4
# 5
# 6

but I can't step through it:
for k in {1..6..2}; do echo $k; done
# {1..6..2}

I'm sure my current shell is zsh, and in a different computer it works, so I'm just wondering what option I might have set that changed the default behavior. Any ideas?

A: While the {x..y} syntax originated in zsh decades ago, ksh93 was the one adding the {x..y..step} one and zsh only added it in version 4.3.10-test-3 in 2010.
You probably have an older version of zsh there.


Q: overlapping floats: z-index doesn't work I'm trying to write a horizontal navigation bar with simple drop down menus (again horz). The main menu displays fine. To hide the submenus when not hovering, I did
ul#submenu {
    visibility: hidden;
    display: inline;
    position: absolute;
    top: 10pt;left: 0;
}

ul#mainmenu li:hover ul#submenu li {
    visibility: visible;
    position: relative;
    float: right;
}

The visibility and appear on hover work fine. However, part of the submenu gets hidden under the float right below. I tried setting z-index: 0 for that and z-index: 1 for the submenus, but it still doesn't work. How do I bring it to the top?

A: Check if overflow: hidden; or overflow: auto is set in the parent div. That could prevent it from showing up.


Q: How to change viewport of 2D image? I'm developing a mobile app for money recognition. Now I'm trying to build the database for this app.
The next step is generate some image from an original image in different view. Here is the example:
Original:

View 1:

As you can see in above image, the view 1 image is view of original from left edge. What I want to do is generate 4 image from original with 4 view from left, right, bottom, up. With the very large number of image, I can not use camera to capture so I need a write a program to do this work. But I can not found any thing about this issue.
Please tell me are there any tools to do what I need? or any library, framework support this? I can code on MATLAB and openCV.
Thanks for your help.

A: You can do the following:

*

*you assume that your original image is looking with 90 degree angle on a planar object

*you assume some camera intrinsic parameters (e.g. focal point in the middle of the image and uniform pixel size), some camera extrinsics (e.g. looking "down" with some position from above the plane) and some plane coordinates (xy-plane). This will result in every pixel to lie on some coordinates of the plane.

*you change your camera extrinic parameters by rotating around the camera center

*you project some (4 or more) plane positions to your camera image (e.g. use cv::projectPoints()).

*you compute the perspective homography that describes the pixel "motion" between both camera views (input pixel positions are those projected plane positions and the same plane positions in your original image)

*remember that homography for each chosen view.

*for each image, just use those homographies, you don't have to recompute them because they are the same for each image.
EDIT:
this is how it looks like in action (sorry for ugly code):
cv::Mat getRotationMatrixAroundY(double angle)
{
    cv::Mat rVec;

    cv::Mat deg45 = cv::Mat::zeros(3,3,CV_64FC1);
    double cos45 = cos(CV_PI*angle/180.0);
    double sin45 = sin(CV_PI*angle/180.0);

    // different axis:
    /*      deg45.at<double>(1,1) = cos45;      deg45.at<double>(1,2) = sin45;      deg45.at<double>(0,0) = 1;      deg45.at<double>(2,1) = -sin45;     deg45.at<double>(2,2) = cos45;      */

    /*      deg45.at<double>(0,0) = cos45;      deg45.at<double>(0,1) = in45;       deg45.at<double>(2,2) = 1;      deg45.at<double>(1,0) = -sin45;     deg45.at<double>(1,1) = cos45;      */

    deg45.at<double>(0,0) = cos45;
    deg45.at<double>(0,2) = sin45;
    deg45.at<double>(1,1) = 1;
    deg45.at<double>(2,0) = -sin45;
    deg45.at<double>(2,2) = cos45;

    cv::Rodrigues(deg45, rVec);

    return rVec;
}

// banknode training sample generator
int main()
{
    cv::Mat input = cv::imread("../inputData/bankNode.jpg");

    std::vector<cv::Point3f> pointsOnPlane;

    pointsOnPlane.push_back(cv::Point3f(0-input.cols/2,0-input.rows/2,0));
    pointsOnPlane.push_back(cv::Point3f(input.cols-input.cols/2,0-input.rows/2,0));
    pointsOnPlane.push_back(cv::Point3f(input.cols-input.cols/2,input.rows-input.rows/2,0));
    pointsOnPlane.push_back(cv::Point3f(0-input.cols/2,input.rows-input.rows/2,0));

    std::vector<cv::Point2f> originalPointsInImage;
    originalPointsInImage.push_back(cv::Point2f(0,0));
    originalPointsInImage.push_back(cv::Point2f(input.cols,0));
    originalPointsInImage.push_back(cv::Point2f(input.cols,input.rows));
    originalPointsInImage.push_back(cv::Point2f(0,input.rows));

    std::cout << "original pixel positions:" << std::endl;
    for(unsigned int i=0; i<originalPointsInImage.size(); ++i)
        std::cout << originalPointsInImage[i] << std::endl;

    cv::Mat cameraIntrinsics = cv::Mat::eye(3,3,CV_64FC1);

    cameraIntrinsics.at<double>(0,0) = 500.0;
    cameraIntrinsics.at<double>(1,1) = 500.0;
    cameraIntrinsics.at<double>(0,2) = input.cols/2.0;
    cameraIntrinsics.at<double>(1,2) = input.rows/2.0;

    std::vector<double> distCoefficients;

    cv::Mat rVec;
    cv::Mat tVec;
    cv::solvePnP(pointsOnPlane, originalPointsInImage, cameraIntrinsics, distCoefficients, rVec, tVec);

    // let's increase the distance a bit
    tVec = tVec*2;
    double angle = -45; // degrees

    cv::Mat rVec2 = getRotationMatrixAroundY(angle);

    // TODO: how to "add" some rotation to a previous rotation in Rodrigues?!?
    // atm just overwrite:

    std::vector<cv::Point2f> projectedPointsOnImage;
    cv::projectPoints(pointsOnPlane, rVec2, tVec, cameraIntrinsics, distCoefficients, projectedPointsOnImage);

    cv::Mat H = cv::findHomography(originalPointsInImage, projectedPointsOnImage);

    cv::Mat warped;
    cv::warpPerspective(input, warped, H, input.size());

    cv::imshow("input", input);
    cv::imshow("warped", warped);
    cv::waitKey(0);
    return 0;
}

with this result:

as you can see there is one problem: the rotation isn't around the center of the banknode. If someone can fix that, the result will be better. Atm I had to scale the translation part, this might not be necessary afterwards. Probably the problem occurs because of wrong translation + rotation combination.
for comparison: tranlation scaled by 1.5:

and not scaled:

Is this what you wanted to achieve (if the viewing center of the camera could be fixed at the middle of the banknode)?

A: Look here for a Projective Transformation using Matlab. You only have to find the right warping matrices (so-called homographies). You can build them with the mathematics on wikipedia, given a rotation matrix and an assumed camera intrinsics.
However, I think synthetically created training data possibly causes some problems regarding your task. The reflecting parts of bank notes are engineered to look different from different view points. You'll lose information.
Further, do not underestimate the effort, which will be necessary to develop this. There is quite sophisticated research going on in this field.
See here:
Towards Mobile Recognition and Verification of Holograms using Orthogonal Sampling
Mobile User Interfaces for Efficient Verification of Holograms


Q: How do I save a byte[] returned from a WCF call? In the code behind of my web page, I call a WCF service. The service returns a byte[] representing a file. In the code behind I have the following line that captures the bytes.
byte[] bytes = client.GeneratePDFBytes(crObj);

The question is, now what do I do with it? I want the user to be prompted to open/save the file. How do I add this functionality? I'm new to services and web stuff so it's likely something really simple but I'm overlooking it.

A: You can use the following:
 Response.ContentType = "application/pdf";
 Response.BinaryWrite(bytes);

A: Don't get hung up on the fact that you retrieved the byte array from a WCF service.  Once you have the result stored in a byte array, you're looking at the exact same technique for writing to disk as if you read it out of a database or off the file system.  If you change you research from WCF to flat-out reading/writing bytes I think you'll have better luck.  Here's one from SO that had some good suggestions:
C# - How do I read and write a binary file?
Edit:  I somehow managed to miss that this was ASP.NET...  sorry about that, you have to write to response and set content type to binary then, as other answers have provided examples for.


Q: Deserializing DbGeometry with Newtonsoft.Json I'm building a SPA using Angular,Breeze and Web API 2 following the approach as outlined by John Papa in his latest PluralSight course.
Everything works well and I can pull information, update, insert, delete back to the server. However I'm using Spatial Types, and when I try to update an entity with a spatial type I get the following error

An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in
      Newtonsoft.Json.dll but was not handled in user code
Additional information: Error getting value from 'WellKnownValue' on
      'System.Data.Entity.Spatial.DbGeometry'.

The inner exception seems to point to the fact that the WellKnownValue is null, its not though, as I have checked the JSON being sent to the server which is then sent to the Breeze ContextProvider and saved using the SaveChanges method.
{
"entities": [
 {
  "TableKey": 2,
  "CaseName": "Mikhail Lermontov",
  "StartDate": "2013-06-11T00:00:00Z",
  "EndDate": null,
  "IsCurrent": true,
  "SRID": 109,
  "Shape": {
    "$id": "2",
    "$type": "System.Data.Entity.Spatial.DbGeometry, EntityFramework",
    "Geometry": {
      "$id": "3",
      "$type": "System.Data.Entity.Spatial.DbGeometryWellKnownValue, EntityFramework",
      "CoordinateSystemId": 2193,
      "WellKnownText": "POLYGON ((1695943 5462665, 1713098 5462665, 1713098 5449659, 1695943 5449659, 1695943 5462665))"
    }
  },
  "SpillLocation": "Marlborough Sounds",
  "Image": "http://www.nzmaritime.co.nz/images/lm5.jpg\r\n",
  "DefaultBaseMapKey": 2,
  "__unmapped": {
    "isPartial": false
  },
  "entityAspect": {
    "entityTypeName": "DatSpillCase:#Osiris.Model",
    "defaultResourceName": "DatSpillCases",
    "entityState": "Modified",
    "originalValuesMap": {
      "CaseName": "Mikhail Lermontov"
    },
    "autoGeneratedKey": {
      "propertyName": "TableKey",
      "autoGeneratedKeyType": "Identity"
    }
  }
}
 ],
  "saveOptions": {}
}

So my question is, is possible to deserialize DbGeometry types within the NewtonSoft library, and if not, what suggestions are there to get around that.

A: The answer above works great, but is hardcoded for SRID (CoordinateSystemId) 2193.
The Coordinate System Id can however be present in the serialised data as shown in the question, or it can be present in the WellKnownText "SRID=2193;POINT (0 0)". Also this method will only read a polygon, but the WellKnownText can be a lot of things, like Geometry Collections, Point, Linestring, etc. To retreive this the ReadJson method can be updated to use the more generic FromText method as shown below.
Here is the class above updated with a more generic Coordinate System, and also for any Geometry Type. I have also added the Geography version for reference.
public class DbGeometryConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType.IsAssignableFrom(typeof(string));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject location = JObject.Load(reader);
        JToken token = location["Geometry"]["WellKnownText"];
        string value = token.ToString();
        JToken sridToken = location["Geometry"]["CoordinateSystemId"];
        int srid;
        if (sridToken == null || int.TryParse(sridToken.ToString(), out srid) == false || value.Contains("SRID"))
        {
            //Set default coordinate system here.
            srid = 0;
        }

        DbGeometry converted;
        if (srid > 0)
            converted = DbGeometry.FromText(value, srid);
        else
            converted = DbGeometry.FromText(value);
        return converted;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        // Base serialization is fine
        serializer.Serialize(writer, value);
    }
}

public class DbGeographyConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType.IsAssignableFrom(typeof(string));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject location = JObject.Load(reader);
        JToken token = location["Geography"]["WellKnownText"];
        string value = token.ToString();
        JToken sridToken = location["Geography"]["CoordinateSystemId"];
        int srid;
        if (sridToken == null || int.TryParse(sridToken.ToString(), out srid) == false || value.Contains("SRID"))
        {
            //Set default coordinate system here.
            //NOTE: Geography should always have an SRID, and it has to match the data in the database else all comparisons will return NULL!
            srid = 0;
        }
        DbGeography converted;
        if (srid > 0)
            converted = DbGeography.FromText(value, srid);
        else
            converted = DbGeography.FromText(value);
        return converted;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        // Base serialization is fine
        serializer.Serialize(writer, value);
    }
}

A: System.Data.Spatial.DbGeometry does not play nicely with Newtonsoft.Json
You need to create a JsonConverter to convert the DbGeometry
public class DbGeometryConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType.IsAssignableFrom(typeof(string));
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject location = JObject.Load(reader);
            JToken token = location["Geometry"]["WellKnownText"];
            string value = token.ToString();

            DbGeometry converted = DbGeometry.PolygonFromText(value, 2193);
            return converted;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            // Base serialization is fine
            serializer.Serialize(writer, value);
        }
    }

Then on your property in your model add the attribute
[JsonConverter(typeof(DbGeometryConverter))]
public DbGeometry Shape { get; set; }

Now when you hit your BreezeController the deserialization will be handled by our new  DbGeometryConverter.
Hope it helps.

A: I don't see why not. On the line with (DbGeometryWellKnownValue):
"$type": "System.Data.Entity.Spatial.DbGeometryWellKnownValue, EntityFramework",

should this be (DbGeometry.WellKnownValue)?
  "$type": "System.Data.Entity.Spatial.DbGeometry.WellKnownValue, EntityFramework",


Q: What does "liquid preparation" mean exactly in this definition of the word "sheep dip"? The definition is under the entry "sheep dip" in The Oxford American College Dictionary：

a liquid preparation for cleansing sheep of parasites or preserving their wool

How to understand "liquid preparation"?
Does it mean "washing", "daubing" or "soaking"?
What's more, does "preparation" indicate that the "sheeep dip" happens before the "cleansing" or "preserving"?

A: From http://dictionary.reference.com/browse/preparation?s=t :

preparation noun
(5) something prepared, manufactured, or compounded: a special preparation for sunbathers.

Thus, sheep dip is a liquid that is prepared for the purpose of cleansing sheep.


Q: Why does QtCreator not show the 'Applications' section on Mac? The lists of templates differ. For example when I load the tutorial "Creating a Qt Widget Based Application", it shows the following screenshot.

"Applications" is clearly a visible section of templates available on the left.
I've just downloaded Qt Creator 2.8.1 for Mac (53 MB) from http://qt-project.org/downloads and when I run it I see:

What's going on? I can't even get a simple project started.


Q: How do I downgrade my nVidia Driver in openSUSE 12.1? I’m trying to trouble-shoot a problem that I’ve been having. Downgrading my nVidia driver is about the only thing I haven’t tried.
I have an nVidea GeForce 6200 and installed the latest driver version 290.10, but Í’d like to try an earlier version. When I search for my driver on the nVidia website, it always brings me to the download page for the latest version. How can I find an older version to install?
Here’s some potentially relevant information:
OS Information
OS:                 Linux 3.1.0-1.2-default i686
System:             openSUSE 12.1 (i586)
KDE:                4.7.2 (4.7.2) "release 5"

Display Info
Vendor:             nVidia Corporation
Model:              GeForce 6200 (0x0221)
2D driver:          nvidia
3D driver:          NVIDIA 290.10

Please let me know if you need anything else.

A: Have you tried this?
ftp://download.nvidia.com/opensuse/12.1/i586/


Q: How to compare across multiple columns containing list value in Python Pandas? I have the following sample data
ID          VAR1                            VAR2                                VAR3                                DATE
1           NaN                             [Timestamp('2012-08-03'), 'M']      [Timestamp('2012-08-03'), 'M']      2012-08-03
2           [Timestamp('2009-04-01'), 'F']  NaN                                 [Timestamp('2009-04-03'), 'F']      2009-04-01
3           NaN                             [Timestamp('2004-01-01'), 'M']      NaN                                 2004-01-01
4           NaN                             [Timestamp('2004-02-15'), 'M']      [Timestamp('2000-08-07'), 'M']      2000-08-07

For each row, I want to go through VAR1, VAR2, and VAR3 and have each to compare against the DATE. Each of the three columns would either have a np.nan (missing value) or a list value (containing a date and gender). I want to compare the first element of the list against the DATE column. If the first-element date is more than a day difference than the DATE value, I want to replace that cell value as np.nan.
I like to use Pandas' apply function as I am clear with the underlying logics.
The desired processed df should be as follows:
ID          VAR1                            VAR2                                VAR3                                DATE
1           NaN                             [Timestamp('2012-08-03'), 'M']      [Timestamp('2012-08-03'), 'M']      2012-08-03
2           [Timestamp('2009-04-01'), 'F']  NaN                                 NaN                                 2009-04-01
3           NaN                             [Timestamp('2004-01-01'), 'M']      NaN                                 2004-01-01
4           NaN                             NaN                                 [Timestamp('2000-08-07'), 'M']      2000-08-07

This is my working code
df = df.apply(remove_value_if_unmatched_against_index_date, axis=1)

def remove_value_if_unmatched_against_index_date(df):
    vars = ['VAR1', 'VAR2', 'VAR3']
    for var in vars:
        if isinstance(df[var], list):   # doesn't work
        # if df[var].notnull():         # doesn't work
        # if df[var] != np.nan:         # doesn't work
            if abs(df[var][0] - df['DATE']) >= timedelta(days=1):
                df[var] = np.nan
    return df

The problem is none of the followings (if isinstance(df[var], list):, if df[var].notnull():, and if df[var] != np.nan:) works to help check if there is a list value within the cell.

A: Try with bfill
df['new'] = df.bfill(axis=1)['VAR1'].str[0]


Q: Encrypting with AES Why can I encrypt only 16 characters of text?
Works:
string plainText = "1234567890123456";

Doesn't work:
string plainText = "12345678901234561";

Doesn't work:
string plainText = "123456789012345";

Code:
string plainText = "1234567890123456";
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

byte[] keyBytes = System.Text.Encoding.UTF8.GetBytes("1234567890123456");

byte[] initVectorBytes = System.Text.Encoding.UTF8.GetBytes("1234567890123456");

RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.Zeros;

ICryptoTransform encryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);

MemoryStream memoryStream = new MemoryStream();

CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);

cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

cryptoStream.FlushFinalBlock();

byte[] cipherTextBytes = memoryStream.ToArray();

memoryStream.Close();
cryptoStream.Close();

string cipherText = Convert.ToBase64String(cipherTextBytes);

Console.ReadLine();

A: Not sure I understand the question, but looking at what I assume the intent is of the code the following
symmetricKey.CreateDecryptor

Should probably be
symmetricKey.CreateEncryptor

A: Probably because AES is a block cipher with 128 bits per block.. maybe you just need to add a padding such that length % 128 == 0.
(I'm not a C# developer but it can happen that an implementation doesn't care about adding padding by itself)
Just a hint: try if it works with 256 bits


Q: get the observations for chi2 test We have a collection of Data that we can draw a histogram with the specified distribution curve on and get the centers of bins, using:
[counts,centers]=hist(Data,14)
h=histfit(Data,14,'normal')

we can get the 100 point XData and YData of the drawn curve, using:
h(2).XData
h(2).YData

How can we find the YData of the curve corresponding to the bin centers of the histogram of Data (in commands without knowing the curve equation)?
Thanks in advance

A: I think you can use fitdistr
 %Generate data
r=randn(100,1);
[counts,centers]=hist(r,20)   %r=Data in your case

%fit a Gaussian
pd=fitdist(r(:),'normal')

pd =
  NormalDistribution

  Normal distribution
       mu = 0.0700439   [-0.111376, 0.251463]
    sigma =  0.914313   [0.802773, 1.06213]

x=-3:0.1:3;
PDF=pdf(pd,x); %PDF is a vector of y values: it's our fit

%overplot
PDF=PDF/max(PDF);
%scale to y axis
y=ylim;
PDF=PDF*y(2);

hold on
plot(x,PDF,'r-','LineWidth',2)
hold off


Q: PowerShell sends empty JSON payload I am calling GraphAPI to update keycredentials for a service principal. I create the JSON payload through combining data from a GET call and a custom JSON object.
I have a variable that is not empty, but when I make an API call I get an "empty payload" error. Why is my $body variable considered empty when it clearly isn't?
Below is the information on how I populate this variable.
Information
Here is the script:
. .\GetSecretToken.ps1
. .\pull_cert_data.ps1

$response = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/servicePrincipals/{id}"  -Method Get -Headers $Header

$current_keys = $response.keycredentials

$key_credentials = $current_keys + $new_KeyCredentials

$key_credentials | ConvertTo-Json | Out-File .\checkkeys.txt

$hash_body =
    @{"keyCredentials" = $key_credentials
    "passwordCredentials" = $password_credentials}

$body = $hash_body | ConvertTo-Json -Depth 5
$body | out-file .\checkvalue.txt
$body

$json = $body

$update_cert = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/servicePrincipals/{id}" -Method Patch -Headers $Header -Body $json

If I use the $body variable in the $update_cert call, I get an empty payload error:
    {"error":{"code":"BadRequest","message":"Empty Payload. JSON content | expected."

However, if I use the $json variable, which just equals the $body variable, my call is successful. It will also print the contents of the $body variable in the terminal, so I know it isn't empty. The script creates two files that were originally done to make sure the JSON formatting was correct.
Here is the output of the $body variable:
{
  "keyCredentials": [
    {
      "customKeyIdentifier": "<HASH_OF_THUMBPRINT>",
      "displayName": "<CN>",
      "endDateTime": "<EXPIRY_DATE>",
      "key": null <EXISTING_CERT>,
      "keyId": "<GUID>",
      "startDateTime": "<START_DATE>",
      "type": "AsymmetricX509Cert",
      "usage": "Verify"
    },
    {
      "customKeyIdentifier": "<HASH_OF_THUMBPRINT>",
      "displayName": "<CN>",
      "endDateTime": "<EXPIRY_DATE>",
      "key": null <EXISTING_CERT>,
      "keyId": "<GUID>",
      "startDateTime": "<START_DATE>",
      "type": "AsymmetricX509Cert",
      "usage": "Sign"
    },
    {
      "customKeyIdentifier": "<HASH_OF_THUMBPRINT>",
      "displayName": "<CN>",
      "endDateTime": "<EXPIRY_DATE>",
      "key": null <EXISTING_CERT>,
      "keyId": "<GUID>",
      "startDateTime": "<START_DATE>",
      "type": "AsymmetricX509Cert",
      "usage": "Verify"
    },
    {
      "customKeyIdentifier": "<HASH_OF_THUMBPRINT>",
      "displayName": "<CN>",
      "endDateTime": "<EXPIRY_DATE>",
      "key": null <EXISTING_CERT>,
      "keyId": "<GUID>",
      "startDateTime": "<START_DATE>",
      "type": "AsymmetricX509Cert",
      "usage": "Sign"
    },
    {
      "customKeyIdentifier": "<HASH_OF_THUMBPRINT>",
      "endDateTime": "<EXPIRY_DATE>",
      "type": "X509CertandPassword",
      "key": "<NEWCERT-PrivateKey>",
      "displayName": "<CN>",
      "startDateTime": "<START_DATE>",
      "keyId": "<GUID>",
      "usage": "Sign"
    },
    {
      "customKeyIdentifier": "<HASH_OF_THUMBPRINT>",
      "endDateTime": "<EXPIRY_DATE>",
      "type": "AsymmetricX509Cert",
      "key": "<NEWCERT-PublicKey>",
      "displayName": "<CN>",
      "startDateTime": "<START_DATE>",
      "keyId": "<GUID>",
      "usage": "Verify"
    }
  ],
  "passwordCredentials": [
    {
      "endDateTime": "<EXPIRY_DATE>",
      "secretText": "<PASSPHRASE_FOR_NEW_CERT>",
      "startDateTime": "<START_DATE>",
      "keyId": "<KEY_ID_OF_PRIVATE_KEY>",
      "customKeyIdentifier": "<HASH_OF_THUMBPRINT_OF_NEW_CERT>"
    }
  ]
}

Note: The $new_keyCredentials and $password_credentials variables are arrays that contain the hashtables of the new keycredentials and password credentials of those keys and are imported from the pull_cert_date.ps1 script.  The $Header is coming from GetSecretToken.ps1 script.

A:
PowerShell sends empty JSON payload

This error states that the PowerShell that the command is wanting the Json and the input provided is empty.
I have reproduced your requirement in my environment, and I have faced similar issue as you.
So, when I displayed the body i got the below as output:

And if I send this as the Json in invoke command, I get similar error as you got.
Then I used ConvertTo-Json and I got expected results as below:

Here what I observed is when I converted \n are added and it worked as expected.
References:

*

*"Empty Payload. JSON content expected" when uploading an item to OneDrive from a URL · Issue #745 · OneDrive/onedrive-api-docs · GitHub


Q: combining jackson objectmapper and stream parsing I have an android application, where parsing a json block takes around 250ms. It contains an array, and I only really need the first 6-7 values available immediatly. And I really need to speed up getting to those pieces of the data.
I have a data structure that essentially looks like:
class Data {
    List<Map> data = objectmapper_readvalue_data;

    public HashMap getItem(int i) {
        return data.get(i);
    }
}

I was really hoping to do something like this with a JsonParser:
    class Data {
        List data = new List();
        JsonParser p;
    public HashMap getItem(int i) {
        while (data.length < i) {
            data.append(p.parseOneBlockOfData());
        }
        return data.get(i);
    }
}

And only the first 5-6 values will be parsed at the first render, the others I can deal with later. However, I'm missing the "parseOneBlockOfData" function. Of course I can use a StringBuilder to buffer every value in the parse until I find the next entire block, then use a objectParser or that, but I'm not sure what the performance will be like.
Are there any non hackish ways of doing this?

A: incase anyone googles this:
JsonParser parser = objectMapper.getFactory().createJsonParser(inputStream);

// Keep going until we find filters:
String fieldName = null;
JsonToken token = null;
while (!"filters".equals(fieldName)) {
    token = parser.nextToken();
    while (token != JsonToken.START_ARRAY) {
        token = parser.nextToken();
    }
    fieldName = parser.getCurrentName();
}
// We're at the filters node

while (parser.nextToken() == JsonToken.START_OBJECT) {
    Map x = objectMapper.readValue(parser, Map.class);
}


Q: How can i integrate a section in Related Lists with the standard Lead Page Could you please help me to know, how can i integrate a section with the standard Lead Page. I have tried to embed a visual force section into a standard page layout, I can add that section in "lead detail", but looking for a way to add the same section outside lead detail or  in "Related Lists".
Is it possible?
I have been searching for this from couple of weeks,Your time and help is cordially appreciated....!

A: You cannot insert Visualforce customizations in the Related List portion of the page layout. Visualforce pages may only be embedded in the Details section.
Your only option would be to fully reimplement the View action for this object in Visualforce, which would take a great deal more code.


Q: Can't setup Exchange account in Outlook I'm trying to add a new account to Outlook but the wizard gives me an error:

Log onto Exchange ActiveSync Mail server (EAS): The server cannot be found. The username or password you entered isn't working.

I checked the settings and I am able to login to OWA without problems.
Existing accounts are not affected and work fine in Outlook.
I can see no apparent problems in my Exchange server, but I also don't know where to look regarding this problem.
I find it also curious that the error message mentions that it can't find the server as well as wrong credentials.
I already did a repair installation of Exchange CU12 last night without any effect.
I also tried the Microsoft Remote Connectivity Analyzer to test Exchange ActiveSync.
The test passed, with a warning that my LE certificate may only work with a Root Certificate Update.
I had to manually provide the server name, as there seems to be some problem with autodiscover. I get a 403 when accessing https://autodiscover.:443/Autodiscover/Autodiscover.xml with the Analyzer, but it works in my browser. I would like to solve that problem as well (if it is not the root cause).

A: This problem occurs because Outlook doesn't support connections to a server that's running Exchange Server by using the EAS protocol.
To resolve this problem, connect to Exchange by using the standard Exchange connection settings.

*

*Select File > Add Account.

*Enter your email address and click Connect.

*If prompted, enter your password again, then select OK > Finish to start using your email account in Outlook.

Refer to: Outlook doesn't support connections to Exchange by using ActiveSync and error: Log onto Exchange ActiveSync mail server (EAS)
Add an email account to Outlook


Q: Solving differential equations given conditions Can anyone help me solving the differential equation: $$i\hbar\frac{\partial}{\partial t}|\Psi(t)\rangle=H|\Psi(t)\rangle$$
$$i\hbar\frac{\partial}{\partial t}\begin{pmatrix}\alpha_0(t)\\\alpha_1(t)\end{pmatrix}=\begin{pmatrix}0&-i\\-i&0\end{pmatrix}\begin{pmatrix}\alpha_0(t)\\\alpha_1(t)\end{pmatrix}$$
Where we have that $$|\Psi(t)\rangle=\begin{pmatrix}\alpha_0(t)\\\alpha_1(t)\end{pmatrix}$$ and the condition, that
expand the state at time t in the basis $|0\rangle, |1\rangle$, such that
$$|\Psi(t)\rangle=\alpha_0(t)|0\rangle+\alpha_1(t)|1\rangle$$ the Hamiltonian (H) of the system in this basis be given by
$$
H=\omega\begin{pmatrix}
0 &1 \\
1 &0
\end{pmatrix}=\begin{pmatrix}
0 &-i \\
-i &0
\end{pmatrix}
$$
and assume that for $t=0$ the state of the system is just given by $\psi(t=0)=\left . \left |   0  \right \rangle\right .$
Can anyone help me solving the equation given by the conditions? I'm not sure how to deal with matrix and complex number solving a differential equation? Hope anyone can help me?


Q: How to Get file from google drive I want to get file from drive use this code but not working.Some code given below -
public class PinFileActivity extends BaseDemoActivity {

        private static final int REQUEST_CODE_OPENER = NEXT_AVAILABLE_REQUEST_CODE;

        private static final String TAG = "PinFileActivity";

        private DriveId mFileId;

        /**
         * Starts a file opener intent to pick a file.
         */
        @Override
        public void onConnected(Bundle connectionHint) {
            super.onConnected(connectionHint);
            if (mFileId == null) {
                IntentSender intentSender = Drive.DriveApi
                        .newOpenFileActivityBuilder()
                        .setMimeType(
                                new String[] { "text/plain", "text/html",
                                        "application/pdf", "audio/mp3",
                                        "video/mp4", "text/plain",
                                        "application/msword", "image/jpeg",
                                        "image/png", "text/html" })
                        .build(getGoogleApiClient());
                try {
                    startIntentSenderForResult(intentSender, REQUEST_CODE_OPENER,
                            null, 0, 0, 0);
                } catch (IntentSender.SendIntentException e) {
                    Log.w(TAG, "Unable to send intent", e);
                }
            } else {
                DriveFile file = Drive.DriveApi.getFile(getGoogleApiClient(),
                        mFileId);
                Log.i("File Name is ", "===========>>>>" + file);
                file.getMetadata(getGoogleApiClient()).setResultCallback(
                        metadataCallback);
            }
        }

        /**
         * Handles response from the file picker.
         */
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            switch (requestCode) {
                case REQUEST_CODE_OPENER:
                    if (resultCode == RESULT_OK) {
                        mFileId = (DriveId) data
                                .getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);

                    } else {
                        finish();
                    }
                    break;
                default:
                    super.onActivityResult(requestCode, resultCode, data);
            }
        }

        /**
         * Handles the metadata response. If file is pinnable and not already
         * pinned, makes a request to pin the file.
         */
        final ResultCallback<DriveResource.MetadataResult> metadataCallback = new ResultCallback<DriveResource.MetadataResult>() {
            @Override
            public void onResult(DriveResource.MetadataResult result) {
                if (!result.getStatus().isSuccess()) {
                    showMessage("Problem while trying to retrieve the file metadata");
                    return;
                }
                if (result.getMetadata().isPinnable()) {
                    showMessage("File is not pinnable");
                    Log.i("==========All Info is here", "mIME tYPE=====>>>"
                            + result.getMetadata().getMimeType() + "======>"
                            + result.getMetadata().getTitle() + "====="

                            + result.getMetadata().getAlternateLink() + "======"

                            + result.getMetadata().getWebContentLink() + "======>>"
                            + result.getMetadata().getQuotaBytesUsed());
                    return;
                }
                if (result.getMetadata().isPinned()) {
                    showMessage("File is already pinned");
                    return;
                }

                Log.i("==========All Info is here", "==========>>>");

                DriveFile file = Drive.DriveApi.getFile(getGoogleApiClient(),
                        mFileId);
                MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                        .setPinned(true).build();
                file.updateMetadata(getGoogleApiClient(), changeSet)
                        .setResultCallback(pinningCallback);

            }
        };

        /**
         * Handles the pinning request's response.
         */
        final ResultCallback<DriveResource.MetadataResult> pinningCallback = new ResultCallback<DriveResource.MetadataResult>() {
            @Override
            public void onResult(DriveResource.MetadataResult result) {
                if (!result.getStatus().isSuccess()) {
                    showMessage("Problem while trying to pin the file");
                    return;
                }
                showMessage("File successfully pinned to the device");
            }
        };
    }

Here My BaseDemoActivity sample code
public abstract class BaseDemoActivity extends Activity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private static final String TAG = "BaseDriveActivity";

    /**
     * DriveId of an existing folder to be used as a parent folder in
     * folder operations samples.
     */
    public static final String EXISTING_FOLDER_ID = "0B2EEtIjPUdX6MERsWlYxN3J6RU0";

    /**
     * DriveId of an existing file to be used in file operation samples..
     */
    public static final String EXISTING_FILE_ID = "0ByfSjdPVs9MZTHBmMVdSeWxaNTg";

    /**
     * Extra for account name.
     */
    protected static final String EXTRA_ACCOUNT_NAME = "account_name";

    /**
     * Request code for auto Google Play Services error resolution.
     */
    protected static final int REQUEST_CODE_RESOLUTION = 1;

    /**
     * Next available request code.
     */
    protected static final int NEXT_AVAILABLE_REQUEST_CODE = 2;

    /**
     * Google API client.
     */
    private GoogleApiClient mGoogleApiClient;

    /**
     * Called when activity gets visible. A connection to Drive services need to
     * be initiated as soon as the activity is visible. Registers
     * {@code ConnectionCallbacks} and {@code OnConnectionFailedListener} on the
     * activities itself.
     */
    @Override
    protected void onResume() {
        super.onResume();
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(Drive.API)
                    .addScope(Drive.SCOPE_FILE)
                    .addScope(Drive.SCOPE_APPFOLDER) // required for App Folder sample
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
        }
        mGoogleApiClient.connect();
    }

    /**
     * Handles resolution callbacks.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
            mGoogleApiClient.connect();
        }
    }

    /**
     * Called when activity gets invisible. Connection to Drive service needs to
     * be disconnected as soon as an activity is invisible.
     */
    @Override
    protected void onPause() {
        if (mGoogleApiClient != null) {
            mGoogleApiClient.disconnect();
        }
        super.onPause();
    }

    /**
     * Called when {@code mGoogleApiClient} is connected.
     */
    @Override
    public void onConnected(Bundle connectionHint) {
        Log.i(TAG, "GoogleApiClient connected");
    }

    /**
     * Called when {@code mGoogleApiClient} is disconnected.
     */
    @Override
    public void onConnectionSuspended(int cause) {
        Log.i(TAG, "GoogleApiClient connection suspended");
    }

    /**
     * Called when {@code mGoogleApiClient} is trying to connect but failed.
     * Handle {@code result.getResolution()} if there is a resolution is
     * available.
     */
    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
        if (!result.hasResolution()) {
            // show the localized error dialog.
            GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
            return;
        }
        try {
            result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
        } catch (IntentSender.SendIntentException e) {
            Log.e(TAG, "Exception while starting resolution activity", e);
        }
    }

    /**
     * Shows a toast message.
     */
    public void showMessage(String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

    /**
     * Getter for the {@code GoogleApiClient}.
     */
    public GoogleApiClient getGoogleApiClient() {
        return mGoogleApiClient;
    }
}

I am getting user select popup only.

select the user after also show this popup how to fix this one.
I get this error:

ConnectionResult{statusCode=SIGN_IN_REQUIRED,
  resolution=PendingIntent{2af2f49: android.os.BinderProxy@462504a}}


Q: Want to know the number of times a value appears on a given date I will try to explain this in as simple a way as possible. I want to be able to count how many times a value is entered into my database table for each day.
Basically, if the data is entered once it would count as a single, if the data was entered twice it would count as a double and if the data was entered three times it would count as a treble.
I then want to be able to count how many singles, doubles and trebles appear within a certain time frame (April to April each year). Then of course echo them out on to the php page like so:
Singles - 23
Doubles - 69
Trebles - 3
I tried adding a round_id column in the database table as I thought if that was default 1 and I could somehow count each day how many 1's appeared that would work but I am totally stuck.
Any help would be greatly appreciated!

A: If I'm understanding you right, to start, we can get a count by day:
SELECT COUNT(*) AS cnt, `date`
FROM `table`
GROUP BY `date`

That will give you the count of records for each day.
Then we can wrap that in another query:
SELECT dailycount.daycnt AS `type`, COUNT(*) AS cnt
FROM (
    SELECT COUNT(*) AS daycnt, `date`
    FROM `table`
    GROUP BY `date`
) dailycount
WHERE `date` BETWEEN start_date AND end_date
GROUP BY daycnt

This will give you something like this:
type cnt
1    23
2    69
3    3

where type would be your singles, doubles, etc.

A: Without knowing the structure, here's the best SQL I could come out with:
SELECT COUNT(DISTINCT field) FROM table GROUP BY field
That will count the number of field appearances for each value.


Q: Make Chrome's menu more compact (vertically) in macOS Desktop real estate is very important to me. Chrome is large and sometimes takes up too much space. Sometimes, I want two windows (one on top of the other), but they are just too clunky because of of the menu/UI. Here's an image of what I'm talking about.
IS there a way to make this smaller? I've looked up some themes, but I don't think they change it. I've also seen this solution: https://www.howtogeek.com/278699/how-do-you-adjust-google-chromes-ui-scaling/ but it's for windows.
Any ideas?

A: Only solution I can think of is going to

chrome://flags/#top-chrome-md

and choosing Normal - this switches Chrome to pre-MD2 design.
Consider using Safari, it's much more compact vertically.


Q: Is "The State it was In when it was..." too wordy? I saw this message:

Reset all save data and return the game to the state it was in when it was newly purchased

Is the the state it was in too wordy or redundant? Can it be just the state when it was newly purchased? Which grammar rule am I breaking if it were the later?

A: Current English idiom allows even more compression:
"return the game to the state when newly purchased"
eventually punctuated:
"return the game to the state-when-newly-purchased"
See:

Technical studies. - Page 176 Douglas F. Greer, United States.
  National Commission on Consumer Finance, Robert Paul Shay - 1974
... as a measure of the average quality of cars in the state when
  newly purchased. Its expected sign is of course positive, and it is
  intended as a variable which could represent those factors influencing
  quality demand which are not accounted for by the other included
  variables.

or:

Identity, Consciousness and Value - Page 120 Peter Unger
  Professor of Philosophy New York University - 1990
When an adequate cure for the illness is discovered, the person's
  body, including her brain, is instantaneously unfrozen, or thawed; it
  is thus returned to its state when last alive.


Q: C# Regex specify allowed start and end condtions I'm trying to create a regex expression with the following requirements:
The value:

*

*Must start with a-z or _, numbers are OK after the first character

*Can have parentheses if they are opened and closed with number inside at the end of string, i.e SomeVar(10) is OK, SomeVar(10 is not OK.

*Can have a . but only one at a time, and only between letters or numbers. SomeVar.InnerVar is OK, SomeVar..Innevar is not OK.

My try at the regex:

*

*[a-zA-Z_]

*??

*??

A: Assuming you want to match an entire string, you may use something like the following:
^[a-zA-Z_](?:\w|(?<=\w)\.(?=\w))*(?:\(\d+\))?$

Demo.
If you want to match partial strings, you'd need to decide what boundaries are allowed. Otherwise, "SomeVar(10" would have a match (i.e., what comes before (), for example.
Notes:

*

*\w matches a lowercase/uppercase letter, a digit, or an underscore. But it also matches Unicode letters and numbers. If you don't want that, you could use [a-zA-Z0-9_] instead.

*Similarly, \d matches any Unicode digit. You either use it or use [0-9] depending on your requirements.

A: Use
^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*(\([^()]*\))?$

See proof.

*

*[a-zA-Z_][a-zA-Z0-9_]* - a letter or underscore, then zero or more letters, digits, underscores

*(\([^()]*\))? - optional group, parens may be present or absent

*(\.[a-zA-Z_][a-zA-Z0-9_]*)* - dot is allowed between letter/digit/underscore.


Q: Delete a row javascript using row id Hi guys I have a table created by php in this way:
  foreach ($query as $row): ?>
                <tr id="<?php echo  $row->aic;?>" >

                    <?php echo $row->aic; ?>
                    <?php echo $row->denominazione ?>
                    <?php echo $row->quantita; ?>
                    <?php echo $row->alert; ?>

                            <img src="<?php echo base_url(); ?>template/images/Modifica.png">

                           "
                                  class="btn btn-default btn-xs"
                                  data-toggle="tooltip"
                                 data-placement="top"
                                 title=""
                                 data-original-title="Elimina"
                                 onclick="deleteRow(<?php echo $row->aic ?>))">

                            <img src="<?php echo base_url(); ?>template/images/Elimina.png">

            <?php

            endforeach; ?>

I need to delete row by rowId. This table has the dynamics id.
The columns ids are the same id of the sql table; in effect aic is id of sql table! In this way I are sure that the HTML row id is unique.
This is script
function deleteRow(rowID)
{   var row = document.getElementById(rowID);
    row.parentElement.removeChild(row);
        alert(rowID);

            }
}

this code don't delete row.

A: Change this:
onclick="deleteRow(deleteRow(<?php echo $row->aic ?>))">

to
onclick="deleteRow(<?php echo $row->aic ?>)">

Another potential issue is that this:
<?php echo $row->aic ?>

may not be a number. So, you need to quote it. That is, change:
onclick="deleteRow(<?php echo $row->aic ?>)">

to:
onclick="deleteRow(\"<?php echo $row->aic ?>\")">

A: 2 issues -

*

*The one that might be causing issue - Incorrect Function Name

*Other one - Calling deleteRow() twice - within each other (this should not cause any issue though)

So, just change -
function eliminaProdotto(rowID)

to -
function deleteRow(rowID)

Edit:
Based on modified question -
Is $row->aic a string? If yes, then add quotes around it...
onclick="deleteRow('<?php echo $row->aic ?>')"


Q: Undefined Reference to vtable with abstract class When building my C++ program, I'm getting the error message.

undefined reference to vtable

I have two virtual abstract classes called and I can't quite figure out what I'm doing wrong if I'm doing anything wrong.
I'm getting errors from both of the classes that are inheriting from the abstract class.
My abstract class is

undefined reference to `vtable for hittable_list'
undefined reference to `vtable for sphere'

hittable.h
     #ifndef HITTABLE_H
        #define HITTABLE_H

    #include "ray.h"

    struct hit_record {
        hit_record() {}
        ~hit_record() {}
        float t;
        vecfloat p;
        vecfloat normal;
        float MAXFLOAT = 100.0;
};

    //Abstract Class containing Sphere and hittablelist
    class hittable
    {
     public:
            virtual ~hittable() = 0;

            virtual bool hit(const ray &r, float t_min, float t_max, hit_record &rec) const = 0;
 };

        #endif

Classes inherting from my abstract class are.
sphere.h
 #ifndef SPHERE_H
#define SPHERE_H

#include "hittable.h"

class sphere : public hittable
{
public:
    sphere() {}
    ~sphere() {}
    sphere(vecfloat cen, float r) : center(cen), radius(r) {}
    bool hit(const ray &r, float t_min, float t_max, hit_record &rec) const;

protected:
    vecfloat center;
    float radius;
};

#endif

sphere.cc
#include "include/sphere.h"

bool sphere::hit(const ray &r, float t_min, float t_max, hit_record &rec) const
{
    vecfloat oc = r.origin() - center;
    float a = oc.dot_product(r.direction());
    float b = oc.dot_product(oc) - radius * radius;
    float c = oc.dot_product(oc) - radius * radius;
    float discriminant = b * b - a * c;
    if (discriminant > 0)
    {
        float temp = (-b - sqrt(b * b - a * c)) / a;
        if (temp < t_max && temp > t_min)
        {
            rec.t = temp;
            rec.p = r.point_at_parameter(rec.t);
            rec.normal = (rec.p - center) / radius;
            return true;
        }
        temp = (-b + sqrt(b * b - a * c)) / a;
        if (temp < t_max && temp > t_min)
        {
            rec.t = temp;
            rec.p = r.point_at_parameter(rec.t);
            rec.normal = (rec.p - center) / radius;
            return true;
        }
    }
    return false;
}

hittable.h
#ifndef HITTABLELIST_H
#define HITTABLELIST_H
#include "hittable.h"

class hittable_list : public hittable
{
public:
    hittable_list() {}

    hittable_list(hittable **l, int n)
    {
        list = l;
        list_size = n;
    }
    bool hit(const ray &r, float t_min, float t_max, hit_record &rec) const;
    ~hittable_list() {}

protected:
    hittable **list;
    int list_size;
};

#endif

hittable.cc
#include "include/hittablelist.h"

bool hittable_list::hit(const ray &r, float t_min, float t_max, hit_record &rec) const
{

    hit_record temp_rec;
    auto hit_anything = false;
    auto closet_so_far = t_max;
    for (int i = 0; i < list_size; i++)
    {
        if (list[i]->hit(r, t_min, closet_so_far, temp_rec))
        {
            hit_anything = true;
            closet_so_far = temp_rec.t;
            rec = temp_rec;
        }
    }
    return hit_anything;
}

A: Solution
Change
virtual ~hittable() = 0;

into
virtual ~hittable() = default;

or
virtual ~hittable()
{
    // does nothing
}

The destructor can remain pure virtual, but it must have a definition.
hittable::~hittable()
{
    // does nothing
}

So what happened?
We can crush the given code down to the following example (Note I can't reproduce the missing vtable with this code or the given code, but regardless, the above will fix it)
Minimal example:
class hittable
{
public:
    virtual ~hittable() = 0; // here we have a destructor,
                             // but there's no implementation
                             // so there is nothing for the
                             // destructors of derived classes
                             // to call

    virtual bool hit() const = 0;
};

class sphere: public hittable
{
public:
    bool hit() const;

};

bool sphere::hit() const
{
    return false;
}

destructors call any base class destructors, and when shpere goes to call ~hittable, it finds that while ~hittableis declared, there is no implementation. Nothing to call.


Q: query: get author of a song and count total of songs for that author I'm not sure how to do the following query. I have 3 tables:
song (song_id, title, is_draft)
author (author_id, name)
song_author (song_id, author_id, display_order)

There are songs, and a song can have multiple authors and an author can write multiple songs
I want to output the authors of a specific song with the total numbers of songs that each author wrote.
So, if i pick song_id: 598, i want to have a result set like this
author_id    name           total songs he wrote
------------------------------------------------
234          Michael Lord   58
589          Lama Turc      12

NOTE: The total number of songs each author wrote must exclude songs were song.is_draft equals 1 and order the result set by song_author.displayorder
From my research, i think i have to do 2 queries (sub queries) but that's as far as i got...
Thanks

A: SELECT  author.author_id, author.name, count(song.song_id)
FROM song, author, song_author,
WHERE song.song_id = $id
AND song.song_id = song_author.song_id
AND song_author.author_id = author.author_id
AND song_author.display_order != 1
GROUP BY song_author.author_id, author.name
ORDER BY author.author_id asc;

A: try this..
select b.author_Id, b.name, COUNT(a.Song_Id) as 'total'
FROm song_author as a
INNER JOIN author as b
    ON a.author_id = b.author_id
where a.song_id IN (select s.song_id
                    From songs as s
                    Where s.Song_Id = 598
                    AnD s.is_draft = 1)
GROUP bY b.author_Id, b.name

A: New to SQL too, but off the top of my head maybe this?  This doesn't explicitly spell out joins, but I've found it works for my purposes.  Maybe someone can let me know if this is bad practice?
Select author.author_id
, author.name
, count(author.author_id)
from song, author, song_author
where song.song_id = song_author.song_id
and author.author_id = song_author.author_id
group by author.authorid, author.name
order by author.author_id asc;


Q: Math for game theory I have read a bunch of book on Game Theory, and I find that one of the best is the the book of Osborne and Rubinstein. Nevertheless, all books which I found are not made for mathematician, meaning that they do not assume prior knowledge, in particular they do not assume measure theory, functional/complex analysis etc.
Is there any really formal and well-written book about game theory made for mathematician? Thanks in advance

A: I do not know what you mean by prior knowledge, but I would give a couple of books which requires more mathematical sophistication than Osborne and Rubinstein. If you are looking for a specific area in game theory then this list may not be useful for you.

*

*Game Theory by Maschler, Solan and Zamir: This book is relatively new and it includes almost everything one needs to know about game theory (both cooperative and non-cooperative). In the mathematical appendix it covers necessary background for existence theorem.

*Game Theory for Economic Analysis by Ichiishi: This is a pretty old book, but it is very well written and it assumes a great deal of mathematical knowledge. Yet, the initial chapters discuss continuity notions for set valued maps(uhc-lhc), properties of convex sets and fixed points.

*Game Theory by Owen: This is also another old book, but  it is still used in various courses in different places. It has traditional definition-theorem-proof structure.


Q: stub random value in rspec with secure_random I am trying to write specs for my gem, which generates otp and saves it in db. Now i am writing specs for it. so basically i have three methods generate_otp!, regenerate_otp!, verify_otp(otp). what generate_otp! does is it calls a method generate_otp which contains three variables

*

*otp_code - basically a random value generated using secure_random

*otp_verified - a boolean value to set the status whether otp is verified or not

*otp_expiry_time - sets expiry time for otp which can be set by rails app in configuration.

these all three are columns of my db also.
Now after generate_otp i am calling active_records's save method to save values to db.
Now for testing i am using in :memory: and storing values in table. after testing i am dropping the db. Now i am not getting how to stub the randomly generated value and test whether value is assigned or not to all three columns, i.e, otp_code , otp_verified, otp_expiry_time.
Here is code for my methods which i need to test.
def generate_otp
    self.otp_verified = false
    self.otp_expiry_time = OtpGenerator::configuration.otp_expiry_time
    self.otp_code = SecureRandom.hex(4)
  end

def generate_otp!
   generate_otp
   save
end

Any help with this ? I have also checked this question, but not much helpful. It's first time i am writing specs and really don't have that much experience with rspecs. I have also studied the official documentation for mock and stub, but i am really getting confused.
update : otp_spec code
require 'spec_helper'

describe OtpGenerator do

  let(:user) { build_mock_class.new() }
  before(:all) { create_table }
  after(:all) { drop_table }

  describe '#generate_otp' do
    it 'generate otp and save it' do
      user.generate_otp!

    end
  end

  describe '#regenerate_otp' do
    it 'regenerate otp and save it' do

    end
  end

  describe '#verify_otp' do
    it 'verifies otp' do

    end
  end

  def build_mock_class
    Class.new(ActiveRecord::Base) do
      self.table_name = 'mock_table'
      include OtpGenerator
    end
  end

  def create_table
    ActiveRecord::Base.connection.create_table :mock_table do |t|
      t.string :otp_code
      t.boolean :otp_verified
      t.datetime :otp_expiry_time
    end
  end

  def drop_table
    ActiveRecord::Base.connection.drop_table :mock_table
  end
end

A: A direct approach to stubbing out the SecureRandom method in rspec would be as follows:
before { allow(SecureRandom).to receive(:hex).with(4).and_return('abcd1234') }

You can then check that 'abcd1234' is stored in the database. In order to keep the test DRY, you may also wish to reference this as a variable, e.g. let(:random_value) { 'abcd1234' }.


Q: Pygame: Character Centered Movement System (Diablo II like click-to-move) I am currently working on a new RPG game using Pygame (my aim here is really to learn how to use object oriented programming). I started a few days ago and developed a movement system where the player clicks a location and the character sprite goes to that location and stops when it get's there by checking if the sprite 'collides' with the mouse position.
I quickly found however that this greatly limited the world size (to the app window size).
I started having a look into making a movement system where the background would move with respect to the player, hence providing the illusion of movement.
I managed to achieve this by creating a variable keeping track of my background map position. The map is much bigger than the app window. And each time I want my player to move I offset the background by the speed of the player in the opposite direction.
My next problem now is that I can't get my character to stop moving... because the character sprite never actually reaches the last position clicked by the mouse, since it is the background that is moving, not the character sprite.
I was thinking of spending some time coding in a variable that would keep track of how many displacements it would take the character sprite to reach the mouse clicked position if it was to move. Since the background moves at the character sprite's speed it would take as many displacement of the background in the x and y directions to center the clicked position on the background to the character sprite at the center of the screen.
It would be something like that:
If MOUSEBUTTON clicked:
   NM = set number of moves needed to reach the clicked position based on character sprite distance to click and character sprite speed.
If NM != 0:
   Move background image
Else:
   pass

This would mean that when my background has moved enough for the character sprite to now be just over the area of the background that was originally clicked by the player, the movement would stop since NM == 0.
I guess that my question is: Does that sound like a good idea or will it be a nightmare to handle the movement of other sprites and collisions ? And are there better tools in Pygame to achieve this movement system ?
I could also maybe use a clock and work out how many seconds the movements would take.
I guess that ultimately the whole challenge is dealing with a fixed reference point and make everything move around it, both with respect to this fixed reference, but also to their own. e.g. If two other sprites move toward one another, and the character of the player also "moves" then the movement of the other two sprites will have to depend both on the position of the other sprite and also on the offset of the background caused by the movement of the player's character.
An interesting topic which has been frying my brain for a few nights !
Thank you for your suggestions !

A: You actually asking for an opinion on game design. The way I look at it, nothing is impossible so go ahead and try your coding. Also it would be wise to look around at similar projects scattered around the net. You may be able to pick up a lot of tips without re inventing the wheel. Here is a good place to start.
scrolling mini map