text:
Q: having optional attributes in an angular directive let's say that I want to create directive to mimic a number input field (doing so just to learn about directives in general)
so, I create a directive like this
angular.module('myApp')

    .directive('inputNumber',function(){
        return {
            replace: true,
            restrict: 'E',
            scope: {
                label: '@',
                property: '=',
                readonly: '@',
                disabled: '@'
            },
            templateUrl: '/directives/numberInput.html'
        };
    })

and the templateUrl is this
<md-input-container>
      <label>{{ label }}</label>
      <input ng-model="property" type="number">
</md-input-container>

and my html text is this
<input-number label="Columns" property="controller.data.cols">
</input-number>

oddly enough this worked ;) I was quite impressed for a first attempt ..
Now, sometimes I want to add the min and max attributes for a number
as these are optional, what do I add to the directive js and html ?
I presume that I add
min: '@',
max: '@',

to the directive js, but what do I put into the html ?
<input ng-model="property" type="number" min="{{min}}" max="{{max}}">

but then what happens if min / max is not supplied ?
thanks

A: You need to append them with a question mark.
scope: {
  label: '@',
  property: '=',
  readonly: '@',
  disabled: '@',
  min: '@?',
  max: '@?'
}

The question mark declares the scope bindings as optional, allowing you to not include them at all in the markup if you don't need them. If you don't include them then the properties on your isolate scope won't be defined.
<input ng-model="property" type="number" min="{{min}}" max="{{max}}">

Yes that is the correct way to pass values into those attributes, using the {{}} binding syntax. This is because the @ binding is a literal binding. It will take the raw string value of that attribute and assign it to that isolate scope variable. By using the binding syntax, Angular will have resolved those bindings to actual values before your directive is parsed and reads those values in.
If you want two-way binding, then you would use the = binding symbol. That one tells angular that whatever you pass to that attribute should be a variable on the parent scope surrounding the directive. Angular knows at that point to create a two-way binding between that outer-scope variable and the variable on your directive's isolate scope. This way, if the variable in your isolate scope changes, so does the outer-scope variable, and vice versa.
<input ng-model="property" type="number" min="minValue" max="maxValue">

In that example your directive would expect minValue and maxValue to be variables already defined on the parent scope surrounding your directive.
I wrote a detailed blog post on isolate scope bindings last year. Hope it helps!


text:
Q: JavaEE changing DB schema runtime for SaaS application i am developing a SaaS application by using JavaEE technologies (JPA, EJB, ..)
for multitenancy, i chose 'Shared Database, Separate Schemas' approach and designed the DB (PostgreSQL) like that
basically what i need to do is changing the default schema for user sessions in the application so that users can get their own data from the right schema
my business logic is implemented with EJB (Container-managed) and the app server is glassfishv3
so in my EJBs i am just injecting the EntityManager like this
@PersistenceContext(unitName="DBNAME")
private EntityManager em;

and leaving the transaction management to the glassfish
i tried to write @PostConstruct callbacks for Stateless EJBs injecting DataSource
but getClientInfo() returns null somehow so i can not even see the default schema. The reason why i injected DataSource was because i thought i have to do some low-level stuff to specify the schema.
i know if i manage the transactions in the application instead of leaving them to the app server, i can change the EntityManager values through EMF easily but i wanna keep the Container-managed infrastructure and just change some values at runtime
is there any way to do this with SessionContext or anything else ?
what is the best way of overcoming this issue ?
thanks in advance

A: @PostConstruct is by definition the wrong way, because it is only a hint to the bean that it has been constructed and its dependencies have been injected. The bean is now in the pool of EJBs waiting for the first service call. Then it will be connected to the client info of that call. After that call the client info is disconnected again.
I think any kind of standard injection and standard container managed persistence stuff will not work in your case because injection is done exactly once (at EJB creation time) but your case would require injection for each service call/transaction _AND your injection would depend on input data - the client request containing the tenant id.
Also: I hope, you have only up to 6 (or so) tenants due to the maintenance and performance burden of that approach. I have never seen this approach working in the wild.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to listen to the cameraX lens facing changes Does camerax provide api for lens facing changes callback? After switching the lens facing camera I want to be notified when it has finished changing and the camera is ready to use.
Currently I'm using this dependencies of camerax
implementation "androidx.camera:camera-lifecycle:1.0.0-beta01"
implementation "androidx.camera:camera-view:1.0.0-alpha08"
implementation "androidx.camera:camera-extensions:1.0.0-alpha08"

A: Sounds like you need a signal for when the camera starts emitting frames. You can use Camera2Interop and set a CaptureCallback on the preview use case for example. After binding the preview use case using a CameraSelector for the lens facing you want, you can listen for when onCaptureCompleted() is invoked, this should give you a signal that the camera has started.
val builder = Preview.Builder()
Camera2Interop.Extender(builder).setSessionCaptureCallback(object: CameraCaptureSession.CaptureCallback() {
   override fun onCaptureCompleted(session: CameraCaptureSession, request: CaptureRequest, result: TotalCaptureResult) {
      // Camera will start emitting frames
   }
})
val preview = builder.build()


text:
Q: How to implement onClick function with parameters using jquery I have a web-page that can be used to highlight streets in my local area on a street map. The user clicks on the name of the street they are looking for and the street gets highlighted on a map.  See http://www.fastmap.eu for working example.
Each street name is displayed as a button and when the user clicks on the button, 3 variables are stored for use in the map.
Currently, button clicks are handled in html by the onClick function, but it doesn't work on some touch screen devices. So I want to use jQuery .on('click tap', function() instead but don't know how to pass the variables.
The html for each button looks similar to this:-
    <button class="btn" onClick="storeData(value1,value2,value3);location.href='map.html';">Street Name</button>

Previous answers of a similar nature explain how to pass parameters from on script function to another, but not from the html code and don't show how it is implemented in html.

A: If I understand correctly you want something using jQuery.data() For example: you could set different values to the function from the html.
Hope it helps.
See this snippet:

$(document).ready(function() {
    $('#btn').on('click', function (e) {
     alert("Your values are :"+ $(this).data("value"));
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn" data-value="1">Street Name</button>

A: You can get the element (and then its data) by doing something like this:
HTML:
    <button class="btn" data-somedata="whatever">Street</button>

JS:
    $("body").on("click tap", ".btn", function(event) {
      var $target = $(event.target);
      var somedata = $target.data("somedata");
    });

Hope that helps =)

A: HTML button definition:
<button class="btn" id="btn">Street Name</button>

JQuery code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<script language="javascript">
    $(document).ready(function() {
        $('#btn').on('click', storeData);
    });

    function storeData() {
        alert ("here check value1, value2, value3");
        location.href='map.html';
    }
</script>

A: For me, the best answer was given by Elias Nicolas but slightly modified.  Rob Perry's solution looks as though it would work too, but as they say - if its not broke, don't fix it.  SkyMaster's solution didn't explain how I would get the variable from the html code to the javascript - I have hundreds of button's, each with different variables to be passes to the script.  Also, because I have hundreds of buttons, I couldn't use id="btn".  Instead I just used button.
The final solution was as shown below:-

$(document).ready(function() {
    $('button').on('click tap', function (e) {
     alert("Your values are :"+ $(this).data("value1")+","+$(this).data("value2")+","+$(this).data("value3"));
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-value1="1" data-value2="2" data-value3="3">Street Name</button>


text:
Q: Styling an Input Field When I try to alter the CSS for the input field named "title" below, which is classed by "submissionfield", the position changes, but the height, length, and font of the field do not change.
How could I make the height of the input field "title" 22 px, the length 550 px, and the font Times New Roman?  The CSS below does not do it.
Thanks in advance,
John
echo '<form action="http://www...com/.../submit2.php" method="post">
    <input type="hidden" value="'.$_SESSION['loginid'].'" name="uid">

Story Title:

<input name="title" type="title" id="title" maxlength="1000">

Link:

<input name="url" type="url" id="url" maxlength="500">

<input name="submit" type="submit" value="Submit">

</form>
';

The CSS:
.submissiontitle
    {
    position:absolute;
    width:100px;
    left:30px;
    top:200px;
    text-align: left;
    margin-bottom:3px;
    padding:0px;
    font-family:Arial, Helvetica, sans-serif;
    font-size: 12px;
    color:#000000;
    }

.submissionfield
    {
    position:absolute;
    width:550px;
    left:50px;
    top:230px;
    text-align: left;
    margin-bottom:3px;
    padding:0px;
    font-family: "Times New Roman", Times, serif;
    font-size: 22px;
    color:#000000;
    }

.urltitle
    {
    position:absolute;
    width:250px;
    left:30px;
    top:300px;
    text-align: left;
    margin-bottom:3px;
    padding:0px;
    font-family:Arial, Helvetica, sans-serif;
    font-size: 12px;
    color:#000000;
    }

.urlfield
    {
    position:absolute;
    width:550px;
    left:30px;
    top:330px;
    text-align: left;
    margin-bottom:3px;
    padding:0px;
    font-family:Arial, Helvetica, sans-serif;
    font-size: 11px;
    color:#000000;
    }

.submissionbutton
    {
    position:absolute;
    width:250px;
    left:30px;
    top:380px;
    text-align: left;
    margin-bottom:3px;
    padding:0px;
    font-family:Arial, Helvetica, sans-serif;
    font-size: 11px;
    color:#000000;
    }

.submittitle
    {
    position:absolute;
    width:250px;
    left:30px;
    top:150px;
    text-align: left;
    margin-bottom:3px;
    padding:0px;
    font-family:Arial, Helvetica, sans-serif;
    font-size: 12px;
    color:#000000;
    }

A: Use this css:
#title {
  font-family: 'Times New Roman';
  height:22px;
  width:550px;
}

A: You target the div with just .submissionfield. Try .submissionfield input { // stuff } to target the input element within the div with that class.


text:
Q: Selenium: unable to get textbox value I am not able to print the value inside the Quantity textbox (i.e 2) on the java console as this page is using Angular JS.

<input id="a0X63000000WSgtEAGQI" class="input-edit ng-pristine ng-valid ng-not-empty ng-valid-maxlength ng-touched" maxlength="16" min="0" ng-blur="onDblClickQuantityInp(item.Id,item)" ng-keyup="onKeyUpQuantityInp(item.Id,item)" ng-model="item.Bsvp_Quantity__c" placeholder="0.00" valid-number="true" type="text">

How do I get the value?

A: I got the answer. I did not anticipate that getAttribute("value") would get the value inside the textbox. I thought of using the variable instead because value was not inside the HTML tag & made no sense but then I went ahead & found out.
WebElement element = driver.findElement(By.xpath("//div[@id='watchtab']/div/div/table/tbody/tr[1]/td[8]/div/input"));

String value = element.getAttribute("value");
System.out.println(value);

A: Use JavascriptExecutor, like
if(driver instanceof JavascriptExecutor) {
    String s = ((JavascriptExecutor) driver).
     executeScript("return document.getElementById(\"a0X63000000WSgtEAGQI\")
     .getAttribute("value");
    ");
    System.out.println(s);
}

You need to  import org.openqa.selenium.JavascriptExecutor;


text:
Q: Typescript 0.9.5 won't compile .d.ts When I copy my AngularJS code from an existing project into a new project, typescript compiler reports an error for the new project as below:
Error 2 Build: Could not find symbol 'bool'.Scripts\AngularTS\ng\route.d.ts Line 8 Column 26

Yes, I understand that the route.d.ts is old that still uses 'bool' which should be 'boolean'.
But the strange thing is: my existing project does not report the error. (Same computer, same typescript compiler 0.9.5).
I tried to edit route.d.ts (added random chars) in my exisiting project, still no error was reported. It seems that typescript compiler won't compile it!
So my question is why typescript behaved so differently in the two situations?
======== Updated ========
The latest finding is: when there is another error, this error will be reported.
If there is no other errors, then it won't be.
So strange!

A: The bool vs boolean error is actually really a warning. TypeScript will still happily compile your code. You can even 'get away with it' in later versions of the compiler, although the type won't be boolean it will be any.
So it is worth fixing as you will lose proper checking if you don't update to boolean.
var x: bool = true;

if (x === true) {
    alert("Isn't it though");
}

See this on the TypeScript playground.


text:
Q: Show/Hide fields without record types - Lightning We are planning to use record types for the Lead object. For one of these record types we have a layout with several custom fields which show / hide depending on eachothers value. Sample 2 fields:

*

*HasOwnDistributor__c (Boolean)

*DistributorName__c (String)

As you can imagine, the distributor name (2) does not have to be visible if the boolean is set to false (1).
Since we are already using record types, different layouts is not an option anymore. Which options do we have?
We are using the Lightning Experience.

A: This is not possible today to do with any standard layout.
You have 3 options:

*

*Develop your own layout with VisualForce pages or lightning components (really not recommended, but a viable option).

*See this idea: Dependent page layouts and wait until it will be GA.

*See this article: Dependent Page Layouts – Dynamically Hide/Show Form Fields in Lightning Experience and try to use flows in your lightning layouts.


text:
Q: Jquery Mobile : listview remote autocomplete official demo not working I'm implementing a remote autocomplete on a listview (Jquery Mobile 1.4.5) based on the official example : https://demos.jquerymobile.com/1.4.5/listview-autocomplete-remote/ . The official demo is actually not working : if you try it, nothing is displayed when you type a few characters.
As I'm debugging it with my own code, I can see I successfully retrieve remote data and populate the listview (ul) with the expected results (li). The problem seems to be on the 2 last lines of the JS code :
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");

The items (li) are just not displayed in the listview.
No error in the console. But if I display in the console the HTML content of the listview (ul), I see that all li elements have the class "ui-screen-hidden"...
Any idea of what's happening ?
Thanks in advance

A: When You type "cnn" inside Your input, You will get the response records. BUT: inside the response from that "cnn" query, there isn't any record which contains the substring "cnn", so all listitems are filtered out and will be hidden by the framework.
From the documentation:

By default, the text contained in each child is used for filtering

Now, maybe You need to rethink the workflow/usabilty of Your application. Do You really need a filterable?

*

*Maybe You just only need to post the
query and display a nicely formatted list?

*Do You need to filter again the received (already filtered) data-set?

A possible solution could be a custom filter function, or maybe You can set the data-filtertext attribute of the <li> to something like "cnn " + item.code, to avoid the initial filtering.
As You haven't provided inside Your question any information about Your desired workflow, the answer is now up to You.


text:
Q: Connect Python to SQL Server without ODBC Does anyone know a way to connect to a SQL Server database from Python without installing a driver like ODBC? I need to do that on a customer server. I already established a connection from Python to SQL Server via pymssql, but since the project is being discontinued, I am looking for an alternative.
Is it for example possible to link a dll with odbc driver? If yes, where would I get it and how could I link it to Python?

A: as of 2021-08, you can still try with pymssql(https://github.com/pymssql/pymssql)
the project no longer depreciated, is active again.
if using conda, you can install from conda-forge
conda install pymssql
if import pymssql shows error:
libiconv.so.2: cannot open shared object file, you can also install libiconv by condaconda install libiconv
code example:
import pymssql

conn = pymssql.connect(server="127.0.0.1", port="33412", user="reader", password="passwd", database="db_name")
cursor = conn.cursor()
cursor.execute('SELECT TOP 10 * FROM table_name')
data=cursor.fetchall()


text:
Q: System.InvalidOperationException: The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine I am trying to run tests using vstest in Azure DevOps. But getting the below error. Any clue what could have caused the below error?
System.InvalidOperationException: The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine..

A: It seems like a host machine issue(IIS). Please contact support and ask them to fix this.
References:

*

*The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine (server)

*https://www.mikesdotnetting.com/article/280/solved-the-microsoft-ace-oledb-12-0-provider-is-not-registered-on-the-local-mach

A: It seems that you are using hosted agent, you could check this doc about the Microsoft-hosted agent configuration.
Access Engine is not pre-installed in the microsoft-hosted agent, so the microsoft-hosted agent couldn't meet the test requirements. It may cause the error. We could use the power shell task and run the script (New-Object system.data.oledb.oledbenumerator).GetElements() | select SOURCES_NAME, SOURCES_DESCRIPTION to check it.
Microsoft Hosted agent windows-2019

Local machine

The effective way is to install Microsoft Access Database Engine on your local machine or VM, and then you can create a self-hosted agent to run your test that require MS Access Engine.
In this situation, the correct method is that you could create a self-hosted agent and run the test on it.


text:
Q: How to get number of visitors of a page on GAE? I need to get the number of unique visitors(say, for the last 5 minutes) that are currently looking at an article, so I can display that number, and sort the articles by most popular.
ex. Similar to how most forums display 'There are n people viewing this thread'
How can I achieve this on Google App Engine? I am using Python 2.7.
Please try to explain in a simple way because I recently started learning programming and I am working on my first project. I don't have lots of experience. Thank you!

A: Create a counter (property within entity) and increase it transactionally for every page view. If you have more then a few pageviews a second you need to look into sharded counters.

A: There is no way to tell when someone stops viewing a page unless you use Javascript to inform the server when that happens. Forums etc typically assume that someone has stopped viewing a page after n minutes of inactivity, and base their figures on that.
For minimal resource use, I would suggest using memcache exclusively here. If the value gets evicted, the count will be incorrect, but the consequences of that are minimal, and other solutions will use a lot more resources.

A: Did you consider Google Analytics service for getting statistics? Read this article about real-time monitoring using this service. Please note: a special script must be embedded on every page you want to monitor.


text:
Q: What Url goes in $http.get call? I have a simple page that is being served by AngulraJs application. The page has div with a value of Test.

Test

My goal is to read this value from localhost. Basically, I am writing a plugin for an application. This application is a desktop app that has its own web server built in and plugins are written in javascript. My goal is to read the test value. The problem that I am facing though is that I get prevented by CORS.
From everything I have read (and I have been reading a lot), I need to add the Access-Control-Allow-Origin header in order for this to work. What my problem is how do I add a header with angular js for one page only.
I have found the follow SO answer: Set HTTP header for one request
I have also read a lot of documentation such as this: https://docs.angularjs.org/api/ng/service/$http
However, I am still confused with is one thing:
The url that is entered, what should it be in my case? Consider the following example, how would you write it to work for my case if the Angularjs app is sitting on www.somedomain.com and it is being called by javascript code from my localhost machine.
$http.get('what url goes here?', {
    headers: {'Access-Control-Allow-Origin': '*'}
});

I also have a small sub question, with the above example, will I be overriding any of the existing headers or will it only append a new header?
EDIT:
Angularjs code serving back the page:
(function() {
    'use strict';
    angular
        .module('App')
        .controller('Test', Test);

    function Test($scope, $http) {
        var T = this;
        T.test = test;

        function test(){
            return "Test";
        }
    }
})();

HTML

{{T.test()}}

A: The header Access-Control-Allow-Origin must be set on returned header, not request header.
So config your server to return the page 'what url goes here?' to have that header return.
If you have no control over 'what url goes here?' then you have to write a proxy with your web server: webserver get that page content then return to your script.


text:
Q: Looking past someone (expression) I'm looking for an expression (hoping one exists), for when you think someone is nodding, smiling, waving etc. to you, and you respond--but in fact they were addressing someone just behind you.
That's the "three-man version". A "two-man version" could be when Person 1 nods, smiles, waves etc. at Person 2, but P2, assuming P1 is addressing someone else, looks over his/her shoulder to check P3, only to find there's no one there, and they've just snubbed P1.
An example might be the footage of Donald Trump's inauguration. He turns and appears to say something to Melania, who beams at him, and when he turns back, she looks crestfallen. Apparently he was addressing his daughter Ivanka, who was standing just behind Melania. This may be similar to the expression "third wheel" or "fifth wheel", possibly with the verb to pass over, or to overlook? To blank is not quite what this involves. Possible examples:

He turned around and _______ Melania.
He turned around and treated Melania to _______ .

Possibly a phrasal verb.
I think most if not all of us have been there. It needn't be an existing expression; any creative suggestion would be welcome, too.

A: look through TFD
to ignore (a person) deliberately:

Whenever he meets his ex-girlfriend, she looks straight
  through him.

A: I'm sure there ain't no such animal but if it brings clarity, that doesn't seem to me related to any spare wheels nor to passing over, overlooking or even really, looking past; not at all to blanking.
This sounds like a case for a Hollywood-Western verb like mis- or discombobulate linked with something such as identity, intention or direction… which ever-so-vaguely hints at miscombobulentified.
If that wasn't far too creative to be widely understood, it might have the same verb structure as confused.

A:
an expression (hoping one exists), for when you think someone is nodding, smiling, waving etc. to you, and you respond--but in fact they were addressing someone just behind you.

I believe that is called, playing second fiddle.

To Play Second Fiddle: to take a subordinate position. (Familiar - the phrase is used in familiar conversation.)
OPEC will be forced to 'play second fiddle' to the US in 2018, analyst says
I'm really sick of playing second fiddle to this ignoramus...
In an orchestra the [musician] who plays second fiddle is normally junior in both skill and seniority to the lead fiddler. The prestige of the position is therefore lower and less desirable.

But if someone does that to another person, you could say they're demoting  them, which is to reassign someone to a less important role or position:

He turned around and demoted Melania.
He turned around and treated Melania to a demotion.

A: You incidentally used the best word I can think of for this—snub. I might say Trump unintentionally snubbed Melania. I might also say he looked right past her—as literal as that is, it does convey both the literal fact and the emotional weight of what happened.
I think you're right, though—there needs to be an actual term for this phenomenon. I'll bet there are some colloquial ones among small groups of people somewhere, but there really should be some in common use. It happens so often, and is such a meaningful thing, we should have an easy way to refer to it.

A: I'm not 100% certain; however, according to definitions in Merriam-Webster's dictionary (https://www.merriam-webster.com/dictionary/pass and https://www.merriam-webster.com/dictionary/past) it would seem the best word to use in such a phrase is 'passed' in lieu of "past".


text:
Q: Methods of Authentication in Go for App Engine I am building a reservation system in Google App Engine using Go. I need 2 forms of authentication in my program.

*

*Public Form -- form built in Angular that is on our public website. I want my front-end to have some sort of credentials.json file to use when requesting the book and getOpenDates endpoints in my RESTful API running in Go on Google App Engine.

*Private Companion App -- protected by username and password that the user supplies in my app built in Flutter. The app is requesting many endpoints in App Engine. I would like to use JWT to authenticate this portion, but I'm not 100% sure JWT is what I need.

I'm not sure if this tutorial on Identity Platform is what I want. I'm very new to App Engine and authentication in general, so I am a bit lost.
Please describe how I could implement these authentication methods in my RESTful API in Go running on Google's App Engine. I think I may be able to implement the username/password method using a tutorial like this but I'm very lost on the 1st form of authentication with just a credentials file as authentication. If I'm going in the complete wrong direction to accomplish what I want please tell me, but what I'm looking for is code or a tutorial describing how to authenticate using these 2 methods. Thanks for any help.

A: From what I understand, you want to have a golang backend API in App Engine that serves both your web frontend (1.) and your users app (2.).
I am going to suppose that any user with username/password can use both your frontends: the web app and the mobile app with these credentials.
The credentials.jsons are not designed to authenticate users of your services, but rather server to server communication.
With that in mind, I have found the guide Session based authentication in golang, that could help you to set up your backend to accept only authenticated requests over HTTPS. The web browser will automatically save the cookie, however you need to store the cookie in your mobile app.
For much more complicated scenarios for authenticating from different webpages, it is required to use OAuth2 as you can see in this thread. If you don't find any of your requirements listed in here it is probably overkill to use Auth0 nor OAuth2.


text:
Q: Centering wrapper div when two child divs are side by side I know this question has been asked many times but I am having difficulty in finding out in what is going wrong with the code in my case.
I have a wrapper div with a number of other divs contained within it. Some of those divs are side by side using float: left; ect. and the layout is almost exactly as I would like it. However for some reason the wrapper divs border is not extending all the way to the footer element when the wrapper is NOT float: left;
Example:
http://jsfiddle.net/8wVdm/
However when I add float: left to the wrapper div the border does extend all the way like I want it too:
http://jsfiddle.net/C5kTh/
However the problem with this is that the wrapper div is then not automatically centered. How do I fix this?

A: You'll want to research clearfixing, which is a set of css rules that force a container to wrap around any floated elements it contains:
.clearfix:after {
   content: " ";
   visibility: hidden;
   display: block;
   height: 0;
   clear: both;
}

here is a nice detailed answer on how they work.
here's an updated fiddle with a clearfix added.


text:
Q: Prove $\sup(A)\leq\inf(B)$ $A$ and $B$ are two non-empty subsets of the real set.
Given that
$$(x \in A \text{ and } y \in B) \implies x\leq y$$
Show that $\sup A$ and $\inf B$ exists and that $\sup A\leq\inf B$

A: Re your comment: that's almost right. But you have to pick some $y\in B$, which gives an actual upper bound for all $x\in A$.
Notice the assumption that $A,B$ are nonempty: you're not using it. If $B$ is empty then it's true that "for all $y\in B, whatever$". If $B$ is empty, then you have NOT shown that $A$ has an upper bound! (try $A=\Bbb R, B=\emptyset$), so you can't conclude that $\sup A$ exists. It also doesn't exist if $A = \emptyset$, so the nonemptiness of $A$ is essential too.
Once you establish that it does exist, though, the same reasoning shows that $\sup A\le y$ for any $y\in B$. Thus $\sup A$ is a lower bound for $B$, and you can conclude that it is $\le \inf B$.


text:
Q: will git pull auto merge if pulled from _any_ remote? let's say I have the following config file
[branch "master"]
    remote = origin
    merge = refs/heads/master
[remote "origin"]
    url = ssh://origin.com
    fetch = +refs/heads/*:refs/remotes/origin/*
[remote "faraway"]
    url = ssh://faraway.com
    fetch = +refs/heads/*:refs/remotes/faraway/*

if I do git checkout master; git pull origin then:

*

*fetch will run

*merge will merge the fetched branch with my current branch.

If I run git checkout master; git pull faraway, then will git-merge merge anything? After all, I am pulling from a different remote than the configured remote.

A: The remote = origin specifies the default behavior for pull (fetch actually) when you are in the branch. So when you do git pull , the remote is origin ( which is also the default i.e even if the remote was not specified, it would have pulled from origin. If some other remote was specified, that remote would have been fetched.)
And when you do git pull faraway, it will fetch the faraway branches but will not merge ( as faraway is not the configured remote) it in the current branch master, unless you do git pull faraway master

A: git pull non-default-remote will return
You asked to pull from the remote 'production', but did not specify
a branch. Because this is not the default configured remote
for your current branch, you must specify a branch on the command line.

But if I type
git pull non-default-remote `git config remote.non-default-remote.fetch`

then it will automatically merge with whatever is currently checked out on the remote and completely ignore the default merge option since I'm pulling from a non-default remote.


text:
Q: Cursor image not working in IE I have a div with the following css.
.mydiv
{
    cursor: url("/image/cursor-hand.png"), move;
}

Works fine in chrome, Firefox and safari, But doesn't work in IE.
Any help?

A: IE doesn't support normal graphics, you need a cursor file .cur.
See also:

*

*quirksmode.org: compatibility list: Cursor

*MDN: Using URL values for the cursor property


text:
Q: Python: Taking frequencies from a song I'm writing a code for making a light show with 4 bulb, they will switch their combinations according to a song. Therefore, i have to take frequency of a song. I found this code and it is basicly what i want.
# Read in a WAV and find the freq's
import pyaudio
import wave
import numpy as np

chunk = 2024

# open up a wave
wf = wave.open('Audio_3.wav', 'rb')
swidth = wf.getsampwidth()
RATE = wf.getframerate()
# use a Blackman window
window = np.blackman(chunk)
# open stream
p = pyaudio.PyAudio()
stream = p.open(format =
                p.get_format_from_width(wf.getsampwidth()),
                channels = wf.getnchannels(),
                rate = RATE,
                output = True)

# read some data
data = wf.readframes(chunk)
# play stream and find the frequency of each chunk
print(len(data))
print(chunk*swidth)
while len(data) == chunk*swidth:
    # write data out to the audio stream
    stream.write(data)
    # unpack the data and times by the hamming window
    indata = np.array(wave.struct.unpack("%dh"%(len(data)/swidth),\
                                         data))*window
    # Take the fft and square each value
    fftData=abs(np.fft.rfft(indata))**2
    # find the maximum
    which = fftData[1:].argmax() + 1
    # use quadratic interpolation around the max
    if which != len(fftData)-1:
        y0,y1,y2 = np.log(fftData[which-1:which+2:])
        x1 = (y2 - y0) * .5 / (2 * y1 - y2 - y0)
        # find the frequency and output it
        thefreq = (which+x1)*RATE/chunk
        print ("The freq is %f Hz." % (thefreq))
    else:
        thefreq = which*RATE/chunk
        print ("The freq is %f Hz." % (thefreq))
    # read some more data
    data = wf.readframes(chunk)
if data:
    stream.write(data)
stream.close()
p.terminate()

However, the problem is this code just working for basic sounds. When i tried this code for a song while loop is turning false. Is there any code for taking frequency from a song? Or any other way?

A: I think the stereo files were causing trouble, as the data size will ultimately be the sample width * num_samples * num_channels. The following seems to work , giving a consistent 433+-1Hz for a 440Hz tone as generated by audacity (the error either coming from the fft or from audacity's generator)
# Read in a WAV and find the freq's
import pyaudio
import wave
import numpy as np

chunk = 1024

# open up a wave

wf = wave.open('/home/jeremy/Music/wav1.wav', 'rb')
swidth = wf.getsampwidth()
RATE = wf.getframerate()
# use a Blackman window
window = np.blackman(chunk)
# open stream
p = pyaudio.PyAudio()
channels = wf.getnchannels()
stream = p.open(format =
                p.get_format_from_width(wf.getsampwidth()),
                channels = channels,
                rate = RATE,
                output = True)

# read some data
data = wf.readframes(chunk)
# play stream and find the frequency of each chunk
print('switdth {} chunk {} data {} ch {}'.format(swidth,chunk,len(data), channels))
while len(data) == chunk*swidth*channels:
    # write data out to the audio stream
    stream.write(data)
    # unpack the data and times by the hamming window
#    indata = np.array(wave.struct.unpack("%dh"%(len(data)/(swidth)),data))*window
    indata = np.fromstring(data, dtype='int16')
    # deinterleave, select 1 channel
    channel0 = indata[0::channels]

    # Take the fft and square each value
    fftData=abs(np.fft.rfft(indata))**2
    # find the maximum
    which = fftData[1:].argmax() + 1
    # use quadratic interpolation around the max
    if which != len(fftData)-1:
        y0,y1,y2 = np.log(fftData[which-1:which+2:])
        x1 = (y2 - y0) * .5 / (2 * y1 - y2 - y0)
        # find the frequency and output it
        thefreq = (which+x1)*RATE/chunk
        print ("The freq is %f Hz." % (thefreq))
    else:
        thefreq = which*RATE/chunk
        print ("The freq is %f Hz." % (thefreq))
    # read some more data
    data = wf.readframes(chunk)
if data:
    stream.write(data)
stream.close()
p.terminate()


text:
Q: getting control object with Graphics from class instance i dont have much experience with Graphics class in winforms.
i am only in the sketching stage of it (also the code i have added).
my problem is that i am trying to create a panel: clockPanel with some graphics on it, no exception is thrown but the panel (as i can see in the UI) have no graphics on it. tryed to look for examples but i cant find mistakes or something i missed in my code. probably its an easy one for those of you that experienced with graphics.
thank you for your time an consideration.
VB CODE:
adding 'clockpanel' panel to other pannel ('secondaryPannel') via instance to GoalsClock class
Public Class ManagersTab
...
  Public Sub BuiledDashBoard()
...
  Dim p As GoalsClock = New GoalsClock(100, 100, 0.8)
        p.Create()
        p.clockPanel.Location = New Point(200, 100)
        secondaryPannel.Controls.Add(p.clockPanel)
...
  End Sub
...
End Class

Create() method is the most relevant part:
Class GoalsClock

    Private Gclock As Graphics
    Private clockWidth As Int16
    Private clockHeight As Int16
    Private xPos As Int16
    Private yPos As Int16

    Public clockPanel As Panel
    Private panelColor As Color

    Private PercentTextColor As Color
    ' rectangles to store squares
    Protected OuterRect As Rectangle
    Protected InnerRect As Rectangle
    Protected InnerStringBrush As Brush
    Protected InnerStringColor As Color
    Protected InnerStringFontSize As Byte

    ' inner square
    Private InnerSquarePen As Pen
    Private InnerSquarePen_Color As Color
    Private InnerSquarePen_Width As Byte
    ' outer square
    Private OuterSquarePen As Pen
    Private OuterSquarePen_Color As Color
    Private OuterSquarePen_Width As Byte

    Private _PercentOfGoals As Single ' to calculate the goals deg arc
    Public Property PercentOfGoals() As Single
        Get
            Return _PercentOfGoals * 100
        End Get
        Private Set(ByVal value As Single)
            If value <= 1.0F Then
                _PercentOfGoals = value
            Else
                value = 0
            End If
        End Set
    End Property

    Sub New(ByVal clockWidth As Int16, ByVal clockHeight As Int16, ByVal GoalsPercent As Single)
        Me.clockWidth = clockWidth
        Me.clockHeight = clockHeight
        PercentOfGoals = GoalsPercent

        ' values for test
        xPos = 0
        yPos = 0
        InnerStringFontSize = 12
        OuterSquarePen = New Pen(Color.Gray)
        InnerSquarePen = New Pen(Color.Cyan)
        OuterSquarePen_Width = 23
        InnerSquarePen_Width = 15
    End Sub

    ''' <summary>
    '''
    '''  create graphics of the goals clock on clockPanel
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub Create()
        ' panel
        clockPanel = New Panel()
        clockPanel.Size = New Size(clockWidth, clockHeight)
        clockPanel.BackColor = Color.Beige
        Gclock = clockPanel.CreateGraphics()
        ' create outer rectangle
        OuterRect = New Rectangle(xPos, yPos, clockWidth, clockHeight)
        ' create inner rectangle
        Dim w, h, x, y As Integer
        getInnerRectSizeAndLocation(w, h, x, y)
        InnerRect = New Rectangle(x, y, w, h)
        ' draw goals string inside inner rect
        InnerStringBrush = Brushes.Cyan
        Gclock.DrawString(getPercentString(), New Font("ARIAL", InnerStringFontSize, FontStyle.Bold), InnerStringBrush, InnerRect)

        ' create outer square
        OuterSquarePen = New Pen(OuterSquarePen_Color, OuterSquarePen_Width)
        Gclock.DrawArc(OuterSquarePen, OuterRect, 1.0F, 360.0F)

        ' create inner square
        InnerSquarePen = New Pen(InnerSquarePen_Color, InnerSquarePen_Width)
        Dim sweepAngle As Short = getSweepAngleFromGoalsPercent()
        Gclock.DrawArc(InnerSquarePen, OuterRect, -90.0F, sweepAngle)

    End Sub

    Private Sub getInnerRectSizeAndLocation(ByRef w As Integer, ByRef h As Integer, ByRef x As Integer, ByRef y As Integer)
        ' values for test
        w = 40
        h = 40
        x = 64
        y = 65
    End Sub

    Private Function getPercentString() As String
        Return PercentOfGoals.ToString() & "%"
    End Function

    Private Function getSweepAngleFromGoalsPercent() As Single
        ' value for test
        Return 0.0F
    End Function

End Class

A: You must subscribe to the panel's Paint event and perform all drawing there. The AddHandler statement is used to dynamically subscribe to events.
The Graphics class will not store any information about what you draw, so when your panel is redrawn everything you previously drew will be gone unless you draw it again. This is where the Paint event comes into play: it will be raised every time your panel is redrawn, passing an instance of a Graphics class in its PaintEventArgs so you can draw your stuff onto the panel again.
Public Sub Create()
    ' panel
    clockPanel = New Panel()
    clockPanel.Size = New Size(clockWidth, clockHeight)
    clockPanel.BackColor = Color.Beige

    ' subscribe to the panel's paint event
    AddHandler clockPanel.Paint, AddressOf clockPanel_Paint
End Sub

Private Sub clockPanel_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs)
    Dim Gclock As Graphics = e.Graphics 'Local variable only, as the Graphics object might change.
    ' create outer rectangle
    OuterRect = New Rectangle(xPos, yPos, clockWidth, clockHeight)
    ' create inner rectangle
    Dim w, h, x, y As Integer
    getInnerRectSizeAndLocation(w, h, x, y)
    InnerRect = New Rectangle(x, y, w, h)
    ' draw goals string inside inner rect
    InnerStringBrush = Brushes.Cyan
    Gclock.DrawString(getPercentString(), New Font("ARIAL", InnerStringFontSize, FontStyle.Bold), InnerStringBrush, InnerRect)

    ' create outer square
    OuterSquarePen = New Pen(OuterSquarePen_Color, OuterSquarePen_Width)
    Gclock.DrawArc(OuterSquarePen, OuterRect, 1.0F, 360.0F)

    ' create inner square
    InnerSquarePen = New Pen(InnerSquarePen_Color, InnerSquarePen_Width)
    Dim sweepAngle As Short = getSweepAngleFromGoalsPercent()
    Gclock.DrawArc(InnerSquarePen, OuterRect, -90.0F, sweepAngle)
End Sub

As you also might've seen I am constantly redeclaring a new Gclock variable in the Paint event. This is because the Graphics instance used to draw your panel with might change, so you shouldn't store it any longer than the time the Paint event lasts (so I highly recommend you remove the declaration in the top of your class).


text:
Q: What's the simplest way to distribute an RSA public key with software? I'm working on some software that exchanges XML documents with a server. The server signs the XML using XMLDSIG and the client should verify the signature before trusting the XML. I'm using RSACryptoServiceProvider to do this. The XML is signed, but not encrypted.
I'm following the basic procedure explained in:
How to Sign XML Documents with Digital Signatures
How to Verify the Digital Signatures of XML Documents
This requires that the client software has the public key available. I want the distribution of the client software to be as simple as possible and I don't want the client to have to deal with certificates. The pair of documents referenced above conveniently skirt around the subject of distributing the public key, simply stating that the user "needs to have the same key". I don't particularly want the end user to even be aware that they have a public key, so asking them to mess around with certificates is out of the question. Since the public key is public, what I would like to do is somehow embed it within the client software. As I see it, my options are:

*

*Install the public key during the setup process

*Somehow embed the public key into the software itself, possibly within the App.config file

Is this feasible in practice? What is the simplest way of achieving this that doesn't require any user interaction or awareness?

A: You don't have to distribute the certificate. One of common approaches is to include the certificate in the signed document, in the KeyInfo/X509Data node.
The validation can use the embedded certificate easily and the only required infrastructure element at the client side is the certificate thumbprint and subject name. In other words, client validates the document using included certificate and then easily checks the certificate agaist the subject name and thumbprint. In case of a match, there is the assumption that a correct certificate has been provided.
Read more about technical details in one of my blog entries (this is a 3 part tutorial so you can also take a look at all other entries). Anyway, no importing certificates and no including certificates with your software, rather you have two string configuration parameters.
The embedded certificate inside the XmlDsigned document has a const size and usually the overhead is neglectable.
http://www.wiktorzychla.com/2012/12/interoperable-xml-digital-signatures-c.html
http://www.wiktorzychla.com/2012/12/interoperable-xml-digital-signatures-c_20.html

A: Am not sure what problem you're facing without seeing your code but, could this answer from Ji Zhou help?
public static void Main()
 {
     try
     {        //initialze the byte arrays to the public key information.
         byte[] PublicKey = {214,46,220,83,160,73,40,39,201,155,19,202,3,11,191,178,56,
                            74,90,36,248,103,18,144,170,163,145,87,54,61,34,220,222,
                            207,137,149,173,14,92,120,206,222,158,28,40,24,30,16,175,
                            108,128,35,230,118,40,121,113,125,216,130,11,24,90,48,194,
                            240,105,44,76,34,57,249,228,125,80,38,9,136,29,117,207,139,
                            168,181,85,137,126,10,126,242,120,247,121,8,100,12,201,171,
                            38,226,193,180,190,117,177,87,143,242,213,11,44,180,113,93,
                            106,99,179,68,175,211,164,116,64,148,226,254,172,147};

        //Values to store encrypted symmetric keys.
         byte[] EncryptedSymmetricKey;
         byte[] EncryptedSymmetricIV;

        //Create a new instance of RSACryptoServiceProvider.
         RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

        //Get an instance of RSAParameters from ExportParameters function.
         RSAParameters RSAKeyInfo = RSA.ExportParameters(false);

        //Set RSAKeyInfo to the public key values.
         RSAKeyInfo.Modulus = PublicKey;
         //Import key parameters into RSA.
         RSA.ImportParameters(RSAKeyInfo);

        //Create a new instance of the RijndaelManaged class.
         RijndaelManaged RM = new RijndaelManaged();

        //Encrypt the symmetric key and IV.
         EncryptedSymmetricKey = RSA.Encrypt(RM.Key, false);
         EncryptedSymmetricIV = RSA.Encrypt(RM.IV, false);

        Console.WriteLine("RijndaelManaged Key and IV have been encrypted with RSACryptoServiceProvider.");
     }
     catch (CryptographicException e)
     {
         Console.WriteLine(e.Message);
     }
 }


text:
Q: Clarity regarding the use of sample() function in R to set up training and test sets for ML. I am trying to understand this example of the KNN algorithm in R by Datacamp: Machine Learning in R for beginners
I am having trouble understanding how they execute sampling to set up the training and test data sets.
I am able to follow the code till this line:
ind <- sample(2, nrow(iris), replace=TRUE, prob=c(0.67, 0.33))

It is my understanding that this creates a vector of length equal to nrow(iris), with the vector values being either 1 or 2 and the probabilities of these values being chosen being 0.67 and 0.33, respectively.
Thus, we get the following output:
> ind
  [1] 1 1 2 1 2 2 1 2 1 1 1 1 2 2 1 1 1 1 2 2 1 1 1 1 2 1 1 1 1 2 1 2 1 2 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1
 [58] 1 1 1 1 2 1 1 1 2 1 2 1 1 2 1 1 1 1 2 2 1 1 1 2 1 1 1 1 1 1 2 2 1 1 1 1 1 1 2 1 2 1 2 1 1 1 1 1 2 1 2 2 1 2 1 1 1
[115] 1 2 1 1 1 2 1 2 1 1 2 1 1 2 1 2 1 2 1 1 2 1 1 1 1 1 2 1 1 1 2 1 1 2 1 1

In the next step, they create the training set using the following code:
iris.training <- iris [ind==1, 1:4]

This line presumably produces a data frame consisting of all the rows for which ind == 1.
head(iris.training)
   Sepal.Length Sepal.Width Petal.Length Petal.Width
1           5.1         3.5          1.4         0.2
2           4.9         3.0          1.4         0.2
4           4.6         3.1          1.5         0.2
7           4.6         3.4          1.4         0.3
9           4.4         2.9          1.4         0.2
10          4.9         3.1          1.5         0.1

My question is how are the variable ind and the iris data set related. That is, how does R know which lines to pick up (which lines have ind == 1) from the original iris data set, as there seems to be no connection between ind and the iris data set. The only time the iris data set is mentioned when setting up ind is to determine the sample size (number of samples to be chosen) using nrow(iris) in ind <- sample(2, nrow(iris), replace=TRUE, prob=c(0.67, 0.33)).

A:
My question is how are the variable ind and the iris data set related.

They're not, but they needn't be. For example, there is no intrinsic relationship between the numbers 1-5 and the iris dataset, yet
iris[1:5, ]
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1          5.1         3.5          1.4         0.2  setosa
#> 2          4.9         3.0          1.4         0.2  setosa
#> 3          4.7         3.2          1.3         0.2  setosa
#> 4          4.6         3.1          1.5         0.2  setosa
#> 5          5.0         3.6          1.4         0.2  setosa

Created on 2018-08-05 by the reprex package (v0.2.0).
It would be a bit clearer to say ind <- sample(c(TRUE, FALSE), nrow(iris), replace=TRUE, prob=c(0.67, 0.33)) and then iris[ind, ] to emphasize that ind is an index of rows to select rather than the result a comparison of variables within iris.

A: Actually, they are not related. We have created the vector "ind" for the purpose of splitting the given data set into train data set and test dataset without any bias such that the accuracy of the model could be more efficient.
As you know that, we have to split the data set into two parts. but we can't simply split the dataset as iris[1:456] and iris[456: ] as we are ignoring the last species of the iris dataset since the dataset is arranged in order of species attribute.
So we create this "ind" vector to randomly split the dataset such that it contains the data related to all the species in each split proportionally and in the same ratio.


text:
Q: Why do the values in the for loop not correspond to those in Numpys arange and linspace? I simply try to iterate through a sequence, but the values always change slightly, it is only noticeable when you try to save files with the appropriate name. I started with Numpys arange, but since the documentation says that the values can differ if the steps are not integer, I switched to linspace as recommended.
import numpy as np
seq = np.linspace(0.01, 0.09,9)
seq2 = ([])
for i in seq:
    seq2.append(i)

Seq is:  array([0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09])
Seq2 is: [0.01,  0.02,  0.03,  0.04,  0.05, 0.060000000000000005,  0.06999999999999999, 0.08,  0.09]
Could someone explain to me what this issue is about?
Thanks in advance
Im working on Python 3.6.7  and Numpy 1.14

A: TL/DR: Its a display issue with numpy.ndarray displaying things differently - you can customize the printing:
import numpy as np
import sys
np.set_printoptions(precision=20)
seq = np.linspace(0.01, 0.09,9)
print(seq)

[0.01                 0.02                 0.03
 0.04                 0.05                 0.060000000000000005
 0.06999999999999999  0.08                 0.09                ]

See How to pretty-print a numpy.array without scientific notation and with given precision?
You still got floats inside and "Is floating point math broken?" applies:
import numpy as np
seq = np.linspace(0.01, 0.09,9)
seq2 = ([])
for i in seq:
    seq2.append(i)

print(*seq)
print(*seq2)

Output:
0.01 0.02 0.03 0.04 0.05 0.060000000000000005 0.06999999999999999 0.08 0.09
0.01 0.02 0.03 0.04 0.05 0.060000000000000005 0.06999999999999999 0.08 0.09


text:
Q: Issue with testing a Spring app with JUnit: NoSuchBeanDefinitionException raised only in tests I am running into serious issues trying to run JUnit tests with Spring.
Here is my JUnit class configuration:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/META-INF/spring/applicationContext*.xml", "file:src/main/webapp/WEB-INF/spring/webmvc-config.xml" })

In one of the applicationContext*.xml files I do have this:
<beans:bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <beans:property name="basenames">
            <beans:list>
                <beans:value>messagesSecurity</beans:value>
            </beans:list>
        </beans:property>
    </beans:bean>

Please note that my app works fine when I run it from tomcat. It is only when I run the JUnit tests that I get the following NoSuchBeanDefinitionException:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.springframework.context.support.ResourceBundleMessageSource] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:924)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:793)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
    ... 118 more

I am quite baffled by this behavior... Can anyone please advise?

A: I finally found the cause of my problem: I was using a message source class instead of using the interface which caused proxying issues.
Refactoring my app to use the MessageSource interface sorted the problem.
See full conversation here on Spring forum.


text:
Q: SHA-256 certificate pinning isn't working I have a strange problem with certificate pinning.
If I use network-security-config xml with raw certificate it works. But if I switch to sha256 pinning in the same file, it doesn't work o_O

I checked 10 times whether I'm using a correct sha256. Even okhttp certificate pinner (from which I'm migrating to the network-security-config xml) shows me the same sha256, so it's 100% correct.

Does anybody know what is going on? :)

A: From your first answer it is likely your certificate isn't supported by the default root CAs. Test on ssllabs.com/ssltest and see what it says for Android.
As you confirmed, the server isn't sending a complete chain to the root, so the missing intermediate is causing a failure.  Some other clients will download the missing cert in this case, but not Android.


text:
Q: What is this error when doing Plot[ArgMin[Norm[...,p]],...]? When doing
Plot[ArgMin[Norm[x - {-3, -1, 0, 5}, p], x], {p, 1, 3}]

I get this error message:
Plot::exclul: {(Abs[-5+x]^p+Abs[x]^p+Abs[1+x]^p+Abs[3+x]^p)-0,(3+x)-0,(1+x)-0,x-0,(-5+x)-0,
 p-0,Im[Abs[-5+x]^p+Abs[x]^p+Abs[1+x]^p+Abs[3+x]^p]-0}
 must be a list of equalities or real-valued functions.

The plot itself seems to be OK

-- although I am not sure because of this error. What caused it?

A: This is a bug that seems to have been resolved in version 11.1, and is related to the exclusion detection functionality used by Mathematica to detect discontinuities. (The presence of Abs[] in the function being analyzed is what triggered the exclusion detection.)
Since you know that the function is continuous in your range of interest, just add Exclusions -> None:
Plot[ArgMin[Norm[x - {-3, -1, 0, 5}, p], x], {p, 1, 3},
     Exclusions -> None]


text:
Q: Find a string in a huge string file I have to find a list of strings in a txt.file
The file has 200k+ lines
This is my code:
with open(txtfile, 'rU') as csvfile:
    tp = pd.read_csv(csvfile, iterator=True, chunksize=6000, error_bad_lines=False,
                     header=None, skip_blank_lines=True, lineterminator="\n")
    for chunk in tp:
        if string_to_find in chunk:
            print "hurrà"

The problem is that with this code only the first 9k lines are analyzed.
Why?

A: Do you really need to open the file first then use pandas? If it's an option you can just read with pandas then concatenate.
To do that just use read_csv, concat the files, then loop through them.
import pandas as pd

df = pd.read_csv('data.csv', iterator=True, chunksize=6000, error_bad_lines=False,
                 header=None, skip_blank_lines=True)
df = pd.concat(df)

# start the for loop

It depends on your for loop, pandas most likely will have a function that you won't need to loop as it's slower to process large data.


text:
Q: pandas dataframe to numpy array without the annoying dtype="blah blah" I selected several rows of the first column and used both .values and as_matrix() to convert it to numpy array.
x1 = df.iloc[[1,3,4,64,34], 0]

The dimension of the each element in the dataframe is a (3, 3, 5) numpy array. I would like to output a (5, 3, 3, 5) numpy array from the dataframe. However when I use .values, i get a (5, ) shape array with a dtype =unit8 at the end of each element. How can I go about fixing this?

A: df = pd.DataFrame(dict(A=[np.ones((3, 3, 5))] * 5))

A = np.array([a.tolist() for a in df.iloc[[0, 1, 2, 3, 4], 0]])

print(A.shape)

(5, 3, 3, 5)


text:
Q: Cant require object export by index in same folder Here is the example app: https://codesandbox.io/s/gracious-bash-g7gg2
The scenarios:

*

*I CAN call func1 and func2 in exec.js

*I CAN call func2() inside func1() importing in this way: const func2 = require('./func2')

*I CANT call func2 inside func1() importing in this way: const { func2 } = require('./')
Why the same functions import works in exec.js and dont works in /src/func1.js ?
I receive "func2 is not a function"

A: in the last scenario, you are requiring no file at all. It's like getting a function out of tin air.
Also, the syntax const  { func2 } is importing an exported property of an object to a variable through object destructuring. In your case, you are exporting an anonymous function. There is no property func2 to import.
if you wish to import func2 using the const { func2 } = require('./func2'), you need to export that from func2:
module.exports = {
    func2: () => {
        console.log("func2");
    }
}


text:
Q: jsoup - how to select all links which are in paragraph after a specific h3 (which also has an id and a span class) I am trying to get all links (more precise the text of the links) from http://virt10.itu.chalmers.se/index.php/Guard as long as they are under the heading "Relations", "Can Instantiate".

Relations

Can Instantiate

Attention Demanding Gameplay,
Conflicts,
Continuous Goals,
Ownership,
Preventing Goals,
Reconnaissance,
Stimulated Planning,
Trade-Offs

Unfortunately I kind of not understand jsoup (or java). So far I have tried stuff like
Elements contentinstantiate = doc.select("span.mw-headline, h3 ~ a");

for (int i=0; i < contentinstantiate.size(); i++) {
    System.out.println(contentinstantiate.get(i).text());
}

or
Elements links = content.getElementsByTag("a");

for (Element link : links) {
    String linkHref = link.attr("title");
    System.out.println(linkHref);
    String linkText = link.text();
    System.out.println(linkText);
}

But both don't work and I am at kind of a loss here. Can anyone help me?

A: you select h3 and h3 don't have any a tag. i think you must selected p tag

A: Jsoup next sibling API will help you. You need to select the

Relations

Then you need to iterate to the next element which will be h3.

Can Instantiate

Then you will go to next sibling and you will check for paragraph node
Once your paragraph node is selected extracting links would be easy
For example H2 next sibling node is H3 and H3 next sibling node is

Every Jsoup node has below method
public Node nextSibling()

Which will iterate it to next sibling
You can read it at Jsoup doc

A: try this it's work for me
code :
final String url = "http://virt10.itu.chalmers.se/index.php/Guard";
         Document doc = Jsoup.connect(url).get();
         Element contentinstantiate = doc.getElementById("Can_Instantiate").parent().nextElementSibling();
         for(Element e : contentinstantiate.getAllElements()){
             System.out.println(e.text());
         }

output :
Attention Demanding Gameplay, Conflicts, Continuous Goals, Ownership, Preventing Goals, Reconnaissance, Stimulated Planning, Trade-Offs
Attention Demanding Gameplay
Conflicts
Continuous Goals
Ownership
Preventing Goals
Reconnaissance
Stimulated Planning
Trade-Offs

A: import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class StackOverflow50897294 {
    public static void main(String[] args) throws IOException {
        Document doc = Jsoup.connect("http://virt10.itu.chalmers.se/index.php/Guard").get();
        Elements links = doc.selectFirst("h3 > span[id=\"Can_Instantiate\"]").parent().nextElementSibling().select("a");
        for (Element link : links) {
            System.out.println(link.text());
        }
    }
}

A: Use this CSS Selector:
#mw-content-text > p:nth-child(18) > a

Here is the code snippet to get the text of the titles.
import java.io.IOException;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class Test {

    public static void main(String[] args) {

        try {

            Document doc = Jsoup.connect("http://virt10.itu.chalmers.se/index.php/Guard").get();
            List<String> titles = doc.select("#mw-content-text > p:nth-child(18) > a").eachText();

            for (String title : titles) {
                System.out.println(title);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Click here for a quick review.


text:
Q: Kindle books on another iCloud account If I add another iCloud account to my iPhone, will I be able to access my kindle books on that iCloud account?

A: The login information is discrete for Amazon Kindle and Apple iCloud. You may need to re-login to your Kindle account, but the iCloud account shouldn't effect it any other way.


text:
Q: Effect of using std::stringbuf for buffering while performing a write via insertion operator '<<' I am trying to benchmark the effects of manual buffering (via std::stringbuf) on the running time while performing a write to a file as opposed to buffering done by the insertion operator <<.
Version 1 (without manual buffering)
This version involves performing a write at each iteration.
std::ofstream ofs;
ofs.open("output_file", std::ios::out);

for (int i = 0; i < 100000000; i++)
  ofs << "Hello world!\n";

Time: 2.83s user 1.14s system 28% cpu 13.918 total
Version 2 (with manual buffering)
This version buffers the entire data in std::string object before finally writing it.
std::string buffer;
std::ofstream ofs;
ofs.open("output_file", std::ios::out);

for (int i = 0; i < 100000000; i++)
  buffer.append("Hello world!\n");

ofs << buffer;

Time: 1.87s user 2.27s system 24% cpu 16.654 total
There is an observable difference between the running times of version 1 and 2, and similar behavior was observed in different runs. How is it the case that the second version ends up being slower when it only performs a single write operation as opposed to multiple writes in first ?
This result is also in contrast with the results posted in a previous question, however the current case is a slight variation of that.

A: It doesn't "only perform a single write operation"; you are not considering the cost of building up that string, which is not zero.
You may find that a buffer.reserve(100000000 * strlen("Hello world!\n")) helps things a little.


text:
Q: Python: How can I read till ETX (End of Text) Hex 03 in a file? I have a file with multiple lines and right now I read 20480 bytes at once:
while True:
    data = fh.read(20480)
    if data == '':
        fh.close()
        break

I have another file where ETX is used as the delimiter. How do I read characters till ETX is reached?
Thanks in advance!

A: Assuming that you want to read multiple records, each delimited by ASCII 3, then the myreadlines function in this answer will do the trick.
The only difference is using the character with value 3 as the delimiter, instead of period, like this:
delim = chr(3)
with open('file') as f:
 for line in myreadlines(f, delim):
  print line


text:
Q: Как пишется дополнение к ТЗ? Допустим у меня есть раздел 2, и пункт 2.3. Требования к СУБД и там будут пункты:

*

*а) СУБД должна быть быстрой;

*б) СУБД должна иметь возможность резервного копирования и восстановления данных;

*в) СУБД должна ставиться на Linux;

Прошел год. И заказчик захотел модернизировать систему. И написал еще требования. Одно из них пусть будет "СУБД должна быть бесплатной". И потребовал все требования и дополнения оформить в виде дополнения к старом ТЗ.
В ГОСТ сказано:

3.6. Титульный лист дополнения к ТЗ на АС оформляют аналогично титульному
листу технического задания. Вместо наименования «Техническое задание» пишут
«Дополнение № ... к ТЗ на АС … ».
3.7. На последующих листах дополнения к ТЗ на АС помещают основание для
изменения, содержание изменения и ссылки на документы, в соответствии с которыми
вносятся эти изменения.
3.8. При изложении текста дополнения к ТЗ следует указывать номера
соответствующих пунктов, подпунктов, таблиц основного ТЗ на АС и т.п. и применять
слова: «заменить», «дополнить», «исключить», «изложить в новой редакции».

Но тут всё не понятно.
Я пишу дополнение так:
Раздел 2. Пункт 2.3.
Дополнить: г) СУБД должна быть бесплатной
Или я переписываю весь (под)пункт полностью? Т.е:
2.3. Требования к СУБД

*

*а) СУБД должна быть быстрой;

*б) СУБД должна иметь возможность резервного копирования и восстановления данных;

*в) СУБД должна ставиться на Linux;

*г) СУБД должна быть бесплатной

A: Исходя из цитаты из ГОСТа, правильнее

Раздел 2. Пункт 2.3. Дополнить: г) СУБД должна быть бесплатной

Да и исходя из здравого смысла тоже, если вы пишете дополнение, то должно быть сразу ясно, что именно изменилось. Как вариант можно (наверное) написать так:

Раздел 2. Пункт 2.3. Дополнить: г) СУБД должна быть бесплатной
Таким образом:

*

*2.3. Требования к СУБД

*а) СУБД должна быть быстрой;

*б) СУБД должна иметь возможность резервного копирования и восстановления данных;

*в) СУБД должна ставиться на Linux;

*г) СУБД должна быть бесплатной


text:
Q: Regex Search with delimiters in and Mysql I'm trying to convert a regex that works fine in PHP to MySQL.
MySQL does not allow negative look-ahead (?!) so I need a solution or a workaround
My DB column data is a string like this:

title:The Book Title¬#¬description:The Book Description¬#¬Price:$10.57

The regex I can use in PHP would be

(^|¬#¬)title:(((?!¬#¬).)*Book((?!¬#¬).)*)

but in MySQL I'm struggling. Anybody have any advice or suggestions

A: MySQL doesn't have a way to apply a REGEX to col's content in SELECT clause.
You may use SUBSTRING function to extract your content in this case.
SELECT
      SUBSTRING_INDEX(
        LEFT( content, LOCATE('?#?description', content)-1 ), 'title:', -1) AS title,
      SUBSTRING_INDEX(
        LEFT( content, LOCATE('?#?Price', content)-1 ), 'description:', -1) AS description,
      SUBSTRING_INDEX(
        RIGHT( content, LOCATE('?#?Price', content)-1 ), 'Price:', -1) AS price
FROM test_table

SQLFiddle
http://sqlfiddle.com/#!2/04e83/1

A: The solution was simple once I thought about splitting it like nhahtdh suggested.
select
  SUBSTRING_INDEX(SUBSTR(table.data, LOCATE('title:', table.data)+6), '¬#¬', 1) regexp '[[:<:]]Book[[:>:]]' AS hasResult
from
  table;


text:
Q: Sharepoint List Exported to Excel - Columns are readonly From a sharepoint list, I chose Actions -> Export to Spreadsheet, saved the owssvr.iqy file, opened this file, and tried editing entries in Excel.
When I try to edit any columns, I am shown: "The xxxx column is a read-only column that cannot be modified."
I did a Google, which suggested a couple of ideas:

*

*One link suggested using sysinternal's ProcMon to see what is happening. However, I didn't see the registry entries it suggested I should see.

*Another link suggested it could be something blocking an 'OPTIONS' request to the sharepoint server?

*Another link suggested it could be because I have SP3 of Excel 2003?

*Another link suggested checking the registry entries for HKCU\Software\Microsoft\Office\11.0\Common\Internet\Server Cache, but these entries looked OK?

    [HKEY_CURRENT_USER\Software\Microsoft\Office\11.0\Common\Internet\Server Cache\https://xxxx.o2.com/sites/xxxx/]
    "Type"=dword:00000005
    "Protocol"=dword:00000003
    "Expiration"=hex(b):30,CD,6b,8a,c6,6a,ca,01

Has anyone else seen this, and found a way around this?

A: I've always run into problems when dealing with the owssvr.iqy file.  I'm not really sure what the file is (something related to a query to sharepoint I think) but it's not really what you want to save.  When exporting to a spreadsheet I do the following (Excel 2007):

*

*Actions -> Export to Spreadsheet

*Open (opposed to Save)

*Click 'enable' when prompted by the security warning

*At this point you should have an Excel spreadsheet with the data from your list.  Save this spreadsheet.

This will create a linked spreadsheet.  You can update the data in your spreadsheet with the sharepoint server by clicking on options->refresh all.

A: Hotfix kb952608 seems to solve the problem according to:

http://www.tekrum.net/excel-2003-sharepoint-list-read-only-column-problem

A: After clicking Open you need to go to the Properties dialog and then uncheck the Save Query check box.
This would make your column editable.


text:
Q: Getting passwords error on Helm upgrade for Airflow I am getting the following error on installing a custom docker image as a revision. I am not able to figure out the reason. So far I have tried adding secrets with the password and it didn't work
helm upgrade --install airflow apache-airflow/airflow -n airflow -f values.yaml --debug
history.go:56: [debug] getting history for release airflow
upgrade.go:144: [debug] preparing upgrade for airflow
Error: UPGRADE FAILED: execution error at (airflow/charts/postgresql/templates/secrets.yaml:20:15):
PASSWORDS ERROR: The secret "airflow-postgresql" does not contain the key "password"


text:
Q: parsing vmstat python code explained I found some python code to parse the output of the linux command 'vmstat' below.
vmstat | python -c 'import sys; print dict(zip(*map(str.split, sys.stdin)[-2:])).get("cache")'

vmstat
procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa
11  0 385372 101696  61704 650716    0    1     5     9    6   12  5  2 92  0

I was wondering if somebody could explain to me what the code is doing particularly the (zip(*map(str.split, sys.stdin)[-2:]) part?
Thank you

A: That's some clever code, but a bit too clever.
Let's decompose :
    dict(zip(*map(str.split, sys.stdin)[-2:]))
The first operation is going to be:
    map(str.split, sys.stdin)
Map apply the function given as its first parameter to each element of the iterable of its second parameter. (If the second parameter is not an iterable, it will be casted as one to give an iterable result).
E.g., here :
>>> map (int, ["1", "2", "3"])
[1, 2, 3]

>>> (int, "1")
[1]

So here, this first expression can be read as : "apply str.split on the standard input" (sys.stdin).
The result of this first operation is easy to examine:
vmstat | python -c 'import sys; print (map(str.split, sys.stdin))'

[['procs', '-----------memory----------', '---swap--', '-----io----', '-system--', '----cpu----'], ['r', 'b', 'swpd', 'free', 'buff', 'cache', 'si', 'so', 'bi', 'bo', 'in', 'cs', 'us', 'sy', 'id', 'wa'], ['1', '0', '490952', '155924', '437356', '2064528', '0', '0', '3', '59', '0', '1', '6', '1', '91', '2']]

The standard input was an array of 3 lines. Each line was split with the default split operation, so each element is nicely parsed. Now, we don't need the first line, so we want only the two last line of the array, hence the [-2:]. Once again, this is classic python :
>>> a = [1,2,3,4]
>>> a[-2:]
[3,4]

So we have a list of list of size 2. The first list is the line with the keys, the second list is the line with corresponding values. This looks like a dictionary, doesn't it ? But it's not one yet. We need dict, for this.
Dict is a type which has a few constructors, one of those being :
 help(dict)
 [...]
 |  dict(mapping) -> new dictionary initialized from a mapping object's
 |      (key, value) pairs
 [...]

So that if I input :
 dict([('name', 'john'), ('profession', 'computer scientist')])

I get:
 {'name': 'john', 'profession': 'computer scientist'}

But we do not have a list of tuples [(key, value)], we have a list of lists [[key, key, key...], [value, value, value...]].
One way of getting a list of tuples is to use the zip function.
>>> k = ['key1', 'key2', 'key3']
>>> v = ['value1', 'value2', 'value3']
>>> zip(k,v)
[('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')]

And the result of zip is something we can use to build a dict !
But we do not have two separate iterators k and v, here. We only have a list of lists ! So there is another trick at play here : passing arguments as a list. This is documented here :
https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists
The idea is that if you have a function that takes x arguments, you can give them explicitely, like this :
def fun(a,b):
   return a + b

fun(2,3)

But you can also call them with a list, using the * syntax, like this :
fun(*[2,3])

The "*" sign means : "Unpack everything from the list to each argument". Note that if I do :
fun(*[2,3,4])

It will fail, just as if I tried :
fun(2,3,4)

Because fun only wants 2 arguments. So here, our list [[key, key...], [value, value]] will be given to zip unpacked, so the real call is zip([key, key...], [value, value...])... which give us exacty what we want, a dictionary. On this dictionary, we simply get the value with the key "cache". And we're done.
This one-liner is clever, but not pleasant to read, though. HuStmpHrrr provides a much better way of doing this in the comment under the question.


text:
Q: ListProperty of db.Key vs Many-to-Many in App Engine (Specific Case) I've seen examples with similar question. But, please allow me to ask more specific questions that I want to confirm my understanding.
My questions:

*

*For ListProperty of db.Key, if I can anticipate the maximum number of keys I want to store, how many should I NOT exceed for storing in ListProperty of db.Key as compared to ReferencedProperty ? [General Question] because it wasn't very clear where App Engine page says this,

Another more important one is that you want to avoid storing overly
  large lists of keys in a ListProperty

*Let's say, there are users who can follow restaurant's activity feeds. Hence, User can add as many restaurants as they want to their favourite list. There are User model and Restaurant model. So, I believe any user would not follow more than 30 restaurants ? which makes it the ListProperty of db.Key as the ideal solution?

A: The considerations here are somewhat fuzzy -- there is no hard limit, except that the total (encoded) entity must not be larger than 1 MB.  30 keys is totally fine.  100 would still be fine.  At 500-1000 I'd start worrying.  At 10,000 you'll probably exceed the 1 MB limit.
Another consideration is that if you expect to add keys to the list one at a time (each time reading and writing the entity) you end up in O(N**2) land, which would make your updates start crawling really slowly, probably somewhere between 100 and 1000 keys.
These considerations are the same for all ListProperties -- keys are not special (the quote you gave just happens to come from an article that focuses on ListProperty(db.key)).


text:
Q: Is there a way to get ℔ (U+2114) without china2e in LuaLaTeX? I'd like to use ℔ in LuaLaTeX. Unfortunately it seems none of the most commonly used fonts and china2e from 1997 - the only package I found which supposedly supports this symbol - isn't even available in the latest TeXlive distro.
\documentclass{scrartcl}
\usepackage{microtype}

\begin{document}
   L B bar = U+2114 = ℔
\end{document}

When using TeX Gyre Bonum as main font via fontspec, I get the following error:
Gives: Missing character: There is no ℔ (U+2114) in font TeXGyreBonum:mode=node;language=dflt;+tlig;!

Now I am left with two options (I think, please correct me if there are more):

*

*find a way to make use of a 23 year old package (china2e)

*find a font which supports this exact symbol

How can I achieve either (I am leaning toward the second option, however)?

A: You can use fontspec's fallback mechanism in LuaTeX to merge multiple fonts together. When a character is missing, it will automatically search this character in Noto Sans, where this character is present. You can set up more fallback fonts as well. In this way, you do not have to change the main font of your document.
\documentclass{scrartcl}
\usepackage{fontspec}
\usepackage{microtype}

\directlua{luaotfload.add_fallback("genericfallback",
    {
      "NotoSans:mode=node;"
    })
}

\setmainfont{TeX Gyre Bonum}[RawFeature={fallback=genericfallback}]

\begin{document}
    the brown fox jumped over the lazy dog ℔
\end{document}

A: Using the new tool  in texlive albatross on the command with
albatross 0x2114

gives me quite a number of fonts on my system which has it. Including for example dejavu which is also in texlive:
\documentclass{scrartcl}
\usepackage{microtype}
\usepackage{fontspec}
\setmainfont{dejavusans}
\begin{document}
   L B bar = U+2114 = ℔
\end{document}

A: You can take the symbol from any font that contains it.  A good method of doing this that does not change the main font is to set the character active with \newunicodechar.
\documentclass{article}
\tracinglostchars=2
\usepackage{fontspec}
\usepackage{newcomputermodern}
\usepackage{newunicodechar}

\newfontfamily\symbolfont{Junicode}[Scale=MatchUppercase]

\newcommand\lbbar{{\symbolfont\symbol{"2114}}}
\newunicodechar{^^^^2114}{\lbbar} % ℔

\begin{document}
lb ℔
\end{document}

Free fonts that contain this glyph include: Cardo, Code2000, DejaVu Sans, Everson Mono, FreeSerif, FreeSans, Junicode, Linux Libertine, Noto Sans, Noto Serif and Symbola.  The Noto fonts are especially useful, since they come in many widths and weights, so it's likely that at least one of them will match your other fonts.


text:
Q: Missing Push Notification Entitlement iOS App Submission (I don't use it) So I submitted a very basic app to the app store and I got this response:

Missing Push Notification Entitlement - Your app appears to include
  API used to register with the Apple Push Notification service, but the
  app signature's entitlements do not include the "aps-environment"
  entitlement. If your app uses the Apple Push Notification service,
  make sure your App ID is enabled for Push Notification in the
  Provisioning Portal, and resubmit after signing your app with a
  Distribution provisioning profile that includes the "aps-environment"
  entitlement. See "Provisioning and Development" in the Local and Push
  Notification Programming Guide for more information. If your app does
  not use the Apple Push Notification service, no action is required.
  You may remove the API from future submissions to stop this warning.
  If you use a third-party framework, you may need to contact the
  developer for information on removing the API.

I have seen a lot of questions on here about this and how to ADD it, but I haven't seen anything (maybe I missed it) about if I don't even use it.  There's nothing in my app or when I submitted it mentioning push notifications.  The message says "no action is required" and that the submission was successful, and then I got an email soon after saying the app was submitted and was under review.
I just want to clarify that I really don't have to do anything?  It's my first submission and I don't want to assume I can just wait for approval/decline when this message they sent me is implying that I need to do something.  Thanks.

A: It appears that Apple has false positive.
If such is the case, this question has been answered here:
How to remove push notification API
If so, this question is a duplicate.


text:
Q: Take ScreenShot without Window I've been studying Son Of Grab Apple demo and I'm really struggling to get a screenshot of screen without any window (only desktop, dock and menu bar). Does anyone knows how to do so?

A: Here's some example code which takes a screenshot with just the desktop.
CFArrayRef onScreenWindows = CGWindowListCreate(kCGWindowListOptionOnScreenOnly, kCGNullWindowID);
CFArrayRef nonDesktopElements = CGWindowListCreate(kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements, kCGNullWindowID);
CFRange range = CFRangeMake(0, CFArrayGetCount(nonDesktopElements));
CFMutableArrayRef desktopElements = CFArrayCreateMutableCopy(NULL, 0, onScreenWindows);
for (int i = CFArrayGetCount(desktopElements) - 1; i >= 0; i--)
{
    CGWindowID window = (CGWindowID)(uintptr_t)CFArrayGetValueAtIndex(desktopElements, i);
    if (CFArrayContainsValue(nonDesktopElements, range, (void*)(uintptr_t)window))
        CFArrayRemoveValueAtIndex(desktopElements, i);
}

CGImageRef cgimage = CGWindowListCreateImageFromArray(CGRectInfinite, desktopElements, kCGWindowListOptionAll);
NSBitmapImageRep* rep = [[NSBitmapImageRep alloc] initWithCGImage:cgimage];
NSData* data = [rep representationUsingType:NSPNGFileType properties:[NSDictionary dictionary]];
[data writeToFile:@"/tmp/foo.png" atomically:YES];

You should be able to extend the general approach to grab the Dock and menu bar. You construct a list of window IDs that you're interested in and then call CGWindowListCreateImageFromArray(). I compute the window IDs of the desktop elements by asking for all on-screen windows and then all on-screen windows excluding the desktop elements. The desktop elements are those in the first list which aren't in the second list.
Getting the window IDs for the menu bar and Dock is not quite as direct as that because there's no option in the CGWindowList API that directly corresponds to that.  You'll need to get the array of description dictionaries for the on-screen windows using either CGWindowListCopyWindowInfo() or CGWindowListCreateDescriptionFromArray() and examine the contents. The most useful key will probably be kCGWindowLayer. In addition to the desktop elements obtained using the technique in my sample code, I think you'll want anything at CGWindowLevelForKey(kCGDockWindowLevelKey) and greater.


text:
Q: Hide Element on Scrolling in Reactjs? I have a div that has scrolling enabled for that div. I have some elements in it, when the user starts to scroll I want an element to disappear and when scrolling stops I want it to show up again.
How can I do this

Hide me on scrolling

Always show

.container{
    flex: 1 1 80%;
    display: flex;
    flex-wrap: wrap;
    width: calc(100vw - 110px);
    height: calc(100vh - 75px);
    overflow-y: auto;
    min-width: 500px;
    display: flex;
    justify-content: center;
    z-index: 1;
}

A: There is not real scrolling state in the browser; the scrolling event occurs, and then it's done.
You could set a piece of state called e.g. isScrolling to true when the scrolling event occurs, and then set a timeout to set it back to false after the last time it was scrolled.
Example

class App extends React.Component {
  timeout = null;
  state = {
    isScrolling: false
  };

  componentDidMount() {
    window.addEventListener("scroll", this.onScroll);
  }

  componentWillUnmount() {
    window.removeEventListener("scroll", this.onScroll);
  }

  onScroll = () => {
    this.setState({ isScrolling: true });

    clearTimeout(this.timeout);

    this.timeout = setTimeout(() => {
      this.setState({ isScrolling: false });
    }, 200);
  };

  render() {
    return (

          {this.state.isScrolling ? "Hidden" : "Shown"}

    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

A: A different approach:
import React,{ Component } from 'react';
    class ScrollHide extends Component {

      constructor(props) {
        super(props);
       this.state = {
        opacity: '1'
      }
    }

      componentDidMount() {
        if (typeof window !== "undefined") {
          window.onscroll = () => {
            const currentScrollPos = window.pageYOffset;
            const maxScroll = document.body.scrollHeight - window.innerHeight;
            // console.log(maxScroll)
            if (currentScrollPos > 0 && currentScrollPos < maxScroll) {
              this.setState({ opacity: "0" })
              // console.log(currentScrollPos)
            } else {
              this.setState({ opacity: "1" })
            }
          }
        }
      }

      render() {
        return (
            <>
            <div  style={{ opacity: `${this.state.opacity}`}} >
             {/* additonal content */}TestView

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent nec felis eu nisl varius gravida eget nec libero. Nulla tristique varius semper. Pellentesque euismod, justo eu rutrum congue, turpis libero placerat lorem, vel accumsan felis enim et enim. Nunc facilisis lectus ac mi iaculis imperdiet. ....add more content here...

    </>
        )
      }
    }

    export default ScrollHide


text:
Q: Wait for completion of threadpool tasks using Phaser I want to return from my executeTasks() method only after all the tasks submitted to the threadpool are finished. Please note that my thread pool has configurable threadpoolsize and uses SynchronousQueue as the backing queue, so my for loop proceeds safely by submitting a task only if a thread is available. So, I just want to wait for the final tasks. I am using Phaser for this.
I've created a Phaser with 1 registered party i.e., the current thread and I register a new party to the Phaser before submitting a task to the threadpool, when the task finishes I deregister the task party. When for loop finishes by submitting the final tasks, I am hoping that my arriveAndAwaitAdvance() will wait for registered parties to arrive but it will only discover that all those parties are deregistered after some time and then move forward and return from my method.
I think that this will solve my problem. Please let me know if I am wrong or if there is any other better way to do this. Countdownlatch is not going to help as my threadpoolsize is configurable. I know that having a counter and monitor will solve this problem but I want out-of-the-box solution like Phaser.
private void executeTasks(TheadPoolExecutor threadPool, Iterator<String> it) {
    final Phaser phaser = new Phaser(1);

    for (final String id : IteratorUtils.iterable(it)) {
        phaser.register();
        threadPool.execute(() -> {
        // phaser.arrive();
            try {
                thread.sleep(10000 * id.length());
            } finally {
                phaser.arriveAndDeregister();
            }
        });
    }
    phaser.arriveAndAwaitAdvance();
    phaser.arriveAndDeregister();
}

A: I never used a  Phaser before but I think a CountDownLatch is the better way to handle this task.
A  CountDownLatch is a synchronization barier that allows one or more threads to wait until a set of operations being performed in other threads completes.
2 methods are useful when using a CountDownLatch :

*

*countDown that decrements the counter when a task is finish.

*await is for the current thread (main for instance) to wait the others to complete.

*
private void executeTasks(TheadPoolExecutor threadPool, Iterator<String> it) {
    final CountDownLatch countDownLatch = new CountDownLatch(threadPool.getPoolSize());

    for (final String id : IteratorUtils.iterable(it)) {
        threadPool.execute(() -> {
            try {
                thread.sleep(10000 * id.length());
                countDownLatch.countDown();
            } catch (InterruptedException ex) {}
        });
    }
    countDownLatch.await();
  }

Here the CountDownLatch is initialized with  the number of threads in the threadpool.


text:
Q: decode snappy messages using Bigtable cbt I have some data in bigtable, but the messages are all snappy encoded. Does anyone know a way to decode it?
cbt -project project-1 -instance test read events count=10 prefix=test123

This gives me output but its snappy encoded


text:
Q: Disable magic mouse back-forward gesture only in XCODE Is it possible to disable magic mouse back-forward gesture only in XCODE?
While in browser it is fine, in XCODE it just totaly unwanted feature for me.

A: In short: disable it on the mouse:
defaults write com.apple.dt.Xcode AppleEnableMouseSwipeNavigateWithScrolls -bool NO
for trackpads use:
defaults write com.apple.dt.Xcode AppleEnableSwipeNavigateWithScrolls -bool NO
Source: [https://stackoverflow.com/questions/20024231/prevent-disable-xcode-scroll-navigation]


text:
Q: Fill NSOutlineView with two dimensional array data This has been buggering me for some time now, and I really need to know or this is even possible. And what maybe is the proper approach.
I have a view-based NSOutlineView with two columns, another class is taking care of the data parsing. The data-parsing class is returning a two-dimensional NSMutableArray. I want fill the first column with the data of the array with index foo[index][0] and the second column with the data at index foo[index][1]
Up to now I only managed to get the NSOutlineView to display the correct data at the first column, I have no clue how to accomplish filling the second column with my data. The NSOutlineView and NSOutlineViewDataSource -delegates look like this:
- (NSInteger)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item {
    return foo.count; // works fine
}

- (BOOL) outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item {
    return FALSE;
}

- (id) outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item {
    return !item ? [[foo objectAtIndex:index] objectAtIndex:0] : 0;
}

    - (id) outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item {
                   if ([[tableColumn identifier] isEqualToString:@"column1"]) {
                return item; // Correct data
            }

                if ([[tableColumn identifier] isEqualToString:@"column2"]) {
               return // Here i want the data for column 2
            }
}

So I guess what is needed is that the delegate - (id) outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item {} needs to be build in such a way that item already consists of all the 2 dimensional data? But how to accomplish this? Is there a way to also return item with the data as followed when the second column needs to be filled?
[[foo objectAtIndex:index] objectAtIndex:1];

Any help is appreciated.


text:
Q: Loading XML into memory I want to read an XML file into memory as a tree of nodes, on which I could perform further operations. Something like C#'s XDocument. What is the Java equivalent of C#'s XDocument.Load?

A: You're looking for the Java XML DOM classes, which are part of JAXP. It's much uglier than in C#.

*

*A DocumentBuilderFactory creates...

*A DocumentBuilder which creates...

*A Document which is what you're really after.

An excellent reference for all this: the JAXP Tutorial, Chapter 3: The Document Object Model.


text:
Q: Limit of expected value of reciprocal of $\chi^2_k$ for $k \to \infty$ I must figure out $\lim_{k \to \infty} \mathbb{E}\left[ W_k  \right]$ for
$$    W_k  =  \frac{1}{a+b \cdot\chi^2_k} \qquad a,b \in \mathbb{R}_+$$
where $\chi^2_k $ indicates a chi-squared random variable with $k$ degrees of freedom.
I know that $X = \lim_{n \to \infty} \chi^2_k \sim \mathcal{N}(0,1)$ but in the limit $\mathbb{E}\left[ \frac{1}{X}  \right]$ does not converge. Any idea of how to obtain the limit of the expectation $\lim_{k \to \infty} \mathbb{E}\left[ W_k  \right]$ analytically?
Many thanks

A: Let $(Y_i)_{i\geqslant 1}$ be a sequence of independent standard normal random variables. We know that for each $k$, $W_k$ has the same distribution as
$$
W'_k=\frac{1}{a+b\sum_{i=1}^kY_i^2}
$$
hence we are looking for
$$
\lim_{k\to\infty}\mathbb E\left[\frac{1}{a+b\sum_{i=1}^kY_i^2}\right].
$$
We can apply the reversed monotone convergence theorem, since $(W'_k)_{k\geqslant 1}$ is non-increasing and $W'_1$ is integrable. The strong law of large numbers shows that $W'_k\to 0$ almost surely hence $\mathbb E[W_n]\to 0$.


text:
Q: subquery returns more than 1 value this is not permitted when the subquery follows I don't know why my case code is having an error but when I execute it not using a parameter by replacing the @PersonId by 2 it runs well. I try to exchange2x the JOIN but I am still having an error. Anyone knows?.
case    when ISNULL(dbo.EducationalBackground.SchoolId,'') = '' then
                (Select a.SchoolName
                    from dbo.EducationalBackground as A INNER JOIN
                        dbo.PersonEducationalBackground as B on a.EducationalBackgroundId = b.EducationalBackgroundId  INNER JOIN
                        dbo.EducationLevel as C on a.EducationalLevelId = c.EducationLevelId
                        where b.PersonId = @PersonId and a.EducationalLevelId in (2,3))

       else (select dbo.school.SchooldName from dbo.School INNER JOIN dbo.EducationalBackground
            ON dbo.School.SchoolId = dbo.EducationalBackground.SchoolId INNER JOIN
            dbo.PersonEducationalBackground ON dbo.EducationalBackground.EducationalBackgroundId = dbo.PersonEducationalBackground.EducationalBackgroundId
            where dbo.PersonEducationalBackground.PersonId = @PersonId)

Cheers. Thanks.


text:
Q: Setup continous deploy from Visual Studio/TFS to a Windows Azure VM Is it possible to automatically deploy to a Windows Azure VM after a successful build from Visual Studio/TFS?

A: You question is not totally clear if you are looking for a solution for Windows Azure Virtual Machines or Windows Azure Cloud Services.
Windows Azure Virtual Machines:
With Windows Azure Virtual Machine, you own your Virtual Machine and thats why you would need to configure any deployment mechanism you decide. The OS VHD deployed for Windows Azure could be the one you upload or the one you got for gallery, so there are no basic deployment services running unless someone configure them first. For example if you will choose Windows Server based Windows Azure Virtual Machines, then you can install Web Deployment Services in Azure VM, and then configure your VS/TFS to continious deploy it or you can setup FTP based services to deploy your app. This SO discussion talks more on this regard.
Windows Azure Cloud Service:
If you are looking a solution directly from VS then you can add post build scripts using Poweshell commands. This solution will not depend on TFS at all. There are a few solutions also described which are non powershell dependent as well.
Using Visual Studio and Team foundation server components you have ability to configure the combination of MsBuild and PowerShell scripts as described here and here (same as Herve).
If you are looking for a solution directly from Windows Azure TFS (Cloud Based), this article includes everything needed.

A: You can find some information about automatic deployment here: http://www.windowsazure.com/en-us/develop/net/common-tasks/continuous-delivery/