text:
Q: Error using Cake PHP SQL Server Driver Upgraded a (dev) Cake PHP site and had to change database drivers from ADO to SQL Server's own driver as ADO is no longer supported in Cake 1.3, I . The new SQL Server driver is installed in PHP, shows in PHPinfo() and should work, but when I try to load a page using the database, I get this error:
Warning (2): sqlsrv_query() expects parameter 1 to be resource, boolean given
[APP\plugins\datasources\models\datasources\dbo\dbo_sqlsrv.php, line 184]
Warning (512): SQL Error: An invalid parameter was passed to sqlsrv_query.
 [CORE\cake\libs\model\datasources\dbo_source.php, line 684]
Query: SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

What appears to be happening is my connection isn't established in the dbo_sqlsrv.php driver; a "$this->connection" variable is supposed to be the connection resource then passed to sqlsrv_query() and it's apparently a bool which is wrong (I tried to Echo the variable and it displays nothing).
This is where the connection SHOULD be set:
sqlsrv_connect($this->config['host'] . $port, $params)

Printing the variables that were passed in gives me this:
SRV, 1433 Array ( [Database] => DB [CharacterSet] => char
[MultipleActiveResultSets] => [UID] => sa [PWD] => password )

Each of those parameters is correct, is there a specific way I should format or change my database configuration array for this driver or is there something I am missing?

A: This error was due to outdated SQL Server drivers. Installing the latest from below allows a SQL Server connection:
http://www.microsoft.com/download/en/details.aspx?id=20098

A: I think there is some issue with your connection. PHP can't establish connection with sql Server.
var $default = array(
        'driver' => 'sqlsrv',
        'persistent' => false,
        'host' => 'Myhome-PC\SQLEXPRESS', // or ip-address(192.168.1.13)
        'login' => 'username',
        'password' => 'password',
        'database' => 'db',
        'prefix' => 'tbl',
        'port' => NULL,
        'returnDatesAsStrings' => True
    );

I think the Connection should be this
Here is the sqlsrv_dbo which I used.
And your $param should be something like this
$connectionInfo = array("UID" => $config['login'],
                        "PWD" => $config['password'],
                        "Database" => $config['database'],
                        'MultipleActiveResultSets' => 1,
                        'ConnectionPooling' => 0
);
if(isset($config['ReturnDatesAsStrings'])){
         $connectionInfo['ReturnDatesAsStrings'] = $config['ReturnDatesAsStrings'];
}
$this->connection = sqlsrv_connect($config['host'] . $port, $connectionInfo);


text:
Q: Taking the coordinates of an object and creating a formula to drag an arrow I am using OpenCV to triangulate the position of an object, and am trying to create some kind of formula to pass the coordinates that I obtain through to drag a pull arrow, casting a fishing rod. I tried using polynomial regression to a very high degree, but it is still inaccurate due to the regression not being able to take into account an (x,y) input to an (x,y) output, rather just an x input to x output etc. I have attached screenshots below for clarity, alongside my obtained formulas from the regression. Any help/ideas/suggestions would be appreciated, thanks.
Edit:

*

*The xy coordinates are organized from the landing position to the position where the arrow was pulled to for the bobber to land there. This is because the fishing blob is the input, and the arrow pull end location comes from the blob location. I am using OpenCV to obtain the x,y coordinates, which I believe is just an x,y coordinate system of the 2d screen.

*The avatar position is locked, and the button to cast the rod is located at an absolute position of (957,748).

*The camera position is locked with no rotation or movement.

*I believe that the angle the rod is cast at is likely a 1:1 opposite of where it is pulled to. Ex: if the rod was pulled to 225 degrees it would cast at 45 degrees. I am not 100% sure, but I think that the strength is linear. I used linear regression partially because I was not sure about this. There is no altitude difference/slope/wind that affects the cast. The only affecting factor of landing position is where the arrow is dragged to. The arrow will not drag past the 180/360 degree position sideways (relative to cast button) and will simply lock the cast angle in the x direction if it is held there.

*The x-y data was collected with a simple program to move the mouse to the same position (957,748) and drag the arrow to cast the rod with different drag strengths/positions to create some kind of line of best fit for a general formula for casting the rod. The triang_x and y functions included are what the x and y coordinates were run through respectively to triangulate the ending drag coordinate for the arrow. This does not work very well because matching the x-to-x and y-to-y doesn't account for x and y data in each formula, just x-to-x etc.
Left column is fishing spot coordinates, right column is where arrow is dragged to to hit the fish spot.

(1133,359) to (890,890)
(858,334) to (886, 900)
(755,579) to (1012,811)
(1013,255) to (933,934)
(1166,469) to (885,855)
(1344,654) to (855,794)
(804,260) to (1024,939)
(1288,287) to (822,918)
(624,422) to (1075,869)
(981,460) to (949,851)
(944,203) to (963,957)
(829,367) to (1005,887)
(1129,259) to (885,932)
(773,219) to (1036,949)
(1052,314) to (919,908)
(958,662) to (955,782)
(1448,361) to (775,906)
(1566,492) to (751,837)
(1275,703) to (859,764)
(1210,280) to (852,926)
(668,513) to (1050,836)
(830,243) to (1011,939)
(688,654) to (1022,792)
(635,437) to (1072,864)
(911,252) to (976,935)
(1499,542) to (785,825)
(793,452) to (1017,860)
(1309,354) to (824,891)
(1383,522) to (817,838)
(1262,712) to (867,758)
(927,225) to (980,983)
(644,360) to (1097,919)
(1307,648) to (862,798)
(1321,296) to (812,913)
(798,212) to (1026,952)
(1315,460) to (836,854)
(700,597) to (1028,809)
(868,573) to (981,811)
(1561,497) to (758,838)
(1172,588) to (896,816)

Shows bot actions taken within function and how formula is used.
coeffs_x = np.float64([
    -7.9517089428836911e+005,
     4.1678460255861210e+003,
    -7.5075555590709371e+000,
     4.2001528427460097e-003,
     2.3767929866943760e-006,
    -4.7841176483548307e-009,
     6.1781765539212100e-012,
    -5.2769581174002655e-015,
    -4.3548777375857698e-019,
     2.5342561455214514e-021,
    -1.4853535063513160e-024,
     1.5268121610772846e-027,
    -2.9667978919426497e-031,
    -9.5670287721717018e-035,
    -2.0270490020866057e-037,
    -2.8248895597371365e-040,
    -4.6436110892973750e-044,
     6.7719507722602512e-047,
     7.1944028726480678e-050,
     1.2976299392064562e-052,
     7.3188205383162127e-056,
    -6.3972284918241943e-059,
    -4.1991571617797430e-062,
     2.5577340340980386e-066,
    -4.3382682133956009e-068,
     1.5534384486024757e-071,
     5.1736875087411699e-075,
     7.8137258396620031e-078,
     2.6423817496804479e-081,
     2.5418438527686641e-084,
    -2.8489136942892384e-087,
    -2.3969101111450846e-091,
    -3.3499890707855620e-094,
    -1.4462592756075361e-096,
     6.8375394909274851e-100,
    -2.4083095685910846e-103,
     7.0453288171977301e-106,
    -2.8342463921987051e-109
])
triang_x = np.polynomial.Polynomial(coeffs_x)

coeffs_y = np.float64([
    2.6215449742035207e+005,
    -5.7778572049616614e+003,
     5.1995066291482431e+001,
    -2.3696608508824663e-001,
     5.2377319234985116e-004,
    -2.5063316505492962e-007,
    -9.2022083686040928e-010,
     3.8639053124052189e-013,
     2.7895763914453325e-015,
     7.3703786336356152e-019,
    -1.3411964395287408e-020,
     1.5532055573746500e-023,
    -6.9719956967963252e-027,
     1.9573598517734802e-029,
    -3.3847482160483597e-032,
    -5.5368209294319872e-035,
     7.1463648457003723e-038,
     4.6713369979545088e-040,
    -7.5070219026265008e-043,
    -4.5089676791698693e-047,
    -3.2970870269153785e-049,
     1.6283636917056585e-051,
    -1.4312555782661719e-054,
     7.8463441723355399e-058,
     1.9439588820918080e-060,
     2.1292310369635749e-063,
    -1.4191866473449773e-065,
    -2.1353539347524828e-070,
     2.5876946863828411e-071,
    -1.6182477348921458e-074
])
triang_y = np.polynomial.Polynomial(coeffs_y)

A: First you need to clarify few things:

*

*the xy data
Is position of object you want to hit or position what you hit when used specific input data (which is missing in that case)?In what coordinate system?

*what position is your avatar?

*how is the view defined?
is it fully 3D with 6DOF or just fixed (no rotation or movement) relative to avatar?

*what is the physics/logic of your rod casting
is it angle (one or two), strength?Is the strength linear to distance?Does throwing acount for altitude difference between avatar and target?does ground elevation (slope) play a role?Are there any other factors like wind, tupe of rod etc?
You shared the xy data but what against you want to correlate or make formula for it? it does not make sense you obviously forget to add something like each position was taken for what conditions?
I would solve this by (no further details before you clarify stuff above):

*

*transform targets xy to player relative coordinate system aligned to ground

*compute azimut angle (geometricaly)
simple atan2(y,x) will do but you need to take into account your coordinate system notations.

*compute elevation angle and strength (geometricaly)
simple balistic physics should apply however depends on the physics the game or whatever you write this for uses.

*adjust for additional stuff
You know for example wind can slightly change your angle and strength
In case you have real physics and data you can do #3,#4 at the same time. See similar:

*

*C++ intersection time of 2 bullets
[Edit1] puting your data into your image
OK your coordinates obviously do not match your screenshot as the image taken is scaled after some intuition I rescaled it and draw into image in C++ to match again so here the result:

I converted your Cartesian points:
int ava_x=957,ava_y=748;    // avatar

int data[]=                 // target(x1,y1) , drag(x0,y0)
    {
    1133,359,890,890,
    858,334,886, 900,
    755,579,1012,811,
    1013,255,933,934,
    1166,469,885,855,
    1344,654,855,794,
    804,260,1024,939,
    1288,287,822,918,
    624,422,1075,869,
    981,460,949,851,
    944,203,963,957,
    829,367,1005,887,
    1129,259,885,932,
    773,219,1036,949,
    1052,314,919,908,
    958,662,955,782,
    1448,361,775,906,
    1566,492,751,837,
    1275,703,859,764,
    1210,280,852,926,
    668,513,1050,836,
    830,243,1011,939,
    688,654,1022,792,
    635,437,1072,864,
    911,252,976,935,
    1499,542,785,825,
    793,452,1017,860,
    1309,354,824,891,
    1383,522,817,838,
    1262,712,867,758,
    927,225,980,983,
    644,360,1097,919,
    1307,648,862,798,
    1321,296,812,913,
    798,212,1026,952,
    1315,460,836,854,
    700,597,1028,809,
    868,573,981,811,
    1561,497,758,838,
    1172,588,896,816,
    };

Into polar relative to ava_x,ava_y using atan2 and 2D distance formula and simply print the angular difference +180deg and ratio between line sizes (that is the yellow texts in left of the screenshot) first is ordinal number then angle difference [deg] and then ratio between line lengths...
as you can see the angle difference is +/-10.6deg and length ratio is <2.5,3.6> probably because of inaccuracy of OpenCV findings and some randomness for fishing rod castings from the game logic itself.
As you can see polar coordinates are best for this. For starters you could do simply this:
// wanted target in polar (obtained by CV)
x = target_x-ava_x;
y = target_y-ava_y;
a = atan2(y,x);
l = sqrt((x*x)+(y*y));
// aiming drag in polar
a += 3.1415926535897932384626433832795; // +=180 deg
l /= 3.0; // "avg" ratio between line sizes
// aiming drag in cartesian
aim_x = ava_x + l*cos(a);
aim_y = ava_y + l*sin(a);

You can optimize it to:
aim_x = ava_x - ((target_x-ava_x)/3);
aim_y = ava_y - ((target_y-ava_y)/3);

