text:
Q: Undefined method `within' using capybara and rspec I'm trying to create a simple rspec that checks for a Bootstrap navigation bar and the appropriate links inside it.  I've included capybara/rspec in spec_helper.rb and have the rspec in the spec/features directory, so I think I have the setup right, but running the spec produces an error stating that the within method is undefined.
require 'spec_helper'

feature "HomePage" do
  before { visit root_path }

  subject { page }

  describe "the navigation bar" do
    it { should have_selector('.navbar') }

    within ".navbar" do
      it { should have_link('Game Contest Server', href: root_path) }
      it { should have_link('Users', href: users_path) }
      it { should have_link('Sign Up', href: signup_path) }
    end
  end
end

Any ideas for how I can fix this?

A: In RSpec, the capybara methods are only available inside of an it block. You just need to refactor your code into something like:
describe "the navigation bar" do
  it { should have_selector('.navbar') }

  it "should have links" do
     within ".navbar" do
       should have_link('Game Contest Server', href: root_path)
       should have_link('Users', href: users_path)
       should have_link('Sign Up', href: signup_path)
     end
  end
end


text:
Q: Making a concrete class abstract, preserving the constructor Suppose you have a concrete class
class Knight(object):
    def __init__(self, name):
        self._name = name
    def __str__(self):
        return "Sir {} of Camelot".format(self.name)

Now it happens that the class hierarchy has to change. Knight should become an abstract base class, with a bunch of concrete subclasses for knights of various castles. Easy enough:
class Knight(metaclass=ABCMeta):  # Python 3 syntax
    def __str__(self):
        return "Sir {} of {}".format(self.name, self.castle)
    @abstractmethod
    def sing():
        pass

class KnightOfTheRoundTable(Knight):
    def __init__(self, name):
        self.name = name
    @property
    def castle(self):
        return "Camelot"
    @staticmethod
    def sing():
        return ["We're knights of the round table",
                "We dance whenever we're able"]

But now all code that used Knight("Galahad") to construct a Knight is broken. We can instead keep Knight as it is and introduce a BaseKnight, but then code that checks for isinstance(x, Knight) and should work on any knight may have to be changed to check for BaseKnight instead.
How does one turn a concrete class into an abstract one, sparing both the constructor and the isinstance checks?

A: Make the existing class a base class, but overload __new__ to return a subclass when an attempt is made to instantiate the base class:
class Knight(metaclass=ABCMeta):
    def __new__(cls, *args, **kwargs):
        if cls is Knight:
            # attempt to construct base class, defer to default subclass
            return KnightOfTheRoundTable(*args, **kwargs)
        else:
            obj = super(Knight, cls).__new__(cls)
            obj.__init__(*args, **kwargs)
            return obj
    def __str__(self):
        return "Sir {} of {}".format(self.name, self.castle)
    @abstractmethod
    def sing():
        pass

Now Knight("Galahad") continues to work but returns a KnightOfTheRoundTable. isinstance(Knight("Robin"), Knight) return True, as does an isinstance(x, Knight) check on any other subclass instance.

A: Your solution messing with __new__ mostly works, but it has the downside where Knight(...) does not give you a Knight, and that Knight is just an ABC.
Writing BaseKnight is a bit cleaner, but then you have the problem

code that checks for isinstance(x, Knight) and should work on any knight may have to be changed to check for BaseKnight instead.

which can be patched by adding
    def __subclasscheck__(object):
        return issubclass(object, BaseKnight)

to Knight. You  don't want this to affect the subclasses of Knight, though, so you do this also horrible hack:
    @classmethod
    def __subclasscheck__(cls, object):
        if cls is Knight:
            return issubclass(object, BaseKnight)
        else:
            return ABCMeta.__subclasscheck__(cls, object)

from abc import ABCMeta, abstractmethod

class BaseKnight(metaclass=ABCMeta):  # Python 3 syntax
    def __str__(self):
        return "Sir {} of {}".format(self.name, self.castle)

    @abstractmethod
    def sing():
        pass

That's the base, then you have the concrete Knight that redirects isinstance and issubclass checks:
class Knight(BaseKnight):
    def __init__(self, name, castle="Camelot"):
        self._name = name

    @abstractmethod
    def sing(self):
        return ["Can't read my,",
                "Can't read my",
                "No he can't read my poker face"]

    @classmethod
    def __subclasscheck__(cls, object):
        if cls is Knight:
            return issubclass(object, BaseKnight)
        else:
            return ABCMeta.__subclasscheck__(cls, object)

Finally, some tests:
class KnightOfTheRoundTable(Knight):
    def __init__(self, name):
        self.name = name

    @property
    def castle(self):
        return "Camelot"

    def sing():
        return ["We're knights of the round table",
                "We dance whenever we're able"]

class DuckKnight(BaseKnight):
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return "Knight Quacker of Quack"

    def sing():
        return ["Quack!"]

isinstance(KnightOfTheRoundTable("John"), Knight)
#>>> True

isinstance(DuckKnight("Quacker"), Knight)
#>>> True

With the edit to to delegate back to ABCMeta.__subclasscheck__(cls, object) I no longer thing either solution is particularly nice.
It's worth noting, though, that

*

*You probably instantiate Knight way more than than you use isinstance against the concrete Knight type (prior to the ABC). It makes sense to keep crazy behaviour confined to small spaces.

*Changing isinstance means you don't have to change what Knight is, which means less damage to the codebase.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to save data to multiple tables in Rails I am using Devise for authentication in my app and got a model named as "Users". I created an another model for Company informations. I generated the migration with references and everything is okay.
I want to add user informations to users table and company informations to companies table in same registration view.
Also both users and companies tables got the same field as "name".
I tried to specify it as ;
<%= f.text_field :company["name"], autocomplete: "company_name" %>

<%= f.text_field :company[:name], autocomplete: "company_name" %>

<%= f.text_field :companies[:name], autocomplete: "company_name" %>

And i got the errors ;
undefined method `' for #<User:0x00007fd5588cb588>

no implicit conversion of Symbol into Integer

I think somehow i should override devise_controller but i want to learn the general practice for these kind of situations.
Sum: I want to save data to different tables which has same column names in database.

A: Assuming user belongs_to company and you want to save user and their associated company from one form submit, you can use fields_for for this
<%= f.fields_for :company do |cf| %>
  <%= cf.text_field :name %>
<% end %>

This will require accepts_nested_attributes_for :company in User.


text:
Q: Image cannot go full-width in react-native I want to make a screen with a full-width Android screen image, but however, for some reason I cannot do it. I have done every single solution available in SO but it still persists.
Here is my code:
<View style={styles.loginContainer}>
    <Image
        style={styles.background}
        source={require('./image.png')}
        //source={{uri: 'http://previews.123rf.com/images/background.jpg'}}
        opacity={0.8}
    >
    <Login navigator={navigator} />
    </Image>
</View>

and my Stylesheet:
var styles = StyleSheet.create({
loginContainer: {
    alignSelf: 'stretch',
    flex: 1,
    alignItems: 'stretch'
},
background: {
    alignSelf: 'stretch',
    flex: 1,
    alignItems: 'stretch'
},
});

For some reason it worked just fine when I used network images, but when I used static images, it will only cover 2/3 width but full height. I have also tried source={{uri: 'image.png', isStatic: true}}, but it gives me null error. Any solution is much appreciated. Thanks.

A: Yes, there is an open issue on Github.
First of all, I would suggest using the resizeMode property, for instance:
<Image
  style={styles.background}
  source={require('./image.png')}
  opacity={0.8}
  resizeMode="contain"
>

Then, for network images, this would work:
var styles = StyleSheet.create({
  loginContainer: {
    flex: 1,
  },
  background: {
    flex: 1,
  },
});

For 'required' images, it does not work, as you pointed out, so you can either specify the width yourself:
var width = require('Dimensions').get('window').width;
var styles = StyleSheet.create({
  loginContainer: {
    flex: 1,
  },
  background: {
    flex: 1,
    width: width,
  },
});

Or even set it to null:
var styles = StyleSheet.create({
  loginContainer: {
    flex: 1,
  },
  background: {
    flex: 1,
    width: null,
  },
});

A: You can use react-native-scalable-image. The following example will give you a full screen width image:
import React from 'react';
import { Dimensions } from 'react-native';
import Image from 'react-native-scalable-image';

const image = <Image width={Dimensions.get('window').width} source={{uri: '<image uri>'}} />;

A: try this    android:scaleType="fitXY"
<ImageView
    android:id="@+id/image_view_full"
    android:layout_width="fill_parent"
    android:scaleType="fitXY"
    android:layout_height="fill_parent" />


text:
Q: Java.lang.securityException java.lang.SecurityException: class "org.bouncycastle.util.Memoable"'s signer information does not match signer information of other classes in the same package
    at java.lang.ClassLoader.checkCerts(ClassLoader.java:952)
    at java.lang.ClassLoader.preDefineClass(ClassLoader.java:666)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:794)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2818)
    at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1148)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1643)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2818)
    at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1148)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1643)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
    at org.apache.catalina.startup.ContextConfig.checkHandlesTypes(ContextConfig.java:1956)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:1919)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:1806)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1765)
    at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1751)
    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1255)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:882)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:317)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:89)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5081)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1033)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:774)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1033)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:291)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)

Am using Spring core web-app ....am getting this issue while am deploying in to tomcat.can any one please please help me regarding this issue.
Thanks in advance....

A: This seems to be a certificate issue. I suggest to do the following:

*

*Check for certificate validity on the classpath using Java keytool.
Command: --> keytool -list -v -keystore keystore.jks

*Check if you have really need HTTPS, or it has been enabled by mistake

*If HTTPS is really required, please check for the certificate between the caller and called API are consistent. You can use the above command to do so.


text:
Q: SignalR- Jquery : $.connection.chathub returns undefined I'm creating a chat application using Asp.net MVC, AngularJs, SignalR and Jquery.
In the Chat View when I'm trying set the value for chat object it passes null value the code reference is inside the brackets ( var chat=$.connection.chathub;).  No other function works because of this.
I'm using "Microsoft.AspNet.SignalR.2.2.2" in this project. And jquery and signalr related scripts such as 'jquery.signalR-2.2.2.js ,jquery-ui-1.12.1.js' and few other jquery libraries as well.
Can anyone help me out? I have attached the code for your reference.

@section scripts{
    @*@Scripts.Render("~/Scripts/jquery-ui-1.12.1.min.js")
        @Scripts.Render("~/Scripts/jquery.signalR-2.2.2.min.js")*@

}
@model ZupChatApp.Models.User
@{
    ViewBag.Title = "ChatRoomView";
}

@Html.Label("LoggedInUser", Model.FirstName, new { id = "" })

