text:
Q: Building a local CPAN repository I wonder if there are any options in Perl to build a local CPAN repository including the modules I want and then redistribute it with Perl distribution and then do not need to access CPAN at all.
If yes, could some me show an example?
I looked on CPAN and found a mincpan but it seems that minicpan bring all the mirror of CPAN. If it's possible to bring only a specific subset of modules using minicpan and in case I have a repository is it possible to copy it to another OS with the same type and install the relevant modules there with no headaches?

A: See Pinto (manages a local cpan-like repository) or Carton (can bundle up dependencies and provide them as needed, but you must run your application under carton after deployment.)
Alternatively, instead of a local minimal CPAN distribution, you can bundle requirements with your module, if you use the Module::Install installer.

A: The Pinto tools only work on Unix-like machines.  However, Windows users can install modules from the repository as long as they can read the filesystem (like with NFS) or reach the host via HTTP (using pintod).  So it is possible to use a Pinto repository with Windows, so long as you have one Unix-like machine to create and manage the repository.
Stratopan provides Pinto repositories hosted in the cloud.  With Stratopan, you don't have to install any tools and everything can be managed through the browser.  You can then install modules anywhere that has internet access using the standard tools.  Stratopan doesn't yet support all the features Pinto has, but it is the most hassle-free solution for creating a private CPAN.
Disclaimer: I operate Stratopan.

A: This is addressed by How to mirror CPAN


text:
Q: MMap and SharedArrays I am confronting a very weird problem when parallelizing some function. I understand that I am supposed to post a MWE but I could not recreate the issue in a simple problem.
@everywhere function simulSample(Profits,ν,J,TerminalT,RelevantT,N,S,params,thresh;RelevantPer=RelevantPeriod)
    Dₑ = rand([0],J,1) # Final Condition
    Dᵢ = rand([0],J,1) # Initial Condition
    tempData=SharedArray{Int8}(J,RelevantT,S*N)
    @inbounds @sync @distributed for n=1:S*N
    #for n=1:N
        #println(n)
        tempData[:,:,n]=solver(Dᵢ,Dₑ,Profits[:,:,n],continent,cont_lang,language,J,TerminalT,RelevantT,RelevantPeriod,params,thresh,ν[:,:,n])
    end
    return tempData
end

This function is being called by another function in an iterative procedure. In the first iteration it works, but in the second iteration I get the following error
SystemError: mmap: The operation completed successfully.
#windowserror#45(::Nothing, ::typeof(Base.windowserror), ::Symbol, ::Bool) at error.jl:148
windowserror at error.jl:148 [inlined]
#mmap#1(::Bool, ::Bool, ::typeof(Mmap.mmap), ::Mmap.Anonymous, ::Type{Array{Int8,3}}, ::Tuple{Int64,Int64,Int64}, ::Int64) at Mmap.jl:221
mmap(::Mmap.Anonymous, ::Type{Array{Int8,3}}, ::Tuple{Int64,Int64,Int64}, ::Int64) at Mmap.jl:186
_shm_mmap_array(::Type, ::Tuple{Int64,Int64,Int64}, ::String, ::UInt16) at SharedArrays.jl:670
shm_mmap_array(::Type, ::Tuple{Int64,Int64,Int64}, ::String, ::UInt16) at SharedArrays.jl:649
#call#3(::Bool, ::Array{Int64,1}, ::Type{SharedArray{Int8,3}}, ::Tuple{Int64,Int64,Int64}) at SharedArrays.jl:118
Type at SharedArrays.jl:105 [inlined]
#call#10 at SharedArrays.jl:161 [inlined]
Type at SharedArrays.jl:161 [inlined]
#call#15 at SharedArrays.jl:171 [inlined]
SharedArray{Int8,N} where N(::Int64, ::Int64, ::Int64) at SharedArrays.jl:171
#simulatedMoments#67(::Float64, ::Int64, ::typeof(simulatedMoments), ::Array{Float64,4}, ::Array{Float64,4}, ::Array{Float64,4}, ::Array{Float64,4}, ::Int64, ::Int64, ::Int64, ::Int64, ::Array{Any,3}, ::Array{Float64,1}, ::Int64, ::Int64, ::Int64, ::Float64) at 13-Estimation_Stable.jl:1255
simulatedMoments at 13-Estimation_Stable.jl:1232 [inlined]
#gmm_fun#70(::Float64, ::Float64, ::Int64, ::typeof(gmm_fun), ::SharedArray{Int64,3}, ::Array{Any,3}, ::Array{Float64,1}, ::Array{Float64,1}, ::Int64, ::Int64, ::Int64, ::Array{Float64,4}, ::Array{Float64,4}, ::Array{Float64,4}, ::Array{Float64,4}, ::Array{Array,1}, ::Array{Array,1}, ::Array{Array,1}, ::Array{Array,1}, ::Array{Float64,2}) at 13-Estimation_Stable.jl:1297
gmm_fun(::SharedArray{Int64,3}, ::Array{Any,3}, ::Array{Float64,1}, ::Array{Float64,1}, ::Int64, ::Int64, ::Int64, ::Array{Float64,4}, ::Array{Float64,4}, ::Array{Float64,4}, ::Array{Float64,4}, ::Array{Array,1}, ::Array{Array,1}, ::Array{Array,1}, ::Array{Array,1}, ::Array{Float64,2}) at 13-Estimation_Stable.jl:1284
obj_function_final(::Array{Float64,1}, ::Array{Any,1}) at 13-Estimation_Stable.jl:1370
top-level scope at util.jl:156

I am adding a MWE with the error that I get hoping it can make things more transparent:
using Distributed, SharedArrays

rmprocs()
addprocs()
big_array = rand(100,11,20000)

function donothing(a)
   shared_array = convert(SharedArray,a)
end

for i=1:1000
    donothing(big_array)
end

With the error:
SystemError: mmap: The operation completed successfully.
#windowserror#45(::Nothing, ::typeof(Base.windowserror), ::Symbol, ::Bool) at error.jl:148
windowserror at error.jl:148 [inlined]
#mmap#1(::Bool, ::Bool, ::typeof(Mmap.mmap), ::Mmap.Anonymous, ::Type{Array{Float64,3}}, ::Tuple{Int64,Int64,Int64}, ::Int64) at Mmap.jl:218
mmap(::Mmap.Anonymous, ::Type{Array{Float64,3}}, ::Tuple{Int64,Int64,Int64}, ::Int64) at Mmap.jl:186
_shm_mmap_array(::Type, ::Tuple{Int64,Int64,Int64}, ::String, ::UInt16) at SharedArrays.jl:670
shm_mmap_array(::Type, ::Tuple{Int64,Int64,Int64}, ::String, ::UInt16) at SharedArrays.jl:649
#call#3(::Bool, ::Array{Int64,1}, ::Type{SharedArray{Float64,3}}, ::Tuple{Int64,Int64,Int64}) at SharedArrays.jl:118
Type at SharedArrays.jl:105 [inlined]
Type at SharedArrays.jl:357 [inlined]
convert at SharedArrays.jl:369 [inlined]
donothing(::Array{Float64,3}) at mwproblem.jl:8
top-level scope at mwproblem.jl:12

A: Here is a MWE pattern for a scenario that should be similar to yours:
using Distributed
addprocs(4)
using SharedArrays

@everywhere function compute()
    rand() + myid()*100
end

function dothejob()
    s = SharedArray(zeros(10000000))
    @sync @distributed for i in 1:10000000
        s[i] = compute()
    end
    s
end

myres = dothejob();

redpajama_set_name: RedPajamaStackExchange


text:
Q: cache in asp.net (output)? in my application i trying to implement the cache (ouput) but it is not working fine,
that is it is every time getting from cache only this is my code.

<%@ OutputCache   VaryByParam ="none"
  Location="Client" Duration="10" %>.

Code:
protected void btn_Click(object sender, EventArgs e)
    {
        DataView dtv;
        dtv = (DataView)Cache["mycache"];
        if(dtv ==null )
        {
            string sqry="select * from scrap";
            da=new SqlDataAdapter (sqry,con);
            ds=new DataSet();
            da.Fill (ds);
            dtv=new DataView (ds.Tables[0]);
            Cache["mycache"]=dtv ;
            Response.Write ("<script> alert ('from code')</script>");
        }
        else
        {
             Response.Write ("<script> alert ('from cache')</script>");
        }
        grd1 .DataSource =dtv;
        grd1 .DataBind();

A: The OutputCache and the Page.Cache are in no way related. The OutputCache caches the html that the page generates and returns that to the browser without running your code again (for 10 seconds as by your current configuration). The Page.Cache provides a mechanism for storing application wide data. Once something is added to that cache it will be there until the next time you restart your website (unless explicitly removed).

A: Yes, @klausbyskov is right. Try using the Cache.Insert() method overload with the expiration argument for setting timeout on the data cache elements.


text:
Q: Processing: scale and transform In my processing application I want to translate a shape and scale it.
The coordinate, scale, and translate-values are saved in objects.
In each cycle I use the same translate-value per object and a bigger scale-value.
The problem is the 'scale' is somehow cumulated with the 'translate'- the scale does not happen in the middle of the object...
How can I setup the objects so the scaling happens at their center?
    for (int i = 1; i < formen.size(); i++) {

        Form f = formen.get(i);

        pushMatrix();

        f.sx = f.sx * 2;
        f.sy = f.sy * 2;
        scale(f.sx, f.sy);
        translate(f.tx, f.ty);

        noStroke();

        createShape();
        beginShape();
        vertex(f.ax, f.ay);
        bezierVertex(f.ax + f.kabx, f.ay, f.bx, f.by - f.kaby, f.bx, f.by);
        bezierVertex(f.bx, f.by + f.kbcy, f.cx + f.kbcx, f.cy, f.cx, f.cy);
        bezierVertex(f.cx - f.kcdx, f.cy, f.dx, f.dy + f.kcdy, f.dx, f.dy);
        bezierVertex(f.dx, f.dy - f.kday, f.ax - f.kdax, f.ay, f.ax, f.ay);

        endShape();

        popMatrix();

        delay(5);
    }


text:
Q: High Charts Rendering on Internet Explorer 10 Highcharts Bar chart doesn't render well when they are put inside HTML Table. Issue is reproduced in this Fiddle. Rendering problem can be seen when opened in IE 10(works well in chrome).
 var options = {
    colors: ["#3ACB35", "#DE3A15", "#FF9A00", "#00B8F1"],
    chart: {
        renderTo: 'Chart3container',
        type: 'bar',
        backgroundColor: 'black',
        borderColor: 'black',
        borderWidth: 0,
        className: 'dark-container',
        plotBackgroundColor: 'black',
        plotBorderColor: '#000000',
        plotBorderWidth: 0
    },
    credits: {
        enabled: false
    },
    title: {
        text: 'Count Per Category',
        style: {
            color: 'white',
            font: 'normal 22px "Segoe UI"'
        },
        align: 'left'
    },
    tooltip: {
        backgroundColor: 'rgba(0, 0, 0, 0.75)',
        style: {
            color: '#F0F0F0'
        }
    },
    categories: {
        enabled: 'true'
    },
    legend: {
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'middle',
        borderWidth: 0,
        itemStyle: {
            font: '9pt Segoe UI',
            color: 'white'
        },
        itemHoverStyle: {
            color: 'grey'
        }
    },
    xAxis: {
        categories: BarData.categories,
        tickInterval: 1,
        labels: {
            enabled: true,
            style: {
                color: 'white'
        }
    },
        title: {
            enabled: false
        },
        gridLineColor: '#222222'
    },
    yAxis: {
        title:
        {
            enabled: true,
            text: "Document Count",
            style: {
                fontWeight: 'normal',
                color: 'white'
            }
        },
        labels: {
            style: {
                color: 'white'
        }
    },
        gridLineColor: '#222222'
    },
    exporting: {
        enabled: false
    },
    plotOptions: {
        series: {
            stacking: 'normal',
            cursor: 'pointer'
        }
    },
    series: []
};

options.series = BarData.bardataarray;

chart1 = new Highcharts.Chart(options);

});
When put outside table, it works well. Here is the related Fiddle.
I need table for proper alignment.

