text:
Q: Curious about char pointer as class member? I saw this in a class declaration and was curious what is means? I am thinking that is may be a way to declare that a char array will be a member but the size is not fixed and will take it as an argument but I am not sure.
char *flagstr(int);

Is this what it is?

A: No, that is not what it is.
When you see a declaration like this inside a class
char *flagstr(int);

it declares a member function called flagstr which takes one argument of type int, and returns a pointer to character.
You can tell that you are looking at a function declaration, because there is a pair of parentheses after the name. It may be confusing, because the parameter name is omitted (C++ syntax rules do not require programmers to specify names of parameters in declarations; moreover, you can omit names of unused parameters in function definitions). Here is the same declaration that should look familiar:
char *flagstr(int flagValue);

A: This is just a function declaration which takes an int as its input parameter and return type char *.
You're confused here mainly because you forget that, in a function declaration, input parameter names are not necessary (only their types are).


text:
Q: Howto: Avoid EF creating Id In EF4 I have the following table
CREATE TABLE [dbo].[Things](
    Id] [uniqueidentifier] NOT NULL,
    [Text] [nvarchar](2048) NULL,
 CONSTRAINT [PK_AdjustmentMarker] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

In the EDMX the StoreGeneratedPattern is set to Identity:
<Property Name="Id" Type="uniqueidentifier" Nullable="false" StoreGeneratedPattern="Identity" />

People can add comments on an anonymous environment (real data, but faked customer names, etc.). We export the comments on the anonymous environment and import them on the production environment and need to have the original keys. But when adding the comments using EF (AddObject) and after calling SaveChanges EF recalculated the Id and inserts the comment with the new Id.
Am I gettings something wrong? I thought StoreGeneratedPatter = Identity will do the trick?
Source:
"Set the StoreGeneratedPattern attribute to "Identity" in your SSDL for the autoincrement field. It should help. "
(Autonumber with Entity Framework)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Play and Seek Audio File in iOS Is there an equivalent class in iOS to the Java Clip class which would allow me to set the position in WAV file in seconds and play the sound from that point?

A: Sounds like you are looking for the AVAudioPlayer class' playAtTime: method.