Zup Chat Room View

    abcccc

        <input type="hidden" id="nickname" />

        @*

                Online Users

*@

                <textarea spellcheck="true" id="message" class="messagebox"></textarea>

                <input type="button" id="btnsend" value="Send" class="btn btn-success col-md-offset-2 glyphicon-font" />

A: This is probably an issue with the casing of chathub. From the "Getting Started with SignalR 2" documentation:

In JavaScript the reference to the server class and its members is in camel case. The code sample references the C# ChatHub class in JavaScript as chatHub.

So, change it to
var chat = $.connection.chatHub;

Also,  reference should be added before

A: You should always start with an exact copy of the sample from Microsoft. Not just for the page but the whole solution. Get the sample solution working.
This is true for any technology with which you are unfamiliar. Then start modifying things one thing at a time to arrive at your arrangement.
And, this is my page that worked (from a while ago). Compare and see what is different:
@section scripts {

}

  <input type="text" id="message" />
  <input type="button" id="sendmessage" value="Send" />
  <input type="hidden" id="displayname" />


text:
Q: Hotelling T2 Test for Non Normal Samples Is there an alternative to test if 2 samples come from the same population given that they don't pass normality tests? (this video assumes normality: https://www.youtube.com/watch?v=mkT3SaxoBJk, so it won't work for this question) For example, a sample may contain binomial, poisson, and normal variables, and same with the second sample. Is there some sort of bootstrap solution to know if these samples come from the same population. And if there is, would you be so kind as to provide a solution to implement it in R.
Possible Solutions I've thought of (given there's no other solution than Hotelling T2):
Thinking outside the box, could I normalize all variables and then run Hotelling T2 test?
Is there any loss of information or some serious mistake I could be running into if I tried this?
Second Solution:
I thought of running K-Means clustering with both samples and then checking if the distribution of both samples is similar on regards to how they are distributed among the centroids. Eg. sample 1 is distributed 75% on Centroid 1, 20% on centroid 2, and 5% on centroid 3. Then, assume that sample 2 falls on Centroid 3 50% of the time, and centroid 2 40%, and 10% on Centroid 1 then we can assume that they don't come from the same population (thinking of running Chi-Square test on these distributions). What do you think about this idea?
Your input would be appreciated.


text:
Q: Detect which Tilemap cells have collided with a Collider2D in Unity I have a Tilemap. This has a TilemapCollider2D component. Onto this are painted several tiles that each have their own sprite collider shape. However they are sprite tiles not prefabs. (They were not painted using the Prefab Brush.)
I also have a game object with a Collider2D (a CircleCollider2D in my case) with isTrigger set to true and no Rigidbody2D attached as this game object stays at a fixed position relative to its parent.
[EDIT: I discovered that this collider is actually using the Rigidbody2D of the parent game object. Without any rigid body, collisions wouldn't be detected at all.]
When the Collider2D enters/exits a tile, how can I identify the grid coordinates (Vector3Int) of that tile?
To be clear, I want to detect this from the Tilemap script. i.e. TilemapCollider2D.OnTriggerEnter2D() or TilemapCollider2D.OnCollisionEnter2D().
For example, in the picture below, I would want to have received OnTriggerEnter2D() for tiles B, C, D & E and to know their positions in the grid.

A: As this question covers not just the collision between the Collider2D and the TilemapCollider2D, but between the Collider2D and each tile, it is not as simple as detecting the collision between the colliders.
(Simple detection of collision between the colliders is covered in this question on answers.unity.com.)
For the tilemap script to detect the entry and exit of each tile, it needs to respond to OnTriggerEnter2D(), OnTriggerStay2D() & OnTriggerExit2D().
Here is my solution based on detecting when a CircleCollider2D intersects with each tile, not taking into account the geometry of any collider within the tiles. The intersections are an approximation (for efficiency) and may need adapting for other types of Collider2D.
Overview
Within OnTriggerEnter2D(), get the bounding box of the CircleCollider2D and from that identify which tiles it intersects with.
For each of those tiles, get the world position of CircleCollider2D that is closest to that tile's centre. If that world position is within the tile, then there is an intersection. As well as handling this as desired, also add this tile's coordinates to a tracking list.
Within OnTriggerStay2D(), do the same as OnTriggerEnter2D() but remove from the tracking list those tiles that no longer intersect and handle their intersection exits.
Within OnTriggerExit2D() the two colliders have separated, so handle intersection exits for all tiles in the tracking list and clear the tracking list.
Code example
using System.Collections;
using System.Collections.Generic;
using System.Linq; // needed for cloning the list with .ToList()
using UnityEngine;
using UnityEngine.Tilemaps; // needed for Tilemap

public class MyTilemapScript : MonoBehaviour
{
    List<Vector3Int> trackedCells;
    Tilemap tilemap;
    GridLayout gridLayout;

    void Awake()
    {
        trackedCells = new List<Vector3Int>();
        tilemap = GetComponent<Tilemap>();
        gridLayout = GetComponentInParent<GridLayout>();
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        // NB: Bounds cannot have zero width in any dimension, including z
        var cellBounds = new BoundsInt(
            gridLayout.WorldToCell(other.bounds.min),
            gridLayout.WorldToCell(other.bounds.size) + new Vector3Int(0, 0, 1));

        IdentifyIntersections(other, cellBounds);
    }

    void OnTriggerStay2D(Collider2D other)
    {
        // Same as OnTriggerEnter2D()
        var cellBounds = new BoundsInt(
            gridLayout.WorldToCell(other.bounds.min),
            gridLayout.WorldToCell(other.bounds.size) + new Vector3Int(0, 0, 1));

        IdentifyIntersections(other, cellBounds);
    }

    void OnTriggerExit2D(Collider2D other)
    {
        // Intentionally pass zero size bounds
        IdentifyIntersections(other, new BoundsInt(Vector3Int.zero, Vector3Int.zero));
    }

    void IdentifyIntersections(Collider2D other, BoundsInt cellBounds)
    {
        // Take a copy of the tracked cells
        var exitedCells = trackedCells.ToList();

        // Find intersections within cellBounds
        foreach (var cell in cellBounds.allPositionsWithin)
        {
            // First check if there's a tile in this cell
            if (tilemap.HasTile(cell))
            {
                // Find closest world point to this cell's center within other collider
                var cellWorldCenter = gridLayout.CellToWorld(cell);
                var otherClosestPoint = other.ClosestPoint(cellWorldCenter);
                var otherClosestCell = gridLayout.WorldToCell(otherClosestPoint);

                // Check if intersection point is within this cell
                if (otherClosestCell == cell)
                {
                    if (!trackedCells.Contains(cell))
                    {
                        // other collider just entered this cell
                        trackedCells.Add(cell);

                        // Do actions based on other collider entered this cell
                    }
                    else
                    {
                        // other collider remains in this cell, so remove it from the list of exited cells
                        exitedCells.Remove(cell);
                    }
                }
            }
        }

        // Remove cells that are no longer intersected with
        foreach (var cell in exitedCells)
        {
            trackedCells.Remove(cell);

            // Do actions based on other collider exited this cell
        }
    }
}

FYI
From a separate discussion on forum.unity.com, I learned a couple of important points (that weren't obvious to me):

*

*For a TilemapCollider2D, OnTriggerEnter2D() & OnTriggerExit2D() are invoked at the level of the whole TilemapCollider2D, not at a per-tile level. i.e. just like any other collider type.

*Collision2D.contacts is an array of ContactPoint2D. ContactPoint2D.point is described as "The point of contact between the two colliders in world space." which implies to me that it is the point of intersection. However, it is actually the location at which the physics model wants to apply force. As a result, my solution uses trigger colliders and OnTriggerXxxx instead of OnCollisionXxxx and I work out the intersections myself.

A: not sure about the set up you have, but I would suggest trying the colliders on the letter objects, they are children of the tile map right?
I have set up like this:
Tilemap
-A - has colider2d and rigidbody2d
-B - has colider2d and rigidbody2d
-C - has colider2d and rigidbody2d
-D - has colider2d and rigidbody2d
Circle - has circle collider2d and a circle script
the following is in the circle script and gives the exact trigger object
private void OnTriggerEnter2D(Collider2D collider)
{
    Debug.Log($"touched {collider.name}");
}

just note that you need at least one rigidbody to get a trigger but you can swap from the letters to the circle if you need.


text:
Q: iOS APNS not recv'd on device for dev and prod even tho http2 returns code 200 Ive recently changed the iOS APNS to use http2 with JWT rather than
certificates.  Initially it worked and all was well.  At some point I
broke it because I was not receiving development APN's, but production
was working.  After revoking both APN dev/prod certificates and making new
ones and getting a new APN token for push (during the course of trying to fix my first issue), my alerts are now broken for both (dev & production) even though the HTTP feedback code is 200.
I then tried to fix both issues with no luck.  Im sure the code that I had
working is still working, but it seems like apple is having some issue
that they aren't showing up on my device(s) at all.
Things Ive done/checked:
1. Re-created both dev and production push certificates
2. both dev and prod mobile provision profiles have been re-done/downloaded and installed.
3. Apple ID's show both Dev and Prod push is 'enabled'
4. in Xcode->Capabilities Push Notifications are turned on
5. deleted the app and re-installed for both dev and prod devices
6. made sure the APN device token (in My Application) is being updated to the server
7. Made sure Im sending to the right Dev/Prod push servers

Unless there's some order of doing things I didn't get right between
the developer portal and installing in Xcode, Im unsure where to go
from here.  Any help is appreciated!
Thanks in advance!
[SOLVED]
I found that the APN payload string had a problem.  It would be helpful
if apple could give some feedback code for that however the fact that
it returns code 200 may be indication enough that something is wrong with
the payload string.

A: Try sending a test push notification using command line. If that works then there is some issue in your server settings. If not then the issue is with your SSL certificate

A: Using single quotes instead of double quotes in the JSON payload will cause this:
        string payload = "{ 'aps' : { 'alert' : 'Hello' } }";  // wrong

        string payload = "{ \"aps\" : { \"alert\" : \"Hello\" } }";  // right


text:
Q: How can I change the size of my textview added programmatically on layout.addview On the following code, I programatically added the textview on the layout.addview
textView = new TextView(Chat.this);
/*textView.setTypeface(null, Typeface.BOLD);*/
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
    getResources().getDimension(R.dimen.original));
textView.setText(message);
final ImageView imgView = new ImageView(Chat.this);

LinearLayout childLayout = new LinearLayout(Chat.this);
LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(
    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp2.setMargins(0, 0, 0, 0);

LinearLayout.LayoutParams LPimgView = new LinearLayout.LayoutParams(
    100,
    100 /*ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT*/);

I also implemented a menu where a user can choose to resize the textviews on his screen by choosing one of the options given.  here's the code:
public void createDialogBoxWithRbutton(){
    /*totalMsg = countChatWithMsg1 + countChatWithMsg2;*/

    AlertDialog.Builder builder = new AlertDialog.Builder(Chat.this);
    builder.setTitle("Select From the Options");
    builder.setSingleChoiceItems(values, -1, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            /*for(int i = 0; i < layout.getChildCount(); i++){
                Toast.makeText(Chat.this, "Total messages: " + i, Toast.LENGTH_SHORT).show();
            }*/
            switch (item){
                case 0:
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.font1));
                    /*textSize = 15;*/
                    break;
                case 1:
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.font2));
                    /*textSize = 20;*/
                    break;
                case 2:
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.font3));
                   /* textSize = 30;*/
                    break;
            }
            alertDialog1.dismiss();
        }
    });
    alertDialog1 = builder.create();
    alertDialog1.show();
}

