text:
Q: Creating objects from dynamic JPanels I have written some code to create JPanels dynamically.   I now need a way to capture the data that the user creates in these JPanels.  I currently have a "create" button.  When fired, I want this button to create an object using the 3 different data types in each panel: name(String), count(int), and a boolean.
I am pretty raw at programming, but the major hurdle I am facing is how to I access dynamic objects that are not named like these panels?  I figured out how to add and remove them, but I can't figure out the methods to capture data from the fields in the panes.
Thanks, the code is as follows:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;

public class MainSnakeGUI {

    public static void main(String[] arg) {
        new MainSnakeGUI();
    }

    public MainSnakeGUI() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                //Create the frame
                JFrame frame = new JFrame("Snake Channels");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new SnakePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class SnakePane extends JPanel {
        public SnakePane() {
            //Create buttons and labels
            JButton btnAdd = new JButton("Add New Snake");
            JButton btnRemove = new JButton("Delete Snake");
            JLabel headerLabel = new JLabel("Create a Split Snake");
            JButton btnCreate = new JButton("Create");
            setLayout(new BorderLayout());
            //Create JPanels
            JPanel buttons = new JPanel(new FlowLayout(FlowLayout.LEFT));
            JPanel header = new JPanel(new FlowLayout(FlowLayout.CENTER));
            JPanel footer = new JPanel(new FlowLayout(FlowLayout.CENTER));
            //add items to JPanels
            buttons.add(btnAdd);
            buttons.add(btnRemove);
            header.add(headerLabel);
            footer.add(btnCreate);
            //add JPanels to window
            add(header, BorderLayout.NORTH);  //sets header at the top of window
            header.setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(10, 10, 10, 10)));
            add(buttons, BorderLayout.BEFORE_LINE_BEGINS);  //sets the button to the left of the display pane
            buttons.setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(10, 10, 10, 10)));
            add(footer, BorderLayout.AFTER_LAST_LINE);  //sets buttons on the bottom of window
            footer.setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(10, 10, 10, 10)));

            //add panel to hold new frames
            final JPanel content = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.weighty = 1;
            content.add(new JPanel(), gbc);

            //add scroll pane?
            add(new JScrollPane(content));

            //add listener for button
            btnAdd.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    SplitSnakeCreationPane pane = new SplitSnakeCreationPane();  //create a new SnakeCreationPane
                    int insertAt = Math.max(0, content.getComponentCount() - 1);  //insert it at the end of the list
                    GridBagConstraints gbc = new GridBagConstraints();
                    gbc.gridwidth = GridBagConstraints.REMAINDER;
                    gbc.fill = GridBagConstraints.HORIZONTAL;
                    gbc.weightx = 1;
                    content.add(pane, gbc, insertAt);  //add the pane to the window
                    content.revalidate();
                    content.repaint();
                }
            });

            btnRemove.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    int paneCount = content.getComponentCount()-1;  //get count of the pane
                    content.remove(content.getComponent(paneCount-1));  //remove the pane at paneCount
                    content.revalidate();  //update window with changes
                    content.repaint();
                    SplitSnakeCreationPane.snakeCount--;  //update count for snakes
                }
            });

            btnCreate.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    int paneCount = content.getComponentCount()-1;  //get count of the pane
                    for (int i=0; i<paneCount;){

                    }
                }
            });
        }

        //set size of window
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(1200, 400);
        }
    }

    public static class SplitSnakeCreationPane extends JPanel {
        //Count of how many snakes created
        private static int snakeCount = 1;

        public SplitSnakeCreationPane() {

            //creates Snake Panes
            setLayout(new GridLayout(2, 4, 10, 10));
            add(new JLabel("Split Snake " + (snakeCount++) + "."));
            add(new JLabel("Snake Name"));
            add(new JLabel("Channel Count"));
            add(new JLabel(""));
            add(new JLabel(""));
            JTextField snakeName =  new JTextField(30);
            JTextField channelCount = new JTextField("0",3);
            JCheckBox artistSupplied = new JCheckBox("Artist Supplied?");
            add(snakeName); //Snake Name field
            add(channelCount);  //Channel Count field
            add(artistSupplied); //Artist supplied checkbox
            setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(10, 10, 10, 10)));
        }
    }
}

A: Instead of putting those fields as local variables in the constructor, You need use class variables in your SplitSnakeCreationPane and then add a public get method to get the values from those fields. As long as you have those get method, you can use it to get filed value anywhere you need.
see the modified class as follows:
public static class SplitSnakeCreationPane extends JPanel {
        //Count of how many snakes created
        private static int snakeCount = 1;

        private JTextField snakeName = null;
        private JTextField channelCount = null;
        private JCheckBox artistSupplied = null;

        public SplitSnakeCreationPane() {

            //creates Snake Panes
            setLayout(new GridLayout(2, 4, 10, 10));
            add(new JLabel("Split Snake " + (snakeCount++) + "."));
            add(new JLabel("Snake Name"));
            add(new JLabel("Channel Count"));
            add(new JLabel(""));
            add(new JLabel(""));
            snakeName =  new JTextField(30);
            channelCount = new JTextField("0",3);
            artistSupplied = new JCheckBox("Artist Supplied?");
            add(snakeName); //Snake Name field
            add(channelCount);  //Channel Count field
            add(artistSupplied); //Artist supplied checkbox
            setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(10, 10, 10, 10)));
        }

        public String getSnakeName() {
            return snakeName.getText();
        }

        public String getChannelCount() {
            return channelCount.getText();
        }

        public boolean getArtistSupplied() {
            return artistSupplied.isSelected();
        }
    }

Here is the complete code, copy paste and give it a run: result will be printed on the console. hope You can get the idea on how to get those values
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;

public class MainSnakeGUI {

    public static void main(String[] arg) {
        new MainSnakeGUI();
    }

    public MainSnakeGUI() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                //Create the frame
                JFrame frame = new JFrame("Snake Channels");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new SnakePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class SnakePane extends JPanel {

        public SnakePane() {
            //Create buttons and labels
            JButton btnAdd = new JButton("Add New Snake");
            JButton btnRemove = new JButton("Delete Snake");
            JButton show = new JButton("show value");
            JLabel headerLabel = new JLabel("Create a Split Snake");
            JButton btnCreate = new JButton("Create");
            setLayout(new BorderLayout());
            //Create JPanels
            JPanel buttons = new JPanel(new FlowLayout(FlowLayout.LEFT));
            JPanel header = new JPanel(new FlowLayout(FlowLayout.CENTER));
            JPanel footer = new JPanel(new FlowLayout(FlowLayout.CENTER));
            //add items to JPanels
            buttons.add(btnAdd);
            buttons.add(btnRemove);
            buttons.add(show);
            header.add(headerLabel);
            footer.add(btnCreate);
            //add JPanels to window
            add(header, BorderLayout.NORTH);  //sets header at the top of window
            header.setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(10, 10, 10, 10)));
            add(buttons, BorderLayout.BEFORE_LINE_BEGINS);  //sets the button to the left of the display pane
            buttons.setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(10, 10, 10, 10)));
            add(footer, BorderLayout.AFTER_LAST_LINE);  //sets buttons on the bottom of window
            footer.setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(10, 10, 10, 10)));

            //add panel to hold new frames
            final JPanel content = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.weighty = 1;
            content.add(new JPanel(), gbc);

            //add scroll pane?
            add(new JScrollPane(content));

            //add listener for button
            btnAdd.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    SplitSnakeCreationPane pane = new SplitSnakeCreationPane();  //create a new SnakeCreationPane
                    int insertAt = Math.max(0, content.getComponentCount() - 1);  //insert it at the end of the list
                    GridBagConstraints gbc = new GridBagConstraints();
                    gbc.gridwidth = GridBagConstraints.REMAINDER;
                    gbc.fill = GridBagConstraints.HORIZONTAL;
                    gbc.weightx = 1;
                    content.add(pane, gbc, insertAt);  //add the pane to the window

                    System.out.println(insertAt);
                    content.revalidate();
                    content.repaint();
                }
            });

            btnRemove.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    int paneCount = content.getComponentCount()-1;  //get count of the pane
                    content.remove(content.getComponent(paneCount-1));  //remove the pane at paneCount
                    content.revalidate();  //update window with changes
                    content.repaint();
                    SplitSnakeCreationPane.snakeCount--;  //update count for snakes
                }
            });

            show.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {

                    for(int n=0; n<content.getComponentCount(); n++){

                        if(content.getComponent(n) instanceof SplitSnakeCreationPane){

                            SplitSnakeCreationPane com = (SplitSnakeCreationPane) content.getComponent(n);

                            System.out.println("Sname Name is : " + com.getSnakeName());
                            System.out.println("ChannelCount is : " + com.getChannelCount());
                            System.out.println("ArtistSupplied  is : " + com.getArtistSupplied());
                        }

                    }

                }
            });

            btnCreate.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    int paneCount = content.getComponentCount()-1;  //get count of the pane
                    for (int i=0; i<paneCount;){

                    }
                }
            });
        }

        //set size of window
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(1200, 400);
        }
    }

    public static class SplitSnakeCreationPane extends JPanel {
        //Count of how many snakes created
        private static int snakeCount = 1;

        private JTextField snakeName = null;
        private JTextField channelCount = null;
        private JCheckBox artistSupplied = null;

        public SplitSnakeCreationPane() {

            //creates Snake Panes
            setLayout(new GridLayout(2, 4, 10, 10));
            add(new JLabel("Split Snake " + (snakeCount++) + "."));
            add(new JLabel("Snake Name"));
            add(new JLabel("Channel Count"));
            add(new JLabel(""));
            add(new JLabel(""));
            snakeName =  new JTextField(30);
            channelCount = new JTextField("0",3);
            artistSupplied = new JCheckBox("Artist Supplied?");
            add(snakeName); //Snake Name field
            add(channelCount);  //Channel Count field
            add(artistSupplied); //Artist supplied checkbox
            setBorder(new CompoundBorder(new LineBorder(Color.BLACK), new EmptyBorder(10, 10, 10, 10)));
        }

        public String getSnakeName() {
            return snakeName.getText();
        }

        public String getChannelCount() {
            return channelCount.getText();
        }

        public boolean getArtistSupplied() {
            return artistSupplied.isSelected();
        }
    }
}

A: The best way to do this is to create your own custom action listener:
public class CustomListener extends ActionListener {

    private List<SplitSnakeCreationPane> allPanes = new ArrayList<SplitSnakeCreationPane>();

    @Override
    public void actionPerformed(ActionEvent e) {
    //Create your pane
    //Add that pane to your 'allPanes' list.
    }

    public List<SplitSnakeCreationPane> getAllPanes(){
        return this.allPanes;
    }

}

Now you create an object of this class and add that to the button:
CustomListener createListener = new CustomListener();
btnCreate.addActionListener(createListener);

Now if you wish to retrieve the panes you added, just call:
List<SplitSnakeCreationPane> allPanes = createListener.getAllPanes();


text:
Q: Placing a Image over paragraph I'm trying to place an image over a text body. The idea is that I will use jquery animation to increase the image opacity then you can see the text underneath it. Any help would be appreciated.

A: You really should have posted some code, check out https://stackoverflow.com/help/how-to-ask.
However, this is a simple piece of code that should start you off.
<!doctype html>

<meta charset="utf-8">
<title>Display Demo</title>

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Now visit the jQuery docs related to .show and .animate and update it to be what you want.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Prevent pushing to master on GitHub? GitHub allows you to configure your repository so that users can't force push to master, but is there a way to prevent pushing to master entirely? I'm hoping to make it so that the only way of adding to commits to master is through the GitHub pull request UI.