Now to improve precision you could measure the dependency or line ratio and line size (it might be not linear) , also the angular difference might be bigger for bigger lines ...
Also note that second cast (ordinal 2) is probably a bug (wrongly detected x,y by CV) if you render the 2 lines you will see they do not match so you should not account that and throw them away from dataset.
Also note that I code in C++ so my goniometrics use radians (not sure if true for python if not you need to convert to degrees) also equations might need some additional tweaking for your coordinate systems (negate y?)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Selenium vs old-school POST/GET based tests We have a considerable code base with relatively high test coverage for pages/forms, all via vanilla POST/GET.
Now, we are find ourselves moving more into the 'ajaxy' space, and it's not quite possible to test with GET/POST complete scenarios like user registration, or an item creation, as they involve lots of JavaScript/Ajax calls.
While things like that are the most likely candidates for testing with Selenium, I wonder should we adopt the Selenium testing across the board, leaving the old-school POST/GET tests altogether?
Advantages of Selenium adoption seems to be too good - ability to run pretty much same GET/POST tests but across the range of browsers.
Or am I missing something in my pursuit of cool and trendy stuff and ditching the old proven POST/GET tests?

A: There's advantages and disadvantages of both approaches, so my recommendation would be to use both.
Selenium launches an actual browser and simulates a user interacting with your web application, which can be great if you're testing Ajax features. It can verify that elements are visible and interact with them just as a user would. Another killer feature is the ability to take screenshots through Selenium, which can be incredibly useful when investigating failures.
Unfortunately launching a browser and navigating to a specific page/state in your application can be slow, and you'd need a lot of hardware if you wanted to test concurrent users (load testing) with Selenium.
If you just want to test that your server responds with a HTTP 200 for certain actions, or load test your applications, or that the response contains certain values then basic POST/GET would be more suitable.
If you do decide to go with a pure Selenium approach to testing I would recommend looking into using Selenium Grid or a cloud based service, as running lots of tests through Selenium can be quite time consuming.

A: I think you should definitely use Selenium and POST/GET (Unit) tests altogether, because the aim of your unit test is to test functionality of a specific section of code but Selenium is is doing integration testing on your web-app.


text:
Q: Errors in Xcode, impossible to launch my application React Native in my iPad I have these errors on Xcode. I have already tried to replace JWTStringCoderProtocol by JWTStringCoder__Protocol in the concerned file but it didn't change anything. Same when I wanted to comment out the lines containing JWTClaimsSetCoordinatorProtocol.
Do you know where the problem comes from?
errors in Xcode


text:
Q: wordpress package a script called by http in a plugin way I am working on wordpress php script which performs in house administrative tasks.
This script is called using HTTP request.
For instance : http://mywpinstance.com/myscript.php
I would like to package this script in a plugin way.
How can i do this ?
Greetings.
ben


