text:
Q: Ambiguity error with higher order lists and type families I have a higher order list GADT defined like so:
data HList as where
    HNil :: HList '[]
    HCons :: a -> HList as -> HList (a ': as)

I can write a function that gets me the first item from that list, provided it is non-empty:
first :: HList (a ': as) -> HList '[a]
first (HCons a _) = HCons a HNil

However, if I make a new type Cat and a type family that merely applies every type in a type-level list to Cat (kind of like a type level map):
newtype Cat a = Cat a

type family MapCat (as :: [*]) :: [*] where
    MapCat '[] = '[]
    MapCat (a ': as) = Cat a ': MapCat as

And a type CatList which converts a list of types to a HList full of those types applied to Cat:
type CatList cs = HList (MapCat cs)

I can't write a similar function that works on CatList.
first' :: CatList (a ': as) -> CatList '[a]
first' (HCons a _) = HCons a HNil

It errors out with:
Couldn't match type 'MapCat as0' with 'MapCat as'
NB: 'MapCat' is a type function, and may not be injective
The type variable 'as0' is ambiguous
Expected type: CatList (a : as) -> CatList '[a]
  Actual type: CatList (a : as0) -> CatList '[a]
In the ambiguity check for:
  forall a (as :: [*]). CatList (a : as) -> CatList '[a]
To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
In the type signature:
  Testing.fst :: CatList (a : as) -> CatList '[a]

What's going wrong? Here is a gist with the entire code.

A: Let's start with a simpler example:
type family F a

err :: F a -> ()
err _ = ()

throws
Couldn't match type 'F a0' with 'F a' NB:
F is a type function, and may not be injective
The type variable a0 is ambiguous
Expected type: F a -> ()
  Actual type: F a0 -> () …

While this compiles fine:
ok :: (a ~ Int) => F a -> ()
ok _ = ()

And this:
type family F a where
    F a = a

ok :: F a -> ()
ok _ = ()

Here is another example, that closer to your problem:
data D = C

data Id (d :: D) where
    Id :: Id d

type family TF_Id (d :: D) :: D where
    TF_Id C = C

err :: Id (TF_Id d) -> ()
err _ = ()

The error is
Couldn't match type 'TF_Id d0' with 'TF_Id d' NB:
TF_Id is a type function, and may not be injective
The type variable d0 is ambiguous
Expected type: Id (TF_Id d) -> ()
  Actual type: Id (TF_Id d0) -> () …

But this works:
ok :: Id (TF_Id C) -> ()
ok _ = ()

and this:
type family TF_Id (d :: D) :: D where
    TF_Id x = x

ok :: Id (TF_Id d) -> ()
ok _ = ()

since TF_Id a immediately reduces to a in both cases.
So the compiler throws an error every time it cannot reduce SomeTypeFamily a, where a is some type variable, that was not determined previously.
So if we want to fix this:
type family TF_Id (d :: D) :: D where
    TF_Id C = C

err :: Id (TF_Id d) -> ()
err _ = ()

without redefining the type family, we need to determine d in the err type signature. The simplest way is
type family TF_Id (d :: D) :: D where
    TF_Id C = C

ok :: Id d -> Id (TF_Id d) -> ()
ok _ _ = ()

Or we can define a datatype for this:
data Proxy (d :: D) = Proxy

ok :: Proxy d -> Id (TF_Id d) -> ()
ok _ _ = ()

And now back to the first' function:
data Proxy (a :: [*]) = Proxy

first' :: Proxy (a ': as) -> CatList (a ': as) -> CatList '[a]
first' _ (HCons a _) = HCons a HNil

This compiles fine. You can use it like this:
main = print $ first' (Proxy :: Proxy '[Int, Bool]) (HCons (Cat 3) $ HCons (Cat True) HNil)

which prints Cat3:[].
But the only thing the compiler must know to reduce MapCat as is a weak head normal form of as, so we do not actually need to provide this additional type information in Proxy :: Proxy '[Int, Bool]. Here is a better way:
data ListWHNF (as :: [*]) where
    LZ :: ListWHNF '[]
    LS :: ListWHNF as -> ListWHNF (a ': as)

first' :: ListWHNF (a ': as) -> CatList (a ': as) -> CatList '[a]
first' _ (HCons a _) = HCons a HNil

main = print $ first' (LS $ LS LZ) (HCons (Cat 3) $ HCons (Cat True) HNil)

So first' now receives something, that looks like the length of a list. But can we do this statically? Not so fast:
data ListWHNF (as :: [*]) where
    LZ :: ListWHNF '[]
    LS :: ListWHNF as -> ListWHNF (a ': as)

data HList as ln where
    HNil  :: HList '[] LZ
    HCons :: a -> HList as ln -> HList (a ': as) (LS ln)

throws Data constructor LZ comes from an un-promotable type ListWHNF …. We cannot use indexed datatypes as indices in Haskell.
Having some sort of functional dependencies, that would allow to associate a term of one type and the weak head normal form of a term of another, we could probably do the trick, but I am not aware about anything like that in GHC (but I am not an expert). In Agda this is simply
_^_ : ∀ {α} -> Set α -> ℕ -> Set α
A ^ 0     = Lift ⊤
A ^ suc n = A × A ^ n

So if the only thing, we need to infer a list, is its length, then we can replace a list with n nested tuples. Abusing the notation, [?, ?] :: [*] becomes (? :: *, (? :: *, Lift ⊤)) and all these ? can now be inferred automatically among with the inhabitant of ⊤ (Agda's equivalent of ()). But in Agda there is no distinction between value-level and type-level programming, so there are no such problems at all.


text:
Q: ember.js .find() only works when called 2nd time Main goal: Using .find() to access a model other than the one available in the current controller -in order to compare data from the current controller's model with a piece of data from a 'foreign' controller's model.
What triggers the comparison:
I have a button inside a template with {{ action "isResponse"}}. This template's controller has an isResponse : function() {...}
The problem I have: The action is fired every time I click the button, but App.Answer.find() only returns content after the 2nd click. I'm wondering if this is because the Answer model hasn't loaded, but am unsure how to properly set up an observer for isLoaded in my example (if that is even the issue)
So how come App.Answer.find() returns empty the first time it's called??
App.ChoiceController = Ember.ObjectController.extend({

    chosen: false,

    isResponse: function() {

        // successfully returns what I want from this controller's model
        var questionId = this.get('question.id')

        // gets DS.RecordArray of the model i'd like to compare with
        var answers = App.Answer.find()

        // filter to get a result that matches this.get('question.id')
        var answer = answers.filter(function(ans) {

            // returns all entries that match
            if(ans.get('question.id') == questionId) { return true }

        }, 'answers.isLoaded'); // this observer doesn't seem to hurt or help

        // get the final value I need
        var choice = answer.mapProperty('choice.id')

        // if choice array is not empty, (should only have 1 element anyways)
        if(!choice) {
            this.set('chosen', choice[0]);

        } else {

            this.set('chosen', false);
        }
    }

})

Here are the models involved. Both include DS.belongsTo attributes
App.Choice = DS.Model.extend({

    "question" : DS.belongsTo('App.Question')

})

App.Answer = DS.Model.extend({

    "question" : DS.belongsTo('App.Question')
    "choice" : DS.belongsTo('App.Choice')

})

App.Question = DS.Model.extend({

})

EDIT
Here is jsfiddle showing the behavior. Make sure to open your browser console to notice that each button requires 2 clicks for action isResponse to function properly. http://jsfiddle.net/iceking1624/QMBwe/

A: After reading your comment I've retought a solution to your problem and one possible way might be that you can define a AnswerController of type ArrayController (since it's for a collection of answers) and then setup this controller in your ApplicationRoute's setupController hook.

Main goal: Using .find() to access a model other than the one available in the current controller -in order to compare data from the current controller's model with a piece of data from a 'foreign' controller's model.

Later on you can then require access to the AnswerController's data using the needs API with needs:['answers'] from inside whatever controller that needs access to the answers collection, and finally have access to the data with this.get('controllers.answer'). You can find here more info on the needs API.
See here a possible solution that works correctly, displaying the right choice already on the 1st click:
App.AnswerController = Ember.ArrayController.extend({});

App.ApplicationRoute = Ember.Route.extend({
  setupController: function(controller, model) {
    this.controllerFor('answer').set('content', App.Answer.find());
  }
});

App.ChoiceController = Ember.ObjectController.extend({
  needs: ['answer'],
  chosen: false,
  isResponse: function() {

    var questionId = this.get('question.id');

    var answers = this.get('controllers.answer');

    var answer = answers.content.filter(function(ans) {
      if(ans.get('question.id') == questionId) { return true }
    }

    var choice = answer.mapProperty('choice.id');

    if(!choice) {
      this.set('chosen', choice[0]);
    } else {
      this.set('chosen', false);
    }
  }
});

And here a working fiddle.
Hope it helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flair NER Metrics interpretation I'm currently preparing a NER Task with Flair and I'm looking for some information about metrics used for NER task.
What are the most used metrics and how to interpretate them ?

A: I would suggest checking sklearn-crfsuite's documentationif you want out of the box implementation.
For interpretation consider your NER system as a multiclass classification system.


text:
Q: Restricting access to a certain Page Type based on group member is in? I am working on a project for a Gym. I have a page type called GymLocationPage.
Every gym will have their own GymLocationPage added by an admin - Every gym will have a login for each of their gym managers. In the Security area I have created a group called Gym Manager and have added them to this group when member gets created.
When the gym manager logs in, I only want them to be able to view and edit their gym's GymLocationPage and no other pages/model admins etc.
How do I go about doing this with a particular page type and also making sure the current logged in user gets to only edit their particular gym's page.
E.g
Bob is New Yorks gym manager => He can only access New York's gym location page (Can't see any other gym locations or other pages etc).

John is Californias gym manager => He can only access Californias gym location page (Can't see any other gym locations or other pages etc).

A: SilverStripe has a pretty nice permission management. You can create permissions in your code and add manually to a user group.
<?php
class Foo extends DataObject implements PermissionProvider
{

    /**
     * Return a map of permission codes to add to the dropdown
     * shown in the Security section of the CMS.
     * array(
     *   'VIEW_SITE' => 'View the site',
     * );
     */
    public function providePermissions()
    {
        return [
            'FOO_MANAGE' => [
                'name' => _t('FOO.PERMISSION_MANAGE_DESCRIPTION', 'Create, edit and delete Foo Items'),
                'category' => _t('Permissions.FOO_CATEGORY', 'Foo'),
            ],
            'FOO_CREATE' => [
                'name' => _t('FOO.PERMISSION_CREATE_DESCRIPTION', 'Create Foo Items'),
                'category' => _t('Permissions.FOO_CATEGORY', 'Foo'),
            ]
        ];
    }
}

In the DataObject or your Page type you can then check the different can methods to define what user can view, can edit, can delete etc... that.
canView() is for "accessing" the page in frontend, canEdit() for editing it in backend.
/**
 * @param null $member
 * @return bool
 */
public function canView($member = null)
{
    //this method is for accessing / viewing the page.
    return true;
}

/**
 * @param null $member
 * @return bool
 */
public function canCreate($member = null)
{
    $parent = parent::canCreate($member);

    $manage = Permission::check('FOO_MANAGE', 'any', $member);
    $create = Permission::check('FOO_CREATE', 'any', $member);

    return $parent || $manage || $create;
}

/**
 * @param null $member
 * @return bool
 */
public function canEdit($member = null)
{
    $member = $member ?: Member::currentUser();
    $parent = parent::canCreate($member);

    $manage = Permission::check('FOO_MANAGE', 'any', $member);

    //you can check everyting here...
    $owner = $member ? $this->OwnerID == $member->ID : false;

    return $parent || $manage || $owner;
}

/**
 * @param null $member
 * @return bool
 */
public function canDelete($member = null)
{
    $parent = parent::canCreate($member);

    $manage = Permission::check('FOO_MANAGE', 'any', $member);

    return $parent || $manage;

}

A:
If I give all my members in the Gym Manger group the same permission then won't they all be able to see each others gym location pages instead of just seeing their own?

Not if you properly implement your canXXX() methods on each GymLocationPage as @wmk has done for you above. It needs to include checks on the relevant Group but the part you're probably missing is how to relate each page to each individual Member record. You can achieve this by extending Member with a $has_one relation to GymLocationPage thus:
class GymMemberExtension extends DataExtension
{
    private static $has_one = array(
        'GymPage' => 'GymLocationPage'
    );
}

..and ensure the user's correct GymLocationPage via the Member.GymPageID field is populated when the user is created.
There is also the 2nd param to Permission::check() to consider which TBH I've never spotted before. It seems to allow for very specific types of entries in the Permission table, but haven't seen any examples as to how this is used in the wild.


text:
Q: Stuck with Angularjs Hello i'm new to angularjs and i'm creating an Angularjs application with visualstudio 2012 mvc4 and i need some help with a request.
this is my get method
    // GET: /getCard/
    Logic l = new Logic();
    public List<Cards> Index()
    {
        var cards = ml.getSortedDeck();
        return cards;
    }

here is my js code
  MemoryApp.factory('Cards', function($resource){
    return $resource('/getCard/', { method: 'GET', isArray: true });
 });

 var ColourCtrl = function ($scope, Cards, $routeParams, $resource) {
$scope.cards = [];

$scope.setcards = function () {
    Cards.query(function (data) {
        console.log(data);
        $scope.cards = $scope.cards.concat(data);
    });
}

$scope.setcards();

}
when i stepped through my backend code it worked fine, i got 16 hits back in the "cards" list which is the right amount. Though when i check my console.log on the website i have an array with 59 items that are unuseable to me.
When i check the response section in under the network tab i get this message
"System.Collections.Generic.List`1[Memory.Models.Cards]" and that seems right to me.
best regards /M

A: Return JSON.
public JsonResult Index()
{
    var cards = ml.getSortedDeck();
    return Json(cards, JsonRequestBehavior.AllowGet);
}


text:
Q: Who introduced the concept of topological mixing? I am writing an introduction and I want to know who introduced the concept of topological mixing?

A: Topological mixing is called "permanent regional transitivity" (and demonstrated) by Gustav Hedlund in his 1939 article on the dynamics of the geodesic flow in constant negative curvature (third page). I think this is the first occurrence of the concept.


text:
Q: Silverlight textbox conditional binding with style I am binding an int to a textbox. Is there a way to change the color of the textbox based on the binded value?
For eg. if the int if > 0, the textbox should be green, else, red.

A: This is where you would use Value Converters, one that converters from an int to a color. You then bind the background property to the int property (as well as binding the text).
Here's an post about them So What's a Silverlight Value Converter Anyway?

A: If you need to get more complex and use proper Styles, try this.


text:
Q: What does this definition of contiguous subsequences mean? I don't understand the following definition of a contiguous subsequence:

A contiguous subsequence of a list S is a subsequence made up of consecutive elements of S.
If S is {5, 15, -30, 10, -5, 40, 10}
then 15, -30, 10 is a contiguous subsequence.

What makes 15, -30, 10 a contiguous subsequence?

A: The form a subset that are next to each other within the set.
con·tig·u·ous/kənˈtigyo͞oəs/Adjective
1. Sharing a common border; touching.
2. Next or together in sequence.

A: This is not directly programming related but 15, 30, -15 is a contiguous subsequence because you can find them in the same order inside the given list (without any holes between the elements of course).

A: In the series (5,15,-30,10,-5,40,10) 5,15,-30 are one after another so they are contiguous but 5,15,40 are not contiguous because we skipped -30,10, and -5 and took 40. In Dasgupta's book, we need to find a sub series of the main series which makes the largest possible sum. Which in this case is 10,-5,40,10. Which is  (10-5+40+10=55).

A: Uhm, maybe because they are consecutive as per your definition?

A: They are elements of your original array and they are all continous.

A: Lets say you have some elements in a subsequence,
then it will be called contiguous iff the elements taken in order are consecutive in original set.
E.g,
Sequence=2,3,abc,5.6,4,abhishek;
Subsequence=5.6,2,abhishek;
Contiguous Subsequence=3,abc,5.6 or 5.6,4,abhishek or abc,5.6.
Remember, The sequence itself is always a contiguous subsequence.
Hope it makes the concept clear!

A: Contiguous elements are consecutive elements.

A: Respectively list some elements from array S without skipping any element from the middle of that list.

A: 15, -30, 10 is not a contiguous sequence.
The answer from user brad would indicate that the sequence of numbers you referenced is not contiguous. You can also validate this by running code from geeksforgeeks.org.

A: A subsequence can be formed from any subset of items from the original subsequence,
so from above {5,10,40} is a valid subsequence. A contiguous subsequence is more restricted, it requires the elements to be consecutive elements from the list, NOT that the values are consecutive but that the positions of the elements taken from the original are consecutive. I  suspect that this distinction was the OPs point of confusion.


text:
Q: Display data in a pop-up and print the page By clicking on a button named " generate report" or "summarize" some sort of pop-up would show summarizing the collected data showing value like average, total, etc... it also comes with a graph. On the corner of the page displaying summarized results there would be a print button to print the summary page
How would I open a new window/tab or some sort of section to display the report?
And how would i be able to print it in the same format as it is?

A: You can use jQuery UI dialog to create modal popup. Inside of this dialog you can put everithing you need. But if need to pring it - better create in js new window and put information there:
window.open();

To print browser window content just call in onClick for your button:
<input type="button" value="Print" onClick="window.print();" />

For graphical information I prefer jqPlot. Try it - that is nice tool. See demo here.
If you need high quality printing than generate pdf or xlsx. If you use java and tomcat you can easilly integrate JasperServer to your application.


text:
Q: is it possible to create Environment variable while setup.exe is running I need to create setup.exe for my abc project (written in c++).
Before running the setup.exe i need to create and set the environment variable to some value.
Is it possible to add custom action of "creating and set the value of environment variable"
in  the installer and if yes then how.
I'm using VS 2012 and Installshield.
Thanks

A: You don't describe your root problem but I can give you advice on environment variable race conditions I've had in the past.   Typically I'll have my installer use standard techniques (Windows Installer Environment table which updates the registry and broadcasts a settings change)  and then if still have a race condition for custom code running in the installer I'll have the custom action set the environment for the process to work around the issue.  This way the permanent change is done correctly and a temporary change is injected to make the custom action happy.
The two most commonly seen race conditions are:
1) Variations of a child process hosted by a windows service doesn't get the settings change message due to service control manager behavior
2) A pending reboot causes MSI to not send the settings change message.  In this scenario it is also possible to write a custom action that does nothing but send the message after the standard action has done it's work.


text:
Q: binding datatable to grid view I have the following code:
Imports System.Data

Partial Class Students_AddWishes Inherits System.Web.UI.Page

    Public dt As New DataTable

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        dt.Columns.Add("ID", System.Type.GetType("System.Int32"))
        dt.Columns.Add("univirsity", System.Type.GetType("System.Int32"))
        dt.Columns.Add("major", System.Type.GetType("System.Int32"))
    End Sub

    Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Dim row1 As DataRow = dt.NewRow()
        row1("ID") = dt.Rows.Count + 1
        row1("univirsity") = ddlUnivs.SelectedValue
        row1("major") = ddlMajors.SelectedValue
        dt.Rows.Add(row1)
        GridView1.DataSource = dt
        GridView1.DataBind()
    End Sub

End Class

The problem is it shows only one row or record. How to make it shows many records?

A: Your page load event you are not checking if it is a post back:
 If Not IsPostBack Then
     'process code if it is not a post back
 End If

Everytime you click the btnAdd button your page does a post back to the server.
I just noticed that you probably are not understanding the life time of an object.
You had done this in your code:
Public dt As New DataTable

The problem with that is you have defined this is a class variable and once the page has loaded you have an instance of type dt that may have some columns associated with it.  But as soon as you record an event such as a button click that reference is destroyed and a new dt is created.
You will have to make some use of session variables or a database to store the state of dt.
Here is an example in C#:
 protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ID", System.Type.GetType("System.Int32"));
            dt.Columns.Add("univirsity", System.Type.GetType("System.Int32"));
            dt.Columns.Add("major", System.Type.GetType("System.Int32"));
            Session["MyDataTable"] = dt;
        }
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        DataTable t = (DataTable)Session["MyDataTable"];
        DataRow row1 = t.NewRow();

        row1["ID"] = t.Rows.Count + 1;
        row1["univirsity"] = 3;
        row1["major"] = 31;
        t.Rows.Add(row1);

        Session["MyDataTable"] = t;
        GridView1.DataSource = t;
        GridView1.DataBind();
    }

And the same code in vb.net:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    If Not Page.IsPostBack Then
        Dim dt As New DataTable()
        dt.Columns.Add("ID", System.Type.[GetType]("System.Int32"))
        dt.Columns.Add("univirsity", System.Type.[GetType]("System.Int32"))
        dt.Columns.Add("major", System.Type.[GetType]("System.Int32"))
        Session("MyDataTable") = dt
    End If
End Sub

Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim t As DataTable = DirectCast(Session("MyDataTable"), DataTable)
    Dim row1 As DataRow = t.NewRow()

    row1("ID") = t.Rows.Count + 1
    row1("univirsity") = 3
    row1("major") = 31
    t.Rows.Add(row1)

    Session("MyDataTable") = t
    GridView1.DataSource = t
    GridView1.DataBind()
End Sub

So now what the code does is instantiate a new datatable object as long as we are on the page (first post back) and adds the columns.  Once it has defined the data table we throw it in some session state.  When you click the add button you cannot in your previous code just keep using dt because dt scope was lost in your prior code.  We do this by assigning the sessioned datatable which was stored prior to a temp datatable.  We add the row and reset the session that way the next time we add a row it will display the second row, then third row, and so on...
I recommend a good asp.net book on such as Beginning ASP.net 3.5 in C# 2008.  There are a ton of vb.net books on the same subject matter.

A: You need to save the datatable to Session, because local variables are not preserved.  So you need to do:
protected override OnLoad(..) //or OnInit
{
   dt = Session["DataTable"] as DataTable;
   if (dt == null)
   {
       dt = new DataTable();
       //load columns
   }
}

protected override OnUnLoad(..)
{
   Session["DataTable"] = dt;
}

Session saves the data table reference across postbacks as the web is stateless.


text:
Q: Can we add custom fallback image to favicon grabber API I have to fetch Favicons from different sites by their domain name.
I've used different APIs like

*

*Google S2 => https://www.google.com/s2/favicons?domain=${domain}&sz=${size}

*DuckDuckGo => https://icons.duckduckgo.com/ip3/{domain}.ico

*Favicon kit

*unavatar.io ( daily rate limited)

I am OK to go with Google S2 and DuckDuckGo, But their fallback icon is a problem. I wanna set my custom fallback image(can't set the on-error function).
I've my own favicon grabber API but I wanna use the free one first and if it gives error then use mine and if it gives error then use a fallback image
I am using Vue.js for frontend and the code is
 <img
 class="w-8 h-8 bg-white dark:bg-zinc-800 p-0.5 ml-1 rounded-full"
 :src="`https://icons.duckduckgo.com/ip3/${items.domain}.ico`"
 @error="$event.target.src = `My custom Favicon Grabber API`"
 loading="lazy"
 />

Step what I want

*

*Use a free API like Googe, DuckDuckGo at first

*If failed, Use my Favicon Grabber API

*If both failed, show a custom fallback image

Is it possible?

A: Using promises in order to handle errors.

*

*Call free api

*

*If succeed, set it to image source variable

*else, call another api

*Call the Favicon Grabber Api

*

*If succeed, set it to image source

*else, set your custom fallback image source

*Set your custom fallback image source
You can easily implement this by using these inside a function or lifecycle hook and you can imagine src as a reference.
let src = ''

fetch(`https://icons.duckduckgo.com/ip3/${this.items.domain}.ico`) // step 1
    .then(res => src = res)
    .catch(() => { // step 1 failed
        fetch(`Favicon Grabber Api`) // step 2
            .then(res => src = res)
             .catch(() => src = 'You custom src') // step 2 failed
    })


text:
Q: Why would one compile all projects to one directory? Extending this questions,
I want to know, what is the reason, one would want to compile multiple projects to a single directory?
Thank you.

A: There could be multiple reasons.
One that I think could be usual is for continuous integration and preparing deployment packages.
You want to have all your code in the same folder in order to be able to run your unit tests (so they find the assemblies you are testing), and also that can make easier to build a release package for your application.


text:
Q: Different output observed in IE8 and IE11 for same HTML file when I open the below html code in  ie8 and ie11  the output is different.

I want to display a white block in the image.
but when run in IE8 the white block appears bigger as compared to when displayed in IE11.
wanted to attach the images but lacked the reputation.
I wanted to know why is this behaviour and if the code is same then the output should also be the same. can anyone help me to understand this behaviour?
thank you very much in advance for your replies.

A: Your HTML output depends upon your browser veersion. Many features of HTML5 and CSS3 are not supported in some of the old browsers. Have a look at the features supported by some famous browsers.

http://www.w3schools.com/cssref/css3_browsersupport.asp

A: I do not think it is the best way to measure / set the size of something by using font and (non breaking) spaces.
That being said, you should use the width/height properties, and the units.
Also take a look at the usage of CSS3's box-sizing property.


text:
Q: How to repopulate each Fragments in ViewPager? I am creating an application in which I have to display question category and questions related to each category. Each question category have different number of questions.On selecting a category I have to display question screen as a sliding screen means user can move to next question on sliding. So, I desgined a screen with two Fragment. First fragment is a ListFragment to display List of category and another is ViewPager to display sliding questions. I was able to populate the Question Fragments in ViewPager for the First Category(containing 3 ques) , but when I select another Category(containing 5 ques) from the List I was not able to replace the previous three Fragment. it just added last two questions in ViewPager. I want to repopulate ViewPager with new set of data. I have added the code below.
QuestionFragmentActivity
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.questions_activity);

        if (findViewById(R.id.question_section_fragment_container) != null) {
            /*
             * if (getIntent().getExtras() != null) { return; }
             */
            QuestionSection firstFragment = new QuestionSection();
            firstFragment.setArguments(getIntent().getExtras());
            getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.question_section_fragment_container,
                            firstFragment).commit();
        }

        categoryPosition = 0;//static variable to hold the position of category item selected.
        CategoryVO cvo = QuestionFragmentActivity.categoryList
                .get(categoryPosition);

        if (findViewById(R.id.question_fragment_container) != null) {
            /*
             * if (getIntent().getExtras() != null) { return; }
             */
            QuestionContainer firstFragment = new QuestionContainer();
            firstFragment.setCvo(cvo);
            firstFragment.setArguments(getIntent().getExtras());
            getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.question_fragment_container,
                            firstFragment).commit();
        }
   }