A: I needed to avoid to accidentally push any commits to master branch.
It is a similar solution like @christian-chandra's but more simple.
go to your local working copy and
$ cd .git/hooks
echo '' > pre-commit
$ chmod +x pre-commit

Add this content to the file (pre-commit)
#!/bin/sh

branch="$(git rev-parse --abbrev-ref HEAD)"

if [ "$branch" = "master" ]; then
  echo "Master Branch commit is blocked"
  exit 1
fi

done!

A: Directly pushing to remote's master is rejected when status checks are enabled, meaning that the only way to add commits on remote's master is merging pull requests (which pass the status checks) on GitHub.
Here is my experiment result for the master branch requiring status checks:

*

*Create a commit on the master branch on my PC.

*Push to remote's master.

*A rejection message appears. The commit is not pushed to remote in the end.

C:\GitRepo\GitHub\TomoyukiAota\photo-location-map [master ↑1]> git push
Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Delta compression using up to 12 threads
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 305 bytes | 305.00 KiB/s, done.
Total 3 (delta 2), reused 0 (delta 0)
remote: Resolving deltas: 100% (2/2), completed with 2 local objects.
remote: error: GH006: Protected branch update failed for refs/heads/master.
remote: error: 3 of 3 required status checks are expected.
To https://github.com/TomoyukiAota/photo-location-map.git
 ! [remote rejected] master -> master (protected branch hook declined)
error: failed to push some refs to 'https://github.com/TomoyukiAota/photo-location-map.git'
C:\GitRepo\GitHub\TomoyukiAota\photo-location-map [master ↑1]>

A: If You are using Node, You can use husky to create a pre-push validation that a direct push to master does not happen. That way, You can still use your administrator privileges to merge PRs. I guess other languages have similar solutions to husky.

*

*npm install husky --save-dev

*In /.huskyrc.js:

const preventPushToMaster = `branch=\`git symbolic-ref HEAD\`
if [ "$branch" = "refs/heads/master" ]; then
    echo "\\033[31mDirect push to master is not allowed.\\033[0m"
    exit 1
fi`;

module.exports = {
  hooks: {
    'pre-push': preventPushToMaster,
  },
};

A: Since the original question / answer, Github has added a new option for this to the restricted branches UI which allows you to set this up.

Require pull request reviews before merging When enabled, all commits must be made to a non-protected branch and submitted via a
pull request with the required number of approving reviews and no
changes requested before it can be merged into a branch that matches
this rule.

To find it go to Settings > Branches > Branch Protection Rules
and click 'Add Rule'.

Then, enter the name of the branch you want to protect and click the checkbox to require pull request reviews before merging.

By default, this only stops people who are not moderators. There is also another checkbox later down for ensuring that even moderators cannot merge.

A: The current accepted answer is actually correct but if you are an organization owner or have admin privileges, which is the case if you created the repo, you can still push to protected branches. From Github documentation at https://help.github.com/en/articles/about-branch-restrictions:

Organization owners and people with admin permissions for a repository are always able to push to a protected branch.

For any other type of collaborator, git push will fail.
If you really want to disable pushing at all, then you have to set that up locally either by configuring an invalid pushRemote for a branch as mentioned before:
git config branch.master.pushRemote no_push
or by creating a pre-push hook as shown here: https://gist.github.com/vlucas/8009a5edadf8d0ff7430

A: If you are using free-plan on private repo in Github, you may not be able to use protected branch feature. So you need to block any push / commit from local.
This is what I did to make it work locally and distributed to all repo's members.
First of all, you need to install husky to control pre-commit and pre-push hook.
Then, I made a pre-push bash script and commit it inside the repository. Then call this script from husky pre-push hook with husky parameter.
This is my husky configuration inside package.json (you can set separated config if you want)
"husky": {
    "hooks": {
        "pre-commit": "./commands/pre-commit",
        "pre-push": "./commands/pre-push $HUSKY_GIT_STDIN"
    }
},

as you can see I have 2 scripts, one for pre-push and one for pre-commit.
And this is my commands/pre-push bash script
#!/bin/bash

echo -e "===\n>> Talenavi Pre-push Hook: Checking branch name / Mengecek nama branch..."

BRANCH=`git rev-parse --abbrev-ref HEAD`
PROTECTED_BRANCHES="^(master|develop)"

if [[ $1 != *"$BRANCH"* ]]
then
  echo -e "\n You must use (git push origin $BRANCH) / Anda harus menggunakan (git push origin $BRANCH).\n" && exit 1
fi

if [[ "$BRANCH" =~ $PROTECTED_BRANCHES ]]
then
  echo -e "\n Cannot push to remote $BRANCH branch, please create your own branch and use PR."
  echo -e " Tidak bisa push ke remote branch $BRANCH, silahkan buat branch kamu sendiri dan gunakan pull request.\n" && exit 1
fi

echo -e ">> Finish checking branch name / Selesai mengecek nama branch.\n==="

exit 0

The script basically will do 2 things:

*