A: You can disable animation or use CSS styles like here:

Related topic: https://github.com/highslide-software/highcharts.com/issues/1157


text:
Q: Make a div with three inner floated divs responsive for mobile I have an outer header div that contains three floated divs within it.
The inner leftHeader and inner rightHeader are both empty.  Only the middleHeader contains a few links.
When viewed on mobile (320 - 420), I only want the middleHeader to be visible and to take up all available space - I have code for this given below?
What is happening is middleHeader is responsive but only seems to take up a third of the row even though I have width 100%, I want middleHeader to take up full 100% of the space in its row.  Any help would be great. Maybe there is a better way to do this?
The HTML

Empty

Link to page 1

Link to page 2

Link to page 3

Empty

The CSS for Mobile
@media only screen and (min-width: 320px) and (max-width: 420px) and (orientation : portrait){

    div.leftHeader{visibility:hidden;}

    div.middleHeader{width: 100%; float: none; text-align:left;}

    div.rightHeader{visibility:hidden;}

}

A: visibility:hidden;

only makes the div not visible, but left empty space where hidden div should be
try instead:
display: none;

A: Visibility: hidden; does not prevent the element from occupying space inside box-model of that element.
You need to use display:none; - this hides the content as well as doesn't allows the element to occupy any browser space.

@media only screen and (min-width: 320px) and (max-width: 420px) and (orientation: portrait) {
  .middleHeader {
    width: 100%;
    float: none;
    text-align: left;
    background: red;
    /* for demo purpose */
  }
  .hidden-xs {
    display: none;
    visibility: hidden;
  }
}

Empty

Link to page 1

Link to page 2

Link to page 3

Empty

Try viewing the code snippet example and resize your browser from 320 to 480px, you'll see the extra content hiding.

A: Can you use Bootstrap?

Empty

Empty

hidden-xs class hide both divs and col-xs-12 will force middleHeader to 100% width.

A: I just created what you are ideally asking for, entirely from scratch using HTML5 and CSS, plus I have created a Public Domain GitHub directory for this, where you can freely use the code at https://github.com/danielrutter/Header-Script---1-Row-3-Columns
This is the code exactly as it was developed on 18th August 2016 from the first submission through GitHub:
index.html or index.php (depending on your preference [currently set to .html]):
<!DOCTYPE html>

<meta charset="utf-8">
<title>Header Script - 1 Row, 3 Columns</title>
<link rel="stylesheet" href="css/styles.css">

LEFT
OBJECT PLACEMENT
RIGHT

css/styles.css:
body {
  font-family: Arial, Helvetica, sans-serif;
  background-color: white;
  color: black;
}

#container {
  margin: auto;
  width: 100%;
}

header {
  max-width: 100%;
  height: 110px;
  border: 1px solid black;
}

header-left {
  width: 18%;
  height: 100%;
  float: left;
  display: block;
  border-right: 1px solid black;
}

header-center {
  width: 64%;
  height: 100%;
  display: inline;
}

header-right {
  width: 18%;
  height: 100%;
  float: right;
  display: block;
  border-left: 1px solid black;
}


text:
Q: MarkLogic - Make CPF run on every ingested document where the URIs are "name.xml" with no directories or slashes We need to add a collection to every document we ingest and would like to use CPF as the collection will depend on data in the documents.
Our document URIs are: GUID.xml no forward-slash or directory in front of them.
We have attempted to get CPF to trigger using:
document scope = directory
uri = /
and
document scope = document
uri = /
Our theory is that CPF is expecting the document URIs to begin with a forward-slash but since they do not CPF is not triggering.
We have considered using a crude solution of adding a basic collection to every document and using that as the document scope for CPF, but obviously this is unnecessary data being added which we don't need.
We would be grateful for any ideas or solutions.

A: I found this in the Domain Scope section of the CPF Guide:

In the Admin Interface, the document scope drop-down list specifies whether the domain applies to a single document, a directory, or a collection. Each domain can only have one of these document scopes; if you need more than one of these document scopes, you can create multiple domains.

In other words, to use CPF on more than one document, you'll need to use either directories or a collections to organize your data a bit.
Also note that the CPF guide says "Do not overlap domains". This means that if you ever wanted CPF to target content more precisely, you'll want a more specific organization of your content anyway (different directories for different types or sources of content, for instance). This can also be helpful during searches. Without knowing anything about your data, I can't suggest how you might break it up, but some kind of organization is typically helpful.
You'll need to do something different in your data load. I think your path of least resistance is to add a / to the beginning of your URIs.

A: I support Dave's post as the appropriate answer. However, for completeness, I have included a deeper dive into the way CPF and triggers work together and how you can accomplish what you want with the tools available. But even though you 'can' accmoplish it, slashes would just be more tidy.
I agree with Dave's suggestion about the '/'. Starting with a slash is a good thing in ML (not required, of course). However, I have run across a handful of things that assume a slash is there at the start.
But, that takes changing what you have  - and MarkLogic has lots of goodies under the hood, so we can have abit of a rummage around and see what other bags of tricks we can try.
What is CPF?
It's an application built on top of triggers that does some really convenient things and is highly configurable for pipelines.
- The important thing is that under the hood, it runs on triggers.
- And triggers require a scope (no wildcard or empty scope).
Now MarkLogic is very clear in that a 'directory' ends with a slash. And that applies to the root directory. So there is no way to use directory scope or document scope in your example based on your URIS.
But we still have trgr:collection-scope() to play with. How?
Well, that's easy:
- For whatever user is used to insert the documents, add a default collection (under the admin panel) -> security ->users [or roles]
- Then define the trigger.
For me, I added a default collection called 'default' and the following trigger definition:
trgr:create-trigger("myTrigger2", "Simple trigger example",
  trgr:trigger-data-event(
  trgr:collection-scope("default"),
  trgr:document-content("create"),
      trgr:post-commit()),
  trgr:trigger-module(0, "/dae/", "log.xqy"),
  fn:true(), xdmp:default-permissions() )

So, now the documents can be triggered because the user inserting them has already defined a collection (which is already available by the time this trigger runs). Yes, this is the business end of CPF - the collection scope is the same as in CPF configurations.
In essence, the documents are scoped to a collection by the user used to insert them (a default collection). With that, you can say that the trigger is also scoped to that user's inserts. And in MarkLogic, you ALWAYS have a user - even if its a default one.
The path is this: document ->inserted with default collection -> trigger is triggered because collection scope is defined for the default collection.


text:
Q: Magento 2: Changing layout for a theme at store level I am recently asked a question, that if a customer wants to change his theme pages for a US store to the 2-column layout but in the default theme, the page has a 3-column layout. How we can achieve this.
Is there a way to do it by overriding layout in the same theme.
As far as I understand we need to create two separate themes itself, making default as the parent of the US store theme. Is this the correct solution or any other best solution is there.


text:
Q: How to reset anonymous function The first button is working fine. When I click on it id adds one to the preceding value. The second button should reset to 0. This is also working, but when I click on the first button again, it increments the old (preceding) value:

*

*contador() value -> 1

*contador() value -> 2

*contador() value -> 3

*reset() value -> 0

*contador() value -> 4

 var sumar = (function() {
   var contador = 0;
   return function() {
     return contador += 1;
   }
 })();

 function llamar() {
   document.getElementById('valor').innerHTML = sumar();
 }

 function reset() {
   document.getElementById('valor').innerHTML = 0;

 }
<button type="button" onclick="llamar()">contar</button>
<button type="button" onclick="reset()">reset</button>

0

A: Put increment and reset in one function, because you need access to the private variable from both of the functions:

var makeCounter = function() {
  var count = 0; // Private variable
  return {
    increment: function() {
      return count += 1;
    },
    reset: function() {
      count = 0;
      return count;
    }
  }
}

var c = makeCounter();

function llamar() {
  document.getElementById('valor').innerHTML = c.increment();
}

function reset() {
  document.getElementById('valor').innerHTML = c.reset();
}
<button type="button" onclick="llamar()">contar</button>
<button type="button" onclick="reset()">reset</button>

0

A: you cannot currently do this with your setup, if you alter it slightly, however...
var sumar, resetContador;
(function() {
    var contador = 0;
    sumar = function() { return contador++; }
    resetContador = function() { contador = 0; return contador; }
})();

var reset = function () { document.getElementById('valor').innerHTML = resetContador(); };

edit: I should explain, you cannot do this because you've enclosed contador into a scope that is not accessible from the outside, so to fix that you must define both the increment and reset functions within the closure that defines the contador variable, this will allow multiple functions to alter the value of the 'private' contador variable

A: All you're doing is setting the text of 'valor' to 0. When you hit the button to increment it, contador is still going to be at whatever you left it at, so it's going to just increment its value and display that. I'm not sure why you're using an anonymous function, but you need a way to change the actual value of contador. You can make it a global variable perhaps, but there are better ways to structure this code.

A: Other answers have shown ways to restructure the code so that llamar and reset access the same counter inside an anonymous function. Storing the count in a closure like this does, however, seem more complicated than necessary.
An OOP approach would be to create an object holding the count as a property value with additional methods to increment, reset or read the count value. Such an object would not make the count value private in any way.
Alternatively you could even use the HTML element for counting purposes:
function llamar(){
  var contador = document.getElementById("valor");
  contador.innerHTML = + contador.innerHTML + 1;
}

function reset(){
  document.getElementById("valor").innerHTML = 0;
}


text:
Q: Nested ng-repeat with ng-bind-html I want to render a list of widgets on a page from my controller. Each widget has its own render function that returns a safe HTML string.
My first part of my ng-repeat (outside layer) looks like this:
$scope.renderWidgets = function() {
  var html = "";
  html += "
";
  html += "

"
  html += "
";
  return $sce.trustAsHtml(html);
}

As you can see I have ng-bind-html inside my ng-repeat which is calling a function named .render() located inside widget:
this.render = function() {
  var html = "";
  html += "
";
  html += "{{choice.name}}";
  html += "
";
  return $sce.trustAsHtml(html);
}

