text:
Q: Call a function if not an element was clicked in svg, but other elements using d3.js v5.4.0 How could I call a function if not an element was clicked in svg, but other elements using d3.js v5.4.0?
For example, I would like the alert message to be displayed only when the xhtml:input is not clicked (and one of the other elements is clicked), but it shows up even if the xhtml:input was clicked as you can see here.
In other words I would like to preserve the functionality which is present in the fiddle, but prevent alert from being executed whenever the xhtml:input is clicked.

A: Well there's a foreignObject that can be looked for in window.event.path after a click.
Check this snippet

var svg = d3.select("#drawRegion")
  .append("svg")
  .attr("width", "100%")
  .attr("height", "100%");
svg.append("rect")
  .attr("x", "0")
  .attr("y", "0")
  .attr("width", "100%")
  .attr("height", "100%")
  .attr("fill", "yellow");

const fObj = svg
.append("foreignObject");
fObj
  .attr("x", "10%")
  .attr("y", "10%")
  .attr("width", "80%")
  .attr("height", "40%");

            const inputArea = fObj
                .append("xhtml:input");
            inputArea
                .style("position", "absolute")
                .style("top", 0)
                .style("width", "100%")
                .style("height", "100%")
                .style("border-radius", "40px")
                .style("border", "none")
                .style("text-align", "center")
                .style("outline", "none");

svg.on("mouseup.inputDialogueInteractionName touchend.inputDialogueInteractionName", function() {
  let isInput = false;
  window.event.path.forEach(function(pathObj){
   if (pathObj.tagName =="foreignObject") isInput = true;
  })
  if (!isInput) alert("not input")
  else console.log("input")
            });
#drawRegion {
  width: 100%;
  height: 100%;
  display: inline-block;
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  position: relative;
}
<div id="drawRegion">

</div>
<script src="https://d3js.org/d3.v5.min.js"></script>


text:
Q: JQuery UI Datpicker excluding icons I'm working on an application and am using jQuery UI Datepicker widget. But I do not want to use the default icons from the datepicker and want the Next and Prev text in place of the icons that is visible when I remove the icon classes.
I'm currently on a code like this:
$("#datePicker").on("click", function(){
    $('.ui-icon.ui-icon-circle-triangle-w').removeClass('ui-icon ui-icon-circle-triangle-w');
})

where datePicker is the id for the date field.
This works fine when I initially open the datepicker. But, when I click the Prev button, the icons appear again. How can I persist with the Next/Prev even when I switch the month view.

A: Here you go with the solution http://jsfiddle.net/8w8v9/3308/

$(function(){

    $('#thedate').datepicker({
        dateFormat: 'dd-mm-yy',
        altField: '#thealtdate',
        altFormat: 'yy-mm-dd',
        prevText: "Prev",
        nextText: "Next"
    });

    replaceIcon = function(){
   $('.ui-icon.ui-icon-circle-triangle-w').parent().removeAttr('class').attr('class', 'updatedClassLeft');
      $('.ui-icon.ui-icon-circle-triangle-w').removeAttr('class');

      $('.ui-icon.ui-icon-circle-triangle-e').parent().removeAttr('class').attr('class', 'updatedClassRight');
      $('.ui-icon.ui-icon-circle-triangle-e').removeAttr('class');

    }

    $("#thedate").on("click", function(){
     replaceIcon();
   });

    $(document).on('click','.updatedClassLeft, .updatedClassRight',function(){
     replaceIcon();

    });
});
.updatedClassLeft{
    position: absolute;
    top: 8px;
    left: 0px;
    cursor: pointer;
}
.updatedClassRight{
    position: absolute;
    top: 8px;
    right: 2px;
    cursor: pointer;
}
<link href="http://code.jquery.com/ui/1.8.21/themes/base/jquery-ui.css" rel="stylesheet"/>

Shown Field : <input id="thedate" type="text" />

Hidden Field : <input id="thealtdate" type="text" />

<input id="thesubmit" type="button" value="Submit" />

A: I would just add more specific CSS rule in your CSS file, that should fix it. Starting point:
body .ui-datepicker .ui-datepicker-prev,
body .ui-datepicker .ui-datepicker-next {
    width: 2.6em;
}

body .ui-datepicker .ui-datepicker-prev span.ui-icon.ui-icon-circle-triangle-w,
body .ui-datepicker .ui-datepicker-next span.ui-icon.ui-icon-circle-triangle-e {
    background: none;
    overflow: visible;
    text-indent: 0;
    width: initial;
    left: 30%;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Powershell Console Menu Options - Need to add line breaks? I've created a console menu from some code I modified.
I use the following code and use the switch command to go to the menu choices outlined in this code:
# new menu for remote tasks ps1
$Title = "Remote Tasks"
$Message = "Please enter your selection below:"
$remoteRestartComputer = New-Object System.Management.Automation.Host.ChoiceDescription "&1 Restart one or more remote computer(s)", `
    "Restart one or more remote computer(s)"
$remoteShutdownComputer = New-Object System.Management.Automation.Host.ChoiceDescription "&2 Shutdown one or more remote computer(s)", `
    "Shutdown one or more remote computer(s)"
$wakeOnLanComputer = New-Object System.Management.Automation.Host.ChoiceDescription "&3 Start/Wake VM Station", `
    "Start/Wake VM Station"
$getOutThisB = new-object System.Management.Automation.Host.ChoiceDescription "&4 Exit", `
    "Exit"
$Options = [System.Management.Automation.Host.ChoiceDescription[]]($remoteRestartComputer, $remoteShutdownComputer, $wakeOnLanComputer, $getOutThisB)
$selectRemoteTask = $host.ui.PromptForChoice($Title, $Message, $Options, 0)

The problem is in the console window it shows a couple of the choices on the same line, i.e.:
Remote Tasks
Please enter your selection below:
[1] 1 Restart one or more remote computer(s)
[2] 2 Shutdown one or more remote computer(s)[3] 3 Start/Wake VM Station
[4] 4 Exit[?] Help (default is "1"):

Any way to add line breaks so this looks nicer?  Thanks in advance.

A: I made this a while ago as an answer for some question on here, I don't even remember what it was. I think it had to do with ASCII pipe characters to make borders. This will make your menu, with an optional title, and display it. Then you just need to display your Get-Host, put it in a loop, and then move on to your switch.
Function MenuMaker{
    param(
        [string]$Title = $null,
        [parameter(Mandatory=$true,
        ValueFromPipeline = $true)][String[]]$Selections
        )

    $Width = if($Title){$Length = $Title.Length;$Length2 = $Selections|%{$_.length}|Sort -Descending|Select -First 1;$Length2,$Length|Sort -Descending|Select -First 1}else{$Selections|%{$_.length}|Sort -Descending|Select -First 1}
    $Buffer = if(($Width*1.5) -gt 78){(78-$width)/2}else{$width/4}
    if($Buffer -gt 4){$Buffer = 4}
    $MaxWidth = $Buffer*2+$Width+$($Selections.count).length
    $Menu = @()
    $Menu += "╔"+"═"*$maxwidth+"╗"
    if($Title){
        $Menu += "║"+" "*[Math]::Floor(($maxwidth-$title.Length)/2)+$Title+" "*[Math]::Ceiling(($maxwidth-$title.Length)/2)+"║"
        $Menu += "╟"+"─"*$maxwidth+"╢"
    }
    For($i=1;$i -le $Selections.count;$i++){
        $Item = "$i`. "
        $Menu += "║"+" "*$Buffer+$Item+$Selections[$i-1]+" "*($MaxWidth-$Buffer-$Item.Length-$Selections[$i-1].Length)+"║"
    }
    $Menu += "╚"+"═"*$maxwidth+"╝"
    $menu
}

You would call it as such:
MenuMaker -Title $Title -Selections "Restart one or more remote computer(s)","Shutdown one or more remote computer(s)","Start/Wake VM Station","Exit"

Sure, it doesn't include Help, but it does make a nice pretty menu for you. You could probably modify the function to add a -Help switch to display a ? - Help line, or just include Help as one of your selections. Then you just do something like:
Do{
MenuMaker -Title $Title -Selections "Restart one or more remote computer(s)","Shutdown one or more remote computer(s)","Start/Wake VM Station","Exit"
$Selection = Read-Host "Please enter your selection (? for Help)"}While($Selection -notin (1..4) -or $Selection -eq "?")

Edit: Switch example (updated above code to include ? for help!):
Switch($Selection){
    4 {Continue}
    3 {Run code to Start/Wake VM Station}
    2 {Run code to shutdown remote computer}
    1 {Run code to restart remote computer}
    "?" {Run code to display Help}
}

A: The following newline character worked for me
[Environment]::NewLine

Edit:
"`n" usually works (note the backtick)

A: I know this is a really old post, but I found your menu layout and its really well done.
I updated it so it was able to run by referencing the unicode characters since it was throwing some errors regarding special characters for me.
incase you or anyone else wanted to still use it, here it is so no one else has to go through the hassle of looking up the characters :D
Function New-Menu{
param(
    [string]$Title = $null,
    [parameter(Mandatory=$true,
    ValueFromPipeline = $true)][String[]]$Selections
    )

$Width = if($Title){$Length = $Title.Length;$Length2 = $Selections|ForEach-Object{$_.length}|Sort-Object -Descending|
Select-Object -First 1;$Length2,$Length|Sort-Object -Descending|Select-Object -First 1}else{$Selections|ForEach-Object{$_.length}|
Sort-Object -Descending|Select-Object -First 1}
$Buffer = if(($Width*1.5) -gt 78){(78-$width)/2}else{$width/4}
if($Buffer -gt 4){$Buffer = 4}
$MaxWidth = $Buffer*2+$Width+$($Selections.count).length
$Menu = @()
$Menu += "$([char]0x2554)"+"$([Char]0x2550)"*$maxwidth+"$([char]0x2557)"
if($Title){
    $Menu += "$([Char]0x2551)"+" "*[Math]::Floor(($maxwidth-$title.Length)/2)+$Title+" "*[Math]::Ceiling(($maxwidth-$title.Length)/2)+"$([Char]0x2551)"
    $Menu += "$([Char]0x255F)" +"$([char]0x2500)"*$maxwidth+"$([Char]0x2562)"
}
For($i=1;$i -le $Selections.count;$i++){
    $Item = "$i`. "
    $Menu += "$([Char]0x2551)"+" "*$Buffer+$Item+$Selections[$i-1]+" "*($MaxWidth-$Buffer-$Item.Length-$Selections[$i-1].Length)+"$([Char]0x2551)"
}
$Menu += "$([char]0x255a)"+"$([Char]0x2550)"*$maxwidth+"$([char]0x255D)"
$menu

}

A: It's partially possible with escaped backspaces (`b)
$OfficeOptions = @($i=0;@("No office","Office 2010","Office 2013","Office 2016") | ForEach-Object {
    New-Object System.Management.Automation.Host.ChoiceDescription ("&$i`b`b$($_)" + [Environment]::NewLine + "`b`b`b`b")
    $i++
})

$OfficeVersion = $Host.UI.PromptForChoice("Office version", "Choose office version", $OfficeOptions, 0)

It will however display 2 spaces on each following line.


text:
Q: Perceptual Image Downsampling So here is my problem:
I have an image, that image is large (high resolution) and it needs to be small (much lower resolution).
So I do the naive thing (kill every other pixel) and the result looks poor.
So I try to do something more intelligent (low pass filtering using a Fourier transform and re-sampling in Fourier space) and the result is a little better but still fairly poor.
So my question, is there a perceptually motivated image down-sampling algorithm (or implementation)?
edit:
While I am aware of a number of resampling techniques, my application is more concerned with preserving the perceptual features, rather than producing smooth images.
edit2: it is safe to assume I have some level of familiarity with digital signal processing, convolutions, wavelet transforms, etc

A: Read this:
http://www.dspguide.com/
OK, that's quite a read. But understanding filter design would be handy.
In general, the process for scaling an image from W1 x H1 to W2 x H2 where W1, W2, H1, H2 are integers, is to find new W3, H3 so that W1 and W2 are integer factors of W3 and H1 and H2 are integer factors of H3, and then pad the original image with zeros (used to space the pixels of the original image) so that it's now W3 x H3 in size. This introduces high frequencies due to discontinuities in the image, so you apply a low-pass filter to the image, and then decimate the filtered image to its new size (W2 x H2). Sounds like you might be trying to do this already, but the filtering can be done in the time domain so that the Fourier transform isn't really necessary.
In practice, the process I just described is optimized (you'll note that when applying a convolution filter to the upscaled image most of the terms will be 0, so you can avoid most of the multiplication operations in your algorithm, for example. And since you end up throwing away many of the filtered results, you don't need to calculate those, so you end up with a handful of multiplications and additions for each pixel in the target image, basically. The trick is to figure out which coefficients to use.)
libswscale in the ffmpeg project does something like this, I believe. Check it out:
http://gitorious.org/libswscale
As others pointed out, (and you apparently noticed) decimating the image introduces aliasing artifacts. I can't be sure about your resampling implementation, but the technique has interesting gotchas depending on the window size you use and other implementation details.

A: Bicubic interpolation is generally regarded as good enough, but there is no perfect solution, it depends on people and on the properties of the picture being resampled.
Related links:
I didn't even know that sharpness was also called acutance.
Aliasing is a problem that can occur when downsampling naively.

A: Pascal is right. Depends on the image, and on what you want. Some factors:

*

*preserving sharp edges

*preserving colours

*algorithm speed

This is your method.
Some others:

*

*Lanczos resampling

*Bicubic interpolation

*Spline interpolation
Note that sometimes resampling down can get you a sharper result than, say, using a lower resolution camera, because there will be edges in the high-resolution image that cannot be detected by a lower-res device.
Side note: Many algorithms (especially Nearest Neighbour) can be optimised if you are scaling down by an integer (e.g. dividing by 4 or 6).

A: Recommended ImageMagick "general purpose" downsampling methods are discussed here: http://www.imagemagick.org/Usage/filter/nicolas/#downsample

A: You could try a content aware resizing algorithm. See: http://www.seamcarving.com/

A: Paint Mono (an OS fork of Paint.NET) implements Supersampling algorithm for image downsampling here: http://code.google.com/p/paint-mono/source/browse/trunk/src/PdnLib/Surface.cs?spec=svn59&r=59#1313


text:
Q: Windows: Cancel WOW6432Node mapping of registry keys when running reg command from 32-bit Java I tried making registry changes by running WScript that runs reg, but it still gets re-routed to WOW6432Node.
Is there a way I can get either a WScript or CMD script (or Java) to force use of the 64bit section?
There are functions for this, but I do not know how to use them in WScript (VBScript/JScript) or Java.

A: You just need to explicitly launch the 64-bit version of reg.exe from %SystemRoot%\sysnative.
Check first whether the folder exists.  If it doesn't, you're either on a 32-bit system or already running in 64-bit context, and you can just run the version from %SystemRoot%\system32 as usual.


text:
Q: Excel: return the number of cells that are not blank I am trying to find a function that will return the number of cells within a given range that have a number in them.  I want to count the number of responses that people gave, irregardless of the value they entered in the cell.
How do I do this?

A: If you are looking for a number of cells containing numeric values, then COUNT() function is what you're looking for:
=COUNT(A1:D6)

If you are looking number of cells with non-blank values (numeric or otherwise), then COUNTA() is the right function:
=COUNTA(A1:D6)

The last formula works only if none of the cells have empty strings as values (i.e. none of the cells in the range have ="" or something equivalent in them).  If that is the case, then this formula should be used instead:
=SUMPRODUCT((E7:G10<>"") * 1)

A: You can use the LEN function to find the length of the input of a cell, and then test if it's greater than zero or not.
=LEN(A1)>0

A: You have to use count to count the number of numbers:
=COUNT(Your_range)

Count will not count the number of cells that do not have a number (but those don't count do they?)


text:
Q: how to create a function that work in specific width in CSS is it possible to create a function in javascript or jquery that work in specific width in CSS
like I want to create a button that alert("hello world") but this will work only on mobile screen in other media queries will do nothing

A: I don't think it's possible, You can use the following code to get the width:
// Size of browser viewport.
$(window).width();

// Size of HTML document (same as pageHeight/pageWidth in screenshot).
$(document).width();

so if you want to apply on mobile, you can add a condition
if ($(window).width() <= 425) {
   // Do something
   alert("hello world")
}

A: if ($(window).width() < 768){
  // do something
}

if using jquery

A:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    if ($(window).width() <= 575) {
        alert("hello world")
        }
});
</script>
</head>
<body>