QuestionContainer.java
public class QuestionContainer extends Fragment {
ViewPager mPager;
CategoryVO cvo;

public CategoryVO getCvo() {
    return cvo;
}
public void setCvo(CategoryVO cvo) {
    this.cvo = cvo;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.question_container, container,
            false);
    ArrayList<QuestionFragment> fragmentList=new ArrayList<QuestionFragment>();
    for(QuestionVO qvo: cvo.getQuestionList()){
        fragmentList.add(new QuestionFragment(qvo));
    }
    mPager = (ViewPager) view.findViewById(R.id.question_viewpager);
    MyAdapter mAdapter = new MyAdapter(getActivity().getSupportFragmentManager());
    mAdapter.setFragmentList(fragmentList);
    mPager.setAdapter(mAdapter);
    return view;
}

public static class MyAdapter extends FragmentPagerAdapter {
    ArrayList<QuestionFragment> fragmentList;

    public ArrayList<QuestionFragment> getFragmentList() {
        return fragmentList;
    }
    public void setFragmentList(ArrayList<QuestionFragment> fragmentList) {
        this.fragmentList = fragmentList;
    }
    public MyAdapter(FragmentManager fm) {
        super(fm);
    }
    @Override
    public int getCount() {
        return fragmentList.size();
    }

    @Override
    public Fragment getItem(int position) {
                    return fragmentList.get(position);
    }
    @Override
    public int getItemPosition(Object object) {
            return POSITION_NONE;
    }
}
}