I also have a directive that I use to $compile the above HTML string into AngularJS.
If I run the above code the widget.render() function gets called just fine but the output on the page will look like this: {{choice.name}} and not the value inside choice.name.
As you can see I am trying to do another ng-repeat inside ng-bind-html with the widget object from my first ng-repeat.
Is this even possible what I am trying to do here (I am new to AngularJS)? If yes then what am I doing wrong? Or is there another way to resolve my problem?
I am using the latest AngularJS (v. 1.7.9).
UPDATE
I think I know the issue. When I call my first function $scope.renderWidgets() the returned HTML will be automatically compiled(the first ng-repeat) at which point the ng-bind-html gets triggered returning a non-compiled HTML string. Now I have to figure out a way to $compile the returned HTML from my ng-bind-html directive.
Am I on the right track?

A: The ng-bind-html directive only binds HTML. It does not compile HTML. This was a deliberate decision by the AngularJS team to avoid security problems.
You state that you have a directive that compiles HTML. Let's assume the directive is:1
app.directive('dynamic', function ($compile) {
  return {
    restrict: 'A',
    replace: true,
    link: function (scope, ele, attrs) {
      scope.$watch(attrs.dynamic, function(html) {
        ele.html(html);
        $compile(ele.contents())(scope);
      });
    }
  };
});

Then use it in your nested code:
$scope.renderWidgets = function() {
  var html = "";
  html += "
";
  ̶h̶t̶m̶l̶ ̶+̶=̶ ̶"̶<̶d̶i̶v̶ ̶n̶g̶-̶b̶i̶n̶d̶-̶h̶t̶m̶l̶=̶'̶w̶i̶d̶g̶e̶t̶.̶r̶e̶n̶d̶e̶r̶(̶)̶'̶>̶<̶/̶d̶i̶v̶>̶"̶
  html += "

"
  html += "
";
  return $sce.trustAsHtml(html);
}

For more information, see

*

*Compiling dynamic HTML strings from database — this answer


text:
Q: Android 6.0 (Marshmallow) READ_CONTACTS permission allows to read Contact's name when permission is denied I want to check how new permission model works so in app's settings I disable Contacts. Then I go to app and try to read Contacts and ... it kinda works:
try {
    Uri result = data.getData();
    int contentIdx;
    cursor = getContentResolver().query(result, null, null, null, null);
    contentIdx = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
    if(cursor.moveToFirst()) {
        content = cursor.getInt(contentIdx);
    }

    if(content > 0) {
        contentIdx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
        if(cursor.moveToFirst()) {
            name = cursor.getString(contentIdx);
        }
        contentIdx = cursor.getColumnIndex(BaseColumns._ID);
        if(cursor.moveToFirst()) {
            content = cursor.getLong(contentIdx);
        }
        cursor = managedQuery(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[] { Phone.NUMBER }, Data.CONTACT_ID + "=?", new String[] { String.valueOf(content) }, null);
        if(cursor.moveToFirst()) {
            number = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
        }
    }
} catch (Exception e) {
    //SecurityException
}

*

*I'm able to read Contact's Name

*when I try to read Contact's Number SecurityException is thrown

java.lang.SecurityException: Permission Denial: reading com.android.providers.contacts.HtcContactsProvider2 uri content://com.android.contacts/data/phones from pid=20123, uid=10593 requires android.permission.READ_CONTACTS, or grantUriPermission()

Why is that?
Related stuff: Contact data leakage via pick activities

A: Android marshmallow have new permissions system.
You need to request permissions at run time.
http://developer.android.com/training/permissions/requesting.html.
Example:
@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.tv_contact:{
            askForContactPermission();
            break;
        }
    }
 }

private void getContact(){
    Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
    startActivityForResult(intent, PICK_CONTACT);
}

 public void askForContactPermission(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    Manifest.permission.READ_CONTACTS)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("Contacts access needed");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setMessage("please confirm Contacts access");//TODO put real question
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @TargetApi(Build.VERSION_CODES.M)
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        requestPermissions(
                                new String[]
                                        {Manifest.permission.READ_CONTACTS}
                                , PERMISSION_REQUEST_CONTACT);
                    }
                });
                builder.show();
                // Show an expanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

            } else {

                // No explanation needed, we can request the permission.

                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{Manifest.permission.READ_CONTACTS},
                        PERMISSION_REQUEST_CONTACT);

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }else{
            getContact();
        }
    }
    else{
        getContact();
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_CONTACT: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getContact();
                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {
                ToastMaster.showMessage(getActivity(),"No permission for contacts");
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}


text:
Q: OS X Base System is the only partition, Can't install macOS High Sierra This is a making of my own stupidity. As I mess around with my dev environment a lot I occasionally wipeout my laptop to restart with a cleaner env. This time I think I accidentally removed one too many partitions and didn't bother with making a backup ( :S ). I tried following the answer for this similar question https://apple.stackexchange.com/questions/250427/cant-reinstall-mac-os-x-el-capitan-because-the-only-partition-is-a-locked-os-x to no avail as the images will show below. In addition to those, things like gpt create -f disk0 returns unable to open device 'disk0' : Resource busy.

A: It uh..fixed itself... Previous restarts had the same results as above. But another restart did the trick to allow disk unmounting :S


text:
Q: Android Push notifications for a specific time using Alarm Manager I want to use push notifications for a spesific time. I am using these codes;
This is my AlarmReceiver class:
public class AlarmReceiver extends BroadcastReceiver {

private static int NOTIFICATION_ID = 1;

@Override
public void onReceive(Context context, Intent intent) {
    NotificationManager manger = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    Notification notification = new Notification(R.drawable.arrrow_icon,
            "test", System.currentTimeMillis());

    PendingIntent contentIntent = PendingIntent.getActivity(context,
            NOTIFICATION_ID, new Intent(context, AlarmReceiver.class),0);

    Bundle extras = intent.getExtras();
    String title = extras.getString("title");
    String note = extras.getString("note");
    notification.setLatestEventInfo(context, note, title, contentIntent);
    notification.flags = Notification.FLAG_INSISTENT;
    notification.defaults |= Notification.DEFAULT_SOUND;
    manger.notify(NOTIFICATION_ID++, notification);

}
};

And this is my main class of part;

Intent alarmintent = new Intent(getApplicationContext(),
                        AlarmReceiver.class);
                alarmintent.putExtra("title", "test");
                alarmintent.putExtra("note", "test message");
                PendingIntent sender = PendingIntent
                        .getBroadcast(getApplicationContext(), 1, alarmintent,
                                PendingIntent.FLAG_UPDATE_CURRENT
                                        | Intent.FILL_IN_DATA);
      AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
          am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);

If my application is working back push notifications are working correctly.but when I force close notifications do not working. Thanks for help.

A: This may help you. First use this code for your alarm receiver class
public class AlarmReceiver extends BroadcastReceiver
{
    NotificationManager nm;
    public void onReceive(Context context, Intent intent)
    {
        Toast.makeText(context, "Log Out !!", Toast.LENGTH_LONG).show();
//      Vibrator vibrator=(Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
//      vibrator.vibrate(1000);
        nm=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        CharSequence ch="Log Out Service";
        CharSequence message="Log Out You have to login again!! ";
        Notification notif = new Notification(R.drawable.ic_launcher,
                    "You Are Logged out...", System.currentTimeMillis());
//       PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
//                  new Intent(), 0);
         Intent notifyintent=new Intent(context,AlarmManagerTestActivity.class);
         PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
            notifyintent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
         notif.flags |=Notification.FLAG_AUTO_CANCEL;
                  notif.setLatestEventInfo(context, ch, message, pendingIntent);
                  nm.notify(0, notif);
         }
    }

then put this code in your activity
Intent intent = new Intent(your activity,AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
AlarmManagerTestActivity.this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);

A: ok then try to use this code,put this code out of onCreate() protected void onUserLeaveHint() {
        // TODO Auto-generated method stub
        super.onUserLeaveHint();
        exitAppAnimate();
    }
private void exitAppAnimate() {
    ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> recentTasks = activityManager
            .getRunningTasks(Integer.MAX_VALUE);
    for (int i = 0; i < recentTasks.size(); i++) {
        if (i == 1
                && recentTasks.get(i).baseActivity.toShortString().indexOf(
                        getPackageName()) > -1) {
            // home button pressed
            IShomepressed = true;
            System.out.println("Home buttonpressed..........");

            // android.os.Process.killProcess(android.os.Process.myPid());
            break;
        }
    }
}  and put this if (IShomepressed) {
        IShomepressed = false;

where you using Pending intent.this will help you.


text:
Q: What are types of Load Balancers involved in the Snowflake Multi-AZ architecture hosted on AWS reading through the page on our community detailing about the multi-az snowflake architecture -
https://support.snowflake.net/s/article/snowflake-delivers-high-availability-by-using-aws-availability-zones
there is a mention on Load balancers.
my question is what type of load balancer is that - network, application or combination of both.

A: The Snowflake uses load balancer service provided by the hosting Cloud Service. For example, on AWS, Snowflake uses ELB (elastic load balancer):
https://support.snowflake.net/s/article/faq-what-ip-address-range-does-snowflake-use


text:
Q: How to generate KML file in ruby? I'd like to serve a dynamically generated KML file using ruby on rails. I made some research and I found kamel which looks great. The problem is that kame depends on ruby_kml gem which doesn't seem to be available anymore.
$ gem install kamel
ERROR:  While executing gem ... (Gem::DependencyError)
    Unable to resolve dependencies: kamel requires ruby_kml (~> 0.1.4)

Searching 'kml' on rubygems.org was unsuccessful.
So does someone know any alternative to achieve KML generation in ruby on rails?

A: KML is just another XML, you can easily make your own "writer" which parses recursively and formats whatever input is passed in as a parameter and generates a string that looks like valid KML/XML.
Recommended reading for the options and the XML layout:
https://developers.google.com/kml/documentation/kmlreference


text:
Q: Split ActiveForm fields into different tabs with Tabs widget I'm creating a form view and I want to organize the form fields with tabs structure, using the official Tabs widget.
Is it possible init the Tabs widget with the id (or class) of the div elements that contains the active form fields?

A: One example of how you can manage it is doing like this:

*

*First, divide your contact-form into one view-file for each tab.

*Place the ActiveForm::begin() and ActiveForm::end() around the Tabs::widget()

*Render the contact-form pages into content, with parameters $model and $form

Example code:
views/site/contact.php
<?php

/* @var $this yii\web\View */
$this->title = 'Contact';

use yii\bootstrap\Tabs;
use yii\bootstrap\ActiveForm;
?>

<?php $form = ActiveForm::begin(['id' => 'contact-form']); ?>
<?= Tabs::widget([
        'items' => [
            [
                'label' => 'One',
                'content' => $this->render('contact_form1', ['model' => $model, 'form' => $form]),
                'active' => true
            ],
            [
                'label' => 'Two',
                'content' => $this->render('contact_form2', ['model' => $model, 'form' => $form]),
            ],
        ]]);
 ?>
    <?php ActiveForm::end(); ?>

views/site/contact_form1.php
<?= $form->field($model, 'name') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'subject') ?>