</body>
</html>


text:
Q: codeigniter mutiple select queries dependent on each other I'm a newbie in codeigniter (CI) and I need to select the logged-in user's competitions and total votes , let say users and competition tables have many-to-many relation and the same goes with the competition items.
I need to select the user's competitions and all items votes that relate to that user; also I need to select all competitions' votes and get the total votes for each one of them.
after all that goes on , all the result must be displayed in one view (and that is the most complicated part) for example , I can't manipulate all that in one model and how to return many arrays to a controller ,so on.
here's an example to my contoller :
<?php
class User_id extends CI_Controller{

    function __construct()
    {
       parent::__construct();
       $this->load->helper(array('form', 'url'));
       $this->load->library('session');
    }

    function index(){
        $this->load->view('v_user_id');
    }

    function view_comp(){
        $c_id = $this->input->post('id');
        $this->session->set_userdata('c_id',$c_id);
        $s_id = $this->session->userdata('c_id');
        $this->load->model('comps_model');
        $data['rows'] = $this->comps_model->getComps($s_id);
    }
}
?>

and here's my aim model that should contain 'all select queries' and return 'all results' previously mentioned :
<?php
class Comps_model extends CI_Model{

    function getComps($id){

        $this->load->database();
        $id = $this->db->query("select competition_id from user_competition        where user_id='".$id."'");
        if($id->num_rows() > 0){
            foreach($id->result() as $id_row){
                $comp_name = $this->db->query("select competition_title from competition where competition_id='".$id_row->competition_id."'");
                if($comp_name->num_rows() > 0) {
                    //all the stuff should go here or something like that
                }
            }
        }
    }

}
?>

I'd be grateful for some code examples :)

A: You can try like this
function getComps($id)
{
    $this->load->database();
    $data=array();
    $id = $this->db->query("select competition_id from user_competition where user_id='".$id."'");
    if($id->num_rows() > 0)
    {
        $data=$id->result_array();
    }
    foreach($data as $key=>$each)
    {
        //adding competition title
        $comp_name = $this->db->query("select competition_title from competition where competition_id='".$each['competition_id']."'");
        if($comp_name->num_rows()>0){
            $temp=$comp_name->row_array();
            $data[$key]['competition_title']=$temp['competition_title'];
        }
        else
        {
            $data[$key]['competition_title']="";
        }
        //other calculations will go on
    }
    echo "<pre>";print_r($data);die;
}

if you do like this the everytime you will calculate some value and insert the value in the existing data array.for example if you count total votes then with in the foreach loop count the total and insert to the array like
  $data[$key]['total_votes']=$temp['total_votes'];

please let me know if you face any problem.


text:
Q: How to remove only one inline
A: I have never used WordPress but installed it on my localhost and tried to modify the (e.g.) h1 tag with class="site-title" on the default template.
Just search on the folder for 'site-title' and found the header.php according to the activated template or your custom template.
Some code is generated by php and then sent to user so maybe to try to find a class that hasn't the same name in your php files than you see in your html received files. Try to find class/id in some tags near the one you want to change.
I hope it helps.

A: wp_enqueue_style takes 5 parameter
$handle
(string) (Required) Name of the stylesheet. Should be unique.
$src
(string) (Optional) Full URL of the stylesheet, or path of the stylesheet relative to the WordPress root directory.
Default value: ''
$deps
(array) (Optional) An array of registered stylesheet handles this stylesheet depends on.
Default value: array()
$ver
(string|bool|null) (Optional) String specifying stylesheet version number, if it has one, which is added to the URL as a query string for cache busting purposes. If version is set to false, a version number is automatically added equal to current installed WordPress version. If set to null, no version is added.
Default value: false
$media
(string) (Optional) The media for which this stylesheet has been defined. Accepts media types like 'all', 'print' and 'screen', or media queries like '(orientation: portrait)' and '(max-width: 640px)'.
Default value: 'all'
You can change your code in function.php file
wp_enqueue_style( 'mycustom_css', get_template_directory_uri() . '/custom.css', array(), '1.0.0', true );

it will be work. check that you have only one custom.css file in your theme root .

A: You can use wp_dequeue_style  and wp_deregister_style.
If you are going to view source, you can see the WP_HEAD generate link style like below:
 <link rel='stylesheet' id='mystyle-css'  href='www.your_domain.com/css.style.css' type='text/css' media='all' />

Now, if you want to remove this line, just go to your functions.php and include the code below:
function dequeue_unnecessary_styles_vxt() {
    $styles = array('mystyle'); //store here all the CSS you want to remove
    foreach ($styles as $key => $value) {
        wp_dequeue_style( $value );
        wp_deregister_style( $value );
    }
}
add_action( 'wp_print_styles', 'dequeue_unnecessary_styles_vxt' );

I have edited the code above so you can dynamically remove all css styles you want to remove. Note that, from css link style, there is an id called, mystyle-css this is how you will track the css in your custom functions.php. Add the ID (without -css) insde the $styles.
Hope it helps.

A: Go to your header file, probably in the <head> you will find
<?php echo get_template_part('customcss'); ?>

And also there is customcss.php in your theme folder. But you should be aware this is the styles you assign in your WordPress Dashboard and deleting it, won't be as happy ever after as you think. You can delete the code or change customcss.php. If it is not as that, look for some phrase of php that echo your CSS file.

