text:
Q: C++ decimal arithmetic libraries I'm fairly new to adding additional libraries to Visual Studio (2013) as well as the idea that floats and doubles are usually not accurate enough when dealing with certain things like money.  I originally thought that BOOST::Multiprecision cpp_dec_float would solve this problem but as I tested it I noticed some unusually things and realized that I could be wrong.  for example,
cpp_dec_float_50 decimal = 0.45;
double dbl = 0.45; //for comparison

cout << fixed << setprecision(50) << "boost:    " << decimal << endl;
cout << "double:  " << dbl << endl;

would give results like this
boost:    0.45000000000000001110223024625156540423631668090820
double:   0.45000000000000001000000000000000000000000000000000

instead of what I expected (0.45000000000000000000000000000000000000000000000000).
is this not going to be much more accurate than just using floats or doubles?  If not, I'm assuming the boost library I just linked to my VS2013 has an arbitrary integer type, would this be acceptable? the only thing I don't like about using integers for such a thing is that I'd probably have to convert interest rates into integers before multiplying it with currency which would likely result in a very, very large number which may or may not cause performance issues.
(assuming BOOST isn't what I need) what are your thoughts on Intel's Decimal Floating-Point Library? I couldn't get it to work (yet) so I'm wondering if it is worth the effort. Are there any other similar libraries worth checking out?

A: So, you're assigning a number (that is already in floating point) to your decimal variable. So the error that you are concerned about has already been introduced.
Instead, let's assign it with a string containing the correct number:
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
using namespace std;
using boost::multiprecision::cpp_dec_float_50;

int main() {
    cpp_dec_float_50 decimal("0.45");
    double dbl = 0.45; //for comparison

    cout << fixed << setprecision(50) << "boost:   " << decimal << endl;
    cout << "double:  " << dbl << endl;
}

Which outputs:
boost:   0.45000000000000000000000000000000000000000000000000
double:  0.45000000000000001110223024625156540423631668090820

A: Use Python:
import decimal

d = decimal.Decimal("0.45")

print(d)

outputs 0.45.


text:
Q: Python with Visual Studio Code on Mac Trying to figure out Python with Visual Studio on Mac. Dependencies and Libraries don't seem to install/launch correctly.
For example, I have pandas on my system, installed via pip, and if I do
import pandas as pd

from a Python prompt, it works fine.
With Visual Studio Code, if I create a file with the above code, autocomplete recognizes that pandas is installed

When I try to run, I get an ImportError: No module named pandas

Any ideas?
Update: It works in VSCode's terminal, just not when I run the code in the debugger.

A: Laurence Moroney is right -- this issue occurs when VS Code is using a Python interpreter different from the one that has your libraries installed.
See Configuring Python Environments for instructions on changing the interpreter globally in VS Code. Don't forget to restart VS Code afterwards.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Best way to have a background full window So I have this site here http://jamessuske.com/freelance/seasons/
and as you can see the background is the full and there will be a different background for each page.
So in my index.php I have this code:
<?php include('include/header.php'); ?>

In my header.php file I have this:

Site One

Site Two

But I cant see the sitebar div at all: below is my css
body{
    background-color:#000;
    margin:0;
    padding:0;
}

#bg {
    position: fixed;
    top: 0;
    left: 0;
}

.bgwidth {
    width: 100%;
}

.bgheight {
    height: 100%;
}

.sitebar{
    position:relative;
    width:100%;
    background-color:#000;
    height:30px;
}

and I tried setting z-index of 1000 on sitebar and 999 on background, but that didn't work.
So I am guess this may not be the best way to have background at full screen as anything else I put on the page doesn't appear. Any suggestions?
Here is some jQuery that helped get the background at full screen..

If I put the sidebar below the image and set the position to relative that works, but I would prefer to have the sitebar above the image.

A: Add this to your css
.sitebar {position:absolute; z-index:999;}


text:
Q: How can I get a proper double form for a symbolic matrix? How can I get a proper double form from this symbolic Matrix in MatLab? I've tried everything but I prefer not using feval or inline function as they're not recommended
This is the code to get the matrix
function T = Romberg (a, b, m, f)

T = zeros(m, m);
T = sym(T);

syms f(x) c h;

f(x) = f;

c = (subs(f,a)+subs(f,b)) / 2;

h = b - a;

T(1,1) = h * c;

som = 0 ;

n = 2;

for i = 2 : m

    h = h / 2;

    for r = 1 : n/2

        som = som + subs(f,(a + 2*(r-1)*h));

        T(i,1) = h * (c + som);

        n = 2*n;

    end

end

r = 1;

for j = 2 : m

    r = 4*r;

    for i = j : m

        T(i,j) = (r * T(i, j-1) - T(i-1,j-1)/(r-1));
    end

end

end

And with an input like this
Romberg(0, 1, 4, '2*x')

I get a symbolic matrix output with all the
3 * f(3)/2 + f(1)/2 + f(5)/2

I would like to have a double output.
Can you please help me?
Thank you very much in advance!


text:
Q: Is it possible to convert lowercase to uppercase AND remove accents in the same function using PHP? I´m writting a PHP code where $posted_data['name'] is my variable.
In order to convert it to UPPERCASE letters, I´m using the following: (which is working pretty well)
$uppercase = $posted_data['name'];
$uppercase = strtoupper($uppercase);

However I´m willing to know if is it possible to implement in the same line another function the letter accentuation removal or a clean up way to do it.
E.g.:
User´s String input: João
String output: JOAO
So, there are two functions running here in this desired situation:  one to convert from lowercase to uppercase and the other one removing the accents.

A: There's some magic in here where it converts the diacritical marks to non-diacritical characters and then converts the letters to uppercase.
<?php

function slug($string) {
    return strtoupper(trim(preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_QUOTES, 'UTF-8')), ' '));
}

$string = 'João';
echo slug($string);

Demo
Here's the same example broken down into separate lines for each function call to make how it works clearer:
function slug($string) {
    $str = htmlentities($string, ENT_QUOTES, 'UTF-8');
    $str = preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', $str);
    $str = trim($str, ' ');
    return strtoupper($str);
}

A: PHPs unicode support (ext/intl) can do that in a single call:
$string = 'Hello ÄöÜ!';
var_dump(
    \Transliterator::create('Any-Upper; Latin-ASCII')->transliterate($string)
);

Output:
string(10) "HELLO AOU!"


text:
Q: Django MPTT Postgres update query runs slowly I'm using mptt in a model to manage a tagging system (each tag has an optional TreeForeignKey to a 'parent' tag)
Whenever I need to save a tag model, the following query runs exceptionally slow (upwards of 45 seconds)
 UPDATE "taxonomy_taxonomy" SET "tree_id" = ("taxonomy_taxonomy"."tree_id" + %s) WHERE "taxonomy_taxonomy"."tree_id" > %s

I send the content of articles through an automated tagging system, which can generate upwards of 20 tags. Obviously, that won't fly :)
I added the db_index=False hoping to change write times (reads don't seem to be a problem) but the problem persists.
Here's the model in question:
class Taxonomy(MPTTModel):

parent = TreeForeignKey('self',blank=True,null=True,related_name='children',verbose_name='Parent', db_index=False)
parent_name = models.CharField(max_length=64, blank=True, null=True, editable=False)
name = models.CharField(verbose_name='Title', max_length=100, db_index=True)
slug = models.SlugField(verbose_name='Slug', blank=True)
primary = models.BooleanField(
    verbose_name='Is Primary',
    default=False,
    db_index=True,
)
type = models.CharField(max_length=30, db_index=True)
created_date = models.DateTimeField(auto_now_add=True, null=True)
updated_date = models.DateTimeField(auto_now=True, null=True)
publication_date = models.DateTimeField(null=True, blank=True)
scheduled_date = models.DateTimeField(null=True, blank=True)
workflowstate = models.CharField(max_length=30, default='draft')
created_by = models.ForeignKey(User, null=True)

paid_content = models.BooleanField(verbose_name='Is Behind the Paywall', default=False, blank=True)
publish_now = True
show_preview = False
temporary = models.BooleanField(default=False)

def save(self, *args, **kwargs):

    if self.slug is None:
        self.slug = self.name

    if not self.slug:
        self.slug = slugify(self.name)[:50]

    if self.parent:
        self.parent_name = self.parent.name

    self.slug = slugify(self.slug)
    self.workflowstate = "published"

    super(Taxonomy, self).save(*args, **kwargs)

    store_to_backend_mongo(self)
    publish_to_frontend(self)

And the query plan (as reported by New Relic):
1) Update on taxonomy_taxonomy (cost=0.00..133833.19 rows=90515 width=139)

2) -> Seq Scan on taxonomy_taxonomy (cost=0.00..133833.19 rows=90515 width=139)

3) Filter: ?

Finally, the traceback from such a query:
    Traceback (most recent call last):
File "/data/www/nj-cms/venv/lib/python3.4/site-packages/newrelic-2.54.0.41/newrelic/api/web_transaction.py", line 711, in __iter__
File "/data/www/nj-cms/venv/lib/python3.4/site-packages/newrelic-2.54.0.41/newrelic/api/web_transaction.py", line 1087, in __call__
File "/data/www/nj-cms/venv/lib/python3.4/site-packages/django/core/handlers/wsgi.py", line 189, in __call__
File "/data/www/nj-cms/venv/lib/python3.4/site-packages/django/core/handlers/base.py", line 132, in get_response
File "/data/www/nj-cms/venv/lib/python3.4/site-packages/newrelic-2.54.0.41/newrelic/hooks/framework_django.py", line 499, in wrapper
File "/data/www/nj-cms/venv/lib/python3.4/site-packages/django/contrib/auth/decorators.py", line 22, in _wrapped_view
File "./editorial/views.py", line 242, in calculate_queryly
File "./editorial/views.py", line 292, in queryly_function
File "/data/www/nj-cms/venv/lib/python3.4/site-packages/django/db/models/manager.py", line 127, in manager_method
File "/data/www/nj-cms/venv/lib/python3.4/site-packages/django/db/models/query.py", line 348, in create
File "./taxonomy/models.py", line 179, in save
File "./taxonomy/models.py", line 58, in save
File "/data/www/nj-cms/venv/lib/python3.4/site-packages/mptt/models.py", line 946, in save
File "/data/www/nj-cms/venv/lib/python3.4/site-packages/mptt/models.py", line 702, in insert_at
File "/data/www/nj-cms/venv/lib/python3.4/site-packages/mptt/managers.py", line 467, in insert_node
File "/data/www/nj-cms/venv/lib/python3.4/site-packages/mptt/managers.py", line 491, in insert_node
File "/data/www/nj-cms/venv/lib/python3.4/site-packages/mptt/managers.py", line 726, in _create_tree_space
File "/data/www/nj-cms/venv/lib/python3.4/site-packages/mptt/managers.py", line 364, in _mptt_update
File "/data/www/nj-cms/venv/lib/python3.4/site-packages/django/db/models/query.py", line 563, in update
File "/data/www/nj-cms/venv/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 1062, in execute_sql
File "/data/www/nj-cms/venv/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 840, in execute_sql
File "/data/www/nj-cms/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 79, in execute
File "/data/www/nj-cms/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
File "/data/www/nj-cms/venv/lib/python3.4/site-packages/newrelic-2.54.0.41/newrelic/hooks/database_dbapi2.py", line 22, in execute