views/site/contact_form2.php
<?php
use yii\helpers\Html;
use yii\captcha\Captcha;
?>

<?= $form->field($model, 'body')->textArea(['rows' => 6]) ?>
<?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
    'template' => '

{image}

{input}

',
]) ?>

<?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?>

Hope this helps!

A: Just add at the top of your contact.php global $form; and all works fine.

A: I have another solution:
When we call $form->field($model, 'name')->textInput(), it will return the model of class yii\widgets\ActiveField, so just continue calling a method of this class as $form->field($model, 'name')->textInput()->render(). It will return a string then you can use it for the tab's content.
I have an example code in my application for translating multi languages as the following code:
<?php
$items = [];
foreach ($translateModels as $translateModel) {
    $tabContent = $form->field($translateModel, "[{$translateModel->code}]name")->textInput()->render();
    $items[] = [
        'label' => $translateModel->language->name,
        'content' => $tabContent,
    ];
}
?>
<?= Tabs::widget([
    'options' => [
        'class' => 'nav-tabs',
        'style' => 'margin-bottom: 15px',
    ],
    'items' => $items,
]) ?>

Maybe it's help.


text:
Q: Android SQLite Query, order by time My time is sent to the database as a string e.g.
8:00 AM
9:00 AM
12:50 PM

I want to retrieve them from the database in the order of time. Researched another question and I realised it could be done in MySQL like so:
SELECT *
FROM table_name
ORDER BY STR_TO_DATE(timeField,'%h.%i%p');

Is there a way I can do it the same way in SQLite? Tried the codes above and logcat states there is no such function.


text:
Q: Angular JS simple API: only showing data that begins with the word 'request' I have been tasked with creating a simple AngularJS API. I have the basics down to display the data but it will only grab data from the JSON file that beings with request. so in the be low data, the table displayed visually will not show
{{ x.colour_name }}, it basically completely ignores it.
HTML

    Request ID{{ x.request_id }}
    Request Time{{ x.request_time }}
    Request Completed{{ x.request_completed }}
    Request Customer{{ x.request_customer }}
    Colour name {{ x.colour_name }}

Here is my script

Stumped!

A: The colour_name is in the thread objects inside the data.threads array. Access it like x.threads[0].colour_name.

A:

 Request ID
 Request Time
 Request Completed
 Request Customer
 Colour name

{{ x.request_id }}
{{ x.request_time }}
{{ x.request_completed }}
{{ x.request_customer }}

{{ thread.colour_name }}

Try this .. It might help

A: HTML

    Request ID{{ x.request_id }}
    Request Time{{ x.request_time }}
    Request Completed{{ x.request_completed }}
    Request Customer{{ x.request_customer }}
    Colour name {{ c.colour_name }},

Controller
var app = angular.module('myApp', []);
app.controller('requestCtrl', function($scope, $http) {
  $http.get("http://www.slick-tools.com/testproject/api/v1.0/feed/data").then(function (response) {
      $scope.myData = response.data;
  });
});

A: Take a look at this plunker, handling multiple colors here:

{{ thread.colour_name }}

Table looks something like this:


text:
Q: jsonwebtoken causes unit tests to fail I have an interesting problem regarding json web token. The moment I add this dependency to maven pom, my unit tests for Spring Rest Controller throw gibberish, like
ResultActions results = mockMvc.perform(post("/customers/" + customerId + "/orders")
.contentType(MediaType.APPLICATION_JSON).content(new Gson().toJson(order)));

is expected to give 200, but gives 400. What I've noticed upon investigating the issue is that the problem happens only for tests that test POST/PUT (transactional HTTP requests I guess I could call them). I've tried excluding dependency from testing using information in this link, but to no avail. I'm not sure what other information to provide, because I really don't have the faintest idea as to what is causing this issue.

A: I've solved this issue. The problem was dependency conflict. JJWT depends on Jackson and I've already been using GSON for my Jsons. Those two conflicted in a weird way. I've solved the issue by changing JJWT to another JWT lib.


text:
Q: PowerShell Slack Function I am trying to write a PowerShell function to call a Slack webhook. I took the function from a Reddit post, but the function seems to be failing with a parse error. Also I removed the webhook.
Here is the code:
function Send-SlackMessage {
    Param (
        [Parameter(Mandatory=$true, Position=0)]$Text,
        $Url = "https://hooks.slack.com/services/xxxxx",
        # Parameters below are optional and will fall back to the default
        $Username = "XXXXXXX",
        $Channel = "XXXXXXX",
        $Emoji = "XXXXXX"
    )

    $body = @{ text=$Text; channel=$Channel; username=$Username; icon_emoji=$Emoji } | ConvertTo-Json
    Invoke-WebRequest -Method Post -Uri $Url -Body $body
}

and the error:

At line:12 char:67
+ ... y = @{ text=$Text; channel=$Channel; username=$Username; icon_emoji=$ ...
+
Missing '=' @{ text=$Text; channel=$Channel; username=$Username; icon_emoji=$ ...

The hash literal was incommplete.
 + CategoryInfo              :ParserError (:) [], ParentContainsErrorRecordException
 + FillyQualifiedErrorId     : MissingEqualsInHashLiteral

A: Where's the function name? You are missing a comma after the 2nd param, and have an extra comma after the last param.
function whatever ()
{
param (
     [Parameter(Mandatory=$true, Position=0)]$Text,
     $Url="https://hooks.slack.com/services/xxxxx",
     # Parameters below are optional and will fall back to the default
        $Username = "XXXXXXX",
        $Channel = "XXXXXXX",
        $Emoji = "XXXXXX"
    )

    $body = @{ text=$Text; channel=$Channel; username=$Username; icon_emoji=$Emoji } | ConvertTo-Json
    Invoke-WebRequest -Method Post -Uri $Url -Body $body
}


text:
Q: How do I convert my Xcode project to use ARC (Automatic Reference Counting)? When I run Convert to Obj-C it firsts runs a Precheck.  Some files I want the Precheck to ignore, and I thought I could set the compiler flag -fno-objc-arc on those files.  But Precheck phase seems to ignore that flag (and reset it)...so I don't really know how to get beyond Precheck.

A: The first step of the pre-check has a list of all your files with checkboxes before them, just unstick the ones you do not want to convert to ARC, the migration tool will take care of setting the correct compiler flags during the conversion.


text:
Q: fsck error on boot: /dev/sda2 - can't type slash character I need to set the fsck manually on boot but I can't type in the character / that is required to set the path.
(initramfs) fsck /dev/sda2

I tried multiple keyboard combinations without success.
How to fix this?

A: In such cases it's useful to have a look at the US keyboard layout.

The key on your keyboard to the left of the right Shift key should be / on US keyboards - which is the default unless changed on Linux.
It's also possible to do this without ever typing /. Simply cd .. until you are at /, then cd dev followed by fsck sda2. You don't need to give it the full path.


text:
Q: Plugin Submenu Admin How do you create Submenu items for a plugin.
I've checked System Module, That have Submenu class, and Filter on Admin. Is this possible without hacking or Overriding class.
Thanks.

A: Sure you can.
Layout response object has method 'setLayoutVariable'. One of accepted variables is 'submenu'. If you supply an array of Ip\Menu\Item objects, a submenu will be generated. Here is an example. Put it in Plugin\Application\Event.php file:
<?php

namespace Plugin\Application;

class Event
{
    public static function ipBeforeController()
    {

        if (true) { //find out some kind of a condition when you want a submenu. (eg. ipRequest()->getControllerClass() == 'Plugin\XXX\AdminController')
            $submenu = array();
            $submenuItem = new \Ip\Menu\Item();
            $submenuItem->setTitle('Test');
            $submenuItem->setUrl('http://www.example.com');
            $submenu[] = $submenuItem;

            if (is_object(ipResponse()) && method_exists(ipResponse(), 'setLayoutVariable')) {
                ipResponse()->setLayoutVariable('submenu', $submenu);
            }

        }
    }

}

You can filter main menu too using filter. Add following code to Plugin\Application\Filter.php file:
<?php

namespace Plugin\Application;

class Filter {
    /**
     * @param \Ip\Menu\Item[] $menu
     * @param $info
     */
    public static function ipAdminMenu ($menu, $info)
    {
        //modify $menu

        return $menu;
    }
}


text:
Q: C++ template return parameter I want a function that just return template type, but not accept any as parameters.
But my
template <typename T>
T getSomeT() {
  T some;
  return some;
}

did not work, it says "error: no matching function for call to 'getSomeT'" and "note: candidate template ignored: couldn't infer template argument 'T'"
But it work just fine if I add some fake template parameter in it:
template <typename T>
T getSomeT(T fake) {
  T some;
  return some;
}

A: As the error tells you, "couldn't infer template argument 'T'".
So tell it:
int result = getSomeT<int>();


text:
Q: Using `std::vector` as default for template template parameter Suppose foo is a template that takes a container type, which itself has one template argument to specify the type of its values:
template <template<typename val_t> class container_t>
struct foo;

For convenience, foo shall take std::vector as a default container.  Trouble is that formally std::vector formally has two arguments of which the second has a default.  This means ... container = std::vector does not work.
A solution with C++11 would be to define a template alias:
template<typename val_t> using vec_dummy = std::vector<val_t>;
template <template<typename val_t> class container_t = vec_dummy>
struct foo;

I don't like, for readability (you have to search vec_dummy) and also for aesthetic reasons (there's no reason to name that type).
Is there a way to somehow define the template alias anonymously?  Other approaches to the problem are of course also warmly welcome.
PS: In reality, foo uses an internal data type as value type for the provided container, so
template <typename container_t = std::vector<int>> struct foo;

is not an option.

A: You could make container_t a variadic template template parameter (shiver).
template <template<typename val_t, typename...> class container_t = std::vector>
struct foo;

This way you can focus on the value type, but still maintain any allocator template parameters etc.


text:
Q: How do I get this ARM program to stop seg faulting? I'm trying to create a program that calculates the string length of the string that I have to scan in.  This is what I have, but it seg faults at ldrb r1, [r1].  I'm trying to increment the address to reach the next character within the string.
.section .data

.balign 4
scan_pattern: .asciz "%s"

.balign 4
string: .word 50

.balign 4
null_char: .byte '\0'

.balign 4
result: .asciz "%d"

.section .text
.global main

main:
    ldr r0, =scan_pattern
    ldr r1, =string
    bl scanf

    mov r0, #0
    ldrb r1, [r1]
    ldr r2, =null_char
    ldrb r2, [r2]
    bl count
count:
    cmp r1, r2
    bne incr
    bl end_pro

incr:
    add r1, r1, #1
    add r0, r0, #1
    bl count

end_pro:
    ldr r1, [r0]
    ldr r0, =result
    ldr r1, [r1]
    bl printf

    mov r0, $0
    bl fflush

    nop             @no operation
    mov r7, $1      @exit syscall
    svc $0          @wake kernel
    .end

A: r1 can/will be clobbered by sscanf; you need to restore it after the call. E.g.
ldr r4, =string
mov r1, r4
bl sscanf
...
ldr r1, [r4]      ; formerly: ldr r1, [r1]

But on first glance, there seem to be more problems in the program (the second ldr r1, [r1] crashes probably too, the bl are not directly wrong but a simple b jump would be more usual, you do not iterate over the string, ...).
I suggest to write your algorithm in C, compile it and look with 'objdump -d' at the binary to get an idea how to solve it...
EDIT:
A simple and untested strlen() implementation could look like
@ size_t xstrlen(char const *s)
xstrlen:
    mov  r3, r0           @ char const *orig = s
1:
    ldrb r1, [r0], #1     @ char c = *s++;
    cmp  r1, #0           @ if (c != 0)
    bne  1b               @       goto 1;

    sub  r0, r0, r3       @ return s - orig - 1
    sub  r0, #1
    bx   lr

Call it like
main:
    ldr r0, =scan_pattern
    ldr r1, =string
    bl  scanf

    ldr r0, =string
    bl  xstrlen

    mov r1, r0
    ldr r0, =result
    bl  printf


text:
Q: Azure Analysis Services vs Direct Query I'm tring to assess the best approach, in terms of cost and performance, in accessing data and running queries on a dataset using Power BI with Azure Analysis Services or Power BI with Direct Query.
I have trie to illustrate both approaches with the following diagram.

From the diagram steps 4 and 5 describe accessing data in Azure Data Lake using Power BI with Direct Query. Wherease, steps 4 and 6 describes accessing data using Power BI with Azure Analysis Services.
From my own research, Direct Query is notorious for having performance issues e.g

All DirectQuery requests are sent to the source database, so the time
  required to refresh a visual is dependent on how long that back-end
  source takes to respond with the results from the query (or queries).

The above statement is well documented, however, in my design DirectQuery request shouldn't be an issue because most of the logic and transformation will take place in Databricks (although, I don't want this question to focus on Databricks).
On the other hand, with Azure Analysis Services(AAS) all requests occur in memory as opposed to DirectQuery and therefore much faster.
So, I would like it if you could share you experience using DirectQuery, and AAS. If you could let me know if I have missed out on any advantages/disadvantages of using on technology over the other/