text:
Q: Animate an existing model with Java? Imagine I have a model that I want to use in a LibGDX game project (as described here). Let's say, it's the model of a human. Now I want to do several animations with this human: I want him to raise his left/right arm, his left/right leg, to raise a single finger, and also all possible combinations of those animations.
My question is: Do I need to create a single animation for all of those movements outside of my Java code (which would mean I need a file for every single animation and would make my project extremly large), or is it somehow possible to create a model (e.g. by using Blender's Armature or something like that) that can be transformed inside my Java code?

A: Assuming you're asking if you can include one or more animations with the g3db/g3dj file format. Yes you can. Just create your model, including the skeleton and animations. Export it to FBX (with animation enabled). Next, convert to g3db or g3dj (fbx-conv -f file.fbx). Load your model as described in the tutorial you referenced. Now you can animate your model using an AnimationController. If you want to combine multiple animations at the same time, you can use multiple AnimationControllers, as long as they don't affect the same bones.


text:
Q: Nearest Neighbor on a 3d Grid In Solid State Physics we were analyzing a crystal with a simple cubic unit cell and wanted to compute the number of first nearest neighbors, second nearest neighbors and so on and their corresponding distances.
I can see this is related to the number of solutions of:
$$x^2+y^2+z^2=r_n^2$$
with $x,y,z\in\mathbb{Z}$ the number of steps in each direction and $r_n$ the distance of the $n$-nearest neighbor.
However, that time we used an approximation to solve this. I am wondering if there is a nice exact expression for this? or any known result?


text:
Q: How can I get the current cache of a target DNS server? I know I can do something like: sudo killall -INFO mDNSResponder, and then just check the /var/log/system.log, but I want to be able to get the cache dump from a target DNS server.
Is this possible?
I'm on a mac.

A: No, there is no standard protocol for dumping the cache of an arbitrary DNS server. If it's a server you own/run, see the documentation for your DNS server software to see how to dump the cache in whatever software you're running.


text:
Q: Thymeleaf binding a selected value from a table I'm having a table with multiple elements that are generated from a List and every table element from that list has a button.By clicking that button there is a post submit request which should bind the values from that table data element to a @ModelAttribute object in spring boot.
The problem is that i'm able to map the whole list but I want to bind only the table element where the button was pressed.

   <form th:action="@{/saveAd}" th:object="${object}" method="POST">

               Image
               Title

               Price
               City

                  <input type="hidden" readonly="readonly"
                     th:name="?"
                     th:value="${element.getUrl()}" />

                     <input type="hidden" readonly="readonly" th:name="img" th:value="${element.getImg()}" />

                     <input type="hidden" readonly="readonly" th:name="?" th:value="${element.getTitle()}" />

                     <input type="hidden" readonly="readonly" th:name="?" th:value="${element.getPrice()}" />

                     <input type="hidden" readonly="readonly" th:name="?" th:value="${element.getCity()}" />

                  <input class="btn btn-danger" type="submit"
                     value="Save">

   </form>

The Controller:
@RequestMapping(path = "/saveAd", method = RequestMethod.POST)
    public String saveAd(@ModelAttribute("Value") ListCreationAutovitDto listCreationAutovitDto) {
        return "home";
    }

I have a hidden input type for every td which should map the values but i've tried naming it in different ways but i can't make it work.Are there any ways to bind only the values where the button was pressed?

A: Idea 1: Make each td contain a form pointing to your controller method. Then bind the values you want to pass to the model by using hidden input fields in the form. Each button would then do a submit for the form it is in.
Idea 2: If you're mapping json to your java objects in your app, you can construct the json request body in JavaScript to contain only the stuff you want for that request


text:
Q: Creating a reference to a value type field I have a method that can be called from two different locations (call it loc A and loc B). In that method I have a while loop that runs as long as a particular bool is true (call it running).
The tricky thing is, if the method was called from loc A, then that bool variable should refer to bool-X. If it was called from loc B, the bool should be referring to bool-Z. X and Z are defined in another class and are globally available.
As you can imagine, just setting running = locIsA ? GetBoolA : GetBoolB; will not work, because running is then fixed and when another part of the program changes A or B, running will not be affected.
How do I set running to be either bool-A or bool-B depending on a condition, as opposed to copying the contents?
Thanks a million.

A: One approach is to pass a Func<bool> amIDoneYet parameter to your method, which it can use to query periodically whether it should terminate.  You would then create a delegate like () => X for passing to the method.
You may want to consider, however, whether a design change could improve things.  For instance, if this is being used for cancellation, consider implementing the Task cooperative cancellation pattern.  This is the recommended standard approach for implementing cancellation for asynchronous tasks.


text:
Q: Script for ffmpeg webcam audio video recording I've bought the very popular Logitech C920 for creating YouTube videos with ffmpeg.
My desire is to build a script for easy recording without bothering with the powerful but rather cryptic ffmpeg commands. I've come pretty far, however I'm now trying for hours to solve basically three problems:
(1) show the video, while recording
   (2) record the stereo audio in good quality
   (3) display an VU-meter
For displaying the video I've found ffplay instead of ffmpeg, however, this would require another command so I'm not sure how to do this in order to start two commands at the same time (and be sure that this are synchronized). I usually use the mpv player in an i3wm desktop environment.
The audio record should be included into the video-file, and it would be desirable push the audio-quality as high as possible, and reasonable (considering the hardware).
Since the setup is not intended to be used for live-streaming, it is not important to make the final encoding on the fly. If an additional step, at the end of the video-recording, would lead to better results, this variant is preferable. The central focus is to produce a video-file which is optimized to have good playback quality on mid-range to low-cost hardware (i.e. no artefacts) for YouTube-viewers without fast internet connections.
Script:
echo "Short title (and/or ENTER):"
read title
recdir=$HOME/Videos/0_Integrate/test-webcam
# Check if the default directory exists
if [ -d $recdir ]
then
    path=$recdir
else
    # If not, write to $HOME
    path=$HOME
fi
echo "Recording now!"
echo "To File:"
# File-name and -location composition
filename=$(date +"$path/%Y%m%d-%H%M_$title.mp4")
echo "$filename"
# Recording command
ffmpeg -f video4linux2 -framerate 30 -video_size 864x480 -input_format h264 -i /dev/video0  $filename
echo
echo
# Show where and which file was recorded
echo "Recorded to file:"
echo -e "\e[1;31m$filename\e[0m"
echo

I've consulted the official (this, this and this ) as well  as other sources (e.g. this, this, and this), without much luck finding an understandable (for casual users) and complete guide for setting this up.
[EDIT
Found possible problem why my audio is not recorded. The VU-meter doesn't react to microphone input. See screenshot:

\EDIT]


text:
Q: httpd/mod_auth_form How to display an error message on invalid credentials? Using inline form with ErrorDocument 401, how can I get an error message to be displayed when the user fails to login?
Expected features are to still work (e.g. login redirect). No login/logout URLs seen in user's browser. When the user logs out, the message should not be shown when they are 401'd back to the inline login page.
I am currently using an onsubmit function to set a flag in sessionStorage. If the page loads (body onload function) and sees this flag, it will show the error message (e.g. user entered wrong credentials and are back here again). This works fine, until they logout. They are 401'd to the login page and the flag is still there, so they see the error message.
I need to clear the message somehow.
Well, GET vs POST! The initial page load is a GET and the logout is a GET; so, only failed logins would be loading this page with a POST.
Let's activate SSI and use an env var (this is on both login and logout Location directives):
SetEnvIf Request_Method "^GET$" LOGIN-ERROR-CLEAR="1"
Inject some JS to our init to clear the sessionStorage:
<!--#if expr="reqenv('LOGIN-ERROR-CLEAR') == '1'" -->
sessionStorage.removeItem('login-attempted');
<!--#endif -->

Sounds logical...but, it doesn't work. The JS is not injected.

*

*GET /logout -> 307 to "/" (due to AuthFormLogoutLocation "/")

*GET / -> 401 with content of /login.html

*error message is wrongly shown

All GETs, yet the JS was not injected. What is going on? I am back where I started before using SetEnvIf - there is no difference. It's not doing anything!
Is there a better way to trigger an error message and clear the trigger after successful login or logout? This shouldn't be this hard!

A: Found out I could use the variables directly in the SSI; so, I removed the SetEnvIfs from my vhost. Also, REQUEST_METHOD is the wrong one to use. REDIRECT_REQUEST_METHOD is the one to look for. In the end, this seems to be working:
<!--#comment This block uses SSI/mod_include. -->
<!--#if expr='v("REDIRECT_REQUEST_METHOD") == "GET"' -->
sessionStorage.removeItem('login-attempted');
<!--#endif -->


text:
Q: How to specify the location for FileReference.browse() in Flex I have a requirement to select a file from fileReference.browse(), but I want to browse a file to specific location say D:\Dir\file instead of the OS specific (The dialog box is native to the user's operating system).
Is it possible?
Thanks in Advance-

A: Since you're using File, I'm assuming you're using the Air runtime.  To do this, you just need to set the path in the file constructor before you browser; like this:
var file:File = new File(somePath);
file.browse();

The only problem with this is that if you set it as an absolute path (like say, "c:\Users\SomeUser"), it might not work on Macs or Linux computers.  Be sure to use some of the File class' built in static properties when you can, like these:

*

*File.applicationStorageDirectory—a storage directory unique to each installed AIR application

*File.applicationDirectory—the read-only directory where the application is installed (along with any installed assets)

*File.desktopDirectory—the user's desktop directory

*File.documentsDirectory—the user's documents directory

*File.userDirectory—the user directory


text:
Q: Proposal for limiting mediocre questions (unit testing for questions?) In my answer to Should we require minimum reputation to continue asking questions? I came up with a possible solution.
The essential problem is that some people come to SO, ask lots of lame questions, and never give anything back. The proposals have included only allowing a certain fraction of one's rep to come from questions and only allowing users to ask questions if they have a certain amount of rep, but neither of those seemed particularly popular.
This suggestion is:
Require that unqualified users have their questions reviewed like edits before being posted.
What is the qualification? It could be rep that's a certain multiple of their questions (say 10 rep per question) or a certain ratio of questions to answers, or some other criteria. We could also allow a certain number of questions to not require review (say, 5-10) so that a user would have to lose their ability to ask unreviewed questions rather than have to earn it.
Who reviews these questions? It could be 5k, 10k, 20k users, or maybe anybody above 2k who also has the ability to post questions without review. It could even be people with sufficient points in the applicable tags.
How would this mitigate the flood of bad questions? First of all, users would be rate-limited by only being able to have a certain number (1?) of questions in review at once. If a user keeps getting their questions rejected, they could lose the ability to submit for a period of time ("We are no longer accepting questions from this IP"). When two reviewers reject a question, nobody else will ever see it (maybe not even as a deleted question). Of course, there would be an "Improve" button so that reviewers could fix minor problems before anybody else ever had to read the problematic post.
Furthermore, upon clicking the "Reject" button, there could be a dialog box with a list of checkboxes to select reasons for rejection ("Off topic", "Spammy links", "Lack of formatting", "Not a question", "Missing sample code", "Too much sample code", "Poor English", etc.) and maybe even a box for remarks. This would allow the person asking the question to see why their question was rejected, fix it and resubmit (if applicable). This should train users how to write acceptable questions. The review page could have the question's preview remarks and deltas from the last submission, a link to the user's most recent rejections, or something in between.
What are the downsides? Unfortunately, this would increase the burden on reviewers. Hopefully the "training" aspect should reduce the ongoing burden of any particular user and not having the bad questions posted in the first place should eliminate edit reviews (i.e. review the question before it's posted so you don't have to review several edits to the question after it's posted). In other words, this is like unit testing -- it seems like it would add too much of a burden initially, but it actually ends up saving time and helps deliver a higher-quality product in the end.
Some users could be insulted by having their question criticized. This should be minimized by having standard rejection reasons that aren't personal, while the remarks would hopefully be a polite nudge in the right direction (e.g. "Just specify the OS you're using"). Of course some users would go away entirely after being confronted by this, but it's not clear that those are users we want.

A: I don't really see the point of this.
Why not "review" questions as they are asked?
https://stackoverflow.com/review
The existing flagging and downvoting mechanisms should suffice without adding Yet Another Queue of Work for more of our users to have to deal with and think about.
Also, questions which fail to get any significant activity are already auto-culled over time, and downvoted questions with no significant activity auto-culled even more aggressively still.


text:
Q: Avoid using global scope in p5 I just started a new project in p5, I've already used it directly imported in the browser, but this time, since it's a more complex project, I'm going to use it in webpack.
I imported the library and bootstraped it in this way:
import * as p5 from 'p5';

function setup() {
  createCanvas(640, 480);
}

function draw() {
  if (mouseIsPressed) {
    fill(0);
  } else {
    fill(255);
  }
  ellipse(mouseX, mouseY, 80, 80);
}

But it doesn't work.
The reason is simple: webpack wraps the module in a local scope, and p5 isn't aware of it.
For this reason, I assigned the functions to the global scope:
import * as p5 from 'p5';

window.setup = function () {
  createCanvas(640, 480);
}

window.draw = function () {
  if (mouseIsPressed) {
    fill(0);
  } else {
    fill(255);
  }
  ellipse(mouseX, mouseY, 80, 80);
}

And it works fine, but still looks wrong. I don't think that pollulating the global scope is the correct way of working with JS in 2019. Expecially if I'm using webpack and I'm about to implement TypeScript.
So, how can I tell p5 to look for the functions in the module scope and not in the global one?

A: You'd use instance mode, which doesn't rely on globals. Here's the example from that page:
var sketch = function( p ) {

  var x = 100;
  var y = 100;

  p.setup = function() {
    p.createCanvas(700, 410);
  };

  p.draw = function() {
    p.background(0);
    p.fill(255);
    p.rect(x,y,50,50);
  };
};

var myp5 = new p5(sketch);

Live Example:

var sketch = function( p ) {

  var x = 100;
  var y = 100;

  p.setup = function() {
    p.createCanvas(700, 410);
  };

  p.draw = function() {
    p.background(0);
    p.fill(255);
    p.rect(x,y,50,50);
  };
};

var myp5 = new p5(sketch);
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.min.js"></script>


text:
Q: How to create "Publishing Image" site column programmatically? How can I create site column with "Publishing Image" content type programmatically in FeatureActivated method?
I need to add this site column to the List

A: All this content Types located in Microsoft.Sharepoint.Publishing. So I have needed to reference this lib. And add this code.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    using (var rootWeb = properties.Feature.Parent as SPWeb)
    {
        if (rootWeb == null)
        {
            return;
        }
        const string testSiteColumn = "TestSiteColumn";
        if (!rootWeb.Fields.ContainsField(testSiteColumn))
        {
            var newImageField = new ImageField(rootWeb.Fields, "Image", testSiteColumn)
                {
                    Group = "Test",
                    StaticName = "Test",
                    Title = "Test",
                    RichText = true,
                    RichTextMode = SPRichTextMode.FullHtml
                };
            rootWeb.Fields.Add(newImageField);
        }
    }
}

This ContentType doesn`t located in SPFieldType, so I have needed to hardcode type in new ImageField as "Image".
Works fine.


text:
Q: Get rid of xmlns lines when using xmlwrite I'm working on a data acquisition application and I'd like to implement a save project function using the XML write method of the DataSet class. When I use the primitive types in my datatable (doubles, strings, etc.) the XML write/read is just working great. However, when I added a custom class type column to my datatable, the XML file output would be full of strange lines containing xmlns, URLs, etc. I understand that was caused by the custom class but how can I get rid of them? It makes the entire XML read process extremely slow.
Edit (just a quick sketch):
namespace CustomClassXMLExporterTest
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();

        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Result", typeof(Result));

        Result r1 = new Result();

        r1.name = "Somebody";
        r1.value = 0.1234;
        r1.valid = true;

        DataRow dr = dt.NewRow();

        dr["Name"] = "Somebody";
        dr["Result"] = r1;

        dt.Rows.Add(dr);

        ds.Tables.Add(dt);

        ds.WriteXml("C:\\testxml.xml");
    }
}
public class Result
{
    public double value;
    public string name;
    public bool valid;

}
}

Output xml:
 <?xml version="1.0" standalone="yes"?>
 <NewDataSet>
 <Table1>
 <Name>Somebody</Name>
 <Result xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <value>0.1234</value>
   <name>Somebody</name>
   <valid>true</valid>
 </Result>
 </Table1>
 </NewDataSet>


text:
Q: SSRS report losing formatting in interactive viewer I have an SSRS report with two subreports that had been working fine.  Recently I added some additional table sections to the report and I started seeing an issue when the report was displayed in the interactive viewer.  The data is fine but the formatting on the last two table sections does not appear in the viewer.
The formatting actually stops working half way through the next to last report.  However, when I print the report (or export to a PDF), all of the formatting is there and the report prints fine.
I have tried splitting the report into more subreports, running with different data and it still does not display correctly in the interactive viewer.  The report and subreports do have a lot of formatting and table sections and I am wondering if the RDL files are too big to store in memory or if they even do get stored in memory.
The RDL file sizes are 61 kB for the main report and 2612 kB and 2608 kB respectively for the subreports.  Is there a size limitation on the RDL files?  Any ideas?

A: I have found a work around for my problem.  If I render my report directly to a PDF, then the report will not display in the interactive viewer, but only as a PDF which displays correctly.  This is done by adding "&rs:Format=PDF" to my URL when I call it from my C# program that allows the user to input the parameters.  Then the user can print the report and never see the missing formatting in the interactive viewer.  This works for my, however, I would still like to know if there is another answer that allows it to view correctly in the interactive viewer or if I have surpassed some memory limitations.

A: If you split the report into its component parts does it display ok? If as you say you have recently added some new sections/Sub reports to it if you remove them does it look ok again.
You have probably got some strange overlapping happening, in the report designer when the report complies check the warning tag to see if it gives you any clues


text:
Q: XMLHttpRequest with constantly changing variable URL I have an array that has multiple strings in it. Anywhere from 1 to 10 strings. This array is cycling threw each string every 5 seconds.
var completeArray = new Array();
completeArray[0] = new comArray('http://domain.com','/sports/','photo','1','http://domain.com');
completeArray[1] = new comArray('10461632','/sports/','video','0','');
completeArray[2] = new comArray('10459620','http://domain.com','video','0','');
completeArray[3] = new comArray('10459542','/sports/m-footbl/recaps/092312aah.html','video','0','');
completeArray[4] = new comArray('http://domain.com','/sports/','photo','0','');

Then I have a XMLHttpRequest that takes the variable completeArray as the url. I want it to initiate a new request every time it comes to a string with numbers in the first node of the string such as '10461632',.
$.ajax({
    type: "GET",
    url: completeArray,
    dataType: "xml",
    success: function(data) {
        $(data).find('item').each(function(){
        });
    }
});

I have no idea how to go about this and any help or direction to get on the right path would be greatly appreciated. Thank you.

A: First of all, what is comArray? I think you are mistakenly naming it comArray instead of Array. I dont see it defined anywhere. I assumed this and renamed it.
I also made a fiddle that just logs the url into the console so that you can see how it works. I still dont think this is going to accomplish what you need because the URLs are coming out mis-formatted, probably due to the way you created each completeArray node.
fiddle: http://jsfiddle.net/dy9kM/12/
var completeArray = new Array();
completeArray[0] = new Array('http://domain.com', '/sports/', 'photo', '1', 'http://domain.com');
completeArray[1] = new Array('10461632', '/sports/', 'video', '0', '');
completeArray[2] = new Array('10459620', 'http://domain.com', 'video', '0', '');
completeArray[3] = new Array('10459542', '/sports/m-footbl/recaps/092312aah.html', 'video', '0', '');
completeArray[4] = new Array('http://domain.com', '/sports/', 'photo', '0', '');

$(function() {
 $.each(completeArray, function(index, value) {
    if (value[0].match(/\d/)) {
        length = value.length;
        array = value.slice(1, length);
        url = array.join('');
        $.ajax({
            type: "GET",
            url: url,
            dataType: "xml",
            success: function(data) {
                $(data).find('item').each(function() {});
            }
        });
    }
 });
});


text:
Q: JPA Inheritence Annotation on Sub Entity Hierarchy Is it possible to use @Inheritence Annotation and different strategy at different hierarchy ?

The inheritance strategy and the discriminator column are only specified in the root of an entity class
hierarchy or subhierarchy .

But different strategy allowed ?

A: I do not think so, please correct me if I am wrong. You can use mixed-inheritance with same hierarchy applying different strategies. Use
@SecondaryTable(
name = "SUBTABLE",
pkJoinColumns = @PrimaryKeyJoinColumn(name = "SUB_TABLE_ID");

before your sub-class definition. Using this, you apply for example SINGLE_TABLE strategy and have separated sub-class table.

A: Mixing inheritance strategies within a single entity inheritance hierarchy is not a supported JPA configuration. The JPA specification states:

The combination of inheritance strategies within a single entity inheritance hierarchy is not defined by this specification.


text:
Q: why after converting XML to a Json it displays so many '&' sign that gives error in console.log()? this post is based on the json generated from XML in my post when json was generated it generates so many '&' sign and formatting symbols here is the generated json show on console.log(). the console.log() complains about this error. how do i fix this and remove those formatting symbols from json?

Uncaught SyntaxError: Unexpected token &

here is the json printed by console.log()
console.log( {"class":{"@Title":"SOCIAL HISTORY","@ID":"1","@ParentID":"0","helpNavNode":[{"@Title":"ALCOHOL CONSUMPTION","@ID":"2","@ParentID":"1","helpNavNode":[{"@Title":" Never","@ID":"3","@ParentID":"2","@Narrative":"ALCOHOL CONSUMPTION: Never"},{"@Title":" Occasionally","@ID":"4","@ParentID":"2","@Narrative":"ALCOHOL CONSUMPTION: Occasionally"},{"@Title":" Socially","@ID":"5","@ParentID":"2","@Narrative":"ALCOHOL CONSUMPTION: Socially"},{"@Title":" Daily (3 beers/day) (6 pack/day)","@ID":"6","@ParentID":"2","@Narrative":"ALCOHOL CONSUMPTION: Daily (3 beers/day) (6 pack/day)"},{"@Title":" Is Alcoholic","@ID":"7","@ParentID":"2","@Narrative":"ALCOHOL CONSUMPTION: Is Alcoholic"},{"@Title":" History of Alcoholism","@ID":"8","@ParentID":"2","@Narrative":"ALCOHOL CONSUMPTION: History of Alcoholism"},{"@Title":" None","@ID":"26","@ParentID":"2","@Narrative":"ALCOHOL CONSUMPTION: None"},{"@Title":"Alcoholism Screen Question","@ID":"39","@ParentID":"2","helpNavNode":{"@Title":" Ever had a drinking problem? Last drink? ","@ID":"40","@ParentID":"39","@Narrative":"ALCOHOL CONSUMPTION:Alcoholism Screen Question: Ever had a drinking problem? Last drink? "}}]},{"@Title":"MARITAL STATUS","@ID":"9","@ParentID":"1","helpNavNode":[{"@Title":" Married","@ID":"10","@ParentID":"9","helpNavNode":{"@Title":" x 10 years","@ID":"15","@ParentID":"10","@Narrative":"MARITAL STATUS: Married: x 10 years"}},{"@Title":" Divorced","@ID":"11","@ParentID":"9","@Narrative":"MARITAL STATUS: Divorced"},{"@Title":" Single","@ID":"12","@ParentID":"9","@Narrative":"MARITAL STATUS: Single"}]},{"@Title":"Recreational drug use","@ID":"13","@ParentID":"1","@Narrative":":Recreational drug use"},{"@Title":"OCCUPATION","@ID":"14","@ParentID":"1","helpNavNode":{"@Title":" works for  x 27 years","@ID":"25","@ParentID":"14","@Narrative":"OCCUPATION: works for  x 27 years"}},{"@Title":" 1 child","@ID":"16","@ParentID":"1","@Narrative":": 1 child"},{"@Title":" 2/3/4/5/6 children","@ID":"17","@ParentID":"1","@Narrative":": 2/3/4/5/6 children"},{"@Title":"Activities","@ID":"18","@ParentID":"1","helpNavNode":[{"@Title":" walks regularly","@ID":"19","@ParentID":"18","@Narrative":"Activities: walks regularly"},{"@Title":" cycles for exercise","@ID":"20","@ParentID":"18","@Narrative":"Activities: cycles for exercise"},{"@Title":" runs 3 days/week","@ID":"21","@ParentID":"18","@Narrative":"Activities: runs 3 days/week"},{"@Title":" hunting and fishing","@ID":"22","@ParentID":"18","@Narrative":"Activities: hunting and fishing"},{"@Title":" hiking and camping","@ID":"23","@ParentID":"18","@Narrative":"Activities: hiking and camping"},{"@Title":" swims regularly","@ID":"24","@ParentID":"18","@Narrative":"Activities: swims regularly"}]},{"@Title":"Tobacco Use","@ID":"27","@ParentID":"1","helpNavNode":[{"@Title":"Cigar, Cigarette, Pipe, Smokeless","@ID":"30","@ParentID":"27","helpNavNode":{"@Title":"10/pk year","@ID":"32","@ParentID":"30","@Narrative":"Tobacco Use:Cigar, Cigarette, Pipe, Smokeless:10/pk year"}},{"@Title":"Quit Date","@ID":"35","@ParentID":"27","@Narrative":"Tobacco Use:Quit Date"},{"@Title":"Year Started","@ID":"36","@ParentID":"27","@Narrative":"Tobacco Use:Year Started"}]},{"@Title":"SocHx  Template","@ID":"37","@ParentID":"1","helpNavNode":[{"@Title":" Living situation:  Occupation:  Tobacco:  EtOH:  Rec. drugs: ","@ID":"41","@ParentID":"37","@Narrative":"SocHx  Template: Living situation:  Occupation:  Tobacco:  EtOH:  Rec. drugs: "},{"@Title":" Living situation:  Occupation:  Tobacco:  EtOH:  Rec. drugs: ","@ID":"42","@ParentID":"37","@Narrative":"SocHx  Template: Living situation:  Occupation:  Tobacco:  EtOH:  Rec. drugs: "}]}]}} );

how do i remove those @ signs and " asigns


text:
Q: Stored Procedure: MySQL, Error unable to select id field INTO @testId table, its showing error code.
code using
SELECT id INTO @testId, (3959 * ACOS (COS ( RADIANS(deviceLat ) ) * COS( RADIANS(`latitude`) )*
COS( RADIANS(`longitude` ) - RADIANS(deviceLong) )+ SIN ( RADIANS(deviceLat) )*
SIN( RADIANS(`latitude` )))) AS dist INTO @distance FROM route_waypoints
GROUP BY route_ID = @routeID AND (route_waypoints.type =  'PICK' OR
route_waypoints.type = 'CAMPUS') HAVING dist < 250  ORDER BY dist ASC LIMIT 1;

A: Try this...
  // Declare variables with datatype and size
    DECLARE @testId int, @distance varchar(500

    // set value of the selected column to that variable by = operator.
    SELECT @testId = id,
           @distance = (3959 * ACOS (COS ( RADIANS(deviceLat ) ) * COS( RADIANS(`latitude`) )*
                        COS( RADIANS(`longitude` ) - RADIANS(deviceLong) )+ SIN ( RADIANS(deviceLat) )*
                        SIN( RADIANS(`latitude` ))))
            FROM route_waypoints
            GROUP BY route_ID = @routeID AND (route_waypoints.type =  'PICK'
            OR route_waypoints.type = 'CAMPUS') HAVING dist < 250
            ORDER BY dist ASC LIMIT 1;

   // Print
   SELECT @testId, @distance


text:
Q: Расшифровать TLS без сокета Остался вопрос: как понять что соединение готово к передаче?
Пишу сервер, в протоколе есть проксированный TLS.
Сообщения нормальные для TLS, но упакованные.
Самый простой способ расшифровать TLS это создать пару сокетов и один врапнуть.
import socket
import ssl
context = ssl.create_default_context()
sock_cache = dict()

def processor(data, session_id):
    sp = sock_cache.get(session_id)
    if sp:
       a,b = sp
    else:
       a,b = socket.socketpair()
       a = context.wrap_socket(a, server_side=True)
       sock_cache[session_id] = a,b

    b.send(data)
    data = a.recv(4096)
    if data:
       answer = process(data)
       a.send(answer)
       sock_cache.pop(session_id)
    else:
       pass # handshake

    return b.recv(4096)

Сделал бы отдельный сервер, но данные из пакета нужны тут, а не вдругом сервере.
Как избавится от создания пары сокетов? следовательно от блокировок и кеша
Похоже нашел https://github.com/python/cpython/blob/bec4186c67345f1e6cd3f8a531bc228f14d7ed7b/Lib/ssl.py#L812
Осталось разобраться как с этим работать
import ssl

incom = ssl.MemoryBIO()
outcom = ssl.MemoryBIO()

context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
context.load_cert_chain(certfile="ssl_cert.pem", keyfile="ssl_key.pem")

sslo = context.wrap_bio(incom, outcom, server_side=True)

client_hello =  b"\x16\x03\x01\x01\x91\x01\x00\x01\x8d\x03\x03D\x93\xe7\xd7w\x1a\xd4G\xebM\xbe@\xb3\xc2\x93\xb7m\xc9\x01\x90\xb9!\x8d\xef<\xbe,\xab\xb2\xace\xa1 N\x81\xebgxn\xe7\x81)8\xaf\xec\xc0_\xe8\x11x\xb4\xc5\xf5t(Y\xd5X9\xa7\xe1\x99\\\x85\xe4\x00\x96\x13\x02\x13\x03\x13\x01\xc0,\xc00\x00\xa3\x00\x9f\xcc\xa9\xcc\xa8\xcc\xaa\xc0\xaf\xc0\xad\xc0\xa3\xc0\x9f\xc0]\xc0a\xc0W\xc0S\xc0+\xc0/\x00\xa2\x00\x9e\xc0\xae\xc0\xac\xc0\xa2\xc0\x9e\xc0\\\xc0`\xc0V\xc0R\xc0$\xc0(\x00k\x00j\xc0s\xc0w\x00\xc4\x00\xc3\xc0#\xc0'\x00g\x00@\xc0r\xc0v\x00\xbe\x00\xbd\xc0\n\xc0\x14\x009\x008\x00\x88\x00\x87\xc0\t\xc0\x13\x003\x002\x00E\x00D\x00\x9d\xc0\xa1\xc0\x9d\xc0Q\x00\x9c\xc0\xa0\xc0\x9c\xc0P\x00=\x00\xc0\x00<\x00\xba\x005\x00\x84\x00/\x00A\x00\xff\x01\x00\x00\xae\x00\x0b\x00\x04\x03\x00\x01\x02\x00\n\x00\x04\x00\x02\x00\x17\x00#\x00\x00\x00\x16\x00\x00\x00\x17\x00\x00\x00\r\x000\x00.\x04\x03\x05\x03\x06\x03\x08\x07\x08\x08\x08\t\x08\n\x08\x0b\x08\x04\x08\x05\x08\x06\x04\x01\x05\x01\x06\x01\x03\x03\x02\x03\x03\x01\x02\x01\x03\x02\x02\x02\x04\x02\x05\x02\x06\x02\x00+\x00\t\x08\x03\x04\x03\x03\x03\x02\x03\x01\x00-\x00\x02\x01\x01\x003\x00G\x00E\x00\x17\x00A\x04\xac\x82\x10z=\x8do\x06w\xd1\xc5\x16\xd5\x8e\x8a$!\xb4\xca\xdc\x97hz~{U y\xf9:\xc7\x9f\xe3\xb4\x0e+\xc9\x11\x1f\xe8\xb2\xb6'U\x90\xa2Urf\xa9\xc3\xb6\xd2\xbd\x15\xd4\x94\xd7\xb5|\xbes\t\xef"

Остановился на том что не понятно куда засунуть это client_hello. Пробовал везде, но получаю ошибку ssl.SSLWantReadError: The operation did not complete (read) (_ssl.c:1108)

A: Для теста вот что получилось:
import ssl
import socket

incom = ssl.MemoryBIO()
outcom = ssl.MemoryBIO()

context = ssl.SSLContext(ssl.PROTOCOL_TLS)
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
context.load_cert_chain(certfile="ssl_cert.pem", keyfile="ssl_key.pem")

sslo = context.wrap_bio(incom, outcom, server_side=True)

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('', 8001))
serversocket.listen(1)

(clientsocket, address) = serversocket.accept()

message = b''

while True:
    req = clientsocket.recv(4096)
    incom.write(req)
    try:
        sslo.do_handshake()
        data = sslo.read()
        message += data
        print(data)
        if not data:
            break
    except ssl.SSLWantReadError:
        resp = outcom.read()
        clientsocket.send(resp)

print(message)

Успешно принял сообщения от
cat | socat stdio openssl-connect:127.1:8001,verify=0

Остался вопрос: как понять что соединение готово к передаче?

A: ОТВЕТ ИЗМЕНЁН: ИСПРАВЛЕН КОД ДЛЯ ЧТЕНИЯ ИЗ SSLObject
Соединение считается установленным в тот момент, когда корректно завершается функция do_handshake. Пока идёт handshake, эта функция выбрасывает исключение SSLWantReadError, чтобы сервер догрузил ещё сообщения от клиента.
Процесс отправки данных клиенту состоит из двух частей: шифрования данных и собственно отправки. Шифрует SSLObject.write, шифртекст записывается в исходящий буфер. Достаточно отправить клиенту содержимое этого буфера.
Процесс чтения устроен хитрее. Есть сообщения протокола TLS во входящем сокете, есть сообщения во входящем буфере, есть расшифрованные данные в SSLObject.
Процесс расшифрования запускает метод SSLObject.read(). Данные в протоколе TLS передаются блоками TLS Record, поэтому может быть такая ситуация, что входящий буфер не пуст, но целого блока там нет. В этом случае будет исключение SSLWantReadError - нужно дочитать блок из буфера сокета в буфер SSL.
Кроме того, чисто экспериментально я установил, что SSLObject.read вычерпывает далеко не все данные из входящего буфера, поэтому функция read_from_client читает до тех пор, пока не опустошит весь буфер, либо будет исключение.
import ssl
import socket

incom = ssl.MemoryBIO()
outcom = ssl.MemoryBIO()

context = ssl.SSLContext(ssl.PROTOCOL_TLS)
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
context.load_cert_chain(certfile="cert1.pem", keyfile="privkey1.pem")

sslo = context.wrap_bio(incom, outcom, server_side=True)

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('', 8001))
serversocket.listen(1)

def send_to_client(plaintext):
    sslo.write(plaintext)
    # outcom holds ciphertext
    if outcom.pending > 0:
        resp = outcom.read()
        clientsocket.send(resp)
        print("DEBUG: write: sent {} bytes".format(len(resp)))

def read_from_client():
    plaintext = b''
    while True:
        try:
            data = sslo.read()
            plaintext += data
            if sslo.pending() == 0 and incom.pending == 0:
                # Received all text that was deciphered by now
                return plaintext, None
        except BaseException as err:
            # sslo.read might throw ssl.SSLWantReadException if the chunk
            # of ciphertext is incomplete
            return plaintext, err

(clientsocket, address) = serversocket.accept()
send_greeting = True
message = b''

while True:
    req = clientsocket.recv(4096)
    if len(req) == 0:
        # Connection closed
        break
    print("DEBUG: received ciphertext", len(req))
    incom.write(req)
    try:
        # if handshake is established already, does nothing
        sslo.do_handshake()
        # Handshake is over, `sslo` is ready to read/write
        if send_greeting :
            send_greeting = False
            send_to_client(b'Hello from ssl server.\n')
        data, err = read_from_client()
        message += data
        if err:
            raise err

    except ssl.SSLWantReadError:
        # (outcom.pending == 0) means that we have left some pieces of the ciphertext in
        # the socket. Continue the loop and read it.
        if outcom.pending > 0:
            resp = outcom.read()
            clientsocket.send(resp)
            print("DEBUG: SSLWantReadError: sent {} bytes".format(len(resp)))
    except ssl.SSLWantWriteError:
        # SSL needs more data to produce output
        # Just go to the beginning of the loop and wait for the client
        continue
    except:
        # connection closed?
        break

print("DEBUG: Data left: sslo.pending(), incom.pending, outcom.pending",
    sslo.pending(), incom.pending, outcom.pending)

print("Plaintext received: ", len(message))

Тестировал при помощи s_client:
cat some.log | openssl s_client localhost:8001

Вывод команды s_client:
Hello from ssl server.
DONE

Лог сервера:
DEBUG: received ciphertext 311
DEBUG: SSLWantReadError: sent 1794 bytes
DEBUG: received ciphertext 93
DEBUG: write: sent 294 bytes
DEBUG: received ciphertext 4096
DEBUG: received ciphertext 4096
DEBUG: received ciphertext 4096
DEBUG: received ciphertext 4096
DEBUG: received ciphertext 4096
DEBUG: received ciphertext 4096
DEBUG: received ciphertext 4096
DEBUG: received ciphertext 4096
DEBUG: received ciphertext 4096
DEBUG: received ciphertext 4096
DEBUG: received ciphertext 4096
DEBUG: received ciphertext 4096
DEBUG: received ciphertext 4096
DEBUG: received ciphertext 4096
DEBUG: received ciphertext 1147
DEBUG: Data left: sslo.pending(), incom.pending, outcom.pending 0 0 0
Plaintext received:  58228

s_client напечатал приветствие сервера и переслал весь файл.
Удивительное дело, но тестирование с socat не удалось. socat почему-то не досылает последние 20-с-небольшим байтов тестового лога.
Команда socat open:some.log openssl:localhost:8001,verify=0 зависает. Если процесс прервать, то сервер выдаёт вот какой лог:
DEBUG: received ciphertext 4096
DEBUG: received ciphertext 1124
DEBUG: Data left: sslo.pending(), incom.pending, outcom.pending 0 0 0
Plaintext received:  58205

Видно, что socat не дослал 23 байта по сравнению с s_client. Соответственно, и данные на стороне сервера тоже меньше на 23 байта.


text:
Q: Sufficient Statistics, MLE and Unbiased Estimators of Uniform Type Distribution Let $X_1, \dots, X_n$ denote a random sample of size $n$ from the probability distribution with pdf:
$$ f_X(x\mid\theta_1, \theta_2) = \frac{1}{\theta_2 - \theta_1} \ I(x)_{[\theta_1,\theta_2]} \ I(\theta_1)_{(-\infty,\theta_2)} \ I(\theta_2)_{(\theta_1,\infty)}\;.$$
(1) Find a pair of sufficient statistics for $(\theta_1, \theta_2)$.
${\bf\text{My thoughts:}}$ This wasn't too bad.  I got $(X_{(1)}, X_{(n)})$ for this part
(2) Find the maximum likelihood estimator $(\hat{\theta}_1, \hat{\theta}_2)$ for $(\theta_1, \theta_2)$.
${\bf\text{My thoughts:}}$ Thinking I need to use monotone functions since it has 2 parameters and the variables are part of the interval.  I believe that $\frac{X_{(1)} + X_{(n)}}{2}$ will become one of my estimators.
(3) Show that $\frac{X_{(1)} + X_{(n)}}{2}$ is an unbiased estimator for $\frac{\theta_1 + \theta_2}{2}$.
$\bf{My \ thoughts:}$  I think I will need to use Cramer-Rao Lower Bound in some form but not quite sure if that is right .
(4) Construct an unbiased estimator for $\theta_2 - \theta_1$.
$\bf{My \ thoughts:}$  Very stuck on this part, but I think I can use some information from previous parts to help me.
Any help is greatly appreciated.

A: $(1)$ Correct.
$(2)$ Since the density is $1/(\theta_2-\theta_1)$, the further $\theta_1$ and $\theta_2$ are apart, the lower the probability for obtaining the given data. Thus the maximum likelihood estimate is given by the values of $\theta_1$ and $\theta_2$ that are closest together and compatible with the data, $(\hat\theta_1,\hat\theta_2)=(\def\xa{X_{(1)}}\xa,\def\xb{X_{(n)}}\xb)$.
$(3)$ This is true by symmetry – the expectation is clearly finite, and it can't be anything other than the midpoint since it could then equally well be the value reflected about the midpoint.
$(4)$ Compute the expectation of $\xb-\xa$. This must be linear in $\theta_2-\theta_1$, with the coefficient depending only on $n$, so you can scale $\xb-\xa$ up accordingly to get an unbiased estimator for $\theta_2-\theta_1$.

A: Just to add what joriki said about the problem.
Part 3: Note: you don't want to find the Best Unbiased Estimator. You just want to show that $\frac{x_{(1)}+x_{(n)}}{2}$ is $\bf{AN}$ unbiased estimator. So the CRLB doesn't need to be used, since you're not trying to show that it's the Best Unbiased Estimator.
For part 4: Note: Look at $\theta_{2}-\theta_{1}$. It looks like b-a, right? Well, what estimator looks like an endpoint minus an endpoint?

The Range! :) Range = $X_{(n)}-X_{(1)}$