But what happen is that when I click an option, it is only the least textview on the layout view that is being changed. The other textview remains on its size.
What could be the cause of this?

A: you can use simple property for set textsize programatically
your_textview.setTextSize(24); // in sp


text:
Q: Blocking HDMI output of video For legal reasons we need to prevent users from playing the video in our app on external screen (TV, monitors), I know how to stop airplay output but we need to stop HDMI output as well, does anybody know if we can do this or perhaps we can detect HDMI output and stop the video playing altogether.

A: You can detect the external HDMI screens with: [[UIScreen screens] count]
Then you can get the external screen instance with: UIScreen* secondScreen = [[UIScreen screens] objectAtIndex:1];
Finally, you can create new UIWindow, ititialize it with the same screen bounds and assign the external screen to its .screen. You can add new views to this UIWindow instance.


text:
Q: Only update statement runs not the Select statement SQL BigQuery In my SQL query here. When I separate both the update (from line 1 to where 1=1) and the Select (Select *, to the end), they both run on my table. But when I put these 2 together like my query below only my update statement is running. How should I reformat my sql query so that both the update and select run.

update `np-inventory-planning-thd.IPP_SLA.sla_table`
set expected_start_date = timestamp(CONCAT( EXTRACT(DATE FROM TIMESTAMP(start_date)),' '
,EXTRACT(TIME FROM TIMESTAMP(expected_start_date)) )),
expected_end_date = timestamp(CONCAT( EXTRACT(DATE FROM TIMESTAMP(end_date)),' '
,EXTRACT(TIME FROM TIMESTAMP(expected_end_date)) ))
where 1=1;

SELECT *,  TIMESTAMP_DIFF(start_date, expected_start_date, MINUTE) AS Difference_Start_Time,

TIMESTAMP_DIFF(end_date, expected_end_date, MINUTE)  AS Difference_End_Time,

CASE WHEN TIMESTAMP_DIFF(start_date, expected_start_date, MINUTE) <= 0 THEN TRUE WHEN TIMESTAMP_DIFF(start_date, expected_start_date, MINUTE) > 0 THEN FALSE END AS Started_On_Time,

CASE WHEN TIMESTAMP_DIFF(end_date, expected_end_date, MINUTE) <= 0 THEN TRUE WHEN TIMESTAMP_DIFF(end_date, expected_end_date, MINUTE) > 0 THEN FALSE END AS end_date_tracker,

CASE WHEN end_date is null then 'FAILED' ELSE 'COMPLETED' END AS status_tracker
FROM `np-inventory-planning-thd.IPP_SLA.sla_table`;


text:
Q: Fatal error Xcode 8 Swift 3 ok guys can I get a little help with my code. When running the app I get an error is there any way to fix this problem?
let fileUrl = dict["fileUrl"]as! String
let url = NSURL(string: fileUrl)
let data = NSData(contentsOf: url! as URL!)
let picture = UIImage(data: data! as Data!)
let photo = JSQPhotoMediaItem(image: picture)
self.messages.append(JSQMessage(senderId: senderId, displayName: senderName, media: photo))

Image here

A: Here I see 4 big fat problems with your code.

*

*You are force casting the value of fileUrl of the dictionary dict to String. If your dictionary doesn't have the value for fileUrl, or if it's not castable to string, your code will crash. You should change that to optional cast like:
if let fileUrl = dict["fileUrl"] as? String
{
//your code if you have fileUrl
}

*When creating the url to the file, you are using the wrong initialization method, you should be using this:
let url = URL(fileURLWithPath: fileUrl)

*After you have the url to the file, you should also check if you have the data of the file, because contentsOfFile: initializer of the NSData returns the optional object, which may be nil, so another if check:
if let data = NSData(contentsOf: url) {\\ code with the data}

*init?(data: Data) initializer of the UIImage also returns optional object, so if the required by latter code, you should also check if you have the image or nil with if statement.
The result code should be something like:
if let fileUrl = dict["fileUrl"] as? String {
            let url = URL(fileURLWithPath: fileUrl)
            if let data = NSData(contentsOf: url) {
                let image = UIImage(data: data as Data) // you can cast NSData to Data without force or optional casting
                let photo = JSQPhotoMediaItem(image: image)
                self.messages.append(JSQMessage(senderId: senderId, displayName: senderName, media: photo))
            }
        }

Hope this helps.

A: Replace the first line of code with this line for optional binding check :-
guard let fileUrl = dict["fileUrl"] as! String else {return}

A: Yo should do validation in cases where the variable may be nil, the following is an example:
if let fileUrl = dict["fileUrl"] as? String {
    let url = URL(string: fileUrl)
    do {
        let data = try Data(contentsOf: url!)
        let picture = UIImage(data: data)
        let photo = JSQPhotoMediaItem(image: picture)
        self.messages.append(JSQMessage(senderId: senderId, displayName: senderName, media: photo))
    } catch {

    }
}


text:
Q: How to write and log to a file on my NAO robot I'm using Choregraphe on Windows to implement programms with Python for my NAO robot. I have two problems which I can't solve by myself:

*

*I want to create a textfile on NAO robot and write information in it. Later I want to store it to my computer. Leading to this article - reading a textfile
I used the following code in a Python Box:
import logging
 filepath = os.path.join(os.path.dirname(ALFrameManager.getBehaviorPath(self.behaviorId)), "fileName.txt")
maybeContains = None
try:
    with open(filepath, "r") as textfile:
        maybeContains = textfile.readlines()
except:
    pass
with open(filepath, "a") as textfile:
    if maybeContains == "":
        agenda = "type1;type2;\n"
        textfile.write(agenda)
        textfile.write(storedData)
    else:
        textfile.write(storedData)
self.onStopped()

When I try to download the file "fileName.txt" via Connection > Advanced > File Transfer there isn't that file in one of those listed orders.

*I also want to create a textfile on the robot to log informations from the coding, so I can check the actions of the robot. As in 1. I want to download the log fiel to the computer.

I added to the onLoad() method of a "Say Text"-box the following code:
     def onLoad(self):
    self.logging.basicConfig(filename="20180712.log", format='%(asctime)s %(levelname)s-8s [%(filename)s:%(lineno)d]%(message)s', level=logging.DEBUG)
self.logger = self.logging.getLogger("Behavior - Box") `

    Before a command, which should be logged I call
    `    self.logger("what happened here")

A: the "Connection > Advanced > File Transfer" open a file at a specific location.
Depending on the version of your robot. Some years ago it was "/var/www" or "~/ftp/" ...
On my current NAO (2.1), it's in "/home/nao".
So the good way in my case is to create the file at this place:
filepath = "/home/nao/myfile.txt"

That being said, there's better way to get a file from your robot, on windows, you can use winscp (gui) or pscp (cli), it's far more convenient than Choregraphe...
Good luck.


text:
Q: How to remove data from a single array after comparing it with an array from a database? So currently, I have a single array ($array1) that I want to compare with an array ($array2) that I created by retrieving data from the database. Technically speaking, $array2 is multidimensional since I used a while loop with mysqli_fetch_assoc. Is there any way to compare these two arrays with each other? My end goal is to compare these two arrays, and to only remove the data from the single array ($array1) when there is a mismatch. By that, I mean only to remove the data that doesn't match with $array2.
For example:
$array1 = Array ( [0] => cookies [1] => chicken [2] => tesla )
$array2 = Array ( [name] => tesla ) Array ( [name] => bmw ) Array ( [name] => opel )
So in this case, $array2 came from the database, and $array1 is given. So how can I compare these two arrays in order to get this array back: $arraynew = Array ( [0] => tesla )?
Note:
So far I have tried this:
            $query = "SELECT name FROM tagsbreedables WHERE idTagCategory = 6";
            $result10 = mysqli_query($conn, $query);

            if (mysqli_num_rows($result10) > 0) {
                while ($row = mysqli_fetch_assoc($result10)) {
                    $bloem = $datas4['name'] = $row;

                    print_r($row);

                    $subarray = array_column($bloem,'name');

                    print_r($array3);

                }
            }

        $aMust = explode(" ", $_GET['q']);
        $searchTermBits = array();
        foreach ($aMust as $term) {
            $term = trim($term);
            if (!empty($term)) {
                $searchTermBits[] = "$term";
            }
        }
        $matches = $searchTermBits;
        $test = array($subarray, $matches);

        foreach ($test as $key => $subarray) {
            foreach ($subarray as $subsubarray) {
                foreach ($matches as $match) {
                    if ($subsubarray == $match) {
                        $finalarr[$key][] = $subsubarray;
                    }
                }
            }
        }
        print_r($finalarr[0]);

        $pindakaas = implode('","',$finalarr[0]);
        echo $pindakaas;

The code works great, it's just that I don't know how to get data from the database into $subarray... I just get Array ( ) Array ( ) ...for $array3

A: if $array2 is an array of arrays like below
array(Array ( [name] => tesla ) Array ( [name] => bmw ) Array ( [name] => opel ))

you can use the function array_column to get the values from a single column, in this case name.
$array3 = array_column($array2,'name')

the above should give you
array(0=>tesla,1=>bmw,2=>opel)

you can then use array_intersect to compare them
$arraynew = array_intersect($array1,$array3);


text:
Q: Function minimization with non-linear constraints using scipy.optimize.minimize 'SLSQP' method Error I'm trying to minimize a maximum likelihood function with non linear constraints:
    #Maximum Likelihood
import math
from scipy import optimize

#Define functions

#K-generalized exponential
def exp_k(x,k):
    e=(math.sqrt(1+(k**2)*(x**2))+(k*x))**(1/k)
    return e
#Beta (for non-linear equality constraint)
def beta(theta):
    a=theta[0]
    b=theta[1]
    k=theta[2]
    B=(1/(2*k))*((math.gamma(1/a)*math.gamma((1/(2*k))-(1/(2*a)))))/(((k+a*(math.gamma((1/(2*k))+(1/(2*a))))))**a)-b
    return B