text:
Q: Ajax loading gif appending during calls I have this ajax call:
$('.ajaxtrigger2').click(function(){
$('#target').load('xxx.html');
...

how to append a Loading msg or image during this simple call? thx

A: Create another element, e.g.

Loading...

then show the loading element when you start loading, and hide it when its done through the load callback.
$('.ajaxtrigger2').click(function() {
    $("#loading").show();
    $("target").load('xxx.html', function() {
        $("#loading").hide();
    });
}

A: Create an Img, make the id equal to something like 'loading' and has a default style like "display: none;" and then add this to your jQuery onReady event
$("#loading").ajaxStart(function () { $(this).show(); }).ajaxStop(function () { $(this).hide(); });

A: I personally like to use css, and add remove stuffs.

A: there's a couple of ways. My preferred way is to attach a function to the ajaxStart/Stop events on the element itself.
$('#loadingDiv')
    .hide()  // hide it initially
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    })
;

The ajaxStart/Stop functions will fire whenever you do any ajax calls.


text:
Q: Xcode: Multiple text lines in pop-up I'm trying to  create a text box with multiple fields, but I'm having trouble getting the second to show (as a matter of fact, when I type the second field in, it causes my text box not to show up all together.)
Here's what I have:
-(IBAction)popupCheckIn {
//UIAlertView *alertCheckIn = [[UIAlertView alloc] initWithTitle:@"Check in" message:@"Please fill out the following to check in." delegate:self cancelButtonTitle:@"Check in." otherButtonTitles:@"Cancel.", nil];

//[alertCheckIn show];
UIAlertView * alert =[[UIAlertView alloc ] initWithTitle:@"Check in" message:@"Please fill out the following fields to check in." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles: nil];

alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField * nameField = [alert textFieldAtIndex:0];
nameField.keyboardType = UIKeyboardTypeDefault;
nameField.placeholder = @"Your Name";

alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField * hostField = [alert textFieldAtIndex:1];
hostField.keyboardType = UIKeyboardTypeDefault;
hostField.placeholder = @"Host Name";

[alert addButtonWithTitle:@"Check in."];
[alert show];

When I run this code, I get an error that says "Thread 1: signal SIGABRT" and my pop up won't come up at all; when I have just the name field, it works fine.
What am I doing wrong with my second text field? Thanks!

A: I think that your error arises because that type of UIAlertView doesn't contain more than one UITextField, and when trying to access the second it raises a NSRangeException. This is according to the docs.
https://developer.apple.com/library/ios/documentation/uikit/reference/UIAlertView_Class/UIAlertView/UIAlertView.html#//apple_ref/occ/instm/UIAlertView/textFieldAtIndex:

A: I tried your code, the entire error message is:
2014-06-26 17:13:56.213 Testing1[2444:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'textFieldIndex (1) is outside of the bounds of the array of text fields'

The issue, is that you only have ONE UITextField with the UIAlertViewStyle set to UIAlertViewStylePlainTextInput. So this part of code ([alert textFieldAtIndex:1] is causing the crash).
Repeating the line alert.alertViewStyle = UIAlertViewStylePlainTextInput; won't create a new one.
The only way to get 2 UITextFields, is to use the UIAlertViewStyleLoginAndPasswordInput UIAlertViewStyle.
A way could be then to set the second one (like the first one) is like this:
[hostField setSecureTextEntry:FALSE];

But personally, I think that I don't recommend it. It may be blocked in the future.
Since we cannot custom really the existing UIAlertView since iOS7 (can't add subview), I'd suggest you create (or find in CocoaControls/GitHub) your own CustomAlertView-like.

A: You'll want to use alert with the alert style UIAlertViewStyleLoginAndPasswordInput. See this answer: UIAlertView with Two TextFields and Two Buttons


text:
Q: Ruby Array - Delete first 10 digits I have an array in Ruby and I would like to delete the first 10 digits in the array.
array = [1, "a", 3, "b", 2, "c", 4, "d", 5, "a", 1, "z", 7, "e", 21, "q", 30, "a", 4, "t", 7, "m", 5, 1, 2, "q", "s", "l", 13, 46, 31]

It would ideally return
['a', 'b', 'c', 'd', 'a', 'z', 'e', 'q', 0, 'a', 4, t, 7, m, 5 , 1, 2, q, s, 1, 13, 46, 31]

By removing the first 10 digits (1,3,2,4,5,1,7,2,1,3).
Note that 21(2 and 1) and 30(3 and 0) both have 2 digits
Here's what I've tried
digits = array.join().scan(/\d/).first(10).map{|s|s.to_i}
=> [1,3,2,4,5,1,7,2,1,3]
elements = array - digits

This is what I got
["a", "b", "c", "d", "a", "z", "e", 21, "q", 30, "a", "t", "m", "q", "s", "l", 13, 46, 31]

Now it looks like it took the difference instead of subtracting.
I have no idea where to go from here. and now I'm lost. Any help is appreciated.

A: To delete 10 numbers:
10.times.each {array.delete_at(array.index(array.select{|i| i.is_a?(Integer)}.first))}
array

To delete 10 digits:
array = [1, "a", 3, "b", 2, "c", 4, "d", 5, "a", 1, "z", 7, "e", 21, "q", 30, "a", 4, "t", 7, "m", 5, 1, 2, "q", "s", "l", 13, 46, 31]
i = 10
while (i > 0) do
    x = array.select{|item| item.is_a?(Integer)}.first
    if x.to_s.length > i
      y = array.index(x)
      array[y] = x.to_s[0, (i-1)].to_i
    else
      array.delete_at(array.index(x))
    end
    i -= x.to_s.length
end
array

A: Unfortunately not a one-liner:
count = 10
array.each_with_object([]) { |e, a|
  if e.is_a?(Integer) && count > 0
    str = e.to_s                     # convert integer to string
    del = str.slice!(0, count)       # delete up to 'count' characters
    count -= del.length              # subtract number of actually deleted characters
    a << str.to_i unless str.empty?  # append remaining characters as integer if any
  else
    a << e
  end
}
#=> ["a", "b", "c", "d", "a", "z", "e", "q", 0, "a", 4, "t", 7, "m", 5, 1, 2, "q", "s", "l", 13, 46, 31]

A: I would be inclined to do it like this.
Code
def doit(array, max_nbr_to_delete)
  cnt = 0
  array.map do |e|
    if (e.is_a? Integer) && cnt < max_nbr_to_delete
      cnt += e.to_s.size
      if cnt <= max_nbr_to_delete
        nil
      else
        e.to_s[cnt-max_nbr_to_delete..-1].to_i
      end
    else
      e
    end
  end.compact
end

Examples
array = [ 1, "a", 3, "b", 2, "c", 4, "d", 5, "a", 1, "z", 7, "e", 21, "q",
         30, "a", 4, "t", 7, "m", 5, 1, 2, "q", "s", "l", 13, 46, 31]

doit(array, 10)
  #=> ["a", "b", "c", "d", "a", "z", "e", "q", 0, "a", 4,
  #    "t", 7, "m", 5, 1, 2, "q", "s", "l", 13, 46, 31]
doit(array, 100)
  #=> ["a", "b", "c", "d", "a", "z", "e", "q", "a", "t", "m", "q", "s", "l"]

Explanation
Each element e of the array that is not an integer is mapped to e.
For each non-negative integer n having d digits, suppose cnt is the number of digits that map has already been removed from the string.  There are three possibilities:

*

*if cnt >= max_nbr_to_delete, no more digits are to be removed, so e (itself) is returned

*if cnt + d <= max_nbr_to_delete all d digits of e are to be removed, which is done by mapping e to nil and subsequently removing nil elements

*if cnt < max_nbr_to_delete and cnt + d > max_nbr_to_delete, e.to_s[cnt+d-max_nbr_to_delete..-1].to_i is returned (i.e. the first cnt+d-max_nbr_to_delete digits of e are removed).


text:
Q: MJML Layout is very buggy in Outlook client but ok in other clients I have used MJML to create 2 different email layouts, one with one button and another one with 2 buttons.
These emails look very good in most clients (webmails, gmail, outlook web, ...) But in the outlook client it looks very bad.
I read that width="" is not that well supported going from MJML to HTML for Outlook, so we deleted the width parameter everywhere in MJML. Apart from that we use nothing out of the ordinary in our emails.
This is the MJML:
<mjml>
      <mj-body background-color="#f2f8f9">
        <mj-section background-color="#77c5d5" padding-bottom="0px" padding-top="0">
          <mj-column vertical-align="top">
            <mj-image src="https://www.goomlandscapes.co.nz/wp-content/uploads/2018/08/logo-placeholder.png" alt="logo" align="center" border="none" width="200px" padding-left="0px" padding-right="0px" padding-bottom="10px" padding-top="10px"></mj-image>
          </mj-column>
        </mj-section>
        <mj-section background-color="#FFFFFF" padding-bottom="0px" padding-top="0">
          <mj-column vertical-align="top">
            <mj-text align="center" color="#1a5966" font-size="28px" font-weight="bold" font-family="open Sans Helvetica, Arial, sans-serif" padding-left="25px" padding-right="25px" padding-bottom="0px" padding-top="15px">Welkom bij WebsiteName</mj-text>
          </mj-column>
        </mj-section>
        <mj-section background-color="#FFFFFF" padding-bottom="20px">
          <mj-column vertical-align="top">
            <mj-text align="left" color="#000000" font-size="18px" font-family="open Sans Helvetica, Arial, sans-serif" padding-left="25px" padding-right="25px">
              Dag John,
            </mj-text>
            <mj-text align="left" color="#000000" font-size="15px" font-family="open Sans Helvetica, Arial, sans-serif" padding-left="25px" padding-right="25px">
              Bedankt om te registreren bij ons.

              Je profiel is aangemaakt en klaar voor gebruik. Je kan inloggen met je emailadres: {{email}}.

              Met vriendelijke groeten.
            </mj-text>
          </mj-column>
        </mj-section>
        <mj-section background-color="#FFFFFF" padding-bottom="20px">
          <mj-column vertical-align="top">
            <mj-button align="center" href="https://www.google.be" font-size="18px" font-weight="bold" background-color="#FFFFFF" border-radius="12px" border="2px solid #D9E9EB;" color="#000000" font-family="open Sans Helvetica, Arial, sans-serif">Doe iets!</mj-button>
          </mj-column>
          <mj-column vertical-align="top">
            <mj-button align="center" href="https://www.google.be" font-size="18px" font-weight="bold" background-color="#FFFFFF" border-radius="12px" border="2px solid #D9E9EB;" color="#000000" font-family="open Sans Helvetica, Arial, sans-serif">Doe iets!</mj-button>
          </mj-column>
        </mj-section>
        <mj-section padding-bottom="0px" padding-top="0">
          <mj-column>
                <mj-image src="https://3263vihaxx3jy9zn2ikegau7-wpengine.netdna-ssl.com/wp-content/uploads/2018/12/footer-bg-placeholder.jpg" alt="footer"></mj-image>
          </mj-column>
        </mj-section>
        <mj-section padding-bottom="0px" padding-top="0">
          <mj-column vertical-align="middle">
            <mj-social font-size="14px" icon-size="25px" mode="horizontal">
              <mj-social-element name="facebook" href="xyz"></mj-social-element>
              <mj-social-element name="instagram" href="xyz"></mj-social-element>
              <mj-social-element  name="linkedin" href="xyz"></mj-social-element>
            </mj-social>
          </mj-column>
        </mj-section>
        <mj-section>
          <mj-column>
            <mj-text align="center" font-size="10px" padding-top="0">Copyright 2021 - WebsiteName. Alle rechten voorbehouden.</mj-text>
          </mj-column>
        </mj-section>
      </mj-body>
    </mjml>

The preview in MJML looks like this:

So the HTML this generates is put into our system and send via SendGrid.
The resulting email looks like this in Outlook:

What is happening for this email to look so bad in Outlook client? (it also looks similarly bad in Windows default Mail client)


text:
Q: Apache- 403 forbidden I have configured Apache to use the UserDir part so I can create users on
http://ip.add.re.ss/~username/ where this refers to /home/username/public_html
The problem is,when I go to the above URL, I get a 403 forbidden.
I have given the /home/username/public_html folder to be writable to check, but I cannot see why this would be forbidden.
Am i missing anything possibly in Apache or user permissions?
Thanks

A: /home/username should be "executable" by the apache process, the executable bit allows to change to that directory. /home/username/public_html and all below should be readable and executable by the apache process. It should not be writable unless there is an application specific need.
So this should do the trick:
chmod a+x /home/username
chmod -R a+rx /home/username/public_html

Try specifying full url to the file, for example: http://ip.add.re.ss/~username/mydoc.html Otherwise you willbe relying on default index. Also if you are using SELinux you may be having trouble with its restrictions, do a quick test changing it to permisive:
http://www.centos.org/docs/5/html/5.2/Deployment_Guide/sec-sel-enable-disable.html

A: Ok, so it looked like: chcon -R -t httpd_sys_content_t /home/username* seemed to do the trick and it is now accessible!


text:
Q: Cannot find module when compiling under Visual Studio I have very simple TypeScript app, which compiles fine using webpack, but gives me an error "Build:Cannot find module 'react'" when trying to build in Visual Studio. I'm stuck, any help is appreciated.
package.json:

{
  "name": "react-router-test",
  "version": "1.0.0",
  "description": "",
  "main": "./dist/bundle.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^15.4.0",
    "react-dom": "^15.4.0",
    "react-router": "^3.0.0"
  },
  "devDependencies": {
    "@types/react": "^0.14.49",
    "@types/react-dom": "^0.14.18",
    "@types/react-router": "^2.0.39",
    "babel-cli": "^6.18.0",
    "babel-core": "^6.18.2",
    "babel-loader": "^6.2.7",
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-react": "^6.16.0",
    "ts-loader": "^1.2.1",
    "typescript": "^2.0.10",
    "webpack": "^1.13.3"
  }
}

webpack.config.js:

    module.exports = {
    entry: "./src/Index.tsx",
    output: {
        filename: "./dist/bundle.js"
    },

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: ["", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
    },

    module: {
        //loaders: [
        //    { test: /\.tsx$/, exclude: /node_modules/, loader: 'babel-loader?presets[]=es2015&presets[]=react!ts-loader' }

        loaders: [
            {
                test: /\.ts(x?)$/,
                loader: "babel-loader!ts-loader"
            },
        ]

    },

    devServer: {
        contentBase: ".",
        host: "localhost",
        port: 8081
    },

    externals: {
        "react": "React",
        "react-dom": "ReactDOM"
    },

}

tsconfig.json:

{
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es6",
    "jsx": "preserve",
    "module": "commonjs"
  }
}

Hello.tsx:

import * as React from "react";

interface IHelloProps { compiler: number }

export class Hello extends React.Component<IHelloProps, {}> {
    render() {
        return <div > Hell no 2!</div >
    }
}

A: I got it all resolved by installing latest version (2.0.6.0) from here: https://www.microsoft.com/en-us/download/details.aspx?id=48593


text:
Q: Adams Bashforth method question Consider an ordinary differential equation
$$\dfrac{dy}{dt} = 0.5y - 2.5\sin(t),~~  0 <t \le 12$$
for the function $y(t)$ with the initial condition $y(0) = 2$

*

*Derive equations for Adams-Bashforth three-step method applied to this
problem. Provide an expression for the value of the approximate solution
$w_{i+1}$ at a timestep $t_{i+1}$ in terms of previously calculated values. Take
required starting values from the exact solution $y(t)= 2 \cos(t) + \sin(t)$.
Provide the starting values.

*Write a Matlab code implementing the method for this problem. Provide
the text of the code

A: The general formula for the A-B 3-step method, as seen in this link, can be defined iteratively as follows:
$$
y_{n+3} = y_{n+2} + h\left( \frac{23}{12} f(t_{n+2}, y_{n+2}) - \frac43 f(t_{n+1}, y_{n+1}) + \frac{5}{12}f(t_n, y_n)\right)
$$
Where $h$ is the difference between each timestep $t_i$.  I'm not sure what they want for the derivation, but in the end of the day, you should have:
$$
\begin{align}
y_{n+3} &= y_{n+2}  \\
+& h\frac{23}{12} (0.5y_{n+2} - 2.5\sin(t_{n+2})) \\
-& h\frac43 (0.5y_{n+1} - 2.5\sin(t_{n+1})) \\
+& h\frac{5}{12}(0.5y_{n} - 2.5\sin(t_{n}))
\end{align}
$$
as your recursive definition.  In your terminology, this becomes
$$
\begin{align}
w_{i+1} &= w_{i}  \\
+& h\frac{23}{12} (0.5w_{i} - 2.5\sin(t_{i})) \\
-& h\frac43 (0.5w_{i-1} - 2.5\sin(t_{i-1})) \\
+& h\frac{5}{12}(0.5w_{i-2} - 2.5\sin(t_{i-2}))
\end{align}
$$
As you can see from the definition, this method requires $3$ starting values.  For whatever $h$ you choose, our starting three values are
$$
w_0 = 2\cos(t_0) + \sin(t_0)=2\\
w_1 = 2\cos(t_1) + \sin(t_1)\\
w_2 = 2\cos(t_2) + \sin(t_2)
$$
Where for each $i$: $t_i=i\cdot h$.
Could you code this problem for here? If not, where do you run into difficulty?

The Code:
%INITIALIZATION:
h = .01; % This is your timestep interval (step size)
a = 0; % This is your starting point
b = 12; % This is your ending point

t = a:h:b; %an array of all timesteps
L = length(t);
w = zeros(1,L); %the array that will eventually contain AB approximation
for i = 1:3
    w(i) = 2*cos(t(i))+sin(t(i));
end

%ITERATION
for i = 3:(L-1)
    part_1 = h*(23/12)*(0.5*w(i)-2.5*sin(t(i)));
    part_2 = -h*(4/3)*(0.5*w(i-1)-2.5*sin(t(i-1)));
    part_3 = h*(5/12)*(0.5*w(i-2)-2.5*sin(t(i-2)));
    w(i+1) = w(i) + part_1 + part_2 + part_3;
end

%TO PLOT THE FUNCTION, ADD
plot(t,w)


text:
Q: how to make scrollable the legends of pie chart ( chart js ) I have this pie chart with this problems. i have many items and the responsive has not an scroll for show correctly the legends in mobile mode. ¿Is there any solution?
Show image here

new Chart(document.getElementById("pie-chart"), {
            type: 'pie',
            data: {
            labels: [<?php echo $mostrar_prendas;?>],
            datasets: [{
            label: "Population (millions)",
            backgroundColor: [<?php echo $mostrar_colores;?>],
            data: [<?php echo $mostrar_cantidad;?>]
            }]
            },
            options: {
            title: {
            display: false,
            text: 'Predicted world population (millions) in 2050'
            },

            }
          });

A: You can make use of an HTML legend, this will stay out of the canvas so it will always be viseble and you can style it however you want. Chart.js has a sample on their website with how to implement it: https://www.chartjs.org/docs/latest/samples/legend/html.html
Live example:

const getOrCreateLegendList = (chart, id) => {
  const legendContainer = document.getElementById(id);
  let listContainer = legendContainer.querySelector('ul');

  if (!listContainer) {
    listContainer = document.createElement('ul');
    listContainer.style.display = 'flex';
    listContainer.style.flexDirection = 'row';
    listContainer.style.margin = 0;
    listContainer.style.padding = 0;

    legendContainer.appendChild(listContainer);
  }

  return listContainer;
};

const htmlLegendPlugin = {
  id: 'htmlLegend',
  afterUpdate(chart, args, options) {
    const ul = getOrCreateLegendList(chart, options.containerID);

    // Remove old legend items
    while (ul.firstChild) {
      ul.firstChild.remove();
    }

    // Reuse the built-in legendItems generator
    const items = chart.options.plugins.legend.labels.generateLabels(chart);

    items.forEach(item => {
      const li = document.createElement('li');
      li.style.alignItems = 'center';
      li.style.cursor = 'pointer';
      li.style.display = 'flex';
      li.style.flexDirection = 'row';
      li.style.marginLeft = '10px';

      li.onclick = () => {
        const {
          type
        } = chart.config;
        if (type === 'pie' || type === 'doughnut') {
          // Pie and doughnut charts only have a single dataset and visibility is per item
          chart.toggleDataVisibility(item.index);
        } else {
          chart.setDatasetVisibility(item.datasetIndex, !chart.isDatasetVisible(item.datasetIndex));
        }
        chart.update();
      };

      // Color box
      const boxSpan = document.createElement('span');
      boxSpan.style.background = item.fillStyle;
      boxSpan.style.borderColor = item.strokeStyle;
      boxSpan.style.borderWidth = item.lineWidth + 'px';
      boxSpan.style.display = 'inline-block';
      boxSpan.style.height = '20px';
      boxSpan.style.marginRight = '10px';
      boxSpan.style.width = '20px';

      // Text
      const textContainer = document.createElement('p');
      textContainer.style.color = item.fontColor;
      textContainer.style.margin = 0;
      textContainer.style.padding = 0;
      textContainer.style.textDecoration = item.hidden ? 'line-through' : '';

      const text = document.createTextNode(item.text);
      textContainer.appendChild(text);

      li.appendChild(boxSpan);
      li.appendChild(textContainer);
      ul.appendChild(li);
    });
  }
};

const options = {
  type: 'doughnut',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
      borderWidth: 1
    }]
  },
  options: {
    plugins: {
      htmlLegend: {
        // ID of the container to put the legend in
        containerID: 'legend-container',
      },
      legend: {
        display: false,
      }
    }
  },
  plugins: [htmlLegendPlugin]
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <div id="legend-container">

  </div>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.3.2/chart.js"></script>