QuestionSection
public class QuestionSection extends ListFragment implements OnClickListener {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.list_fragment1, container, false);
    return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    Button hideListSection = (Button) getActivity().findViewById(
            R.id.btn_hide_section);
    hideListSection.setOnClickListener(this);
    ListView lv = getListView();
    ArrayList<String> listItem = new ArrayList<String>();
    for (CategoryVO cvo : QuestionFragmentActivity.categoryList) {
        listItem.add(cvo.getCategoryName());
    }
    lv.setAdapter(new SectionListAdapter(getActivity(), listItem));
    lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int pos,
                long arg3) {
            if (pos == 1) {
                  FragmentManager fragmentManager = getFragmentManager();
                  FragmentTransaction fragmentTransaction = fragmentManager
                  .beginTransaction();
                  QuestionFragmentActivity.categoryPosition=pos; CategoryVO cvo=
                  QuestionFragmentActivity.categoryList.get(pos);

                  QuestionContainer fragment = new QuestionContainer();
                  fragment.setCvo(cvo);
                  fragmentTransaction.replace(R.id.question_fragment_container
                  , fragment); fragmentTransaction.commit();
            }
        }
    });
}
}

A: ViewPager.setAdapter(pager_adapter)

forces a redraw of the ViewPager. Make appropriate changes first and do this for a refresh.
Edit: Adapter.notifyDataSetChanged() invalidates the existing data to prepare for new one. Do look into that if you are not using it till now.


text:
Q: Searching Date From DateTime table I have code that to search the date Between start to from date
My Database field is like this:

==============================================
id |    Userid        |  receivedDate
==============================================
1  |     abc          | 2013-07-10 14:07:40
2  |     abc          | 2013-07-15 16:27:04
3  |     rty          | 2013-07-10 16:27:04
4  |     rty          | 2013-07-16 16:07:04
5  |     abc          | 2013-07-25 11:07:04

Examples Database:
My Search Function is Like This
$query = "SELECT * FROM visitdate WHERE id <> ''";

if(isset($dateFrom) && $dateFrom !=""){
$sql_dateFrom= $sql_dateFrom." AND receivedDate='".$dateFrom."'";}

if(isset($dateTo) && $dateTo !=""){
    $sql_dateTo= $sql_dateTo." BETWEEN receivedDate='".$dateTo."'";}

    $query = $query.$sql_dateFrom.$sql_dateTo;

    while($row = mysql_fetch_array($result)){

    echo $row['Userid'];
    }

Then this is my samples HTML Form:
<form name="form" type="post">
<input type="text" name="dateFrom">
<input type="text" name="dateTo">
<input type="submit" value="Searh">
</form>

PROBLEM IS:
How to display whole data from that users base on selected date. Thanks

A: Try to build this query
 "SELECT * FROM visitdata WHERE id <> '' AND receivedDate >= '" . $dateFrom  . "' AND receivedDate <= '" . . "'

A: try converting the user input to a time stamp 1st and compare using your mysql something like this
SELECT FROM_UNIXTIME(receivedDate,"%Y-%m-%d") FROM mytable

A: Try building your query this way, using the mysql date function will cast your datetime fields to date fields.
<?php
$query = "SELECT * FROM visitdate WHERE id <> ''";

if(isset($dateFrom) && $dateFrom !=""){
    $sql_dateFrom= $sql_dateFrom." AND date(receivedDate)>='".date("Y-m-d", strtotime($dateFrom))."'";
}

if(isset($dateTo) && $dateTo !=""){
    $sql_dateTo= $sql_dateTo." AND date(receivedDate)<='".date("Y-m-d", strtotime($dateTo))."'";
}

$query = $query.$sql_dateFrom.$sql_dateTo;

while($row = mysql_fetch_array($result)){
    echo $row['Userid'];
}

This will allow for four possible cases

*

*User Specifies start and end date, will get the records between inclusively

*User Specifies a start date only, will get records for that date and later

*User Specifies a end date only, will get records for that date and before

*User Specifies nothing. All records are returned.

if any of these cases don't work for you then just test for those cases and display errors to user before building and running the query.

A: Add a static 00:00:00 to the beginning variable and 23:59:59 to the end variable.
$sql_dateFrom= $sql_dateFrom." AND receivedDate='".$dateFrom." 00:00:00'";}

if(isset($dateTo) && $dateTo !=""){
    $sql_dateTo= $sql_dateTo." BETWEEN receivedDate='".$dateTo." 23:59:59'";}

A: Try this:
$query = "SELECT * FROM visitdate WHERE id <> ''";
if (!empty($dateFrom)) {
    $query .= " AND receivedDate >= '$dateFrom'";
}
if (!empty($dateTo)) {
    $query .= " AND receivedDate <= '$dateTo'";
}

$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
    echo $row['Userid'];
}