#Beta's pdf
def p(x,theta):
    a=theta[0]
    b=theta[1]
    k=theta[1]
    pdf=(a*b*(x**(a-1))*exp_k(-b*(x**a),k))/math.sqrt(1+(k**2)*(b**2)*(x**(2*a)))
    return pdf
#Maximum likelihood logaritmic function
def max_likelh(theta):
    x=[0.001960784,0.096078431,0.194117647,0.292156863,0.390196078,0.488235294,
    0.58627451,0.684313725,0.782352941,0.880392157,0.978431373,1.174509804,
    1.370588235,1.566666667,1.762745098,1.958823529,2.154901961,2.743137255,
    3.331372549,3.919607843,5.882352941]
    w=[0.078155633,0.06292445,0.131394783,0.32198121,1.010524004,0.925629323,
    0.889101147,0.840841293,0.815564861,0.73600276,0.634737057,0.516167129,
    0.333792876,0.255670572,0.17205571,0.090707194,0.039736612,0.014291316,
    0.002790717,0.002189501,0]
    l=0
    for i in range(len(x)):
        l=l+((math.log(p(x[i],theta),math.e))**w[i])
    return l

#OPTIMIZATION
#Boundaries (alpha, beta, kapa)
bnds = ((0, None),(0,None),(0,0.99999))

#Constraints
cons ={'type': 'eq', 'fun': beta}

#First parameter estimation
x0=[1,1,0.5]

#Optimize
res = scipy.optimize.minimize(max_likelh, x0, method='SLSQP', bounds=bnds, constraints=cons)
res.theta

I get these two errors:
TypeError: can't convert complex to float
ValueError: Objective function must return a scalar
What am I doing wrong to get a complex number? All the values in the sqrts are supposed to be positive.


text:
Q: how to convert list of objects to json using gson when object has ArrayList attribute I am trying to store some list of objects in sharedpreference when my app is first time launched and i am going to use this list of objects in subsequent usage of my app.
myclass:
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

public class MyClass {
    private int a;
    private String b;
    private int c;
    private ArrayList<NameValuePair> d;

    public MyClass(int a, String b, int c) {
        super();
        this.a = a;
        this.b = b;
        this.c = c;

    }

    public MyClass(int a, String b, int c, ArrayList<NameValuePair> d) {
        super();
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
    }

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }

    public String getB() {
        return b;
    }

    public void setB(String b) {
        this.b = b;
    }

    public int getC() {
        return c;
    }

    public void setC(int c) {
        this.c = c;
    }

    public ArrayList<NameValuePair> getD() {
        return d;
    }

    public void setD(ArrayList<NameValuePair> d) {
        this.d = d;
    }

    public static List<MyClass> getMyObjects() {
        // TODO Auto-generated method stub
        List<MyClass> myObjects = new ArrayList<MyClass>();

        ArrayList<NameValuePair> temp1 = new ArrayList<NameValuePair>();
        temp1.add(new BasicNameValuePair("1", "20"));
        temp1.add(new BasicNameValuePair("2", "30"));
        temp1.add(new BasicNameValuePair("3", "40"));

        ArrayList<NameValuePair> temp2 = new ArrayList<NameValuePair>();
        temp2.add(new BasicNameValuePair("1", "50"));
        temp2.add(new BasicNameValuePair("2", "60"));
        temp2.add(new BasicNameValuePair("3", "70"));

        ArrayList<NameValuePair> temp3 = new ArrayList<NameValuePair>();
        temp3.add(new BasicNameValuePair("1", "50"));
        temp3.add(new BasicNameValuePair("2", "60"));
        temp3.add(new BasicNameValuePair("3", "70"));

        myObjects.add(new MyClass(1, "ABC", 20, temp1));
        myObjects.add(new MyClass(2, "DEF", 30, temp2));
        myObjects.add(new MyClass(3, "GHI", 40, temp3));

        return myObjects;
    }
}

i've created the list of objects and stored in sharedpreference using following lines of code:
 List<MyClass> myObjects = MyClass.getmyObjects();
    String myObjectsJSONString = new Gson().toJson(myObjects);
    prefsEditor.putString("MYOBJECTS", myObjectsJSONString);

JSON string formed as expected while writing myObjects to sharedpreference
sample:
 [{"d":[{"name":"1","value":"20"},{"name":"2","value":"30"},{"name":"3","value":"40"}],"b":"ABC","c":20,"a":1},{"d":[{"name":"1","value":"50"},{"name":"2","value":"60"},{"name":"3","value":"70"}],"b":"DEF","c":30,"a":2},{"d":[{"name":"1","value":"50"},{"name":"2","value":"60"},{"name":"3","value":"70"}],"b":"GHI","c":40,"a":3}]

in subsequent usage i am trying to populate my list using following lines of code:
String myobjectsJSONString =appPrefs.getString("MYOBJECTS", null);
Type type = new TypeToken < List <MyClass>> () {}.getType();
List <MyClass> myObjects = new Gson().fromJson(myobjectsJSONString, type);

I am able to store and generate my list of objects from sharedpreferences
without attribute "d", which is of ArrayList<NameValuePair> type;
But, with "d" as one of the attributes, i am unable to generate the object.
Error shown is :
java.lang.RuntimeException: Unable to invoke no-args constructor for interface org.apache.http.NameValuePair. Register an InstanceCreator with Gson for this type may fix this problem
the above exception raised while trying to populate objects from the json stored in sharedpreference

A: I think I get it now: Your MyClass includes a field
private  ArrayList<NameValuePair> d;

NameValuePair however, is actually Apache's org.apache.http.NameValuePair, which is an interface. As such, Gson cannot create instances of it - it can only create instances of a class.
You could try changing that to
private  ArrayList<BasicNameValuePair> d;

but that class doesn't seem to have a no-arguments constructor, so it might not work either (this answer, though, says it should: https://stackoverflow.com/a/18645370/763935).
So your safest bet might be to write your own class implementing NameValuePair:
public class MyNameValuePair implements NameValuePair {
    private final String name;
    private final String value;

    public MyNameValuePair() {
        this.name = null;
        this.value = null;
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public String getValue() {
        return this.value;
    }
}

A: You can do like this:
{
    "Result": [{
        "name": "1",
        "value": "100"
    }, {
        "name": "1",
        "value": "100"
    }, {
        "name": "1",
        "value": "100"

    }]
}

use :
Type listType = new TypeToken<List<BeanClass.ResultEntity>>() {
            }.getType();