A: Consider executing the hook with low preference like 100 or above.
add_action( 'wp_enqueue_scripts', function() {
    //conditional tags or check function
        wp_dequeue_style( 'inline-style-id' );
    }
}, 100 ); //important to pass it with low preference.


text:
Q: Can't read data from JSON file in local folder in Angular 7 I have the below code and it works fine.
 searchData() {
 const url: any = 'https://jsonplaceholder.typicode.com/photos?albumId=1';
 this.http.get(url).subscribe((res) => {
 this.data = res;
 console.log('Response Returned');
 },
  err => {
    console.log('Error Response');
  });

Output: Response Returned
Expected: Response Returned
Now instead of URL, I want to fetch data from a local JSON file which is kept in the assets folder, so I changed the path and gave the path of the JSON file, however, if I give local path the code goes to err part and in response, I get Error Response.
Can someone help me figure out how to read from a local JSON file?
Code for Local JSON file
searchData() {
     const ucv_data: any = 'src/assets/json/ucv_json.json';
    this.http.get(ucv_data).subscribe((res) => {
      this.data = res;
      console.log('Response Returned');
    },
      err => {
        console.log('Error Response');
      }
    );
 }

Output: Error Response
Expected: Response Returned
Angular.json file
{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "test-ng7": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist",
            "index": "src/index.html",
            "main": "src/main.ts",
            "tsConfig": "src/tsconfig.app.json",
            "polyfills": "src/polyfills.ts",
            "assets": [
              "src/assets/json",
              "src/assets/images",
              "src/favicon.ico"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css",
              "./node_modules/bootstrap/dist/css/bootstrap.min.css",
              "./node_modules/font-awesome/css/font-awesome.css",
              "./node_modules/font-awesome/css/font-awesome.min.css",
              "src/styles/app.scss","src/assets/css/material.scss",
              "src/assets/css/styles.scss"

            ],
            "scripts": [
              "node_modules/chart.js/dist/Chart.js",
              "./node_modules/jquery/dist/jquery.min.js",
              "./node_modules/bootstrap/dist/js/bootstrap.min.js"

            ]
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "test-ng7:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "test-ng7:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "test-ng7:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "scripts": [
              "node_modules/chart.js/dist/Chart.js"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css",
              "node_modules/font-awesome/css/font-awesome.css",
              "src/styles/app.scss"
            ],
            "assets": [
              "src/assets",
              "src/assets/images",
              "src/favicon.ico"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "test-ng7-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "prefix": "",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "test-ng7:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "test-ng7:serve:production"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "test-ng7",
  "schematics": {
    "@schematics/angular:component": {
      "prefix": "app",
      "styleext": "scss"
    },
    "@schematics/angular:directive": {
      "prefix": "app"
    }
  }
}

A: The path is relative from the src folder. Try
const ucv_data: any = 'assets/json/ucv_json.json';

Update
Based on the OP's comment, the assets property definition is
"assets": [
  "src/assets/json",
  "src/assets/images",
  "src/favicon.ico"
]

So the call should be made to location /json/ucv_json.json.

A: With Angular 7+ we can import JSON like modules.
In tsconfig file put:
{  "compilerOptions": {  "resolveJsonModule": true, "esModuleInterop": true } }

And you can import it like this afterwords.
import ucv_data from "assets/json/ucv_json.json"


text:
Q: Arrays of data classes in C# I've been messing around with this for ages and I'm not getting any closer.
My current version is as below. The comments are what I think I'm doing.
The semantic is basically an index number (like a house number) and a list of attributes in an array. Then create an array 'street'. I want to be able to update the values of all elements in the current scope. The class is defined as high as possible so as to make the scope global. My ossified 'C' brain doesn't really understand things like lists and IEnumerable so I haven't tried to go that route. The code parser in the editor makes a bit of a mess of this - sorry.
public class house
{

      // Ok, looking at this from the world of 'C' and thinking 'struct' like,
      // I put my variables here.

      public int my_id;
      public long [] pl_id;

      public house()
      {
         // I try to initialise the starting values, so I can carry out some tests later.
         my_id = 0;
         pl_id = new long[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
      }
  }

// I attempt to inform the compiler that I will be wanting an array of the house objects
// and call that array 'new_house'. Again, the code editor isn't keen.

  house [] new_house;

    private void button1_Click(object sender, EventArgs e)
    {
      // In the programs main routine (not *main*!), I then try to get the
      // array 'new_house' populated with initialised 'house' objects
      for (int idx = 0; idx < 10; idx++)
       {
          new_house[idx] = new house();
       }

       // And at some point in the future I wish to set or update the values arbitrarily. eg:
        new_house[7].my_id = 123;
        new_house[7].pl_id = 345678;
        // any combination of attributes and id numbers is possible, so I use zero simply to see if they have been set, with -1 indicating failure / an absence of data-
    }
}

Right. As I say, I've tried a lot of different ways to do this, and the main problem I am getting is that I never seem to correctly initialise the array 'new_house' and get null exceptions thrown when I try to assign anything. I can't believe something that seems so intuitively simple can be so hard to code, so where have I got it wrong (and I fully accept that there could be more than one conceptual or coding error in the above).
Comments on appropriateness of approach, and help with coding alike, gratefully accepted.

A: The first obvious problem with your code is that your constructor doesn't have the same name as the class. It should be this:
public house()
{
   // ...
}

A second point is you don't need the constructor at all here:
public int my_id = 0;   // The "= 0" is actually not needed here either.
public long[] pl_id = new long[10];

I would also suggest that you don't use arrays for things like houses on a street because house numbers won't necessarily be sequential. You can have gaps and even multiple houses with the "numbers" 5A and 5B. A dictionary might be a better choice.
IDictionary<string, house> houses = new Dictionary<string, house>();

If you really want to have sequential numbering you might want to consider a List<house> instead of an array so that it can be easily extended if new houses are built.
Finally I'd advise using PascalCase for classes. It will make your code much easier to read if you use the same standards as the rest of the .NET framework.

A: You need to instantiate the array before initializing items of it:
house[] new_house = new house[10];
Replace 10 with desired number of items.
In case you don't know the number, use List:
List<house> new_house = new List<house>()
Then you can dynamically add items using new_house.Add(item) and access them in foreach loop or through index new_house[i]

A: Change public game()
to public house()
Your constructor has to have the same name as the class.

A: A couple things:

*

*new_house is never initialized. You can't use it until you've initialized it.

*pl_id is an array, but you attempt to store a long in it (345678) -- you could change it to new int[] { 345678}.

*You've got a method, game(), in the class house which looks and acts like a constructor. You would have to name it house() if it is meant to be a constructor.

A: not public game()
right: public house()
Always the constructor has to have the same name as the class.

A: Use List<T> for those collections. Try not to say you don't understand something because you are 'c' addicted. Try to say yourself you want to try something new and search for a good solution
namespace Myprog
{
// I attempt to inform the compiler that I will be wanting an array of the house objects
// and call that array 'new_house'

  List<house> houselist = new List<house>();

    private void button1_Click(object sender, EventArgs e)
    {
      // In the programs main routine (not *main*!), I then try to get the
      // array 'new_house' populated with initialised 'house' objects
      for (int idx = 0; idx < 10; idx++)
       {
          houselist.add(new house());
       }

       // And at some point in the future I wish to set or update the values arbitrarily. eg:
        houselist[7].my_id = 123;
        // any combination of attributes and id numbers is possible, so I use zero simply to see if they have been set, with -1 indicating failure / an absence of data-
    }
  }
}


text:
Q: Ruby on Rails: Reference to a singleton class action in routes I am trying to work over a class using Ruby on Rails in order to create a simple controller. In that sense, I have a singleton and I need to refer routes to it. How is it possible?
The message I get:

The action 'foo' could not be found for Test::TestController

The controller file, inside a Test folder:
class Test::TestController < ApplicationController
    class << self
            def index
                    render json: {test:"Hello World!"}
            end
            def foo
                    render json: {response:"It works!"}
            end
    end
end

The routes file:
Rails.application.routes.draw do
    namespace 'test' do
            resources :test
    end
    get '/:id', to: 'test/test#foo'
end

A: Its not possible. And its not even a remotely good idea.
Rails controllers take their input in form of the request and env which encompasses things like server settings and anything the middleware has stuffed away as initializer arguments. They are not globals like in for example PHP.
The actions of a controller themselves don't actually take any arguments. So even if you could declare your actions as class methods you would have absolutely no context. And its actually pretty damn irrelevant since you would have to replace the entire router layer to even get it called.
Ruby does not even have real singleton classes either. If you want an object that can't be instantiated use a module (and no you can't make a module a controller in rails).


text:
Q: How to redirect from a CatchAll method without being re-catched in Python/Flask I'm building an Web site using Python and Flask and I want the website to run the same way as GrooveShark and Twitter do : having a masterPage with a $.ajax call that append the content of another .html file into a  of the masterPage.
For the moment, my masterPage contains a $.ajax that calls my WebServer passing the current window.location.href
I would like to know how to catch all Url in a Python/Flask WebServer and then, on certain condition, redirect without begin recatched by the method !
E.g.
    Based on http://flask.pocoo.org/snippets/57/
@app.route('/', defaults={'p_path': ''})
@app.route('/<path:p_path>')
def CatchAll(p_path):
    if(p_path.startswith("page/")):
        #if (route exist...I don't know yet how to do this part...):
            #Call the method routed to the /Page/ route
            #  Without being re-catched by the CatchAll method
    elif (p_path.startswith("api/")):
        #Run a method on my API that will call my controller > DAL > Database
        #  Without being re-catched by the CatchAll method
    else:
        #I render my masterpage
        return render_template("masterPage.html")

So if the website is loaded for the first time in the browser, it will load the MasterPage, which contains the ajax call that will recall the WebServer passing a URL like "/Page/Contact" which will render the html which I will append in my <div>
Do you have any idea of how doing this ?
It's my first draft so feel free to give me comments (optimization, best pratice, performance) because I'm new to Python/Flask

A: You do not need catch all requests for your case.
You can set main page access by GET request and ajax by POST, for example with next decorator:
class AjaxApp(Flask or Blueprint):

    def ajax_route(self, rule, **options):
        def decorator(f):
            @functools.wraps(f)
            def wrapper(*args, **kwargs):
                if request.method == 'POST':
                    return f(*args, **kwargs)
                return render_template("masterPage.html")

            endpoint = options.pop('endpoint', None)
            methods = options.pop('methods', ['GET', 'POST'])
            self.add_url_rule(rule, endpoint, wrapper, methods=methods, **options)
            return wrapper
        return decorator

You also can just check X-Requested-With header if do not want restrict access for each methods:
class AjaxApp(Flask or Blueprint):

    def ajax_route(self, rule, **options):
        def decorator(f):
            @functools.wraps(f)
            def wrapper(*args, **kwargs):
                if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    return f(*args, **kwargs)
                return render_template("masterPage.html")

            endpoint = options.pop('endpoint', None)
            self.add_url_rule(rule, endpoint, wrapper, **options)
            return wrapper
        return decorator