text:
Q: Emulate Touch Screen option absent, Device Emulation provides no touch screen response I am working on a mobile website at the moment and I refreshed the page, Chrome quit unexpectedly, and since then all touch screen emulation is absent and/or failing.
Chrome Version: 36.0.1985.125 m,
OS: Windows 7 Ultimate SP1
Google Chrome suddenly and unexpectedly stopped emulating devices properly.  All touch screen functionality has been disabled and apparently removed.  When I emulate a device, the Sensors box fails to be checked and upon inspection, does not show any 'Emulate Touch Screen' option.
I have tried the following, all in conjunction:

*

*Uninstalling/Reinstalling Chrome and deleting all personal settings, including uninstalling all extensions, restoring all defaults, etc.

*Restarting the computer

*Running anti-virus software

*EDIT: Installed Chrome Canary which produced the exact same problem

Please let me know if there are any other relevant details that I might need to add.

A: Sorry about this.  We overhauled the touch emulation in Chrome 36 to be much more accurate (sharing code with what really happens in Chrome Android): https://plus.sandbox.google.com/+RickByers/posts/CBCmhVttj5C.  In the process we ended up disabling touch emulation when real touch support was present (at the time we thought this was no big deal because if you've got a real touchscreen why would you want to fake one with mouse?).  But some Windows PCs report that they have a touchscreen when in fact they don't really (Eg. Visual Studio installs a touch screen emulator I believe).
We're fixing this at http://crbug.com/395531 - hopefully there will be a Chrome Canary build soon that re-enables touch emulation in these cases.
In the meantime you can mostly work around the issue by disabling Chrome's support for built-in touchscreens at chrome://flags/#touch-events.  Make sure you set this back to 'Enabled' after Chrome is updated to fix the issue.  With this disabled, some minor aspects of touch emulation (eg. DOM0 ontouchstart= handlers) will not work properly.

A: Stop the "Tablet PC Input Service" and restart chrome. If chrome thinks you have a touch screen, it won't let you emulate one.
I stumbled across the answer here:
https://github.com/Modernizr/Modernizr/issues/880


text:
Q: What sorts of fun things can I do with an android phone? Tomorrow I am buying an HTC magic phone on the Rogers network. Since it runs android (the only reason for picking this phone :) ), I was hoping to do some playing around with it, writing applications for it and the like. But first of all, how? Do I need some special cord? I know about the android SDK, but how do I even get started?
And, the main point of this question: I've never programmed for anything besides a website or a PC before. What is strikingly new and exciting about writing software for a phone? What are some things I should try to write, which aren't too difficult, and will maximize my "OMG AWESOME" moment density per unit of time?
Oh, one more (possibly stupid) question: What language do I write in? Java...right? Is there any other languages or frameworks I can use to write for this phone?
Note that there's nothing special about this phone: It's not unlocked anything, I didn't order it as a developer phone from Google, I'm buying it out of a Rogers store on a three year contract.

A: Here's what you need to do:

*

*install Eclipse and the Android SDK

*work through the dev guide, tutorials and documentation at developer.android.com

*join the Android Google Group
Once you're done with that, you should have some ideas on how to proceed. Good luck and have fun!

A: You can phone up your significant other and talk.

A: The big difference in writing software for a phone is the constraints placed on you by the hardware. Forget creating masses of objects and throwing them away. That takes memory and your garbage collecter will end up taking too much processing power away from you to clean up after your mess. There are a number of good videos and tutorials up at developer.android.com which give you more info on how to code 'tightly' for low memory/processor environments. It's actually great fun - you have to think a bit harder about what you are doing than if you are coding for a more powerful environment like desktops.
As for the android OS itself - I think it is fantastic. Just brilliantly designed for something like cellphones. I love the way they use intents to trigger things. Seriously, go take a look at all the tutorials and then play. If you like well thought out software then you'll love android.
I found this book quite handy for rapidly getting into coding on android.
Android book
I'm not a java developer by trade so I can't be sure this guys coding style is a god Java style but he does touch on most of the main topics you need to get started with android. Do the Sudoku example in full - don't cut and paste, actually code it from scratch with the book as a help.

A: You can take a loot at apple iphone app store, there are thousands of cool apps already, some of them are indeed OMG.
Language - java is the most commonly used.
You can visit the official website, it has a lot of your answers.


text:
Q: What is the best distro for Toshiba Satellite L10-205 (old hardware) used mostly for development? I'm new to the Linux world, but I would love to switch from Windows. I'm developer, mostly in web server based technologies, but sometimes I love to tinker with C++ and other languages. As I'm student I can't afford powerful hardware so I have:

It's a Toshiba Satellite L10-205 (Laptop) P.S. Don't blame me for my old hardware.
Whats the best distro of Linux for my PC to run fast and for my needs?

A: Since you are new to Linux, you may consider installing a distro aimed at newcomers, so probably one of the *buntu family. As you are concerned with ressources, Lubuntu may be a good choice: it should keep the ease of installation of Ubuntu, while being much lighter on ressources by default.


text:
Q: Node.Js error - listener must be a function I am trying to build an endpoint /order.... where an order a POST request can be made.
var http = require('http');

var options = {
  hostname: '127.0.0.1'
  ,port: '8080'
  ,path: '/order'
  ,method: 'GET'
  ,headers: { 'Content-Type': 'application/json' }
};

var s  = http.createServer(options, function(req,res) {

  res.on('data', function(){
       // Success message for receiving request. //
       console.log("We have received your request successfully.");
  });
}).listen(8080, '127.0.0.1'); // I understand that options object has already defined this.

req.on('error', function(e){
  console.log("There is a problem with the request:\n" + e.message);
});

req.end();

I get an error "listener must be a function"....when trying to run it from command line - "node sample.js"
I want to be able to run this service and curl into it.
 Can someone proof read my code and give me some basic directions on where I am going wrong? and how I may improve my code.

A: http.createServer() does not take an options object as a parameter. Its only parameter is a listener, which must be a function, not an object.
Here's a really simple example of how it works:
var http = require('http');

// Create an HTTP server
var srv = http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('okay');
});

srv.listen(8080, '127.0.0.1');


text:
Q: !grepl in for loop to remove rows from a dataframe I want to use a for loop to remove any row that contains a text string of values in another vector. I know I can use regex, but this is a process I repeat regularly, so I want to pass a vector of terms into a loop and then a larger function to save time.
# Dataframe that always changes
keyword <- c('acme regulator','regulator','brand regulator')
position <- c(1, 23, 3)

# Terms I want to remove that always change
rmterms <- c('acme','brand')

t_allkwsum <- data.frame(keyword, position)

df <- for (i in 1:length(rmterms)){
     x <- t_allkwsum[!grepl(rmterms[i],t_allkwsum$keyword),]
     df2 <- rbind(df2,x)
     }

df returns as NULL. I want it to return any row where an 'rmterms' value isn't present in t_allkwsum$keyword.

A: df[-which(rowSums(sapply(rmterms,
function(t,df){!grepl(pattern = t,x = df$keyword)},df))!=length(rmterms)),]

#keyword position
#2 regulator       23

A: Not so clear what you want as an output. But, if you would like to keep the structure of the code you have provided, you could just use if condition in the for loop like below which would return you a row where an 'rmterms' value isn't present in 't_allkwsum$keyword'.
keyword <- c('acme regulator','regulator','brand regulator')
position <- c(1, 23, 3)

# Terms I want to remove that always change
rmterms <- c('acme','brand')

t_allkwsum <- data.frame(keyword, position)

list1 <- list()
j = 0
for (i in 1:length(rmterms)){
   if (grepl(rmterms[i],t_allkwsum$keyword) == FALSE) {
      j = j + 1
      list1[[j]] <- t_allkwsum[i,]
   }
}
df2 <- do.call(rbind, list1)

df2
keyword position
2 regulator       23

However, I do not think using conditional and for loop is good idea computational wise.

A: In dplyr version:
t_allkwsum %>% filter(!grepl(paste(rmterms, collapse="|"), keyword))


text:
Q: filtering pd.DataFrame with dash dropdown I'm new to Dash and trying to filter the the following dataframe with a dropdown and show the filter dataframe. I am not able to define the callback function properly. Any sample code is really appreciated,
df = pd.DataFrame({
    'col1': ['A', 'B', 'B', 'A', 'B', 'A'],
    'col2': [2, 1, 9, 8, 7, 4],
    'col3': [0, 1, 9, 4, 2, 3],
})