            List<BeanClass.ResultEntity> list = new Gson().fromJson(response.toString(), listType);

It will work definitely...


text: Q: How to search Jira with Link = Empty? How to search Jira with Link = Empty? I am trying to search for list of issues which do not have links. To be specific, For example, I am looking for duplicates issues but the duplicates are not linked. We are using Jira v6.


text:
Q: What is the difference between limit inferior and limit? So, I am working on problems on $L_p$ spaces. Every time I think of taking limits of both sides of an equation, the solution seems to take limit inferior/ limit superior instead and use the relation between them to prove an equality.
As an example, I had for all $p$
 and arbitrary $M\leq\|f\|_\infty$,
$$\|f\|_p \geq \mu(E)^{1/p}M$$
where the norm is the $L_p$ norm of a function on $(X,\mu)$ and $E$ is a set of finite measure.
Now I was going to take the limit of both sides with $p\to \infty$, and then take limit of $M$ going to $\|f\|_\infty$ to show that
$$\lim_{p\to\infty}\|f\|_p\geq \|f\|_\infty$$
but the solutions specifically take $\liminf_{p\to\infty}$.
I am confused on why they do this? Am I making a fundamental mistake?
Thanks!

A: We take the $\liminf$ because we don't know a priori the limit exists, while the $\liminf$ (possibly infinity) always exists.
(here it turns out that the limit indeed exists, we we don't know it yet at this step)


text:
Q: something like EVT_OPEN wxPython I want to run some code after the window has loaded. I imagined using EVT_OPEN, as opposite of EVT_CLOSE, to do this, only to find out it doesn't exist.
I have some code that must run after the window has loaded and that updates a gauge in that window. Therefore I can't run it in the __init__ of the frame. How do I do this?

A: There's EVT_WINDOW_CREATE.  From the docs: "The EVT_WINDOW_CREATE event is sent as soon as the window object (the underlying GUI object) exists."

A: You can try EVT_SHOW
http://www.wxpython.org/docs/api/wx.ShowEvent-class.html
Note that this event occurs for both show and hide - you need to call GetShow to determine which event occurred.
Or you could do something like this:
wx.CallAfter(self.update_gauge) (for example) in your __init__


text:
Q: SDP for FFMPEG (IP addresses) I'm receiving audio via RTP, so I'm opening input from the SDP I generate.
Media is coming from Port_sender, IP_sender. IP and port of the server for listening: IP_server, Port_server. Here is my SDP template. What of {Port_sender, IP_sender, IP_server, Port_server} should I put in {%1%, %2%, %3%} for the SDP that I feed to ffmpeg and for the SDP that I give back to the sender?
\n\nv=0\n
o=- 0 0 IN IP4 %1%\n
s=name\n
c=IN IP4 %2%\n
t=0 0\n
a=tool:libavformat 57.3.100\n
m=audio %3% RTP/AVP 97\n
b=AS:705\n
a=rtpmap:97 PCMU/44100/2\n"

Debugging it from different IPs is hard for me now. But from one computer it works perfectly.

A: I encourage you to read the RFC 4566, it explains everything you are wondering.

*

*o= stands for Origin

*c= stands for Connection data

*m= stands for Media descriptions
For the question at hand, I assume you receive a SIP INVITE with a SDP offer, and you have to reply with a SIP 200 OK containing the SDP reply.
In that scenario you should reply with:

*

*%1% -> IP_server

*%2% -> IP_server, assuming a uni-cast session "the connection address contains the uni-cast IP address of the expected data source"

*%3% -> Port_sender, since m= is the transport port to which the media stream is sent (Port that was defined by the sender in his offer).


text:
Q: Firebase: Authenticate an existing user using REST API and Firebases hidden Auth URL For the past 3 years we have used HTML/Js only with Firebase but now we are using Unity as well.
The current Unity/Firebase only works on Android/iOS when deployed and 99% of our work is on the windows store.
I've actually got a pretty decent Unity/Firebase codebase going but it requires me to use a full App Secret.
All the other libraries expose a method to login with Email/Password but the REST API only allows the use of a token or your app secret that it then states is ill advised to put into your client; I guess the thinking is if you're using a different library that you'll have your own auth/user method which we don't...
Now, I've pulled apart the web version and got this:
https://auth.firebase.com/v2/<myfirebase>/auth/password?&email=dennis%40<mysite>&password=<mypassword>v=js-2.2.9&transport=json&suppress_status_codes=true

So there IS an endpoint that I can send stuff to and I've tested it inside unity with good results.
Obviously the URL isn't guaranteed to stay working but I'm wondering if there is any reason NOT to use this?
Also, Why not just expose this endpoint in the official REST API?

A: As I understand it, that URL will continue to work for your Legacy Firebase project. You will have to do the same sort of reverse engineering if you want to update to the new Firebase 3.0 API. However, if you are still using a legacy Firebase project -- I encourage you to take a look at this. It has not been updated to work with Firebase 3.0 -- so I needed to do something similar to what you did to allow login to the new API.
I was able to do this with the new API using C# as follows (where FirebaseManager is a Singleton I wrote for Global variables and functions to write and read from/to the DB :
Hashtable loginData = new Hashtable();
loginData.Add ("email", <EMAIL-GOES-HERE>);
loginData.Add ("password", <PASSWORD-GOES-HERE>);
loginData.Add ("returnSecureToken", true);
UnityHTTP.Request loginRequest = new UnityHTTP.Request ("post",
    "https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key="
    + <YOUR-PROJECT-API-KEY-GOES-HERE>, loginData);

loginRequest.Send ((request) => {
    Hashtable jsonResponse = (Hashtable)JSON.JsonDecode(request.response.Text);
    if (jsonResponse == null) {
        DisplayErrorMessage("Error logging in. Server returned null or malformed response");
    }
    FirebaseManager.Instance.idToken = (string)jsonResponse["idToken"]; // This is your auth token
    FirebaseManager.Instance.uid = (string)jsonResponse["localId"]; // this is your "uid"
});

// I have a list of users in my db keyed by the "uid" -- I access them like this

UnityHTTP.Request fullnameRequest = new UnityHTTP.Request ("get",
    <YOUR-DATABASE-ROOT-URL-HERE>
    + "/users/" + FirebaseManager.Instance.uid + ".json?auth=" + FirebaseManager.Instance.idToken);

fullnameRequest.Send ((request) => {
    Debug.Log(request.response.Text);
    Hashtable jsonResponse = (Hashtable)JSON.JsonDecode(request.response.Text);
    if (jsonResponse == null) {
        DisplayErrorMessage("Error getting user info. Server returned null or malformed response");
    }
    FirebaseManager.Instance.fullname = (string)jsonResponse["fullname"];
    FirebaseManager.Instance.groupId = (string)jsonResponse["group"]; // just storing this in memory
});

So I don't think there is any harm in using the URL, just make sure you budget time for more work when things change.


text:
Q: Angular OnInit not triggered after routing to component I just ran into a very weird problem I've never had with the angular router before.
I'm using a leaflet plugin to display some map markers related to my underlying dataset. In order to get to more detail information about these places a click on one of the markers should route the user to another component called detail by passing the respective dataset id within the url (detail/:id).
However, in this case the component is loaded and the constructor is called, but the implemented OnInit function is not triggered as normally. There's just nothing happening there.
All this can also be seen in this stackblitz example.
Is this a known bug in the current release of Angular (6.0.5)?
If so, is there a workaround?
Cheers and thanks in advance

A: Clicking on marker runs logic outside of NgZone which prevents change detection from happening. You need to run it manually.
Inject NgZone into MapComponent
export class MapComponent {
...
  constructor(private router: Router, private ngZone: NgZone) {...}

Then change
 marker_label.on('click', (event: MouseEvent) => {
            const link = ['detail', id];
            this.router.navigate(link);
        });

to
marker_label.on('click', (event: MouseEvent) => {
            const link = ['detail', id];
            this.ngZone.run(() => this.router.navigate(link))
        });


text:
Q: How to update saved credit card information using stripe from app side(swift) I have issue regarding Stripe.I am using Stripe for payment in my app.So is it possible that i can update stored user's card information from app side ? is there any method for update stored card information from application side?

A: By design, this is not possible.
Cf. this StackOverflow answer (I talked about Android in that answer but iOS is in the same boat).


text:
Q: Grad-CAM with hub.KerasLayer I have a custom model, which has 2 instances of inception resnet v2 models from tensorflow hub
...
 self.original_model = hub.KerasLayer(
            "https://tfhub.dev/google/imagenet/inception_resnet_v2/feature_vector/5",
            trainable=False,
            name='original_layer'
        )
        self.fractal_model = hub.KerasLayer(
            "https://tfhub.dev/google/imagenet/inception_resnet_v2/feature_vector/5",
            trainable=False,
            name='fractal_layer'
        )
...

I want to get Grad-CAM,  like in the example https://keras.io/examples/vision/grad_cam/ .
The problem is, that example works with keras application and not KerasLayer .
KerasLayer doesn't really give access to its internal structure.


text:
Q: Touchpad and wireless adapter not recoginsed Acer Aspire V3-372-53UE I have installed the offical Ubuntu 14.04 OS. After booting I have realized that my touchpad and wifi are not working. I connected usb mouse and usb wifi adapter and they are both working so I think I am having troubles with drivers. Can anyone help? Btw everything is working on Windows 10.
Thanks in advance!
02:00.0 Ethernet controller [0200]: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller [10ec:8168] (rev 15)
    Subsystem: Acer Incorporated [ALI] Device [1025:104c]
    Kernel driver in use: r8169
03:00.0 Network controller [0280]: Qualcomm Atheros QCA6174 802.11ac Wireless Network Adapter [168c:003e] (rev 32)
    Subsystem: Lite-On Communications Inc Device [11ad:0807]
    Kernel driver in use: ath10k_pci

A: I don't know why are you having problems with the touchpad, but the thing with the wifi is very normal for the newest pc on the market,  so for that problem you can try this :
https://help.ubuntu.com/community/WifiDocs/Driver/Ndiswrapper
that's gonna install the wifi drivers of windows on Ubuntu or something like that, btw I'm not a english speaker (?) so my redaction have a lot of mistakes , but I want to help you
saludos :)


text:
Q: Java/MySql - getting a row and convert it to a arraylist I am trying to get a row and convert it to a array I alredy tried to convert the resultset.getArray() to a ArrayList but for some reason it returned nothing somebody help me with this
code now:
public ArrayList<String> getReport(String name) {
    try {
        Statement sql =  mySql.getConnection().createStatement();
        ResultSet resultSet = sql.executeQuery("SELECT * FROM `reports` WHERE `reportedplayer`='" + name + "';");
        if(!resultSet.next()) {
            sql.close();
            resultSet.close();
            return null;
        }
        ArrayList<String> rowValues = new ArrayList<String>();
        while (resultSet.next()) {
            rowValues.add(resultSet.getString("reason"));
        }
        sql.close();
        resultSet.close();
        return rowValues;
    }catch (SQLException e) {
        e.printStackTrace();
        return null;
    }
}

A: You should read column names from resultSet metadata and then iterate over the names for each row. Maybe better idea will be to store the parameters as ArrayList<HashMap<String,String>>than intoArrayList<String>, since select * doesn't say anything about order of the fileds you read.
But if you know for sure you have just one row, and you know the order, or maybe the order doesn't matter, you could use something like this:
public ArrayList<String> getReport(String name) {
    try {
        Statement sql =  mySql.getConnection().createStatement();
        ResultSet resultSet = sql.executeQuery("SELECT * FROM `reports` WHERE `reportedplayer`='" + name + "';");
        if(!resultSet.next()) {
            sql.close();
            resultSet.close();
            return null;
        }
        ArrayList<String> rowValues = new ArrayList<String>();
        int columnCount = resultSet.getMetaData().getColumnCount();
        String[] columnNames = new String[columnCount];
        for (int idx=0; idx<columnCount; idx++) {
            columnNames[idx] = resultSet.getMetaData().getColumnName(idx);
        }

        while (resultSet.next()) {
            for (String columnName: columnNames) {
                rowValues.add(resultSet.getString(columnName));
            }
        }
        sql.close();
        resultSet.close();
        return rowValues;
    }catch (SQLException e) {
        e.printStackTrace();
        return null;
    }
}

A: Your line:
if (!resultSet.next())

Is moving to the second row without even looking at the first row. You should also have a finally block to handle closing to ensure that it is always carried out properly.
try {
    Statement sql =  mySql.getConnection().createStatement();
    ResultSet resultSet = sql.executeQuery("SELECT * FROM `reports` WHERE `reportedplayer`='" + name + "';");
    List<String> rowValues = new ArrayList<String>();
    while (resultSet.next()) {
        rowValues.add(resultSet.getString("reason"));
    }
    return rowValues.isEmpty() ? null : rowValues;
} catch (SQLException e) {
    e.printStackTrace();
    return null;
} finally {
    sql.close();
    resultSet.close();
}

A: resultSet.next() will move the cursor to the next row.
1st time when you call resultSet.next() in the if condition it will point to 1st row and when you again call resultSet.next() in the while condition it will point to the 2nd row.
since you are using the resultSet.next() twice you will be getting the 2nd row onwards into the list. If you have only one row in the table you will not get anything in the list.
You can close the connection in the finally block as shown below.
    finally
    {
        try {
        sql.close();
        resultSet.close();
        } catch (SQLException e) {
        e.printStackTrace();
        }
    }


text:
Q: How to handle autocomplete list in webdriver? How to select country name from auto-complete drop down list?
Please provide suggestion with code for Google search so that i can understand.

A: If your dropdown is editable you can directly type the values using send keys, else you need to simulate the Arrow down key actions as you needed. But it not wise once, because if new values are added in the drop down(Anyway in this case, there will be fixed because the number of countries is a constant),then it will get messed.
driver.findElement(locator).sendKeys(countryName , Keys.TAB);

or
driver.findElement(locator).sendKeys(Keys.DOWN);

A: Try the following code:
WebElement dropdown = driver.findElement(By.....);
Select dropdownSelect = new Select(dropdown);
dropdownSelect.selectByVisibleText(itemStr) or selectByValue(value);

A: Link : http://www.mythoughts.co.in/2012/05/getting-google-search-auto-suggestions.html#.Ul-lJdi1Zbc
@Test
  public void SearchSuggestion() {

  driver.get("http://google.com");
  driver.findElement(By.id("gbqfq")).sendKeys("vam");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

   WebElement table = driver.findElement(By.className("gssb_m"));
   List<webelement> rows = table.findElements(By.tagName("tr"));
   Iterator<webelement> i = rows.iterator();
   System.out.println("-----------------------------------------");
   while(i.hasNext()) {
           WebElement row = i.next();
           List<webelement> columns = row.findElements(By.tagName("td"));
           Iterator<webelement> j = columns.iterator();
           while(j.hasNext()) {
                   WebElement column = j.next();
                   System.out.println(column.getText());
           }
           System.out.println("");

   System.out.println("-----------------------------------------");
   }
  }
}

A: driver.findElement(By.id("your searchBox")).sendKeys("your partial keyword");
Thread.sleep(3000);
List <WebElement> listItems = driver.findElements(By.xpath("your list item locator"));
listItems.get(0).click();
driver.findElement(By.id("your searchButton")).click()


text:
Q: Best method for adding compass to a django project What's the preferred or best method for integrating compass with susy or blueprint into a django project?

A: Your best bet is to use django-css, a fork of django-compressor which also does css compilation of SASS. Once you have that plugged in, you can use compass, susy and blueprint as normal, and they will be compiled by django whenever it detects an updated version of the source files.
EDIT: If you are deploying on a pure python host such as ep.io, you will want to research how easily these build into cleverCSS (Pure python SASS&SCSS compiler)
EDIT 2:
This info has dated. django-compressor is now the best option as it has the preprocessing facilities built in, and it will be able to bundle up the files for you too ;)