A: The Power BI (PBI) data model, is a lighter weight version of Analysis Service. If you have PBI Desktop open, you can open task manager and see that there is a Analysis Services instance in the background.
In Power BI the dataset size is limited to 1GB, in Premium it is 10GB, with the ability to refresh to 12GB.

Analysis Services will be able to hold more data, and is not limited to the limited data set sizes, and you also have other features based for an Enterprise Organisation. Analysis Services can also sit over a data source in direct query mode or import the data, like Power BI.
In your question you mentioned that the Direct Query Mode 'is notorious for having performance issues', however that will be dependent on the structure and size of the data source. For a number of projects that I have deployed, I have used Direct Query to sit over data sources that have been at least 50-100GB, however these have been mostly standard Star Schema data warehouses, or a defined reporting table, both will have the relevant indexes, covering indexes, or Column Store Indexes to allow more efficient retrieval of data. Direct Query Mode will slow down due to the number of query's that it has the do on the data source based on the measure, relationships and the connection overhead. Another can be the number of visuals on page, as each visual is a query and each one has to run on the data source.
One other method to increase the speed of Direct Query would be to use Aggregations in Power BI, to store an Imported subset of data in Power BI. If the query can be answered by the aggregation layer then it will be answered quicker. Microsoft demonstrated this with the 'Trillion Row Demo'
In terms of the Power BI Direct Query Issues, from the range of clients that I interact with, those that do have issues with Direct Query, have a mash up of tables in an inefficient schema, running sub optimal query's on the data source, with a number of data transformations in DAX, and DAX measures that have been badly written, for example lots of DISTINCT COUNTS & SWITCH.
So, if you wish to import the data, and it is over dataset size limits then Analysis Services is your best option. If you can set up the data structure in a good way, there should be no issues with Power BI and Direct Query.
Hope that helps


text:
Q: How to format elements of lists by splitting '\n'? I have the list
col3_data = ['Hi','Good\nMorning','My\nfriend','Sam']

I want to format the list in a way such that elements containing \n only display the first line.
expected output:
['Hi','Good','My','Sam']

I tried using :
desired_list = [x.split('\n')[1:] for x in col3_data]

But I didn't get the desired result

A: Try this should work
    col3_data = ['Hi', 'Good\nMorning', 'My\nfriend', 'Sam']

    newl = []
     for x in col3_data:

         newl.append((x.split("\n",1)[0]))

      print(newl)

Will give
['Hi', 'Good', 'My', 'Sam']

A: You have issue woth x.split('\n')[1:] this line. It should be x.split('\n')[:1][0] or [x.split('\n')[0]
Try this:
col3_data = ['Hi','Good\nMorning','My\nfriend','Sam']

desired_list = [x.split('\n')[:1][0] for x in col3_data]

# OR

desired_list = [x.split('\n')[0] for x in col3_data]

print(desired_list)

Output:
['Hi', 'Good', 'My', 'Sam']


text:
Q: EditText Change Canvas drawText Android i have an activity(not the main activity) that has 2 graphics, an edittext field and a button.
all the button does is return the user back to the main activity.
i want to be able to change one of text graphic's when the EditText field changes. So whenever the user inputs text in the edittext field the graphic text changes to the same instantly. currently it only changes when i close the keypad.
heres my code
public class ThirdActivity extends AppCompatActivity {

    private DemoView demoview;
    private EditText editText;
    private String graphicText = "blank";
    private Paint paint;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_third);

        demoview = new DemoView(this);

        Button button = (Button) findViewById(R.id.thirdActButton);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                onButtonPress();
            }
        });

        editText = (EditText) findViewById(R.id.thirdActEditText);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!editText.getText().toString().equalsIgnoreCase("")){
                    graphicText = editText.getText().toString();
                    Log.d("MyApp",graphicText);
                }
            }
        });

        LinearLayout v = (LinearLayout) findViewById(R.id.linearlayout);
        v.addView(demoview);

    }

    private class DemoView extends View{
        public DemoView(Context context){
            super(context);
        }

        @Override protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);

            paint = new Paint();

            // draw some text using STROKE style
            paint.setStyle(Paint.Style.FILL_AND_STROKE);
            paint.setStrokeWidth(5);
            paint.setColor(Color.BLUE);
            paint.setTextSize(100);
            canvas.drawText("Graphic", 75, 75, paint);

            // draw some text using FILL style
            paint.setStyle(Paint.Style.FILL);
            paint.setColor(Color.RED);
            paint.setTextSize(75);
            canvas.drawText(graphicText, 150, 210, paint);

        }
    }
}

any help would be greatly appreciated.
thanks

A: Write your code in onTextChanged() instead of afterTextChanged() and it will do the trick. If you want to change the graphics after user inputs at least one character then use onTextChanged(). If you want to change the graphics before user gives any inputs then use beforeTextChanged().

A: Instead of adding the code in afterTextChanged, add it in onTextChanged. For example -
  @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

               if (!editText.getText().toString().equalsIgnoreCase("")){
                graphicText = editText.getText().toString();
                Log.d("MyApp",graphicText);
            }
        }

A: thanks to the responses above this was the solution i used.
it didnt actually make a difference whether the code was in the afterTextChanged() method or the onTextChanged(). what made the difference was the demoview.invalidate(); which refreshes the demoview
@Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (!editText.getText().toString().equalsIgnoreCase("")){
                    graphicText = editText.getText().toString();
                    Log.d("MyApp",graphicText);
                    //refreshes the demoview so it will change instantly
                    demoview.invalidate();
                }

            }

thanks for the help


text:
Q: Let $X$ be a finite set. Prove or disprove: $(X,\tau)$ is separable topological space. My attempt:
$X$ is finite, so countable, and $\overline{X}=X$, so $(X,\tau)$ is separable. Is this correct?

A: Sure. It's totally obvious. We can also state it's second countable, compact, Lindelöf, countably compact, first countable,all for the same reason.


text:
Q: Interpreting sensitivity analysis of mediation using Baron-Kenny procedure I got an output similar to this :

And I would like to interpret it precisely. I would like to know how could I know if the reported mediation is correct based on the values of p(rho in the output) or the other two measures in the second section of the output. What is the threshold that similar quantities to R-squared should have in order to confirm the robustness of the mediation (the lesser, the better, or vice versa, and what is the threshold 0.40,0.10...)
Thank you so much in advance


text:
Q: Rest API: Naming convention I want your's opinion for given scenario, while working with REST API.
Let's say, I have one route to fetch user details, we have some roles for users like supplier, buyer and admin.

GET: user-details/{id}

In this case we have to fetch some other user related data, which is very less, if we compare supplier user role  with user having role buyer or admin.
Can we create route like below by sending query parameter to route to get each user details like:

GET: users/1/supplier
GET: users/1/buyer

--- OR---

GET: users/1?role=supplier

If we introduce different function for each route, which will reduce complexity and any change request for specific user role can be easily adjusted.

A: Designing routes completely depend upon what kind of data you returning to the client and what kind of business logic you are trying to implement for each user role. But not prefer pass user role into the query string.

*

*If you are returning different data for each role and you have a few business logic, It's better to define different routes for each user role.
GET: users/1/supplier
GET: users/1/buyer

*If you don't have that much business logic but you want to retrieve same data with additional condition (want to add dynamically SQL where condition based on user role), You can fetch result with laravel eloquent way ->when even you don't need to define multiple routes.

A: If the user roles do not overlap, i.e. a Supplier would never be a Buyer and a Buyer would never be a Supplier, then:
We can get user role from ID in our API method and can create different methods to get details for different set of user data (based on the "type" - use Switch, may be)
Single API to support all user types would be fine: GET: user-details/{id}
However, if a Supplier can also act as a Buyer, then you should have different function/route set-up in place.
E.g. supplier-details/{id} or buyer-details/{id}
Having different routes focus on providing only specific data for the user type.

A:
Can we create route like below by sending query parameter to route to get each user details

Yes, you can -- creating new resources to handle a new use case is a perfectly reasonable thing to do.
There are trade offs.  As far as "REST" clients are concerned, two different URI means two different unrelated resources -- even if they happen to have overlapping path segments.  That means that invalidating the cached representation(s) of one resource don't impact the other in any way.  So you can end up with a client that has cached representations of the two resources that are inconsistent with each other.
An alternative to consider is whether you want to have two resources, or one resource with two representations.  Having multiple representations of the same resource solves the cache invalidation problem, but you move additional complexity into the problem of distributing knowledge of multiple media types.

A: in my opinion,
If "supplier" and "buyer" are sub resources of a user, than first approach is perfectly fine.
In second case "role=supplier" looks more like a search criteria.