This methods very implicit and you should use just ajax_route for your special ajax pages, but it increase complexity and probably better use Pluggable Views http://flask.pocoo.org/docs/views/.
If you want group logic by api, pages and other you can look at blueprints http://flask.pocoo.org/docs/blueprints/:
class AjaxBlueprint(Blueprint):
    def route(self, rule, **options):
        # one of examples

ajax = AjaxBlueprint('ajax', __name__)

@ajax.route('/main.html')
def main():
    return render_template('main.html')

app.register_blueprint(ajax)

and override route with one of examples method for blueprint. So ajax bluprint in this case will have custom logic, others blueprint will have independent.


text:
Q: How to avoid stopping the wx.Gauge progress with python when the program takes time? My program uses a recursive function that takes a few seconds. This function is used several times in a loop.
I want to show the progress of the loop with a gauge. But after a few passes through the loop, the gauge freezes and the program seems to stop working: "don't answer" appears in the title while the program is really running.
Once the main loop is finished, the gauge fills up to 100% at once.
import wx

class Mywin(wx.Frame):

    def __init__(self, parent, title):
        super(Mywin, self).__init__(parent, title=title, size=(300, 200))
        self.InitUI()

    def InitUI(self):
        self.count = 0
        pnl = wx.Panel(self)
        vbox = wx.BoxSizer(wx.VERTICAL)

        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        hbox2 = wx.BoxSizer(wx.HORIZONTAL)

        self.gauge = wx.Gauge(pnl, range=20, size=(250, 25), style=wx.GA_HORIZONTAL)
        self.btn1 = wx.Button(pnl, label="Start")
        self.Bind(wx.EVT_BUTTON, self.OnStart, self.btn1)

        hbox1.Add(self.gauge, proportion=1, flag=wx.ALIGN_CENTRE)
        hbox2.Add(self.btn1, proportion=1, flag=wx.RIGHT, border=10)

        vbox.Add((0, 30))
        vbox.Add(hbox1, flag=wx.ALIGN_CENTRE)
        vbox.Add((0, 20))
        vbox.Add(hbox2, proportion=1, flag=wx.ALIGN_CENTRE)
        pnl.SetSizer(vbox)

        self.SetSize((300, 200))
        self.Centre()
        self.Show(True)

    def Recursive(self, param1, param2):
        for i in range(1000):  # complex work simulated by for loop in my recursive function
            print(i)
        # list1 is modified in my function
        return

    def OnStart(self, e):
        nb_elements = 150
        for n in range(nb_elements):
            list1 = []
            list2 = []
            self.Recursive(list1, list2)
            self.gauge.SetValue(int((n/nb_elements)*100))

ex = wx.App()
Mywin(None, 'wx.Gauge')
ex.MainLoop()

A: First be careful with that range value on the gauge.
Use wx.GetApp().Yield() to momentarily pass control back to the main loop, so the update to the gauge can occur.
If you don't want to unnecessarily pass back control, moderate the yields by only yielding occasionally.
Here I do that with divmod.
import wx
import time

class Mywin(wx.Frame):

    def __init__(self, parent, title):
        super(Mywin, self).__init__(parent, title=title, size=(300, 200))
        self.InitUI()

    def InitUI(self):
        self.count = 0
        pnl = wx.Panel(self)
        vbox = wx.BoxSizer(wx.VERTICAL)

        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        hbox2 = wx.BoxSizer(wx.HORIZONTAL)

        self.gauge = wx.Gauge(pnl, range=1000, size=(250, 25), style=wx.GA_HORIZONTAL)
        self.btn1 = wx.Button(pnl, label="Start")
        self.Bind(wx.EVT_BUTTON, self.OnStart, self.btn1)

        hbox1.Add(self.gauge, proportion=1, flag=wx.ALIGN_CENTRE)
        hbox2.Add(self.btn1, proportion=1, flag=wx.RIGHT, border=10)

        vbox.Add((0, 30))
        vbox.Add(hbox1, flag=wx.ALIGN_CENTRE)
        vbox.Add((0, 20))
        vbox.Add(hbox2, proportion=1, flag=wx.ALIGN_CENTRE)
        pnl.SetSizer(vbox)

        self.SetSize((300, 200))
        self.Centre()
        self.Show(True)

    def Recursive(self, param1, param2):
        for i in range(1000):  # complex work simulated by for loop in my recursive function
            time.sleep(0.001)
            quo,rem = divmod(i,50)
            if rem == 0:
                self.gauge.SetValue(i)
                wx.GetApp().Yield()
        # list1 is modified in my function
        return

    def OnStart(self, e):
        nb_elements = 10
        for n in range(nb_elements):
            list1 = []
            list2 = []
            self.Recursive(list1, list2)
        print("Finished")

ex = wx.App()
Mywin(None, 'wx.Gauge')
ex.MainLoop()


text:
Q: Cell spacing issue I am using a table to display data pulled from two database tables.  I am trying to put the information in two rows seperated by a hr tag to create a line between them.  However the last cell (in this case) does not have anything to be input into the bottom of it.  It here a character that is the same height as a letter that I can put in there to make the hr tag line up with the others while still not being visible to the user?

A: To get a table cell to appear, you need to have a character in it. To add an invisible character, generally, a non-breaking space is used. This is created using the   HTML entity.

A: To get a blank character, use the following HTML entity:
In order to draw lines, however, I would not use an <hr>.
Use CSS to define your table borders:
table td {
    border:1px solid #ccc;
    padding:1px;
}

You can do this at the table, row, or cell level (or any HTML element for that matter), which makes it very flexible, and renders the hr tag superfluous in this instance.


text:
Q: Visual Studio 2005 - Add webreference fails for secured webservice I have a webservice (asmx file) in a directory requiring  form authentication
When I try to add the WebReference through VS2005 - I get the following error:
The request failed with the error message:
--
<title>Object moved</title>

Object moved to here.

When I remove the web.config in that directory (and basically removing the requirement for form authentication) everything works fine. I can add the WebReference.
Any idea?

A: Place the following code in your web.config:
<location path="path/to/your/service.asmx">
    <system.web>
        <authorization>
            <allow users="*"/>
        </authorization>
    </system.web>
</location>

ASP.Net allows to override application-wide settings for specific locations.


text:
Q: How to get number of web hits for a given query? I'm doing a project based on information retrieval, in that i want to know how many web hits for a given query on the web. Is it possible to get web hits from google?? if so , can any body tell me how to get web hits using a java program??

A: Have a look at Google Trends. You can find out the trend of a particular query and download the results as CSV.


text:
Q: aws access key id and secret access key I tried to understand access keys. I read https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-secret-access-keys and says use access keys to sign programmatic requests that you make to AWS.
Can I say access key id is like public key and it can be shared, and secret access key is like private key that is not sharable? When I connect to AWS in CLI, I need to specify both in ~/.aws/credentials and I wonder why

A: Although the internal relation between the two keys is not readily disclosed by aws, I will explain what I gather from their resources and by experience.
Their REST Api requires an Authorization Header which consists of Access Key ID concatenated with a Signature derived from the secret key. This signature is an HMAC string using the Secret Key and the Message as given here: https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html#ConstructingTheAuthenticationHeader. I would imagine the same method being used when we use aws cli.
There are other resources that claim, the access key is essentially public as it can be accessed by others in certain situations as given here: https://alestic.com/2009/11/ec2-credentials/.
I would imagine that would imply footprint in logs or visibility to admins for individual access keys of users but not their secret keys. The secret key is only shown at the time of creation and thereafter access to it is denied even to an admin.


text:
Q: GenStage: bad return value I'm trying to implement an extremely simple GenStage for the purpose of making sure I understand it and can get it working before I start introducing my specific application logic. I'm getting an error on the return data from the Producer. The data looks right to me. I've read that the second value in the returned tuple has to be a list, and it appears to be one.
Here is my GenStage implementation:
defmodule CoachActivity.Event.Producer do
  use GenStage

  def start_link(page) do
    GenStage.start_link(CoachActivity.Event.Producer, page)
  end

  def init(page) do
    {:producer, page}
  end

  def handle_demand(demand, page) when demand > 0 do
    # in here we need to run the ecto query for the next X items?
    events = get_fake(page)

    IO.puts "PRODUCER: preparing to return events"
    IO.puts "PRODUCER: page will be: #{page + 1}"

    {:no_reply, events, page + 1}
  end

  defp get_fake(page) do
    IO.puts "PRODUCER: generating events for page #{page}"
    [
      "Event One",
      "Event Two",
      "Event Three",
      "Event Four",
      "Event Five"
    ]
  end
end

defmodule CoachActivity.Event.ProducerConsumer do
  use GenStage

  def start_link(page) do
    GenStage.start_link(CoachActivity.Event.ProducerConsumer, page)
  end

  def init(number) do
    {:producer_consumer, number}
  end

  def handle_events(events, _from, number) do
    # in here we will do the transformation of events
    IO.puts "PRODUCER_CONSUMER: importing a bunch of events"

    events = Enum.map(events, fn(event) ->
      CoachActivity.Event.ImportEvent.import(event)
    end)

    {:noreply, events, number}
  end
end

defmodule CoachActivity.Event.Consumer do
  use GenStage

  def start_link() do
    GenStage.start_link(CoachActivity.Event.Consumer, :ok)
  end

  def init(:ok) do
    {:consumer, :the_state_does_not_matter}
  end

  def handle_events(events, _from, state) do
    # Wait for a second.
    Process.sleep(1000)

    # Inspect the events.
    IO.inspect(events)

    # We are a consumer, so we would never emit items.
    {:noreply, [], state}
  end
end

defmodule CoachActivity.Event.ImportEvent do
  def import(event) do
    IO.puts "Converting an event: #{event}"
  end
end

defmodule KickStart do
  def start do
    {:ok, producer} = CoachActivity.Event.Producer.start_link(0)
    {:ok, producer_consumer} = CoachActivity.Event.ProducerConsumer.start_link(2)
    {:ok, consumer} = CoachActivity.Event.Consumer.start_link()

    GenStage.sync_subscribe(consumer, to: producer_consumer)
    GenStage.sync_subscribe(producer_consumer, to: producer)
  end
end

When I do
KickStart.start