A: Here is the page from the docs that I think might be a good place to start. If you know the dataframe ahead of time, then you can populate the dropdown with the values that you know you'll need. If you don't, then you would need to use a callback to update the dropdown options prop.
The first example on that docs page shows how to get the value from a dropdown, and output it. In your case, you'd use the dropdown to filter the dataframe perhaps like:
@app.callback(
    Output('data-table-id', 'data'),
    [Input('dropdown-id', 'value')
)
def callback_func(dropdown_value):
    df_filtered = df[df['col1'].eq(dropdown_value)]

    return df_filtered.to_dict(orient='records)

And then you would set the output of the callback to the data prop of a Dash datatable. I've added some made-up values for the Output and Input part of the dropdown, hopefully that gives the general idea.


text:
Q: openssl s_client -showcerts -servername xyz -connect xyz:443 hangs for a long time On Ubuntu I am using:
$ openssl s_client -showcerts -servername myhost -connect myhost:443 | openssl x509 --enddate --noout
depth=2 ...
verify return:1
depth=1 ...
verify return:1
depth=0 ...
verify return:1
notAfter=Aug 11 10:56:02 2036 GMT

to check e.g. expiration dates for certificates. But for some reason it hangs for a long time - some times up to a minute - even though the results are returned immediately.
Is there a way to avoid this wait and just terminate after the result has been printed?

A: openssl s_client is designed to be interactive and by default, it is waiting for your input. So you should either have echo | in front, or </dev/null after the command.
Additionally, you could also add a timeout in case a server cannot be reached.
This is how I do it in a script which verifies dates on different servers and services:
timeout $timeout \
openssl s_client -showcerts -connect $server:$port </dev/null 2>/dev/null \
| openssl x509 -noout -subject -dates


text:
Q: RavenDB Studio - Patch can't find this.__document_id I'm trying to write a patch over a Collection that involves getting the current document ID and I was trying to test it to see the output in the RavenDB Studio Patch area which does a good job of showing before and after. I couldn't understand why my script wasn't working the way I expect and I managed to narrow it down to this small piece:
this.TestId = this.__document_id

In the output for my document when running the test is:
TestId: null

But I can see the document Id is users/1234. Does anyone know the correct syntax to pull the document Id out in the JavaScript used by the RavenDB Studio?
RavenDB Version: #2230

A: Remove the 'this' in front of the '__document_id'.
this.TestId = __document_id


text:
Q: ResourceDictionary in App.xaml won't load I have a set of styles that I want to load to use as a StaticResource throughout my app: Styles.xaml
Everything works fine if I include the style in each window or page:
<Window x:Class="MainWindow"
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Resources/Styles.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
</Window>

If I try to include the style in my app resource, it throws an error that it can't find the MainWindow.xaml resource.
<Application x:Class="App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Resources/Styles.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

Anyone know why I can't include this in my app resource?

A: I'm not sure why the MergedDictionary doesn't work, but if I add the style as a standalone resource it works fine.
<Application x:Class="App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:Excavator"
         StartupUri="MainWindow.xaml">
    <Application.Resources>
         <ResourceDictionary Source="Resources/Styles.xaml" />
    </Application.Resources>
</Application>

A: I would comment on your post but there's a 50 rep requirement...
Have you tried setting a key for the ResourceDictionary?
       <ResourceDictionary x:Key="Styles" Source="Resources/Styles.xaml" />


text:
Q: Tell preview to get the window whose document is named "book.pdf" I'm trying to get the window whose document has the name "book.pdf". Here's my approach
tell application "Preview"
    set w to every window whose document is named "book.pdf"
end

This doesn't work. I've tried about 100 permutations but I'm not getting anywhere. Any tips?

A: You can use AXTitle combined with contains, and tell System Events not Preview
Note I have it wrapped in a try block because myWindow will be undefined if no string match is found.
set n to "book.pdf" -- whatever substring you want to find

tell application "System Events" to tell process "Preview"
    try
        set myWindow to (1st window whose value of attribute "AXMain" is true and value of attribute "AXTitle" contains n)
        log myWindow
    on error
        log "not found"
    end try
end tell


text:
Q: Android Studio:Warning when generate Signed Apk in release mode Warning:com.fasterxml.jackson.databind I'm using the jackson-json dependency in an Android project, and generate Signed Apk in release mode, I get the following errors:
Warning:com.fasterxml.jackson.databind.ext.DOMSerializer: can't find referenced class org.w3c.dom.bootstrap.DOMImplementationRegistry
Warning:com.fasterxml.jackson.databind.ext.Java7SupportImpl: can't find referenced class java.beans.Transient
Warning:com.fasterxml.jackson.databind.ext.Java7SupportImpl: can't find referenced class java.beans.ConstructorProperties
Warning:com.fasterxml.jackson.databind.ext.Java7SupportImpl: can't find referenced class java.nio.file.Path
Warning:com.fasterxml.jackson.databind.ext.Java7SupportImpl: can't find referenced class java.beans.Transient
Warning:com.fasterxml.jackson.databind.ext.Java7SupportImpl: can't find referenced class java.beans.ConstructorProperties
Warning:com.fasterxml.jackson.databind.ext.Java7SupportImpl: can't find referenced class java.beans.Transient
Warning:com.fasterxml.jackson.databind.ext.Java7SupportImpl: can't find referenced class java.beans.ConstructorProperties
Warning:com.fasterxml.jackson.databind.ext.Java7SupportImpl: can't find referenced class java.beans.Transient
Warning:com.fasterxml.jackson.databind.ext.Java7SupportImpl: can't find referenced class java.beans.ConstructorProperties
Warning:com.fasterxml.jackson.databind.ext.NioPathDeserializer: can't find referenced class java.nio.file.Path
Warning:com.fasterxml.jackson.databind.ext.NioPathDeserializer: can't find referenced class java.nio.file.Paths
Warning:com.fasterxml.jackson.databind.ext.NioPathDeserializer: can't find referenced class java.nio.file.Path
Warning:com.fasterxml.jackson.databind.ext.NioPathSerializer: can't find referenced class java.nio.file.Path
Warning:there were 26 unresolved references to classes or interfaces.
Warning:Exception while processing task java.io.IOException: Please correct the above warnings first.

Error:Execution failed for task':app:transformClassesAndResourcesWithProguardForRelease'.> Job failed, see logs for details
Information:BUILD FAILED
Information:Total time: 17.808 secs
Information:1 error
Information:16 warnings

A: Based on this answer and this answer, you can ignore those warning in your proguard file using:
-keepnames class com.fasterxml.jackson.databind.** { *; }
-dontwarn com.fasterxml.jackson.databind.**

Edit:
To fix new run-time error in comments below, add:
 -keepattributes InnerClasses


text:
Q: Arguments in function I am a new c++ student and I am trying to make a basic program for kids to learn basic math.  This is a work in progress so some of the code is not done.  I am trying to compile what I have done so far and I am getting an error that says: 47 59    [Error] new declaration 'void add(int, int, std::string, char)' AND 18  5[Error] ambiguates old declaration 'int add(int, int, std::string, char)'
#include <iostream>
#include <iomanip>
#include <time.h>
#include <string>
#include <cstdlib>
#define over2  "\t\t"
#define over3  "\t\t\t"
#define over4  "\t\t\t\t"
#define down5  "\n\n\n\n\n"
#define down8  "\n\n\n\n\n\n\n\n"
#define down10 "\n\n\n\n\n\n\n\n\n\n"
#define down12 "\n\n\n\n\n\n\n\n\n\n\n\n"

using namespace std;

int add(int,int,string,char);
int sub();
int multi();
int div();

int main(int argc, char** argv)

{
    int num1, num2;

    unsigned seed = time(0);
    srand(seed);
    num1 = 1 +rand() % 4;
    num2 = 1 +rand() % 4;
//  correctAnswer = (num1+num2);

    cout << "This program is a tool for young kids to learn basic math.\n";
    cout << "Just press any key and the learning will commence!\n";

    system("CLS");

    add(num1, num2, "Addition", '+');
//  addResults(num1+num2);

    return 0;
}

void add(int num1, int num2, string operation, char symbol)
{
    cout << down8;
    cout << over3 << operation << endl;
    cout << over3 << "________\n";
    cout << over3 << setw(3) << num1 << endl;
    cout << over3 << symbol << endl;
    cout << over3 << setw(3) << num2 << endl;
    cout << over3 << "________\n";

}

A: The return types of your add method differ in the declaration (int) and in the definition (void). I think the definition's type should be changed to int and make it return the result.

A: I'm not entirely sure, but I think the problem is in the beginning.
When you define your add function, you write it as int add(int,int,string,char);
However, you don't define the variables properly like you do when you actually write the function. Also, in the beginning you define it as int, but you write it as void. The compiler doesn't know what you are trying to do because it thinks there are 2 add functions, one of int type and another void function, which is probably the 18 5[Error] ambiguates old declaration 'int add(int, int, std::string, char)'


text: Q: How to open files in the same instance of Wolfram Desktop? I have just installed version 12.1 and a new default setting is bothering me. Previously when I used to open a notebook file and following that open another one, it used to open in the same instance of Wolfram Desktop rather than creating a new one every time. Is there an option to change it back to this behaviour?


text:
Q: paracol and KOMA: Weird Text Color Related Behaviour Depending on Page Break
Final Update (2018-05-18)
Version 1.34 of paracol with the fix related to this question is availabe on CTAN now.

*

*I use a KOMA document class in combination with the paracol package.

*The final purpose of the document is a bilingual document (two languages, two synchronized columns).

*In my real document, I color the heading of level subparagraph (here I use red). \addtokomafont{subparagraph}{\color{red}}

*My problem is that the color of the subparagraph on some page break circumstances produces that the normal text is also colored.

*I have trouble narrowing down the problem and making the code minimal: Different page break and the problem/effect is gone.

% Dokumentenklasse inkl. Optionen
\documentclass[
    fontsize = 12pt
    ,headings = small
    ,parskip = true
    ,numbers = noendperiod
    ,chapterprefix = true
    ]{scrbook}

%% Seitenlayout
\usepackage[
    %showframe = true,
    showframe = false,
        ]{geometry}

% Seiten-Dimensionen
\geometry{paperwidth = 300mm} % Format 16:9
\geometry{paperheight = 168.75mm} % Format 16:9
\geometry{margin = 15mm}
\geometry{marginparsep = 2mm}
\geometry{marginparwidth = 8mm}
\geometry{footskip = 14mm}

% Color Support
\usepackage{xcolor}

% paracol
\usepackage{paracol}
\setlength{\columnseprule}{1pt}
\setlength{\columnsep}{2em}

\addtokomafont{subparagraph}{\color{red}}

% http://texwelt.de/wissen/fragen/10289/wie-andere-ich-die-abstande-uberunter-section-subsection-subsubsection
\RedeclareSectionCommand[
  beforeskip = 0\baselineskip,
  afterskip = 1\baselineskip,
  innerskip = 0\baselineskip]{chapter}
\RedeclareSectionCommand[
  beforeskip = 0\baselineskip,
  afterskip = 0.25\baselineskip]{section}
\RedeclareSectionCommand[
  beforeskip = 0\baselineskip,
  afterskip = 1sp]{subparagraph}

%% Dummy-Texte
\usepackage{blindtext}

\begin{document}

\chapter{Chapter Heading}

% ### ### ###
\begin{paracol}{2}
% --- --- ---
\begin{leftcolumn*}
    % --- ---
    \section{Section Heading Left}
    \subparagraph{Subparagraph Heading Left}
    % ---

    \blindtext
    \vspace{10mm}

    % ---
    % --- ---
\end{leftcolumn*}
% --- --- ---

% --- --- ---
\begin{rightcolumn}
    % --- ---
    \section*{Section Heading Right}
    \subparagraph*{Subparagraph Heading Right (Without Numbering)}
    % ---

    \blindtext

    % ---
    % --- ---
\end{rightcolumn}

% --- --- ---
\begin{leftcolumn*}
    % --- ---
    \section{Section Heading Left}
    \subparagraph*{Subparagraph Heading Right (Without Numbering)}
    % ---

    \blindtext

    % ---
    % --- ---
\end{leftcolumn*}
% --- --- ---

% --- --- ---
\begin{rightcolumn}
    % --- ---
    \section*{Section Heading Right (Without Numbering)}
    \subparagraph*{Subparagraph Heading Right (Without Numbering)}
    % ---

    \blindtext

    % ---
    % --- ---
\end{rightcolumn}
% --- --- ---
\end{paracol}
% ### ### ###

\end{document}

Now I edit one line of code, e. g. comment \geometry{margin = 15mm} and get no red normal text:
% Dokumentenklasse inkl. Optionen
\documentclass[
    fontsize = 12pt
    ,headings = small
    ,parskip = true
    ,numbers = noendperiod
    ,chapterprefix = true
    ]{scrbook}

%% Seitenlayout
\usepackage[
    %showframe = true,
    showframe = false,
        ]{geometry}

% Seiten-Dimensionen
\geometry{paperwidth = 300mm} % Format 16:9
\geometry{paperheight = 168.75mm} % Format 16:9
%\geometry{margin = 15mm}
\geometry{marginparsep = 2mm}
\geometry{marginparwidth = 8mm}
\geometry{footskip = 14mm}

% Color Support
\usepackage{xcolor}

% paracol
\usepackage{paracol}
\setlength{\columnseprule}{1pt}
\setlength{\columnsep}{2em}

\addtokomafont{subparagraph}{\color{red}}

% http://texwelt.de/wissen/fragen/10289/wie-andere-ich-die-abstande-uberunter-section-subsection-subsubsection
\RedeclareSectionCommand[
  beforeskip = 0\baselineskip,
  afterskip = 1\baselineskip,
  innerskip = 0\baselineskip]{chapter}
\RedeclareSectionCommand[
  beforeskip = 0\baselineskip,
  afterskip = 0.25\baselineskip]{section}
\RedeclareSectionCommand[
  beforeskip = 0\baselineskip,
  afterskip = 1sp]{subparagraph}

%% Dummy-Texte
\usepackage{blindtext}

\begin{document}

\chapter{Chapter Heading}

% ### ### ###
\begin{paracol}{2}
% --- --- ---
\begin{leftcolumn*}
    % --- ---
    \section{Section Heading Left}
    \subparagraph{Subparagraph Heading Left}
    % ---

    \blindtext
    \vspace{10mm}

    % ---
    % --- ---
\end{leftcolumn*}
% --- --- ---

% --- --- ---
\begin{rightcolumn}
    % --- ---
    \section*{Section Heading Right}
    \subparagraph*{Subparagraph Heading Right (Without Numbering)}
    % ---

    \blindtext

    % ---
    % --- ---
\end{rightcolumn}

% --- --- ---
\begin{leftcolumn*}
    % --- ---
    \section{Section Heading Left}
    \subparagraph*{Subparagraph Heading Right (Without Numbering)}
    % ---

    \blindtext

    % ---
    % --- ---
\end{leftcolumn*}
% --- --- ---

% --- --- ---
\begin{rightcolumn}
    % --- ---
    \section*{Section Heading Right (Without Numbering)}
    \subparagraph*{Subparagraph Heading Right (Without Numbering)}
    % ---

    \blindtext

    % ---
    % --- ---
\end{rightcolumn}
% --- --- ---
\end{paracol}
% ### ### ###

\end{document}

I know that the code is not minimal enough to pass a MWE test. I have trouble providing it.

Update: Numbered SubParagraph
I made my "MWE" too minimal: I forgot that I have numbered subparagraph . When I incorporate David's code in the originally provided example then I get the desired behaviour.
When I have numbered subparagraph, then the number is not colored.
% Dokumentenklasse inkl. Optionen
\documentclass[
    fontsize = 12pt
    ,headings = small
    ,parskip = true
    ,numbers = noendperiod
    ,chapterprefix = true
    ]{scrbook}

%% Seitenlayout
\usepackage[
    %showframe = true,
    showframe = false,
        ]{geometry}

% Seiten-Dimensionen
\geometry{paperwidth = 300mm} % Format 16:9
\geometry{paperheight = 168.75mm} % Format 16:9
\geometry{margin = 15mm}
\geometry{marginparsep = 2mm}
\geometry{marginparwidth = 8mm}
\geometry{footskip = 14mm}

% Color Support
\usepackage{xcolor}

% paracol
\usepackage{paracol}
\setlength{\columnseprule}{1pt}
\setlength{\columnsep}{2em}

% subparagraph is numberes
\setcounter{secnumdepth}{5}

% Code from David
% -------------------------
\makeatletter
\def\zzz{%
\long\def\sectionlinesformat##1##2##3##4{%
\@hangfrom {\hskip ##2##3}{\textcolor{red}{##4}}}}
\makeatother

\addtokomafont{subparagraph}{\zzz}
%\addtokomafont{subparagraph}{\color{red}}
% -------------------------

% http://texwelt.de/wissen/fragen/10289/wie-andere-ich-die-abstande-uberunter-section-subsection-subsubsection
\RedeclareSectionCommand[
  beforeskip = 0\baselineskip,
  afterskip = 1\baselineskip,
  innerskip = 0\baselineskip]{chapter}
\RedeclareSectionCommand[
  beforeskip = 0\baselineskip,
  afterskip = 0.25\baselineskip]{section}
\RedeclareSectionCommand[
  beforeskip = 0\baselineskip,
  afterskip = 1sp]{subparagraph}

%% Dummy-Texte
\usepackage{blindtext}

\begin{document}

\chapter{Chapter Heading}

% ### ### ###
\begin{paracol}{2}
% --- --- ---
\begin{leftcolumn*}
    % --- ---
    \section{Section Heading Left}
    \subparagraph{Subparagraph Heading Left}
    % ---

    \blindtext
    \vspace{10mm}

    % ---
    % --- ---
\end{leftcolumn*}
% --- --- ---

% --- --- ---
\begin{rightcolumn}
    % --- ---
    \section*{Section Heading Right}
    \subparagraph*{Subparagraph Heading Right (Without Numbering)}
    % ---

    \blindtext

    % ---
    % --- ---
\end{rightcolumn}

% --- --- ---
\begin{leftcolumn*}
    % --- ---
    \section{Section Heading Left}
    \subparagraph{Subparagraph Heading Right (Without Numbering)}
    % ---

    \blindtext

    % ---
    % --- ---
\end{leftcolumn*}
% --- --- ---

% --- --- ---
\begin{rightcolumn}
    % --- ---
    \section*{Section Heading Right (Without Numbering)}
    \subparagraph*{Subparagraph Heading Right (Without Numbering)}
    % ---

    \blindtext

    % ---
    % --- ---
\end{rightcolumn}
% --- --- ---
\end{paracol}
% ### ### ###

\end{document}

Update (2018-04-27)
I contacted the author of KOMA (Markus Kohm, Germany) and here's
  summary of what he recommended.

*

*Better use \sbox instead of \setbox.

*Or use  \color@begingroup and \color@endgroup when using \setbox.

*The definition of \sbox shows how it should/could be done.

*In the case of paracol (mad box tricks that span multiple pages) you need to take care of color stack.

  I also contacted the author of the paracol package (Hiroshi
  Nakashima, Japan). He wants to look into it.
I also contacted Heike Oberdiek, the author of
  color-stack-related packages. He won't be able to look into it in
  detail though.
Update (2018-05-03)
The author of the paracol package replied and it doesn't look good
  for me :). In short: color is a problem (in rare cases like mine) for the current version of paracol.
I investigated your problem to find the following. (1) The root cause
  is in paracol (i.e., not in KOMA). (2) Fixing the bug in paracol is
  extremely tough, though I'll try it    in future.
Here I show you a little bit lengthy explanation of each issue above.
(1) Root Cause Text coloring is one of toughest implementation issues
  of paracol because, for example, we have to color some page-crossing
  lines in left column without interference with coloring in right
  column.  The coloring mechanism in paracol usually works well, but in
  some unusual cases like your MWE it fails to color texts properly.
  More specifically, we face a trouble in the following case. (a) A
  sequence of non-breakable lines is given when a page has too    small
  room to have them as a whole.  In your case, the sequence    consists
  of the heading of Section 1.2, that of subparagraph and    first two
  lines of the ordinary paragraph. (b) The sequence has colored
  paragraphs.  In your case, section    heading and subparagraph heading
  are colored (with black and red)    and are one-line paragraphs. (c)
  The sequence could be broken into two pages and the second page
  would start with a colored paragraph, if it were breakable.  In
  your case, TeX would find a page-break point between the section
  and subparagraph headings. When paracol's coloring mechanism sees such
  a sequence, it inserts a page-break point into the sequence
  inappropriately, and misunderstands that the coloring of the first
  line of the second page (subparagraph heading) has started in the
  first page to cause an improper coloring (reddening all texts
  following the subparagraph heading).
(2) (Nearly) Perfect Fix Since the problem you faced reveals that the
  fundamental idea of paracol's coloring mechanism is inappropriate,
  fixing the bug requires to redesign the mechanism completely even if
  it is possible.  I have an idea for the fix and will examine its
  feasibility, but I cannot be sure when, or even whether, the fix is
  incorporated into a future release of paracol.
Update (2018-05-08)
The author of the paracol package generated a new version (1.34) which will be publicly available in the coming weeks. I got the chance to test it now and with my current actual document: It works within my current document!
Final Update (2018-05-18)
Version 1.34 of paracol with the fix related to this question is availabe on CTAN now.

A: pdftex does warn you
pdfTeX warning: pdflatex: pop empty color page stack 0

If you change the definition to
\makeatletter
\def\zzz{%
\long\def\sectionlinesformat##1##2##3##4{%
\@hangfrom {\hskip ##2##3}{\textcolor{red}{##4}}}}
\makeatother

\addtokomafont{subparagraph}{\zzz}

then the red stays in the heading, without any warnings that the stack is corrupted.  the indirect definition inserts a \textcolor  just around the text of the heading without disturbing the heading layout code.


text: Q: Implementing a search bar multiple times on iOS I have a UISearchBar embedded in all 4 navigation bars of my iOS app. All of the search bars read from the exact same data so my question is, do i have to setup a tableview and hook it up to the information for each view controller or can i hook all the search Bars to one "search view controller" and if so how do i implement this. Keep in mind I am developing for iOS 9 so please use the most up-to-date methods as a lot of search stuff has been depreciated in iOS 8. Thanks


text:
Q: Microsoft Edge - Developer tools/console not showing up Like the title says, the Dev Tools in MS Edge are not working for me. I have a clean installation of Windows 10 and when i open the Edge explorer, go to any site and hit F12, nothing but a blank window shows up.
I have tried a reinstallation according to this: https://www.intowindows.com/how-to-reinstall-microsoft-edge-in-windows-10/ , but it didn't help, still same issue.

Has anyone any idea how to fix this?

*

*Windows 10 Home

*Microsoft Edge 42.17134.1.0

*Microsoft EdgeHTML
17.17134

UPDATE 20/09/2018
This problem is still persisting ... behaving the same as described above.

*

*Last Windows Update: KB4457128

*Current Edge version: 42.17134.1.0 (still the same)


text:
Q: Mongoose, how to empty a collection I've the following hapi.js server
const Hapi = require('hapi')
const Mongoose = require('mongoose')
const Wreck = require('wreck');

const server = new Hapi.Server({
    "host": "localhost",
    "port": 3000
})

Mongoose.connect('mongodb://localhost/myDB', { useNewUrlParser: true })

const BlockModel = Mongoose.model('block', {
    height: Number,
    size: Number,
    time: Number
})

server.route({
    method: "GET",
    path: "/",
    handler: async (request, h) => {

        Mongoose.model.blocks.remove({});    //<------This is the part of the code I intend to use to delete the collection

        const { res, payload } = await Wreck.get('https://api.url');
        let myJson = JSON.parse(payload.toString()).blocks
        console.log(myJson)
        for (let i = 0; i<myJson.length; i++) {
            var block = new BlockModel({  height: myJson[i].height, size: myJson[i].size, time: myJson[i].time });
            block.save();
        }
        console.log(myJson)

        return "test"
    }
})

server.start();

Point is, it works fine and saves the desired data to my collection, but ofc the database will keep growing if I dont delete the data on each execution. So I intend to implement something similar to
db.blocks.remove({}) //where blocks is my collection

Which works fine in the mongoconsole.
But I cant find how to implement this in the code

A: You can use the deleteMany operator with an empty filter.
db.collection.deleteMany({})

or with your model:
await BlockModel.deleteMany({})

A: Empty all collections in a db
const collections = await mongoose.connection.db.collections();

for (let collection of collections) {
    await collection.deleteMany({})
}


text:
Q: Force a program to connect directly to internet and not using VPN
Possible Duplicate:
2 Internet connections with VPN

Hi,
when I am at home and need to connect to work's LAN I use firefox, point to VPN network, so it calls "Network Connect" and then I am like physically at work. And that is the same for every program of Mac OS X, terminal, etc.
Nevertheless, I wonder whether I could tell to some program to connect directly to the internet and not using VPN.
Thanks

A: My experience with Cisco VPN software is that while there was an option that that would allow you to route packets not destined for company resources through your regular DNS, this option was overridden by the VPN server policy so I was out of luck. I'm thinking you're probably going to be in the same boat.


text:
Q: JavaFX: How to unregister Button Action Event I have a Button which sets an action like
moveRight.setOnAction(new EventHandler<ActionEvent>() {
@Override
            public void handle(ActionEvent e) {
}});

How can I remove this EventFilter from that Button? I tried removeEventHandler method but what should be the parameters for that?

A: The following call does the trick you want:
moveRight.setOnAction(null);

A: Since my comment under your question is barely legible, I'm posting an answer.
Based on your comments you want to register an actionlistener, remove it, the reregister the same listener.
There are more then on ways to accomplish this.
1) Write your own handler:
EventHandler<ActionEvent> eh = new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent event) {
        // CODE
    }
};
button.setOnAction(eh); //registered
button.setOnAction(null); //unregistered
button.setOnAction(eh); //re-registered

(Same with lamda looks like this:
EventHandler<ActionEvent> eh = (ActionEvent event) -> {
                // CODE
            };

)
2) Make your class implement EventHandler and override the abstract methods. Then you can add/remove listener by:
button.setOnAction(this);
button.removeEventHandler(ActionEvent.Action,this);

In the handle method you can get the object that was calling your method, by event.getSource() so you can get your button back in the handle method by
Button b = (Button)event.getSource();

3) Create some other class that is implementing javafx.event.EventHandler and instantiate that as your handler;