Hence, why joriki notes that you want to compute the expectation of $x_{(n)}-x_{(1)}$.


text:
Q: I want to solve Mathieu Equation $y''(x)+(a−2q \cos(2x))y(x)=0$. How to solve it using Floquet solution? I want to solve Mathieu Equation $$y''(x)+(a−2q \cos(2x)) \, y(x)=0.$$ How to solve it using Floquet solution? In Floquet solution for integer order of $v$ and $π$ periodicity
We have Solution
$$y(x)=\exp(ivx) \, P(x)$$
I want to know what are the $P(x)$?

A: It is impossible to give a full answer here as this would require to go through a lot of mathematical technicalities (which are in the literature anyhow, see below). As this is a physics site, let me first point out that the Mathieu equation may be viewed, for example, as the Schrödinger equation for a particle in a periodic potential. As such it describes the occurrence of energy bands, relevant for solid state physics.
As the equation is second order, the general solution is actually of the form (allowing for complex argument, $z$)
$$ y(z) = c_1 e^{i\nu z} P(z) + c_2 e^{-i\nu z} P(-z) \; , $$
as long as the Floquet exponent $\nu = \nu (a,q)$ is non-integer. It does become integer for certain characteristic values of $a$, the Mathieu eigenvalues $a_n(q)$ and $b_n(q)$. The curves $a = a_n(q)$ and $a = b_n(q)$, corresponding to integer $\nu$, divide the $(q,a)$ plane into regions of stability ($\nu$ real) and instability ($\nu$ complex). In physics terms, these correspond to energy bands and gaps, respectively.
The standard mathematical online resource for the Mathieu equation is Ch. 28 of the Digital Library of Mathematical Functions. You may also want to look at Ch. 20 of Abramowitz and Stegun, available via its Wikipedia entry.
The most thorough physics discussion I am aware of is in Ch. 17 of Müller-Kirsten's Introduction to Quantum Mechanics. It contains also the weak and strong coupling approximations (small and large $q$, respectively). There has been a very recent renaissance of the Mathieu equation in the context of divergent series and resurgence. The papers arxiv:1401.5202 and arxiv:1502.06680 contain discussions relevant in this context (and much more), including plots of the stability regions/band structure using Mathematica.
The bottom line is that there is no way of understanding the (physics described by the) Mathieu equation without getting one's hands dirty with the somewhat complicated maths involved.