text:
Q: JavaFX Application Freezes, and I have no idea why So, I have made a Sudoku Solver as a project. The solving works fine except for one thing. When I insert numbers in positions i know will not work, the program freezes and crash. I think i've located the problem and it seems to be stuck in an infinite loop, but I can't figure out why?
Keep in mind that i'm new to JavaFX.
Any help is appreciated, thanks in advance.
The Sudoku Class
public class Sudoku {

private int board[][];

public Sudoku(){
    this.board = new int[9][9];
    clear();
    initBoard();
}

public void printBoard(){
    for(int i = 0; i < 9; i++){
        if((i % 3) == 0){
            System.out.print("-------------------------" + "\n");
        }
        for(int n = 0; n <9; n++){
            if((n % 3) == 0){
                System.out.print("| ");
            }
            System.out.print(board[i][n] + " ");
        }
        System.out.print("|" + "\n");
    }
    System.out.print("-------------------------");
}

public int getValueAt(int col, int row){
    return board[col][row];
}

public boolean solve(){
    if(solve(0,0)){
        return true;
    }else{
        clear();
        return false;
    }
}

public void clear(){
    for( int row = 0; row < 9; row++ ){
        for( int col = 0; col < 9; col++ ){
            board[row][col] = 0 ;
        }
    }
}

public void setBoard(int input[][]){
    clear();

    board = input;
}

private void initBoard(){
    clear();

    //Rad 1
    board[0][2] = 8;
    board[0][5] = 8;
    board[0][7] = 6;
    board[0][8] = 2;
    //Rad 2
    board[1][8] = 5;
    //Rad 3
    board[2][0] = 1;
    board[2][2] = 2;
    board[2][3] = 5;
    //Rad 4
    board[3][3] = 2;
    board[3][4] = 1;
    board[3][7] = 9;
    //Rad 5
    board[4][1] = 5;
    board[4][6] = 6;
    //Rad 6
    board[5][0] = 6;
    board[5][7] = 2;
    board[5][8] = 8;
    //Rad 7
    board[6][0] = 4;
    board[6][1] = 1;
    board[6][3] = 6;
    board[6][5] = 8;
    //Rad 8
    board[7][0] = 8;
    board[7][1] = 6;
    board[7][4] = 3;
    board[7][6] = 1;
    //Rad 9
    board[8][6] = 4;
}

private boolean solve(int i, int j){
    //Ifall en lösning har hittats
    if(i > 8){
        return true;
    }

    //Ifall positionen inte är satt
    if(board[i][j] != 0){
        //next(i, j);
        if(j < 8){
            if(solve(i, j+1)){
                return true;
            }
        }else{
            if(solve(i+1, 0)){
                return true;
            }
        }
    }
    //Ifall positionen är satt
    else{
        for(int n = 1; n < 10; n++){
            //Kollar ifall siffran "n" inte finns på någon av raderna
            if(rowIsOk(i, n) && colIsOk(j, n) && boxIsOk(i, j ,n)){
                board[i][j] = n;
                //next(i, j);
                if(j < 8){
                    if(solve(i, j+1)){
                        return true;
                    }
                }else{
                    if(solve(i+1, 0)){
                        return true;
                    }
                }
            }
        }
        board[i][j] = 0;
    }
    //board[i][j] = 0;
    return false;
}

//Kollar om raden är ok
private boolean rowIsOk(int row, int num){
    for(int i = 0; i < 9; i++){
        if(board[row][i] == num){
            return false;
        }
    }
    return true;
}

//Kollar om kolumnen är ok
private boolean colIsOk(int col, int num){
    for(int i = 0; i < 9; i++){
        if(board[i][col] == num){
            return false;
        }
    }
    return true;
}

private boolean boxIsOk(int row, int col, int num){
    row = (row/3) * 3;
    col = (col/3) * 3;

    for(int r = 0; r < 3; r++){
        for(int c = 0; c < 3; c++){
            if(board[row+r][col+c] == num){
                return false;
            }
        }
    }

    return true;
}

}
The GUI Class
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.TilePane;
import javafx.stage.Stage;

public class SudokuGUI extends Application{

private Sudoku sudoku = new Sudoku();
private TilePane board;

public static void main(String[] args){
    launch(args);
}

@Override
public void start(Stage primaryStage){
    primaryStage.setTitle("Sudoku Solver: H4xx0r Edition");

    BorderPane root = new BorderPane();
    board = initBoard();
    HBox control = addControl();

    root.setCenter(board);
    root.setBottom(control);

    primaryStage.setScene(new Scene(root, 500, 500));
    primaryStage.show();
}

private void updateBoard(TilePane tile){
    tile.getChildren().clear();
    for(int col = 0; col < 9; col++){
        for(int row = 0; row < 9; row++){
            tile.getChildren().add(createCell(col, row));
        }
    }
}

private TilePane initBoard(){
    TilePane tile = new TilePane();

    tile.setHgap(4);
    tile.setVgap(4);
    tile.setPadding(new Insets(0, 10, 0, 10));
    tile.setPrefColumns(9);
    tile.setPrefRows(9);
    //tile.setStyle("-fx-background-color: rgba(255, 215, 0, 0.1);");
    tile.setAlignment(Pos.CENTER);

    tile.getChildren().clear();
    for(int col = 0; col < 9; col++){
        for(int row = 0; row < 9; row++){
            tile.getChildren().add(createCell(col, row));
        }
    }

    return tile;
}

//Skapar "celler" med textfält
private TextField createCell(int col, int row){
    TextField txtfield = new TextField();
    String text;

    if(sudoku.getValueAt(col, row) != 0){
        text = Integer.toString(sudoku.getValueAt(col, row));
    }else{
        text = "0";
    }

    txtfield.setText(text);
    txtfield.setPrefWidth(45);
    txtfield.setPrefHeight(45);
    txtfield.setAlignment(Pos.CENTER);
    //txtfield.setEditable(false);
    txtfield.setStyle("-fx-font-weight: bold;");
    if(((row < 6 && row > 2) && (col < 6 && col > 2))
            || ((row < 3) && (col < 3)) //Vänster Upp
            || ((row < 3) && (col > 5)) //Höger Upp
            || ((row > 5) && (col > 5)) //Höger Ner
            || ((row > 5) && (col < 3)))//Vänster Ner
    {
        txtfield.setStyle("-fx-background-color: rgba(255, 178, 0, 0.9);" + "-fx-font-weight: bold;");
    }

    return txtfield;
}

//LÄgger till knappar i en Box
private HBox addControl(){
    HBox hbox = new HBox();
    Button solve = new Button("Solve");
    Button clear = new Button("Clear");
    Button set = new Button("Set");

    hbox.setPadding(new Insets(15, 12, 15, 12));
    hbox.setSpacing(10);
    hbox.setAlignment(Pos.BOTTOM_CENTER);

    solve.setPrefSize(100, 20);
    solve.setOnAction(e -> solve());
    clear.setPrefSize(100, 20);
    clear.setOnAction(e -> clear());
    set.setPrefSize(100,  20);
    set.setOnAction(e -> set());

    hbox.getChildren().addAll(solve, clear, set);

    return hbox;
}

//Knapp-funktioner
private void solve(){
    if(sudoku.solve()){
        updateBoard(board);
    }else{
        sudoku.clear();
        Alert alert = new Alert(AlertType.ERROR);
        alert.setTitle("YOLO SWAGGINS");
        alert.setHeaderText("Sudokut SWAG ERROR");
        alert.setContentText("Sudokut har inte tillräckligt med SWAG");
    }
}

//Hämtar värden från textfälten
private void set(){
    int newset[][] = new int[9][9];
    int array[] = new int[board.getChildren().size()];

    for(int i = 0; i < board.getChildren().size(); i++){
        TextField tmp = (TextField) board.getChildren().get(i);
        //System.out.println(tmp.getText());
        array[i] = Integer.parseInt(tmp.getText());
    }

    int n = 0;
    for(int col = 0; col < 9; col++){
        for(int row = 0; row < 9; row++){
            newset[col][row] = array[n];
            n++;
        }
    }

    sudoku.setBoard(newset);
    updateBoard(board);
}

private void clear(){
    sudoku.clear();
    updateBoard(board);
}

}

A: The Problems seems to be that your solve(int i, int j) is called over and over again (recusive) which freezes the GUI if it does not find a solution. It seems that your algorithm is not well implemented.
Generally it is a good advise to execute computationally expensive code in a separate thread (i.e. not in the GUI-thread).


text:
Q: Setting displayable objects in multiple classes (J2ME) I'm trying to make my code neater by using multiple classes for my applications
form options. Currently I keep getting null pointer exceptions when trying to setCurrent.
Here is my main class the error starts in my command listener when I call the other class.
import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;

public class CalFrontEnd extends MIDlet implements CommandListener {

  private Display display;
  private List list = new List("Please Select a Option", List.IMPLICIT);
  private List Blist = new List("Please Select a Browsing Option", List.IMPLICIT);
  private Command select = new Command("Select", Command.SCREEN, 1);
  private Command exit = new Command("Exit", Command.EXIT, 2);
  private Command save = new Command("Save,", Command.SCREEN, 2);
  private DateField calendar;
  Alert alert;

  //
  //
  //
  public CalFrontEnd() {
    display = Display.getDisplay(this);

    list.append("Select Date", null);
    list.append("Add Events", null);
    list.append("Remove Events", null);
    list.append("Browse Events", null);
    list.addCommand(select);
    list.addCommand(exit);
    list.setCommandListener(this);

  }

  //
  //Start Application Method
  //
  public void startApp() {
    display.setCurrent(list);
  }

  //
  //Pause Application Method
  //
  public void pauseApp() {
  }

  //
  //Destroy Application Method
  //
  public void destroyApp(boolean unconditional) {
  }

  //
  //Method creates form which contains calendar
  //
  /*public void selectDate()
  {
      calendar = new DateField("Date In :", DateField.DATE, TimeZone.getTimeZone("GMT"));
      Form cform = new Form("Calendar");
      cform.append(calendar);
      cform.addCommand(exit);
      display.setCurrent(cform);
  }*/

  //
  //Method creates form which contains adding events
  //
  public void AddEvents()
  {
      TextBox aeText = new TextBox("Add Event","", 256, 0);
      display.setCurrent(aeText);
  }

  //
  //Method creates form which contains removing events
  //
  public void RemoveEvents()
  {

      Form reform = new Form("Remove Event");
      reform.append(calendar);
      display.setCurrent(reform);
  }

  //
  //Method creates form which contains removing events
  //
  public void BrowseEvents()
  {
      Blist.append("Monthly", null);
      Blist.append("Daily", null);
      Blist.addCommand(select);
      Blist.addCommand(exit);
      Blist.setCommandListener(this);
      display.setCurrent(Blist);
  }

  //
  //but it's better practice to make each form a different class extending CommandListener and it's own commandAction. And leave the display public static in MIDlet class
  //...
  public void commandAction(Command command, Displayable displayable) {
      if (displayable == list) {
          if (command == List.SELECT_COMMAND) {
              switch (list.getSelectedIndex()) {
                  case 0: // select date
                      SelectDate.BuildCalendar(); //Error Here
                      break;
                  case 1: //add events
                      AddEvents();
                      break;
              }
          } else if (command == exit) {
             destroyApp(false);
             notifyDestroyed();
          }
      }
  }
}