Any idea how I can get these model saves to be speedier?
EDIT for further info:
This is in Postgres, with the psycopg2 engine
'ENGINE': 'django.db.backends.postgresql_psycopg2',
SECOND EDIT:
As requested, I ran the query with EXPLAIN ANALYZE. The result is as follows:
nj=# EXPLAIN ANALYZE UPDATE "taxonomy_taxonomy" SET "tree_id" = ("taxonomy_taxonomy"."tree_id" + 1) WHERE "taxonomy_taxonomy"."tree_id" > 1;

                                                            QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------
 Update on taxonomy_taxonomy  (cost=0.00..9588.75 rows=24582 width=132) (actual time=258718.550..258718.550 rows=0 loops=1)
   ->  Seq Scan on taxonomy_taxonomy  (cost=0.00..9588.75 rows=24582 width=132) (actual time=59.956..8271.209 rows=24582 loops=1)
         Filter: (tree_id > 1)
         Rows Removed by Filter: 2
 Planning time: 28.763 ms
 Execution time: 258718.661 ms
(6 rows)

A: django mptt uses Nested Set Model
So if your save method causes insert operation django-mptt have to recalculate a lot of data. It's just don't work on big tables.
You have to refuse using django-mptt and invent your own database schema.

A: There appears to be a lot of updates across the table when you modify the tree. On postgres, this will result in a lot of deleted rows that are actually not really deleted unless you do a vacuum full. we experienced a blown up table whose size shrank to 0.3% after a vacuum. Accordingly the performance increased a lot.


text:
Q: What will this PowerShell code output to? Will this code produce only the last line of the System eventlog file associated with event ID number 4201? I just don't get it. Help please!
Code:
     get-eventlog system | where-object {$_.eventID -eq 4201}

A: Lets break it apart

*

*get-eventlog - Calls the Get-EventLog commandlet

*system - Passes as the first parameter the word "system" this causes the System Event log to be choosen

*| - Pipe the output of the previous commandlet as the input to the next commandlet

*where-object - Filters the input commandlet based on a filter expression

*{ - The start of the expression

*$_ - A variable that represents the current row being evaluated in the result set

*.eventID - Selects the EventID property from the variable.

*-eq - test that the left hand side is equal to the right hand side

*4201 - the number 4201 to signify the event id we want to test.

*} - the end of the expression that is used to filter

As you see there is no part that only selects the most recent record. Thankfully because Get-EventLog returns the objects in order of newest to oldest we only need to add a Select-Object to the query.
get-eventlog system | where-object {$_.eventID -eq 4201} | Select-Object -First 1

*

*Select-Object - Filter out the result set based on some parameters

*-First - Select only the first X items where X is defined by the next property

*1 - The number 1 to signify we only want the first result.

If our list was not in order we would need to add a Sort-Object to it too
get-eventlog system | where-object {$_.eventID -eq 4201} | Sort-Object -Descending TimeGenerated | Select-Object -First 1

*

*Sort-Object - Sort the result based on some parameters

*-Descending - Sort from largest to smallest

*TimeGenerated - Use the TimeGenerated property to sort

Note: you could drop the -Descending and change -First 1 to -Last 1 to also get the same results.

A: It will output all of the event log entries that have that EventID.


text:
Q: make div disable in html I have a div like this:

No more posts available

I want to make it not clickable. So I added disable="true" but it doesn't work.
I want to make it in HTML without javascript.
I want to know if exists any attribute in HTML that makes a div unclickable because disabled isn't working.
Please help.
Edit:
this class load-more-home is called in a javascript function that generates posts, actually,  the difference between buttons is only the inner text.
When there are no more posts the text is replaced with "No more posts..". But by default I need to put there a not clickable div(div that acts like a button). I hope I explained it

A: You can emulate it using css:

.disabled {
    pointer-events: none;
    opacity: 0.4;
}

  <button>some clickable content</button>

A: disabled isn't a valid property for div.
You can use this css statment to disable click events:
pointer-events:none;

A: Try This:

No more posts available

.load-more-home{
  cursor: not-allowed;
}

A: You could use CSS to disable pointer events
#my-div {
pointer-events:none;

}

A: Only HTML, tricky but works:
<fieldset disabled='true'>Solution Name</fieldset>

A: add attribute
style="cursor:none;"

Or like this
.notClick {
  cursor:none;
}

No more posts available


text:
Q: How to hide/hidden Lightning page tab banner from lightning app page I have one Lightning Page Tab, which is link with my VFP and LWC component.I need to hide the Page Banner in the Lightning App Page.
This is Lightning page tab not a lightning component Tab.
So please help me to give some solution on it.

I try to create new tab but it give me same problem.


text:
Q: Type HalfOpenInterval does not conform to protocol BooleanType I have a very simple for loop that is giving me troubles. This code ran without issue in Xcode beta 4, but in beta 5 it is complaining that the half open interval (and the closed interval) don't conform to BooleanType. What has changed, why doesn't this work anymore, or is this a bug?
for let i = 0; i..<cellCount!; ++i {
    //do stuff
}

cellCount is defined as an optional Int property:
private var cellCount: Int?

I have tried storing the cellCount into a non-optional constant but the issue still remains:
let numberOfCells: Int = cellCount!
for let i = 0; i..<numberOfCells; ++i {
    //do stuff
}

I see in the Release Notes a lot has changed with Ranges, but nothing seems to be relevant to this issue.

A: Ranges are meant to be used in a for in loop:
for i in 0..<cellCount! {
    // do stuff
}

A: Does this have anything to do with HalfOpenInterval? I thought the struct is Range?
If you use HalfOpenInterval in for-in, it will not work. It is not of protocol SequenceType


text:
Q: Load an HTML5 Canvas to another HTML5 Canvas with Flash CC and CreateJS Hi all I'm just curious , is it possible to load the HTML5 Canvas file into another HTML5 Canvas with Flash CC or CreateJS . If we can do that ( I really hope it's possible ) , How can I do it ? Thanks a lot for your help.

A: You have a couple of options:
The first is to consume the second canvas into a Bitmap object. This will paint it into your primary canvas, but if you have any mouse listeners in the second canvas, these will not function.

var canvas2 = document.getElementById("mySecondCanvas");
var bmp = new createjs.Bitmap(canvas2);
myStage.addChild(bmp);

If you'd like to maintain interactivity in the "sub" content, the best approach is to simply copy the display list over. If you're using content exported from Flash Pro, this is as easy as adding the exportRoot container. You may also want to add a mask to clip it to the original canvas dimensions.

myStage.addChild(secondCanvasExportRoot);
mask = new createjs.Shape();
mask.graphics.rect(0,0,canvas2.width, canvas2.height);
secondCanvaCanvasExportRoot.mask = mask;

If not, then just add or copy all of the elements on your second stage into a container on your primary stage.


text:
Q: How to execute a custom function if there is an exception in airflow? If there is an exception in Airflow I want to execute a custom function or Activity. Is it possible to do that in airflow? I also want to send the exception message to the method or activity.

A: For every dag and task you can define "on_failure_callback" . once you get exception in task and it failed this function is called.
for more details see : https://airflow.apache.org/docs/apache-airflow/2.2.2/logging-monitoring/callbacks.html


text:
Q: Sandbox: Localize listInstance title how to localize listInstance title in sandboxed solution?
It is posible to add Resources.resx file to feature and localize ListDefinition:
<ListTemplate
        Name="TagsListDefinition"
        Type="20020"
        BaseType="0"
        OnQuickLaunch="TRUE"
        SecurityBits="11"
        Sequence="410"
        DisplayName="$Resources:TagsListDefinitionDisplayName"
        Description="$Resources:TagsListDefinitionDescription"
        Category="Communications"
        Image="/_layouts/images/itgen.png"/>

But this don't work for ListInstance
<ListInstance Title="$Resources:TagsListInstanceTitle"
                OnQuickLaunch="TRUE"
                TemplateType="20020"
                Url="Lists/Tags"
                Description="descr" />

A: Make sure your format to pick the name from the Resource file is:
Name="$Resources:MyResources,TagsListInstanceTitle"
MyResources – name of the resources file (as described below)
TagsListInstanceTitle – the resource entry

And the name of Resources file (for the entry above) for English should be:
MyResources.en-US.resx

And deployed to:
{SharePointRoot aka 14 hive}Resources

For SandBox solutions:
You need to use Embedded Resource files. An Embedded Resource is compiled directly into the output assembly. See the link about the their usage
Hope it helps!


text:
Q: Including a link to an SVG file within Javascript file I am inserting a button within the page using JQuery.  Within the button is an SVG.  I would like to instead of having SVG in the .js file, have a link to a seperate svg file.  I have included part of the file below.  As you can see, it is very unreadable, so I would much prefer to hold it elsewhere..
var feedButton = '<button title="Share to feed" data-original-title="Feed" data-container="body" data-delay="50" data-position="top" class="tooltipped send-to-feed" type="button"><svg class="feed-button-icon" viewBox="0 0 38 37"><g fill="none"><path d="M0 0L24 0 24 24 0 24 0 0Z"/><path d="M17 17C17 17 17 17 17 17L8 17C8 17 8 17 8 17L8 14 6 14 6 19C 6 20.1 6.9 21 8 21L17 21C18.1 21 19 20.1 19 19L19 5 17 5 17 17ZM17 3C18.1 3 19 3.9 19 5L17 5 17 3ZM6 5C6 3.9 6.9 3 8 3L8 5 6 5ZM3 10L3 12 11 12 11 14 14 11 11 8 11 10 3 10ZM6 5L8 5 8 8 6 8 6 5ZM8 3L17 3 17 5 8 5 8 3Z" fill="white"/></g></svg></button>';

shotitem.find('.feed-button').html(feedButton);


text:
Q: Constrain lower limit of the result of a subtraction I want to subtract the values in a vector from a scalar. However, if the result is lower than zero I want to set the result to zero.
I have tried using max, but it doesn't give me the expected result
s
# [1]  750.0  975.0 1125.0 1237.5 1312.5 1400.0

max(1050 - s, 0)
# [1] 300

I expect result to be c(300, 150,  0,  0,  0,  0)

A: I suggest pmax:
pmax(1050 - s, 0)
# [1] 300  75   0   0   0   0


text:
Q: How do I submit an app through Xcode 4's organizer? I'm getting an error I installed Xcode 4, thinking it would be similar to Xcode 3, and now I cannot get my binary to the App Store using organizer which I believe is the proper way to do this.
Has anyone got this working properly?  Not sure what setting I need to update - All I get is an "invalid binary" message.  Of course, it is a critical update I need to submit.

A: I've had something similar. You should check your code signing settings. Xcode 4 introduces "schemes", which are a little complicated. Think of them as sets of configurations. In Xcode 3, you could only have one such set of settings.
I believe that you need to check your code signing settings for your active scheme. Check the "Archive" option.
Edit your code signing settings:

Then, ensure that your "Archive" option is using the correct signing settings. Click on the "Edit Scheme" entry in the menu on the top left of your window.

And then verify that the proper signing setting is being used:

Depending on how you've set up your code signing and Build Settings, you may need to adjust your schemes appropriately.

A: After trying a wide variety of options over a period of two intensive and enormously frustrating days, only to be faced with the cryptic and utterly unhelpful "invalid binary" message, I reviewed this post again.
When I reviewed avaynshtok's question - "You mean when you submit the binary, you have to select the distribution profile. However in the Code Signing section of the build settings, you still want the developer profile selected for the release build configuration, correct?"
Although it wasn't answered, it got me to think about the profile you select when you are in Organizer and select the "Submit" button. I took another look and realized that you need to set the distribution profile there, for which I had been just accepting the default until now.
So, I set my "AppStore" archiving profile back to use the development certificates, as suggested above. I then resubmitted using the distribution profile at the Organizer "submit" time, and voila - it passed.
Question to Apple: you guys have $70,000,000,000 in cash. Can you afford to update the apps store submission procedure docs and "invalid binary" message to be a tad more clear? I'd be fired if I produced such low quality work.