I get this error message output:
iex(4)> KickStart.start
PRODUCER: generating events for page 0
{:ok, #Reference<0.2077982655.942931969.179180>}
PRODUCER: preparing to return events
PRODUCER: page will be: 1
iex(5)> [error] GenServer #PID<0.1066.0> terminating
** (stop) bad return value: {:no_reply, ["Event One", "Event Two", "Event Three", "Event Four", "Event Five"], 1}
Last message: {:"$gen_producer", {#PID<0.1067.0>, #Reference<0.2077982655.942931969.179180>}, {:ask, 1000}}
State: 0
** (EXIT from #PID<0.1002.0>) evaluator process exited with reason: bad return value: {:no_reply, ["Event One", "Event Two", "Event Three", "Event Four", "Event Five"], 1}

What I'm struggling with is a) understanding WHAT that error message means, and of course, why it's manifesting.


text:
Q: How to get the Color from LinearGradient? I have used LinearGradient in my project. Please let us know, how to get the Color from the LinearGradient ?
LinearGradient
 LinearGradient gradient =  new LinearGradient(float x0, float y0, float x1, float y1, int[] colors, float[] positions, TileMode tile);

How to get the color from the gradient ?

A:
Please let us know, how to get the Color from the LinearGradient ?

You can't. This is one way ticket, once the LinearGradient is created, you can't extract the colors for creating it.
If you want the colors, the only option is to locally store the colors for creating the LinearGradient.


text:
Q: Showing that an algebraic set is not isomorphic to $\mathbb{A}^1$ (For convenience, I'm assuming $\mathbb{K} = \mathbb {C}$.)

I'm trying to show that the algebraic set $\mathbb{V}(xz-y^2,x^3-yz,z^2-x^2y) \subseteq \mathbb{A}^3$ is not isomorphic to $\mathbb{A}^1$.

I already know that $X = \{(t^3,t^4,t^5) \in \mathbb{A}^3 \;|\; t \in \mathbb{A}^1 \} $, and that $\mathbb{I}(X) = \langle xz-y^2,x^3-yz,z^2-x^2y \rangle$.
If there were an isomorphism between the $\mathbb{A}^1$ and $X$, then $\mathbb{K}[\mathbb{A}^1] \cong \mathbb{K}[X]$. But $\mathbb{K}[\mathbb{A}^1] \cong \mathbb{K}[t]$, whereas $\mathbb{K}[X] \cong \mathbb{K}[t^3,t^4,t^5]$ by considering the homomorphism
$$\mathbb{K}[x,y,z] \rightarrow \mathbb{K}[t], \; x\rightarrow t^3, \; y\rightarrow t^4, \; z\rightarrow t^5$$
which has kernel $\mathbb{I}(X)$ and image $\mathbb{K}[t^3,t^4,t^5]$, so
$$\mathbb{K}[X] \cong \mathbb{K}[x,y,z]/\mathbb{I}(X) \cong \mathbb{K}[t^3,t^4,t^5]$$
Thus we would have that $\mathbb{K}[t] \cong \mathbb{K}[t^3,t^4,t^5]$, but this is not the case since the former is a UFD, whilst the latter is not, since for example $t^8 = t^3t^5 = (t^4)^2$ has two factorisations. Hence, $\mathbb{A}^1 \ncong X$.
Is this line of reasoning correct? Is there an easier way I could have gone about it?

A: Alternative way is to observe that $X$ is not smooth at the origin. In other words, localization of $\mathbb{C}[x,y,z]/I$ at $\mathfrak{m}_0=\langle x,y,z\rangle$ is not regular, where $I=\langle xz−y^2,x^3−yz,z^2−x^2y\rangle$. But $\mathbb{C}[t]$ is smooth everywhere.
Let us verify the above claim. We can use the Jacobian criteria to test regularity (see for instance Eisenbud's Commutative Algebra, Chapter 16):
Suppose $k$ has char. $0$, and $I=(f_1,\dots,f_m)$ is an ideal in $S:=k[x_1,\dots,x_n]$. Suppose $\mathfrak{p}\supset I$ is prime and $I_\mathfrak{p}$ has codimension $r$ in $S_\mathfrak{p}$. Define the Jacobian matrix as
$$
J_{ij}=\frac{\partial{f_i}}{\partial x_j}
$$
Then $(S/I)_\mathfrak{p}$ is a regular local ring if and only if $J$ has rank $r$ in $S/\mathfrak{p}$.
(This is saying that regularity and smoothness are the same things in char. $0.)
Now in our case, we note that $I_{\mathfrak{m}_0}$ has codimension $>0$ in $\mathbb{C}[x,y,z]_{\mathfrak{m}_0}$ (in fact it has codimension $3$, but we don't need this). But the Jacobian
$$
J=\left(\begin{array}{ccc}z& -2y&x\\3x^2&-z&-y\\ -2xy&-x^2&2z\end{array}\right)
$$
has rank zero in $\mathbb{C}[x,y,z]/\mathfrak{m}_0$. Thus the origin is not a smooth point of $X$.


text:
Q: Capybara find element value of aria-pressed I would like to get the value of aria-pressed for the below code in capybara:
<button aria-pressed="true" class="btn btn-default active" data-active="true" data-toggle="button" id="grid-filter-invited-button" type="button">
  Invited
</button>

It's a button... when i click on it, its aria-pressed value toggles between true and false..I want the value of "aria-pressed". Can anyone please help?

A: Nodes have a [] method that returns attribute values.
capybara_element['attribute_name'] allows accessing an element's attributes in Capybara
aria-pressed = page.find('button#grid-filter-invited-button')['aria-pressed']
puts aria-pressed
#=> "true"

Reading an element's attributes with Capybara

A: I'm assuming you want to check the value has changed. You should be able to assert this with an xpath expression. As it's a boolean, you could get a value by checking the results are nil or empty.
Something like:
page.all(
  :xpath,
  "//button[@id='grid-filter-invited-button'][@aria-pressed='true']"
)

or to expect it's been pressed:
expect(page).to have_selector(
  :xpath,
  "//button[@id='grid-filter-invited-button'][@aria-pressed='true']"
)

Also, take a look at this answer to a similar problem. You can also do it with a css selector: RSpec + Capybara: How do I test a Bootstrap progress bar


text:
Q: Uso de const como paso de referencia acabo de subir una pregunta en la que exponía un problema que estaba teniendo a la hora de realizar la sobrecarga del operador suma (+) para poder operar con dos vectores. Un compañero ha conseguido descifrar el problema y brindarme la solución:
El problema residía en que se estaba tratando de acceder a un lvalue cuando correspondía un rvalue. La solución era bien sencilla y consistía en añadir a la declaración del método la palabra reservada const en el argumento que le pasaba como referencia:
Vector2D operator +(const Vector2D& v);

Abro esta respuesta porque no acabo de entender por qué al añadir el const se soluciona el problema.
Si alguien puede realizar una breve explicación o indicarme algún foro o página se lo agradecería :)

A: Falta indicar que la pregunta original es esta.
Aprovechando el ejemplo de la respuesta a esa pregunta:
struct Vector2D {
  Vector2D operator+( Vector2D & ) { return Vector2D( ); }
  Vector2D operator*( int ) { return Vector2D( ); }
};

int main( ) {
  Vector2D position;
  Vector2D speed;

  auto result = position + speed * 4;

  return 0;
}

La operación conflictiva es esta:
auto result = position + speed * 4;

Y el problema que tenemos aquí es que esta operación es compleja, por lo que necesitamos descomponerla:
auto temp = speed * 4;
auto result = position + temp;

Vale, como puedes observar, temp es un objeto que se crea implícitamente y, por tanto, no se asigna a una variable en concreto. El caso es que este resultado temporal no se asigna a una variable.
Este detalle es importante ya que, al no usar una variable para almacenar este valor, el mismo pasa a ser consierado como un r-value y una característica de los r-value  es que son constantes.
Dado que el objeto es constante, al realizar la suma, el compilador intentará localizar una sobrecarga en la que el parámetro sea constante... no la encuentra y la compilación falla.
Puedes probar a dividir la operación, como he hecho yo en esta respuesta, y verás como entonces sí que funciona con la versión no const


text:
Q: Cannot get drag and drop to work onto NSCollectionView There is probably a simple mistake that I'm making, but I simply cannot get dropping of files onto an NSCollectionView to work even in the most basic way.
In a test project, I have an NSCollectionView on a window, and the view controller is both its delegate and data source. I want to be able to drag files from the Finder onto this collection view.
From reading the docs, all I should have to do is:
Register for dragged type(s):
- (void)viewDidLoad {

    [super viewDidLoad];
    // Do any additional setup after loading the view.

    NSLog(@"Registering dragged types for collection view: %@", self.collectionView);
    [self.collectionView registerForDraggedTypes:@[NSFilenamesPboardType]];
    [self.collectionView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
    [self.collectionView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:NO];
}

And then implement these two methods:
-(NSDragOperation)collectionView:(NSCollectionView *)collectionView validateDrop:(id<NSDraggingInfo>)draggingInfo proposedIndex:(NSInteger *)proposedDropIndex dropOperation:(NSCollectionViewDropOperation *)proposedDropOperation {

    NSLog(@"Validate drop: %@", draggingInfo);

    return NSDragOperationMove;
}

-(BOOL)collectionView:(NSCollectionView *)collectionView acceptDrop:(id<NSDraggingInfo>)draggingInfo index:(NSInteger)index dropOperation:(NSCollectionViewDropOperation)dropOperation {

    NSLog(@"Accept drop: %@", draggingInfo);

    return YES;
}

But none of the two methods is ever called, when I try to drag an item onto the collection view, which makes me think that the registerForDraggedTypes: call is not working as expected.
What can be the issue here? What else do I have to look into?

A: From OS X 10.11 the NSCollectionViewDelegate methods take an index path instead of an index. For instance in
-(NSDragOperation)collectionView:(NSCollectionView *)collectionView validateDrop:(id<NSDraggingInfo>)draggingInfo proposedIndex:(NSInteger *)proposedDropIndex dropOperation:(NSCollectionViewDropOperation *)proposedDropOperation

the proposedIndex: parameter is replaced by proposedIndexPath:
- (NSDragOperation)collectionView:(NSCollectionView *)collectionView validateDrop:(id <NSDraggingInfo>)draggingInfo proposedIndexPath:(NSIndexPath * __nonnull * __nonnull)proposedDropIndexPath dropOperation:(NSCollectionViewDropOperation *)proposedDropOperation


text:
Q: ListView's OnItemClick does not work I made a listview.
Using this tutorial link
It works fine.
But the problem is when i try to add onitemclick listener in its activity class the click action does not work.i just want to show a toast message.And here it the code for onItemClickListener
listViewCity.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> a, View v, int position, long id) {

                    String item = ((TextView)v).getText().toString();

                    Toast.makeText(getApplicationContext(), item, Toast.LENGTH_LONG).show();

            }
        });

Why it doesn't work anybody can tell me???

A: If you are getting an exception or a force close, you should have mentioned it.
First of all, your OnItemClickListener is wrong, because the View that is passed to your OnClickListener is not a TextView so You can not just cast it to a TextView.
You can fix it using the following:
listViewCity.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> a, View v, int position, long id) {
        String item = ((TextView)v.findViewById(R.id.cityName)).getText().toString();
            Toast.makeText(getApplicationContext(), item, Toast.LENGTH_LONG).show();

    }
});

Try what I just did and it should work. If it doesn't work, you may need to remove the line android:autoLink="web" from your xml file.

The attribute android:autoLink="web" is making your View's TextView Clickable. As I mentioned in my comment, if any of your subviews is clickable, your OnItemClickListener will not receive events, because it will be consumed by the children.

A: Use this
Since you are using a customadapter you will have to do this in your customadapter class to handle onclicks of the listview...
convertView.setClickable(true);
    convertView.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View paramView)
                    {
                      //if you want you can use the "position" value to get the desired row items.
                    }
                    });