text:
Q: How to run Spark 3.0.0 on HDP (Horthonworks)? Is there a way to run a Spark 3.0 on HDP3 (Horthonworks)?
I'm aware that there is always a standalone option, but I would like to configure YARN as a scheduler.

A: CDP 7.1.3 onwards, you can use Spark3.
https://docs.cloudera.com/cdp-private-cloud-base/7.1.3/cds-3/topics/spark-spark-3-overview.html
Installation Steps:
https://docs.cloudera.com/cdp-private-cloud-base/7.1.3/cds-3/topics/spark-install-spark-3-parcel.html


text:
Q: How to divide a map into circles of a given radius? Folks,
How can I take a state and divide it into areas that are 50 miles in radius?
Perhaps there's a better way to solve my problem: I have a list of 700 locations with unique city names. Some cities are less than 50 miles apart. I need to reduce that list to the minimal number of locations that are no more than 50 miles away and that basically cover the nearby cities in the list. This way I can find the center radius ZIP code of each of the location on the reduced list and then search for "stores within 50 miles", which should return all 700 locations.
Update: I have 5000 products and 700 stores in different cities. I need to check inventory for ALL products. The site where I check it only shows inventory in stores that are within 50 miles of a given city. That mean that I need to make 3,500,000 requests. Hence, I am looking for a way to reduce 700 stores to a smaller number.

A: A simple algorithm which would work but is far from optimal. This starts with a list of candidate towns

*

*Pick a town at random, draw a circle around that point

*Remove all towns inside the circle

*Repeat until there are no towns left