text:
Q: Process.Start() totally ignore the environment variables in PATH I found that my cmd window prompted by Process.Start() totally ignore my environment variables in PATH. It always said that "xxx is not internal or external commands". I tried run it manually and it worked. Therefore, I am sure the PATH has been set correctly.
I also tried to add the variable explicitly. It still did not work.
This is my code:
public static string ExecuteCommandSync(string command)
{
    try
    {
        System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("C:\\Windows\\System32\\cmd.exe", "/K " + command);

        var length = command.Length;

        procStartInfo.RedirectStandardOutput = false;
        procStartInfo.UseShellExecute = false;
        //Does not work
        procStartInfo.EnvironmentVariables.Add("PATH", "C:\\Program Files\\Arm\\Arm Mobile Studio 2021.0");
        procStartInfo.CreateNoWindow = false;
        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.StartInfo = procStartInfo;
        proc.Start();
    }
    catch (Exception objException)
    {
        return objException.ToString();
    }
}

A: It is better when you did add the complete description of the error, in stead of "does not work"

System.ArgumentException: Value does not fall within the expected
range.    at
System.Collections.Specialized.StringDictionaryWrapper.Add(String key,
String value)    at ConsoleApp88.Program.ExecuteCommandSync(String
command) in

You cannot add PATH because it is already in the list of environment variables.
Solution can be to add the next statement, just before the add:
procStartInfo.EnvironmentVariables.Remove("PATH");


text:
Q: installation graphviz, no module named graphviz I been trying to install graphviz and connect with python to graph some nodes for decision trees. I had read a lot of threads with the same problem as me but i perform much of the solutions but i still cannot perform my decision trees :(
I am not a programmer, i am just an simple economist which is trying to learn machine learning models, so for me is difficult to read much of the solutions provided in other threads.
I already could conda install -c anaconda graphviz in my cmd and conda install -c anaconda pydot and installation was completed. (I also download the rar package from GraphViz page)
Then i try to import graphviz, but python shows me the following error No module named 'graphviz'.
So then i try to add to my environment a new path with the following cd C:\Program Files (x86)\Graphviz2.38\bin but i continue to having the same problem.
I am trying to run the following script in my spyder codes but without any succed
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

import pydot
from IPython.display import Image, display
# import graphviz as gv

from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.externals.six import StringIO
from sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier,
export_graphviz
from sklearn.ensemble import BaggingClassifier, RandomForestClassifier,
BaggingRegressor, RandomForestRegressor, GradientBoostingRegressor
from sklearn.metrics import mean_squared_error,confusion_matrix,
classification_report

# This function creates images of tree models using pydot
def print_tree(estimator, features, class_names=None, filled=True):
   tree = estimator
   names = features
   color = filled
   classn = class_names

   dot_data = StringIO()
   export_graphviz(estimator, out_file=dot_data, feature_names=features,
   class_names=classn, filled=filled)
   graph = pydot.graph_from_dot_data(dot_data.getvalue())
   return(graph)

hitter =
pd.read_csv('C:\\Users\\ldresl\\Documents\\Chapter8\\Hitters.csv',sep=';')

hitter = hitter.dropna()

#Llamo una nueva matriz
X = hitter[['Years','Hits']].as_matrix()
y = np.log(hitter.Salary.as_matrix())

 #Se corre todo el codigo junto
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(11,4))
ax1.hist(hitter.Salary.as_matrix())
ax1.set_xlabel('Salary')
ax2.hist(y)
ax2.set_xlabel('Log(Salary)');

# Corro la regresion de la decision tree (NOTAR QUE NO ES RANDOM FOREST!!!)
regr = DecisionTreeRegressor(max_leaf_nodes=3)
regr.fit(X, y)

graph, = print_tree(regr, features=['Years', 'Hits'])
Image(graph.create_png())

but whenever i try to run the last two lines throws me the following error [WinError 2] "dot.exe" not found in path.. Also if i write import graphviz as gv doesnt found it.
Sorry for my english :( i am learning :).

A: There exists now a python-graphviz package at Anaconda.org which contains the Python interface for the graphviz tool. Simply install it with:
conda install python-graphviz

Check out here for more info.

A: Below command worked for me in windows 10, Anaconda version 4.8.3 :
conda install -c anaconda python-graphviz

A: The best way to solve the problem is:
source activate anaconda
pip install pydot
pip install pydotplus
pip install pydot-ng
Then you download and install Graphviz according to your OS type:
http://www.graphviz.org/download/
Check my previous answer for more information:
Python RuntimeError: Failed to import pydot

A: conda install --channel https://conda.anaconda.org/garylschultz pygraphviz


text:
Q: SSIS Conditional Split Error Output not writing any data to table I have created this simple SSIS package:

This is my conditional split:

This is the Configure Error Output:

I am getting this error when running:

[ErrorTable [52]] Warning: Rows sent to the error output(s) will be
lost. Add new data flow transformations or destinations to receive
error rows, or reconfigure the component to stop redirecting rows to
the error output(s).

Before I got this error it was creating the error table but did not write any rows so I changed it to redirect row and now have this error. I'd be grateful for any help.

A: I just ran into the same issue and think I found the answer.
The output from your conditional split should not be the red "Error" path, but another output path (blue) to the "Error" file.
I kept expecting the red path to output the data from the conditional split, but it didn't because there actually weren't any errors.
I'm learning here, but I'm guessing the red "error" path is for actual data issues and not the conditional split functions.
Hope that helps!  I


text:
Q: Disjunction in Intuitionistic Logic, what about $((P \to U \lor V) \to Z)$ I wonder whether the following holds in intuitionistic logic:
$$((P \to U \lor V) \to Z) \leftrightarrow ((P \to U) \to Z) \land ((P \to V) \to Z)$$
For disjunction I assume the following two rules:
$$\begin{array}{lcl}
\begin{array}{l}
G\vdash U\\
\hline
G\vdash U\lor V
\end{array} &\quad& \text{(Rv1)}\\
&\\
\begin{array}{l}
G\vdash V\\
\hline
G\vdash U\lor V
\end{array} &\quad& \text{(Rv2)}\\
&\\
\begin{array}{l}
G,\ U\vdash A\\
G,\ V\vdash A\\
\hline
G,\ U\lor V \vdash A
\end{array} &\quad& \text{(Lv)}\end{array}$$
I can easily proof the following direction:
$$((P \to U \lor V) \to Z) \to ((P \to U) \to Z) \land ((P \to V) \to Z)$$
Namly we have:
$$\begin{array}{ll}
U\vdash U\lor V\\
\hline
P\to U\vdash P\to U\lor V\\
\hline
(P\to U\lor V) \to Z\vdash (P\to U)\to Z
\end{array}$$
But I am not sure whether I can establish the other direction.
Bye
P.S.: I didn't try Kripke models or Weak conterexamples. I only tried proof theoretically to derive it, by the rules that I have given in my Question.
P.S.S.: It would give an alternative method to the Rip (Resolution for Intuitionistic Logic) found in Basic Proof Theory, Second Edition, Troelstra & Schwichtenberg, 2000, p.253.

A: This is a very interesting question!
You have named the axiom (1) $$((P \to U) \to Z) \land ((P \to V) \to Z) \to ((P \to U \lor V) \to Z).$$
Let us throw away the $Z$ and switch it around though: (2) $$(P \to U \lor V) \to (P \to U) \lor (P \to V),$$

Details on the equivalence of (1) and (2):
To show that (1) implies (2) instantiate $Z := (P \to U) \lor (P \to V)$ and we have: $$((P \to U) \to ((P \to U) \lor (P \to V))) \land ((P \to V) \to ((P \to U) \lor (P \to V))) \to ((P \to U \lor V) \to ((P \to U) \lor (P \to V)))$$ the hypothesis both disappear and we are left with $$(P \to U \lor V) \to ((P \to U) \lor (P \to V)).$$
As for the other direction, we just apply the general theorem that $(A \to (B \lor C))$ implies $((B \to Z) \land (C \to Z)) \to (A \to Z)$.

Algorithmically, it is obvious that this axiom is not intuitionist. It is somehow guessing in advanced whether $P$ will imply $U$ or $V$ and taking that answer to build either a proof of $P \to U$ or $P \to V$. There is no way to  perform this process without actually having $P$ already.

I claim this axiom is equivalent to the Godel-Dummett axiom there is a proof here on JSTOR but you can see the first page and get enough an idea how to do it. The Godel-Dummett axiom is $(P \to Q) \lor (Q \to P)$. If you have trouble proving this equivalent to (2) I can write it out in detail but it is not very difficult and quite fun.
It is a classical result that the Godel-Dummett implies weak excluded middle: $$\neg P \lor \neg \neg P.$$ That is not enough to get full classical logic but it is certainly not intuitionist logic! It's "half way" between excluded middle (classical) and the double negation embedding (which can be proved intuitionistically).

A: Picking up the idea of Quanta I get from:
((P -> U v V) -> Z) <- ((P -> U) -> Z) & ((P -> V) -> Z)
by setting Z = (P -> U) v (P -> V) we get:
((P -> U v V) -> (P -> U) v (P -> V)) <- ((P -> U) -> (P -> U) v (P -> V)) & ((P -> V) -> (P -> U) v (P -> V))
The parts of the conjunction do hold, so this should be equal to:
(P -> U v V) -> (P -> U) v (P -> V)
and now by setting P = U v V we get:
(U v V -> U v V) -> (U v V -> U) v (U v V -> V)
The left hand side holds, so this should be equal to:
(U v V -> U) v (U v V -> V)
Which is in turn equal to:
((U -> U) & (V -> U)) v ((U -> V) & (V -> V))
The identity implications do also hold, so that this should be equal to:
(V -> U) v (U -> V)
Now, although classically valid, this has a simple intuitionist counter model:
    w1 V=1, U=0
   /
  w0 V=0, U=0
   \
    w2 V=0, U=1

Since the instantiated formula is not valid, the general original formula
can also not be valid. Q.E.D.
Bye


text:
Q: How to resolve a proxy error in a reactjs/ express app? I have the following error:

Proxy error: Could not proxy request /AppManager.jsx See
  https://nodejs.org/api/errors.html#errors_common_system_errors for
  more information (ECONNREFUSED).
react-dom.development.js:199 GET http://localhost:3000/List.jsx 500
  (Internal Server Error)

I am using an app based on create-react-app. The app talks to a express/ node api server. Why do I get this error?

A: You need to white list your cross domain url in express.
Here's a simple middleware function to serve up the correct CORS header from a whitelist. Setting this near the top of your express app will allow all your routes to set the proper header from the whitelist before serving up content.
 app.use(function(req, res, next){
 var whitelist = ['localhost:4000', 'localhost:3000', 'anydomain.com']
 var host = req.get('host');

 whitelist.forEach(function(val, key){
  if (host.indexOf(val) > -1){
   res.setHeader('Access-Control-Allow-Origin', host);
  }
})

next();
});