A: You might as well disable it from being clicked and it does not listen to action anymore


text:
Q: Two different types of arrays of arrays I'm confused about the different types of arrays of arrays. Consider these two examples
a = Array{Float64}[]
push!(a,[1, 2])
push!(a,[3, 4])
push!(a,[1 2; 3 4])

b = Array[[1.0, 2.0], [3.0,4.0], [1.0 2.0; 3.0 4.0]]

I'm not sure how a and b differ. Suppose I intend to run a for loop over each of the elements in a or b, and multiple each element by 2. That is,
for i in 1:3 a[i] = a[i]*2 end

for i in 1:3 b[i] = b[i]*2 end

I time the run time of both lines respectively, but they are equally fast. Are a and b the same? If so, why does a even exist? It looks fairly complicated, because typeof(a) yields "Array{Array{Float64,N} where N,1}". What does where do here?

A: Both a and b are vectors but they allow different type of elements. You can check this by writing:
julia> typeof(a)
Array{Array{Float64,N} where N,1}

julia> typeof(b)
Array{Array,1}

Now Array isa parametric type taking two parameters. The first parameter is type of elements that it allows. The second parameter is the dimension. You can see that in both cases the dimension is 1 which means both a and b are vectors. You can also check it using the ndims function:
julia> ndims(a)
1