You could run it a few times to see if some runs produce significantly fewer resulting circles.

A: You can concatenate the binary value from the x- and y co-oordinates. Instead of a straight line it orders the points along a z-curve. Then you can compute the upper bounds with the mostsignificant bits. The z-curve is often use in mapping applications:http://msdn.microsoft.com/en-us/library/bb259689.aspx.


text:
Q: Barking up a tree ("barking up the wrong tree") I don't understand expression

barking up a wrong tree

Does it think about putting bark on tree or taking it off?
A person says

you're barking up the wrong tree

and he means

don't bother me

But what is it from?
Does he mean the bark is wrong kind for the tree?
Like "I am oak, take your pine bark!"
In Croation we say the wall is closed meaning you have the wrong wall, have to climb through another with window.
Is that how this means?

A: This well-known phrase is an idiom, part of colloquial (AmE at least) speech, that means:

*

*you are investigating something/gathering information, and

*the action you're currently taking to find information will not help you, and

*you probably don't know this, so that's why someone is telling you this.
Contrived example:

A: Hey Bob, I'm looking for Sally.  (A thinks Bob knows where Sally is)
B: You're barking up the wrong tree, my friend.  She hasn't been around here for months.  (A obviously is not aware that Sally hasn't been around for months)

If you ask someone for information, and they respond with "you are barking up the wrong tree", they are indirectly telling you that they have not been involved whatsoever in what you are asking.  It's not quite equivalent to "don't bother me" - more like "don't bother me because I can't help you get what you want."
Another contrived example:

Police officer: Sally said she talked to you at the restaurant, before she was murdered.  What did she say to you?
Suspect: You're barking up the wrong tree.  I've never been at that restaurant.

A: You have a hunting dog that helps you catch a wild animal. If it climbs up a tree, the dog is supposed to bark at the tree it climbed up. Imagine the situation where the dog is barking at a different (wrong) tree and you would be very disappointed at the dog.

*

*It could mean as a dog:

You are wasting your efforts and energy by pursuing the wrong path. In
  other words, you made the wrong choice.

*As a tree:

You are asking the wrong person. You have to ask somebody else. Leave me
  alone. I am not the tree you want.

The verb bark means the following:

to make the characteristic short loud cry of a dog.

It has nothing to do with the noun bark:

the tough exterior covering of a woody root or stem.

[Merriam-Webster]

A: Here is a dog who is barking:

"Drooker style dog" by Balthazar, licensed CC-BY-SA 3.0
Here is a dog who is barking up a tree:

"Treeing Fiest" by Scochran4, licensed CC-BY 3.0
There is an animal in the tree that the dog wants to catch.
But what if the dog picked the wrong tree? (Maybe the animal jumped into a different tree and the dog didn't see. Maybe the dog didn't see which tree the animal climbed, and guessed wrong.) Then we could say that the dog is barking up the wrong tree.
When you ask someone for information, and they say, "You're barking up the wrong tree," it means, "I don't have the information you want."
This is metaphorically like the dog (you) trying to catch the animal (information) in the tree (person). The dog is barking up some tree, but the animal isn't in that tree. The animal is in a different tree. Similarly, you're looking for information from a person, but that person doesn't have the information. Someone else knows the information you want.

A: Although the other skin of a tree is referred to as it bark, this is not what is meant by

Barking up the wrong tree.

When a dog gives chase to a cat(as an example), it will bark while it frantically runs after the cat.
The cat may run up a tree to escape, leaving the barking dog below.
If the dog gets confused, (s)he may bark at/up a tree with no cat.
This is barking up the wrong tree
Looking for something in the wrong place


text:
Q: php ldap not logging in I have php ldap login page look like this:
<?php
if(isset($_POST['username']) && isset($_POST['password'])){

    $adServer = "ldap://ldap.somedomain.com:389";

    $ldap = ldap_connect($adServer);
    $username = $_POST['username'];
    $password = $_POST['password'];

    $ldaprdn = 'o=mycompany' . "\\" . $username;

    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);

    $bind = @ldap_bind($ldap, $ldaprdn, $password);

    if ($bind) {
        $filter="(sAMAccountName=$username)";
        $result = ldap_search($ldap,"dc=MYDOMAIN,dc=COM",$filter);
        ldap_sort($ldap,$result,"sn");
        $info = ldap_get_entries($ldap, $result);
        for ($i=0; $i<$info["count"]; $i++)
        {
            if($info['count'] > 1)
                break;
            echo "
You are accessing  ". $info[$i]["sn"][0] .", " . $info[$i]["givenname"][0] ."
 (" . $info[$i]["samaccountname"][0] .")
\n";
            echo '
';
            var_dump($info);
            echo '
';
            $userDn = $info[$i]["distinguishedname"][0];
        }
        @ldap_close($ldap);
    } else {
        $msg = "Invalid email address / password";
        echo $msg;
    }

}else{
?>
    <form action="#" method="POST">
        Username: <input id="username" type="text" name="username" />
        Password: <input id="password" type="password" name="password" />        <input type="submit" name="submit" value="Submit" />
    </form>
<?php } ?>

keep getting this error:
Invalid email address / password

I have a java ldap code that is working fine to login to the server:
String oldicnumber;
String newicnumber;
String sn;
String mail;

public boolean userIsValid (HttpServletRequest request, ServletContext application, String userid, String password)
throws java.io.IOException
{
  sainserp_servlet.Logger logger = new sainserp_servlet.Logger(request);

  String url = "ldap://ldap.somedomain.com:389";

  Hashtable environment = new Hashtable();
  environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
  environment.put(Context.PROVIDER_URL, url);

  if (password.equals("")) {
    logger.setPath(2);
    logger.WriteLogFile("Ldap userid: "+userid+"  \t exc: no userid or password apply\n\n");
    return false;
  }
  else {
      try {
                DirContext ctx = new InitialDirContext(environment);
                if (ctx == null ) {
                logger.setPath(2);
                logger.WriteLogFile("Ldap userid: "+userid+"  \t exc: DirContext ctx == null\n\n");
                return false;
                }

                SearchControls constraints = new SearchControls();
                constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
                //search mycompany subtree for uid
                NamingEnumeration results = ctx.search("o=mycompany", "uid=" + userid, constraints);

                if ((results != null) && results.hasMore()) {   //can be found
                SearchResult si = (SearchResult)results.next(); //retrieve results
                environment.put(Context.SECURITY_AUTHENTICATION,"simple");
                environment.put(Context.SECURITY_PRINCIPAL, si.getName()+",o=mycompany");
                environment.put(Context.SECURITY_CREDENTIALS, password);
                DirContext dirctx = new InitialDirContext(environment);
                if (dirctx == null) {
                logger.setPath(1);
                logger.WriteLogFile("Ldap userid: "+userid+"  \t exc: DirContext dirctx == null\n\n");
                return false;
                }
                String[] attrOLDIC = {"oldicnumber"};
                String[] attrNEWIC = {"newicnumber"};
                String[] attrSN = {"sn"};
                String[] attrMAIL = {"mail"};

                Attributes name = dirctx.getAttributes(si.getName()+", o=mycompany", attrSN);
                sn = (String)name.get("sn").get();

                } else {
                logger.setPath(2);
                logger.WriteLogFile("Ldap userid: "+userid+"  \t exc: username not found\n\n");
                        return false;       //username not found
                }
        } catch (Exception e) {
            if (e.toString().indexOf("Invalid Credentials") >= 0) {
        logger.setPath(2);
        logger.WriteLogFile("Ldap userid: "+userid+"  \t Error: Invalid Credentials\n\n");
                return false;
      } else if (e.toString().indexOf("No Such Object") >= 0) {
        logger.setPath(2);
        logger.WriteLogFile("Ldap userid: "+userid+"  \t exc: No Such Object\n\n");
                return false;
      } else {

        logger.setPath(2);
        logger.WriteLogFile("Ldap userid: "+userid+"  \t exc: " + e + "(unknown exception)\n\n");
                return false;
            }
        }
    logger.setPath(2);
    logger.WriteLogFile("Ldap userid: "+userid+"  \t Ldap login success\n\n");
    return true;
  } //end if password = null
} //userIsValid

I am able to to get the true status if I call the java function like this:
userIsValid(request, application, userid, password);
How do I get the php code to work, I think it require to put something like:
environment.put(Context.SECURITY_AUTHENTICATION,"simple");
environment.put(Context.SECURITY_PRINCIPAL, si.getName()+",o=mycompany");

A: manage to sort it by add this at java code
System.out.println("  si.getName() : "+ si.getName());

my php code altered to:
$ldaprdn = "uid=$username,o=Company1,o=Company2";

solved the problem.


text:
Q: pefile How do I nullify the first 8 bytes of a file? How do I nullify the first 8 bytes of a file?
this example does not work:
import pefile
pe = pefile.pe(In)
pe.set_dword_at_rva(0,0)
pe.set_dword_at_rva(0,4)
pe.write(Out)
pe.close()

How i can rename import functions in the file?
this example does not work:
for entry in pe.DIRECTORY_ENTRY_IMPORT:
  print entry.dll
  for imp in entry.imports:
     imp.name = 'NewIMports'
pe.write(Out)

sorry for my english

A: I'd propose to use the standard way (i. e. not using pefile) of doing this:
with file('filename.bla', 'wr+') as f:
  f.write('\0' * 8)