text:
Q: Redirect the user after a form submission I have an <input type="text" /> as a search bar inside a <form>.
Because it's a search bar the user should be redirected to a route similar to : /search?q=thingIWantToSearch when the form is submited.
Currently I'm doing with a location.href but I don't think this is a good way of doing it (or is it?)
Here's my code :
<script>
    let inputValue = '';

    const handleSubmit = () => {
        // there should be some parsing before putting it in the url, but it's not the subject
        location.href = `/search?q=${inputValue}`;
    }
</script>

<form on:submit|preventDefault={handleSubmit}>
    <input type="text" bind:value={inputValue} />
    <button type="submit">submit</button>
</form>

So how can I properly redirect the user on form submission?

A: Check out Sappers goto function. It may serve your purposes.
Here's how you can use your code with it.
<script>
  import { goto } from '@sapper/app';

  let inputValue = '';

  const handleSubmit = () => {
    // there should be some parsing before putting it in the url, but it's not the subject
    goto(`/search?q=${inputValue}`);
  };
</script>

<form on:submit|preventDefault="{handleSubmit}">
  <input type="text" bind:value="{inputValue}" />
  <button type="submit">submit</button>
</form>


text:
Q: Void* example for JNA I have been struggling to find examples on void* example in JNA. I am trying to understand how to use Pointer in JNA.
For example
IN C :
int PTOsetApiOpt(int iOpt,void* lpValue,int iLen)

Parameters: iOpt: int
lpData: address from which data should be read.
iLen: length of data
returns int values : 0 as success or -1 as failure.

How do we write that in JAVA using JNA?
I have tried this in JAVA
public MyTest{

 public interface MyLibrary extends Library {
   public int PTOsetApiOpt(int iOpt,Pointer lpValue,int iLen);

 }
 public static void main(String[] args) {
   MyLibrary myLib = (MyLibrary)MyLibrary.INSTANCE;
   int result = myLib.PTOsetApiOpt(1,new Pointer(0),1024);
 }

I get JVM crash when myLib.PTOsetApiOpt is invoked. I am guessing this is because of new Pointer statement. How can I create a Pointer and use it as parameter without JVM crash? I have been stuck on it for 2 days.   Any tips would be great. Thanks in advance.
Regards,
-Vid-

A: Declare your method to take IntByReference as an argument, then you don't have to call ByReference.getPoint() when calling the method.

A: I think I have figured it out.
Here's how i wrote it in Java..
void* lpValue can be any type. So in C it is expecting address of int value.
 public MyTest{

 public interface MyLibrary extends Library {
   public int PTOsetApiOpt(int iOpt,Pointer lpValue,int iLen);

 }
 public static void main(String[] args) {
   MyLibrary myLib = (MyLibrary)MyLibrary.INSTANCE;
    IntByReference ir = new IntByReference(1);
    //got a result as 0 instead of -1.
    int result = myLib.PTOsetApiOpt(1, ir.getPointer() , ir.getPointer().SIZE);
 }


text:
Q: Why is gems missing after 'bundle install' says it installs them? Running bundle install in my project gives the following output:
➜  <my-project> git:(main) ✗ bundle install
Ignoring eventmachine-1.2.7 because its extensions are not built. Try: gem pristine eventmachine --version 1.2.7
Ignoring ffi-1.15.5 because its extensions are not built. Try: gem pristine ffi --version 1.15.5
Ignoring http_parser.rb-0.8.0 because its extensions are not built. Try: gem pristine http_parser.rb --version 0.8.0
Ignoring sassc-2.4.0 because its extensions are not built. Try: gem pristine sassc --version 2.4.0
Fetching gem metadata from https://rubygems.org/.........
Using concurrent-ruby 1.1.10
Using zeitwerk 2.5.4
Using public_suffix 4.0.6
Using bundler 2.3.11
Using coffee-script-source 1.11.1
Using colorator 1.1.0
Using minitest 5.15.0
Using thread_safe 0.3.6
Using execjs 2.8.1
Using commonmarker 0.23.4
Using unf_ext 0.0.8
Fetching eventmachine 1.2.7
Fetching http_parser.rb 0.8.0
Using faraday-em_http 1.0.0
Using faraday-excon 1.1.0
Using faraday-net_http_persistent 1.2.0
Using faraday-patron 1.0.0
Using faraday-rack 1.0.0
Using faraday-retry 1.0.3
Fetching ffi 1.15.5
Using faraday-net_http 1.0.1
Using forwardable-extended 2.6.0
Using gemoji 3.0.1
Using faraday-em_synchrony 1.0.0
Using rexml 3.2.5
Using rb-fsevent 0.11.1
Using ruby2_keywords 0.0.5
Using mercenary 0.3.6
Using safe_yaml 1.0.5
Using liquid 4.0.3
Using rouge 3.26.0
Using faraday-httpclient 1.0.1
Using racc 1.6.0
Using multipart-post 2.1.1
Using jekyll-paginate 1.1.0
Using webrick 1.7.0
Using rubyzip 2.3.2
Using jekyll-swiss 1.0.0
Using jekyll-commonmark 1.4.0
Using coffee-script 2.4.1
Using tzinfo 1.2.9
Using addressable 2.8.0
Using pathutil 0.16.2
Using kramdown 2.3.1
Using faraday-multipart 1.0.3
Using nokogiri 1.13.3 (arm64-darwin)
Using i18n 0.9.5
Using kramdown-parser-gfm 1.1.0
Using unicode-display_width 1.8.0
Using jekyll-coffeescript 1.1.1
Using activesupport 6.0.4.6
Using faraday 1.10.0
Using terminal-table 1.8.0
Using sawyer 0.8.2
Using unf 0.1.4
Using html-pipeline 2.14.0
Using octokit 4.22.0
Using simpleidn 0.2.1
Using jekyll-gist 1.5.0
Using dnsruby 1.61.9
Installing http_parser.rb 0.8.0 with native extensions
Installing eventmachine 1.2.7 with native extensions
Installing ffi 1.15.5 with native extensions
Using ethon 0.15.0
Using rb-inotify 0.10.1
Using typhoeus 1.4.0
Using sass-listen 4.0.0
Using listen 3.7.1
Using github-pages-health-check 1.17.9
Using sass 3.7.4
Using jekyll-watch 2.2.1
Using jekyll-sass-converter 1.5.2
Using em-websocket 0.5.3
Using jekyll 3.9.0
Using jekyll-commonmark-ghpages 0.2.0
Using jekyll-feed 0.15.1
Using jekyll-github-metadata 2.13.0
Using jekyll-redirect-from 0.16.0
Using jekyll-avatar 0.7.0
Using jekyll-remote-theme 0.4.3
Using jekyll-optional-front-matter 0.3.2
Using jekyll-sitemap 1.4.0
Using jekyll-readme-index 0.3.0
Using jekyll-include-cache 0.2.1
Using jekyll-relative-links 0.6.1
Using jekyll-mentions 1.6.0
Using jekyll-seo-tag 2.8.0
Using jekyll-default-layout 0.1.4
Using jekyll-titles-from-headings 0.5.3
Using jemoji 0.12.0
Using jekyll-theme-midnight 0.2.0
Using jekyll-theme-architect 0.2.0
Using jekyll-theme-cayman 0.2.0
Using jekyll-theme-dinky 0.2.0
Using jekyll-theme-slate 0.2.0
Using jekyll-theme-leap-day 0.2.0
Using jekyll-theme-merlot 0.2.0
Using jekyll-theme-minimal 0.2.0
Using jekyll-theme-modernist 0.2.0
Using jekyll-theme-primer 0.6.0
Using jekyll-theme-hacker 0.2.0
Using jekyll-theme-tactile 0.2.0
Using jekyll-theme-time-machine 0.2.0
Using minima 2.5.1
Using github-pages 225
Bundle complete! 6 Gemfile dependencies, 102 gems now installed.
Gems in the group 'production' were not installed.
Use `bundle info [gemname]` to see where a bundled gem is installed.

And as you can see it says http_parser, eventmachine and ffi are all being installed with no errors in the process.
But when I try to run bundle exec jekyll build in the same directory afterwards I get this error:
➜  <my-project> git:(main) ✗ bundle exec jekyll build
Could not find eventmachine-1.2.7, http_parser.rb-0.8.0, ffi-1.15.5 in any of the sources
Run `bundle install` to install missing gems.

Can anyone tell me why this might be happening and what I need to do to fix it?
I'm on macOS Ventura 13.0 (22A380)

A: It's right at the top of your output:
Ignoring eventmachine-1.2.7 because its extensions are not built. Try: gem pristine eventmachine --version 1.2.7
Ignoring ffi-1.15.5 because its extensions are not built. Try: gem pristine ffi --version 1.15.5
Ignoring http_parser.rb-0.8.0 because its extensions are not built. Try: gem pristine http_parser.rb --version 0.8.0
Ignoring sassc-2.4.0 because its extensions are not built. Try: gem pristine sassc --version 2.4.0

Try running those pristine commands.


text:
Q: Android-Creating a runtime Edittext when a Button is Clicked I am new to android.I just what to create a Edittext at a run time when a button is clicked.for example in contact when the image + is clicked it will add a button and a edittext in the layout.can anyone help me with some sample codes.Thanks in advance.

A: For this u need to create a layout which is set on click of button.
Chk out dis  :button


text:
Q: Duplicate column name in count joins When I try to obtain the amount of joins in this query, I get an #1060 - Duplicate column name 'columnXY', because there is a column with this name in both tables. How can I avoid this? I don't see why it should this make it impossible  to count the joins.
SELECT count(*) as c
FROM
(SELECT *
 FROM table1
 join table2 on table1.index = table2.index)  T1

A: Why not shorten to
SELECT COUNT(*)
FROM table1
JOIN table2 ON table1.index = table2.index

Here the column names should not matter at all.


text:
Q: Find the coordinates of all rectangles of contiguous 1s in a 2D array in Javascript I have found numerous questions asking about how to find the largest contiguous rectangle in a 2D array, and some that ask for the number of rectangles, but only one that deals with finding the coordinates, width, and height of all of the rectangles required to cover an area of 1s in a 2D of 1s and 0s.
The question (Finding rectangles in a 2d block grid) has a solution but is difficult to follow since it references an external code block.
I am dealing with 2D arrays that make up the pixels of letters:

0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0

0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0

0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0

0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0

0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0

0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0

0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0

0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0

0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0

0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0

0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0

0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0

0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0

0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0

0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0

0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0

0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0

0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0

The desired output here would be something like:
[[4,0,6,17],[7,0,16,2],[7,7,15,9],[7,15,15,17]]
Where each array contains the upper left hand coordinate and lower right hand coordinate (any method that gets upper left and width and height also works).
Could someone provide the psudocode (or Javascript) for either the question previously asked or another algorithm that works, or provide a more in-depth explanation of the steps required?

A: Here is a way to do it with using a simple algorithm.

*

*Calculate the total area covered by rectangles -> A

*While the area of the rectangles found so far is smaller than A

*

*Find a new rectangle

*

*Find the upper left corner, scan the matrix and stop at the first 1 found

*Find the bottom right corner, starting at the upper left corner, scan the matrix and stop at the first 0 found

*Mark the rectangle found by setting each cell to something else than 1

*Add its area to the accumulated area

*Push the rectangle to a list

const mat = [
  [0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0],//0
  [0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0],//1
  [0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0],//2
  [0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0],//3
  [0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0],//4
  [0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0],//5
  [0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0],//6
  [0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0],//7
  [0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0],//8
  [0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0],//9
  [0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0],//10
  [0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0],//11
  [0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0],//12
  [0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0],//13
  [0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0],//14
  [0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0],//15
  [0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0],//16
  [0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0] //17
];

const W = mat[0].length;
const H = mat.length;

// get the area covered by rectangles
let totalRectArea = 0;
for (let i = 0; i < W; ++i) {
  for (let j = 0; j < H; ++j) {
    totalRectArea += mat[j][i] > 0 ? 1 : 0;
  }
}

const rects = [];
let rectArea = 0;

// find all rectangle until their area matches the total
while (rectArea < totalRectArea) {
  const rect = findNextRect();
  rects.push(rect);
  markRect(rect);
  rectArea += (rect.x2 - rect.x1 + 1) * (rect.y2 - rect.y1 + 1);
}

console.log(rects);

function findNextRect() {
  // find top left corner
  let foundCorner = false;
  const rect = { x1: 0, x2: W-1, y1: 0, y2: H-1 };
  for (let i = 0; i < W; ++i) {
    for (let j = 0; j < H; ++j) {
      if (mat[j][i] === 1) {
        rect.x1 = i;
        rect.y1 = j;
        foundCorner = true;
        break;
      }
    }
    if (foundCorner) break;
  }
  // find bottom right corner
  for (let i = rect.x1; i <= rect.x2; ++i) {
    if (mat[rect.y1][i] !== 1) {
      rect.x2 = i-1;
      return rect;
    }
    for (let j = rect.y1; j <= rect.y2; ++j) {
      if (mat[j][i] !== 1) {
        rect.y2 = j-1;
        break;
      }
    }
  }
  return rect;
}

// mark rectangle so won't be counted again
function markRect({ x1, y1, x2, y2 }) {
  for (let i = x1; i <= x2; ++i) {
    for (let j = y1; j <= y2; ++j) {
      mat[j][i] = 2;
    }
  }
}


text:
Q: JuiceUI Change Theme / Style Is there an option to change the styles of JuiceUI controls? Any predefined themes? (If yes, I couldn't find any documentation on it.) Do I style them with regular CSS like other controls? (That didn't seem to work either.)
TIA
Edit: Here's how the button looks: (I had no preinstalled jquery themes in this one - this is a new website.)

I did notice JuiceUI installed a content - themes folder with base, Fresh-Squeezed and Supercharged.
Don't know where it's being referenced though and how to change it.

A: At the moment, the source for JuiceUI can be your best friend. Check out this line: https://github.com/appendto/juiceui/blob/master/Juice/JuiceApp.cs#L52
This is what you'll want to add to Global.asax.cs:
CssManager.CssResourceMapping.AddDefinition("juice-ui", new CssResourceDefinition {
    Path = "~/Content/themes/[Name of custom theme dir]/jquery-ui-1.8.18.custom.css",
    DebugPath = "~/Content/themes/[Name of custom theme dir]/jquery-ui-1.8.18.custom.css"
});

This will redefine the location of the "juice-ui" rendered theme, and you'll see that output in each page juice is used on.
Sorry this isn't more obvious at the moment. We're planning on a series of articles to cover topics such as these and updating the documentation on the site is already in the works.

A: For VB... yes people still use it! :P
<%@ Application Language="VB" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Web.UI" %>
<%@ Import Namespace="Juice.Framework" %>

<script runat="server">

    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs on application startup

        Dim juiResDef As New CssResourceDefinition
        juiResDef.Path = "~/Content/themes/[Name of custom theme dir]/jquery-ui-1.8.18.custom.css"
        juiResDef.DebugPath = "~/Content/themes/[Name of custom theme dir]/jquery-ui-1.8.18.custom.css"
        CssManager.CssResourceMapping.AddDefinition("juice-ui", juiResDef)

    End Sub

</script>

Good to go :)

A: Another approach to override the Fresh-Squeezed default is to just drag and drop the jquery-ui-X.X.XX.custom.css file onto the page and create an html link to it.  This will override the css from the default and apply the theme you want.  It would have to be done on any page you want to use the theme.  Another approach is to just treat the Fresh-Squeezed folder as the container for the theme you want to use and replace the images and the custom.css file in that folder.  Hopefully they will offer a different way of modifying this in future releases.

A: Becky, after looking at the GitHub repo it appears that it is using the ui-lightness css file for jQuery UI. https://github.com/appendto/juiceui/tree/master/Juice-Test-Site/css you can try loading a different jQuery Theme in place of this? you may have to ensure this file is not being loaded on your site. if i'm way off base and you've already tried this let me know.


text:
Q: How to configure watchdog for the arduino Nano 33 BLE Sense board? For the arduino Nano 33 BLE Sense board, the standard avr/wdt.h is not available. And it seems that no standard library provides it. How to use the watchdog system for this board ? I found no full information about it.
I've found the page https://www.mysensors.org/apidocs/group__avr__watchdog.html which allow to configure the reboot mode. And it works.
But no way to configure the interruption mode with ISR() function.
Moreover, there's no explanation about the manipulation of used register/variables for any fine configuration.
Simple code example with regular asynchronous stuff using the watchdog ISR() mechanism. It which works well with ATmega328 (e.g.UNO). But I do not find equivalent configuration for the Nano 33 BLE using the nRF52840.
# include <avr/wdt.h>

volatile byte led;
int k;

ISR(WDT_vect) {
  Serial.println("Asynchronous stuff in ISR() function");
  digitalWrite(LED_BUILTIN,led);
  led=!led;
}

void setup() {
  pinMode(LED_BUILTIN,OUTPUT);
  led=0;

  Serial.begin(9600);
  while(!Serial) {}
  Serial.println("== R E B O O T ==");

  WDTCSR = ( 1 << WDE ) | ( 1 << WDCE );
  WDTCSR = ( 1 << WDP2 ) | ( 1 << WDP0 ) | ( 1 << WDIE ) ; // Interruption and timeout  1/2 s
}

void loop() {
  Serial.print("Loop #");
  Serial.println(k);
  if (k++%2) {
    Serial.println("Some stuff (even branch)");
    delay(1200);
  }
  else {
    Serial.println("Some stuff (odd branch)");
    delay(4800);
  }
}

Thks.

A: In fact, for the RF52940, I'm not sure that the watchdog can provide the needed interruption mechanism despite it exists the INTENSET bit for interruption according to the chipset doc https://content.arduino.cc/assets/Nano_BLE_MCU-nRF52840_PS_v1.1.pdf).
But the good way is for sure the use of timers (and one can use more than just one, quite good).
For a similar behaviour as the code given for the UNO before, here is the code one can write for the Nano BLE using a timer interrupt (see https://github.com/khoih-prog/NRF52_MBED_TimerInterrupt for full and usefull doc).
#include "NRF52_MBED_TimerInterrupt.h"

volatile byte led;
volatile uint32_t count=0;
NRF52_MBED_Timer myTimer(NRF_TIMER_1);
unsigned k=0;

void myHandler() {
  digitalWrite(LED_BUILTIN,led);
  led=!led;
  count++;
}

void setup() {
  pinMode(LED_BUILTIN,OUTPUT);
  led=0;

  Serial.begin(9600);
  while(!Serial) {}
  Serial.println("== R E B O O T ==");

  if (myTimer.attachInterruptInterval(500*1000, myHandler)) // each 1/2 second
    Serial.println("myTimer launched");
  else
    Serial.println("Can not set the timer");
}

void loop() {
  Serial.print("Loop #");
  Serial.print(k);
  Serial.print(" and nb times in Handler : ");
  Serial.println(count);
  if (k++%2) {
    Serial.println("Some stuff (even branch)");
    delay(1200);
  }
  else {
    Serial.println("Some stuff (odd branch)");
    delay(4800);
  }
}


text:
Q: Why do we need to add SE_SHUTDOWN_NAME privilege before using ExitWindowsEx Before we can use the ExitWindowsEx function for shutting down the computer, we must add the SE_SHUTDOWN_NAME privilege to the process like this:
HANDLE hToken = NULL;
LUID luid;
OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken);
LookupPrivilegeValue(L"", SE_SHUTDOWN_NAME, &luid);
TOKEN_PRIVILEGES tp;
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
bRet = AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(tp), NULL, 0);