julia> ndims(b)
1

The first parameter is allowed element type. In the case of a it is Array{Float64,N} where N while in the case of b just Array is printed. Before I explain how to read them note that the first parameter can be extracted using the eltype function:
julia> eltype(a)
Array{Float64,N} where N

julia> eltype(b)
Array

You can see that both a and b allow Array to be stored. First let me explain how to read Array{Float64, N} where N. It means that a allows storing of arrays of Float64 of any dimension. Actually you could have written in a shorter way like this Array{Float64} as you can check that:
julia> (Array{Float64,N} where N) === Array{Float64}
true

The reason is that if you do not put a restriction on a tail parameter it can be dropped in syntax. The where N part is a restriction on the parameter. In this case there is no restriction on the second parameter.
Now we can turn to b. You see its eltype is just Array, so both parameters are dropped, thus there are no restrictions on them as explained above. So Array is the same as Array{T, N} where {T,N} as you can see here:
julia> (Array{T, N} where {T,N}) === Array
true

So the difference is that a can store arrays of any dimension but they must have Float64 element type, while b can store arrays of any dimension and any element type. The distinction, in this case, has no performance impact as you have noted, but will have an impact on what can be stored in a and b. Here are some examples.
In this case they work the same, as you try to store an Int in them, but they allow only arrays:
julia> a[1] = 1
ERROR: MethodError: Cannot `convert` an object of type

julia> b[1] = 1
ERROR: MethodError: Cannot `convert` an object of type

but here they differ:
julia> a[1] = ["a"]
ERROR: MethodError: Cannot `convert` an object of type String to an object of type Float64

julia> b[1] = ["a"]
1-element Array{String,1}:
 "a"

julia> a
3-element Array{Array{Float64,N} where N,1}:
 [1.0, 2.0]
 [3.0, 4.0]
 [1.0 2.0; 3.0 4.0]

julia> b
3-element Array{Array,1}:
 ["a"]
 [3.0, 4.0]
 [1.0 2.0; 3.0 4.0]

As you can see you can store an array of String in b, but this is not allowed to be stored in a.
Two additional comments (both topics are a bit complex so I leave out the details, but just give you hints what is going on):

*

*You are allowed not to specify element type of an array when defining it. In this case Julia will automatically pick its element type:

julia> [[1.0, 2.0], [3.0,4.0], [1.0 2.0; 3.0 4.0]]
3-element Array{Array{Float64,N} where N,1}:
 [1.0, 2.0]
 [3.0, 4.0]
 [1.0 2.0; 3.0 4.0]

*The performance impact of the choice of element type of an array depends on the fact:

*

*if the type is abstract (that can be checked by isabstracttype; this impact type inference made by the compiler),

*if it is bits type (that can be checked by isbitstype; this impacts the storage layout),

*if the element type is Union (small unions can are handled more efficiently).

In your case both element types are abstract and non-bits so the performance will be the same.


text:
Q: Google Cloud HTTP/HTTPs load balancer REFRESHING I have my application installed in 2 Ubuntu VMs running behind an HTTP/HTTPS Load balancer.
The load balancer is for some reason refreshing the connection, sometimes in couple of seconds, other times might after half hour.
Due to this refresh the user is moved out of the discussion in the application.
Any pointer on what might be going wrong.
Thanks alot


text:
Q: Extending Global in jest with typescript So I'm trying to have some global variables to use easily in my test files so I researched a lot and managed to make a jest setup file that runs before all my test files to initialize the global variables and this is the setup.ts file
import  app  from'../src/express';
import request from 'supertest';

//Set Express app as global
global.app = request(app);

//TODO: Add global data

It's working fine but the autocomplete isn't working in my test files so after searching for the problem I found out I had to merge my new added variables to NodeJS.Global and ended up doing so in a file called global.d.ts

declare global {
    namespace NodeJS {
     interface Global {
       app: import('supertest').SuperTest<import('supertest').Test>;
     }
   }
 }

but still, nothing is working tried other solutions but none worked.
Note
ts.config
"target": "es2019",
    "moduleResolution": "node",
    "module": "commonjs",
    "lib": ["es2019"],
    "sourceMap": true,
    "outDir": "dist",
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noImplicitThis": true,
    "resolveJsonModule": true,
    "alwaysStrict": true,
    "removeComments": true,
    "noImplicitReturns": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "allowJs": true /* Allow javascript files to be compiled. */,
    "typeRoots": [
      "./types",
      "node_modules/@types",

    ] /* List of folders to include type definitions from. */,
    "types": [ "node","jest"],
  },
  "include": ["./src/**/*", "./utils/**/*", "localization", "./tests/**/*"],
  "exclude": ["./seeds/**/*"]

jest.config.ts
/*
 * For a detailed explanation regarding each configuration property and type check, visit:
 * https://jestjs.io/docs/configuration
 */

export default {
  clearMocks: true,
  coverageProvider: "v8",
  coverageDirectory: "coverage",
  collectCoverage: true,
  setupFiles: ["<rootDir>/tests/setup.ts"],
  testMatch: [
    "<rootDir>/tests/**/*.test.ts"
  ],

};

A: I had a similar usecase, where I needed a safeSubscribe helper available globally in all my tests.
This function would perform the subscription and then do the unsubscription in a general afterEach hook, executed after any test.
Here is how I achieved that:
// test/setup/safe-subscribe.ts
import { Observable, Subscription } from 'rxjs';

const subscriptions: Subscription[] = [];
const safeSubscribeFn = <T>(source: Observable<T>): T[] => {
  const res: T[] = [];
  const subscription = source.subscribe((value) => {
    res.push(value);
  });
  subscriptions.push(subscription);
  return res;
};

global.safeSubscribe = safeSubscribeFn; // Add helper implementation

global.afterEach(() => {
  while (subscriptions.length > 0) {
    const subscription = subscriptions.pop();
    subscription?.unsubscribe();
  }
});

declare global {
  // See: https://stackoverflow.com/a/68328575/12292636
  var safeSubscribe: typeof safeSubscribeFn;
}

// jest.config.js
module.exports = {
  ...,
  setupFilesAfterEnv: [
    ...,
    './test/setup/safe-subscribe.ts', // Import your setup in jest config
  ],
};

// tsconfig.spec.json
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "module": "commonjs",
    "types": ["jest", "node"],
    "resolveJsonModule": true,
    "esModuleInterop": true,
  },
  "files": ["src/polyfills.ts", "test/setup/*.ts"], // Add it there
  "include": ["src/**/*.d.ts", "src/**/*.spec.ts", "test/setup/*.ts"] // And also there
}

Now, it is possible to use the globally-defined safeSubscribe in the tests:
// foo.spec.ts
it('should emit value', () => {
  // Given
  const outputs = safeSubscribe(service.myObservable$); // global import with typescript stuff ✔
  // When
  actions$.next(action);
  // Then
  expect(outputs).toHaveLength(1);
});

A: If you want to use it like app (instead of global.app), then declare it globally:
declare global {
  const app: import('supertest').SuperTest<import('supertest').Test>;
}


text:
Q: Jquery sortable dropped Z-index I'm having some problems with jquery UI sortable.
Problem1
Once an item is dropped into place and you want to redrag it, the draggable items goes behind other divs.
Problem2
I can't drag to original location, this can be related to problem1.
You can find my code on http://jsfiddle.net/dXzrV/
Thanks in advance!
Ward

A: Found my problem. It was with the position:relative on the .widget .widget-header


text:
Q: Duvidas de responsividade Estou com um problema e preciso de ajuda
Tenho uma área no site em que tem o que a empresa faz,no caso não é esse da imagem, é só um exemplo que tenho.
No caso da imagem um temos
Imagem + Texto
Texto + Imagem
e quando você olha na responsividade o mesmo fica do mesmo padrão conforme a foto dois
No meu caso quando vou fazer os testes de responsividade fica
Imagem + Texto + Texto + Imagem
Como posso fazer para na hora da responsividade ele manter o padrão?

N
Código:

Sites Teste
   TTeste

 Teste

Teste.


text:
Q: Why we say that an arbitrary element of $(Z, +)$ is of infinite order? Why we say that an arbitrary non-identity element of $(Z, +)$  is of infinite order? I know it is cyclic, because it is possible to express all elements as multiples (repeated additions) of the element $1$.
The order of an element is defined as how many times we need to combine it with itself until we obtain the identity.
We say that an arbitrary element of $(Z, +)$ have infinite order but why we don't just say it is of no order because in this case no matter how many times we combine an element with itself, we can't obtain identity?