A: You've got multiple problems with your code, but I'm not sure which ones are causing whatever problems you're experiencing (since you haven't explained the problems).
First, you want to set the first 8 bytes to 0, but you're using set_dword_at_rva rather than set_dword_at_offset. An RVA ("Relative Virtual Address") is the offset in memory to the runtime address of a section (whatever that runtime address ends up being). An offset is the offset on disk from the start of the file. If that's what you want, use that. (While you're at it, the qword functions are the way to set 8 bytes at a time. Using dword instead can't cause any problems except for endianness, which can't possibly matter for just setting to 0… but still, why make it harder on yourself?)
So:
pe = pefile.pe(In)
pe.set_qword_at_offset(0, 0)

Meanwhile, if you're modifying arbitrary strings within the file, while pefile can make room for them, it does not adjust any other headers that need to be adjusted to compensate. See "Notes about the write support" in the docs for details. So, imp.name = 'NewIMports' may work, but generate a broken PE, if the old name was shorter.
On top of that, renaming all of the imports to have the same name will definitely generate a broken PE.


text:
Q: PYQT5 Open menu on cursor position in QTextEditor I have a QTextEditor which I would like to open a menu for user to choose when he press Ctrl+Space.
I was able to capture the key events and create the menu and trigger it.
My problem is to open the menu on the text cursor position.
How do i get the QPoint of the textcursor and not the mouse position?

A: QTextEdit.cursorRect returns a rectangle (in viewport coordinates) that includes the cursor.
You're probably imlementing autocompletion/intellisense, it which case I'd recommend using QCompleter instead of QMenu. Take a look at Custom Completer Example.
You can override QTextEdit.keyPressEvent or use eventFilter to capture Ctrl+Space shortcuts and call completer.complete(rect) to show popup.


text:
Q: Specifying window (global) variable type hinting in VSCode from external JS file without typescript This may be a silly question but I really don't know where to look.
I'm creating a browser testing environment for a pretty large-scale API written in typescript. This API uses esbuild to build the typescript files into a /dist/ folder with a single index.js entry-point and its appropriate d.ts file.
I've created a /tests/ folder to hold some browser files that includes an index.html file with Mocha and Chai imported. It also imports /dist/index.js which is set globally to a window.myAPI variable.
In /tests/index.html:
import * as myAPI from "./dist/index.js"

Alongside index.html in the tests folder, there are separate JS files included for different tests that run things on window.myAPI... to do assertion tests.
search.test.js
book.test.js
navigate.test.js

I then run a server to host at the root. These separate tests are then imported from /tests/index.html. The separate tests look like this inside:
const { chai, mocha } = window;
const { assert } = chai;

describe("Search", function() {
    describe("Setup", function() {
        it("Setting URL should work", function() {
            const call = myAPI.someCall()
            assert.ok(call);
        });
    });
});

mocha.run();

Everything works, but I have no code hinting for myAPI. I'd like to be able to see what functions are available when I type myAPI, and what parameters they take, and what they should return - along with all my comments on each function.
In typescript you can do things like ambient declarations, but I don't want to make my tests typescript because then I add an unnecessary build step to the tests. But it would be as easy as:
/// <reference path = "/dist/index.d.ts" />

How can I tell VSCode that window.myAPI is an import of /dist/index.js and should import the types as well so I can see them ?
I'm open to different solutions to this, but I feel like this should be pretty simple. I don't know if ESLint is capable of doing something like this, but I tagged it because I feel it's relevant.
Thanks!


text:
Q: "required from here" when using Eigen library I am implementing some control algorithms in Eclipse C++ using the Eigen library. When I want to calculate the eigenvalues for example of a matrix, I get "required from here" warning as an exclamation mark beside the line of code. And I have no idea how to solve it.
This is my main.cpp file:
#include <iostream>
#include "System.h"
#include "ControllerCode2.h"

using namespace std;

int main(){

    int n = 3;   // # of states
    int m = 1;   // # of inputs
    int l = 1;   // # of outputs

    MatrixXd A(n, n), B(n,m), C(l,n), D(l,m), Q(n,n), R(m,m), Qe(n,n), Re(m,m);

    A << 0,  1,  0,
         0,  0,  1,
         0, -2, -3;

    B << 0,
         0,
         1;

    C << 1, 0, 0;

    D << 0;

    MatrixXd C_trans = C.transpose();
    Q = C_trans * C;
    R =  MatrixXd::Identity(m, m); // initially

    MatrixXd B_trans = B.transpose();
    Qe = B * B_trans;
    Re =  MatrixXd::Identity(m, m); // initially

    System sys = System(A, B, C, D);

    sys.set_covariance_matrices(R, Q);
    sys.set_noise_covariance_matrices(Re, Qe);
    schur_eigen_test(sys);

    return 5;
}

Now, the ControllerCode2.cpp code:
#include "ControllerCode2.h"

MatrixXd U11;
MatrixXd U21;

void schur_eigen_test( System G ){
    /****** Constructing the Hamiltonian Matrix ******/
    int n = G.A.rows();
    MatrixXd H(2*n, 2*n);          // the Hamiltonian matrix has the dimensions of 2n*2n where n is the number of states
    H.block(0,0,n,n)      = G.A;
    H.block(0,n,n,n)      = -1 * G.B * G.R.inverse() * G.B.transpose();
    H.block(n,0,n,n)      = -1 * G.Q;
    H.block(n,n,n,n)      = -1 * G.A.transpose();

    /****** Performing a real Schur decomposition on the square Hamiltonian matrix ******/
    RealSchur<MatrixXd> schur(H);
    MatrixXd U = schur.matrixU(); //The orthogonal matrix U
    MatrixXd T = schur.matrixT(); //The quasi-triangular matrix T

    /****** Find the eigenvalues and eigenvectors of the Hamiltonian matrix ******/
    EigenSolver<MatrixXd> H_eigen;        // create an EigenSolver Matrix
    H_eigen.compute(H, false);            // compute the eigenvalues ./and eigenvectors of matrix H
    MatrixXd H_eigenval = H_eigen.eigenvalues();
    //              //MatrixXd H_eigenvec = H_eigen.eigenvectors();

    /****** Select the eigenvectors (U11, U21) corresponding to the stable (with -ve real part) eigenvalues ******/
    U11 = U.block(0,0,n,n);
    U21 = U.block(n,0,n,n);

    /****** Calculate F ******/
    MatrixXd F = -1 * G.R.inverse() * G.B.transpose() * U21 * U11.inverse(); // transposeInPlace or transpose??

    //////// Extra: for output
    cout << endl << "H = " << endl << H << endl;
    cout << endl << "U schur(H) " << endl << U << endl;
    cout << endl << "T schur(H) " << endl << T << endl;
    cout << endl << "U*T*U.transpose() " << endl << U * T * U.transpose();

    //      cout << endl << "U.transpose() - U.inverse() " << endl << U.transpose() - U.inverse(); // = which proves that U is orthogonal, i.e. U.transpose() = U.inverse()
    //      EigenSolver<MatrixXd> H_eigen;        // create an EigenSolver Matrix
    //      H_eigen.compute(H, false);            // compute the eigenvalues and eigenvectors of matrix H
    //      MatrixXd H_eigenval = H_eigen.eigenvalues();
    //      cout << endl << "eigenvalues of H = " << endl << H_eigenval << endl;
}

I get the warning beside this line:
MatrixXd H_eigenval = H_eigen.eigenvalues();

my ControllerCode2.h code:
#ifndef CONTROLLERCODE_H_
#define CONTROLLERCODE_H_

#include "System.h"

    void schur_eigen_test( System );

//};

#endif /* CONTROLLERCODE_H_ */

System.h code:
// include guard
#ifndef SYSTEM_H_
#define SYSTEM_H_

#include <Eigen/Dense>
#include <iostream>
#include <Eigen/Eigenvalues>
#include <iostream>

using namespace Eigen;
using namespace std;
using Eigen::MatrixXd;

class System {

public:

    MatrixXd A;
    MatrixXd B;
    MatrixXd C;
    MatrixXd D;
    MatrixXd Q;
    MatrixXd R;
    MatrixXd Re;
    MatrixXd Qe;

    System(MatrixXd a, MatrixXd b, MatrixXd c, MatrixXd d){
        A = a;
        B = b;
        C = c;
        D = d;
        //cout << A << endl << B << endl << C << endl;
    };

    void set_covariance_matrices(MatrixXd r, MatrixXd q){
        R = r;
        Q = q;
        //cout << R << endl << Q << endl;
    }

    void set_noise_covariance_matrices(MatrixXd re, MatrixXd qe){
        Re = re;
        Qe = qe;
        //cout << Re << endl << Qe << endl;
    }

    virtual ~System();

    // this function receives the 4 state space matrices and returns one plant matrix G
    MatrixXd setContSys(MatrixXd a, MatrixXd b, MatrixXd c, MatrixXd d);

};

#endif /* SYSTEM_H_ */

and finally this is the result shown in the console:
15:12:51 **** Incremental Build of configuration Debug for project Controller ****
Info: Internal Builder is used for build
g++ "-IC:\\Users\\Alsharif\\eigen" -O0 -g3 -Wall -c -fmessage-length=0 -o ControllerCode2.o "..\\ControllerCode2.cpp"
In file included from C:\Users\Alsharif\eigen/Eigen/Core:285:0,
                 from C:\Users\Alsharif\eigen/Eigen/Dense:1,
                 from ..\System.h:12,
                 from ..\ControllerCode2.h:11,
                 from ..\ControllerCode2.cpp:8:
C:\Users\Alsharif\eigen/Eigen/src/Core/Matrix.h: In instantiation of 'Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>::Matrix(const Eigen::MatrixBase<OtherDerived>&) [with OtherDerived = Eigen::Matrix<std::complex<double>, -1, 1>; _Scalar = double; int _Rows = -1; int _Cols = -1; int _Options = 0; int _MaxRows = -1; int _MaxCols = -1]':
..\ControllerCode2.cpp:220:45:   required from here
C:\Users\Alsharif\eigen/Eigen/src/Core/util/StaticAssert.h:115:9: error: 'YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY' is not a member of 'Eigen::internal::static_assertion<false>'
         if (Eigen::internal::static_assertion<static_cast<bool>(CONDITION)>::MSG) {}
         ^
C:\Users\Alsharif\eigen/Eigen/src/Core/Matrix.h:326:7: note: in expansion of macro 'EIGEN_STATIC_ASSERT'
       EIGEN_STATIC_ASSERT((internal::is_same<Scalar, typename OtherDerived::Scalar>::value),
       ^

15:12:55 Build Finished (took 4s.567ms)

A: So you got a static assert: YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY.
I'm not expert in Eigen, but I see that eigenvalues() returns const EigenvalueType& which is a different matrix type, not the one you use to instantiate EigenSolver (that is MatrixXd in your case).
So you should use correct type, or cast the matrix explicitly, that is what static assert says.


text:
Q: django TypeError: 'coroutine' object is not iterable Here is the code snippet.
I am fetching data from fatabase asynchronusly.
but, I am getting below error
            for contract in contracts:
            TypeError: 'coroutine' object is not iterable

    @sync_to_async
    def get_all_contract_objects():
        return EthereumContract.objects.all()

    def compute_topics_to_eventabis() -> Dict:
        "Loop through all contracts in our DB and compute topics to ABI mapping"
        topics_to_event_abis = {}
        contracts = get_all_contract_objects()
        for contract in contracts:
            print(contract)
        return topics_to_event_abis

This part only need to fix. so that i can loop over contracts and print it.


text:
Q: Finding missing translations in django `.po` files Working with Django, you can use django.utils.translation.ugettext and ....ugettext_lazy (as well as some template tags) to handle translation of localized messages.
Later, with command: django-admin.py makemessages -l <LANGUAGE> you can generate the po file containing the original string, so that the developer can specify the desired translation.
Question: is there a django command, or any other quick way, to find out which messages have not been translated?
Usually I look for the string msgstr "" in the po file, but that's inaccurate, since some translations are multiline, like the following:
#file.py:xyz
msgid ""
"Some very long text"
msgstr ""
"The translation of some very long text"

Thus, looking for msgstr "" I get "false positives" (i.e. strings that are actually translated, but whose translation start the next line). With thousand of lines, this quite often.
Any smart suggestion?
Thanks

A: Assuming you are using some popular editors:

*

*in most editors, simply search msgstr ""\n\n

*under windows / with notepad, maybe you will need something like msgstr ""\r\n\r\n

*you could also try some specialized editors, check this

*ultimatively, you could do the following: sed -i '/msgstr ""/{N;N; s/\n\n/\n# translate me!\n\n/g}' django.po and then search for # translate me! comments in the file.

A: You can use
msgfmt --statistics --output=/dev/null locale/django.po

to see how many missing translations there are (if any), and
msgattrib --untranslated locale/fr/LC_MESSAGES/django.po

to list the untranslated messages.

A: The easiest way to check for missing translations, and other errors, would be to use the "msgcmp" utility. It's actually supposed to be used to compare a translations file (.po) against a template (.pot), but it's perfectly happy to compare a .po file against itself:
msgcmp path/to/nl.po path/to/nl.po

will do the trick, and even fail if any translations are marked as fuzzy (unless you specify --use-fuzzy).


text:
Q: Unity www.uploadProgress jumps from 0 to 100 in build but works fine on editor all!
Im trying to monitor the progress of the file I'm uploading. In Unity editor, it works fine. You can it climb from 0 to 100. But when I build it on my phone, it goes from 0 straight to 100.
Here is my code
WWWForm form = new WWWForm();
form.AddBinaryData("image", image_bytes);
using (UnityWebRequest www = UnityWebRequest.Post("mylink.com/post", form))
{
   www.SendWebRequest();
   while (!www.isDone)
   {
       float progress = Mathf.Clamp01(www.uploadProgress / 0.9f)
       progress = Mathf.Round(progress * 100);
       Debug.Log("Upload Progress : " + progress + "%");
       yield return null;
   }

   Debug.Log("Success");
}


text:
Q: Given $a_1=1$ and $ a_{n+1}=a_n + 1 +\frac{a_n}{a_{n+1}}$ prove $\lim\limits_{n\to\infty }( a_{n+1} - a_n)=2$ Given a sequence $(a_n)_{n\geq 1}$  such that $a_1=1$ and $ a_{n+1}=a_n + 1 +\frac{a_n}{a_{n+1}}$ where $ n\geq1$
prove that $\lim\limits_{n\to\infty }( a_{n+1} - a_n)=2$
I tried to prove that $a_n$ is increasing but it I just can't get around to it.  Thank you in advance!

A: Let's address first the necessity that $a_n \geq \frac{1}{2}$ for any $n$ so that the sequence is well defined. Suppose that $a_n \geq \frac{1}{2}$, then there are two options for $a_{n+1}$:
$$a_{n+1}=\frac{1}{2}(1+a_n\pm \sqrt{a_n^2+6a_n+1})$$
The positive option is good and it satisfies $a_{n+1}\geq \frac{1}{2}$. Now, let's prove that if we choose $a_{n+1}=\frac{1}{2}(1+a_n- \sqrt{a_n^2+6a_n+1})$, then $a_{n+2}$ won't be defined anymore. We have:
$$a_{n+2}-a_{n+2}(a_{n+1}+1)-a_{n+1}=0$$
and the discriminant is:
$$\Delta = a_{n+1}^2+6a_{n+1}+1=a_{n+1}(a_n+1)+a_n+6a_{n+1}+1=a_{n+1}(7+a_n)+a_n+1$$
$$=\frac{1}{2}\left[(a_n+1)(a_n+9)-(a_n+7)\sqrt{a_n^2+6a_n+1}\right]$$
We are going to prove that this discriminant is negative:
$$(a_n+1)(a_n+9)<(a_n+7)\sqrt{a_n^2+6a_n+1}$$
After squaring and expanding, this simplifies to:
$$a_n^2+8a_n >2$$
which is true since $a_n \geq \frac{1}{2}$. Now, that we have proved we always have to choose the option greater than $\frac{1}{2}$, we can start proving the question.
Since we established we must have $a_n\geq \frac{1}{2}$ for any $n$, from the recurrence formula, $a_n$ is increasing and:
$$a_{n+1}-a_n=1+\frac{a_n}{a_{n+1}} < 2$$
therefore the sequence $a_{n+1}-a_n$ is bounded. Also
$$a_{n+1}^2 = a_{n+1}a_n +a_{n+1}+a_{n} \geq a_{n+1}a_n+2a_{n} = a_n(a_{n+1}+2) > a_na_{n+2}$$
This implies that
$$(a_{n+2}-a_{n+1})-(a_{n+1}-a_n) = \frac{a_{n+1}^2-a_na_{n+2}}{a_{n+1}a_{n+2}} > 0$$
the sequnce $a_{n+1}-a_n$ is bounded and increasing (thus convergent) and $\frac{a_n}{a_{n+1}}$ is also bounded above by $1$ and increasing (it converges to $1$). Therefore:
$$\lim_{n \to \infty} (a_{n+1}-a_{n}) = 1+\lim_{n \to \infty} \frac{a_n}{a_{n+1}} = 2$$

A: Solving the given recursion for $a_{n+1}$ gives
$$a_1=1,\qquad a_{n+1}=f(a_n)\quad(n\geq1)$$
with
$$f(x)={1\over2}\bigl(1+x+\sqrt{x^2+6x+1}\,\bigr)$$
(Atticus has shown that we have to choose the $+$-solution in order to avoid complex $a_n$). It follows that
$$f(x)-x={1\over2}+{1\over2}\bigl(\sqrt{x^2+6x+1}-x\bigr)={1\over2}+{1\over2}{6+{1\over x}\over\sqrt{1+{6\over x}+{1\over x^2}}+1}>{1\over2}\ .$$
This shows that $a_{n+1}-a_n>{1\over2}$ for all $n\geq1$; hence $\lim_{n\to\infty} a_n=\infty$. As a consequence we also have
$$\lim_{n\to\infty}(a_{n+1}-a_n)=\lim_{n\to\infty}\bigl(f(a_n)-a_n\bigr))=\lim_{x\to\infty}\bigl(f(x)-x\bigr)=2\ .$$

A: We first need to show $\{a_n\}$ is an increasing sequence, and the argument of this part could adopt the proof above by Prof. Blatter. Once this is overcome, then $a_n > 0$ for all $n \ge 1$. Next ,  $a_{n} = (a_n - a_{n-1})+ (a_{n-1} - a_{n-2}) +...=(a_2 -a_1) + a_1 = (1+\dfrac{a_{n-1}}{a_n})+ (1 + \dfrac{a_{n-2}}{a_{n-1}}) + (1 + \dfrac{a_1}{a_2}) + a_1 > (n-1)+1 = n$. Thus we have: $ 1< \dfrac{a_{n+1}}{a_n}  = 1 + \dfrac{1}{a_n} + \dfrac{1}{a_{n+1}} < 1+\dfrac{1}{n}+\dfrac{1}{n+1}$ and this shows $\dfrac{a_{n+1}}{a_n} \to 1$ as $n \to \infty$. This implies $a_{n+1} - a_{n} = 1 + \dfrac{a_n}{a_{n+1}}\to 1+1 = 2$ as claimed.

A: So for given $a_n$, the next term $a_{n+1}$ is one of the roots of
$$X^2-(a_n+1)X-a_n, $$
i.e.,
$$\tag1\begin{align}a_{n+1}&=\frac{a_n+1\pm\sqrt{(a_n+1)^2+4a_n}}{2}\\&=\frac{a_n+1\pm\sqrt{(a_n+3)^2-8}}{2},\end{align}$$
which unfortunately gives us two choices. But there are some restrictions: As we (seem to) want a sequence of real numbers, we must have $(a_n+3)^2\ge 8$ for all $n$, i.e., $$\tag2a_n\ge 2\sqrt 2-3\approx -0.17\quad \text{or}\quad a_n\le -2\sqrt 2-3\approx -5.8.$$
If $a_n>0$ and we take the plus-branch in $(1)$, then we have $a_{n+1}\ge a_n+1$ from the first line in $(1)$.
As long as we take the plus-branch throughout, we thus find that $a_n\ge n$.
Assume we do not always take the plus-branch in $(1)$ and let $n$ be the first time we take the minus-branch. Then $$ \begin{align}a_{n+1}&=\frac{a_n+1-\sqrt{(a_n+3)^2-8}}2\\&=\frac{(a_n+1)^2-(a_n+3)^3+8}{2(a_n+1+\sqrt{(a_n+3)^2-8})}\\
&=\frac{-4a_n}{2(a_n+1+\sqrt{(a_n+3)^2-8})}\\
&<\frac{-4a_n}{2(a_n+1+\sqrt{(a_n+3)^2})}\\
&=-1+\frac{2}{a_n+2}\\&\le -1+\frac2{n+2}\\&\le -\frac13\\&<2\sqrt 2-3,\end{align}$$
contradicting $(2)$.
We conclude that we always take the plus-branch, i.e.,
$$a_{n+1}=\frac{a_n+1+\sqrt{(a_n+3)^2-8}}{2}$$
and (as seen above)
$$ a_n\ge n.$$
Now
$$\begin{align}a_{n+1}-a_n&=\frac{1-a_n+\sqrt{(a_n+3)^2-8}}2\\
&= 2+\frac{\sqrt{(a_n+3)^2-8}-(a_n+3)}2\\
&=2-\frac{4}{\sqrt{(a_n+3)^2-8}+(a_n+3)}\end{align}$$
and as $a_n\to\infty$, the desired result follows.


text:
Q: Ios Emulator for Windows for flutter I am working on flutter development.
I want to test my created ios application in emulator on Windows laptop is there any solution.

A: Nope ;)
If you dev for iOS / MacOS target, you need to be on Mac.
iOS / MacOS building need:

*

*MacOS

*XCode (with cli tools)


text:
Q: What is the difference between different display standards? I'm looking at my shiny new PC's GPU and Motherboard, and I can see in the motherboard 2 display adapters (DVI-D and VGA) whilst on the GPU I can see 5 (4 HDMI and 1 DVI-D). What is the difference between the 3 standards, VGA, DVI-D and HDMI (aside from the cable)?

A: VGA: is purely analog: low resolution, low quality
DVI: is the first digital standard, the digital value in the graphics card is passed to the display, which takes care of displaying it. DVI-D is transports only digital data. DVI-A only analog data (useless), DVI-I both.
HDMI: this is the digital standard for home entertainment industry devices, blue-ray players, tv's and so on. Graphics cards have learned to use this after having used DVI for some time. It's a better format than  DVI, as it can include sound and networking data
Display Port: Comes after HDMI, at least for PC's as it has a higher bandwidth for more monitors (daisy chaining them), which isn't really a requirement for home entertainment equipment.


text:
Q: Eslint not recognizing Reflect I'm using Reflect in my code. Problem is Eslint thinks its an undeclared variable. I'm getting this error:
eslint --config ./.eslintrc.json src

30:25  error  'Reflect' is not defined  no-undef
32:9   error  'Reflect' is not defined  no-undef
39:21  error  'Reflect' is not defined  no-undef
40:5   error  'Reflect' is not defined  no-undef

I have my .eslintrc file set to ECMAScript 2015:
"parserOptions": {
    "ecmaVersion": 2015,
    "sourceType": "module",
    "ecmaFeatures": {
      "globalReturn": true
    }
  }

Not sure why it's applying the no-undef rule to Reflect. All my code is typically ECMAScript 2015, nothing unusual.

A: In addition to setting the ecmaVersion, you need to tell it to include "es6" globals:
{
    "env": {
        "es6": true
    }
}

(You'll probably want others in there too, such as browser.)
More in Specifying Environments in the docs.


text:
Q: Asp.net session expire very soon I get this message too often and think that it is not usual, how i can fix this issue?

A worker process with process id of '8052' serving application pool 'mywebsite.com' has requested a recycle because it reached its private
  bytes memory limit.

A: Hi this is not an expire because of a timeout, it's an application pool recycle due to memory limit. Usually very bad.
if you have full control of your ASP.NET application I suggest you profile it carefully and detect where you are allocating and not releasing / disposing a lot of memory.
It might help to understand what are the common use cases users are going through more often and start investigating those.
Are you loading a lot of byte[] in memory for file downloads?
are yoou keeping too many references in the Session?
once we had a similar problem and we found out only after several weeks that we were storing a reference to pages in the Session so all visited pages were kept in memory all the times. Not easy to find but once we corrected this the problem was solved.

A: You probably have a memory leak. There are many possible causes, possibly session or request instances registered with static events. Operations that are trying to load too much data into memory, session timeouts set too long etc.
You need to do some profiling to identify the cause.
Of course its also possible you just don't enough memory for the number of users and need to scale, but it's highly unlikely unless you have a lot of traffic.

A: Maybe your application use a lot of memory? Regarding to this post you have reached allowed memory size for application and IIS restarts the application pool.


text:
Q: Why times elapsed connecting to a server are different? I have a small program which connects to a server of my choice and measures the time elapsed to do so. Each time I run it it returns different result. My question is what does this time depend on ?
Network congestion for one.
If I choose a server that has multiple addresses e.g. google.com the length of physical link may differ from time to time ? Is it safe to assume that it also affects connection time ?
Are there any other factors in place ?

A: When it comes to network speeds, there are a lot of factors.  Distance, latency, bandwidth, congestion, route, etc.  Any one factor can be a bottleneck.  Then there is the device/server itself.  It can be overloaded with traffic, busy doing other requests, etc...

A: You might want to read about how Internet works and how packet switching works to add to the explanation here.
But for now, lets assume things are purely between your PC, to a very specific host server that you have the IP address.
The way packet switching works is "try our best" to send packets to the destination.
If for whatever reason the switches/routers between your PC and the server has issues (too much traffic on it, or it dies) it will simply try to route the packet using different route. The same request may ends up coming through multiple different routes just because it happens to be the better route 'at that time'.
Or if the router/switch that your packet arrives to is too busy, that router WILL drop your packets, and send a confirmation to your PC that they dropped it. Your PC will then re-send the packet, hoping it will arrive. (This whole process is completely transparent and you won't see it unless you know what you are doing / looking for)
Different physical link will definitely affect time elapsed, not only because you may be not on the most straight-line route, but also, maybe the straight-line route is highly congested and you may ends up faster using the route going round the world first.
For comparison, imagine you are driving your car from A to B. Same driving speed, same road, you still end up with different time elapsed due to network congestion. Then one day you decided to use different road. The smaller road, the backroad, the highway, you name it. You may arrive faster / slower - you really don't know. You may have an 'average' time, but the time elapsed will still be different.
Hope this helps.