ExitWindowsEx(EWX_REBOOT, 0);

This works perfectly fine.
I know that this is by design, but I don't understand what's the motivation of Microsoft for deciding that a privilege must be enabled before the ExitWindowsEx function can be used. It's obviously not designed to prevent a process from rebooting the computer, because all it needs to do for rebooting is adding the SE_SHUTDOWN_NAME to the process and call ExitWindowsEx.
The Windows developpment term could have put the code above directly into the ExitWindowsEx function.

A: You don't need to add it (you can't add a privilege to your current token), you need to enable it.
Most privileges are disabled by default, probably to avoid an accidental use (just like the read-only attribute on files). There's no need to run around with the privilege enabled at all times, and having the ExitWindowsEx function enable it by itself would break consistency with other privilege-dependent functions.


text:
Q: Magento 1.9: Simple Product is not adding To Cart programmatically When I try to add the product to cart programmatically then give an error

The product could not be found.

Here is my code for product add to cart programmatically.
$productId = 2783;
$cart = Mage::getSingleton('checkout/cart');
$params = array('product' => $productId ,'qty' => 1);
$product = Mage::getModel('catalog/product')
        ->setStoreId(Mage::app()->getStore()->getId())
        ->load($productId);
print_r($product->getId());
$cart->addProduct($product,$params);
$cart->save();
$session = Mage::getSingleton('checkout/session');
$session->setCartWasUpdated(true);

A: You can use the below code to add a product to the cart programmatically.

Simple product with out options

$prod_id = 2783; // pass product id
$_product = Mage::getModel('catalog/product')->load($prod_id);
$params = array(
   'product' => $prod_id,
   'qty' => 1,
   'form_key' => Mage::getSingleton('core/session')->getFormKey()
);

$cart = Mage::getModel('checkout/cart');
$cart->init();
$cart->addProduct($_product, $params);
$cart->save();

$quote = Mage::getModel('checkout/session')->getQuote();
$quote->collectTotals()->save();

Simple product with options

$productId = "Your Product Id"
$cart = Mage::getSingleton('checkout/cart');
$cart->init();
$options = array('92'=>'49','144'=>'21');
$product = Mage::getModel('catalog/product')->load($productId);

$paramater = array('product' => $productId,
                    'qty' => '1',
                    'form_key' => Mage::getSingleton('core/session')->getFormKey(),
                    'options' => $options
            );

$request = new Varien_Object();
$request->setData($paramater);
$cart->addProduct($product, $request);
$cart->save();

Configurable product

$productId = "Your Product Id"
$cart = Mage::getSingleton('checkout/cart');
$cart->init();
$options = array('92'=>'49','144'=>'21');
$product = Mage::getModel('catalog/product')->load($productId);

$paramater = array('product' => $productId,
                    'qty' => '1',
                    'form_key' => Mage::getSingleton('core/session')->getFormKey(),
                    'supper_attribute' => $options
            );

$request = new Varien_Object();
$request->setData($paramater);
$cart->addProduct($product, $request);
$cart->save();

Hope it helps!!!


text:
Q: Can't open document opencv2\opencv.hpp on visual studio 2012 I got an error like this when I open the document of opencv2\opencv.hpp on the visual studio 2012.

The error is underlined below code but I still run the program

I want to open the document of library and no error code.
Can you help me! Thank you!


text:
Q: Can I force Mac OS to cache my most frequently used applications? If I buy a lot of ram for my new iMac (16GB), is there a way to make the system cache my most frequently used applications so the launch time is much faster?