*This script will block anybody who tries to push to a certain branch (in my case I don't want anybody -including myself- to push directly to master and develop branch). They need to work in their own branch and then create a pull request.

*This script will block anybody who tries to push to a branch that is different from their current active branch. For example you are in branch fix/someissue but then you mistakenly type git push origin master.

For more detailed instructions you can follow from this article:
https://github.com/talenavi/husky-precommit-prepush-githooks

A: You can enable branch restrictions and decide who (in terms of users and teams of the organization) are allowed to push.
https://help.github.com/articles/about-branch-restrictions/
«Note: If the "Include administrators" is checked and you've enabled required status checks on the branch and they fail, any attempt to push changes to the base branch will also fail, regardless of a user or team's permission status.»

A:
I'm hoping to make it so that the only way of adding to commits to master is through the GitHub pull request UI.

I have a solution that prevents pushing to the main branch and doesn't require approvals or long status checks to pass in the pull request.
The trick is to create a status check that passes immediately.
Create the following GitHub Action in .github/workflows/requirePullRequest.yml.
name: require pull request

on:
  pull_request:
    branches:
      - master

jobs:
  job:
    name: require pull request
    runs-on: ubuntu-latest
    steps:
      - run: echo hello

Next, update repository settings to require require pull request status check to pass.
If you want administrators to follow the same rule, then you have to check include administrators rule.
This way, GitHub will reject all direct pushes to the main branch and pull requests won't be delayed by anything.


text:
Q: svelte svelte-adapter-firebase function setup I have been messing around with new Svelte SSR adapters since the future of Svelte will not use Sapper.  I am trying to create a firebase function for SSR, but I can't seem to find any clue on how to do this.
This guide tells you how to implement Svelte so that it can use Firebase Functions.  I have no problem there, but I do not see anywhere on how to setup the firebase function itself:
Installing Svelte@next
https://carlosvin.github.io/posts/svelte-next-bright-future-with-snowpack/en/
https://github.com/jthegedus/svelte-adapter-firebase
In my actual index.js or index.ts firebase function file, I do not know what to call.  I am thinking something like this:
const functions = require("firebase-functions");

const next = require("./build/index.js");

exports.ssr = functions.https.onRequest(next);

I believe I am missing something so simple.  Any ideas?

Sapper SSR Resources

*

*https://github.com/tristolliday/sapper-firebase-sample/blob/master/functions/index.js

*https://dev.to/eckhardtd/how-to-host-a-sapper-js-ssr-app-on-firebase-hmb

A: Author of the Firebase adapter here.
There was an update with SvelteKit that by default disabled the logging level the adapter was using to guide you through the process.
Please try the latest version of the adapter (0.5.0) with the caveat that SvelteKit is still in alpha so the adapter can be broken by updates there. svelte-adapter-firebase@0.5.0 was tested and working against @sveltejs/kit@1.0.0-next.49


text:
Q: How to render a HTML page form NodeJs API? **After running http-server, I try to get to URL- http://127.0.0.1:8080 -  but  instead of what I write, I get
"Node.js v8.11.4/ ecstatic server running @ 127.0.0.1:8080"` every time I try.
But index.html file opens when clicked directly from the button, shows chrome as default browser and any changes made in coding like adding an email, password or changing the background color, it catches it accordingly.  How can I solve this problem??**
Here is the code for index.html-
<!DOCTYPE html>

            <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

            <link rel="stylesheet" href="css/style.css" />

 Wallpaper App Admin

                <form id="login-form">

                        Email
                        <input type="email" id="email" class="form-control" />

                            Password
                            <input type="password" id="password" class="form-control" />

                            <button id="btn-login" type="button" class="btn btn-primary">Login</button>

                </form>

A: Looks to me like you are not able to find end-point which respond your HTML page.
Every url is an API which make request to server. The url which we type on browser are GET API.
Your http://localhost:8080 and http://127.0.0.1:8080 are API with end-point as /.
If you are using expressJs then look for something like this:
app.get('/yourAPI/', (req, res) => {
    //res.render is function that send html page to browser
    res.render('htmlFile');
});
// So your page will be available on http:127.0.0.1:8080/yourAPI
// or http://localhost:8080/yourAPI

Note your function should be app.get() as you wont be able to call app.post from browser.
You need to find out end-point which response HTML page.


text:
Q: How to get rid of this footer from the ACM template? How can I remove the footer as is included in the ACM double column template? I created a screenshot of it: http://cdn.imghack.se/images/223c46062e6b28d6b0d9dc9500bf6098.jpg
A minmal file producing this footer looks like this:
\documentclass{acmtog}

\acmVolume{28}
\acmNumber{4}
\acmYear{2009}
\acmMonth{September}
\acmArticleNum{106}
\acmdoi{10.1145/1559755.1559763}

\begin{document}
\title{a}
\author{a}
\maketitle
\end{document}

When I remove the following lines...
\acmVolume{28}
\acmNumber{4}
\acmYear{2009}
\acmMonth{September}
\acmArticleNum{106}
\acmdoi{10.1145/1559755.1559763}

..then I get errors. I'm a beginner and confused why the template or more precisely the .cls file demands this information. I mean shouldn't it be possible to compile without having an ACM article number for example?
The respective .cls file is from http://www.acm.org/publications/latex_style/ (v2-acmtog.zip)

A: The acmtog class is not intended to be used without the footer. However, the following works:
\documentclass{acmtog}

% clear acmtog.cls footer settings
\makeatletter
\def\runningfoot{\def\@runningfoot{}}
\def\firstfoot{\def\@firstfoot{}}
\makeatother

\begin{document}
\title{a}
\author{a}
\maketitle
\end{document}

A: I came across a recent issue and one way I overcame this by defining a new macro in the preamble of my main latex document.
Here is an example of how it would look:
\documentclass{sigchi}

\makeatletter
\def\@copyrightspace{\relax}
\makeatother

\begin{document}
\end{document}

This command worked in the latest(March2018) version of the ACM SIGCHI template as well as when using the 2015 ACM sig-alternate class file.


text:
Q: Phoenix - no function clause matching in DieterDierenWeb.UserController.show/2 I am trying to make a site on which users can login and see there information and possibly even change that information. I already made it so that everything CRUD wise works (that is for admin users) however I try to now make it so that users can see their own profile but i keep getting this error:
Phoenix.ActionClauseError at GET /users/1
no function clause matching in DieterDierenWeb.UserController.show/2
The following arguments were given to DieterDierenWeb.UserController.show/2:
# 1
%Plug.Conn{adapter: {Plug.Cowboy.Conn, :...}, assigns: %{}, before_send: [#Function<0.78923111/1 in Plug.CSRFProtection.call/2>, #Function<2.106486136/1 in Phoenix.Controller.fetch_flash/2>, #Function<0.55231287/1 in Plug.Session.before_send/2>, #Function<0.93523768/1 in Plug.Telemetry.call/2>, #Function<0.126770172/1 in Phoenix.LiveReloader.before_send_inject_reloader/3>], body_params: %{}, cookies: %{"Idea-3e8c4776" => "3b04f3fa-aa86-4c82-99aa-67afd963f87b", "_auth_web_key" => "SFMyNTY.g3QAAAACbQAAAAtfY3NyZl90b2tlbm0AAAAYdlktVkpOcndMeHduMW9BRURvTlpsR0pRbQAAABZndWFyZGlhbl9kZWZhdWx0X3Rva2VubQAAAUxleUpoYkdjaU9pSklVelV4TWlJc0luUjVjQ0k2SWtwWFZDSjkuZXlKaGRXUWlPaUpoZFhSb1gzZGxZaUlzSW1WNGNDSTZNVFU1T0RRM056Y3pOQ3dpYVdGMElqb3hOVGsyTURVNE5UTTBMQ0pwYzNNaU9pSmhkWFJvWDNkbFlpSXNJbXAwYVNJNklqY3pZV1ppTjJRMExXVTNNRGN0TkRrNVpDMDROR015TFdVME9ERXpaREJrTXpJd05pSXNJbTVpWmlJNk1UVTVOakExT0RVek15d2ljM1ZpSWpvaU15SXNJblI1Y0NJNkltRmpZMlZ6Y3lKOS5tbjJDSkZ2VFNZSFNTd0cwaERaMUhjQ2RrSk1Od1ltTlEyUWZvQkNVV0NnUEhCbmVLeHBMbks0ZkVoX3hZS1ZEZmxtUzlZU24xMWFKR0RkbnNRQ1M1UQ.3CIxsqM_P0nRQDemm87hTX6wX5Exs0cITllQc3Z6EBk", "_dieter_dieren_web_key" => "SFMyNTY.g3QAAAACbQAAAAtfY3NyZl90b2tlbm0AAAAYX1R2cGUyNXM0dmdTUENYV1B0R2hEUnQzbQAAABZndWFyZGlhbl9kZWZhdWx0X3Rva2VubQAAAWRleUpoYkdjaU9pSklVelV4TWlJc0luUjVjQ0k2SWtwWFZDSjkuZXlKaGRXUWlPaUprYVdWMFpYSmZaR2xsY21WdVgzZGxZaUlzSW1WNGNDSTZNVFU1T0RRNE1qTXdNQ3dpYVdGMElqb3hOVGsyTURZek1UQXdMQ0pwYzNNaU9pSmthV1YwWlhKZlpHbGxjbVZ1WDNkbFlpSXNJbXAwYVNJNklqSXlNamd6TUdObExURmhPVGN0TkdZMU5TMDVNMkpoTFRJMk56UXlabUkyTWpBMFpDSXNJbTVpWmlJNk1UVTVOakEyTXpBNU9Td2ljM1ZpSWpvaU1TSXNJblI1Y0NJNkltRmpZMlZ6Y3lKOS51REFYaXNnbEFFV0xFcVc5cmwtLUdSZlQyRkRzaHhJc2l3OUZ4QU11Y2NuVTM5TF9IX2dmRWxmbDZFTnN2ME1UUzJhN1hwemo2UXZIN2NfT2xUMk1Edw.vhYfhv6S2-X_bwDRnfYxHBhb20bZgDHg74VWbAx3RYw", "locale" => "en"}, halted: false, host: "localhost", method: "GET", owner: #PID<0.550.0>, params: %{"user_id" => "1"}, path_info: ["users", "1"], path_params: %{"user_id" => "1"}, port: 4000, private: %{DieterDierenWeb.Router => {[], %{}}, :guardian_default_claims => %{"aud" => "dieter_dieren_web", "exp" => 1598482300, "iat" => 1596063100, "iss" => "dieter_dieren_web", "jti" => "222830ce-1a97-4f55-93ba-26742fb6204d", "nbf" => 1596063099, "sub" => "1", "typ" => "access"}, :guardian_default_resource => %DieterDieren.UserContext.User{__meta__: #Ecto.Schema.Metadata<:loaded, "users">, hashed_password: "$pbkdf2-sha512$160000$Bg04EMgtWjNcElFqKbWyWw$riiymuaNwzg1dDl/UL4PMpUffNdblCAlbgWSWkUdRf0ei9M4KOGG/YUnY0m87MpbhbSk7wI0SG/JunGJtGaM3g", id: 1, password: nil, role: "User", username: "user"}, :guardian_default_token => "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJkaWV0ZXJfZGllcmVuX3dlYiIsImV4cCI6MTU5ODQ4MjMwMCwiaWF0IjoxNTk2MDYzMTAwLCJpc3MiOiJkaWV0ZXJfZGllcmVuX3dlYiIsImp0aSI6IjIyMjgzMGNlLTFhOTctNGY1NS05M2JhLTI2NzQyZmI2MjA0ZCIsIm5iZiI6MTU5NjA2MzA5OSwic3ViIjoiMSIsInR5cCI6ImFjY2VzcyJ9.uDAXisglAEWLEqW9rl--GRfT2FDshxIsiw9FxAMuccnU39L_H_gfElfl6ENsv0MTS2a7Xpzj6QvH7c_OlT2MDw", :guardian_error_handler => DieterDierenWeb.ErrorHandler, :guardian_module => DieterDierenWeb.Guardian, :phoenix_action => :show, :phoenix_controller => DieterDierenWeb.UserController, :phoenix_endpoint => DieterDierenWeb.Endpoint, :phoenix_flash => %{}, :phoenix_format => "html", :phoenix_layout => {DieterDierenWeb.LayoutView, :app}, :phoenix_router => DieterDierenWeb.Router, :phoenix_view => DieterDierenWeb.UserView, :plug_session => %{"_csrf_token" => "_Tvpe25s4vgSPCXWPtGhDRt3", "guardian_default_token" => "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJkaWV0ZXJfZGllcmVuX3dlYiIsImV4cCI6MTU5ODQ4MjMwMCwiaWF0IjoxNTk2MDYzMTAwLCJpc3MiOiJkaWV0ZXJfZGllcmVuX3dlYiIsImp0aSI6IjIyMjgzMGNlLTFhOTctNGY1NS05M2JhLTI2NzQyZmI2MjA0ZCIsIm5iZiI6MTU5NjA2MzA5OSwic3ViIjoiMSIsInR5cCI6ImFjY2VzcyJ9.uDAXisglAEWLEqW9rl--GRfT2FDshxIsiw9FxAMuccnU39L_H_gfElfl6ENsv0MTS2a7Xpzj6QvH7c_OlT2MDw"}, :plug_session_fetch => :done}, query_params: %{}, query_string: "", remote_ip: {127, 0, 0, 1}, req_cookies: %{"Idea-3e8c4776" => "3b04f3fa-aa86-4c82-99aa-67afd963f87b", "_auth_web_key" => "SFMyNTY.g3QAAAACbQAAAAtfY3NyZl90b2tlbm0AAAAYdlktVkpOcndMeHduMW9BRURvTlpsR0pRbQAAABZndWFyZGlhbl9kZWZhdWx0X3Rva2VubQAAAUxleUpoYkdjaU9pSklVelV4TWlJc0luUjVjQ0k2SWtwWFZDSjkuZXlKaGRXUWlPaUpoZFhSb1gzZGxZaUlzSW1WNGNDSTZNVFU1T0RRM056Y3pOQ3dpYVdGMElqb3hOVGsyTURVNE5UTTBMQ0pwYzNNaU9pSmhkWFJvWDNkbFlpSXNJbXAwYVNJNklqY3pZV1ppTjJRMExXVTNNRGN0TkRrNVpDMDROR015TFdVME9ERXpaREJrTXpJd05pSXNJbTVpWmlJNk1UVTVOakExT0RVek15d2ljM1ZpSWpvaU15SXNJblI1Y0NJNkltRmpZMlZ6Y3lKOS5tbjJDSkZ2VFNZSFNTd0cwaERaMUhjQ2RrSk1Od1ltTlEyUWZvQkNVV0NnUEhCbmVLeHBMbks0ZkVoX3hZS1ZEZmxtUzlZU24xMWFKR0RkbnNRQ1M1UQ.3CIxsqM_P0nRQDemm87hTX6wX5Exs0cITllQc3Z6EBk", "_dieter_dieren_web_key" => "SFMyNTY.g3QAAAACbQAAAAtfY3NyZl90b2tlbm0AAAAYX1R2cGUyNXM0dmdTUENYV1B0R2hEUnQzbQAAABZndWFyZGlhbl9kZWZhdWx0X3Rva2VubQAAAWRleUpoYkdjaU9pSklVelV4TWlJc0luUjVjQ0k2SWtwWFZDSjkuZXlKaGRXUWlPaUprYVdWMFpYSmZaR2xsY21WdVgzZGxZaUlzSW1WNGNDSTZNVFU1T0RRNE1qTXdNQ3dpYVdGMElqb3hOVGsyTURZek1UQXdMQ0pwYzNNaU9pSmthV1YwWlhKZlpHbGxjbVZ1WDNkbFlpSXNJbXAwYVNJNklqSXlNamd6TUdObExURmhPVGN0TkdZMU5TMDVNMkpoTFRJMk56UXlabUkyTWpBMFpDSXNJbTVpWmlJNk1UVTVOakEyTXpBNU9Td2ljM1ZpSWpvaU1TSXNJblI1Y0NJNkltRmpZMlZ6Y3lKOS51REFYaXNnbEFFV0xFcVc5cmwtLUdSZlQyRkRzaHhJc2l3OUZ4QU11Y2NuVTM5TF9IX2dmRWxmbDZFTnN2ME1UUzJhN1hwemo2UXZIN2NfT2xUMk1Edw.vhYfhv6S2-X_bwDRnfYxHBhb20bZgDHg74VWbAx3RYw", "locale" => "en"}, req_headers: [{"accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"}, {"accept-encoding", "gzip, deflate"}, {"accept-language", "nl,en-US;q=0.7,en;q=0.3"}, {"connection", "keep-alive"}, {"cookie", "Idea-3e8c4776=3b04f3fa-aa86-4c82-99aa-67afd963f87b; locale=en; _dieter_dieren_web_key=SFMyNTY.g3QAAAACbQAAAAtfY3NyZl90b2tlbm0AAAAYX1R2cGUyNXM0dmdTUENYV1B0R2hEUnQzbQAAABZndWFyZGlhbl9kZWZhdWx0X3Rva2VubQAAAWRleUpoYkdjaU9pSklVelV4TWlJc0luUjVjQ0k2SWtwWFZDSjkuZXlKaGRXUWlPaUprYVdWMFpYSmZaR2xsY21WdVgzZGxZaUlzSW1WNGNDSTZNVFU1T0RRNE1qTXdNQ3dpYVdGMElqb3hOVGsyTURZek1UQXdMQ0pwYzNNaU9pSmthV1YwWlhKZlpHbGxjbVZ1WDNkbFlpSXNJbXAwYVNJNklqSXlNamd6TUdObExURmhPVGN0TkdZMU5TMDVNMkpoTFRJMk56UXlabUkyTWpBMFpDSXNJbTVpWmlJNk1UVTVOakEyTXpBNU9Td2ljM1ZpSWpvaU1TSXNJblI1Y0NJNkltRmpZMlZ6Y3lKOS51REFYaXNnbEFFV0xFcVc5cmwtLUdSZlQyRkRzaHhJc2l3OUZ4QU11Y2NuVTM5TF9IX2dmRWxmbDZFTnN2ME1UUzJhN1hwemo2UXZIN2NfT2xUMk1Edw.vhYfhv6S2-X_bwDRnfYxHBhb20bZgDHg74VWbAx3RYw; _auth_web_key=SFMyNTY.g3QAAAACbQAAAAtfY3NyZl90b2tlbm0AAAAYdlktVkpOcndMeHduMW9BRURvTlpsR0pRbQAAABZndWFyZGlhbl9kZWZhdWx0X3Rva2VubQAAAUxleUpoYkdjaU9pSklVelV4TWlJc0luUjVjQ0k2SWtwWFZDSjkuZXlKaGRXUWlPaUpoZFhSb1gzZGxZaUlzSW1WNGNDSTZNVFU1T0RRM056Y3pOQ3dpYVdGMElqb3hOVGsyTURVNE5UTTBMQ0pwYzNNaU9pSmhkWFJvWDNkbFlpSXNJbXAwYVNJNklqY3pZV1ppTjJRMExXVTNNRGN0TkRrNVpDMDROR015TFdVME9ERXpaREJrTXpJd05pSXNJbTVpWmlJNk1UVTVOakExT0RVek15d2ljM1ZpSWpvaU15SXNJblI1Y0NJNkltRmpZMlZ6Y3lKOS5tbjJDSkZ2VFNZSFNTd0cwaERaMUhjQ2RrSk1Od1ltTlEyUWZvQkNVV0NnUEhCbmVLeHBMbks0ZkVoX3hZS1ZEZmxtUzlZU24xMWFKR0RkbnNRQ1M1UQ.3CIxsqM_P0nRQDemm87hTX6wX5Exs0cITllQc3Z6EBk"}, {"host", "localhost:4000"}, {"upgrade-insecure-requests", "1"}, {"user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0"}], request_path: "/users/1", resp_body: nil, resp_cookies: %{}, resp_headers: [{"cache-control", "max-age=0, private, must-revalidate"}, {"x-request-id", "FiZa8vmBNwA5UtgAAAOh"}, {"x-frame-options", "SAMEORIGIN"}, {"x-xss-protection", "1; mode=block"}, {"x-content-type-options", "nosniff"}, {"x-download-options", "noopen"}, {"x-permitted-cross-domain-policies", "none"}, {"cross-origin-window-policy", "deny"}], scheme: :http, script_name: [], secret_key_base: :..., state: :unset, status: nil}

# 2
%{"user_id" => "1"}

Despite this being fully possible through admin resources (see below).
This is my router file (as you can see there is also an admin scope with resources and i can indeed do this properly as admin by just going to /admin/users/1:
>  defmodule DieterDierenWeb.Router do   use DieterDierenWeb, :router
>
>   pipeline :browser do
>     plug :accepts, ["html"]
>     plug :fetch_session
>     plug :fetch_flash
>     plug :protect_from_forgery
>     plug :put_secure_browser_headers   end
>
>   pipeline :api do
>     plug :accepts, ["json"]   end
>
>   pipeline :auth do
>     plug DieterDierenWeb.Pipeline   end
>
>   pipeline :ensure_auth do
>     plug Guardian.Plug.EnsureAuthenticated   end
>
>   pipeline :allowed_for_users do
>     plug DieterDierenWeb.Plugs.AuthorizationPlug, ["Admin", "User"]   end
>
>   pipeline :allowed_for_admins do
>     plug DieterDierenWeb.Plugs.AuthorizationPlug, ["Admin"]   end
>
>   scope "/", DieterDierenWeb do
>     pipe_through [:browser, :auth]
>
>     get "/", SessionController, :new
>     get "/login", SessionController, :new
>     post "/login", SessionController, :login
>     get "/logout", SessionController, :logout
>     get "/users/new", UserController, :show_sign_up
>     post "/users/new", UserController, :sign_up   end
>
>   scope "/", DieterDierenWeb do
>     pipe_through [:browser, :auth, :ensure_auth, :allowed_for_users]
>
>     get "/users/:user_id", UserController, :show
>     get "/user_scope", PageController, :user_index   end
>
>   scope "/admin", DieterDierenWeb do
>     pipe_through [:browser, :auth, :ensure_auth, :allowed_for_admins]
>
>     resources "/users", UserController   end   # Other scopes may use custom stacks.   # scope "/api", DieterDierenWeb do   #   pipe_through
> :api   # end end

This is my controller file the show function should show the profile page on the basis of the currently logged in user but here it gives the error:
 defmodule DieterDierenWeb.UserController do
  use DieterDierenWeb, :controller

  alias DieterDieren.UserContext
  alias DieterDieren.UserContext.User

  def index(conn, _params) do
    users = UserContext.list_users()
    render(conn, "index.html", users: users)
  end

  def new(conn, _params) do
    changeset = UserContext.change_user(%User{})
    roles = UserContext.get_acceptable_roles()
    render(conn, "new.html", changeset: changeset, acceptable_roles: roles)
  end

  def show_sign_up(conn, _params) do
    changeset = UserContext.change_user(%User{})
    roles = UserContext.get_acceptable_roles()
    render(conn, "sign_up.html", changeset: changeset, acceptable_roles: roles)
  end

  def create(conn, %{"user" => user_params}) do
    case UserContext.create_user(user_params) do
      {:ok, user} ->
        conn
        |> put_flash(:info, "User created successfully.")
        |> redirect(to: Routes.user_path(conn, :show, user))

      {:error, %Ecto.Changeset{} = changeset} ->
        render(conn, "new.html", changeset: changeset)
    end
  end

  def sign_up(conn, %{"user" => user_params}) do
    case UserContext.create_user(user_params) do
      {:ok, user} ->
        conn
        |> put_flash(:info, "User created successfully, please login to your new account.")
        |> redirect(to: Routes.session_path(conn, :new))

      {:error, %Ecto.Changeset{} = changeset} ->
        render(conn, "sign_up.html", changeset: changeset)
    end
  end

  def show(conn, %{"id" => id}) do
    user = UserContext.get_user!(id)
    render(conn, "show.html", user: user)
  end

  def edit(conn, %{"id" => id}) do
    user = UserContext.get_user!(id)
    changeset = UserContext.change_user(user)
    roles = UserContext.get_acceptable_roles()
    render(conn, "edit.html", user: user, changeset: changeset, acceptable_roles: roles)
  end

  def update(conn, %{"id" => id, "user" => user_params}) do
    user = UserContext.get_user!(id)

    case UserContext.update_user(user, user_params) do
      {:ok, user} ->
        conn
        |> put_flash(:info, "User updated successfully.")
        |> redirect(to: Routes.user_path(conn, :show, user))

      {:error, %Ecto.Changeset{} = changeset} ->
        render(conn, "edit.html", user: user, changeset: changeset)
    end
  end

  def delete(conn, %{"id" => id}) do
    user = UserContext.get_user!(id)
    {:ok, _user} = UserContext.delete_user(user)

    conn
    |> put_flash(:info, "User deleted successfully.")
    |> redirect(to: Routes.user_path(conn, :index))
  end
end

I will also give you the nav I use to try and navigate to the profile page:
    <!DOCTYPE html>

    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title><%= assigns[:page_title] || "DieterDieren · Phoenix Framework" %></title>
    <link rel="stylesheet" href="<%= Routes.static_path(@conn, "/css/app.css") %>"/>
    <%= csrf_meta_tag() %>

日本語

Nederlands

English

        <%= if Guardian.Plug.authenticated?(@conn, []) do%>

Overzicht

My profile

<a href="<%= Routes.session_path(@conn, :logout) %>">Logout

          <%= if checkAdmin(@conn) == true do%>

<a href="<%= Routes.user_path(@conn, :index) %>">User management

          <% end %>

        <% end %>

<%= get_flash(@conn, :info) %>

<%= get_flash(@conn, :error) %>

      <%= render @view_module, @view_template, assigns %>

Since I am quite new to this and since it says the first parameter is from my plug I will also give you the plug file no idea if this is helpfull or not though:
defmodule DieterDierenWeb.Plugs.AuthorizationPlug do
    import Plug.Conn
    alias DieterDieren.UserContext.User
    alias Phoenix.Controller

    def init(options), do: options

    def call(%{private: %{guardian_default_resource: %User{} = u}} = conn, roles) do
      conn
      |> grant_access(u.role in roles)
    end

    def grant_access(conn, true), do: conn

    def grant_access(conn, false) do
      conn
      |> Controller.put_flash(:error, "Unauthorized access")
      |> Controller.redirect(to: "/")
      |> halt
    end
  end

Can anyone please help me find my error?

A: Okay I was being quite stupid I just didn't fully understand the error.
My show function in the controller was needing an id argument.
So I did have one argument less in the nav part and therefore got my error.


text:
Q: How to place the JSON data in a list in a Ktor server? I have been trying to get Json data from dummyjson and place them into an Array in the ktor server. But it just won't work.
Application.kt:
fun main() {
    embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
        install(ContentNegotiation) {
            gson {
                setDateFormat(DateFormat.LONG)
                setPrettyPrinting()
            }
        }
        val client = HttpClient(CIO)
        val products: Array<Product> = client.get("https://dummyjson.com/products").body()
        configureRouting()
    }.start(wait = true)
}

I could create the client but I am not allowed to use the get method because it says Suspend function 'get' should be called only from a coroutine or another suspend function.
Then, in configureRouting.kt I defined the client and used the get method. It works and returns the String to the client.
fun Application.configureRouting() {
    val client = HttpClient(CIO)
    routing {
        get("/get-all-products"){
            val product: String = client.get("https://dummyjson.com/products").body()
            call.respond(product)
        }
}

However, what I want to achieve is without the client's request, the server can automatically load all the JSON file from dummyjson, and place it in a list. But it just keep giving me the same error if I place this get method outside the routing.


text:
Q: Email input in Magento Product I need to add this 3 custom attributes to a Magento product:

*

*Name

*Email

*Contact

I need it to be in the product page so that the user can add the information. I can't use and don't want to use the billing information. From what I understand that all attributes are configured and filled via back-end and not in front-end.
Imagine for example poster and I want to print this fields on it.

A: The only possible solution is to develop a custom attribute that presents in self in a way of a form in the product view.
Then we need to catch the inputs on does forms and then do whatever we need to do with this data.
There is no simple implementation in one of magento versions and also there is no extension free or paid in the market. This need to be done from scratch.


text:
Q: Cannot access correct value in React useState at first render Is a bit of a weird and deep problem, I will try to explain at my best.
I'm using React state to keep my user state update through my Chrome/Firefox extension app.
I grab some values from my cookies (with a custom Hook), save them in the user state and then pass them to my components.
Something that is driving me crazy happens in my components: If I access to the whole user state, I can see the correct user's values. If I access to a specific property from the user state object, I get another value!!
Here is the code:
useState sync with cookies custom hook:
import { useState, useCallback, useMemo } from 'react'
import { UserContextProps, UserStateProps, USER_STATE_DEFAULT } from '../context/UserContext'
import {
  COOKIE_NAME_LANGUAGE,
  COOKIE_NAME_ADULT_FILTER,
  COOKIE_NAME_NEW_TAB,
  COOKIE_NAME_SEARCH_COUNT,
  getCookieValue,
  setCookie,
} from '../helpers/_cookies'

const cookiesName: { [key: string]: any } = {
  numOfSearches: COOKIE_NAME_SEARCH_COUNT,
  language: COOKIE_NAME_LANGUAGE,
  adultContentFilter: COOKIE_NAME_ADULT_FILTER,
  openInNewTab: COOKIE_NAME_NEW_TAB,
}

const mergeCookiesWithUserState = (defaultUserState: UserStateProps): UserStateProps => {
  const newUserState = { ...defaultUserState }

  for (const key in newUserState) {
    if (Object.getOwnPropertyDescriptor(cookiesName, key)) {
      const printAddress = async () => {
        const cookieValue = await getCookieValue(cookiesName[key])

        if (cookieValue !== undefined) {
          newUserState[key] = cookieValue
        }
      }

      printAddress()
    }
  }

  return newUserState
}

export const useUserStateSyncedWithCookies = (): UserContextProps => {
  const initialUserState = useMemo(() => mergeCookiesWithUserState(USER_STATE_DEFAULT), [])

  const [userState, _setUserState] = useState(initialUserState)

  const setUserState = useCallback((nextState: Partial<UserStateProps>): void => {
    _setUserState((prevState) => {
      const newState = {
        ...prevState,
        ...nextState,
      }
      newState.adultContentFilter = Number(newState.adultContentFilter)
      newState.language = Number(newState.language)

      for (const key in nextState) {
        if (Object.getOwnPropertyDescriptor(cookiesName, key)) {
          setCookie(cookiesName[key], newState[key], { expires: 365 })
        }
      }

      return newState
    })
  }, [])
  console.log({ userState }) // Here i console log my user state and I get all teh updated value from my cookies.

  return {
    userState,
    setUserState,
  }
}

Just for complete information here is the getCookies() function
export async function getCookieValue(name: CookieName) {
    const promiseCookie = new Promise<string | number | boolean | undefined>((resolve, reject) => {
      extensionApiObject.cookies.getAll({}, (cookies) => {
        const filteredCookies = cookies.filter((cookie) => {
          return cookie.domain === 'elliotforwater.com' && cookie.name === name
        })

        resolve(convertCookieValue(name, filteredCookies[0]?.value))
      })
    })

    return promiseCookie.then()
}

And in my App.tsx for example I have:
function App() {
  const user = useUserStateSyncedWithCookies()

console.log(user) // user = { numbOfSearch: 1}
console.log(user.numOfSearches) // 0  !!! WHY?!

  return (
    <UserContext.Provider value={user}>
      <Background>
        <div>
          <Header />
          <Dashboard />
        </div>

        <Modal.Host />
      </Background>
    </UserContext.Provider>
  )
}
export default App

You can find the whole code on github here:
https://github.com/ElliotForWater/elliot-dashboard/blob/develop
https://github.com/ElliotForWater/elliot-dashboard/blob/develop/src/App.tsx
https://github.com/ElliotForWater/elliot-dashboard/blob/develop/src/hooks/useUserStateSyncedWithCookies.tsx

A: Since getCookieValue returns a promise so at the time of consoling user it will not have any value but after a while, it returns the value of the user asynchronously which gets updated in the console log. This does not happen in the case of object properties.
This is a well-known peculiarity (an optimization) of most browser consoles : the tree is only built when you open the object, with the new values of the object.
If you want to see the state of the object at the time of logging, supposing it's a small enough and not self referencing object, you may clone it like this :
console.log(JSON.parse(JSON.stringify(user));
To resolve this just use await for the promise and then you should get expected results.


text:
Q: return index of file in folder based on file creation date I have a project in C# language. which should take the name of a folder and a file. If the file does not exist in the folder, the file not exist will be printed. If there is a file, based on the file creation date, determine how many files have a creation date smaller than this file.
My code is as follows:

*

*First, it is checked if the file does not exist in the folder, the file not exist is printed
DirectoryInfo dir = new DirectoryInfo(@"c:\mydirectory");
string fileName = "myfile.png";
FileInfo[] files = dir.GetFiles("*.*");

Boolean fileFound = false;

for(int i=0; i<files.Length; i++)
{
   if(files[i].Name == fileName)
  {
      fileFound = true;
      break;
  }
}

if(fileFound==false)
{
    Console.WriteLine("the file not exist");
    return;
}

*The files are then sorted by creation date:
    for (int i = 0; i < files.Length; i++)
    {
        for (int n = i; n < files.Length; n++)
        {
            if (files[n].CreationTime < files[i].CreationTime)
            {
                var temp = files[i];
                files[i] = files[n];
                files[n] = temp;
            }
        }
    }

3.Finally, I find the index of the file in the list and it is printed:
        for (int i = 0; i < files.Length; i++)
        {
            if (files[i].Name == fileName)
            {
                Console.WriteLine("index of this file is: " +i);
                break;
            }
        }

My project works fine, but I think there must be an easier way with fewer lines. Can anyone guide me?

A: You can easily do all these steps using linq:
 //1. if the file does not exist in the folder, `the file not exist` is printed

 if (!files.Any(f => f.Name == fileName))
 {
     Console.WriteLine("the file not exist");
 }
 else
 {
     //2 ,3 : sort the list and find file index

     var indexOfFile = files.OrderBy(item => item.CreationTime)
              .Select((item, i) => new { Item = item.Name, Index = i })
              .First(x => x.Item == fileName).Index;

     Console.WriteLine("index of this file is: {0}", indexOfFile);
 }

A: without linq, avoids case sensitive string comparisons and only a single iteration
        string dir = @"c:\mydirectory";
        string fileName = @"myfile.png";

        System.IO.FileInfo fi = new System.IO.FileInfo(System.IO.Path.Combine(dir, fileName));
        if (fi.Exists) {
            int count = 0;
            foreach (System.IO.FileInfo other in fi.Directory!.EnumerateFiles()) {
                if (other.CreationTime < fi.CreationTime) {
                    count++;
                }
            }

            System.Console.WriteLine("index of this file is: " + count);
        }
        else {
            System.Console.WriteLine("the file not exist");
        }

A: There is, using LINQ. You'll need to have a List<FileInfo> instead of an array for this to work.
List<FileInfo> files = dir.GetFiles("*.*").ToList();
string fileName = "filetofind.txt";

First, sort the files by creation time. There's also OrderByDescending if you want to reverse the order.
files = files.OrderBy(o => o.CreationTime).ToList();

Then get the index of the file by its name.
int index = files.FindIndex(o => o.Name == fileName);

If you need to have an array at the end of this process, you can create one from the List.
FileInfo[] fileArray = files.ToArray();


text:
Q: How can I upload/change user's profile image programatically or via API? I know, that there is no way to mass-upload these images via dataloader as described here

*

*can I upload user's profile image via data loader

*https://success.salesforce.com/ideaView?id=08730000000HA1nAAG&sort=2
Is there a way to access and change the image programmatically or via API? There seems to be an local app for it and I wonder on how this is done in the app: http://satrangtech.com/products.htm#4

A: As @jonathanwiesel mentioned, it can be done via Connect API which has an APEX wrapper and therefore it's easy and very straight forward to implement.
Here you can even find sample code for that: https://developer.salesforce.com/forums/?id=906F0000000AWe7IAG
I've checked it and it works fine for me like this:
VF-Page
<apex:page controller="FileUploadController">
    <apex:sectionHeader title="Visualforce Example" subtitle="File Upload Example" />

    <apex:form enctype="multipart/form-data">
        <apex:pageMessages />
        <apex:pageBlock title="Upload a File">

            <apex:pageBlockButtons>
                <apex:commandButton action="{!upload}" value="Save" />
            </apex:pageBlockButtons>

            <apex:pageBlockSection showHeader="false" columns="2" id="block1">

                <apex:pageBlockSectionItem>
                    <apex:outputLabel value="File Name" for="fileName" />
                    <apex:inputText value="{!document.name}" id="fileName" />
                </apex:pageBlockSectionItem>

                <apex:pageBlockSectionItem>
                    <apex:outputLabel value="File" for="file" />
                    <apex:inputFile value="{!document.body}" filename="{!document.name}" id="file" />
                </apex:pageBlockSectionItem>

                <apex:pageBlockSectionItem>
                    <apex:outputLabel value="Description" for="description" />
                    <apex:inputTextarea value="{!document.description}" id="description" />
                </apex:pageBlockSectionItem>

                <apex:pageBlockSectionItem>
                    <apex:outputLabel value="Keywords" for="keywords" />
                    <apex:inputText value="{!document.keywords}" id="keywords" />
                </apex:pageBlockSectionItem>

            </apex:pageBlockSection>

        </apex:pageBlock>
    </apex:form>
</apex:page>

APEX-Controller
public without sharing class FileUploadController {

    public Document document {
        get {
            if (document == null)
                document = new Document();
            return document;
        }
        set;
    }

    public PageReference upload() {
        Blob b;
        document.AuthorId = UserInfo.getUserId();
        document.FolderId = UserInfo.getUserId(); // put it in running user's folder

        try {
            document.type = 'jpg';
            document.IsPublic = true;
            insert document;
            // ImageId = '06990000001HnuB';
            b = document.Body;
            //ConnectApi.ChatterUsers newPhoto = new ConnectApi.ChatterUsers();

        } catch (DMLException e) {
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Error uploading file'));
            return null;
        } finally {
            document.body = null; // clears the viewstate
            document = new Document();
        }

        ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, 'File uploaded successfully : ' + b));
        String communityId = null;
        String userId = UserInfo.getUserId();
        //ID fileId = ImageId;

        // Set photo
        ConnectApi.Photo photo = ConnectApi.ChatterUsers.setPhoto(communityId, userId, new ConnectApi.BinaryInput(b, 'image/jpg', 'userImage.jpg'));
        return null;
    }

}

A: You could use the new Connect API.
Specifically the ChatterUsers Class with the setPhoto method.
However I believe this would not work for bulk as your initial requirement states.

A: ChatterUsers class no longer supports setting photos. Currently this functionality is available under UserProfiles class.
ConnectApi.Photo photo = ConnectApi.UserProfiles.setPhoto(communityId, userId, new ConnectApi.BinaryInput(b, 'image/jpg', 'userImage.jpg'));

Source


text:
Q: fsck not working to fix corrupted external drive I am using an early 2011 MacBook Pro with the Mavericks OS. I've researched a similar issue on an internal drive but As far as I know, being in Single User mode won't help my situation.
One of my external drives with all my photos stopped working - it does not mount, even though I see it in Disk Utility.
Using DU I tried to verify and repair the disk and got this message:
'Invalid B-tree node size'
Following the advice in this link:
I tried to list my drives with the Terminal command
df -hl
The specificied disk was not in the list
When I tried the suggested tail command
tail -f /var/log/fsck_hfs.log
I saw the name of the disk as
/dev/rdisk3s2: ** The volume   could not be verified completely.

Following that, I used this command (also suggested in the above link)
sudo fsck_hfs -r -d /dev/disk3s2
Instead of the expected proper outcome, what I received was an error message in Terminal as below:
inancs-MacBook-Pro:~ INCA$ sudo fsck_hfs -r -d /dev/disk3s2
Password:
journal_replay(/dev/disk3s2) returned 0
** /dev/rdisk3s2
    Using cacheBlockSize=32K cacheTotalBlock=65536 cacheSize=2097152K.
   Executing fsck_hfs (version hfs-226.1.1).
** Checking Journaled HFS Plus volume.
   Invalid B-tree node size
(3, 0)
** The volume   could not be verified completely.
    volume check failed with error 7
    volume type is pure HFS+
    primary MDB is at block 0 0x00
    alternate MDB is at block 0 0x00
    primary VHB is at block 2 0x02
    alternate VHB is at block 1464477326 0x574a268e
    sector size = 512 0x200
    VolumeObject flags = 0x07
    total sectors for volume = 1464477328 0x574a2690
    total sectors for embedded volume = 0 0x00
    CheckHFS returned -1317, fsmodified = 0

What are my options?
I have Data Rescue but not Disk Warrior (low on budget these days).
Is there a possibility to fix the drive?
If not, and if I can rescue my data and put it on a different disk, is it safe to format the current drive and re-add my photos or should i stay away from this disk?


text:
Q: VBA DataBodyRange background color error 91? I am trying to add a color to my header and my databodyrange but the header is being coloured but the body isn't:
Tbl.HeaderRowRange.Interior.Color = RGB(62, 199,98)
Tbl.DataBodyRange.Interior.Color = RGB(151, 225, 137)

code:
Set Tbl = .ListObjects.Add(xlSrcRange, Source:=.Range("F" & NextRow + 8 & ":I" & NextRow + 8), XlListObjectHasHeaders:=xlYes)

                Tbl.Name = "KozijnAspect_" & I

                Tbl.HeaderRowRange(1).Value = "Kozijn"
                Tbl.HeaderRowRange(2).Value = "Gevel Type"
                Tbl.HeaderRowRange(3).Value = "Orientatie"
                Tbl.HeaderRowRange(4).Value = "Stand"

                Tbl.HeaderRowRange.Interior.Color = RGB(62, 199, 98)
                Tbl.DataBodyRange.Interior.Color = RGB(62, 199, 98)

Error code: Object variable not set (Error 91)

*

*I copied the HeaderRowRange, pasted it below and changed RGB values and switched it to DataBodyRange

*When I debug it just goes straight to the next line, it's not going to another module / excel object or anything.

A: Here it is a piece of code from a bigger pie...
I am afraid that your code does not produce any DataBodyRange and that's why VBA is not able to do something on a non existing object...
When your code is stopped on this yellow row, please go on Excel Table and manually insert one, or two rows. Then, go back in IDE and press F5...
You may have a good surprise... :)


text:
Q: How do I tell how many challenges I have left on Halos Ultimate Weekly reward?
I only see one challenge under weekly ultimate.  When I complete this challenge will I unlock the armor coating?  Or is there a chance that the challenge will be replaced with a new one?


text:
Q: "XXX is hashed" meaning from type command? I realized that you can use windows dir in ubuntu terminal, when I tried to dig deeper into its implementation, type command tells me it is hashed, I read some doc but it didn't explain what "hashed" means

A: From https://unix.stackexchange.com/a/105878 by user frostschutz on Unix Stackexchange:

It's a performance thing; instead of searching the whole path for the binary every time it is called, it's put into a hash table for quicker lookup. So any binary that's already in this hash table, is hashed. If you move binaries around when they're already hashed, it will still try to call them in their old location.
See also help hash, or man bash and search for hash under builtin commands there.


text:
Q: textFont() not working in p5.js Alright, I'm just trying to add this font to my website, but this error keeps showing up in the console.
Uncaught TypeError: Cannot read property 'length' of undefined
at Substitution.getDefaultScriptName (p5.js:31993)
at Font.stringToGlyphs (p5.js:27954)
at Font.forEachGlyph (p5.js:28069)
at Font.getAdvanceWidth (p5.js:28144)
at p5.Font._textWidth (p5.js:63498)
at p5.Font._handleAlignment (p5.js:63523)
at p5.Font._getPath (p5.js:63339)
at p5.Font._renderPath (p5.js:63458)
at p5.Renderer2D._renderText (p5.js:48828)
at p5.Renderer2D.text (p5.js:48788)

This is the only error that appears and it makes my entire code stop.
Here is my code:
var sound;
var imgs = [];
var myFont;
function preload() {
    soundFormats('mp3');
    sound = loadSound('Your Reality.mp3');
    myFont = loadFont('assets/monika.ttf');
    for (var i = 0; i < 12; i++) {
        imgs[i] = loadImage('assest/img(' + i + ').png');
    }
}
function setup() {
    imageMode(CENTER);
    sound.setVolume(0.5);
    sound.play();
    //sound.onended(soundEnd);
    createCanvas(windowWidth-20, windowHeight-20);
    text("Click Anywhere!", 0, 10);
    soundEnd();
}
function soundEnd() {
    imgs = [];
    for (var i = 0; i < 12; i++) {
        imgs[i] = loadImage('assets/img(' + i + ').png');
    }
    reload();
    textSize(36);
    textFont(myFont);
    var inter = setInterval(flashText, 200);
}
function flashText() {
    text("Just Monika", floor(random(0, width-30)), floor(random(0, height-15)));
}
function windowResized() {
    resizeCanvas(windowWidth - 20, windowHeight - 20);
}
function reload() {
    resizeCanvas(windowWidth - 20, windowHeight - 20);
    text("Click Anywhere!", 0, 10);
}

What is supposed to happen is that music plays, and you can click your mouse (mouseClicked function not included in this code because it was irrelevent) and some images will appear, after the music ends a different set of images will appear, then the text "Just Monika" is supposed to flash around the screen in a specific font,but the font isn't working, is this an issue with p5.js?


text:
Q: Better to customize UINavigationBar with image or programmatically? I know that there are two distinct ways to customize a UINavigationBar: you can either set the background image to some custom png, or you could customize the bar's appearance in code, programmatically. If my aim is to support iOS 4,5,6 does it make sense to try to customize the bar's appearance through code?
I essentially want a navigationbar without any gradience, a solid color, rounded corners, and an extremely thin shadow line. I would post an image below but I need at least 10 reputation points :(
I've started with the following code to address the no gradience and solid color issues, and I've placed this in the .m file of my rootviewcontroller before the @implementation of the class itself, but to no avail:
@implementation UINavigationBar (UINavigationBarCategory)
- (void)drawRect:(CGRect)rect {
    UIColor *color = [UIColor blueColor];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColor(context, CGColorGetComponents( [color CGColor]));
    CGContextFillRect(context, rect);
}
@end

I also have implemented this code to round out the corners, which works:
CALayer *capa = [self.navigationController navigationBar].layer;
[capa setShadowColor: [[UIColor blackColor] CGColor]];
[capa setShadowOpacity:0.85f];
[capa setShadowOffset: CGSizeMake(0.0f, 1.5f)];
[capa setShadowRadius:2.0f];
[capa setShouldRasterize:YES];

//Round
CGRect bounds = capa.bounds;
bounds.size.height += 10.0f;    //I'm reserving enough room for the shadow
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bounds
                                               byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight)
                                                     cornerRadii:CGSizeMake(10.0, 10.0)];

CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = bounds;
maskLayer.path = maskPath.CGPath;

[capa addSublayer:maskLayer];
capa.mask = maskLayer;

Any help on this matter would be greatly appreciated!

A: If you want to target iOS < 5 then the UIAppearance won't help you because it is supported only for iOS >= 5.
So in my opinion, using a png file for the navigation bar's background is faster and maybe safer. Depending on your desired result you can do it from code and also make it faster, just create a BaseViewController that will handle the navigation bar's appearance (background, title, buttons etc) and all your custom view controllers can inherit from this BaseViewController, but this implementation in some cases can has it's own drawbacks since you can't inherit from multiple classes in iOS, and I'm afraid that you will find out this a little bit late when you will get to a point when you will want to have features from a view controller that doesn't inherit from the BaseViewController.
On the other hand, creating the color and the graphics from code will probably raise issues from the beloved designers who will want 1px left/up/right/down/diagonal/etc, and in this way you will have headaches (happen to me).
If you are targeting iOS >=5 then UIAppearance is your friend.
So in conclusion, if you are targeting iOS >= 5 use UIAppearance if not, if you have a more complex (gradient, lines, strange colors) UI for your nav bar use png, if you have simple (one flat color) UI for nav bar, you can do it from code with no problems.

A: The appearance proxy of the UINavigationBar is there to set the default for ALL UINavigationBars if you want ALL of the bars to change then do it programmatically, if you want only 1 to change then do it in the storyboard both methods should have the same outcome for the appearance of your NavigationBar
The color/shadow should be with in the image, but be mindful of the fact that you shouldn't change the height of the navigation bar...
if you are able to have the image have the rounded corners and the shadow baked in
if you are not you will have to do it in code by using your code above
That is a simple method... a more advanced method would be creating a UINavigationBar item in your storyboard with an associated IBOutlet, setting an outlet to that item, set all the properties from with in the storyboard like the background image, then with in the viewDidLoad method set the IBOutlet of the UINavigationBar to the UINavigationBar of the UINavigationController of the UIViewController that you are loading. Also, you can round the corners of the UINavigationBar here if you desire.


text:
Q: Draw ellipses on people using Expectation Maximization with OpenCV I have a few doubts about how to approach my goal. I have an outside camera who is recording people and I want to draw an ellipse on every person.
Right now what I do is get the feature points of the people from the frame (I get them using a mask to only have the feature points on the people), set a EM algorithm and train it with my samples (the feature points extracted). The number of clusters is twice the number of people from the image (I get it before start the EM algorithm using other methods such as pixel counting with a codebook).
My question is

*

*(a) Do I have to just train it only for the first frame and then use predict in the following frames? or,

*(b) use train with the feature points in every frame?

Right now I am doing the option b) (I don't use predict) because I don't really know how to use the predict.
If I do a), can you help me with it and after that how to draw the ellipses?. If I do b), can you help me drawing an ellipse for every person? Since right know I got different ellipses for the same person using the cov, mean, etc (one for the arm, for example).
What I want to achieve is this paper using the Gaussian model:  Link

A: If you would draw bounding boxes, rather then ellipses, you could use the function groupRectanlges to merge the different bounding boxes.
But, more important - for people detection, you can simply use openCV's person detector (based on HOG) or latent svm detector with the person model.

A: You should do b) anyway because, otherwise you'll try to match the keypoints to the clusters (persons) in the first frame. After a few seconds this would not be relevant.
It seems reasonable to assume that from frame to frame change is not going to be overwhelming, so reusing the results of the training on frame N-1 is a good seed to train on frame N, likely to converge faster that running EM from scratch on each frame.
in order to draw the ellipses you can leverage from the mixture of gaussian example in the python bindings:
https://github.com/opencv/opencv/blob/master/samples/python/gaussian_mix.py
Note if you use a diagonal covariance matrix, your ellipses are going to be aligned "straight", their own axis aligned with the X and Y axis of the frame, you can skip the calculation of the angle of the ellipse


text:
Q: Check if a specific IP address exists on local NIC I'm looking for a simple script or batch method for checking the existence of a specific IP address (being moved between machines via NETSH) on the local network card. I need to start up certain services / apps etc ONLY if the specified IP address exists on the card.
Any ideas?
Thanks.

A: powershell?  save this as a .ps1 script and execute.  (substitute the IP address you care about...)
$ipaddr = Get-WMIObject win32_NetworkAdapterConfiguration |   Where-Object {$.IPEnabled -eq $true } |   Foreach-Object { $.IPAddress }
if ($ipaddr -eq "10.10.10.10")
{
 "Yes it's here"
 }
 else
 {
 "Nope"
 }

A: Here's a batch script that uses ipconfig, parses the output for the ip address you specified. Then tells you if it was found or not.
To use it: paste the code into notepad saveas .bat file and execute it.  Change the ip address to the one you want.
set ip=192.168.1.1

ipconfig | find /i "%ip%" > nul
if %errorlevel% equ 0 (echo ip address found) else (echo ip address not found)


text:
Q: Pass touches through a UIViewController I have a view controller that I overlay on top of another view controller. I just need the top view controller so I can overlay a temporary pop up notification, and having an overlayed VC allows me to present this over a UITableViewController as you can't add subviews to tableview controllers directly.
Is it possible to interact with the bottom view controller while it has another view controller covering it. If this were a view or a window you would achieve this by setting user interaction to false or using hitTest but neither of these approaches works for a view controller.

A: Create subclass like this
class TouchDelegatingView: UIView {
    weak var touchDelegate: UIView? = nil

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        guard let view = super.hitTest(point, with: event) else {
            return nil
        }

        guard view === self, let point = touchDelegate?.convert(point, from: self) else {
            return view
        }

        return touchDelegate?.hitTest(point, with: event)
    }
}

Then in your ViewController set view class (you can do it directly in xib, or inside loadView() method)
And add
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        if let delegatingView = view as? TouchDelegatingView {
            delegatingView.touchDelegate = presentingViewController?.view
        }
    }
}

Also you can use this mechanism to delegate touches to any other view, no matter if it


text:
Q: Using generators in Typescript tsconfig What I'm Trying to Do
This is pretty simple, I want to use a generator function in Typescript and have it not error on me.
traverseTree = function* (tree: Section[]) {
    for (let branch of tree) {
        yield branch;
        if (branch.Children.length > 0)
            yield* traverseTree(branch.Children);
    }
}

What I'm Seeing
When compiling, I get the error TS2318 Cannot find global type 'IterableIterator'
What I've done so far
I've read a number of questions such as this one or this one, but none of the suggestions I've been able to find have made any difference.  I'm using Typescript 3.2.2 and trying to use a pretty simple generator function.  I've tried many things, but this is my current tsconfig file:
{
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "module": "none",
    "lib": [
      "esnext",
      "dom",
      "es2015.promise"
    ]
  },
  "compileOnSave": true
}

I've also tried adding "downlevelIteration": true, both true and false for "noLib", in "lib": not having "esnext", using "es6", and not having "lib" at all, I also messed with setting files:
"files": [
  "node_modules/typescript/lib/lib.d.ts",
  "node_modules/typescript/lib/lib.es6.d.ts"
]

Nothing I do seems to make any difference, I always get the exact same error when compiling.

A: Got it, I was using Visual Studio 2019 Preview and for some reason 2017 worked fine.  Turns out I just needed to install the 3.2.2 SDK and everything worked perfectly in both versions.  I don't know why 2017 didn't care that the SDK wasn't installed and 2019 did, seems odd.


text:
Q: Spring: Injecting property as a value into an annotation I am trying to inject a value into a Custom Annotation but Spring doesn't seem to be evaluating.
Here is my annotation:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnno {
    String var1();
    String var2();
}

Here is my Bean (it is created in a Spring Configuration file) with Annotation:
public class MyClass {

    @MyCustomAnno(var1 = "${some.property.one}",
                  var2 = "${some.property.two}")
    public void someMethod() {
    // do something here
    }
}

Here is the Aspect where I am trying to use the values passed into the annotation:
@Aspect
public class MyAop {

    @Around(value="@annotation(myCustomAnno)",argNames="myCustomAnno")
    public Object aroundMethod(MyCustomAnno myCustomAnno) {
        int intVar1 = Integer.parseInt(myCustomAnno.var1());
        int intVar2 = Integer.parseInt(myCustomAnno.var2());

        // ....
    }
}

In the around method I am receiving a NumberFormatException: For input string: ${some.property.one}. This means that Spring didn't inject the value for some reason.
In case you are wondering, in the same class I can do the normal @Value annotation and the value gets injected properly:
@Value("${some.property.one}")
private propertyOne;            // This works

Is it possible to do what I want to and if so, how?

A: AFAIK, placeholders are not resolved in custom annotations. However you could resolve them in the Aspect itself.
For example:
@Aspect
class MyAop implements EmbeddedValueResolverAware {

    private StringValueResolver resolver;

    @Around(value="@annotation(myCustomAnno)",argNames="myCustomAnno")
    public void play(MyCustomAnno ann) {
        System.out.println(resolver.resolveStringValue(ann.var1()));
    }

    @Override
    public void setEmbeddedValueResolver(StringValueResolver resolver) {
        this.resolver = resolver;
    }
}


text:
Q: Loading an abstract class based object by YAML file I want to load object which contains array list of objects based on abstract class from yaml file. And i get this error message:
Exception in thread "LWJGL Application" Cannot create property=arrayListOfAbstractObjects for JavaBean=com.myyaml.test.ImplementationOfExampleClass@7a358cc1
in 'reader', line 1, column 1:
dummyLong: 1
^
java.lang.InstantiationException
in 'reader', line 3, column 3:
- dummyFloat: 444
^
YAML file
dummyLong: 1
arrayListOfAbstractObjects:
  - dummyFloat: 444
  - dummyDouble: 123

Java classes:
public abstract class ExampleClass {
    protected ArrayList<AbstractClass> arrayListOfAbstractObjects;
    protected long dummyLong = 111;

    public ExampleClass() {
    }

    public void setArrayListOfAbstractObjects(ArrayList<AbstractClass> arrayListOfAbstractObjects) {
        this.arrayListOfAbstractObjects = arrayListOfAbstractObjects;
    }

    public void setDummyLong(long dummyLong) {
        this.dummyLong = dummyLong;
    }
}

public class ImplementationOfExampleClass extends ExampleClass {

    public ImplementationOfExampleClass() {
    }
}

public abstract class AbstractClass {
    private int dummyInt = 22;

    public AbstractClass() {
    }

    public void setDummyInt(int dummyInt) {
        this.dummyInt = dummyInt;
    }
}

public class FirstImplementationOfAbstractClass extends AbstractClass {
    float dummyFloat = 111f;

    public FirstImplementationOfAbstractClass() {
    }

    public void setDummyFloat(float dummyFloat) {
        this.dummyFloat = dummyFloat;
    }
}

public class SecondImplementationOfAbstractClass extends AbstractClass {
    double dummyDouble = 333f;

    public SecondImplementationOfAbstractClass() {
    }

    public void setDummyDouble(double dummyDouble) {
        this.dummyDouble = dummyDouble;
    }
}

My guess is that yaml doesn't know which sort of abstract class implementation to use. FirstImplementationOfAbstractClass or SecondImplementationOfAbstractClass. Is it possible to load an object by yaml with such classes?

A: This is only possible if you tell the YAML processor which class you want to instantiate on the YAML side. You do this with tags:
dummyLong: 1
arrayListOfAbstractObjects:
  - !first
    dummyFloat: 444
  - !second
    dummyDouble: 123

Then, you can instruct your YAML processor to properly process the items based on their tags. E.g. with SnakeYAML, you would do
class MyConstructor extends Constructor {
    public MyConstructor() {
        this.yamlConstructors.put(new Tag("!first"), new ConstructFirst());
        this.yamlConstructors.put(new Tag("!second"), new ConstructSecond());
    }

    private class ConstructFirst extends AbstractConstruct {
        public Object construct(Node node) {
            // raw values, as if you would have loaded the content into a generic map.
            final Map<Object, Object> values = constructMapping(node);
            final FirstImplementationOfAbstractClass ret =
                    new FirstImplementationOfAbstractClass();
            ret.setDummyFloat(Float.parseFloat(values.get("dummyFloat").toString()));
            return ret;
        }
    }

    private class ConstructSecond extends AbstractConstruct {
        public Object construct(Node node) {
            final Map<Object, Object> values = constructMapping(node);
            final SecondImplementationOfAbstractClass ret =
                    new SecondImplementationOfAbstractClass();
            ret.setDummyFloat(Double.parseDouble(values.get("dummyFloat").toString()));
            return ret;
        }
    }
}

Note: You can be more intelligent when loading the content, avoiding toString and instead process the node content directly; I use a dumb implementation for easy demonstration.
Then, you use this constructor:
Yaml yaml = new Yaml(new MyConstructor());
ExampleClass loaded = yaml.loadAs(input, ImplementationOfExampleClass.class);

A: The Node class is kind of YAML file transformed into Java data object. I found under debugger it contains field ArrayList<E> value. Which contains NodeTuple with YAML file fields (e.g. dummyFloat). So I must in constructMapping(node) method convert on my own each field and then set them in e.g. ConstructFirst.construct(Node node) on the constructed object.
EDIT:

So I must in constructMapping(node) method convert on my own each field and then set them in e.g. ConstructFirst.construct(Node node) on the constructed object.

Cast of param node to MappingNode is needed. This method is inherited from BaseConstructor.constructMapping(MappingNode node). Flyx didn't add that cast and I didn't know where to get it from. Thanks for help. Now it works. But i'm still struggle with nested abstract classes. Maybe i'll need help, but I will try to handle myself.
Also this link might be helpful:
Polymorphic collections in SnakeYaml


text:
Q: Count total amount of references from multiple foreign tables in MySQL I have 3 tables:
A
B which has a foreign key to A
C same
How can I count the total number of relations that references a row in A?
ex.

A
+----+------+
| id | name |
+----+------+
|  1 |  foo |
|  2 |  bar |
+----+------+

B
+----+----+
| id |  a |
+----+----+
|  1 |  1 |
|  2 |  1 |
|  3 |  2 |
|  4 |  2 |
+----+----+

C
+----+----+
| id |  a |
+----+----+
|  1 |  1 |
|  2 |  1 |
+----+----+

I want to get this result:
+------+----+
| name |  a |
+------+----+
| foo  |  4 |
| bar  |  2 |
+------+----+

Thanks

A: From your sample data and expected results it seems like you need to left join A to the UNION of the other tables:
select A.name, count(t.a) count
from A
left join (
  select id, a from B
  union all
  select id, a from C
) t
on A.id = t.a
group by A.id, A.name

See the demo.
Results:
| name | count |
| ---- | ----- |
| foo  | 4     |
| bar  | 2     |

A: Edit 1: taking into account that all children tables may be empty
Edit 2: Accepted answer is inefficient and will result in temporary table being created by the union of the size of B + C, then grouping will be performed on that temporary table. An explain plan on that query reveals Using temporary; Using filesort, both being bad:
+------+-------------+------------+-------+---------------+------+---------+-----------------+------+---------------------------------+
| id   | select_type | table      | type  | possible_keys | key  | key_len | ref             | rows | Extra                           |
+------+-------------+------------+-------+---------------+------+---------+-----------------+------+---------------------------------+
|    1 | PRIMARY     | A          | ALL   | NULL          | NULL | NULL    | NULL            | 5    | Using temporary; Using filesort |
|    1 | PRIMARY     | <derived2> | ref   | key0          | key0 | 5       | A.id            | 2    |                                 |
|    2 | DERIVED     | B          | index | NULL          | a    | 4       | NULL            | 15   | Using index                     |
|    3 | UNION       | C          | index | NULL          | a    | 4       | NULL            | 14   | Using index                     |
+------+-------------+------------+-------+---------------+------+---------+-----------------+------+---------------------------------+

While if you simply sum up the individual COUNT, you would only have the indexes being queried to know the amount of elements:
SELECT name,
  (SELECT COUNT(*) FROM B WHERE B.a = A.id) +
  (SELECT COUNT(*) FROM C WHERE C.a = A.id) AS count
FROM A;

This would result in the following explain plan:
+------+--------------------+-------+------+---------------+------+---------+-----------------+------+-------------+
| id   | select_type        | table | type | possible_keys | key  | key_len | ref             | rows | Extra       |
+------+--------------------+-------+------+---------------+------+---------+-----------------+------+-------------+
|    1 | PRIMARY            | A     | ALL  | NULL          | NULL | NULL    | NULL            | 5    |             |
|    3 | DEPENDENT SUBQUERY | C     | ref  | a             | a    | 4       | A.id            | 1    | Using index |
|    2 | DEPENDENT SUBQUERY | B     | ref  | a             | a    | 4       | A.id            | 1    | Using index |
+------+--------------------+-------+------+---------------+------+---------+-----------------+------+-------------+

Queries and explain plan of accepted answer + this one available in the demo.


text:
Q: Incrustar PDF con base64 y PHP mayor a 6MB en un html Tengo el siguiente problema, necesito generar un html con un pdf incrustado dentro de un embed, lo interesante es que con archivos menores a 6MB no hay ningún problema pero cuando el archivo es mas grande falla  y solo aparece una pantalla blanca.
¿Como lo hago para que aparezca el archivo mas grande igual que el pequeño?
Acepto todo tipo de sugerencias.
Muchas gracias de antemano.
    $src = urldecode($_REQUEST['archivo']);
    //$src <-- string 'Z:/327000360.pdf'

    ini_set('memory_limit', '256M');
    $dataBase64 = base64_encode(file_get_contents($src));

    $html = "<!DOCTYPE html>
    <html lang='en'>
    <head>
        <meta charset='UTF-8'>
        <title>Visor de PDF</title>
        <style>
            html,body{
                margin: 0;
                padding: 0;
            }
            embed{
                height: 99vh;
            }
        </style>
    </head>
    <body>
        <embed src='data:application/pdf;base64,$dataBase64' width='100%' type='application/pdf'>
    </body>
    </html>";

    echo $html;

A: Generalmente este problema sucede debido a que el tiempo que tarda en ejecutarse tu script excede el tiempo máximo por defecto programado en el PHP.ini provocando así la detención abrupta de la ejecución del script.
Para solucionar esto puedes utilizar la instrucción set_time_limit(300); dentro de tu archivo. Esto te permite ejecutar un script (en tu caso la carga de un archivo PDF de mayor tamaño) por un tiempo de 300 segundos o lo que es lo mismo 5 minutos. Si deseas colocar un tiempo mayor a 300 segundos debes cambiar otros parametros disponibles en el .conf del servidor como lo muestra esta respuesta a un usuario de StackOverflow página inglesa: PHP set_time_limit.
Tu código quedaría así (aunque preferiblemente colocar el set time limit al inicio del archivo .php):
set_time_limit(300); // Esta es la línea añadida para lograr tu objetivo.
$src = urldecode($_REQUEST['archivo']);
    //$src <-- string 'Z:/327000360.pdf'

    ini_set('memory_limit', '256M');
    $dataBase64 = base64_encode(file_get_contents($src));

    $html = "<!DOCTYPE html>
    <html lang='en'>
    <head>
        <meta charset='UTF-8'>
        <title>Visor de PDF</title>
        <style>
            html,body{
                margin: 0;
                padding: 0;
            }
            embed{
                height: 99vh;
            }
        </style>
    </head>
    <body>
        <embed src='data:application/pdf;base64,$dataBase64' width='100%' type='application/pdf'>
    </body>
    </html>";

    echo $html;

Espero sea de utilidad. Un Saludo!


text:
Q: Groovy - Grab - download failed I have a fresh installation of Groovy 2.1.4 and I'd like to create a script that uses HTTP builder.
I've added the following line at the top of the script:
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.6')

When I run the script in GroovyConsole, I get the following error:
1 compilation error:

Exception thrown
VI 01, 2013 12:15:39 ODP. org.codehaus.groovy.runtime.StackTraceUtils sanitize

WARNING: Sanitizing stacktrace:

java.lang.RuntimeException: Error grabbing Grapes -- [download failed: commons-logging#commons-logging;1.1.1!commons-logging.jar]

    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)

    ... (aso) ...

java.lang.RuntimeException: Error grabbing Grapes -- [download failed: commons-logging#commons-logging;1.1.1!commons-logging.jar]

When I run the following command on the Windows command line:
grape -V resolve org.codehaus.groovy.modules.http-builder http-builder 0.6

I get the same error, i.e.:
:: problems summary ::
:::: WARNINGS
        [NOT FOUND  ] commons-logging#commons-logging;1.1.1!commons-logging.jar (0ms)

    ==== localm2: tried

      file:C:\Documents and Settings\Administrator/.m2/repository/commons-logging/commons-logging/1.1.1/commons-logging-1.1.1.jar

:: USE VERBOSE OR DEBUG MESSAGE LEVEL FOR MORE DETAILS
Error in resolve:
    Error grabbing Grapes -- [download failed: commons-logging#commons-logging;1.1.1!commons-logging.jar]

When I try to resolve commons-logging directly, via the following command:
grape -V resolve commons-logging commons-logging 1.1.1

I get the same error, i.e. not found.
When I instead try to download the latest version, i.e. 1.1.3, via the appropriate command, it works. But even after that, resolving the http-client still fails.
Where's the problem?

A: Try deleting ~/.m2 directory and also ~/.groovy/grapes directories.
It worked for me.

A: It looks like your Grape settings are set only to look in your local .m2 directory for the library. Check your grapeConfig.xml configuration file. (If you don't have one, you can create it--it should go in the same directory where your groovysh.history and grapes cache directory are created by Groovy.) You can copy the example file shown on the Groovy Grape reference page.
If that doesn't help, I would try deleting your grapes cache directory and try it again.

A: My problem was, groovy (v2.4.8) was looking in the maven repository fist (~/.m2/repository/) and finding the pom file but not finding the associated artifact/JAR. Instead of just moving on to the next resolver, which would have succeeded, it just gives up. The workaround would be to remove the pom file, the specific directory cache, or just temporarily rename the repository and run groovy again as other suggested. Or you could try to manually add it to the repository. But these are just temporary and you'll likely run into the issue again if you clear your groovy cache or with another dependency.
To troubleshoot this issue you can turn on verbose logging and try to manually install the dependency. So if your error is something like:
java.lang.RuntimeException: Error grabbing Grapes -- [download failed: commons-logging#commons-logging;1.1.1!commons-logging.jar, download failed: commons-codec#commons-codec;1.6!commons-codec.jar, download failed: commons-lang#commons-lang;2.4!commons-lang.jar]
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)

Which means your dependency is commons-logging-1.1.1.jar. You can run:
grape -V install commons-logging commons-logging  1.1.1
What ended up solving the problem for me was overriding the default configuration and setting usepoms="false" in the localm2 resolver. It works in my case because I have the pom but not the JAR, so since Ivy isn't considering the POM now and the JAR was never there to begin with, it goes onto the next resolver which does find it. So in summary:

*

*Create this file: ~/.groovy/grapeConfig.xml

*With these contents:

<ivysettings>
  <settings defaultResolver="downloadGrapes"/>
  <resolvers>
 <chain name="downloadGrapes" returnFirst="true">
   <filesystem name="cachedGrapes">
  <ivy pattern="${user.home}/.groovy/grapes/[organisation]/[module]/ivy-[revision].xml"/>
  <artifact pattern="${user.home}/.groovy/grapes/[organisation]/[module]/[type]s/[artifact]-[revision](-[classifier]).[ext]"/>
   </filesystem>
   <ibiblio name="localm2" root="file:${user.home}/.m2test/repository/" checkmodified="true" changingPattern=".*" changingMatcher="regexp" m2compatible="true" usepoms="false"/>
   <ibiblio name="jcenter" root="https://jcenter.bintray.com/" m2compatible="true"/>
   <ibiblio name="ibiblio" m2compatible="true"/>
 </chain>
  </resolvers>
</ivysettings>

I was tempted not to use the maven 2 cache at all, but if I removed the line, I got errors about not being able to find "localm2". Although updating it to point to fictitious directory worked.

A: Deleting .m2 and grapes did not resolve the issue for me as when they were repopulated, the jar was not being downloaded.  In my case, I was missing xml-apis-1.3.04.jar
I eventually resolved the issue by manually downloading the jar file and copying it into ~/.m2/repository/xml-apis/xml-apis/<version>
Hopefully this is useful if simply deleting the directories isn't working.

A: this might help someone down the line as i faced similar issue in windows
java.lang.RuntimeException: Error grabbing Grapes -- [download failed: commons-collections#commons-collections;3.2.2!commons-collections.jar]
the required jar above was not being downloaded in C:/Users/%USER%/.groovy/grapes/common-collections/jars/ folder.
so manually downloaded the required version from https://jar-download.com/
and added in the corresponding folder

A: Not quite the same case as the question, adding it in case someone finds himself in a similar case with me where I did not have any direct access on the machine to check the grapeConfig.xml configuration file, as suggested by the accepted answer. What worked for me was to configure a grab resolver.
I did something similar with what is stated in the documentation and it worked (documentation link):
@GrabResolver(name='restlet', root='http://maven.restlet.org/')
@Grab(group='org.restlet', module='org.restlet', version='1.1.6')

A: I solved a similar issue by using a newer version of commons-codec:commons-codec in groovy script using the @Grab annotation:
@Grapes([
  @Grab('org.slf4j:slf4j-simple:1.7.25'),
  @Grab('commons-codec:commons-codec:1.14'),
  @Grab('io.github.http-builder-ng:http-builder-ng-apache:1.0.4')
])

A: you need create ~/.groovy/grapeConfig.xml
coments
<ivysettings>
  <settings defaultResolver="downloadGrapes"/>
  <resolvers>
    <chain name="downloadGrapes" returnFirst="true">
      <filesystem name="cachedGrapes">
        <ivy pattern="${user.home}/.groovy/grapes/[organisation]/[module]/ivy-[revision].xml"/>
        <artifact pattern="${user.home}/.groovy/grapes/[organisation]/[module]/[type]s/[artifact]-[revision](-[classifier]).[ext]"/>
      </filesystem>
      <ibiblio name="localm2" root="file:${user.home}/.m2test/repository/" checkmodified="true" changingPattern=".*" changingMatcher="regexp" m2compatible="true" usepoms="false"/>
      <ibiblio name="jcenter" root="https://jcenter.bintray.com/" m2compatible="true"/>
      <ibiblio name="ibiblio" m2compatible="true"/>
    </chain>
  </resolvers>
</ivysettings>

A: I had a similar error when using Groovy + Java 7.
The error from groovy was:

General error during conversion: Error grabbing Grapes -- [unresolved dependency: com.microsoft.sqlserver#mssql-jdbc;6.4.0.jre7: not found]

When trying the

grape -V resolve com.microsoft.sqlserver mssql-jdbc 6.4.0.jre7

command i had these errors:

*

*java.net.SocketException: Connection reset

*javax.net.ssl.SSLException: Received fatal alert: protocol_version

The way to fix this was adding the -Dhttps.protocols=TLSv1.2 parameter:

grape -Dhttps.protocols=TLSv1.2 -V resolve com.microsoft.sqlserver mssql-jdbc 6.4.0.jre7

Then the package is downloaded and i can use it from Groovy


text:
Q: Chrome Syncing Old Data I have not synced any of my Bookmarks to my Google Account in a year or so. If I sign-in to Chrome will it automatically sync and overwrite all the data i currently have with old the data on my Google Account and if so how can I work around it?

A: synching is not overwriting.
Yes, it would sync, but that means it will merge them together, so you would end with the old and the new links. You can then delete from the list the old stuff if you don't want it anymore.
If you happen to have modified a link since the last sync a year ago, the newer one will prevail.


text:
Q: curl: (7) Failed to connect to get.sdkman.io port 443: Network is unreachable I am trying to install sdkman on my mac. I simply copy and paste the curl command that is given on the website "curl -s "https://get.sdkman.io" | bash" but when i do I keep getting the error message mentioned above in the title.
I remove the -s to get the error message so the command looks like this
"curl "https://get.sdkman.io" | bash"
can anyone help?