A: Try this...
listViewCity.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> a, View v, int position, long id) {
                     String item = listViewCity.getItemAtPosition(position).toString();

                    Toast.makeText(getApplicationContext(), item, Toast.LENGTH_LONG).show();

            }
        });

A: I had the same problem and solved it by setting each view I needed to click to clickable and then added the listener. I put the following method inside the customized adapter (in getView method). Something like this:
public void setViewsClickable(int position) {
        myView.button.setClickable(true);
        myView.radioButton.setClickable(true);
        myView.button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // what this button should do
            }
        });

        myView.radioButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // what clicking this radio button should do
            }
        });

    }


text:
Q: Extjs 6 responsiveConfig cannot find setters for layout config items I've got a fiddle of a base layout I'm trying to add responsive configurations to.
My goal is to use a border layout where the navigation can change between the western region and the northern region depending on the window size and the layout config can switch between vertical and horizontal so that when the region is west the buttons are grouped vertically and when the region is north the buttons are grouped horizontally.
I know that by default, the layout type cannot be changed at runtime, but I found this forum thread where a user points out that if you use the box layout type (the parent of vbox and hbox) you can update the vertical config to change the grouping at runtime.
The fiddle I linked above is my attempt at prototyping that concept out.
The problem I'm running into is that the responsiveConfig cannot find the setters for the particular properties that I'm trying to change, and it's not just for the vertical config. Config items that I know have setters and I have seen work before in the responsiveConfig are not working as well:

Ext.layout.container.Box definitely has a setPack method.
Am I mis-configured somehow?