A: It's an oversimplification, but this is essentially what Unix does with its memory in the first place.  If you don't shut down your computer and don't close your apps, your most frequently used apps will always be in memory ready for you to use.  Apps you don't use will get swapped to disk (assuming you ever run out of RAM  :-)
In Lion especially, you can almost forget about quitting apps by hand.


text:
Q: I want to use Power Shell or Batch file to make file associations I need a programmatic method to set associations as part of an installer program.
I am trying to set a file extension so that when a user double clicks on that extension it runs the associated program in this case c:\temp\test.bat
I have tried using the assoc and also the ftype commands in a .bat file but when the file .003 (just for testing purposes) it still opens the Unpacker program that was already set as the default for that extension. See image of Control Panel>Programs>Default Programs>Set Associations. If I use this interface and change the program associated as I did with 002 File then it works when I double click on test.002 it runs test.bat.
I need to include this association in an install so I need to be able to do what I can do in the GUI in a .bat file. the .bat commands assoc and ftype do not seem to make changes to the GUI in the image and also still launch Unpacker not test.batenter image description here


text:
Q: HorizontalListView inside a ScrollView within fragments in a ViewPager In my application I have a scenario where I have to show different products inside a viewpager. In each product I show a pic and when the user does a fling action on the photo scrollview translates and covers the photo. Now for showing the related items I have to use HorizontalListview. But what happens is ,when I start scrolling the HorizontalListView for the first time it scrolls but the second touch is passed to the ViewPager i.e. alternate touches work. Can someone suggest me a better way of showing horizontal items in my case.
Thanks in advance!!!!!

A: Disable images' scroll, enlarge the image on click and show scroll. Else keep focus on listview.
I think facebook app also does same (keep images out of focus until clicked on)


text:
Q: Using Google fonts: however, the code is not valid HTML5 according to W3C? I'm working on an assignment, and I am using Google Fonts for my site. I'm trying to validate my HTML using W3C, as my assignments must be valid to get full marks, and I keep on getting an error for the Google Font code. I can't seem to figure out why. Here's the code:
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Orbitron|Special+Elite|Open+Sans">

Here's the error message I am getting from W3C:

Bad value http://fonts.googleapis.com/css?family=Orbitron|Special+Elite|Open+Sans for attribute href on element link: Illegal character in query: not a URL code point.
…href="http://fonts.googleapis.com/css?family=Orbitron|Special+Elite|Open+Sans">
Syntax of IRI reference:
      Any URL. For example: /hello, #canvas, or http://example.org/. Characters should be represented in NFC and spaces should be escaped as %20.

Any thoughts? I'm pretty new to HTML5, so I'm unsure what I'm missing here.

A: Try replacing the pipe | with %7c and see if it will pass and still load the font on the webpage. You may have to do the same thing for the plus sign.
http://www.w3schools.com/tags/ref_urlencode.asp

A: The offending character here is "|" U+007C VERTICAL LINE, used by Google as a separator between font names; that's a poor choice by them, since "|" is a reserved character, both by the "URL Living Standard" (which is what the HTML5 CR cites) and by the Internet-standard STD 66 (RFC 3986).
In practice, it works fine when you use "|" as such, but to conform to the standards and drafts, use percent encoding (% encoding, as defined in the URL specifications) for it, writing %7c (case insensitive) instead:
<link rel="stylesheet" type="text/css" href=
"http://fonts.googleapis.com/css?family=Orbitron%7cSpecial+Elite%7cOpen+Sans">


text:
Q: Magic Square with Python I have a file called "magic.txt" which contains the following numbers:
3
8 1 6
3 5 7
4 9 2

The "3" stands for the NxN size of the square, and the rest of the numbers is the potential magic square. I wrote code that can sum up all the rows and the columns and the first diagonal (namely, the numbers 8, 5, 2). However I have no clue how to solve for the other diagonal (namely, 6, 5, 4). Below is my code for the first diagonal.
def sum_diagonal():
    with open("magic.txt") as file:
        text = file.readlines() # Read magic.txt file

        square_size = int(text.pop(0)) # Pop off the square size from the list and converting it to an integer
        terminator = int(text.pop(square_size)) # Pop off the -1 terminator

        sumdia1 = 0
        for x in range(square_size): # This for loop is to loop through all the rows and add up the diagonal.
            text_list = text[x].split() # Splits the y-th index into its own list (multi-dimensional list)
            sumdia1 = sumdia1 + int(text_list[x]) # Sum up the diagonal 1
        print("Sum of diagonal 1:", sumdia1)

Any suggestions would be appreciated.

A: You may notice the index of the other diagonal is (i, 2-i), or (i, square_size-1-i) in your case.
So you can do something similar to before
def sum_diagonal():
    with open("magic.txt") as file:
        text = file.readlines() # Read magic.txt file

        square_size = int(text.pop(0)) # Pop off the square size from the list and converting it to an integer
        terminator = int(text.pop(square_size)) # Pop off the -1 terminator

        sumdia1 = 0
        for x in range(square_size): # This for loop is to loop through all the rows and add up the diagonal.
            text_list = text[x].split() # Splits the y-th index into its own list (multi-dimensional list)
            sumdia1 = sumdia1 + int(text_list[x]) # Sum up the diagonal 1
        print("Sum of diagonal 1:", sumdia1)

        sumdia2 = 0
        for x in range(square_size): # This for loop is to loop through all the rows and add up the diagonal.
            text_list = text[x].split() # Splits the y-th index into its own list (multi-dimensional list)
            sumdia2 = sumdia2 + int(text_list[square_size-1-x]) # Sum up the diagonal 1
        print("Sum of diagonal 2:", sumdia2)