</body>


text:
Q: Sharepoint Online WebPart in Blazor Wasm I am trying to add a blazor wasm application on sharepoint. Is a client application so its support to be supported.
I create .net 7 Blazor empty site, just basic settings. In my index.html I have:

and also


text:
Q: Chrome extension + angular-cli : UI issues after build I wrote an app with a sticky header on the top using angular2 mdl layouts.
Recently I rewrote the code to get a more flexible custom header.
Since then, when I build the app (ng build) and import it as an unpacked extension, the content in my container doesn't scroll anymore.
Nonetheless, the build works flawlessly in a 'casual' browser window, i.e when the app is hosted on a local server and opened in chrome.
What could be the problem ?
Here is the angular-cli project. You can test it with ng serve.
Then load the result (dist folder) produced by the ng build command as an unpacked extension. Don't forget to add the manifest to the folder.
And here is a plunker
The code itself :
app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app title!';
  search = 'search';
}

app.component.html

        {{title}}

          {{search}}

test

test

test

test

test

test

test

test

test

test

test

test

test

test

test

test

test

test

test

test

test

index.html
!doctype html>

  <base href="/">
  <meta charset="utf-8">
  <title>Mosaic Chrome Extension</title>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="https://fonts.googleapis.com/css?family=Open+Sans|Roboto" rel="stylesheet">

  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link rel="stylesheet" href="https://code.getmdl.io/1.2.1/material.deep_orange-indigo.min.css" />

  <app-root>Loading...</app-root>

A: After much hair pulling, it appears that Google Chrome Extensions don't like the min & max width parameters.
Setting both to :
  min-width: 799px;
  max-width: auto;

Did the trick. Go figure.
Edit Jun 17 :
I also encountered afterwards awkward behaviour from Angular Material and Mdl components, that were not or partially working. Upon further investigation it appeared that the Angular Zones were broken and that I needed to refresh the UI state manually by calling zone.run(() => {});
From the different tests I did, it looks like this problem was also causing that weird scrolling issue.


text:
Q: How to create a dissimilarity matrix with daisy function in R? I want to perform a cluster analysis with the pam function in R, using daisy to create a dissimilarity matrix. My data contains 2 columns (ID and Disease). Both are factors with a lot of values (400 and 1800 respectively). How can I create the dissimilarity matrix I need to cluster the data using pam?
Example data frame:
set.seed(1)
df <- data.frame(ID = rep(sample(c("a","b","c","d","e","f","g"),10,replace = TRUE),70),
                 disease = sample(c("flu","headache","pain","inflammation","depression","infection","chest pain"),100,replace = TRUE))

df <- unique(df)

Can I run the daisy function on this data frame or do I have to convert it into another format?

A: Since "Dissimilarities will be computed between the rows of x" (?daisy), you may want to run daisy on the table of your data frame.
(df.tab <- table(df))
#    disease
# ID  chest pain depression flu headache infection inflammation pain
#   a          1          1   1        1         1            1    1
#   b          1          1   1        1         1            1    1
#   c          1          1   0        0         1            1    1
#   d          1          1   1        0         1            0    1
#   e          0          1   1        1         1            1    0
#   f          0          1   1        1         1            0    1
#   g          1          1   1        1         1            1    0

library(cluster)
daisy(df.tab, metric="euclidean")
# Dissimilarities :
#   a        b        c        d        e        f
# b 0.000000
# c 1.414214 1.414214
# d 1.414214 1.414214 1.414214
# e 1.414214 1.414214 2.000000 2.000000
# f 1.414214 1.414214 2.000000 1.414214 1.414214
# g 1.000000 1.000000 1.732051 1.732051 1.000000 1.732051
#
# Metric :  euclidean
# Number of objects : 7


text:
Q: javafx drag and drop not able to drop in another application, can from a swing wrapper Here is a sample application, which allows you to drag and drop some text into other areas.
One application I want to drop into allows the drop from swing but not from JavaFX.
If the JavaFX is in a JFXPanel and a Swing JFrame, it drops fine.
If it's just pure JavaFX in a Stage, it has the 'no entry' logo and doesn't accept the drop.
Other applications allow or block both.  But this one application accepts the drop from JFrame but not Stage, the actual Label component etc is the same.
import javafx.application.Application;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;

import javax.swing.*;