A: I posted to the thread in sencha's forums where the technique I was trying was described. The poster who answered the question originally answered my post with an updated fiddle showing the correct implementation.
I've added the responsive box implementation as well as the region switching into my fiddle.
Here's the responsive sections needed:
plugins: 'responsive',
responsiveConfig:{
    wide:{
        layout:{
            type: 'box',
            vertical: true,
            pack:'start'
        },
        region: 'west'
    },
    tall:{
        layout:{
            type: 'box',
            vertical: false,
            pack: 'center'
        },
        region: 'north'
    }

I think the important part to know here (and what was tripping me up) is that you have to include the type: 'box' in the layout config for the responsiveConfig property because responsiveConfig is not firing each individual setter for the layout (type, vertical, and pack), it's firing the overall layout setter method. If you don't include the type config in the object you give the layout config, it uses the default type which is 'auto'.
This is why in the screenshot I included in the original post the error messages in the javascript console where referring to Ext.layout.container.Auto and not Ext.layout.container.Box. The error message was right, Ext.layout.container.Auto doesn't have a setPack method.

A: Changing layouts at runtime is not currently supported. There is a feature request for it here:
https://www.sencha.com/forum/showthread.php?294082
Fiddle with a workaround:
https://fiddle.sencha.com/#fiddle/dqj

A: The error is complaining about auto layout having no setter for pack.
This tells me the layout is indeed being set during runtime, according to the value specified in the responsive layout config. Since there is none defined, just the vertical and pack, config, the layout type is interpreted as auto. Small changes in your fiddle, defining the layout type as below:
responsiveConfig:{
    wide:{
        layout:{
            type : 'vbox',
            pack:'start'
        },
        bodyStyle:{'background-color': 'orange'}
    },
    tall:{
        layout:{
            type : 'hbox',
            pack: 'center'
        },
        bodyStyle:{'background-color': 'purple'}
    }
},

And your error was gone.


text:
Q: XML error: Prefix not bound to a namespace, KML file So I'm attempting to repair a KML file from my boss. For those who know these are just XML files really, so I'm working off a copy I renamed to XML and using Firefox to validate. I get this error:

XML Parsing Error: prefix not bound to a namespace Location:
  file:///home/user/Desktop/myplaces.broken-19-11-2019.xml Line Number
  942553, Column 3:
  <Document id="NEC"
  xsi:schemaLocation="http://www.opengis.net/kml/2.2
  http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd
  http://www.google.com/kml/ext/2.2
  http://code.google.com/apis/kml/schema/kml22gx.xsd">

I am not a developer, but I have been around for some time. Below, is the lien in question along with the 1 before and the 1 after to help give context.  What can I do to help resolve this?
</Folder>
<Document id="NEC" xsi:schemaLocation="http://www.opengis.net/kml/2.2 http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd http://www.google.com/kml/ext/2.2 http://code.google.com/apis/kml/schema/kml22gx.xsd">
    <name>NEC</name>

Here is the first couple of lines in the file as well since I've seen those might be relevant:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>

A: XML namespace prefixes such as xsi: must be defined.
Simply add
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

to your kml element to eliminate that error:
<kml xmlns="http://www.opengis.net/kml/2.2"
     xmlns:gx="http://www.google.com/kml/ext/2.2"
     xmlns:kml="http://www.opengis.net/kml/2.2"
     xmlns:atom="http://www.w3.org/2005/Atom"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^


text:
Q: If R is integral domain, Q field of fractions and I an ideal. Prove $I_Q \cong Q \otimes _R I \rightarrow Q\otimes _R R \cong Q$ is an isomorphism If R is integral domain, Q field of fractions and I an ideal then prove the induced map $I_Q \cong Q \otimes _R I \rightarrow Q\otimes _R R \cong Q$ is an isomorphism.
I know how to prove $I_Q\cong Q$ since there is an isomorphism between localization of modules and tensoring it with the field of fractions. And $Q\otimes _R R \cong Q$ is well-know property of tensors. But I don't know how to prove the isomorphism between $I_Q\rightarrow Q$.

A: $Q \otimes_R I \rightarrow Q \otimes_R R = Q$ is injective since $Q$ is a localization over $R$ and localizations are flat.
For surjectivity, let $a/b \in Q$ , and $i \in I$. Then, $\frac{a}{ib} * i = a/b $, so a preimage is $\frac{a}{b} \otimes i$.


text:
Q: Update Column Using Inner Join and Aggregate Function I have a table that I need to update using the sum of specified values from another table. The table that needs updated is called EngTasks with a field called RunStatus. RunStatus can hold 3 values:

*

*1 = Not Started

*2 = In Progress

*3 = Complete

The table I need to look at is called EngTaskLog which holds a field called HoursApplied and Foreign Key called EngTaskID. For each record I need to look at all records in EngTaskLog and total up all HoursApplied where EngTaskID = the ID of the EngTasks record that needs updated.
I tried the following query on a whim but got an error:
UPDATE EngTasks
SET EngTasks.RunStatus = 1
FROM EngTasks ET
INNER JOIN
    EngTaskLog ETL
ON
    SUM(ETL.HoursApplied) = 0

I don't have a whole lot of experience with queries, so the above code may look absurd to someone with more experience.
I hope the above makes sense and I appreciate your time and help.

A:     UPDATE ET
    SET ET.RunStatus = 1
    FROM EngTasks ET
    INNER JOIN (
        SELECT ETL.EngTaskID, SUM(ETL.HoursApplied) s
        FROM EngTasks ET
        INNER JOIN EngTaskLog ETL ON ET.ID = ETL.EngTaskID
        GROUP BY ETL.EngTaskID
        HAVING SUM(ETL.HoursApplied) = 0 ) x ON ET.ID = x.EngTaskID


text:
Q: Matrix Feedback Take the following series D.
2
5
6
12

I then need to make a new column(and make it a matrix) to subtract the values of the previous like so
2, 3
5, 1
6, 6
12,
until eventually
2, 3, 2, 3
5, 1, 5
6, 6
12,
As you can see the result(r) is 3, given that the series could be of any size what formula would always return the last number. I also couldn't figure out how to use the MathJax with matrices. A one line formula would be very nice something like.
r = ??? D ???

A: A quick computation for 2, 3 and 4 elements makes me believe you get $$
  r = \sum_{i=1}^N (-1)^{N-i}\binom{N}{i}d_i
$$
In particular you get $$
\begin{eqnarray}
  r &=& d_2 - d_1 & \text{if } N = 2 \\
  r &=& d_3 - 2d_2 + d_1 & \text{if } N = 3 \\
  r &=& d_4 - 3d_3 + 3d_2 - d_1 & \text{if } N = 4
\end{eqnarray}
$$
But beware, as I said, so far that's just an edcutated guess, not a formally proved fact. Having said that, I'd be somewhat surprised if I didn't turn out to hold, though.
(Note that $\binom{N}{i}$ is not a fraction, but a binomial coefficient, pronounced "N over i". See http://en.wikipedia.org/wiki/Binomial_coefficient for more information)


text:
Q: String Padding Not Calculating as Expected I'm displaying numbers being vertically added and trying to draw a line below the numbers being added but above the total.
I'm using a fixed-width font, making the line the width of the widest part of the equation, and trying to keep everything lined up.
This works well, but I'm not a fan of the breaks between the dashes:
str_pad(str_repeat('-', $width), 10, ' ', STR_PAD_LEFT);

I'd like to use the character below, but I can't get it to line up:
str_pad(str_repeat('─', $width), 10, ' ', STR_PAD_LEFT);

If $width is 3, I'd expect 7 spaces followed by 3 wide dashes. That's what I get with the first line but the second line gives me 4 spaces and 3 wide dashes.


text:
Q: Polymer google-client-loader, does not care about root property I'm trying to get my Polymer1.0 app to work with my google cloud endpoints API but for some reason it seems that google-client-loader doesn't care what i put in for root, it always goes to content.googleapis.com to fetch the API , of course it isn't there !
code:
<google-client-loader
                id="api" name="parliament" version="v1"
                root="http://localhost:8080/_ah/api"></google-client-loader>

getting:
GET https://content.googleapis.com/discovery/v1/apis/parliament/v1/rest?fields=rootUrl%2CservicePath%2Cresources%2Cparameters%2Cmethods&pp=0 404 (OK)

tried:

*

*api-root

*apiRoot

*root

*api-root with app-id

*apiRoot with app-id

*root with app-id

doesn't work !
What's the problem ? Am I doing something wrong ?

A: The correct attribute to use is api-root (which works, just tested).
<google-client-loader
     id="api" name="parliament" version="v1"
     api-root="http://localhost:8080/_ah/api"></google-client-loader>

You have to make sure to use the latest version of the google-apis element collection, i.e. with this dependency in your bower.json:
"google-apis": "GoogleWebComponents/google-apis#^1.0.1"


text:
Q: JPA - Allow null parent in Recursive query I want to create Organization Structure using JPA. If I insert data using my controller, it will throw a PSQLException because the first node's parent is null. But if I input the first node manually into DB, it works for the next node. I read about this and other postings but no luck for me.
This is my entity:
@Entity
@Table(name = "tree")
public class Node implements Serializable {
@Id
private int id;
private String name;

@OneToMany(
        cascade = CascadeType.ALL
)
@JoinColumn(name = "parent_id", nullable = true)
@OrderColumn
@JsonManagedReference
private Set<Node> children = new HashSet<>();

@Basic(optional = true)
@ManyToOne(
        fetch = FetchType.LAZY,
        optional = true
)
@JoinColumn(name = "parent_id", nullable = true)
@JsonBackReference
private Node parent;

public void addNode(Node node){
    this.getParent().getChildren().add(node);
    node.setParent(this.getParent());
}

// Getter setter was removed for brevity
}

This is my controller:
@RestController
@RequestMapping("/node")
public class NodeController {
@Autowired
private NodeRepository nodeRepository;

@GetMapping
public @ResponseBody Iterable<Node> index(){
    return nodeRepository.findByParentIsNull();
}

@PostMapping
public String add(
        @RequestBody List<Node> nodes){

        nodes.stream().forEach(
                node -> {
                    node.addNode(node);
                }
        );

        nodeRepository.saveAll(nodes);
        return "nice";
     }
}

And, this is my data sample:
[
 {
   "id":8,
   "name":"Top Parent",
   "parent":{}
 },{
   "id":9,
   "name":"Node 1",
   "parent":{
      "id":8
    }
 },{
   "id":10,
   "name":"Node 2",
   "parent":{
      "id":8
    }
 },{
   "id":11,
   "name":"Node 3",
   "parent":{
      "id":9
    }
 }
]

The Expected Result after inserting via controller is:
id    |name       |parent_id
===========================
8     |Top Parent |null
9     |Node 1     |8
10    |Node 2     |8
11    |Node 3     |9

Let me know if something unclear. Thank in advance!

A: I find a workaround for my problem. So, I put here if someone faces a similar problem with me.
I added a NativeQuery in my repository like this:
@Query(value = "insert into tree values(:id,:name)", nativeQuery = true)
void saveTop(@Param("id")int id,@Param("name")String name);

And then I added some lines in my controller like this:
@PostMapping("/top")
public void addTop(@RequestBody Node node){
    nodeRepository.saveTop(node.getId(),node.getName());
}

Basically, I create an endpoint("/node/top") to insert top node for my structure organization tree manually.


text:
Q: Parametrized decorators which share inner functions I'm trying to make two very similar decorators, each of which accepts general args and kwargs, and both of which internally share code. The only difference between their two definitions is the value of a particular flag (which is not exposed to the user). The full context is in this issue.
I currently have the first decorator defined (with no reference to the flag) as
import functools

def decorator_factory(*args_units, **kwargs_units):

    def _decorator(func):
        @functools.wraps(func)
        def _wrapper(*args, **kwargs):
            return f(*args, **kwargs, *args_units, **kwargs_units)

        return _wrapper
    return _decorator

which can be used like this
@decorator_factory(*args_units, **kwargs_units)
def func_to_be_decorated(*args, **kwargs):
    ...

What I want is to instead create two very similar decorators something like this
def decorator_factory1(*args_units, **kwargs_units):
    return functools.partial(_decorator, flag=True)

def decorator_factory2(*args_units, **kwargs_units):
    return functools.partial(_decorator, flag=False)

def _decorator(func, flag):
    @functools.wraps(func)
    def _wrapper(*args, **kwargs):
        if flag:
            return f1(*args, **kwargs, *args_units, **kwargs_units)
        else:
            return f2(*args, **kwargs, *args_units, **kwargs_units)

    return _wrapper

which could then be used like this
@decorator_factory1(*args_units, **kwargs_units)
def func1_to_be_decorated(*args, **kwargs):
    ...

@decorator_factory2(*args_units, **kwargs_units)
def func2_to_be_decorated(*args, **kwargs):
    ...

The problem is that this pattern doesn't pass down *args_units and **kwargs_units, because they are no longer available in the local namespace within the _decorator function.


text:
Q: msSaveOrOpenBlob property doesn't exist on type Navigator angular 13 The property msSaveOrOpenBlob doesn't exist on type Navigator after updating to the angular 13.
I know the Navigator.msSaveOrOpenBlob is being deprecated as per https://developer.mozilla.org/en-US/docs/Web/API/Navigator/msSaveOrOpenBlob#browser_compatibility
I had an angular 12 application, now I am migrating to angular 13 and typescript have been updated to the latest version, but facing the issue of The property msSaveOrOpenBlob doesn't exist on type Navigator
what will be the alternate code for the below
if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveOrOpenBlob(blob, filename);
        }

A: let newVariable: any = window.navigator;
var newBlob = new Blob([res.body], { type: "application/csv" });
if (newVariable && newVariable.msSaveOrOpenBlob) {
    newVariable.msSaveOrOpenBlob(newBlob);
    return;
}

A: Found some of the references
https://github.com/microsoft/TypeScript-DOM-lib-generator/issues/1029
https://github.com/microsoft/TypeScript/issues/45612
Use the declaration merging and declare the types locally in your project work.

A: Declare below code in main.ts
  declare global{
    interface Navigator {
      msSaveOrOpenBlob?: (blob: any, defaultName?: string) => boolean
    }
  }


text:
Q: Every linear mapping satisfies $f(0) = 0$ In my textbook is written that every linear mapping $ f: V \to V'$ satisfies $f(0)=0$. But what about the mappings between the polynomials like $p(x) = ax^2 + bx + c$, where $c$ is nonzero? Elementary probably, but fundamental.

A: The set of polynomials $ax^2+bx+c$ with $c\ne 0$ t is not a vector space (at least with the usual operations), so we cannot speak of linear mapping on this set.

A: You are getting confused between $f$ and $p$.
$f$ is a function that applies to the coefficients of the polynomial and returns new coefficients.
For clarity, we can write
$$f(a,b,c)=(a',b',c')$$
and a necessary condition for linearity is
$$f(0,0,0)=(0,0,0).$$
For instance,
$$f(a,b,c)=(2a,b+c,c-a),$$ also understood as
$$f(ax^2+bx+c)=2ax^2+(b+c)x+(c-a)$$
may be linear because
$$f(0x^2+0x+0)=0x^2+0x+0.$$
This has nothing to do with the exaluation of the polynomial at $x=0$, and mandatorily involves a polynomial such that $c=0$.

A: There is a null polynomial $p(x) = 0$. What you mean is an affine space, not a linear space.
About the property:
Every vector space has a null vector $\vec{0}$ so for a linear map $f$ we have
$$
f(\vec{0}) = f(0 \, \vec{0}) = 0 f(\vec{0}) = \vec{0}
$$


text:
Q: Adding to the Chef Gem Source? My organization works entirely within the firewall (i.e, no machines have internet access). Whenever chef cookbooks are update and require gems the recipes fail due to the fact they cannot download and install gems from rubygems.org.
We self host copies of required gems - how can we add a custom internal source to chef, so that we don't have to deal with failures?

A: You can manage the gemrc for the embedded Ruby with Chef Client.
chef_etc_dir = Chef::Util::PathHelper.join(Chef::Config.embedded_dir, 'etc')
chef_gemrc   = Chef::Util::PathHelper.join(chef_etc_dir, 'gemrc')

directory chef_etc_dir do
  owner "root"
  group "root"
  mode "0755"
end.run_action(:create)

file chef_gemrc do
  owner "root"
  group "root"
  mode "0644"
  content <<EOF
---
:sources:
- https://path.to.internal.repo/
- https://rubygems.org
:update_sources: true
EOF
  end.run_action(:create)

The PathHelper methods should give appropriate paths for either Windows or Linux.
The ".run_action(:create)" addition executes the resources at compile time, not converge time, to ensure subsequent chef_gem resources will have access to the newly-managed gemrc at converge time.
Update: Chef appears to recommend the rubygems cookbook to perform this functionality.
gemrc :global do
  values(
    sources: %w{ https://path.to.internal.repo https://rubygems.org }
  )
end


text:
Q: how would i make a dynamic image? I have a online.png and a offline.png
My idea is to do serverstatus.php?sid=1
then have it check if the server is online or not, i know how to run the checks for that.
Then have it return the online or offline image with the mime type of png but really a php file and show up like a image. No text or anything added to it. just the original online or offline png. So it can be used for img tags.

A: From PHP documentation at http://php.net/manual/en/function.imagepng.php
<?php
$im = imagecreatefrompng("test.png");

header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

A: You can use the imagecreatefrompng function


text:
Q: log4j custom configuration I faced following situation: we have an application which uses standard Apache log4j facility for logging. It contains two classes (lets name them A & B).
A.java:
package TestLog4j;

import org.apache.log4j.Logger;

public class A {
    private static Logger logger = Logger.getLogger(A.class);

    public static void main(String[] args) {
        logger.info("This is A");
    }
}

B.java:
package TestLog4j;

import org.apache.log4j.Logger;

public class B {
    private static Logger logger = Logger.getLogger(B.class);

    public static void main(String[] args) {
        logger.info("This is B");
    }
}

My log4j.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="true">

  <appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
    <param name="File" value="${app_log_dir}/${process_name}.log" />
    <param name="maxBackupIndex" value="1" />
    <param name="maxFileSize" value="50MB" />
    <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[%d{DATE}] %5p %c{1} - %m%n" /> </layout>
  </appender>

  <logger name="TestLog4j.B">
    <level value="info"/>
    <appender-ref ref="fileAppender" />
  </logger>

  <root>
    <level value="${log4j_loglevel}"></level>
    <appender-ref ref="fileAppender" />
  </root>

</log4j:configuration>

log4j.properties:
app_log_dir=C:\Work\Java\log4j
log4j_loglevel=INFO

log4j.properties.custom
process_name=custom.log

Both classes are in the same jar: TestLog4j.jar
I am trying to run both classes using following command:

java -Druntime_dir=.
  -Dlog4j.custom.properties=log4j.properties,log4j.properties.custom -cp .;TestLog4j.jar;log4j-1.2.15.jar  TestLog4j.B (or A)

Output for A is:

INFO: This is A

Output for B is:

log4j:ERROR setFile(null,true) call failed.
  java.io.FileNotFoundException: .log (Access is denied)
         at java.io.FileOutputStream.openAppend(Native Method)
         at java.io.FileOutputStream.(Unknown Source)
         at java.io.FileOutputStream.(Unknown Source)
         at org.apache.log4j.FileAppender.setFile(FileAppender.java:290)
         at org.apache.log4j.RollingFileAppender.setFile(RollingFileAppender.java:194)
         at org.apache.log4j.FileAppender.activateOptions(FileAppender.java:164)
         at org.apache.log4j.config.PropertySetter.activate(PropertySetter.java:257)
         at org.apache.log4j.xml.DOMConfigurator.parseAppender(DOMConfigurator.java:285)
         at org.apache.log4j.xml.DOMConfigurator.findAppenderByName(DOMConfigurator.java:171)
         at org.apache.log4j.xml.DOMConfigurator.findAppenderByReference(DOMConfigurator.java:184)
         at org.apache.log4j.xml.DOMConfigurator.parseChildrenOfLoggerElement(DOMConfigurator.java:502)
         at org.apache.log4j.xml.DOMConfigurator.parseCategory(DOMConfigurator.java:415)
         at org.apache.log4j.xml.DOMConfigurator.parse(DOMConfigurator.java:919)
         at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:790)
         at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:696)
         at org.apache.log4j.helpers.OptionConverter.selectAndConfigure(OptionConverter.java:471)
         at org.apache.log4j.LogManager.(LogManager.java:125)
         at org.apache.log4j.Logger.getLogger(Logger.java:118)
         at TestLog4j.B.(B.java:6)

It seems that log4j does not recognize -Dlog4j.custom.properties for second class. Why this happens?

A: Problem is resolved. I've added the parsing of log4j.custom.properties property and everything went fine.

A: Are you sure INFO: This is A is displayed?
From above log4j_loglevel=ERROR for root (that would include TestLog4j.A)
Since you have given level as ERROR, my understanding is that it would ignore
logger.info("This is A");
So there is possibility that its not even finding log4j.properties.


text:
Q: What does the word "only" mean in this context? This is a part of a dialogue between two characters that I was reading in my book:

Mr Lamb: You could tell me your name. If you chose. And not, if you didn't.
Derry: Derry. Only it's Derek.... but I hate that. Derry. If I am your friend, you don't have to be mine. I choose that.

What does the word "only" mean in this context? And the second thing I want to ask is why Derry retells his name (the highlighted part)?

A: In context, only means actually or however.
Derry is telling Mr. Lamb that his real name is Derek, but that he prefers to be called Derry.  His repetition of the name, "Derry", is to reiterate his preference.
See also only, specifically the definition where only is used a conjunction.


text:
Q: Correct usage of "has been" and "had been" I would like to know whether any of these sentences are correct:

Yesterday, I found out that all the money I had in my bank account
  has been stolen from me.
Yesterday, I found out that all the money I had in my bank account
  had been stolen from me.

Or should I just use "was" in this case?
Thanks!

A: The second sentence sounds better to me. I think it's because "had been" is the past perfect which is used to describe an event that occurred before another event in the past. The earlier event is the theft of the money, which occurred before you found out about it. If you just wanted to say that your money was stolen without reference to when you found out about it, you could use "was" or "has been."

A: My writing professor told us that you want to avoid many words in writing; something these words include, but are not limited to the following: has/have, do/does/done, make/made, get/got, can, should, would, etc. Oftentimes, they are unnecessary (i.e.- "He has been there already" vs. "He previously went there," "He was already there," or "he went"). The same is said of most adverbs and the use of the "to be" verb (be/is/been/was/are/were). You ought to limit yourself to three uses of the "to be" verb per paragraph.


text:
Q: Php project login error Recently i developed  a small school management software everything is fine in localhost but when i move the file to online server and try to login my (role) than it shows me a message and change the url mydomain/authenticate.php
The bizedu.co.in page isn't working

bizedu.co.in is currently unable to handle this request.
500

Authenticate.php code here-
    <?php

require 'connection.php';
ob_start();

session_start();

$id = "";
$password = "";

if (isset($_POST['id'])) {
    $id = $_POST['id'];
}
if (isset($_POST['password'])) {
    $password = $_POST['password'];
}

echo $id . " : " . $password;

$q = 'SELECT * FROM account WHERE id=:id AND password=:password';

$query = $conn->prepare($q);

$query->execute(array(':id' => $id, ':password' => $password));

if ($query->rowCount() == 0) {
    header('Location: index.php?err=1');
} else {

    $row = $query->fetch(PDO::FETCH_ASSOC);

    session_regenerate_id();
    $_SESSION['sess_user_id'] = $row['id'];
    $_SESSION['sess_username'] = $row['username'];
    $_SESSION['sess_userrole'] = $row['role'];

    echo $_SESSION['sess_userrole'];
    session_write_close();

    if ($_SESSION['sess_userrole'] == "admin") {
        header('Location: school_admin_home1.php');
    } elseif ($_SESSION['sess_userrole'] == "employee") {
        header('Location: school_employee_home.php');
    } elseif ($_SESSION['sess_userrole'] == "parent") {
        header('Location: parent_home.php');
    } else {

    }
}
?>

Connection.php code here-
    <?php
//database credentials
define('DBHOST','localhost');
define('DBUSER','bizeduco_portal ');
define('DBPASS','password123');
define('DBNAME','bizeduco_school');

try {

    //create PDO connection
    $conn = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER,  DBPASS);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch(PDOException $e) {
    //show error
    echo '
'.$e->getMessage().'
';
    exit;
}

?>

Please give me a solution.


text:
Q: html canvas - multiple svg images which all have different fillStyle colors For a digital artwork I'm generating a canvas element in Vue which draws from an array of multiple images.
The images can be split in two categories:

*

*SVG (comes with a fill-color)

*PNG (just needs to be drawn as a regular image)

I came up with this:
    const depict = (options) => {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      const myOptions = Object.assign({}, options);
      if (myOptions.ext == "svg") {
        return loadImage(myOptions.uri).then((img) => {
          ctx.drawImage(img, 0, 0, 100, 100);
          ctx.globalCompositeOperation = "source-in";
          ctx.fillStyle = myOptions.clr;
          ctx.fillRect(0, 0, 100, 100);
          ctx.globalCompositeOperation = "source-over";
        });
      } else {
        return loadImage(myOptions.uri).then((img) => {
          ctx.fillStyle = myOptions.clr;
          ctx.drawImage(img, 0, 0, 100, 100);
        });
      }
    };
    this.inputs.forEach(depict);

for context:
myOptions.clr = the color
myOptions.uri = the url of the image
myOptions.ext = the extension of the image
While all images are drawn correctly I can't figure out why the last fillStyle overlays the whole image. I just want all the svg's to have the fillStyle which is attached to them.
I tried multiple globalCompositeOperation in different orders. I also tried drawing the svg between ctx.save and ctx.restore. No succes… I might be missing some logic here.

A: So! I figured it out myself in the meantime :)
I created an async loop with a promise. Inside this I created a temporary canvas per image which I then drew to one canvas. I took inspiration from this solution: https://stackoverflow.com/a/6687218/15289586
Here is the final code:
    // create the parent canvas
    let parentCanv = document.createElement("canvas");
    const getContext = () => parentCanv.getContext("2d");
    const parentCtx = getContext();
    parentCanv.classList.add("grid");

    // det the wrapper from the DOM
    let wrapper = document.getElementById("wrapper");

    // this function loops through the array
    async function drawShapes(files) {
      for (const file of files) {
        await depict(file);
      }
      // if looped > append parent canvas to to wrapper
      wrapper.appendChild(parentCanv);
    }

    // async image loading worked best
    const loadImage = (url) => {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.onload = () => resolve(img);
        img.onerror = () => reject(new Error(`load ${url} fail`));
        img.src = url;
      });
    };

    // depict the file
    const depict = (options) => {
      // make a promise
      return new Promise((accept, reject) => {
        const myOptions = Object.assign({}, options);
        var childCanv = document.createElement("canvas");
        const getContext = () => childCanv.getContext("2d");
        const childCtx = getContext();
        if (myOptions.ext == "svg") {
          loadImage(myOptions.uri).then((img) => {
            childCtx.drawImage(img, 0, 0, 100, parentCanv.height);
            childCtx.globalCompositeOperation = "source-in";
            childCtx.fillStyle = myOptions.clr;
            childCtx.fillRect(0, 0, parentCanv.width, parentCanv.height);
            parentCtx.drawImage(childCanv, 0, 0);
            accept();
          });
        } else {
          loadImage(myOptions.uri).then((img) => {
            // ctx.fillStyle = myOptions.clr;
            childCtx.drawImage(img, 0, 0, 100, parentCanv.height);
            parentCtx.drawImage(childCanv, 0, 0);
            accept();
          });
        }
      });
    };

    drawShapes(this.inputs);