text:
Q: What are classes and why use more than one (C#)? I am studying C#. As far as I understand, classes are where everything is happening. However, I have never used one more than one class in a script, nor do I know the actual definition of a class. So why have more than one class in a script and what is the definition of a class?

A: A type that is defined as a class is a reference type. At run time, when you declare a variable of a reference type, the variable contains the value null until you explicitly create an instance of the class by using the new operator, or assign it an object of a compatible type that may have been created elsewhere:
MyClass mc = new MyClass();
//Declaring another object of the same type, assigning it the value of the first object.
MyClass mc2 = mc;

That is great explaining from the C# guide by Microsoft.
You can read more from here

A: Classes serve two main purposes:

*

*encapsulation - putting code into different locations rather than just having one great big pile of random methods

*object orientation - having instances of classes (or value-types, in some cases) that represent a logical object (or value); you typically have many different concepts in a system, and many instances of each concept - for example, you might have a class to represent a "user", a class to represent an "order", etc (rather than just having a great big pile of random bytes as the data)


text:
Q: Access files outside a chroot'ed environment? I need to setup some users to access our server. I thought the most secure way to allow them access was to setup a chroot'ed jail for them to log into.
But I need them to access a few select directories that are outside the chroot'ed environment. Apparently I can't use symlinks for this. What is the best approach? Can a chroot'ed environment not be used for this purpose?

A: If it's on the same filesystem and it's individual files, hardlinks will work.
Softlinks will not work: the main purpose of a chroot'ed jail is that users can't get out to access files that aren't inside there.
You can use cp -lr to duplicate a directory tree with each file being a hardlink to the same underlying file, but that won't immediately pick up renames/moves, new files or deletes.
I think @SvenW has the best idea: move the directory into the chroot area and make the current location a symlink to the version inside the chroot.

A: This is a place where a bind mount will do what you want.


text:
Q: API resolved without sending a response for /api/holders/xxx, this may result in stalled requests I got this code and if I call this api I will get the response as expected but nextjs is still complaining with the warning:
API resolved without sending a response for /api/holders/xxx, this may result in stalled requests.
How can i fix this problem?
const handler = async (req, res) => {
  const { discordUserId, signedMessage, walletAddress } = req.body

  if (req.method === "POST") {
    // connect to db
    sqlConnection.connect((err) => {
      if (err) throw err
    })

    if (!(discordUserId && signedMessage && walletAddress))
      return res.json({ message: "not verfified" })
    // check if discord user id in database
    sqlConnection.query(
      `SELECT * FROM users WHERE discord_user_id = '${discordUserId}'`,
      (err, result) => {
        if (err) return res.json({ err })
        // if discord user id not found add new discord user id and wallet address
        if (result.length === 0) {
          const userData = {
            discord_user_id: discordUserId,
            wallet_address: walletAddress
          }
          sqlConnection.query("INSERT INTO users SET ?", userData, (err) => {
            if (err) return res.json({ err })
            return res.json({ message: "added to database" })
          })
        } else {
          // if discord user id found update wallet address
          sqlConnection.query(
            `UPDATE users SET wallet_address = '${walletAddress}' WHERE discord_user_id = '${discordUserId}'`,
            (err) => {
              if (err) return res.json({ err })
              return res.json({ message: "wallet address updated" })
            }
          )
        }
      }
    )
  }
}


text:
Q: forward return value of x-apikeyInfoFunc to operation I'm using openapi to define my API. I just added this security schema:
  securitySchemes:
    api_key:
      type: apiKey
      name: X-Auth
      in: header
      x-apikeyInfoFunc: apikey_auth

where apikey_auth is defined like this
def apikey_auth(token, required_scopes):
    decrypted_token = None
    try:
        decrypted_token = mydecrypter.decrypt(token)
    except InvalidToken:
        raise OAuthProblem('Invalid token')

    return {'decrypted_token': decrypted_token}

Now i'd like to use this authentication for my actual endpoints which are defined in openapi like this:
/myendpoint
   get:
      operationId: operation
      #more stuff
      security:
      - api_key: []

When now calling myendpoint the authentication is being done and works as expected. What I would like to have now is the return value of apikey_auth being passed into the call of operation so i can access decrypted_token in operation like this:
def operation(decrypted_token):
    data = get_data_for_token(decrypted_token)
    return data

Does anyone have an idea if this is possible somehow without having an extra parameter in the endpoint defintion?

A: Solved. For whatever reasons with these changes it works:
def apikey_auth(token, required_scopes):
    decrypted_token = None
    try:
        decrypted_token = mydecrypter.decrypt(token)
    except InvalidToken:
        raise OAuthProblem('Invalid token')

    return {'sub': decrypted_token}

def operation(user):
    data = get_data_for_token(user)
    return data


text:
Q: Return array to .get call from a Django View? I'm quite new to Django and jQuery and I'm having trouble getting data from my Django models into my jQuery.
My Django models look like this:

class Exercise(models.Model):
    name = models.CharField(max_length=30)
    description = models.CharField(max_length=500)
    rounds = models.IntegerField()

class Task(models.Model):
    Exercise = models.ForeignKey(Exercise)
    task = models.CharField(max_length=100)
    solution = models.CharField(max_length=100)
    description = models.CharField(max_length=500, blank=True)
    difficulty_level = models.IntegerField()

My jQuery:
var tasks = [];

// set up tasks
tasks.push(task("hun kaldes lilletøs","hun kaldes Lilletøs","Ret sætningen nedenfor, så der bliver stavet med store bogstaver efter reglerne.","Help tekst","Feedback tekst","2"));
tasks.push(task("john johnson","John Johnson","Ret sætningen nedenfor, så der bliver stavet med store bogstaver efter reglerne.","Help tekst","Feedback tekst","1"));
tasks.push(task("han hedder bent","han hedder Bent","Ret sætningen nedenfor, så der bliver

function task(text,solution, description, help, feedback, level){
    return {
        text:text,
        solution:solution,
        description:description,
        help:help,
        feedback:feedback,
        level:level,
    }
}

I created the jQuery first, and I'm therefor hoping that there's a way to get the Django data into my data structure in jQuery. The rest of my jQuery is very dependant on having the data in this format.
Here's what I have so far:
From my searches I've identified two different possible methods. Parsing the data directly into the jQuery via Django's template language or loading the data via ajax. I don't know which method is most efficient, and how exactly one should go about this best, but for some reasons it seems to me that using ajax would be the best solution.
The jQuery .load method doesn't seem like the best fit, since it's built to load data directly into HTML.
The jQuery .get method might be able to do it. Here's what I've tried doing:
Views.py:
def get_tasks(request):
    task_list = Task.objects.filter(Exercise_id=1)
    return HttpResponse(task_list)

jQuery:
$.get( "/get_tasks" )
            .done(function( data ) {
                var test = []
                test.push(data);
                alert(test)
            });

The ajax itself works. The data is retrieved, but it only shows the unicode representation, not the object. This is probably because I should return it in another way than HttpResponse, I just havn't figured out how to do this.
So the question is, how do I return an array to a jQuery .get call from a Django view?
EDIT:
Here's the code I have so far, it's giving me a 500 error with the jQuery call though

import simplejson
from django.http import HttpResponse
def get_tasks(request):
    task_list = Task.objects.filter(Exercise_id=1)
    tasklist = dict((x.id, {
        'task': x.task,
        'solution': x.solution,
        }) for x in task_list)
    return HttpResponse(simplejson.dumps(dict(isOk=1,tasklist=tasklist)))

A: Your view look like this
import simplejson
def get_tasks(request):
    task_list = Task.objects.filter(Exercise_id=1)
    tasklist = dict((x.id, {
        'field1': x.your_filed_name1,
        'field2': x.your_filed_name2,
    }) for x in task_list.iterator())
    return HttpResponse(simplejson.dumps(dict(isOk=1,tasklist=tasklist)))

your jQuery look like this
$.get( "/get_tasks" )
            .done(function( data ) {
                console.log(data.tasklist)
            });

A:
Parsing the data directly into the jQuery via Django's template
  language or loading the data via AJAX. I don't know which method is
  most efficient

You should use ajax, if the data you fetch from the server depends on some user choices on the page or if the amount of data is huge and would otherwise slow the loading of the page. Otherwise use Django templating instead to load the values into your javascript.
If you do need AJAX, I recommend checking out http://www.dajaxproject.com/. It's a nice little library to simplify AJAX-calls in Django.
Here's how it would look with Dajaxice (with the added example of passing parameters from the page to Django):
app/ajax.py:
from dajaxice.decorators import dajaxice_register
from django.utils import simplejson
from app.models import Task

@dajaxice_register(method='GET')
def get_tasks(request, exercise_id):
    task_list = Task.objects.filter(Exercise_id=exercise_id)
    return simplejson.dumps(task_list)

JS:
function get_tasks_callback(data){
    console.log(data);
}
var params = {'exercise_id': 1}
Dajaxice.app.get_tasks(get_tasks_callback, params);


text:
Q: Can not understand this pi calculate algorithm I saw a pi calculate algorithm on a website and it looks like that:
#include <stdio.h>
int a[52514],b,c=52514,d,e,f=1e4,g,h;
main(){
 for(;b=c-=14;h=printf("%04d",e+d/f)){
    for(e=d%=f;g=--b*2;d/=g){
        d=d*b+f*(h?a[b]:f/5);
        a[b]=d%--g;}
   }
}

it was said this code was based on this expansion,but i do not understand the relative between the code and the expansion.

pi= sigma( (i!) ^2*2^(i+1))/(2i+1)!
  (i=0 to infinite)

Could you help me explain it?Thanks.

A: pi+3=sigma( (m!)^2 * 2^m * m / (2*m)! ) (m=1 to infinite).

Algorithm's S Pflouffe use it.


text:
Q: activity will not authenticate with local DB The program I am having a issue with is a login page that uses a sqlite db for authentication and a registration page to insert data into the db. I am able to insert data into the db but my login class is not pulling the info from the dn to authenticate plus i receive no errors.
I put a printstackrtace() in my login class but am not sure what the info is actually saying.
db class:
     public class LoginDB extends SQLiteOpenHelper {

//Table attributes
public static final String DATABASE_NAME = "logindatadb";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME_CREDENTIALS = "credentials";

// Data attributes
public static final String COLUMN_NAME_USERNAME = "username";
public static final String COLUMN_NAME_PASSWORD = "passcode";

private static SQLiteOpenHelper DBHelper;
private static SQLiteDatabase db;

public LoginDB(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

        String sqlDataStore = "create table if not exists " +
        TABLE_NAME_CREDENTIALS + " ("+ BaseColumns._ID + " integer primary key autoincrement,"

                    + COLUMN_NAME_USERNAME + " text not null,"
                    + COLUMN_NAME_PASSWORD + " text not null);";

        db.execSQL(sqlDataStore);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        if(oldVersion == 1 && newVersion == 2){
            //Upgrade the database
    }

}

    public static boolean Login(String username, String password) {
        Cursor c =  db.rawQuery(
                "SELECT * FROM " + DATABASE_NAME + " WHERE "
                        + COLUMN_NAME_USERNAME + " = '" + username +"' AND "+ COLUMN_NAME_PASSWORD +" = '"+ password +"'" ,  null);
       if (c.getCount()>0)
          return true;
          return false;
    }

    public void open() {
        // TODO Auto-generated method stub
        db = DBHelper.getWritableDatabase();
    }
    public void close() {
        db.close();
    }

}
registration:
    private void insertCredentials(RegDetails regDetails){

        LoginDB androidOpenDBHelper = new LoginDB(this);

        SQLiteDatabase sqliteDB = androidOpenDBHelper.getWritableDatabase();

        ContentValues contentValues = new ContentValues();

        contentValues.put(LoginDB.COLUMN_NAME_USERNAME, rUsername);
        contentValues.put(LoginDB.COLUMN_NAME_PASSWORD, rPasscode);

        long affectedColumnid = sqliteDB.insert(LoginDB.TABLE_NAME_CREDENTIALS, null, contentValues);

        Toast.makeText(getApplicationContext(), "Credentials Saved! Please login" + affectedColumnid, Toast.LENGTH_SHORT).show();

        sqliteDB.close();
        finish();
    }

  }

Login:
            lsLogin.setOnClickListener (new OnClickListener() {

                @Override
                public void onClick(View v) {
                    //check login
                    String username = lsUsername.getText().toString();
                    String password = lsPassword.getText().toString();
                    try{
                        if(username.length()>0 && password.length()>0)
                        {
                            LoginDB dbUser = new LoginDB(LoginScrExample.this);
                            dbUser.open();

                        if(LoginDB.Login(username, password)) {
                            Intent goToNextActivity = new Intent(getApplicationContext(), menu.class);
                            startActivity(goToNextActivity);

                                Toast.makeText(LoginScrExample.this,"Login Sucessful",Toast.LENGTH_LONG).show();
                            }else{
                                Toast.makeText(LoginScrExample.this,"Invalid Username/Password",Toast.LENGTH_LONG).show();
                            }
                        dbUser.close();
                            }
                    }
                    catch(Exception err){
                        err.printStackTrace();
                        Toast.makeText(LoginScrExample.this," Something is wrong " ,Toast.LENGTH_LONG).show();

                    }

                    }
                       {

                       }

                                            }
                            );

Logcat when authentication is attempted:
     08-23 14:34:58.713: W/System.err(1396): java.lang.NullPointerException
     08-23 14:34:58.733: W/System.err(1396):    at com.LoginScr.Example.LoginDB.open(LoginDB.java:68)
     08-23 14:34:58.733: W/System.err(1396):    at com.LoginScr.Example.LoginScrExample$1.onClick(LoginScrExample.java:53)
     08-23 14:34:58.733: W/System.err(1396):    at android.view.View.performClick(View.java:3511)
     08-23 14:34:58.733: W/System.err(1396):    at android.view.View$PerformClick.run(View.java:14105)
     08-23 14:34:58.753: W/System.err(1396):    at android.os.Handler.handleCallback(Handler.java:605)
     08-23 14:34:58.753: W/System.err(1396):    at android.os.Handler.dispatchMessage(Handler.java:92)
     08-23 14:34:58.763: W/System.err(1396):    at android.os.Looper.loop(Looper.java:137)
     08-23 14:34:58.775: W/System.err(1396):    at android.app.ActivityThread.main(ActivityThread.java:4424)
     08-23 14:34:58.775: W/System.err(1396):    at java.lang.reflect.Method.invokeNative(Native Method)
     08-23 14:34:58.775: W/System.err(1396):    at java.lang.reflect.Method.invoke(Method.java:511)
     08-23 14:34:58.783: W/System.err(1396):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
     08-23 14:34:58.783: W/System.err(1396):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
     08-23 14:34:58.783: W/System.err(1396):    at dalvik.system.NativeStart.main(Native Method)
     08-23 14:35:20.533: W/IInputConnectionWrapper(1396): showStatusIcon on inactive InputConnection

A:   db = DBHelper.getWritableDatabase();

try changing this to
     db = this.getWritableDatabase();

as your helper class name is not db helper and you have just declared the DBHelper thats why it doesnt show a compilation error


text:
Q: Too many re-renders in ReactJs So I keep getting this too many re-renders error after trying this code... I cant add data.results immediately on the state because it is undefined on the beggining.
import React, { useState } from 'react';
import { useParams } from 'react-router-dom';
import NotFound from './NotFound';

const Gender = ({ data }) => {
    const { gender } = useParams();
    const [people, setPeople] = useState([]);

    if(data.results === undefined) return

Loading...

    setPeople(data.results)

    if( gender === 'male' ) {
        return null
    } else if(gender === 'female') {
        return null
    } else {
        return <NotFound />
    }
};

export default Gender;

A: Because as part of rendering you are setting state.  And setting state triggers a re-render.  So the code will bounce between these two things indefinitely.
Since you're not actually using state here, there's no need to, well, use state here.  The data you're using is passed to the component, so just rely on that.  No need to also put it in a state value.
Something like this:
const Gender = ({ data }) => {
    const { gender } = useParams();

    if(data.results === undefined) return

Loading...

    if( gender === 'male' ) {
        return null
    } else if(gender === 'female') {
        return null
    } else {
        return <NotFound />
    }
};


text:
Q: Use congruence's to find the reminder when $2^{50}$ and $41^{65}$ are divided by $7$ Use congruence's to find the reminder when $2^{50}$ and $41^{65}$ are divided by 7
$2^{50}$
$50=(7)^2+1$
$2^{50}=2^{7\cdot7+1}$
and I'm not sure where to go from here?

A: $\color\red{2^3}\equiv\color\red{1}\pmod7\implies$
$2^{50}\equiv2^{3\cdot16+2}\equiv(\color\red{2^3})^{16}\cdot2^2\equiv\color\red{1}^{16}\cdot2^2\equiv1\cdot4\equiv4\pmod7$

$\color\red{41}\equiv\color\red{-1}\pmod7\implies$
$\color\red{41}^{65}\equiv(\color\red{-1})^{65}\equiv(-1)\equiv6\pmod7$

A: Note that, $$\begin{align} & 2^3\equiv 1 \pmod7 \\ \implies & (2^3)^{16}\equiv 1^{16} \pmod7 \\ \implies & 2^{48}\equiv 1 \pmod7 \\ \implies & 2^{48}\cdot 2^2\equiv 1\cdot 2^2 \pmod7 \\ \implies & \color{blue}{2^{50}\equiv 4 \pmod7}\end{align}$$
Also note that $$\begin{align} & 41\equiv -1\pmod7 \\ \implies & 41^{65}\equiv (-1)^{65}\equiv -1\pmod7 \\ \implies & \color{blue}{41^{65}\equiv 6\pmod7}\end{align}$$


text:
Q: Relations between various definitions of a Radon measure The following various definitions of a Radon measure  seem to be given for the Borel sigma algebra of different types of topological spaces: general, Hausdorff, locally compact, or locally compact Hausdorff.
I was wondering if the definitions are related in some way?
Can these definitions or most of them be unified?
References are appreciated! Thanks and regards!

*

*From Measure Theory, Volumes 1-2 by Vladimir I. Bogachev

Let $X$ be a topological space. A Borel measure $\mu$ on $X$ is called a Radon measure if for every $B$ in $B(X)$ and
$ε>0$, there exists a compact set $K_ε ⊂ B$ such that $|\mu|(B - K_ε)  <ε$.

*From Wikipedia:

On the Borel $σ$-algebra of a Hausdorff topological space $X$, a
measure is called a Radon measure if it is

*

*locally finite, and

*inner regular.

*From ncatlab

If $X$ is a locally compact Hausdorff topological space, a Radon
measure on $X$ is a Borel measure on $X$ that is

*

*finite on all compact sets,

*outer regular on all Borel sets, and

*inner regular on open sets.

*From planetmath

Let $X$ be a Hausdorff space. A Borel measure $\mu$ on $X$ is said to
be a Radon measure if it is:

*

*finite on compact sets,

*inner regular (tight).

*From Wikipedia's Radon measures on locally compact spaces

When the underlying measure space is a locally compact topological
space, the definition of a Radon measure can be expressed in terms of
continuous linear functionals on the space of continuous functions
with compact support.

A: Schwartz (Radon measures on arbitrary topological spaces and cylindrical measures, 1973) defines Radon measures as comprising two measures. The first is the measure given in version 3 above and the second is the essential measure defined as locally finite, tight measure  He then shows that each can generate the other. On LCH spaces, version 3 equivalent to version 5.  Prinz (Regularity of Riesz measures, 1986, Proc Amer Math Soc) calls version 3 a "Riesz" measure and the locally finite, tight version a "Radon" measure and refers to Schwartz to give their duality.

A: I will concentrate on comparing (3) and (4). The definition (1) is meant for finite signed measures, whereas all the other definitions are meant for arbitrary positive measures; (1) is equivalent to (4) in the case of finite positive measures. (2) appears to be equivalent to (4) ["locally finite" can mean "finite on compact sets", although it is sometimes taken to mean "finite on the elements of some topological basis"; these are equivalent in the LCH (locally compact Hausdorff) case]. Finally, (5) does not appear to be a definition at all, but rather a description of a definition.
Now then,
i) In the case of a second countable LCH space, every locally finite measure satisfies both (3) and (4) (Theorem 7.8 of [1]). This is the most commonly considered scenario in applications, which is why almost no one bothers to carefully sort out the differences between the different definitions.
ii) In the case of a sigma-compact LCH space, (3) and (4) are equivalent. The forward direction is Corollary 7.6 of [1]; the backwards direction follows from the forward direction together with (iv) below (but I'm sure there is an easier proof).
iii) (3) and (4) are not equivalent in general, even for LCH metrizable spaces (Exercise 7.12 of [1]).
iv) In an LCH space, there is a bijection between
A) measures satisfying (3),
B) measures satisfying (4), and
C) positive linear functionals on the space of continuous functions with compact support.
(The Riesz representation theorem gives either (A)<->(C) or (B)<->(C), depending on where you look; (A)<->(B) is in the Schwarz book mentioned by Joe Lucke; see also Exercise 7.14 of [1])
[1] G. B. Folland, Real Analysis: Modern Techniques and Their Applications
Note: In [1], "Radon" refers to measures satisfying (3).