text:
Q: Roblox OnClick clothers giver script  pnts = script.Pants
shirt = script.Shirt

function onClicked(playerWhoClicked)

end
function GiveClothes(character)
if not character:findFirstChild("Shirt") then
shirt:Clone().Parent = character
else character:findFirstChild("Shirt"):Destroy()
shirt:Clone().Parent = character
end

if not character:findFirstChild("Pants") then
pnts:Clone().Parent = character
else character:findFirstChild("Pants"):Destroy()
pnts:Clone().Parent = character
end
end

game.Players.PlayerAdded:connect(function(p)
p.CharacterAdded:connect(function(char)
wait(1.12)
local plr = game.Players:findFirstChild(char.Name)
print(char.Name)

local groupid = 0 -- Id of your group

local plr =  game.Players:GetPlayerFromCharacter(part.Parent)

if plr then

if plr:IsInGroup(groupid) then

if plr:GetRoleInGroup(groupId) >= 50
then GiveClothes(char)
end
end
end

script.Parent.ClickDetector.MouseClick:connect(onClicked)

This script is supposed to give you certain clothes if you click on the button(Script is under the button and yes there is also a ClickDetector),but it only gives you the clothes if you are a certain rank in a Group.
But currently it does not work. How to fix this?

A: Avoid weird names like pnts, you will probably not die from adding the letter a
The ClickDetector already give you the player
And it is over all messy
Try this:
local Pants = script.Pants
local Shirt = script.Shirt

local GroupID = 42 -- Group id here

script.Parent.ClickDetector.MouseClick:connect(function(Player)
    if not Player:IsInGroup(GroupID) then return end
    if Player:GetRoleInGroup(GroupID) < 50 then return end
    local Character = Player.Character
    if Character == nil then return end

    -- Get new shirt
    local CharacterShirt = Character:findFirstChild("Shirt")
    if CharacterShirt then CharacterShirt:Destroy() end
    Shirt:Clone().Parent = Character

    -- Get new pants
    local CharacterPants = Character:findFirstChild("Pants")
    if CharacterPants then CharacterPants:Destroy() end
    Pants:Clone().Parent = Character
end)

Also make sure to post errors when you ask for help


text:
Q: avoid opening extra window/tab by checking whether browser tab is already opened Am trying the below case using jquery
Is there any way to check all the windows/tabs opened in the browser (IE) and open a link in same window in order to avoid multiple windows i.e.
say i have a window which has links
a,b,c where a (link=google/abc) b (link=google/def) c (link=google/xyz)
the code should check only if the link starts with google in above link and open a window/tab in the same tab where the address starts with google
I am trying with the below code
window.open(url, "windowName")

but the above approach will only work if i open the window using window.open and keep a reference as windowName. Is there any other way other than this?


text:
Q: Advice on Where to Start with My App I'm a relative beginner using Google Apps Script and JavaScript, but I've been playing around with bot for days now and I've created a few simple programs and I'd really like to try and get started on my dream project, even if it takes me forever. I'd like some advice on what I should use in terms of making the UI and what database I should use to hold the information (and if this app is even possible).
The App
I'd like to create an online novel management app that utilizes Google Drive as it's source for files. The UI would have a tree that showcases all the google drive files in the novel. When a scene is clicked, the scene opens up for editting.
Questions

*

*Is this app a possibility?

*If so, in terms of a UI, what do you think I should use? The google
provided UIbuilder? The HTML service - for example, can I have a
frame on the right that the google doc   that needs to be editted
can open up in on the right?

*Lastly, what database should I use? The database would have to store
chapter names and   positions, as well as scene names, positions,
and the google doc ID that the scene corresponds to. I've got a
handle on ScriptDB and Spreadsheets... And if either of these two
aren't the best option, would some other database work better? And
why?

This app will, hopefully, be able to give an overview of a novel in tree form, allow you to open a particular scene and edit it, create new scenes, and also change the order in which the scenes are displayed. And then when the person finishes their novel, the app will compile all the scenes into one novel (also in google Drive).
Any insight or suggestions would be greatly appreciated!

A: Having a look at the questions you recently posted I think I have a pretty good idea of what you are trying to do and it looks like an exciting project... I can only encourage you to start it as soon as you can even if you're not comfortable with all the tools you will need to use, the best learning method is probably to work on something important to you.
Now your 3 questions : 1 - This is perfectly doable in the GAS environment and shouldn't be too hard to go through.
2 - the GUI builder is an easy way to start with UI but it lacks a number of features and tools that you will be needing (tree for example ) and is not so easy to expand if you ever need to.  Depending on your knowledge in html, the choice is mainly between UiApp and html service... I would choose UiApp because I'm not good at all in html (but that's not relevant here ;-) but both are capable of building what you want, are easily expandable and not too hard to debug. The advantage could go to html service if you are going to look for 'nice looking features' because it opens the door to 3rd party tools... but again, this is a matter of personal choice.
3 - A recent post from Mogsdad showed that spreadsheet are faster than scriptDb for data storage and manipulation. I find it also easier since I can have a global view on data in the spreadsheet when debugging. Of course Spreadsheet must be considered as a container and data manipulated at array level to benefit from maximum performance. I use that in a lot of database application with full satisfaction.
Sorry for these "general considerations" that don't comply to sto standards ;-)

A: Yes, it seems that all of the things you are requesting are not too ridiculous. I recommend sticking to Google services because they are all easily integrated. To start off, you may want to use the UI builder/UI services. There may be a point in this project where you may want some functionality that the UiApp doesn't provide. At that point, you might want to switch over to HtmlService.
My answer is the same for the databases question. You might want to use a spreadsheet for your database so that you will be able to easily edit it by hand if you need to. You may not have the performance that another database would give you, but it will be fairly easy to test and mess around with your spreadsheet "database."

A: You could start out with getting the basics down. There's a serious amount of data out there. I would suggest you research on an "as-needed" basis. Design some work-/dataflow patterns for your app, for which you could try to use the Fluid UI extension for Chrome. Have a look at this from Mozilla on the designing of apps.
When you've gone through this you might want to have a look at Phonegap and the basics of web development and how you could combine the two.
There's also several ways of using/storing data. You could try WebSQL though it they no longer develop it. You could look at IndexedDB. You could try to use cookies.
Seriously, have a look around. You might also like the books of Wrox. They're very informative and have great work with reading demo's. Though the books are huge ;)


text:
Q: Which $n$ can make $\frac{n!}{n(n-1)...(n-n_0)\; \pi^n}\geq 1$ be true? My question is:

For which $n$ respect to $n_0$, the following inequality is true?
  $$\frac{n!}{n(n-1)\cdots(n-n_0)\; \pi^n}\geq 1\;\;;\;n\geq\; ?.$$

Firstly, I checked the different $n$ to find the first number which make the inequality be true. That was $n=9$ and it implied that $n_0=0$ and I continued this method as follows:
If $n=9$ or $n=10$ then $n_0=0$;
If $n=11$ or $n=12$ then $n_0=1$;
If $n=13$ or $n=14$ then $n_0=2$;
If $n=15$ or $n=16$ then $n_0=3$;
If $n=17$ or $n=18$ then $n_0=4$. ...
But I could not find any relation between $n$ and $n_0$ generally. Also which $n$ can make the inequality be true? Thanks.


text:
Q: Loading image not working when image.crosOrigin="annonymous" So I am trying to load an image from a URL as such (this.path contains the link of the image):
 let image = new Image()
    image.onload = () => {
      console.log('loaded')
    }
    image.src = this.path

the Images are loaded to my page however when loading as above the images are marked as tainted and therefore I cant extract pixel data from them. So I tried the following:
 let image = new Image()
    image.onload = () => {
      console.log('loaded')
    }
    image.crossOrigin = 'Anonymous'
    image.src = this.path

With the above code I get now the following CORS Blocked error
Access to image at 'https://wallpapercave.com/wp/wp2559551.jpg' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
and the image does not load anymore
(I noticed that this link works any other doesn't)
How can I fix this?


text:
Q: Hide AJAX call parameter from browser Below is My AJAX code. I want to Hide this AJAX call and its parameters from the browser console. Also the URL should not be called from externally. Here you can find browser screen shot:

<script type="text/javascript">
 var serviceurl="http://192.168.6.81:8085/SpringJSONServicev4/service/"
 var service= serviceurl+"search2/"+FirstName+"/"+PAN ;
      $.ajax({
        type: "POST",
        url:service,
        timeout: 30000,
        cache:false,
        async :true,
     jsonpCallback:'jsonpCallback',
     contentType: "application/json; charset=utf-8",
        dataType: "jsonp", // "xml", "json"
        success: function(data){
          drawTable(data);
        },
        error: function(e){
         /*  alert('Error: ' + e); */
          alert('Error: ');
        }
      });
    }
</script>


text:
Q: RE: CherryPy and Selecting the Host and Port from the Command Line and/or with What File? I do not know which file to view in /cherrypy to change the host and port to view my server online from my 32-bit ARM device.
...
Which file can I use to change the interior parts to that file so I can use 0.0.0.0:? And...is it possible to use cherrypy from the command line to switch things around for the host and port?
Seth
P.S. I found many items of interest on this site dedicated to the source cherrypy and the rearrangement of the port but not of the host. I do not want to use 127.0.0.1 any longer.

A: I reviewed some answers online and actually found an answer.
cherrypy.engine.stop()
cherrypy.config.update({'server.socket_host': '0.0.0.0'})
cherrypy.config.update({'server.socket_port': 5000})
cherrypy.engine.start()

This amount of info. updates your host and port so you can route things a bit differently.
...


text:
Q: Should Authorization flow use both secret and PKCE for a Web app I'm currently looking at the different OIDC flows and found AuthorizationCode flow and AuthorizationCode flow with PKCE.
Almost all places that I found said that the PKCE is a replacement for the Client secret and should be used by native applications.
Now i'm wondering what reason there is to not use a client secret and PKCE, would this be usefull or is this just not necessary?
I'm running an Openiddict server that i've tested will check for both the client secret and the code verifier. But everywhere i read, it just says PKCE and no (static) secret.

A:
Almost all places that I found said that the PKCE is a replacement for the Client secret and should be used by native applications.

Definitely not. PKCE and client authentication are two additive but completely separate measures:

*

*Client authentication - which is typically used by server-side clients - guarantees that only the client application the authorization code was issued to can redeem it. With this security measure in place, even the resource owner himself cannot redeem his own code.

*PKCE guarantees that only the client that initiated an authorization request can send a valid token request, since the authorization code is bound to the initial code challenge/verifier that is only known by the legitimate client that generated it. With mobile/desktop applications, PCKE is particularly useful to prevent attacks that rely on modifying the URI schemes handled by a specific application, that may be hijacked to re-reroute an authorization response and steal the authorization code.
These days, we also tend to use PKCE in confidential server-side apps to prevent authorization code leakages, even though it was originally designed for public apps like mobile or desktop apps. In this case, you should definitely combine it with client authentication (i.e client secret validation).