public class DragViewExample extends Application {

@Override
public void start(Stage primaryStage) {
    TextField tf = new TextField("Copied Text");

    tf.setOnDragDetected(e -> {
        Dragboard db = tf.startDragAndDrop(TransferMode.COPY);
        db.setDragView(new Text(tf.getText()).snapshot(null, null), e.getX(), e.getY());
        ClipboardContent cc = new ClipboardContent();
        cc.putString(tf.getText());
        db.setContent(cc);
    });

    tf.setOnDragDropped(event -> {
        System.out.println("dropped");
    });

    tf.setOnDragDone(event -> {
        System.out.println("done");
    });

    //FULL JAVAFX
    Scene scene = new Scene(new StackPane(new HBox(10, tf)), 350, 75);
    primaryStage.setScene(scene);
    primaryStage.show();

    //JAVAFX INSIDE SWING
//        JFrame frame = new JFrame();
//        JFXPanel fxPanel = new JFXPanel();
//        Scene swingscene = new Scene(new StackPane(new HBox(10, tf)), 350, 75);
//        fxPanel.setScene(swingscene);
//        frame.setContentPane(fxPanel);
//        frame.pack();
//        frame.setVisible(true);
}

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

A: It doesn't work cause you have not implemented on onDragOver:
The correct way to do the drag and drop here is(where source is the textField):
source.setOnDragDetected(new EventHandler<MouseEvent>() {
    public void handle(MouseEvent event) {
        /* drag was detected, start a drag-and-drop gesture*/
        /* allow any transfer mode */
        Dragboard db = source.startDragAndDrop(TransferMode.ANY);

        /* Put a string on a dragboard */
        ClipboardContent content = new ClipboardContent();
        content.putString(source.getText());
        db.setDragView(new Text(tf.getText()).snapshot(null, null), e.getX(), e.getY());
        db.setContent(content);

        event.consume();
    }
});

target.setOnDragOver(new EventHandler<DragEvent>() {
    public void handle(DragEvent event) {
        /* data is dragged over the target */

        if (event.getDragboard().hasString()) {
            /* allow for both copying and moving, whatever user chooses */
            event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
        }

        event.consume();
    }
});

For a full answer follow the official oracle tutorial

(http://docs.oracle.com/javafx/2/drag_drop/jfxpub-drag_drop.htm)


text:
Q: notice trying to get property of non-object what is the error in this please help!
here is the query from mysql :

public function stgradu($condition=">=50"){
    $stmt=$this->db->prepare("SELECT
    courses_has_schedule.mark as mark,
    Sum(courses.crs_hours) as total_hrs
    FROM
    courses_has_schedule
    Inner Join courses ON courses_has_schedule.crs_id = courses.crs_id
    Inner Join schedule ON schedule.sch_id = courses_has_schedule.sch_id
    Inner Join student ON student.st_id = schedule.st_id

    where
    student.st_id=? AND courses_has_schedule.mark $condition");
    $stmt->execute(array($this->getCurrentStudent(true)));
    return $stmt->fetchAll();
}

when i run this if statement :
$stgr = $dataService->stgradu(">=50");
if(($stgr->total_hrs==7) AND ($stgradu->mark >= 50)) {
  echo Yes*";
}else
  echo "No";

when i run the app its gives me  this error
(( Notice: Trying to get property of non-object in C:\xampp\htdocs\samer\stgr.php on line >12))
please help all!

A: fetchAll returns an array and you are trying to acces it like an object. Try this:
    if(($stgr['total_hrs']==7) AND ($stgradu['mark'] >= 50)) {

A: You need to pass PDO::FETCH_OBJ to fetchAll() because it returns an associative array by default.
public function stgradu($condition=">=50"){
    $stmt=$this->db->prepare("SELECT
    courses_has_schedule.mark as mark,
    Sum(courses.crs_hours) as total_hrs
    FROM
    courses_has_schedule
    Inner Join courses ON courses_has_schedule.crs_id = courses.crs_id
    Inner Join schedule ON schedule.sch_id = courses_has_schedule.sch_id
    Inner Join student ON student.st_id = schedule.st_id

    where
    student.st_id=? AND courses_has_schedule.mark $condition");
    $stmt->execute(array($this->getCurrentStudent(true)));
    return $stmt->fetchAll(PDO::FETCH_OBJ);
}

If you are supposed to get only one row then change it to fetch(PDO::FETCH_OBJ) and your code should run fine.

A: thanx all.. i knew it by my self :P the syntax should be...

return $stmt->fetchAll()[0];


text:
Q: NullPointerException in swing at actionPerformed This is a login form for a slot machine game which will evoke a "NextPage" object. I don't think this LoginDemo.java code has to do anything with the error but I prefer to post the entire code. Thanks in advance..
    //LoginDemo.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class Login extends JFrame implements ActionListener
{
     JButton SUBMIT;
     JPanel panel;
     JLabel label1,label2;
     final JTextField  text1,text2;
    Login()
    {
        label1 = new JLabel();
        label1.setText("Username:");
        label1.setBounds(50,50,100,30);
        text1 = new JTextField(15);
        text1.setBounds(250,50,100,30);
        label2 = new JLabel();
        label2.setText("Password:");
        label2.setBounds(50,250,100,30);
        text2 = new JPasswordField(15);
        text2.setBounds(250,250,100,30);
        //this.setLayout(new BorderLayout());

        SUBMIT=new JButton("SUBMIT");
        SUBMIT.setBounds(350,350,100,30);

         //     panel=new JPanel(new GridLayout(3,1));
            panel=new JPanel(null);
        panel.setBounds(50,50,1000,1000);
        //  panel.setLayout(new FlowLayout());
        panel.add(label1);
        panel.add(text1);
        panel.add(label2);
        panel.add(text2);
        panel.add(SUBMIT);
            add(panel,BorderLayout.CENTER);
                SUBMIT.addActionListener(this);
                setTitle("LOGIN FORM");
    }
    public void actionPerformed(ActionEvent ae)
    {
        String value1=text1.getText();
        String value2=text2.getText();
        if (value1.equals("a") && value2.equals("a"))
        {
            NextPage page=new NextPage();
            page.setVisible(true);
            //JLabel label = new JLabel("Welcome:"+value1);
                // page.getContentPane().add(label);
            setVisible(false);
        }
        else
        {
            //System.out.println("enter the valid username and password");
            JOptionPane.showMessageDialog(this,"Incorrect login or password","Error",JOptionPane.ERROR_MESSAGE);
        }
    }
}
class LoginDemo
{
    public static void main(String arg[])
{
    try
    {
        Login frame=new Login();
        frame.setSize(1000,1000);
        frame.setVisible(true);
    }
    catch(Exception e)
    {
        JOptionPane.showMessageDialog(null, e.getMessage());
    }

    }
}

    //NextPage.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.Random;
import java.sql.*;
import java.lang.*;
import java.awt.image.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class NextPage extends JFrame implements Runnable, ActionListener
{
        BufferedImage  img1,i0,i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,star1;
    JFrame f1;
    Thread t1,t2,t3;
    int x1,y1,i,j,k,l,m,n,r1,r2,r3;
    JButton b1;
    Random r=new Random();
    TextField tf1;
        JPanel p1;

    NextPage()
    {
        setBounds(50,50,1000,1000);
        p1=(JPanel)(getContentPane());
        p1.setBounds(50,50,1000, 1000);
        p1.setLayout(null);
        //tf1=new TextField(20);
        //tf1.setBounds(50,50,100,30);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Welcome");

        b1=new JButton("START");

        //p1.add(tf1);

        b1.setBounds(150,400,100,30);
        //try{
        b1.addActionListener(this);
        //}
        /*catch(Exception e)
        {
            System.out.println(""+e);
        }*/
        add(b1);
        setVisible(true);
        try
        {
            i0=ImageIO.read(new File("tea.jpg"));
                 i1=ImageIO.read(new File("coffee.jpg"));
             i2=ImageIO.read(new File("bhel.jpg"));
            i3=ImageIO.read(new File("pizza.jpg"));
             i4=ImageIO.read(new File("icecream.jpg"));
             i5=ImageIO.read(new File("dosa.jpg"));
             i6=ImageIO.read(new File("idli.jpg"));
             i7=ImageIO.read(new File("panipuri.jpg"));
             i8=ImageIO.read(new File("orange.jpg"));
             i9=ImageIO.read(new File("watermelon.jpg"));
             i10=ImageIO.read(new File("pavbhaji.jpg"));
             i11=ImageIO.read(new File("noodles.jpg"));
             i12=ImageIO.read(new File("sandwich.jpg"));
         }
        catch (IOException ie)
        {
            System.out.println("Error:"+ie.getMessage());
        }

        j=0; m=0; n=0;

        r1= r.nextInt(13);
        r2= r.nextInt(13);
        r3= r.nextInt(13);

    }
    public void init()
    {
        t1=new Thread(this);
        t2=new Thread(this);
        t3=new Thread(this);
    }

    public void start()
    {
        t2.start();
        t3.start();
    }
    public void run()
    {
        try
        {
            if(Thread.currentThread()==t1)
            for(j=0; j<150; j++)
            //for(i=0; i<=150; i+=20)
            {
                r1= r.nextInt(13);
                repaint();
                t1.sleep(10);
            }

            if(Thread.currentThread()==t2)
            for(m=0; m<160; m++)
            //for(k=0; k<=150; k+=20)
            {
                r2= r.nextInt(13);
                repaint();
                t2.sleep(10);
            }
            if(Thread.currentThread()==t3)
            for(n=0; n<170; n++)
            //for(l=0; l<=150; l+=20)
            {
                r3= r.nextInt(13);
                repaint();
                t3.sleep(10);
            }
        }
        catch(Exception e)
        {
            System.out.println(""+e);
        }

    }

    public void paint(Graphics g)
    {
        g.setColor(Color.blue);

        g.drawRect(50,300,150,80);
        g.drawRect(200,300,150,80);
        g.drawRect(350,300,150,80);

            switch(r1)
            {
                case 0: g.drawImage(i0,65,300,this);
                break;
                case 1: g.drawImage(i1,65,300,this);
                break;
                case 2: g.drawImage(i2,65,300,this);
                break;
                case 3: g.drawImage(i3,65,300,this);
                break;
                case 4: g.drawImage(i4,65,300,this);
                break;
                case 5: g.drawImage(i5,65,300,this);
                break;
                case 6: g.drawImage(i6,65,300,this);
                break;
                case 7: g.drawImage(i7,65,300,this);
                break;
                case 8: g.drawImage(i8,65,300,this);
                break;
                case 9: g.drawImage(i9,65,300,this);
                break;
                case 10: g.drawImage(i10,65,300,this);
                break;
                case 11: g.drawImage(i11,65,300,this);
                break;
                case 12: g.drawImage(i12,65,300,this);
                break;
            }

            switch(r2)
            {
                case 0: g.drawImage(i0,215,300,this);
                break;
                case 1: g.drawImage(i1,215,300,this);
                break;
                case 2: g.drawImage(i2,215,300,this);
                break;
                case 3: g.drawImage(i3,215,300,this);
                break;
                case 4: g.drawImage(i4,215,300,this);
                break;
                case 5: g.drawImage(i5,215,300,this);
                break;
                case 6: g.drawImage(i6,215,300,this);
                break;
                case 7: g.drawImage(i7,215,300,this);
                break;
                case 8: g.drawImage(i8,215,300,this);
                break;
                case 9: g.drawImage(i9,215,300,this);
                break;
                case 10: g.drawImage(i10,215,300,this);
                break;
                case 11: g.drawImage(i11,215,300,this);
                break;
                case 12: g.drawImage(i12,215,300,this);
                break;
            }

            switch(r3)
            {
                case 0: g.drawImage(i0,365,300,this);
                break;
                case 1: g.drawImage(i1,365,300,this);
                break;
                case 2: g.drawImage(i2,365,300,this);
                break;
                case 3: g.drawImage(i3,365,300,this);
                break;
                case 4: g.drawImage(i4,365,300,this);
                break;
                case 5: g.drawImage(i5,365,300,this);
                break;
                case 6: g.drawImage(i6,365,300,this);
                break;
                case 7: g.drawImage(i7,365,300,this);
                break;
                case 8: g.drawImage(i8,365,300,this);
                break;
                case 9: g.drawImage(i9,365,300,this);
                break;
                case 10: g.drawImage(i10,365,300,this);
                break;
                case 11: g.drawImage(i11,365,300,this);
                break;
                case 12: g.drawImage(i12,365,300,this);
                break;
            }
        }
        public void actionPerformed(ActionEvent ae)
        {
            if(ae.getSource()==b1)
            t1.start();
        }

        /*public static void main(String args[])
        {
            NextPage o=new NextPage();
        }*/
    }
}

Here are the exceptions that I get-
F:\java\jdk\bin>java LoginDemo
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at NextPage.actionPerformed(NextPage.java:235)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
atjavax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6289)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6054)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4652)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4482)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4482)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:644)
at java.awt.EventQueue.access$000(EventQueue.java:85)
at java.awt.EventQueue$1.run(EventQueue.java:603)
at java.awt.EventQueue$1.run(EventQueue.java:601)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87
at
java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98
at java.awt.EventQueue$2.run(EventQueue.java:617)
at java.awt.EventQueue$2.run(EventQueue.java:615)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87
at java.awt.EventQueue.dispatchEvent(EventQueue.java:614)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Can't get any solution.. I am a learner..please help..

A: You do not call the init method, hence your t1 variable is still null when you enter the actionPerformed method.
This is rather obvious from the stacktrace (there is only one thing that can be null on that line), and if not obvious from the stacktrace a debugger would have shown this immediately. Way faster then creating a post with hundreds of lines of irrelevant code

A: You used the variable t1 to start the thread that should be assigned to this variable. How ever the function init() that creates the instance of the thread that is assigned to this variable is never called. There for t1 is null and calling any function on a null object causes the NullPointerException.
Simply call the init() function. I think the original idea was to call it within the constructor and you simply forgot to insert it.
For future question please consider only posting the lines close to the point where the StackTrace reports the error. To find that spots of interest look into the StackTrace and look for entries in classes you wrote. In this case NextPage.actionPerformed(NextPage.java:235) is a point of interest. In your question best mark those spots to get a good resolution quickly.


text:
Q: Cross-Origin Request Blocked erroring out after adding application/json I'm trying to send some data to Node using React. Here's my React code:
sendMail(e) {
    e.preventDefault();
    // fetch('/https://uczsieapp-mailer.herokuapp.com/', {
    var name = document.getElementById('name').value;
    var contactReason = document.getElementById('contactReason').value;
    var email = document.getElementById('email').value;
    var additionalInfo = document.getElementById('additionalInfo').value;
    var body = {
        name: name,
        contactReason: contactReason,
        email: email,
        additionalInfo: additionalInfo,
    };
    body = JSON.stringify(body);
    console.log(body);
    fetch('http://localhost:4000/', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        content: body,
    }).then(r => console.log(r)).catch(e => console.log(e));
}

Here's my Node code:
var cors = require('cors');
var app = express();
app.use(cors());
var a = '=';
router.post('/', (req, res, next) => {
        console.log('mailing');
        console.log(a);
        a += '=';
        var nodemailer = require('nodemailer');

        var transporter = nodemailer.createTransport({
            host: "smtp.gmail.com", // hostname
            auth: {
                user: 'someuser@gmail.com',
                pass: 'testgmail'
            }
        });
        console.log(req.body.content);
        let mailOptions = {
            from: `${req.body.name} ${req.body.email}`, // sender address
            to: 'alexander.ironside@mygeorgian.ca', // list of receivers
            subject: 'Email from UczSieApp contact form', // Subject line
            text: 'Hello world ', // plaintext body
            html: `

Imie: ${req.body.name}

Email: ${req.body.email}

Powod kontaktu: ${req.body.contactReason}

Wiadomosc: ${req.body.additionalInfo}

                    `
        };

        // send mail with defined transport object
        transporter.sendMail(mailOptions, function (error, info) {
            if (error) {
                return console.log(error);
            }

            console.log('Message sent: ' + info.response);
        });
    }
);