text:
Q: Chain of responsibility - how to call certain handler when current is failed I'm going to use Chain of responsibility pattern for simple CLI dialog:
type Handler interface {
    Request(flag bool)
}

type AskName struct {
    next Handler
}

func (h *AskName) Request(flag bool) {
    fmt.Println("AskName.Request()")
    if flag {
        h.next.Request(flag)
    }
}

type AskAge struct {
    next Handler
}

func (h *AskAge) Request(flag bool) {
    fmt.Println("AskAge.Request()")
    if flag {
        h.next.Request(flag)
    }
}

type AskEmail struct {
    next Handler
}

func (h *AskEmail) Request(flag bool) {
    fmt.Println("AskEmail.Request()")
}

func main() {
    handlerA := &AskName{&AskAge{new(AskEmail)}}
    handlerA.Request(true)
}

Question: imagine situation, when user entered invalid email. How can I re-call AskEmail handler (or call other handler at all)?
For example, if I split logic like this:
type AskEmail struct {
    next Handler
}

func (h *AskEmail) Request(flag bool) {
    fmt.Println("AskEmail.Request()")
    if flag {
        h.next.Request(flag)
    }
}

type ValidateEmail struct {
    next Handler
}

func (h *ValidateEmail) Request(flag bool) {
    fmt.Println("ValidateEmail.Request()")
}

how can I call AskEmail from ValidateEmail if ValidateEmail fails?

A: I think you can do this
type AskEmail struct {
    next Handler
}

func (h *AskEmail) Request(flag bool) {
    fmt.Println("AskEmail.Request()")
    if flag {
        h.next.Request(flag)
    }
}

type ValidateEmail struct {
    next Handler
    prev Handler
}

func (h *ValidateEmail) Request(flag bool) {
    fmt.Println("ValidateEmail.Request()")
    if !valid {
       h.prev.Request(flag)
    }
}

askEmail := &AskEmail{}
validateEmail := &ValidateEmail{prev: askEmail}
askEmail.next = validateEmail

A:
imagine situation, when user entered invalid email. How can I re-call AskEmail handler (or call other handler at all)?

In my opinion, the AskEmail "link" in the chain shouldn't call next unless it got back a valid e-mail address. Each "link" should only call next if its own responsibility has been handled - if you look at both https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern#UML_class_and_sequence_diagram and https://refactoring.guru/design-patterns/chain-of-responsibility you will see control only travels in one direction.
The example at https://github.com/yksz/go-design-patterns/blob/master/behavior/chain_of_responsibility.go is a bit simplistic
If you follow this idea, your code will become something like this:
func main() {
    // Build a chain of steps to take
    c := AskEmail{
        next: AskName{
            next: Print{},
        },
    }

    //  Run the chain with an empty "Person"
    c.Run(&Person{})
}

// Person holds the data that is relevant to your application. It should have a name that makes sense for your domain
type Person struct {
    Email string
    Name string
}

// PersonInfoChainLink is a link in the chain of command
type PersonInfoChainLink interface {
    Run(p *Person) (error)
}

// AskEmail can ask for an e-mail address
type AskEmail struct {
    next PersonInfoChainLink
}

func (a AskEmail) Run(p *Person) (error) {

    // Ask for e-mail addresses until the user gives a valid one
    var err error
    var email string
    for {
        email, err = askString(`What is your e-mail address?`)
        if err != nil {
            return err
        }

        if strings.Contains(email, `@`) {
            break
        }

        fmt.Printf("Invalid e-mail address %s!", email)

    }
    p.Email = email

    return a.next.Run(p)
}

// AskName can ask for the name of a person
type AskName struct {
    next PersonInfoChainLink
}

func (a AskName) Run(p *Person) (error) {
    name, err := askString(`What is your name?`)
    if err != nil {
        return err
    }
    p.Name = name
    return a.next.Run(p)
}

// Print can print the information about a person
type Print struct {

}

func (Print) Run(p *Person) (error) {
    log.Printf(`Email %s at %s!`, p.Name, p.Email)
    return nil
}

func askString(question string) (string, error) {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print(question + ` `)
    return reader.ReadString('\n')
}


text:
Q: Overriding RouteValueDictionary in a Constraint in ASP.NET Core I've just started using ASP.NET Core MVC and I want one route (global slug) to go to multiple controllers and actions depending on what type of page I'm serving to the user. For example, I want to use {*slug} for category and product pages.
I'm trying to override the default controller and action in a constraint.
In past versions of MVC, you could change either values["controller"] or values["action"] in a constraint and it would re-route to the appropriate controller and action.
public class Startup
{
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {

        app.UseMvc(routes =>
                    {
                        routes.MapRoute(
                            name: "Category",
                            template: "{*slug}",
                            defaults: new { controller = "Page", action = "Home" },
                            constraints: new { slug = new PageConstraint() }
                            );
                    });

    }

}

public partial class PageConstraint : IRouteConstraint
{
    public virtual bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
    {
        if (routeDirection == RouteDirection.UrlGeneration)
        {
            return true;
        }

        var slug = values["slug"] != null ? values["slug"].ToString() : null;

        if (string.IsNullOrWhiteSpace(slug))
        {
            // Homepage
            return true;
        }

        // Get category service
        var categoryService = httpContext.RequestServices.GetRequiredService<ICategoryService>();

        var category = categoryService.GetBySlug(slug);

        if (category == null)
        {
            return false;
        }

        values["controller"] = "Category";
        values["action"] = "Listing";
        values["category"] = category;

        return true;
    }
}

In PageConstraint, I look to see if the Category exists, and if it does, it changes the Controller to Category and the Action to Listing in the RouteValueDictionary. However, when I debug the code through, it still goes to the Controller Page and the Action Home.
Anyone know why this is happening, or whether there is a better way of doing this? I know I could have one action in a controller doing all the work that the constraint is, but I would prefer to house the code in separate controllers and actions.

A: For your requirement, you could try to implement custom IRouter
public class RouterFromAppSettings : IRouter
{
    private readonly IRouter _defaulRouter;
    private readonly IConfiguration _config;
    public RouterFromAppSettings(IRouter defaulRouter
        , IConfiguration config)
    {
        _defaulRouter = defaulRouter;
        _config = config;
    }
    public async Task RouteAsync(RouteContext context)
    {
        var controller = _config.GetSection("Router").GetValue<string>("Controller");
        var action = _config.GetSection("Router").GetValue<string>("Action");
        context.RouteData.Values["controller"] = controller;
        context.RouteData.Values["action"] = action;
        await _defaulRouter.RouteAsync(context);
    }
    public VirtualPathData GetVirtualPath(VirtualPathContext context)
    {
        return _defaulRouter.GetVirtualPath(context);
    }
}

And then register it in Startup.cs like
app.UseMvc(routes =>
{
    routes.Routes.Insert(0, new RouterFromAppSettings(routes.DefaultHandler,Configuration));

    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});


text:
Q: Process with an ID #### is not running in visual studio 2019 I am trying to run any program on visual studio 2019 and I get the following alert box :
Process with an ID #### is not running . // every time there is different ID number showing
and in the error windows I get this error msg:
Sometimes it runs and in the browser I get the following message :
The webpage is not available.

A: Close Visual Studio
Open the project file in Notepad
Delete the below 3 lines
<DevelopmentServerPort>#</DevelopmentServerPort>
<DevelopmentServerVPath>/</DevelopmentServerVPath>
<IISUrl>http://localhost:#/</IISUrl>

Save the file
Reopen the Visual Studio and run it