And here is the class that is being called.
public class SelectDate
{

    private static DateField calendar;
    private static Form form = new Form("derb");
    private static Command select = new Command("Select", Command.SCREEN, 1);
    private static Command exit = new Command("Exit", Command.EXIT, 2);
    private static Command save = new Command("Save,", Command.SCREEN, 2);
    private static Display display;

    public static void BuildCalendar()
    {
        calendar = new DateField("Date In :", DateField.DATE, TimeZone.getTimeZone("GMT"));
        form.append(calendar);
        form.addCommand(exit);
        display.setCurrent(form);
    }
}

A: The NullPointerException happens because display in SelectDate class is null.
To fix that, you can for example drop it from there and instead, add to method parameters:
// ...
public static void BuildCalendar(Display display) // added parameter

Then, when you invoke above method from CalFrontEnd, pass the instance of display there:
                      // ...
                      SelectDate.BuildCalendar(display); //Error will go away


text:
Q: Javascript - make a feature that lowers or raises the pitch of the song that's playing Has anyone ever made an app for music?  I need to make a feature that lowers or raises the pitch of the song that's playing... I need to be able to play my audio sample .wav, .mp3, .mp4
Which library to use to do this in javascript?  I still haven't decided which language to use.  How do I capture an audio or video with audio and manage to increase or decrease the sound pitch?  I want to do a KARAOKE show.  In this program I will need to increase and decrease the pitch of the music.  I'll do it with javascript


text:
Q: Override vs Overwrite
Possible Duplicate:
C++ Overriding… overwriting?

What's the difference between override and overwrite? I've heard them used interchangeably but I suspect that's incorrect.

A: You can only overwrite what's been written and where it's been written, while you can override things elsewhere (for instance you can override members of base class in derived classes).

A: override is a C++11 keyword used to override base virtual method:
class A
{
    virtual f(int) {}
};

class B
{
    virtual f(int) override {} // override A::f(int)
};

This lets you make sure that A::F(int) gets overriden, meaning you are not creating new virtual function.
Of course this code won't compile if the function signature was different.
overwrite is not C++ keyword and it basically means to overwrite some file or text with new one.
The keyword override has been introduced because some times a programmer doesn't know whether he is overriding or whether he is creating a new virtual method with a different signature.
Using that keyword you either get an error or override virtual method.


text:
Q: What conditional to use for hypothetical explanation of the past? If our sample had a lot of variation in people's abilities, our results could be biased.

We talk about the past. Therefore we should the type 3 conditional, with past perfect. However, the condition might well be true, we are just unable to confirm it, due to not measuring people's abilities. It is not an unlikely scenario and the result might well be true in the present.

A: The meaning you want is an "open" conditional: it's as likely as not. This is used with a modal preterite, the verb "had" in the if clause. This is not the same as "past" in time.
This particular use resembles what some teaching websites call the "second conditional":
Cambridge "imagined conditions"
"We use the second conditional to talk about the possible result of an imagined situation in the present or future. We say what the conditions must be for the present or future situation to be different."
Your example uses the verb "had" in the "if" clause, plus modal "could" in the main clause, which seems to fit the description at that website.
I suggest that this isn't a "past" meaning in the temporal sense. It actually has a "future" aspect, because you are talking about conditions that may exist at present, and may be found to be true later.
I believe your suggested sentence is correct for the situation you describe.
I've looked at a few websites that categorize conditionals, and they are variable as to the number of categories, the time frames involved, and the degree of unreality implied. In addition to that, they refer to "mixed conditionals", which suggests that the categories shouldn't be taken as rigid at all.


text:
Q: Calling functions in two different ways - JavaScript I'm very new to JavaScript, so my apologies if this answer is glaringly obvious or I'm barking up the wrong tree!
What's the difference in the following code snippets:
function primeAddNum(innerHTML) {
    return function() {
        addNum(innerHTML);
        return false;
    };
}
var func = primeAddNum(innerHTML);

The second one:
var func = function() {
        return function() {
            addNum(innerHTML);
            return false;
        };
}();

The top one works the way I'd like it to, but not the bottom, but that's not overly important to me. What I want to know is the logic behind each block, because I just can't see the difference!

A: The problem with the second block is that innerHTML is undefined there, since you're not passing it. They will become equivalent if you change it to:
var func = function(innerHTML) {
    return function() {
        addNum(innerHTML);
        return false;
    };
}(innerHTML);

A: Well with the second one you can only create a func once. But with first one, you can create many:
var func1 = primeAddNum(innerHTML);
var func2 = primeAddNum(someOtherInnerHTML);

A: there is no difference, you can use both without any problems


text:
Q: How to prove with Lagrange theorem How can I prove that:
if $f: \Bbb R \rightarrow \Bbb R$ is convex and differentiable, such that $y = 0$ is an asymptote for $x \rightarrow \infty$, then $f(x) \ge 0, \forall x \in \Bbb R$
How can I prove that $f(x) \ge 0$ with the Lagrange theorem?