A: We've chosen to avoid automatic runtime sass/compass compilation, and instead simply use "compass --watch" in development and commit both Sass and the generated CSS to the repository. Then there is no special machinery at all required in your Django project; you just handle the CSS files as you normally would.
This has several advantages for us:

*

*Removes an entire additional chunk of moving parts from our deployment and production server infrastructure: no need to have a full Ruby stack, plus Sass, Compass, and any other required gems on our production servers. Making production servers simpler is A Very Good Thing. Also, no issues deploying to pure-Python hosting.

*No mysterious subtle display inconsistencies between one developer and another, or between development and production, because of minor differences in something like a Compass plugin gem version. Everyone sees the same CSS. Differences between developers' Compass environments are caught quickly, because they show up right away as unexpected changes in the pre-commit diff of the generated CSS.

The disadvantage, of course, is committing generated code to the repo, which is generally frowned upon. We haven't seen any actual problems as a result of this, though. Nobody is tempted to edit the generated CSS directly; we all know that we use Compass. The advantages definitely outweigh the disadvantages, for us - we've never had the slightest temptation to switch to an integrated approach like django-css.


text:
Q: How do I validate nested properties using anyOf I'm struggling to write a validation rule using json-schema. Here is my data in json format:
{
    "headers" : {
        "api_key" : "aaa-bbb-ccc-ddd-eee"
    },
    "query_string" : {
        "apikey" : "aaa-bbb-ccc-ddd-eee"
    }
}

I need a rule that says:

At least "headers->api_key" or "query_string->apikey" needs to be present in the json, but not both.

Here is my schema validation so far:
{
  "title": "Application Get Single",
  "type": "object",
  "properties": {
    "headers": {
      "type": "object",
      "properties": {
        "api_key": {
          "type": "string"
        }
      }
    },
    "query_string": {
      "type": "object",
      "properties": {
        "apikey": {
          "type": "string"
        }
      }
    }
  },
  "anyOf": [
    {"required": ["headers"["api_key"]]}, // what should this be??
    {"required": ["query_string"["apikey"]]} // what should this be??
  ]
}

I think it's anyOf I'm looking for but I don't know how to refer to a nested json items above.
At the moment I get an error:

JSON syntax is malformed

I'm using Justin Rainbow as I'm working with PHP for this.

A: There are a couple ways.  The most straightforward is:
{
  "title": "Application Get Single",
  "type": "object",
  "properties": {
    "headers": {
      "type": "object",
      "properties": {
        "api_key": {
          "type": "string"
        }
      }
    },
    "query_string": {
      "type": "object",
      "properties": {
        "apikey": {
          "type": "string"
        }
      }
    }
  },
  "anyOf": [
    {
      "properties": {
        "headers": {
            "type": "object",
            "required":["api_key"]
        }
      }
    },
    {
      "properties": {
        "query_string": {
            "type": "object",
            "required":["apikey"]
        }
      }
    }
  ]
}

You would probably also want "minProperties": 1 on the root object in order to ensure that either headers or query_string exist.
EDIT: Just re-read the question and if headers.api_key and query_string.apikey are mutually exclusive change anyOf to oneOf

A: The trick is the "and not the other" part.  Here's what I'd recommend (assuming draft-06 or later, see below for draft-04):
{
  "title": "Application Get Single",
  "type": "object",
  "properties": {
    "headers": {
      "type": "object",
      "properties": {
        "api_key": {
          "type": "string"
        }
      }
    },
    "query_string": {
      "type": "object",
      "properties": {
        "apikey": {
          "type": "string"
        }
      }
    }
  },
  "oneOf": [
    {
      "required": ["headers"],
      "query_string": false
    },
    {
      "required": ["query_string"],
      "headers": false
    }
  ]
}

For draft-04, replace false with {"not": {}} which means the same thing but is annoying to read.  But you can't use boolean schemas in most places in draft-04 so you need the verbose way of saying "this property must not be present".


text:
Q: Are the -webkit or -moz or whatever properties really necessary? I wanted to put box shadow on an element, this time instead of filling the parameters manually, I used an online generator which gave me an output like this:
-webkit-box-shadow: 0px 10px 7px -8px rgba(0,0,0,0.25);
-moz-box-shadow: 0px 10px 7px -8px rgba(0,0,0,0.25);
box-shadow: 0px 10px 7px -8px rgba(0,0,0,0.25);

But its just the same thing 3 times over, I'd get it if there were some parametric differences between different browser implementations but in this case there aren't any. Also, just plain old
box-shadow: 0px 10px 7px -8px rgba(0,0,0,0.25);

works in all modern browsers anyway so why would I want to bloat my css file?

A:
Are the -webkit or -moz or whatever properties really necessary?

Do you want to use experimental / unstable / non-standard CSS properties that are at the bleeding edge of support in the browsers they appear in?
Then yes.
Do you want to use stable, standard CSS properties that have had their specs finalised and will only work in browsers that think they have a robust implementation?
Then no.

And related to that — "Is box-shadow 'experimental / unstable / non-standard'"?
See the support chart: Not these days.

A: It depends on your asnwer to question;
Should my web app work on older browsers?

*

*Yes!

Use the vendors, but consider some tools which will do it for you. Check:
https://github.com/postcss/autoprefixer

*

*No:)

But are you sure? Some users use PCs in their work with Windows Vista and IE10 and they cannot change it becouse of license and boss politics.


text:
Q: Splitting files by line across two files equally without pre-defined chunk length - Unix I have two files of equal length (i.e. no. of lines):

*

*text.en

*text.cs

I want to incrementally split the files into 12 parts and as I iterate, I need to add 1 out of the first ten part to it.
Let's say if I the files contain 100 lines, I need some sort of loop that does:
#!/bin/bash

F1=text.en
F2=text.cs

for i in `seq 0 9`;
do
    split -n l/12 -d text.en
    cat x10 > dev.en
    cat x11 > test.en
    echo "" > train.en
    for j in `seq 0 $i`; do
        cat x0$j >> train.en
    done

    split -n l/12 -d text.cs
    cat x10 > dev.cs
    cat x11 > test.cs
    echo "" > train.cs
    for j in `seq 0 $i`; do
        cat x0$j >> train.cs
    done

    wc -l train.en train.cs
    echo "############"
done

[out]:
   55632 train.en
   55468 train.cs
  111100 total
############
  110703 train.en
  110632 train.cs
  221335 total
############
  165795 train.en
  165011 train.cs
  330806 total
############

It's giving me unequal chunks between the files.
Also, when I use split, it's splitting into unequal chunks:
alvas@ubi:~/workspace/cvmt$ split -n l/12 -d text.en
alvas@ubi:~/workspace/cvmt$ wc -l x*
   55631 x00
   55071 x01
   55092 x02
   54350 x03
   54570 x04
   54114 x05
   55061 x06
   53432 x07
   52685 x08
   52443 x09
   52074 x10
   52082 x11
  646605 total