So as you can see I'm using the cors module, which is supposed to handle all the cors issues.
But that's not enough. When I get rid of the headers property passed to fetch(), the call is being done, but no data is being sent. When I add the headers, I get the fun

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:4000/. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

error again.
How can I get around it and what am I missing?
I used this answer when writing my code: https://stackoverflow.com/a/42965820/7055769

A: It turns out that CORS only allows some specific content types.
The only allowed values for the Content-Type header are:

*

*application/x-www-form-urlencoded

*multipart/form-data

*text/plain

The origin parameter specifies a URI that may access the resource. The browser must enforce this. For requests without credentials, the server may specify "*" as a wildcard, thereby allowing any origin to access the resource.
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
fetch('http://localhost:4000/', {
    method: 'POST',
    mode: 'cors',
    headers: {
        'Access-Control-Allow-Origin': '*',
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    },
    content: body,
}).then(response => response.json()).then(r => console.log(r)).catch(e => console.log(e));

A: You mind trying this as follow, this should solve the problem :
app.use(function (req, res, next) {
    //set headers to allow cross origin requestt
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

A: Ok there were numerous reasons this didn't work. I'm leaving this answer for the future developers to ease their pain.
This is the method that worked on the client side:
$.ajax({
    type: "POST",
    url: 'http://localhost:4000/',
    data: body,
    success: data=>{console.log(data)},
    dataType: 'json',
});

Here's my whole server side code:
var express = require('express');
var router = express.Router();
var cors = require('cors');
var app = express();

app.use(cors());
app.options('*', cors());

var a = '=';
router.post('/', (req, res, next) => {
        console.log('mailing');
        console.log(a);
        a += '=';
        var nodemailer = require('nodemailer');

        var transporter = nodemailer.createTransport({
            host: "smtp.gmail.com", // hostname
            auth: {
                user: 'sqtableknights@gmail.com',
                pass: 'testgmail'
            }
        });
        console.log(req.body);
        let mailOptions = {
            from: `${req.body.name} ${req.body.email}`, // sender address
            to: 'alexander.ironside@mygeorgian.ca', // list of receivers
            subject: 'Email from UczSieApp contact form', // Subject line
            text: 'Hello world ', // plaintext body
            html: `

Imie: ${req.body.name}

Email: ${req.body.email}

Powod kontaktu: ${req.body.contactReason}

Wiadomosc: ${req.body.additionalInfo}

                        `
        };

        // send mail with defined transport object
        transporter.sendMail(mailOptions, function (error, info) {
            if (error) {
                return console.log(error);
            }

            console.log('Message sent: ' + info.response);
        });
    }
);
module.exports = router;

So in my case I had to add these:
app.use(cors());
app.options('*', cors());

No idea why, but it just breaks without the app.options('*', cors()); parameter. If someone knows a better answer to this, and/or sees any security flaws please leave a comment and let me know. Thank you everybody once more for all the help!


text:
Q: Error while trying to use an API. java.lang.NoSuchFieldError: INSTANCE I am trying to connect to the smartsheet api using a java program.
Initially I had problems with the site certificate which was resolved by adding it to the java keystore. Now when I am trying to run my code, I get the following error.
Exception in thread "main" java.lang.NoSuchFieldError: INSTANCE
    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.<clinit>(SSLConnectionSocketFactory.java:144)
    at org.apache.http.impl.client.HttpClientBuilder.build(HttpClientBuilder.java:955)
    at org.apache.http.impl.client.HttpClients.createDefault(HttpClients.java:58)
    at com.smartsheet.api.internal.http.DefaultHttpClient.<init>(DefaultHttpClient.java:64)
    at com.smartsheet.api.SmartsheetBuilder.build(SmartsheetBuilder.java:203)
    at SmartsheetConnection.main(SmartsheetConnection.java:13)

This is my code (I followed their documentation).
import com.smartsheet.api.*;
import com.smartsheet.api.models.*;
import com.smartsheet.api.models.enums.*;
import com.smartsheet.api.oauth.*;

public class SmartsheetConnection {
    public static void main(String[] args) throws SmartsheetException {
        // Set the access token.
        Token token = new Token();
        token.setAccessToken("foo");
        Smartsheet smartsheet = new SmartsheetBuilder().setAccessToken(token.getAccessToken()).build();
    }
}

The line that is throwing error is (line 144)
@Deprecated
    public static final X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER
        = AllowAllHostnameVerifier.INSTANCE;

but I am not sure what to make of it. I am using maven to get the dependencies. Does it have something to do with the version of the Apache HttpComponents?
Here is the pom.xml
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>com.smartsheet</groupId>
            <artifactId>smartsheet-sdk-java</artifactId>
            <version>2.0.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>jersey-apache-client</artifactId>
            <version>1.9</version>
        </dependency>
    </dependencies>

A: I know its I am replying a bit late actually I am also struggling the same problem and I found the solution by using Maven Shade plugin.
The Problem is the JAR conflict probably your project is using a different Version Of HTTPclient then your container over which your Appliaction is running.

To resolve this use the Below Maven Shade Plugin which will change the package name of HttpClient to the specified one which packaging the JAR. This will also refactor all the usage in your code.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.1</version>
<executions>
    <execution>
        <phase>package</phase>
        <goals>
            <goal>shade</goal>
        </goals>
        <configuration>
            <relocations>
              <relocation>
                <pattern>org.apache.http</pattern>
                <shadedPattern>org.shaded.apache.http</shadedPattern>
              </relocation>
            </relocations>
        </configuration>
    </execution>
</executions>
</plugin>

The Above sample will change HttpClient Package with org.shaded.apache.http from org.apache.http

Maven Shade will also create a fat/uber jar so your final package size get increased and will have all the classes which you have mentioned in the Dependency in POM.
If you don't want to include the all your dependency jar in your final jar then add the Scope for the Dependency as <scope>provided</scope>.

A: Other posts about this error seem to suggest that it's typically caused by conflicting versions of httpcore jar. i.e., an older version of httpcore on the classpath.
For more information, I'd suggest you checkout the following posts:

*

*java.lang.NoSuchFieldError: org.apache.http.message.BasicLineFormatter.INSTANCE from Mashape Unirest in Java application

*java.lang.NoSuchFieldError: INSTANCE

A: the reason for this problem is:
org.apache.http.conn.ssl.AllowAllHostnameVerifier class,which is execused in the runtime,has no field 'INSTANCE'.
My project classpath contains two same name class of "org.apache.http.conn.ssl.AllowAllHostnameVerifier".
One cames from a jar customized by our company,which has no field 'INSTANCE'.
Another cames from maven central repository,which has the field 'INSTANCE'.
My code sometimes run the logic of the latter jar and sometimes the fromer jar,which is the reason I guessed.
my classpath search result
the comparison of the two jar

A: I was using intellij for both android and spring development.
In my case, I accidentally chose Android sdk as the module SDK.
After choosing JDK 1.8 and rebuilding the project fixed the issue for me


text:
Q: Como perguntar ao PDO se a inserção foi feita ou deu erro? Como perguntar ao $Produtos se a inserção foi feita ou se houve algum erro na tentativa de inserção tipo o or die do mysql?
    if(isset($_POST['cadastra_produtos'])){
    ///////////////////////////////////

    $Produtos = $pdo->prepare("INSERT INTO tbl_produtos VALUES
    (NULL, :prod_nome, :prod_categoria, :prod_dimens, :prod_qtde, :prod_valor, :prod_descr, :prod_data)");

    $Produtos->execute(array(
        prod_nome       => strip_tags($_POST['prod_nome']),
        prod_categoria  => strip_tags($_POST['prod_categoria']),
        prod_dimens     => strip_tags($_POST['prod_dimens']),
        prod_qtde       => strip_tags($_POST['prod_valor']),
        prod_valor      => strip_tags($_POST['prod_valor']),
        prod_descr      => strip_tags($_POST['prod_descr']),
        prod_data       => date('Y-m-d H:i:s')
    ));

A: O ideal é se valer do modelo Orientado a Objetos da PDO também para os erros, pegando as PDOException disparadas quando algum erro ocorrer:
try {

    $stmt = $conn -> prepare( /* ... */ );

    try {

        $stmt -> execute();

    } catch( PDOException $e ) {

        // Statement não foi executado
    }

} catch( PDOException $e ) {

    // Statement não preparado

    echo $e -> getMessage();
}

Mas... Tem um pequeno inconveniente. Por padrão a PDO prefere ficar quietinha quanto aos erros, sem reportá-los, mesmo que seus alertas de erro estejam habilitados e em nível suficiente para que erros sejam reportados.
Sendo assim, para que ela grite aos quatro ventos quando qualquer coisa machucar ela, você deve configurar o objeto de conexão, depois de criado:
$dbh = new PDO( /* ... */ );

$dbh -> setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

A: O execute retorna false se a operação falhar. Você também pode pegar informações adicionais sobre o erro com o errorInfo:
$Produtos = $pdo->prepare("INSERT INTO tbl_produtos VALUES
(NULL, :prod_nome, :prod_categoria, :prod_dimens, :prod_qtde, :prod_valor, :prod_descr, :prod_data)");

$ok = $Produtos->execute(array(
    'prod_nome'       => strip_tags($_POST['prod_nome']),
    'prod_categoria'  => strip_tags($_POST['prod_categoria']),
    'prod_dimens'     => strip_tags($_POST['prod_dimens']),
    'prod_qtde'       => strip_tags($_POST['prod_valor']),
    'prod_valor'      => strip_tags($_POST['prod_valor']),
    'prod_descr'      => strip_tags($_POST['prod_descr']),
    'prod_data'       => date('Y-m-d H:i:s')
));

if(!$ok) {
    print_r($Produtos->errorInfo());
}

PS: Use aspas nos nomes das chaves da array (funciona sem por uma particularidade do PHP, mas não é correto)

A: Dá para fazer o seguinte:
if(isset($_POST['cadastra_produtos'])){
    ///////////////////////////////////

    $Produtos = $pdo->prepare("INSERT INTO tbl_produtos VALUES
    (NULL, :prod_nome, :prod_categoria, :prod_dimens, :prod_qtde, :prod_valor, :prod_descr, :prod_data)");

    if($Produtos->execute(array(
        prod_nome       => strip_tags($_POST['prod_nome']),
        prod_categoria  => strip_tags($_POST['prod_categoria']),
        prod_dimens     => strip_tags($_POST['prod_dimens']),
        prod_qtde       => strip_tags($_POST['prod_valor']),
        prod_valor      => strip_tags($_POST['prod_valor']),
        prod_descr      => strip_tags($_POST['prod_descr']),
        prod_data       => date('Y-m-d H:i:s')
    ))){

        if($Produtos->rowCount() > 0){
           echo "inserido com sucesso";
        }else{
           echo "ocorreu um erro!";
        }

    }else{
        echo "ocorreu um erro!";
    }

A: Só usar isso após o execute():
$stmt->execute();

$foo_arr = $stmt->errorInfo();

print_r($foo_arr);


text:
Q: Selenium using IE11, getting Unable to find element with id == lst-ib , server did not provide any stacktrace information   System.setProperty("webdriver.ie.driver", "d://IEDriverServer.exe");
  WebDriver driver = new InternetExplorerDriver();
  driver.get("http://www.google.com");

  WebElement textbox;
  WebElement buton;
  textbox = driver.findElement(By.id("lst-ib"));
  textbox.sendKeys("Mindtree");
  buton = driver.findElement(By.id("sblsbb"));
  buton.click();

Unable to find element with id == lst-ib (WARNING: The server did not provide any stacktrace information)
this is working fine with firefox.


text:
Q: Object spawn timing causing scrolling background freeze I am attempting to spawn an object every 10 seconds, which enters from left of screen and terminates when it reaches right of screen, or on intersection with my other rectangle.
I have been able to spawn the object every 3 seconds or more, but if I try to spawn the object any less frequently, my scrolling background freezes for an amount of time (measurable to the object spawn time I have set). Note that other parts of my game remain unaffected (e.g. my object animation still works fine).
I am guessing the timing schedule of my spawning object is interfering with the timing schedule of my scrolling background, but I can't figure out exactly how this is happening.
My spawning object time schedule is set using this approach (note that spawnObject is the name of the method that creates the object rectangle, which is part of an array):
private long lastObjectTime;

lastObjectTime = TimeUtils.millis();
if(TimeUtils.millis() - lastObjectTime > 3000) spawnObject();

My scrolling background time schedule is set using this approach:
private float currentBgX;
private float currentBgX1;
private long lastTimeBg;

// background separator for 800x480 background .ong
currentBgX = 800;
currentBgX1 = 800;

// set background to current time
lastTimeBg = TimeUtils.nanoTime();

// move the separator every 100000 nanoseconds
if(TimeUtils.nanoTime() - lastTimeBg > 1000000)
{
// move the separator 1px; 4px
currentBgX -= 1;
currentBgX1 -= 4;
lastTimeBg = TimeUtils.nanoTime();
}

// if the separator reaches the edge, move it back to the start
if(currentBgX == 0)
  currentBgX = 800;
if(currentBgX1 == 0)
  currentBgX1 = 800;

Note that I have tried using an alternate timing schedule for my spawning object to avoid interference with my scrolling background time schedule. I tried this:
float timer = 0f;

if (timer >= 3f)
{
spawnObject();
timer = 0f;
}

The spawning object timing schedule directly above had exactly the same effect as the first timing schedule (based on TimeUtils.millis(); )
Does anyone know how I can make the objects spawn less frequently (i.e. more than 3 seconds apart) without having my scrolling background freeze?

A: What is the point of this if statement?
// set background to current time
lastTimeBg = TimeUtils.nanoTime();

// move the separator every 100000 nanoseconds
if(TimeUtils.nanoTime() - lastTimeBg > 1000000)
{

Do you really want to see if it took 100000 nanoseconds to get from the the line before the if to the if itself?
Oh and try just using com.badlogic.gdx.utils.Timer.

A: I think the problem is here:
lastObjectTime = TimeUtils.millis();
if(TimeUtils.millis() - lastObjectTime > 3000) spawnObject();

You are setting lastObject to the current time, then immediately afterwards you are getting the difference (which will be very very small) and seeing if it's greater than 3 seconds (probably won't be).
Regardless, I would suggest creating a Spawner class which simply updates every time through the loop with a deltaTime. It will manage its own spawn timers accordingly there and act appropriately. Create another class for your background and it will do the same. Both of these will be contained in a "world" class which will also update based on a deltaTime. This way everything is separate and you shouldn't have to worry about these kinds of problems. Let me know if you need more clarification.


text:
Q: delete item in dictionary one level down {"python":[
  {"name":"achname","points":9999, "description":"The best achievement ever"}
]}

I want to delete the achievement achname from the list - but I don't know the category name(python). The achievement will always be one level down, but maybe in a different category other that python. How can I do this?

A: What about using del, and the .keys() method?  I don't know how your dictionary is going to be structured, but assuming that "name" will always refer to the achievement you want to delete:
for key in foo.keys():
    if "name" in foo[key]:
        del foo[key]["name"]

Unfortunately, you will need to iterate over every top-level element in the dictionary, to search through all the sub dictionaries.


text:
Q: What's the difference between downcasting and creating child object in java? I write this one:
parent obj1=new Child();
Child obj2 =(Child)obj1; //downcasting

like this one:
Child obj2 = new Child(); //creating child object

A: There difference is that in one case you have two references to one object.  In the other, you have two references pointing to two different objects.  Consider how it works with the following:
parent.kill();
if (child.isDead()) {
  System.out.println("He's dead");
} else {
  System.out.println("He lives!");
}

If the references point to the same object then we will print out "He's dead".  If they are pointing to two different objects then we will print out "He lives!".


text:
Q: appearance and plugin not available in wordpress admin panel I have created online store in word press. I logged in to admin panel with my admin login and i have verified that login is having admin rights also. Now,I want to change banner image and some font color but I can't see plugin and appearance tab in sidebar.please help. screenshot of the admin panel
User admin

A: An issue that some users have mentioned is that when they have entered their WordPress admin panel that they have been unable to locate their plugins menu from within the dashboard. This should appear about half way down the menu on the left of the screen below appearance and should have an icon that looks a little like a domestic plug. However for multisite users you may have to login as network admin to view this tab.
If however this tab is still missing you may wish to try the following:

*

*See if the following exists:
http://www.example.com/wp-admin/plugins.php (where you should
replace example.com with the name of your site. If this does not
exist then it is missing from your theme and needs to be replaced or
you should swap your theme.

*Also check in your FTP for a folder called wp-plugins where your plugins should reside, if this does not exist then you should create
it.

*If you do have a wp-plugins folder deactivate it by changing its name and then check your WordPress admin panel as your problem could
be caused by a faulty plugin.

A:
Are you sure that you are the admin and you have all rights to access?

Try checking with default admin login while you installed the wordpress, it seems you don't have complete permissions.
In your attached screenshot notification showing "Wordpress update available. Please notify administrator" clearly showing that you are not having the complete admin rights


text:
Q: How to give an empty array to function in bash? I am learning bash.
Now I would like to give an empty array to a function. However, it does not work. Please refer to following,
function display_empty_array_func() {
  local -a aug1=$1
  local -a aug2=${2:-no input}
  echo "array aug1 = ${aug1[@]}"
  echo "array aug2 = ${aug2[@]}"
}

declare -a empty_array=()

display_empty_array_func "${empty_array[@]}" "1"

The outputs are following,
array aug1 = 1  # I expected it is empty
array aug2 = no input  # I expected it is 1

In my understanding, quoting variable allow us to give an empty variable,
like following,
function display_empty_variable_func() {
  local aug1=$1
  local aug2=${2:-no input}
  echo "variable aug1 = ${aug1}"
  echo "variable aug2 = ${aug2}"
}

display_empty_variable_func "" "1"

And its outputs are following
variable aug1 =    # it is empty as expected
variable aug2 = 1  # it is 1 as expected

I don't know what is the problem with passing am empty array.
Someone who knows mechanism or solutions. Please let me know it.
Thank you very much.

A: enter image description hereIf positional parameter is empty,  shell script & shell function will not consider that value and instead it took the next non empty value as its value(positional parameter value).
    If we want to take the empty value, must we have to put that value in quotes.
Ex: I'm having small script like
cat test_1.sh
#!/bin/bash

echo "First Parameter is :"$1;

echo "Second Parameter is :"$2;

case -1
If i executed this script as
sh test_1.sh

First Parameter is :

Second Parameter is :

Above two lines are empty because i have not given positional parameter values to script.

case-2
If i executed this script as
sh test_1.sh 1 2

First Parameter is :1

Second Parameter is :2

case-2
If i executed this script as
sh test_1.sh  2 **# here i given two spaces in between .sh and 2 and i thought 1st param is space and second param is 2 but**

First Parameter is :2

Second Parameter is :

The output looks like above. My first statement will apply here.

case-4
If i executed this script as
sh test_1.sh " " 2

First Parameter is :

Second Parameter is :2

Here i kept space in quotes. Now i'm able to access the space value.

**This will be help full for you. But for your requirement please use below code.**

In this you have **quote** the space value(""${empty_array[@]}"") which is coming from **an empty array**("${empty_array[@]}"). So you have to use additional quote to an empty array.

function display_empty_array_func() {
  local -a aug1=$1
  local -a aug2=${2:-no input}
  echo "array aug1 = ${aug1[@]}"
  echo "array aug2 = ${aug2[@]}"
}

declare -a empty_array=()

display_empty_array_func ""${empty_array[@]}"" "1"

The output is:
array aug1 =
array aug2 = 1


text: Q: Azure application gateway back-end pool load-balancer We have configured application gateway with a backend pool which has multiple targets. We see that by default does load balancing. Is backend pools are load balanced by default with round robin? Is there any way we can configure it for weighted load balancing?


text:
Q: Unable to generate access token for Powerbi My ask is to generate a token for Power Bi so to achieve it I created an application for organization by selecting Embedded for your organization
So, to integrate with Azure AD created the application in Azure AD.
The endpoint I used is    POST: https://login.microsoftonline.com/common/oauth2/token
and in the body tab, I gave the below inputs:
data: {
    grant_type: password
    scope:
    resource:
    client_id:
    username:
    password:
    }

My requirement is to generate token with ROPC authentication flow only.
This is the page I am referring to Solved: Re: How to generate the authorization code and the... - Microsoft Power BI Community
But after hitting send got this error:
{
"error": "invalid_request",
"error_description": "AADSTS900144: The request body must contain the following parameter: 'grant_type'.\r\nTrace ID: \r\nCorrelation ID: \r\nTimestamp: 2022-09-25 13:40:05Z",
]

Not sure what am I missing in configuring the application or postman. Any suggestions?

A: I tried to reproduce the same in my environment and got the same error as below:
POST: https://login.microsoftonline.com/common/oauth2/token
data: {
    grant_type: password
    scope: openid
    resource: https://analysis.windows.net/powerbi/api
    client_id: ******
    username: ******
    password: ******
    }

If your application is not public, then add client_secret parameter like below:
To resolve the error, add the parameters in Body tab -> x-www-form-urlencoded
I am able to generate the access token successfully like below:


text:
Q: How to programmatically enable and disable a button using javascript I want a button to be disabled initially. Once a condition is met, I want to enable the button. I tried the below and the button is not getting enabled.
<button class="search btn right-align search-button disabled" id="view-btn">
Hello
</button>

$('#submit_query').click(function(){
document.getElementById("myBtn").disabled = false;

}

A: If you use jQuery is simpler:

$('#submit_query').click(function(){
$("#myBtn").attr("disabled","false");

});

<button class="search btn right-align search-button disabled" id="myBtn">
Hello
</button>

<button id="submit_query">Submit</button>

A: Make sure your #ids match your HTML button controls and that you are bringing in jQuery.
Then to enable an element you want to do this:
$('#enable').click(function(){
  $("#view-btn").removeAttr("disabled");
});

and to disable:
$('#disable').click(function(){
  $("#view-btn").attr("disabled","true");
});

For working example:
http://jsbin.com/xigeyixoji/edit?html,output

A: Try this:

function myFunction() {
    document.getElementById("myBtn").disabled = false;
}

<button id="myBtn" disabled>My Button</button>

Click the button below to disable the button above.

<button onclick="myFunction()" >Try it</button>

A: In the code provided the id for the button element is "view-btn" however the JavaScript code is using getElementById using "myBtn".
Also, the button is assigned the 'disabled' class which may or may not actually disable the button. "disabled" is a separate attribute from class.
Additionally, the JavaScript is using jQuery to assign the click handler. The standard way to use jQuery to enable a control is:
$("#view-btn").prop("disabled", false );

A: <button class="search btn right-align search-button" disabled id="view_btn">
Hello
</button>

<button class="search btn right-align search-button"  id="submit_query">
click me
</button>

var myHTML = document.querySelector('#submit_query');
myHTML.onclick = function() {
console.log(1);
  document.getElementById("view_btn").disabled = false;
};

relevant link : http://jsfiddle.net/765ogwf1/11/


text:
Q: Converting an imperative algorithm into functional style I wrote a simple procedure to calculate the average of the test coverage of some specific packages in a Java project. The raw data in a huge html file is like this:
<body>
package pkg1 <line_coverage>11/111,<branch_coverage>44/444<end>
package pkg2 <line_coverage>22/222,<branch_coverage>55/555<end>
package pkg3 <line_coverage>33/333,<branch_coverage>66/666<end>
...
</body>

Given the specified packages "pkg1" and "pkg3", for example, the average line coverage is:
(11+33)/(111+333)
and average branch coverage is:
(44+66)/(444+666)
I wrote the follow procedure to get the result and it works well. But how to implement this calculation in a functional style? Something like "(x,y) for x in ... for b in ... if...". I know a little Erlang, Haskell and Clojure, So solutions in these languages are also appreciated. Thanks a lot!
from __future__ import division
import re
datafile = ('abc', 'd>11/23d>34/89d', 'e>25/65e>13/25e', 'f>36/92f>19/76')
core_pkgs = ('d', 'f')
covered_lines, total_lines, covered_branches, total_branches = 0, 0, 0, 0
for line in datafile:
    for pkg in core_pkgs:
        ptn = re.compile('.*'+pkg+'.*'+'>(\d+)/(\d+).*>(\d+)/(\d+).*')
        match = ptn.match(line)
        if match is not None:
            cvln, tlln, cvbh, tlbh = match.groups()
            covered_lines += int(cvln)
            total_lines += int(tlln)
            covered_branches += int(cvbh)
            total_branches += int(tlbh)
print 'Line coverage:', '{:.2%}'.format(covered_lines / total_lines)
print 'Branch coverage:', '{:.2%}'.format(covered_branches/total_branches)

A: Down below you can find my Haskell solution. I will try to explain the important points I went through as I wrote it.

*

*First you will find that I created a data structure for coverage data. It's generally a good idea to create data structures to represent whatever data you want to handle. This is in part because it makes it easier to design your code when you can think in terms of whatever you are designing – closely related to functional programming philosophies, and in part because it can eliminate a few bugs where you think you are doing something but are in actuality doing something else.

*Related to the point before: The first thing I do is to convert the string-represented data into my own data structure. When you are doing functional programming, you are often doing things in "sweeps." You don't have a single function that converts data to your format, filters out the unwanted data and summarises the result. You have three different functions for each of those tasks, and you do them one at a time!
This is because functions are very composable, i.e. if you have three different ones, you can stick them together to form a single one if you want to. If you start with a single one, it is very difficult to take it apart to form three different ones.
The actual workings of the conversion function is actually quite uninteresting unless you are specifically doing Haskell. All it does is try to match each string with a regex, and if it succeeds, it adds the coverage data to the resulting list.

*Again, mad composition is about to happen. I don't create a function to loop over a list of coverages and sum them up. I create a single function to sum two coverages, because I know I can use it together with the specialised fold loop (which is sort of like a for loop on steroids) to summarise all coverages in a list. There's no need for me to reinvent the wheel and create a loop myself.
Besides, my sumCoverages function works with a lot of specialised loops, so I don't have to write a ton of functions, I just stick my single function into a ton of pre-made library functions!

*In the main function you will see what I mean by programming in "sweeps" or "passes" over the data. First I convert it to the internal format, then I filter out the unwanted data, then I summarise the remaining data. These are completely independent computations. That's functional programming.
You will also notice that I use two specialised loops there, filter and fold. This means that I don't have to write any loops myself, I just stick in a function to those standard library loops and let those take it from there.

import Data.Maybe (catMaybes)
import Data.List (foldl')
import Text.Printf (printf)
import Text.Regex (matchRegex, mkRegex)

corePkgs = ["d", "f"]

stats = [
  "d>11/23d>34/89d",
  "e>25/65e>13/25e",
  "f>36/92f>19/76"
  ]

format = mkRegex ".*(\\w+).*>([0-9]+)/([0-9]+).*>([0-9]+)/([0-9]+).*"

-- It might be a good idea to define a datatype for coverage data.
-- A bit of coverage data is defined as the name of the package it
-- came from, the lines covered, the total amount of lines, the
-- branches covered and the total amount of branches.
data Coverage = Coverage String Int Int Int Int

-- Then we need a way to convert the string data into a list of
-- coverage data. We do this by regex. We try to match on each
-- string in the list, and then we choose to keep only the successful
-- matches. Returned is a list of coverage data that was represented
-- by the strings.
convert :: [String] -> [Coverage]
convert = catMaybes . map match
  where match line = do
          [name, cl, tl, cb, tb] <- matchRegex format line
          return $ Coverage name (read cl) (read tl) (read cb) (read tb)

-- We need a way to summarise two coverage data bits. This can of course also
-- be used to summarise entire lists of coverage data, by folding over it.
sumCoverage (Coverage nameA clA tlA cbA tbA) (Coverage nameB clB tlB cbB tbB) =
  Coverage (nameA ++ nameB ++ ",") (clA + clB) (tlA + tlB) (cbA + cbB) (tbA + tbB)

main = do
      -- First we need to convert the strings to coverage data
  let coverageData = convert stats
      -- Then we want to filter out only the relevant data
      relevantData = filter (\(Coverage name _ _ _ _) -> name `elem` corePkgs) coverageData
      -- Then we need to summarise it, but we are only interested in the numbers
      Coverage _ cl tl cb tb = foldl' sumCoverage (Coverage "" 0 0 0 0) relevantData

  -- So we can finally print them!
  printf "Line coverage: %.2f\n" (fromIntegral cl / fromIntegral tl :: Double)
  printf "Branch coverage: %.2f\n" (fromIntegral cb / fromIntegral tb :: Double)

A: Here are some quickly-hacked, untested ideas applied to your code:
import numpy as np
import re

datafile = ('abc', 'd>11/23d>34/89d', 'e>25/65e>13/25e', 'f>36/92f>19/76')
core_pkgs = ('d', 'f')
covered_lines, total_lines, covered_branches, total_branches = 0, 0, 0, 0

for pkg in core_pkgs:
    ptn = re.compile('.*'+pkg+'.*'+'>(\d+)/(\d+).*>(\d+)/(\d+).*')
    matches = map(datafile, ptn.match)
    statsList = [map(int, match.groups()) for match in matches if matches]
    # statsList is a list of [cvln, tlln, cvbh, tlbh]
    stats = np.array(statsList)
    covered_lines, total_lines, covered_branches, total_branches = stats.sum(axis=1)

Well, as you can see I haven't bothered to finish off the remaining loop, but I think the point is made by now.  There's certainly a lot more than one way to do this; I elected to show off map() (which some will say makes this less efficient, and it probably does), as well as NumPy to get the (admittedly light) math done.

A: This is the corresponding Clojure solution:
(defn extract-data
  "extract 4 integer from a string line according to a package name"
  [pkg line]
  (map read-string
       (rest (first
              (re-seq
               (re-pattern
                (str pkg ".*>(\\d+)/(\\d+).*>(\\d+)/(\\d+)"))
               line)))))

(defn scan-lines-by-pkg
  "scan all string lines and extract all data as integer sequences
    according to package names"
  [pkgs lines]
  (filter seq (for [pkg pkgs
                    line lines]
                (extract-data pkg line))))

(defn sum-data
  "add all data in valid lines together"
  [pkgs lines]
  (apply map + (scan-lines-by-pkg pkgs lines)))

(defn get-percent
  [covered all]
  (str (format "%.2f" (float (/ (* covered 100) all))) "%"))

(defn get-cov
  [pkgs lines]
  {:line-cov (apply get-percent (take 2 (sum-data pkgs lines)))
    :branch-cov (apply get-percent (drop 2 (sum-data pkgs lines)))})

(get-cov ["d" "f"] ["abc" "d>11/23d>34/89d" "e>25/65e>13/25e" "f>36/92f>19/76"])


text:
Q: How to grouping Label In Char JS Hello i have problem using Chart JS. I want show grouping label in my chart i see another promblem in other question, but now i am not understand how to implment to my project. Exampe : in my chart show data
7:00, 7:01, 7:02, 7:03, 7:04 but i just want 7:00, 8:00, if you not undertans see my image

i want like this

my JS
function tampilChart(data,labels){
    var ctx = document.getElementById('myChart').getContext('2d');
    var myChart = new Chart(ctx,{
      type:'line',
      data:{
        labels:labels,
        datasets : [{
          label:'Harga',
          backgroundColor:'rgba(54, 162, 235, 0.2)',
          borderColor:'rgba(54, 162, 235, 1)',
          data:data
        }],
      },
      options:{
        scales:{
          yAxes:[{
            ticks:{
              beginAtZero:true
            }
          }]
        }
      },
    });
}
isiChart();
function isiChart(){
      $.ajax({
        url:"http://localhost/topsis/admin/Menu/tampilChart",
        type:'post',
        dataType:'json',
        success:function(data){
            var nilai =[];
            var label=[];
            for(var i=0;i<data.length;i++){
                label[i]=data[i].hari;
                nilai[i] = data[i].harga;
            }
            tampilChart(nilai,label);
        }
      });
    }

My JSON
{"harga":17.79708432356102,"hari":"2020-03-23 08:32:45"},{"harga":17.591260378595486,"hari":"2020-03-23 08:38:49"},{"harga":17.61026854797192,"hari":"2020-03-23 08:42:55"},{"harga":17.80475850892087,"hari":"2020-03-23 08:46:09"},{"harga":17.400984669807688,"hari":"2020-03-23 08:53:59"},{"harga":17.46294725519658,"hari":"2020-03-23 08:59:48"},{"harga":17.474364994815666,"hari":"2020-03-23 09:04:57"},{"harga":17.66738555493817,"hari":"2020-03-23 09:09:21"},{"harga":17.16010419143489,"hari":"2020-03-23 09:15:50"},{"harga":17.59928014323995,"hari":"2020-03-23 09:20:37"},{"harga":17.286875855560602,"hari":"2020-03-23 09:29:02"},{"harga":17.146187228413567,"hari":"2020-03-23 09:35:12"},{"harga":17.38490758256079,"hari":"2020-03-23 09:39:03"},{"harga":17.15664324821635,"hari":"2020-03-23 09:44:28"},{"harga":17.192637780118307,"hari":"2020-03-23 09:49:15"},{"harga":17.62267025376745,"hari":"2020-03-23 09:54:10"},{"harga":17.723818283548656,"hari":"2020-03-23 09:59:53"},{"harga":17.71860964564134,"hari":"2020-03-23 10:04:00"},{"harga":17.73204012352615,"hari":"2020-03-23 10:09:24"},{"harga":17.768559437846704,"hari":"2020-03-23 10:11:15"},{"harga":17.993312941638735,"hari":"2020-03-23 10:20:26"},{"harga":18.103742695096674,"hari":"2020-03-23 10:25:02"},{"harga":18.1144523202333,"hari":"2020-03-23 10:28:55"},{"harga":18.104201546453393,"hari":"2020-03-23 10:32:38"},

A: Use the time axis:
options: {
  scales: {
    xAxes: [{
      type: "time",
      time: {
        unit: "hour",
        displayFormats: {
          hour: "HH:mm"
        }
      }
    }]
    ...

Be sure to use the 'bundled build' of Chart.js, or include moment.js before Chart.js.


text:
Q: Wordpress: Loading custom.js in a childtheme with multiple dependencies i have a website that is running the Master Slider Pro wordpress plugin and the iLightBox plugin. I am running a custom script in a custom.js file in wordpress child theme:
/* Link JavaScript file */
function custom_scripts() {
    wp_register_script( 'custom-script', get_stylesheet_directory_uri() . '/assets/js/custom.js', array('jquery') , false, true );
    wp_enqueue_script( 'custom-script' );
}

I am calling the custom file as per the below in my functions.php file:
jQuery(document).ready(function(){

    (function(){
      var groupsArr = [];
      jQuery('[rel^="ilightbox["]').each(function () {
        var group = this.getAttribute("rel");
        jQuery.inArray(group, groupsArr) === -1 && groupsArr.push(group);
      });
      jQuery.each(groupsArr, function (i, groupName) {
        jQuery('[rel="' + groupName + '"]').iLightBox({ /* options */ });
      });
    })();

  });

The issue i am having is that sometimes it loads the custom script (i assume in the correct order) and my slider loads and the lightbox displays when i click the image... other times the slider gets stuck in a loading state and shows the errors:
Uncaught TypeError: jQuery(...).iLightBox is not a function

I believe i am loading the custom.js file after the jQuery file has loaded... what i am assuming is, that the lighbox plugin is sometimes loading after the jQuery and therefore loading after custom.js file which is why it cannot find the ilightbox function ?
Anyway i can prevent this ?

I have been doing some reading and spoke to my theme author (who has integrated the ilightbox function).
My code now looks like the below:
/* register script that defines ilightbox (in parent theme) */
wp_register_script( 'ilightbox_script', get_stylesheet_directory . '/includes/class-avada-scripts.php' );

/* Link JavaScript file */
function custom_scripts() {
    wp_register_script( 'custom-script', get_stylesheet_directory_uri() . '/assets/js/custom.js', array('jquery', 'ilightbox_script') , false, true );
    wp_enqueue_script( 'custom-script' );
}

add_action( 'wp_enqueue_scripts', 'custom_scripts', 99 );

I believe i have now registered the script that contains the ilightbox function (stored in my parent theme). I then called the custom.js file after jQuery and the registered script has loaded. However it still is not working. I also get the following error from the file i am now trying to register:
Uncaught SyntaxError: Unexpected token <

Maybe i have misunderstood everything, so i have copied what the theme author has said to me when i asked which fine defines the ilightbox function.. what do you think?

These scripts are enqueued in class-avada-scripts.php available in
  following directory
/wp-content/themes/avada/includes
and all JS code is in main.min.js available in following directory
/wp-content/themes/avada/assets/js
However if you enable developer mode from
Wp admin -> appearance -> theme options -> advanced
then you can modify code in avada-lightbox.js and lightbox.js
  available in same directory.

UPDATE (22/11/2015):
Latest update has me using:
/* Ensure jquery loads before iLightBox */
add_action( 'wp_enqueue_scripts', 'add_my_script' );

function add_my_script() {
                wp_register_script( 'ilightbox_script', get_theme_root_uri() . '/Avada/includes/class-avada-scripts.php', array( 'jquery' ) );
                wp_register_script( 'custom-script', get_stylesheet_directory_uri() . '/assets/js/custom.js' );

                wp_enqueue_script('ilightbox_script');
                wp_enqueue_script('custom-script');
}

Still same error :(


text:
Q: How can I create a self-consistent .jar file with Eclipse? I wrote my Java application in Eclipse. Now I would like to generate a .jar file which can be run on other systems from the command line. Is there a easy way to do it in Eclipse?
In particular I am wondering what should I do with the jar files of external library that I use (should it be included into my .jar file?).
Moreover, should I generate some manifest files?
ADDED:
I see the window in which I can choose "Extract required libraries into generated JAR" or "Package required libraries into generated JAR" and so on. I select the first option, I specify export destination but "Next" button is not activated yet. What else should I specify. I am offered to launch a configuration but i do not want to. Every configuration is associated with a fixed set of parameters given in the command line and I do not want that.

A: When you go to Export => Java => Runnable JAR file,
You said "Next" button is not activated yet, You don't have to press the next button because you can just press finish, If you don't want the Lauch Configuration, You can manually edit the manifest file later. If you have external libraries you can chose one of the options they give you, extract/package/copy required libraries into jar file

A: Select you project, then Export => Java => Runnable JAR file
You can then choose to extract/package/copy required libraries into your JAR and also select the class, whose main() method should be executed on startup.
Then you can execute the generated jar via:
java -jar yourjar.jar


text:
Q: C# DataGridView doesn't show data on other form I have two Windows Forms (Form1 and Form2). Form1 has a button (openfrm2) and a datagridview (dataGridView1). Form2 has a textbox (sql_textbox) and a button (button1).
Clicking on openfrm2 opens Form2, then I'm writing an SQL query in sql_textbox to view a table in a Postgres database and clicking on button1 should show the result of the query in dataGridView1. But it doesn't.
Here is my code:
Form1:
public BindingSource bindingSource1 = new BindingSource();

private void openfrm2_Click(object sender, EventArgs e)
{
    Form2 frm2 = new Form2();
    frm2.Show();
}

Form2:
private void button1_Click(object sender, EventArgs e)
{
    Form1 frm1 = new Form1();
    frm1.bindingSource1.DataSource = query();
    frm1.dataGridView1.DataSource  = frm1.bindingSource1;
}

DataTable query()
{
    NpgsqlConnectionStringBuilder cnsb = new NpgsqlConnectionStringBuilder();
    cnsb.Database = "postgres";
    cnsb.Username = "postgres";
    cnsb.Password = "root";
    cnsb.Host     = "localhost";
    DataTable dt  = new DataTable();

    using (NpgsqlConnection cnn = new NpgsqlConnection(cnsb.ConnectionString))
    {
        cnn.Open();

        using (NpgsqlCommand cmd = new NpgsqlCommand(sql_textbox.Text, cnn))
        {
            NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql_textbox.Text, cnn);
            da.Fill(dt);
        }
    }
    return dt;
}

I tried the solutions written at similar questions, but nothing works. If I add a datagridview to Form2, and add this
dataGridView2.DataSource = frm1.bindingSource1;
line to button1_Click it shows the data, but I need to display it on Form1.
How can I do it?


text:
Q: Can't get GRUB to work after adding PopOS to system with OpenSUSE I was running OpenSUSE as a single boot on my laptop. For some work reasons I installed PopOS 22.04 and it booted straight to it. So I tried to setup GRUB for more comfort (as expected, I can manually choose which system to boot at start up with F12).
But no matter what I try it is not working. First it would go into grub rescue and say it doesnt recognize any filesystems. After trying some fixes it now just goes into grub command line when booting grub. What am I doing wrong? I also dont know what information you guys need to help me out, so please let me know what info you need and which steps I should consider approaaching first. Thank you for your time and help in advance.
sudo update-grub gives:
Sourcing file `/etc/default/grub'
Sourcing file `/etc/default/grub.d/init-select.cfg'
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-5.18.10-76051810-generic
Found initrd image: /boot/initrd.img-5.18.10-76051810-generic
Warning: os-prober will be executed to detect other bootable partitions.
Its output will be used to detect bootable binaries on them and create new boot entries.
Found openSUSE Leap 15.3 on /dev/sdb2
Found Windows Boot Manager on /dev/sdc4@/efi/Microsoft/Boot/bootmgfw.efi
Adding boot menu entry for UEFI Firmware Settings ...
done


text:
Q: Debugging Cordova iOS plugin with NSLog, where does it output? I followed the tutorial at the Cordova official website to create my first "hello world" program for iOS, and everything went successfully, and I'm able to run the example application in the simulator just fine. What I need is to test, use and if necessary fix an iOS plugin. I installed the plugin and it seems to have installed and works fine.
My problem is simple: I'm trying to output some debugging information from the Objective-C code of the plugin using NSLog(), but I have no idea where that output can be seen.
I am definitely editing the correct .m file (inside the platforms/ios/HelloWorld/Plugins/plugin-name directory), as eg. syntax errors show up and stop the "cordova emulate ios" command from completing successfully. So I'm certain that my NSLog() additions are being compiled in. I'm also certain that the functions in question are being called from the javascript. I just don't know where those messages are being outputted to.
In the simulator I try to select Debug > Open System Log... but nothing of what I'm printing appears there.
When I run "cordova emulate ios", it says "[ios-sim] logPath: /path/to/the/project/platforms/ios/cordova/console.log". However, there is no such file in that directory. (In fact, there is no file named "console.log" anywhere inside the project directory tree.)

A: NSLog logs to the simulated device's logarchive.  You must select the simulator device in Console to see that, or you can use the CLI:
xcrun simctl spawn booted log show
xcrun simctl spawn booted log stream
etc...

Check the log command's help and man pages for filtering options.