text:
Q: Many-to-many sorting in Entity Framework My application has an Entity Framework model containing a many-to-many relationship like the following:
ProductGroup:
    Scalar: Id, Name
    Navigation: ProductGroupProduct
Product:
    Scalar: Id, Sku, Description, etc.
    Navigation: ProductGroupProduct
ProductGroupProduct:
    Scalar: ProductGroupId, ProductId, Position
    Navigation: Product, ProductGroup

Note how the intermediate table has a scalar property called Position that specifies the order in which a product should be displayed within a product group.
How would you write a LINQ query that returns a list of products in a given product group sorted by the Position property? If I was writing good ol' SQL I'd write something like this:
SELECT p.Id, p.Sku, p.Description
FROM Product p
INNER JOIN ProductGroupProduct pgp ON p.Id = pgp.ProductId
WHERE pgp.ProductGroupId = @MyProductGroupId
ORDER BY pgp.Position

But I can't figure the LINQ out.

A: Um, your SQL won't work, because there is no ProductGroup.Position
But I think you want:
var q = from pgp in Context.ProductGroupProducts
        where pgp.ProductGroup.Id == id
        orderby pgp.Position
        select pgp.Product;


text:
Q: finally block in async method does not always run Consider this method that is called from a WebAPI controller
//WebAPI Controller
    public async LetsDoThis() {
       await _logic.Method();
    }

//logic class
     public async Task Method()
     {
         try
         {
             await DoSomething();
         }
         finally
         {
             await AlwaysDoThis();  //Will not always run
         }
    }

I am seeing a lot of instances where the code in the finally block is not being executed.  At first I thought this was due to OperationCancelledException being thrown but that does not seem to be the case.
What are likely causes for the code in the finally block to not run? (this is happening a lot so it is not an uncommon thing like the server crashing)

A:
What are likely causes for the code in the finally block to not run?

DoSomething() not completing.


text:
Q: p:commandButton with immediate=true What action is taken when I declare immediate="true" in command button? The documentation says

Boolean value that determines the phaseId of the action event, when true actions are processed at "Apply Request Values", when false at "Invoke Application" phase.

However, I don't understand it. Can someone please explain this?

A: JSF lifecycle contains 6 phases, which are:

*

*Restore view

*Apply request values

*Process validations

*Update model values

*Invoke application

*Render response

If a command button has immediate="true", then the phases 'Process validations' and 'Update model values' are skipped. Therefore, convertions and validations are not processed and attributes in managed bean are not updated.
However, if a UIInput in the form also has immediate="true", then its value will be converted, validated and updated in managed bean, because it will happen in 'Apply request values' phase.
One example of when you might use a button with immediate="true" is the case of a 'Cancel' button.