I don't know the no. of lines of the file before hand, so I can't use the split -l option.
How do I split a file into equal size by no. of lines given that I don't know how many lines are there in the files beforehand? Should I do some sort of pre-calculation with wc -l?
How do I ensure that the split across two files are of equal size in for every chunk?
(Note that the solution needs to split the file at the end of the lines, i.e. don't split up any lines, just split the file by line).

A: It's not entirely clear what you're trying to achieve, but here are a few pointers:
split -n l/12 splits into 12 chunks of roughly equal byte size, not number of lines.
split -n r/12 will try to distribute the line count evenly, but if the chunk size is not a divisor of the total line count, you'll still get (slightly) varying line counts: the extra lines are distributed round-robin style.
E.g., with 100 input lines and a line chunk size of 12, you'll get line counts of 9, 9, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8: 100 / 12 = 8 (integer division), and 100 % 12 = 4, so all files get at least 8 lines, with the extra 4 lines distributed among the first 4 output files.
So, yes, if you want a fixed line count for all files (except for the last, if the chunk size is not a divisor), you must calculate the total line count up front, perform integer division to get the fixed line count, and use split -l with that count:
 totalLines=$(wc -l < text.en)
 linesPerFile=$(( totalLines / 12 ))

 split -l 12 text.en # with 100 lines, yields 8 files with 12 and 1 with 4 lines

Additional observations:
With a small, fixed iteration count, it is easier and more efficient to use brace expansion (e.g., for i in {0..9} rather than for i in `seq 0 9`).
If a variable must be used, or with larger numbers, use an arithmetic expression:
n=9; for (( i = 0; i <= $n; i++ )); do ...; done
While you cannot do cat x0{0..$i} directly (because Bash doesn't support variables in brace expansions), you can emulate it by combining seq -f and xargs:
You can replace
echo "" > train.en
for j in `seq 0 $i`; do
    cat x0$j >> train.en
done

with the following:
seq -f 'x%02.f' "$i" | xargs cat > train.en

Since you control the value of $i, you could even simplify to:
eval "cat x0{0..$i}" > train.en  # !! Only do this if you trust $i to contain a number.


text:
Q: .htaccess redirect subdirectory to subdirectory without changing URL This is The senario
http://example.com/it
If I click: /it redirect to /it2 without changing URL.
if I click /it2 show content of itself (it2) but the URL change to /it
I tried this but this code change the URL:
RewriteRule ^it$ /it3 [L,NC,QSA,R]

A: Update your index.htm in /it
<meta http-equiv="refresh" content="0;url=http://www.example.com/it2">

A: You can use:
RewriteEngine On

RewriteCond %{THE_REQUEST} \s/+it2[/?] [NC]
RewriteRule ^it2(/.*)?$ /it$1 [R=301,L,NE]

RewriteRule ^it(/.*)?$ /it2$1 [L,NC]


text:
Q: ng-options not behaving as expected,as documented? No matter what I try, the ID is always passed as the value. I want the Genre.label(string) as the value...
I am trying to get my head around ng-options, i read the docs, and the examples seem straight forward, however I am getting differet results than expected.
my model for Books is
Book: {
    title: string,
    genre: string,
    description: string
}

and my model for Genre is
Genre: {
    label: string
    description: string
}

then when I use ng-init="getGenres()" to pull genres into my scope, I EXPECT using
ng-options="genre.label for genre in genres track by genre.label"

will use the LABEL for each iteration and populate the option value with the LABEL and as a matter of fact - Inspect Element does show that - it looks like this:
<option label="Sci-fi" value="Sci-fi">Sci-fi</option>

My DATA however ends up looking like this:
_id : 5a2f...5691
genre : "5a2f552765226c3018be9878"
title : "Blah Blah"

Here is the form in context:
<form ng-submit="addBook()" ng-init="getGenres()" >

        Title
        <input type="text" class="form-control" ng-model="book.title" placeholder="Title" >

        Genre
        <select class="form-control" ng-model="book.genre"
                ng-options="genre.label for genre in genres track by genre.label" >
            <option value="">-- choose genre --</option>
        </select>

</form>

Here is the COLTROLLERs getGenres:
// get genres
$scope.getGenres = function() {
    $http.get('/api/genres')
    .success(function(response) {
        $scope.genres = response;
    });
}

it returns:
[{
    "_id": "5a2f5.....a065b",
    "label": "Sci-fi",
    "description": "Dealing with subject matter that combines fictional worlds and science, both real and theoretical."
}, {
    "_id": "5a2f5.....9877",
    "label": "Romance",
    "description": "Topics with amorous overtone, undertones and toneless rantings. Matters of the heart. Emotional folly and frolic."
}, {
    "_id": "5a2f5.....9878",
    "label": "Suspense",
    "description": "Events dealing with an arousal of anticipation and dread, mostly in equal parts."
}, {
    "_id": "5a2f5.....9879",
    "label": "Gobbeldegook",
    "description": "nonsensical gibberish. blather, post-moderistic drivel."
}, {
    "_id": "5a2f5.....987a",
    "label": "Drama",
    "description": "Drama Drama Drama Drama Drama Drama Drama"
}, {
    "_id": "5a2f5.....987b",
    "label": "NonFiction",
    "description": "Real life crap. No fakery or literary license, this is REAL!"
}]

Any help is much appreciated
-cheers

A: you should use like this:
    <select class="form-control" ng-model="book.genre"
            ng-options="genre.label  as genre.label for genre in genres track by genre.label" >
        <option value="">-- choose genre --</option>
    </select>

If you don't use genre.label  as , the genre will be used as the model in this case.
The expression BEFORE as, which is genre.label, will be used as model value.
The expression after as, which is genre.label will be used as displayed value in options.


text:
Q: Reading multiple bytes from file and storing them for comparison in C++ I want to binary read a photo in 1460 bytes increments and compare consecutive packets for corrupted transmission. I have a python script that i wrote and want to translate in C++, however I'm not sure that what I intend to use is correct.
for i in range(0, fileSize-1):
    buff=f.read(1460) // buff stores a packet of 1460 bytes where f is the opened file
    secondPacket=''
    for j in buff:
        secondPacket+="{:02x}".format(j)
    if(secondPacket==firstPacket):
        print(f'Packet {i+1} identical with {i}')
    firstPacket=secondPacket

I have found int fseek ( FILE * stream, long int offset, int origin ); but it's unclear if it reads the first byte that is located offset away from origin or everything in between.
Thanks for clarifications.
#include <iostream>
#include <fstream>
#include <array>

std::array<char, 1460> firstPacket;
std::array<char, 1460> secondPacket;
int i=0;

int main() {
    std::ifstream file;
    file.open("photo.jpg", std::ios::binary);

    while (file.read(firstPacket.data(), firstPacket.size())){
        ++i;
        if (firstPacket==secondPacket)
            std::cout<<"Packet "<<i<<" is a copy of packet "<<i-1<<std::endl;
        memcpy(&secondPacket, &firstPacket, firstPacket.size());
    }
    std::cout<<i; //tested to check if i iterate correctly
    return 0;
}

This is the code i have so far which doesn't work.

A: fseek

doesn't read, it just moves the point where the next read operation should begin. If you read the file from start to end you don't need this.
To read binary data you want the aptly named std::istream::read. You can use it like this wih a fixed size buffer:
// char is one byte, could also be uint8_t, but then you would need a cast later on
std::array<char, 1460> bytes;

while(myInputStream.read(bytes.data(), bytes.size())) {
    // do work with the read data
}


text:
Q: Jackson custom deserialization - can't read JsonParser twice I am trying to implement a Jackson Deserializer to have a way of migrating JSONs when they change (like a renamed field, for example, where I would need to read a now inconsistent JSON into a consistent one).
One way of doing this would be to create a JsonDeserializer, read the JSON as the proper final class, then read it again as a MAP, to cherry pick the changes.
I can't seem to do that though, because everytime I read or deserialize the JSON, the backing Stream closes.
class CustomDeserializer extends StdDeserializer<MyPOJO> implements ResolvableDeserializer{

    private final JsonDeserializer<?> deserializer;
    private final ObjectMapper mapper;

    public CustomDeserializer(JsonDeserializer<?> deserializer, ObjectMapper mapper) {
        super(MyPOJO.class);
        this.deserializer = deserializer;
        this.mapper = mapper;
    }

    @Override
    public MyPOJO deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        MyPOJO deserialized = (MyPOJO) deserializer.deserialize(jp, ctxt);
        // Custom migration would go here...
        return deserialized;
    }

    @Override
    public void resolve(DeserializationContext ctxt) throws JsonMappingException {
        ((ResolvableDeserializer) deserializer).resolve(ctxt);
    }
}

I am avoiding creating new ObjectMapper because there is already a customized one, with a custom Date deserializer, for example, so when I am using MyPOJO custom deserializer I want to be able to somehow delegate the deserialization in some way so it uses all previous configuration.

A: This is what I came up with:
@Autowired
    public Serializer(List<IDeserializer> deserializers) {
        SimpleModule module = new SimpleModule("name");
        registerDeserializers(module, deserializers);
        mapper.registerModule(module);
        mapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
    }

    private void registerDeserializers(SimpleModule module, List<IDeserializer> deserializers) {
        if (CollectionUtils.isNotEmpty(deserializers)) {
            final Map<Class<?>, IDeserializer> deserializerRegistryMap = toMap(deserializers);
            module.setDeserializerModifier(new BeanDeserializerModifier() {
                @Override
                public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
                    if (deserializerRegistryMap.containsKey(beanDesc.getBeanClass())){
                        return deserializerRegistryMap.get(beanDesc.getBeanClass()).getDeserializer(mapper);
                    }
                    return super.modifyDeserializer(config, beanDesc, deserializer);
                }
            });
        }
    }

@Component
public class MigrationDeserializer {

    @Autowired
    private MigratorRegistry migratorRegistry;

    public <T> JsonDeserializer<T> createDeserializer(final ObjectMapper mapper, final Class<T> returnType, final Class<? extends SerializedObjectsHistory<T>> historyType){
       return new StdDeserializer<T>(returnType){

           @Override
           public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
               SerializedObjectsHistory<T> history = mapper.readValue(p, historyType);
               return migratorRegistry.migrate(history, returnType);
           }
       };
    }
}

On the serializers I am deserializing my POJO into "HistoryPOJO" which is basically the same thing as my POJO but with all the fields, even removed/renamed ones.
Then I transform it into the current version.


text:
Q: How to get those records which have a foreign key connected with another exact foreign key? I build API with django & django rest framework and stuck with writing one view. See the code below:
models.py
class Order(models.Model):
    name = models.CharField(max_length=255)
    posted_by = models.ForeignKey(User, on_delete=models.CASCADE)

class Offer(models.Model):

    order_related = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='offers')
    author = models.ForeignKey(User, on_delete=models.CASCADE)

serializers.py:
class OfferSerializer(serializers.ModelSerializer):
    class Meta:
        model = Offer
        fields = '__all__'

class OrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = '__all__'

Now I need a view which return those orders, which have offers in which author = int:pk. E.g.
GET /orders/3
should give all orders which have offers with author = 3
plz help me - I can write it with raw SQL but have no idea how to do it via ORM

A: In this case you can simply use pre_fecthes using select_related
offer = Offer.objects.filter(author__id=pk).select_related('order_related')
orders = offer.order_related

Or you could use a get, but i personally don't do that since get statement breaks the code when data is not found but filter returns an empty array or query-set when data is not food and doesn't break the code
offer = Offer.objects.get(author__id=pk).select_related('order_related')
orders = offer.order_related

A: Thanks to Joshua Edward I have got this as a result:
views.py
class GetWorksByAuthor(ListModelMixin, GenericAPIView):

    serializer_class = OfferSerializer

    def get_queryset(self):
        author = self.kwargs['author']
        return Offer.objects.filter(author__id=author).select_related('order_related')

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

urls.py
urlpatterns = [
    path('works/author/<int:author>/',views.GetWorksByAuthor.as_view()),
]


text:
Q: SQL trying to Insert into DB PHP keeps throwing an error telling me I have a syntax problem but gives no other information, what's up with this?
$sql = "INSERT INTO objective_form (name, doa, dob, pmuscle_length, palpation, accessory_movements, functional_tests, myotomes, dermatiomes, refles, ntpt, special_tests, working_hypothesis, plan, tx)
 VALUES ('$name', '$doa', '$dob', '$pmuscle_length', '$palpation', '$accessory_movements', '$functional_tests', '$myotomes', '$dermatiomes', '$refles', '$ntpt', '$special_tests,
 '$working_hypothesis', '$plan', '$tx')";