A: This is a possible solution to the problem (but i'd also like to see some of yours):
My Try:
Given the following theorem:
TEO. Is $f$ differentiable in an interval $I$. Then $f$ is concave (convex) in $I$, if and only if $f'$is increasing (decreasing) in I.
For the previous theorem we have that $f'(x)$ it is growing broadly.
So, reasoning by contradiction, we suppose that exists $x_0 \in \Re: f(x) < 0$, then we set $\epsilon = \frac{|f(x)|}{3}$.
For the definition of asymptote $\rightarrow \lim _{x\to \infty \:}\left(f(x)\right)=1$, then by definition of limit, we have that exists $M \in \Re: |f(x)|<\epsilon, \forall x > M$.
At this point, we choose $x_1 > max\{x_0, M\}$, then we set
$$L_1 = \frac{f(x_1)-f(x_0)}{x_1-x_0}$$
Then, we choose $x_2>x_1$ so that $x_2-x_1>x_1-x_0$ from which it follows that:
$$L_2 = \frac{f(x_2)-f(x_1)}{x_2-x_1} \le \frac{2\epsilon}{x_2-x_1}< \frac{2\epsilon}{x_1-x_0}<\frac{f(x_1)-f(x_0)}{x_1-x_0} = L_1$$
where the last inequality follows from the fact that $f(x_0) = -3\epsilon$ and $f(x_1)> -\epsilon$.
So is $L_2<L_1$. On the other hand, for the Lagrange's theorem applied to the function $f$ initially restricted in $[x_0,x_1]$ and then in $[x_1,x_2]$ you get $L_1=f'(c_1)$ and $L_2=f'(c_2)$, where $c_1, c_2$ are chosen so that $x_0<c_1<x_1$ and $x_1<c_2<x_2$.
So $c_1 < c_2$ and $f'(c_1) = L_1 > L_2 = f'(c_2)$ for which you get a
contradiction to the growth in the broad sense of the first derivative function.

A: Let $x_0$ such that $y_0 = f(x_0) < 0$ and consider $x_1 > x_0$.  I claim that $f(x_1) \leq y_0 < 0$.  If this is true, it's a contradiction since $x_1$ was general, which shows that $y=0$ can not be an asymptote.
To prove the claim, assume $f(x_1) > y_0$, so $\frac{f(x_1) - y_0}{x_1 - x_0} > 0$.  Note that since $y=0$ is an asymptote ( or, just that there is any horizontal asymptote ), as $x\to \infty$, we have $\frac{f(x)-y_0}{x-x_0} \to 0$, so in particular we can find $x_2 > x_1$ such that $\frac{f(x_2) - y_0}{x_2 - x_0} < \frac{f(x_1)-y_0}{x_1 - x_0}$, which means that $(x_1,f(x_1))$ lies above the line connecting $(x_0,f(x_0))$ and $(x_2,f(x_2))$, which is not possible since $f$ is convex.

A: Since $f$ is convex, its derivative is nondecreasing. In particular, the limit
$$
\lim_{x\to\infty}f'(x)
$$
exists (finite or infinite). By l'Hôpital's theorem,
$$
\lim_{x\to\infty}f'(x)=\lim_{x\to\infty}\frac{f(x)}{x}=0
$$
Therefore $f'(x)\le0$, for every $x$. Thus $f$ is nonincreasing. Then, if $f(x_0)<0$, for some $x_0$, we have $f(x)\le f(x_0)$, contradicting
$$
\lim_{x\to\infty}f(x)=0
$$
Proposition. If $f$ is differentiable and convex over $\mathbb{R}$, then $f'$ is nondecreasing.
Proof. Let $a<b$. The line through $(a,f(a))$ and $(b,f(b))$ can be written as
\begin{gather}
y=\frac{f(b)-f(a)}{b-a}(x-a)+f(a)\\
y=\frac{f(b)-f(a)}{b-a}(x-b)+f(b)
\end{gather}
By Lagrange's theorem (mean value theorem),
$$
\frac{f(b)-f(a)}{b-a}=f'(c)
$$
for some $c\in(a,b)$. Then, for $t\in(a,b)$, convexity says that
\begin{gather}
f(t)\le f'(c)(t-a)+f(a)\\
f(t)\le f'(c)(t-b)+f(b)
\end{gather}
so we derive
$$
\frac{f(t)-f(a)}{t-a}\le f'(c)\le\frac{f(t)-f(b)}{t-b}
$$
and, taking the limits for $t\to a$ and for $t\to b$,
$$
f'(a)\le f'(c)\le f'(b)
$$
proving $f'(a)\le f'(b)$. QED
Proposition. Let $f$ be differentiable over $\mathbb{R}$. If $f'(x)\le0$, for every $x$, then $f$ is nonincreasing.
Proof. Let $a<b$. Then
$$
\frac{f(b)-f(a)}{b-a}=f'(c)\le0
$$
by Lagrange's theorem. Thus $f(a)\ge f(b)$. QED


text:
Q: New input type Bundle Items I am thinking to create a new input type for another type of select, because i have 2 types of them.
I want a new option that use a diferent template of: bunde_catalog_product_view_type_bundle_option_select.phtml
I want to select the new option at: Backend - product - bundle items - and when i add a new bundle item option, i want to choose between drop-down and new drop-down.
Because i wanna have the same type of select but just with little changes on frontend.
I can't manage with other solutions, and i have no idea if its a terrible idea to do that.

A: After discussing, i opt to use other design with the same codes unless the template that i want to use on this products, so on backend->product->design i associate the new template.


text:
Q: Override ImageFactory Block in Magento2 I am trying to override the way that the Images in the Catalog, Checkout and Cart are going to be loaded someway different then Magento does it by default.
Thats why I'm trying to create a module that changes ImageFactory.php for me.
Module Structure:

I have created an appropriate di.xml:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Catalog\Block\Product\ImageFactory" type="Vendor\Name\Block\Product\ImageFactory" />
</config>

In ImageFactory I have changed the module that's being loaded by Magento2, which is located correctly in the structure.
However, neither the Phtml or the ImageFactory is being called by Magento. The module is actively read by Magento as I see the adminhtml settings that I've configured in config.xml and such.

A: I ran into this as well and found out that in ImageBuilder this ImageFactory class is not included in the way it should be included.
Usually one should include a class like this:
use Magento\Catalog\Helper\ImageFactory;

However in one of the most important classes where it is used, it is included in the construct without the full path. In Magento\Catalog\Block\Product\ImageBuilder.php it is included in the construct without the full path:
use Magento\Catalog\Helper\ImageFactory as HelperFactory;
use Magento\Catalog\Model\Product;
...
public function __construct(
    HelperFactory $helperFactory,
    ImageFactory $imageFactory
) {
    $this->helperFactory = $helperFactory;
    $this->imageFactory = $imageFactory;
}

So in the above it has no full path to the imageFactory so it searches it locally (and low and behold it is in the same directory). This is bad practice and means that you can override it all you want, if you do not override ImageBuilder as well, nothing will change for the major part of where it is used.
I ended up making a preference for both and including the full path in the ImageBuilder construct for ImageFactory.


text:
Q: Unable to retrieve the runtime generic context for 'System.Collections.Generic.List I've created a class that inherits from List to be used on my Unity-firebase project porpouses.
using System.Collections.Generic;

public class FirestoreList<FirestoreData, PlainData> : List<FirestoreData>, IConvertToPlainData<List<PlainData>>
    where FirestoreData : IConvertToPlainData<PlainData>
    where PlainData : IConvertToFirestore<FirestoreData>
{
    public FirestoreList() : base() { }
    public FirestoreList(List<PlainData> plainDataList) <-- this is the 8th line
    {
        this.Clear();
        foreach (PlainData plainData in plainDataList)
        {
            this.Add(plainData.ToFirestoreData());
        }
    }

    public List<PlainData> ToPlainData()
    {
        List<PlainData> convertedPlainDataList = new List<PlainData>();
        if (this.Count > 0)
        {
            foreach (FirestoreData firestoreData in this)
            {
                convertedPlainDataList.Add(firestoreData.ToPlainData());
            }
        }

        return convertedPlainDataList;
    }
}

The interfaces are the following ones (basically functioning as a Serialize/Deserialize):
public interface IConvertToPlainData<T>
{
    T ToPlainData();
}

public interface IConvertToFirestore<T>
{
    T ToFirestoreData();
}

This code works on the Editor, on runtime etc, but when I try to build using IL2CPP (cause I'm targeting mobile stores) the following error on the build appears:
IL2CPP error for method 'System.Void FirestoreList`2::.ctor(System.Collections.Generic.List`1<PlainData>)' in FirestoreList.cs:8
Additional information: Unable to retrieve the runtime generic context for 'System.Collections.Generic.List`1<PlainData>'.

I don't understand the error message, and I didn't find any similar references on google, all that I have is this link about Unity and IL2CPP ScriptingRestrictions :(
Can someone help me or at least point me to the answer? Thanks!
EDIT:
An example of the classes that I use to show the generic parameter that I use to instantiate FirestoreList:
[Serializable]
public class User : IConvertToFirestore<User_FirestoreData>
{
  [SerializeField] public List<User> usersList = new List<User>();

  public User_FirestoreData ToFirestoreData()
  {
    User_FirestoreData userFire = new User_FirestoreData()
    {
      usersList = new FirestoreList<User_FirestoreData, User>(this.usersList)
    };

    return userFire;
  }

}

[FirestoreData]
public class User_FirestoreData : IConvertToPlainData<User>
{
  [FirestoreProperty] public FirestoreList<User_FirestoreData, User> usersList { get; set; }

  public User ToPlainData()
  {
    User user = new User()
    {
      usersList = this.usersList.ToPlainData(),
    };
    return user;
  }

}

EDIT2:
My thoughs are that when I'm using this.usersList.ToPlainData() there's no specification of what is FirestoreData and PlainData, so the compiler can't know what cast to do (or something similar).
For the moment the only solution have been to remove the FirestoreList class and implement a couple of extension methods for List like these ones:
public static List<PlainData> ToPlainData<PlainData, FirestoreData>(this List<FirestoreData> list) where FirestoreData : IConvertToPlainData<PlainData> where PlainData : IConvertToFirestore<FirestoreData>
{
    List<PlainData> convertedPlainDataList = new List<PlainData>();
    if (list.Count > 0)
    {
        foreach (FirestoreData firestoreData in list)
        {
            convertedPlainDataList.Add(firestoreData.ToPlainData());
        }
    }

    return convertedPlainDataList;
}

public static List<FirestoreData> ToFirestoreData<FirestoreData, PlainData>(this List<PlainData> list) where FirestoreData : IConvertToPlainData<PlainData> where PlainData : IConvertToFirestore<FirestoreData>
{
    List<FirestoreData> convertedFirestoreDataList = new List<FirestoreData>();
    if (list.Count > 0)
    {
        foreach (PlainData plainData in list)
        {
            convertedFirestoreDataList.Add(plainData.ToFirestoreData());
        }
    }

    return convertedFirestoreDataList;
}

As you are forced to call it like this: this.charactersList.ToPlainData<User, User_FirestoreData>() seems like there is no problem with the JIT or AOT.

A: Generics used like this are not going to work in Unity on all platforms. From Microsoft documentation:

When a generic type is first constructed with a value type as a parameter, the runtime creates a specialized generic type with the supplied parameter or parameters substituted in the appropriate locations in the MSIL. Specialized generic types are created one time for each unique value type that is used as a parameter.

This is called Just In Time (JIT) compilation, and is not supported in Unity using IL2CPP (only Mono). From Unity's documentation:

The IL2CPP backend converts MSIL (Microsoft Intermediate Language) code (for example, C# code in scripts) into C++ code, then uses the C++ code to create a native binary file (for example, .exe, .apk, or .xap) for your chosen platform. This type of compilation, in which Unity compiles code specifically for a target platform when it builds the native binary, is called ahead-of-time (AOT) compilation.

In other words, when you compile your app, it creates a native binary that does not have the JIT functionality in C#/.NET.
Additionally:

Some platforms don't support AOT compilation, so the IL2CPP backend doesn't work on every platform. Other platforms support AOT and IL2CPP, but don't allow JIT compilation, and so can't support the Mono backend.

This is why it works on some platforms, but not others.


text:
Q: Will disabling nagles algorithm improve performance? I currently have an application that receives real time messages at a very high rate and my application needs to display those messages instantly. I read about nagles algorithm and I understand that it combines small messages into one big message and then transmits it (It is designed to reduce the number of acknowledgement packets by delaying the ACK for a short time).My question is will disabling Nagles algorithm help my application ? all my messages are to be displayed in realtime as soon as they are received.Any suggestions on this issue would be appreciated.
Update:
Also I only have control of the receiver , will disabling nagles algo. on the receiver have any affect or does it only have affect when its disabled on the sender ?

A: Nagle is a sender side algorithm only, so if you can only affect the receiver, you cannot disable it.
Even if you could affect the sender, disabling Nagle is not very effective when doing one directional communication.  In bidirectional communication, disabling Nagle can improve throughput because the benefits of removing delays can accumulate as each node can send its responses slightly sooner, letting the other side respond even sooner than that.  However, in the one direction case, disabling Nagle can decrease latency by one round trip, but those benefits cannot accumulate because the fact that you are not delaying packets does not slow down the generation of new packets.  You never get ahead by more than one round trip.  Over the internet, that's ~20-30ms.  Over a LAN, that's usually ~1ms
If your system is sufficiently hard real time that a single round-trip latency matters, then TCP is a poor protocol, and you should be using UDP instead.  Nagle is a TCP only algorithm, so it would not affect UDP.
Just for fun:  Pinging a local computer on my LAN is <1ms.  This means Nagle can only delay my messages by something under 1ms.  Quantums for desktop computer schedulers can 20-60ms [1], and even longer for servers, so I would expect removing the nagle algorithm to have no visible effect on my LAN, dwarfed by the effect of other threads on my computer consuming the CPUs
[1] http://recoverymonkey.org/2007/08/17/processor-scheduling-and-quanta-in-windows-and-a-bit-about-unixlinux/


text:
Q: Is it possible to disable the kudu scm Disable kudu for the running web app.
Why? Kudu is consuming the CPU periodically and I want to stop that.
So far I have tried to Kill the process by clicking on Properties >> Kill button. but this process gets start again.

A: You can use below settings in Application settings.

When separation enabled (the default), the main site and scm site run in different sandboxes.

WEBSITE_DISABLE_SCM_SEPARATION=true

Then you can check Process Explorer.

Offical Doc:

Use the same process for the user site and the scm site


text:
Q: SQL Server - Round a number when it's one decimal before .50 I would like to know if there is a way to round a number if it's one decimal before 50.
i.e,
I am using the below code and it works, it gives 8.50:
select Round(8.49,1) = 8.50

The problem comes when I want to round the below one, I would expect this one to be only 8.48 but results in 8.50 as well.
select Round(8.48,1) = 8.50

The idea is to keep the 8.48 as it is, but when it's 8.49, it needs to be 8.50.

A: If you want something other than a standard rounding, you will probably need to use a nested CASE statement.
Maybe take something like the below and tweak it:
DECLARE @Num DEC (10,2) = 8.49 --8.48

SELECT
CASE
WHEN @Num - FLOOR(@Num) >= 0.5 THEN ROUND(@Num,1)
WHEN @Num - FLOOR(@Num) = 0.49 THEN FLOOR(@Num) + 0.5
ELSE @Num
END AS NewValue


text:
Q: Entity Framework Entity properties as Object type I have a situation where I have multiple DB versions that I cannot change. I have readonly MVC application with EF attached to those DB on different environments.
I have encountered a problem when entity property datatypes just don't match and Entity Framework throws datatype mismatch exception.
What I've done is created property type of object and mapped a column in a DB then added to original generated column "Passed" and skipped mapping, added getter with object to Int32? conversion. Property "_passed" gets always null sadly.
Maybe anyone have an idea how to solve object to Int32 conversion problem or point me to a direction to a more correct approach regarding this issue?
Thanks,
E
[Table("VotingSession")]
public partial class VotingSession
{

    [Column("Passed")]
    public object _passed;
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }

    public int Agenda_id { get; set; }

    public double? TotalLoggedIn { get; set; }
    [NotMapped]
    public object Passed {
        get
        {
            if (_passed.GetType() == typeof(bool))
            {
               return (bool)_passed == true ? 1 : 0;
            }
            else
            {
                return _passed;
            }
        }

    }

    [NotMapped]
    public int? Quorum { get; set; }

A: I think you can't use backing field for db first models,
you can try to do this,
Override getter, if typeof the model.Passed is bool, check if true return 1 else 0, if not bool, return this.Passed value;
public object Passed {
    get
    {
        if (this.Passed.GetType() == typeof(bool))
        {
           return this.Passed == true ? 1 : 0;
        }
        else
        {
            return this.Passed;
        }
    }