if(mysqli_query($link, $sql)){
    echo "Recorded successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

A: You forgot apostrophe sign (') after $special_tests in VALUES line. Try:
$sql = "INSERT INTO objective_form (name, doa, dob, pmuscle_length, palpation, accessory_movements, functional_tests, myotomes, dermatiomes, refles, ntpt, special_tests, working_hypothesis, plan, tx)
 VALUES ('$name', '$doa', '$dob', '$pmuscle_length', '$palpation', '$accessory_movements', '$functional_tests', '$myotomes', '$dermatiomes', '$refles', '$ntpt', '$special_tests',
 '$working_hypothesis', '$plan', '$tx')";

If that does not work still, please do echo $sql and try to run the command in SQL itself, that'd show the location of the syntax error.


text:
Q: regex positive negative decimal numbers, comma separated I am having trouble getting the regex right for the validation. Need multiple decimals, positive, negative numbers, and comma separated to be allowed and NOTHING else.
Should allow:
41.975481,-87.728222, 41.974141,-87.721569, 41.973247,-87.7135
Shouldn't allow:
41.975481,-87.728222, 41.97TEST4141,-87.721569, 41.973247,-87.7135, test
This is what I am using but its allowing for characters.
(\-?\d+(\.\d+))(,\s*(\-?\d+(\.\d+)))*

Am I missing something?
$('textarea[name="latlong"]').bind('focusout',function(){
        $(".polygon .geoerror").text("");
        var polygon = $(this).val();
        //remove trailing comma and extra space if its there
        polygon = polygon.replace(/,\s*$/, "");
        var checkpoly = /(\-?\d+(\.\d+))(,\s*(\-?\d+(\.\d+)))*/;
        var evenodd = polygon.split(',').length;

        if (checkpoly.test(polygon) && evenodd % 2 == 0) {
            $(".polygon .geoerror").text("Polygon string is valid." + polygon);
            $(".polygon .geoerror").css("color", "green");
        } else if (checkpoly.test(polygon) && evenodd % 2) {
            $(".polygon .geoerror").text("Mismatch of lat and long values." + polygon);
            $(".polygon .geoerror").css("color", "red");
        } else {
            $(".polygon .geoerror").text("Not valid." + polygon);
            $(".polygon .geoerror").css("color", "red");
        }
        return false;
    });

Based on the code if the user inputs - 41.975481,-87.728222, 41.974141,-87.721569, 41.973247,-87.7135, test - then it tests as valid. It needs to error instead.

A: This should do it:
/^(?:\-?\d+\.\d+[, ]*)+$/

https://regex101.com/r/nP9lE8/1

A: $('textarea[name="latlong"]').bind('focusout',function(){
    $(".polygon .geoerror").text("");
    var polygon = $(this).val();

    //remove extra space if its there
    polygon = polygon.replace(/\s*/g, "");

    var nums = polygon.split(',');
    var len = nums.length;
    var is_even = ( len % 2 == 0 );

    if (!is_even) {
        $(".polygon .geoerror").text("Mismatch of lat and long values." + polygon);
        $(".polygon .geoerror").css("color", "red");

        return false;
    }

    var validNums = true;

    for(var i = 0; i < len; i++) {
        if(isNaN(nums[i])) {
            validNums = false;
            break;
        }
    }

    if (validNums) {
        $(".polygon .geoerror").text("Polygon string is valid." + polygon);
        $(".polygon .geoerror").css("color", "green");
    } else {
        $(".polygon .geoerror").text("Not valid." + polygon);
        $(".polygon .geoerror").css("color", "red");
    }

    return false;
});

A: The core of your regex is absolutely okay. The point(s) you are missing were given in the answer of caeth, but without explanation.
Basically, he added ^ at the beginning and $ at the end, forcing the regex to match the whole word, not just parts of it. According to the description on RegExr (Reference -> Anchors) ^

[m]atches the beginning of the string, or the beginning of a line if the multiline flag (m) is enabled. This matches a position, not a character.

Similiarly $ (same source)

[m]atches the end of the string, or the end of a line if the multiline flag (m) is enabled. This matches a position, not a character.

So a corrected (and a little bit cleaner) version of your regex would be something like
/^(-?\d+\.\d+)(\s*,\s*-?\d+\.\d+)+$/


text:
Q: how to execute prepared statement in a for loop to fetch data from tables in jsp? what is wrong in this code? I am getting this error.
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'attendance where sub_id='3' and reg_no='1111'' at line 1

Code
try {
    Class.forName("com.mysql.jdbc.Driver");
    Connection con =
            DriverManager.getConnection("jdbc:mysql://localhost:3306/sms", "root", "*****");

    int k;
    String sub = "";
    int t_class[] = new int[counter];
    int att_class[] = new int[counter];
    int tallo_class[] = new int[counter];

    PreparedStatement ps3;
    PreparedStatement ps4;
    PreparedStatement ps5;

    for (k = 0; k < (counter - 1); k++) {

        sub = subjects_id[k];

        //START : getting total no of classes held
        ps3 = con.prepareStatement("SELECT COUNT(*) FORM attendance where sub_id=? and reg_no=?");

        ps3.setString(1, sub);
        ps3.setString(2, reg_no);

        ResultSet rs3 = ps3.executeQuery();

        rs3.next();
        t_class[k] = rs3.getInt(1);
    }
}

A: So one big tip is you want to prepare your statement outside of the loop. That is kind of the point of preparing it(Also, parameterizing the inputs). You can re-use the statement, then as stated above you misspelled the word FROM.
PreparedStatement statement = con.prepareStatement("SELECT COUNT(*) FROM attendance where sub_id=? and reg_no=?");
        for (int i = 0; i < (k - 1); i++) {
            statement.setString(1, sub);
            statement.setString(2, reg_no);
            ResultSet rs3 = ps3.executeQuery();
            rs3.next();
            t_class[k] = rs3.getInt(1);
        }

A: There is a typo in your SQL query. You have given FROM as FORM. It should be
ps3 = con.prepareStatement("SELECT COUNT(*) FROM attendance where sub_id=? and reg_no=?");

Also since you are using the same PreparedStatement throughout the loop, then its better you keep the PreparedStatement outside the loop. If you have sql statment which keeps changing inside the loop, then only its worth using it in the loop. If its keep changing, then just use Statement instead of PreparedStatement, else the very purpose of PreparedStatement is lost as you keep changing it.

A: It should be FROM instead of FORM. The error message clearly indicates that the issue is after the required FROM keyword.
ps3 = con.prepareStatement("SELECT COUNT(*) FROM attendance where sub_id=? and reg_no=?");


text:
Q: Убрать последнюю запятую в массиве из генерируемых элементов <script type="application/ld+json">
    {
      "@context": "https://schema.org",
      "@type": "FAQPage",
      "mainEntity": [
      <? foreach($arResult["ITEMS"] as $arItem):
      $name = strip_tags($arItem['NAME']);
      $text = str_replace(array("\r\n", "\r", "\n"),' ', trim(strip_tags($arItem['PREVIEW_TEXT'])));
      ?>
      {
        "@type": "Question",
        "name": "<?=$name?>",
        "acceptedAnswer": {
          "@type": "Answer",
          "text": "<?=$text?>"
        }
      } ,
      <? endforeach; ?>
      ]
    }
</script>

Подскажите,пожалуйста, как после последнего элемента убрать запятую(перед конструкцией endforeach ). Перебрал все похожие варианты с сайта, ничего не подходит.
заранее спасибо


text:
Q: Pre-initialize weights in glove use Initial parameter in glove text2vec fit_transform I would like to pre-initialise glove, word vectors and biases using the initial parameter of the fit_transform. The documentation of the function states to pass as a named list "w_i, w_j, b_i, b_j" values - initial word vectors and biases.
As a result i fit_tranform and extract them. Consequently i create a new glove instance and pass the extracted to a new glove instance (using the initial parameter). Although i am expecting to "continue" from where the first fit_transform reached, the cost always explodes, indicating i am not doing it the right way, or it is not supported.
I tried passing the initial parameter on GloVe$new( only on glove_model$fit_transform only, and on both. The error/cost explodes any time i use the initial parameter.
# A. make vectoriser, tcm,
vectorizer <- vocab_vectorizer(vocab)
tcm <- create_tcm(it_train, vectorizer, skip_grams_window = 2, skip_grams_window_context = "left")

# B. create glove and fit transform - first pass
glove_model <- GloVe$new(word_vectors_size = 300, vocabulary = vocab, x_max = 10)
wv <- glove_model$fit_transform(tcm, n_iter = 10,  progressbar = FALSE, shuffle = F, learning_rate = 0.25, lambda = 1e-5)# convergence_tol = 0.01,

# C. extract parameters from glove model into a named list
initialisationParamsNames <- c("w_i", "w_j", "b_i", "b_j")
initialParam <- lapply(initialisationParamsNames, function(x)glove_model$.__enclos_env__$private[[x]])
names(initialParam) <- initialisationParamsNames

# D. fit transform by using the initial parameter from the first pass
glove_model <- GloVe$new(word_vectors_size = 300, vocabulary = vocab, x_max = 10, initial = initialParam)
wv2 <- glove_model$fit_transform(tcm, n_iter = 10,  progressbar = FALSE, shuffle = F, learning_rate = 0.01, lambda = 1e-5, initial = initialParam)# convergence_tol = 0.01,

the output on the first pass (B.) is
INFO [2019-10-12 12:23:52] 2019-10-12 12:23:52 - epoch 1, expected cost 0.3355
INFO [2019-10-12 12:24:00] 2019-10-12 12:24:00 - epoch 2, expected cost 0.1273
INFO [2019-10-12 12:24:08] 2019-10-12 12:24:08 - epoch 3, expected cost 0.0930
INFO [2019-10-12 12:24:16] 2019-10-12 12:24:16 - epoch 4, expected cost 0.0804
INFO [2019-10-12 12:24:24] 2019-10-12 12:24:24 - epoch 5, expected cost 0.0735
INFO [2019-10-12 12:24:32] 2019-10-12 12:24:32 - epoch 6, expected cost 0.0686
INFO [2019-10-12 12:24:40] 2019-10-12 12:24:40 - epoch 7, expected cost 0.0648
INFO [2019-10-12 12:24:48] 2019-10-12 12:24:48 - epoch 8, expected cost 0.0618
INFO [2019-10-12 12:24:55] 2019-10-12 12:24:55 - epoch 9, expected cost 0.0594
INFO [2019-10-12 12:25:03] 2019-10-12 12:25:03 - epoch 10, expected cost 0.0574

while on the second pass the cost, explodes from 0.0574 to 1062
Warning in glove_model$fit_transform(tcm, n_iter = 10, progressbar = FALSE,  :
  Cost is too big, probably something goes wrong... try smaller learning rate
INFO [2019-10-12 12:27:49] 2019-10-12 12:27:49 - epoch 1, expected cost 1018.4479
Warning in glove_model$fit_transform(tcm, n_iter = 10, progressbar = FALSE,  :
  Cost is too big, probably something goes wrong... try smaller learning rate
INFO [2019-10-12 12:27:57] 2019-10-12 12:27:57 - epoch 2, expected cost 1062.0293
Warning in glove_model$fit_transform(tcm, n_iter = 10, progressbar = FALSE,  :
  Cost is too big, probably something goes wrong... try smaller learning rate
INFO [2019-10-12 12:28:05] 2019-10-12 12:28:05 - epoch 3, expected cost 1062.0293

I expect the cost resuming from 0.0574, but its not :(.
The parameters stated in the documentation appear matching the source code

*

*https://github.com/dselivanov/text2vec/blob/master/R/model_GloVe.R

*https://cran.r-project.org/web/packages/text2vec/text2vec.pdf
Thank you very much for your help