text:
Q: Browsersync keeps reloading I have Gulp + Browsersync working with Wordpress.
Everything was working well, reloading every time I change files.
But since yesterday only, Browsersync keeps reloading without any reason.
I didn't made any changes on my gulpfile. I tried reverting to a former commit from 2 days ago, same thing. I don't know where it comes from.
Here's my repo.
I tried :

*

*downgrading browsersync to 2.24.4 from this post

*adding this to gulp :

   socket: {
      clients: {
               heartbeatTimeout: 60000
            }
        },

Here are my files.
gulpfile.babel.js
import { src, dest, watch, series, parallel } from 'gulp';
import yargs from 'yargs';
import sass from 'gulp-sass';
import cleanCss from 'gulp-clean-css';
import gulpif from 'gulp-if';
import postcss from 'gulp-postcss';
import sourcemaps from 'gulp-sourcemaps';
import autoprefixer from 'autoprefixer';
import imagemin from 'gulp-imagemin';
import del from 'del';
import webpack from 'webpack-stream';
import named from 'vinyl-named';
import browserSync from 'browser-sync';
import zip from 'gulp-zip';
import info from './package.json';
import replace from 'gulp-replace';
import wpPot from 'gulp-wp-pot';
import tailwindcss from 'tailwindcss';
// import purgeCss from 'gulp-purgecss';
const PRODUCTION = yargs.argv.prod;

export const clean = () => del(['dist']);

export const styles = () => {
    return (
        src('src/scss/app.scss')
            .pipe(gulpif(!PRODUCTION, sourcemaps.init()))
            .pipe(sass().on('error', sass.logError))
            .pipe(postcss([tailwindcss('./tailwind.config.js')]))
            .pipe(gulpif(PRODUCTION, postcss([autoprefixer])))
            .pipe(gulpif(PRODUCTION, cleanCss({ compatibility: 'ie8' })))
            // .pipe(
            //  gulpif(
            //      PRODUCTION,
            //      purgeCss({
            //          content: ['**/*.php']
            //      })
            //  )
            // )
            .pipe(gulpif(!PRODUCTION, sourcemaps.write()))
            .pipe(dest('dist/css'))
            .pipe(server.stream())
    );
};

export const images = () => {
    return src('src/images/**/*.{jpg,jpeg,png,svg,gif}')
        .pipe(gulpif(PRODUCTION, imagemin()))
        .pipe(dest('dist/images'));
};

export const copy = () => {
    return src(['src/**/*', '!src/{images,js,scss}', '!src/{images,js,scss}/**/*']).pipe(
        dest('dist')
    );
};

export const watchForChanges = () => {
    watch('src/scss/**/*.scss', styles);
    watch('src/images/**/*.{jpg,jpeg,png,svg,gif}', series(images, reload));
    watch(['src/**/*', '!src/{images,js,scss}', '!src/{images,js,scss}/**/*'], series(copy, reload));
    watch('src/js/**/*.js', series(scripts, reload));
    watch('**/*.php', reload);
};

export const scripts = () => {
    return src(['src/js/bundle.js'])
        .pipe(named())
        .pipe(
            webpack({
                module: {
                    rules: [
                        {
                            test: /\.js$/,
                            use: {
                                loader: 'babel-loader',
                                options: {
                                    presets: ['@babel/preset-env']
                                }
                            }
                        }
                    ]
                },
                mode: PRODUCTION ? 'production' : 'development',
                devtool: !PRODUCTION ? 'inline-source-map' : false,
                output: {
                    filename: '[name].js'
                }
            })
        )
        .pipe(dest('dist/js'));
};

/***** Generating a POT file *****/

export const pot = () => {
    return src('**/*.php')
        .pipe(
            wpPot({
                domain: 'boosters',
                package: info.name
            })
        )
        .pipe(dest(`languages/${info.name}.pot`));
};

/***** Compress theme into a ZIP file after renaming _themename *****/

export const compress = () => {
    return src([
        '**/*',
        '!node_modules{,/**}',
        '!bundled{,/**}',
        '!src{,/**}',
        '!.babelrc',
        '!.gitignore',
        '!gulpfile.babel.js',
        '!package.json',
        '!package-lock.json'
    ])
        .pipe(
            gulpif(
                // prevent bug if there are zip files inside the theme
                file => file.relative.split('.').pop() !== 'zip',
                replace('boosters', info.name)
            )
        )
        .pipe(zip(`${info.name}.zip`))
        .pipe(dest('bundled'));
};

/****** BrowserSync ******/

const server = browserSync.create();
export const serve = done => {
    server.init({
        proxy: 'localhost:8888/boosters', // put your local website link here
        snippetOptions: {
            ignorePaths: 'boosters/wp-admin/**'
        },
        ghostMode: false
        // socket: {
        //  clients: {
        //      heartbeatTimeout: 60000
        //  }
        // },
        // logLevel: 'debug',
        // logFileChanges: true,
        // logConnections: true
    });
    done();
};
export const reload = done => {
    server.reload();
    done();
};

/****** Series & Parallel Scripts ******/

export const dev = series(clean, parallel(styles, images, scripts, copy), serve, watchForChanges);
export const build = series(clean, parallel(styles, images, scripts, copy), pot, compress);
export default dev;

package.json
{
    "name": "boosters",
    "version": "1.0.0",
    "description": "A Wordpress website for Boost.rs by DoubleCat Studio",
    "main": "gulpfile.babel.js",
    "scripts": {
        "start": "gulp",
        "build": "gulp build --prod"
    },
    "repository": {
        "type": "git",
        "url": "git+ssh://git@github.com/indaviande/boosters.git"
    },
    "author": "Vianney Bernet",
    "license": "ISC",
    "bugs": {
        "url": "https://github.com/indaviande/boosters/issues"
    },
    "browserslist": [
        "last 4 version",
        "> 1%",
        "ie 11"
    ],
    "homepage": "https://github.com/indaviande/boosters#readme",
    "devDependencies": {
        "@babel/core": "^7.4.3",
        "@babel/preset-env": "^7.4.3",
        "@babel/register": "^7.4.0",
        "autoprefixer": "^9.5.1",
        "babel-loader": "^8.0.5",
        "browser-sync": "^2.26.7",
        "del": "^4.1.0",
        "gulp": "^4.0.0",
        "gulp-clean-css": "^4.0.0",
        "gulp-if": "^2.0.2",
        "gulp-imagemin": "^5.0.3",
        "gulp-postcss": "^8.0.0",
        "gulp-replace": "^1.0.0",
        "gulp-sass": "^4.0.2",
        "gulp-sourcemaps": "^2.6.5",
        "gulp-wp-pot": "^2.3.5",
        "gulp-zip": "^4.2.0",
        "tailwindcss": "^1.0.4",
        "vinyl-named": "^1.1.0",
        "webpack-stream": "^5.2.1",
        "yargs": "^13.2.2"
    },
    "dependencies": {
        "tar": ">4.4.7"
    }
}

A: Browsersync has a log that you can inspect to see which files are being changed that trigger the reload.  You can also increase specificity of what you're watching/ignoring.  Start off small and gradually increase your glob paths until you can see reloads on all changes.
server.init({
  logLevel: 'debug',
  files: [
    'wp-content/themes/**/*.css',
    'wp-content/themes/**/*.js',
    'wp-content/themes/**/*.php',
  ],
  ignore: [
    'folder-to-ignore/**/*.*'
  ]
});


text:
Q: Как добавить дату и время в таблицу mysql Написал вот такой код:
QString datetimeMysql = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
qDebug() << datetimeMysql;
if(mysql_query(&mysql, "INSERT INTO TableEventBalancer VALUES ('1','datetimeMysql', 'Подача основного питания');"))
{
    qDebug() << mysql_error(&mysql);
}

В столбце datetimeMysql нуль.
Как добавить время datetimeMysql в столбец таблицы?

A: не надо генерить currentDateTime() в коде. генерите его прямо в запросе:
INSERT INTO TableEventBalancer VALUES ('1',NOW(), 'Подача основного питания');

INSERT INTO TableEventBalancer VALUES ('1',CURDATE(), 'Подача основного питания');

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to sum jquery map values I have map function to get selected checkboxes and I need to sum values of this map but I get NaN
Code
var prices = $("input:checkbox:checked").map(function(){
  return $(this).val();
}).get();

var number = prices;
var nf = new Intl.NumberFormat('en-US', {
  maximumFractionDigits:0,
  minimumFractionDigits:0
});
var formattedNumber = nf.format(number);

$('.paybutton').append(''+ nf.format(prices)+'');

console.log(prices); returns data below when i play with check boxes so i guess my map is OK.
Array [ "5467457" ]
Array [ "57558", "5467457" ]
Array [ "57558" ]
Array []

In other hand my appended data is like:
5,467,457NaN57,55805,467,4570

And it keeps this way as long as i play with check boxes.
Question

*

*How can I have sum of my function in + nf.format(prices)+?

A: You are passing an array to nf.format(number);
instead do this :
function add(a, b) {
    return a + b;
}

var number = prices.reduce(add, 0);

and then do nf.format(number);

A: Your approach seems to be correct, but I must say jquery map works in a weird way, those return Array's had me thinking for a while but then I realised it was map which was returning values in array and hence multiple arrays. I was able to get the sum of checked checkboxes using plain javascript and Mihir suggestion. It looks like follows
const checkboxes = document.querySelectorAll('input[type=checkbox]');

// this could have been avoided if NodeList had map method
const prices = [];

checkboxes.forEach(chkbox => prices.push(chkbox.checked && Number(chkbox.value)));

const totalSum = prices.reduce((a, b) => a + b, 0);

console.log(totalSum)

I tested it few times seems to be working fine

A: Give this a try:
var prices = $("input:checkbox:checked").map(function(){
  return $(this).val();
}).get();

function formatCurr(arr){
  var n = 0;
  if(arr.length){
    $.each(arr, function(k, v){
      n += parseFloat(v);
    });
  }
  return n.toLocaleString('en-US');
}

$('.paybutton').append(''+ formatCurr(prices) +'');

May not be the only way to do this. I suspect this is one of a few. Input is [ "5467457" ], Output is 5,467,457.
Working Example

$(function() {
  function formatCurr(arr) {
    var n = 0;
    if (arr.length) {
      $.each(arr, function(k, v) {
        n += parseInt(v);
      });
    }
    return n.toLocaleString('en-US');
  }
  console.log(formatCurr(["5467457"]));
  console.log(formatCurr(["57558", "5467457"]));
  console.log(formatCurr(["57558"]));
  console.log(formatCurr(["9876543210"]));
  console.log(formatCurr(["1001", "2002", "3003", "4004", "5005"]));
});

Hope it helps.


text:
Q: What is the best practice for changing the functionality of a Rails controller, while keeping legacy code and the route intact? I have a web service that returns some XML data using a RESTful API.  I am going to implement a new database with completely different controller code, that will be in effect after some date.  But any WS call for the old data should still use the old DB.
Right now, part of the URL contains the date.  I am parsing this at the beginning of the controller and then going off to an old or new function.
def web_service_action

  #shared code between old and new methods
  @some_instance_variables = ...

  # check the date and fork appropriately
  if use_new?
    web_service_action_new
  else
    web_service_action_old
  end

  def use_new?
    date_match = params[:id_string].match(/^.*([0-9]{8})$/)
    matched_date = date_match[1]
    date = Time.local(date_match[0,4],date_match[4,2],date_match[6,2])
    if date >= DATE_CONSTANT
      return true
    else
      return false
    end
  end

end

I'm wondering if there is a clever way to do this with a before_filter or a conditional in the routes file somehow?
Additional information:  I am using an old version of Rails (2.3.x) and the new method is a total rewrite, not an incremental change.

A: To start, I recommend watching Ryan Bates' railscast on REST API Versioning. He explains very well how to manage API changes in your application while maintaining BC.


text:
Q: Why systemd says that postfix failed, while postfix works perfectly well We are using the postfix mta on a debian server. Everything seems to work well (mail is sent and received), except that systemd says that the postfix@- service failed:
# systemctl restart postfix@-
Job for postfix@-.service failed because the control process exited with error code.
See "systemctl status postfix@-.service" and "journalctl -xe" for details.

# systemctl --failed
  UNIT              LOAD   ACTIVE SUB    DESCRIPTION
● postfix@-.service loaded failed failed Postfix Mail Transport Agent (instance -)

Here is the end of systemd configuration file postfix@.service:
...
[Service]
Type=forking
GuessMainPID=no
ExecStartPre=/usr/lib/postfix/configure-instance.sh %i
ExecStart=/usr/sbin/postmulti -i %i -p start
ExecStop=/usr/sbin/postmulti -i %i -p stop
ExecReload=/usr/sbin/postmulti -i %i -p reload

I tried running configure-instance.sh and postmulti by hand, they all return status 0

*

*Debian version = bullseye

*Postfix version = 3.5.6

Thanks for your help !
EDIT To be more precise, there are two systemd services: postscript and postscript@-
The following sequence is confusing for me:
root@pic2s:/var/log# postfix status
...
postfix/postfix-script: the Postfix mail system is running: PID: 3341207

root@pic2s:/var/log# systemctl status postfix
● postfix.service - Postfix Mail Transport Agent
     Loaded: loaded (/lib/systemd/system/postfix.service; enabled; vendor preset: enabled)
     Active: active (exited) since Sun 2022-06-05 10:13:00 CEST; 1 day 5h ago
    Process: 3117705 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
   Main PID: 3117705 (code=exited, status=0/SUCCESS)
        CPU: 6ms

root@pic2s:/var/log# systemctl stop postfix
root@pic2s:/var/log# postfix status
...
postfix/postfix-script: the Postfix mail system is running: PID: 3341207

So, to summarize:

*

*The postfix systemd service is not marked as failed

*When I stop the systemd service, postfix is NOT stopped

*The default instance is marked as failed by systemd


text:
Q: How do I make Emacs start without so much fanfare? Every time I start Emacs I see a page of help text and a bunch of messages suggesting that I try the tutorial.  How do I stop this from happening?

A: You can customize message in minibuffer therefore remove fanfare:
;; Hide advertisement from minibuffer
(defun display-startup-echo-area-message ()
  (message ""))

A: Emacs has a couple of variables which inhibit these actions.  If you edit your emacs control file (.emacs) and insert the following:
;; inhibit-startup-echo-area-message MUST be set to a hardcoded
;; string of your login name
(setq inhibit-startup-echo-area-message "USERNAME")
(setq inhibit-startup-message t)

that should solve your problem.  They basically set the inhibit parameters to true to prevent the behavior you want to get rid of.

A: Put the following in your personal init file (ususally ~/.emacs.el):
(setq inhibit-startup-message t)

(Or (setq inhibit-startup-screen t) in with older Emacs versions.)
You can also turn off the message "For information about GNU Emacs and the GNU system, type C-h C-a." in the echo with the variable inhibit-startup-echo-area-message, but it is not enough to set it to t; you must set it to your username.  See the documentation for inhibit-startup-echo-area-message.

A: Put the following in your .emacs:

(setq inhibit-startup-message t)
(setq inhibit-startup-echo-area-message t)

A: If your init file is byte-compiled, use the following form instead:
(eval '(setq inhibit-startup-echo-area-message "YOUR-USER-NAME"))

A: Add the below to your init file
(setq inhibit-startup-message t
inhibit-startup-echo-area-message t)


text:
Q: When to divide data into training & test set in logistic regression? I am using Logistic Regression in a low event rate situation.
Overall universe: 46,000
Events: 420
Conventional logistic regression models divide the data into training and test sets and compute the error rates.  The final coefficients and threshold levels are chosen and a model is created.
OTH, I'm just trying to prove that so and so coefficient is significant and has positive association with the event in study.  I'm not developing a model as of now.  I don't focus on error rates (too many true negatives!) and chose my threshold level ~ hit rate.
Should I consider dividing my universe into 2 samples, the conventional way?  With such a low event rate, I'm worried that doing this to bias my coeff. estimates.

A: I do not think you need to divide the set if you are interested in the significance of a coefficient and not in prediction.  Cross validation is used to judge the prediction error outside the sample used to estimate the model.  Typically, the objective will be to tune some parameter that is not being estimated from the data.
For example, if you were interested in prediction, I would advise you to use regularized logistic regression.  This is similar to logistic regression, except for the fact that coefficients (as a whole) are biased towards 0.  The level of bias is determined by a penalty parameter that is typically fine tuned via cross validation.  The idea is to choose the penalty parameter that minimizes the out of sample error (which is measured via cross validation.)  When building a predictive model, it is acceptable (and desirable) to introduce some bias into the coefficients if said bias causes a much larger drop in the variance of the prediction (hence, resulting in a better model for predictive purposes.)
What you are trying to do is inference.  You want an unbiased estimate of a coefficient (supposedly to judge the effect that changing one variable may have on another).  The best way to obtain this is to have a well specified model and a sample as large as possible.  Hence, I would not split the sample.  If you are interested in sampling variation, you should try a bootstrap or a jacknife procedure instead.
EDIT:
Short version: You want an unbiased model.  Cross validation can help you find a good predictive model, which are often biased.  Hence, I do not think cross validation is helpful in this situation.

A: (1) Split sample is likely not the conventional way to approach this problem. Obviously conventions differ by fields of research and subject area. But I don't think it is unreasonable to say that bootstrapping for optimism would be the standard here, and I think you would have to justify in some detail if you were planning on using alternative methods.
(2) You're right, you might most probably don't need to validate model if you're only planning on looking at the association/coefficients. But you should know that the coefficients (and their p-values) are only valid for the pre-specified model. If you've included splines, variable selection etc. these values are inflated and might well have limited meaning. The validation process attempts to estimate the over-fitting of the model - the degree of optimism. It validates the model building process, not the model. If there is no model building - only a pre-specified model - not that useful for you. If there is model building - not unhelpful to have some estimate of how much it lead to over-fitting.

A: Why not use cross validation, maybe with a higher X, like 10X. LOOCV might also be interesting but that could go really slowly.
You could alternatively do some kind of more fancy custom CV where you leave one of the 420 positive events out, and the same proportion of the negative events (1/420 of them to preserve the relative proportion?) out at a given round. You would then have 420 CV iterations to calculate stats on, and you only give up training on a single positive sample at each round. That way you can get away with smaller training/testing splits. You could modify that to have fewer CV iterations if 420 would be too slow, maybe leave out 5 positives at a time, and 5/420 negatives?


text:
Q: Forks and Pipes in c++ I am using 4 processes in which A's output will goto A1 and A1's output will go to A2 and A2 output will come out in the console. Even A1 output also will comeout in console.

*

*1st program - A C++ program which is a random generator that will generate the output as per the requirements of A1's input and also act as a collector for stdout from the sub processes

*2nd program - Python script which will take the input of A's output and will generate the output as per the requirements of A2 and the output of A1 should print in the console.

*3rd program - cpp file which will take the input of A1's output and will give the output and print in the control.

I am using 2 pipes - ABtoC for A to A1,  A1toA2 for A1toA2.
Here A to A1 is working and A1's output is printing in the console. But the issue is A1's output is not going to A2's input. Here is the below code I am using for this operation.
#include <vector>

#include <iostream>
#include <signal.h>
#include <unistd.h>
#include <string>
#include <sstream>

/// Entry point of process B
int procB(void) {
  // Process B writing to C
  while (!std::cin.eof()) {
    // read a line of input until EOL and store in a string
    std::string line;
    std::getline(std::cin, line);
    if (line.size() > 0)
      std::cout << line << std::endl;
  }
  std::cout << std::endl;
  return 0;
}

int main(int argc, char** argv) {
  std::vector<pid_t> kids;
  // create a pipe
  int ABtoC[2];
  pipe(ABtoC);

  int A1toA2[2];
  pipe(A1toA2);

  pid_t child_pid;
  child_pid = fork();
  if (child_pid == 0) {
    // redirect stdout to the pipe
    dup2(ABtoC[1], STDOUT_FILENO);
    close(ABtoC[0]);
    close(ABtoC[1]);
    close(A1toA2[0]);
    close(A1toA2[1]); // Close this too!

    execv("./rgen", argv);
  } else if (child_pid < 0) {
    std::cerr << "Error: could not fork\n";
    return 1;
  }

  kids.push_back(child_pid);

  child_pid = fork();
  if (child_pid == 0) {
    // redirect stdin from the pipe
    dup2(ABtoC[0], STDIN_FILENO);
    close(ABtoC[1]);
    close(ABtoC[0]);
    close(A1toA2[0]);
    close(A1toA2[1]);

    argv[0] = (char *)"python3";
      argv[1] = (char *)"a1ece650.py";
      argv[2] = nullptr;

    dup2(A1toA2[1], STDOUT_FILENO);
    close(A1toA2[1]);
    close(A1toA2[0]);
    close(ABtoC[0]);
    close(ABtoC[1]);
    execvp("python3", argv);

  } else if (child_pid < 0) {
    std::cerr << "Error: could not fork\n";
    return 1;
  }

kids.push_back(child_pid);

  child_pid = fork();
  if (child_pid == 0) {
    // redirect stdin from the pipe
    dup2(A1toA2[0], STDIN_FILENO);
    close(A1toA2[1]);
    close(A1toA2[0]);
    close(ABtoC[0]);
    close(ABtoC[1]);

    execv("./ece650-a2", argv);

  } else if (child_pid < 0) {
    std::cerr << "Error: could not fork\n";
    return 1;
  }

  kids.push_back(child_pid);
  child_pid = 0;

  // redirect stdout to the pipe
  dup2(A1toA2[1], STDOUT_FILENO);
  close(A1toA2[0]);
  close(A1toA2[1]);
  close(ABtoC[0]);
  close(ABtoC[1]);

  // start process B
  int res = procB();

  // send kill signal to all children
  for (pid_t k : kids) {
    int status;
    kill(k, SIGTERM);
    waitpid(k, &status, 0);
  }

  return res;
}

Insert ASCII graphics below:
+--------------+   +-----+             +-----+                +-----+
|Fork and Pipe| --  A.cpp stdout--stdin A1.py --stdout--stdin  A2.cpp
+--------------+.  +-----+             +-----+                +-----+
```                                       |                      |
                                          V                      V
                                        stdout                  stdout

A: When you launch A1, you are closing A1toA2[1] and then after that trying to dup it into stdout.  Do all of the dups first, and then close what you don't need.


text: Q: How to write equations in a two column document I have been wanting to convert my math notes into a two column document since there is lots of wasted space currently. When I try to do this using the multicols environment from the multicol package, some of my longer new line equations run into the second column from the first and overlap with text in the other column. I was wondering if there is any way to fix this without having to break up the equations into several lines manually?


text:
Q: Why does this async function not return anything? I have a function that needs to run when my app starts. It basically makes several API calls to fetch the user's information, count its messages and subscribe to a socket channel.
It is made with React-query. But it doesn't perform any API call. The function _getUserInformations is never triggered and the network tab of my inspector remains void.
The server has no issues and the routes work. Here is the code:
export default function App() {
  useEffect(() => {
    initializeUser();
  }, []);
  const user = userStore();

  return routes + app
  );
}

export const initializeUser = () => {
  try {
    const res = await getUserInformations();
    const user = res.data.user;
    updateUser(user);
    const { unreadConversations } = await hasUnreadConversations(user._id);
    updateunreadConversations(unreadConversations);
    getNotifications(user._id);
  }
  catch (err) {
    return null;
  }
};

const _getUserInformations = async () => {
  try {
    const userToken = await api.get("/user-informations", {
      withCredentials: true,
    });
    return userToken;
  } catch (err) {
    throw new Error(err.message || "error.unknown");
  }
};

const getUserInformations: UserService["getUserInformations"] = () => {
  const { data } = useQuery("getUserInfos", () => _getUserInformations(), {
    cacheTime: 1000 * 60 * 60 * 24, // 24 hours
  });
  return data.data.user;
};

What is wrong here?
Here is also a sandbox that reproduces the same issue with PokeApi: https://codesandbox.io/s/gifted-hill-tei88?file=/src/App.js
_getPokemon (that imitates _getUserInformations) is never called as well...

A: Hooks should only be used in a functional component.
For example in your codesandbox codes, if you use the following, it will work.
export default function App() {
  const { data, isError } = useQuery("getpokemon", () => _getPokemon());
  console.log('data', data) //you can see the data printed.
  React.useEffect(() => initialize(), []);

  if (!data && !isError) return <Loading /> // Bonus Tip - data is fetching if both data and isError is undefined.

  return
hello
;
}

https://reactjs.org/docs/hooks-rules.html

Don't call Hooks from regular JavaScript functions. Instead, you can:
✅ Call Hooks from React function components.
✅ Call Hooks from custom
Hooks (we'll learn about them on the next page).

Also...

Only Call Hooks at the Top Level Don't call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top
level of your React function, before any early returns. By following
this rule, you ensure that Hooks are called in the same order each
time a component renders. That's what allows React to correctly
preserve the state of Hooks between multiple useState and useEffect
calls. (If you're curious, we'll explain this in depth below.)


text:
Q: Angularjs filter through array of object literals I am new to angular js so please forgive me for this basic question.
I have an array of object literals and I want to add filter in angular js according to particular field type.
Array of object literals:
 var todos= [{text: 'To-DO1', done: false,group:'Group1' }, {text: 'To-do2', done: false, group:'Group2' } ];

I am using this code:
<select  data-ng-model="selectOption" data-ng-options="item as item.gtype for item in items"> </select>

Above filter is not working
For populating the select I am using :
$scope.items = [
  {gtype:'Group1'},
  {gtype:'Group2'},`enter code here`
  {gtype:'Group3'},
  {gtype:'Group4'},
  {gtype:'Group5'}
];

Could someone please help me through ?

A: The problem is with the track by $index. The correct place for it is at the end of the expression, after the filter (see ngRepeat documentation)...

Live Demo
Edit: As requested, here's an updated fiddle to show an alternate message if filter produces nothing...
Live Demo


text:
Q: Upgraded MonoGame and now I can't get my shader to compile I upgraded my monogame to the latest version.  When building the shader in the pipeline tool at first I got the error Vertex shader 'SpriteVertexShader' must be SM 4.0 level 9.1 or higher! So I changed ps_2_0 to ps_4_0_level_9_1 but now I'm getting the error:
error X3004: undeclared identifier 'SecondPassTextureSampler'
Anybody have an idea on how to fix this issue?
#include "Macros.fxh"

texture Bitmap;

sampler2D FirstPassTexture = sampler_state{
    Texture = (Bitmap);
    MagFilter = Linear;
    MinFilter = Linear;
    AddressU = Clamp;
    AddressV = Clamp;
};

sampler2D SecondPassTexture = sampler_state{
    Texture = (Bitmap);
    MagFilter = Linear;
    MinFilter = Linear;
    AddressU = Clamp;
    AddressV = Clamp;
};

#define KERNEL_RADIUS 7
#define KERNEL_WIDTH (2*KERNEL_RADIUS + 1)

// Uniforms
BEGIN_CONSTANTS
    float kernel[KERNEL_WIDTH];
    float2 offsets[KERNEL_WIDTH];

MATRIX_CONSTANTS
    float4x4 MatrixTransform    _vs(c0) _cb(c0);
END_CONSTANTS

struct VSOutput
{
    float4 position     : SV_Position;
    float4 color        : COLOR0;
    float2 texCoord     : TEXCOORD0;
};

VSOutput SpriteVertexShader(    float4 position : SV_Position,
                                float4 color    : COLOR0,
                                float2 texCoord : TEXCOORD0)
{
    VSOutput output;
    output.position = mul(position, MatrixTransform);
    output.color = color;
    output.texCoord = texCoord;
    return output;
}

float4 gaussH(VSOutput input): SV_Target0
{
    float4 color = float4(0,0,0,0);
    for(int i = 0; i < KERNEL_WIDTH; ++i)
        color += SAMPLE_TEXTURE(SecondPassTexture, (input.texCoord + float2(offsets[i].x, 0.0) )) * kernel[i];
    return color * input.color;
}

float4 gaussV(VSOutput input): SV_Target0
{
    float4 color = float4(0.0,0.0,0.0,0);
    for(int i = 0; i < KERNEL_WIDTH; ++i)
        color += SAMPLE_TEXTURE(SecondPassTexture, (input.texCoord + float2(0.0, offsets[i].y) )) * kernel[i];
    return color * input.color;
}

float4 gaussVGlow(VSOutput input): SV_Target0
{
    float4 color = float4(1.0,1.0,1.0,0);
    for(int i = 0; i < KERNEL_WIDTH; ++i)
    {
        float alpha = SAMPLE_TEXTURE(SecondPassTexture, (input.texCoord + float2(0.0, offsets[i].y) )).a * kernel[i];
        color.a += alpha;
    }
    // This will make stripes on top of the glow
    /*
    float m = smoothstep(0.45, 0.55, 0.5*cos(25.0*atan2(input.texCoord.y-0.5, input.texCoord.x-0.5))+0.5) * 0.5 + 0.5;
    color.a *= m;
    */
    color.a = pow(color.a, 0.5);
    color.rgb *= color.a; // Yeah, you have to pre multiply your alpha -- either that or render with premultiply option
    return color * input.color;
}

technique Blur {
    pass p0 {
        VertexShader = compile vs_4_0_level_9_1 SpriteVertexShader();
        PixelShader = compile ps_4_0_level_9_1 gaussH();
    }
    pass p1 {
        VertexShader = compile vs_4_0_level_9_1 SpriteVertexShader();
        PixelShader = compile ps_4_0_level_9_1 gaussV();
    }
    pass p1Glow {
        VertexShader = compile vs_4_0_level_9_1 SpriteVertexShader();
        PixelShader = compile ps_4_0_level_9_1 gaussVGlow();
    }
}

Macros.fxh is: http://pastebin.com/y51kFfii

A: From the Monogame Forum:
You get an error because you use the macro SAMPLE_TEXTURE for sampling, but do not use the macro DECLARE_TEXTURE for declaring the texture.
If you want to use the macros in Macros.fxh then the texture needs to be named SecondPassTexture and the sampler needs to be named SecondPassTextureSampler. (Do not change the line where SAMPLE_TEXTURE is called.)
If you look at the macro (_Macro.fxh, line 31), the code
SAMPLE_TEXTURE(SecondPassTexture, (input.texCoord + float2(0.0, offsets[i].y) ))
expands to
SecondPassTexture.Sample(SecondPassTextureSampler, (input.texCoord + float2(0.0, offsets[i].y) ))
But in your case (original post) it should be
Bitmap.Sample(SecondPassTexture, (input.texCoord + float2(0.0, offsets[i].y) ))
Here is a simpler solution, you can try:
Just replace all SAMPLE_TEXTURE with tex2D. (Leave the samplers as in the original post.)


text:
Q: How reporting service store the password of SQL user when connect the data source? When we create the datasource in the reporting service, we need to assign the account to connect to that datasource, either windows, sql user.
If we choose sql user, we wonder that where is the password of sql user is stored. Or does it encrypt with any algorithm?
Can I refer to any official document regarding this issue?

A: The details are stored in the dbo.DataSource table. The Username and Password are stored in the UserName and Password columns respectively and are encrypted, as is the ConnectionString column. An end user would not be able to decrypt it, unless they obtained the decryption key used internally by SSRS.


text:
Q: Attribution muddled by Financing Partner In Google Analytics, under Conversion > Attribution > Attribution Model Comparison Tool, I am running into an attribution problem. Our e-commerce company has partnered with a financing company that allows visitors to purchase our product by financing with our partner. This requires our user to click a link that takes them from our purchase page, to our partner's page. After getting approved for financing, they are redirected to our page, and the purchase is completed.
This causes a problem in Google Analytics. To Google Analytics, it looks like our partner page is the referring media source, so many of our purchases show up under the source/medium of our financing partner. In reality, these people originally came from some other media source like Facebook, instagram or google.
Is there a way to bypass the traffic from this specific source/medium (our financing partner) so that I can see where these purchases originated from?

A: In this scenario, you'd probably want to add the partner domain to the Referral Exclusion List. https://support.google.com/analytics/answer/2795830
Note, there is something more sinister happening as well to your session counts. As the user returns with a new referrer,  meaning the source/medium/campaign changed during a session,  the previous sessions closes out and a new session is created. So this is ruining your session based metrics like pages/visit, time on site, etc... https://support.google.com/analytics/answer/2731565


text:
Q: How to create an Explorer window without Navigation Pane using Shell command Explore My app Folders Popup is using the command ComObjCreate("Shell.Application").Explore(strPath) to create a new Explorer window. I need a way to tell this new instance of Explorer to comply with the Navigation Pane setting decided by the user (to show or not show the pane) in previous Explorer windows.
Actually, this setting is not taken into account by default in the new instance created by the Shell command and users of my app who prefer to use Explorer without this navigation pane are annoyed to see it reappear when my app is opening a new Explorer. Is there any solution to this (except sending keys to the Explorer, what I prefer to avoid)?

A: Simpler is sometimes better ;)
The Run command isn't just for executables, it can also open non-executable files like images/documents (as long as their file type is associated) and especially folders:
myFolderPath = C:\Path\To\Folder
Run, %myFolderPath%

Generally, it makes sense to use built-in commands or functions if available, before incorporating ActiveX, COM objects or DLL calls; those should provide extra functionality, and not replace what AHK can do out of the box. That, of course, occasionally requires some digging into the docs, but it's worth it! AHK is one of the most well-documented automation scripting languages for Windows.


text:
Q: How to change template in Parent based on child route data in Angular So, imagine in a Angular 4 application there is a Parent component which has a router-outlet for child component.
Now how can we change something in Parent component (for example container around child component) based on route data of the child component ?
Tried setting via a service but get ExpressionChangedAfterItHasBeenCheckedError
Any thoughts appreciated.


text:
Q: How can I loop through an array, starting at an offset and looping round again? Newb question: I'm using a foreach loop to get items from an array.
I need to start looping at an offset number- (I'm using a $i variable to do this, no problem).
But when my foreach reaches the end of the array I want it to start going through the array again until it reaches the offset number.
I need to do this so I can have a user open any image in an artist's portfolio and have this image used as the first image presented in a grid of thumbnail icons , with all the other images subsequently populating the rest of the grid.
Any ideas?
Please bear in mind I'm new to PHP! :)
See below for an example of my current code...
       $i=0;
        $limit=50;// install this in the if conditional with the offset in it (below) to limit the number of thumbnails added to the page.
        $offset=$any_arbitrary_link_dependant_integer;

        foreach($portfolio_image_array as $k=>$image_obj){//$k = an integer counter, $image_obj = one of the many stored imageObject arrays.
            $i++;
            if ($i > $offset && $i < $limit) {// ignore all portfolio_array items below the offset number.
                if ($img_obj->boolean_test_thing===true) {// OK as a way to test equivalency?
                    // do something
                } else if ($img_obj->boolean_test_thing===false) { // Now add all the non-see_more small thumbnails:
                    // do something else
                } else {
                    // error handler will go here.
                }
            } // end of offset conditional

        }// end of add boolean_test_thing thumbnails foreach loop.
    };// end of add thumbnails loop.

A: A simple method is to use two separate numeric for loops, the first going from offset to end, and the second going from beginning to offset.
<?php
// Create an example array - ignore this line
$example = array(1,2,3,4,5,6);

$offset = 3;

// Standard loop stuff
$count = count($example);
for($i = $offset; $i < $count; $i++)
{
    echo $example[$i]."
";
}

for($i = 0; $i < $offset; $i++)
{
    echo $example[$i]."
";
}

?>

This is also almost certainly cheaper than doing multiple checks on every single element in the array, and it expresses exactly what you are trying to do to other programmers who look at this code - including yourself in 2 weeks time.
Edit: depending on the nature of the array, in order to use numeric keys you may first need to do $example = array_values($portfolio_image_array);.

A: $i = 0;
$limit = 50;
$offset = $any_arbitrary_link_dependant_integer;
$count = count($portfolio_image_array);
        foreach($portfolio_image_array as $k=>$image_obj){//$k = an integer counter, $image_obj = one of the many stored imageObject arrays.
        $i++;
        if ($i > $offset && $i < $limit && $i < ($count - $offset)) {// ignore all portfolio_array items below the offset number.
            if ($img_obj->boolean_test_thing===true) {// OK as a way to test equivalency?
                // do something
            } else if ($img_obj->boolean_test_thing===false) { // Now add all the non-see_more small thumbnails:
                // do something else
            } else {
                // error handler will go here.
            }
        } // end of offset conditional

    }// end of add boolean_test_thing thumbnails foreach loop.
};

Only thing I added was a $count variable.
Edit: If your array starts at 0 I would suggest you put the $i++; at the end of your foreach loop.

A: Using Answer Question to force StackOverflow to let me post a decent length of text!
OK @Mark Walet et al, not sure how to post correctly on this forum yet but here goes. I got the issue sorted as follows:
$i=0;
$offset=$image_to_display_number;
    $array_length = count($portfolio_image_array);

    // FIRST HALF LOOP:
    foreach($portfolio_image_array as $k=>$img_obj){// go through array from offset (chosen image) to end.
    if ($i >= $offset && $i <= $array_length) {
            echo write_thumbnails_fun($type_of_thumbnail, $image_path, $k, $i, $portfolio_image_array, $title, $image_original);
            $t_total++;// update thumbnail total count.
        }
        $i++;
    }// end of foreach loop 1.
    $looped=true;// Just FYI.
    $i=0;// Reset.
    // SECOND HALF LOOP:
    foreach($portfolio_image_array as $k=>$img_obj){// go through array from beginning to offset.
        if ($i < $offset) {
            echo write_thumbnails_fun($type_of_thumbnail, $image_path, $k, $i, $portfolio_image_array, $title, $image_original);
        }
        $i++;
    }// end of foreach loop 2.

Thankyou so much for all the help!
:)

A: as @arkascha suggested use modulo operator
<?php

$example = array(1,2,3,4,5,6);
$count = count($example);
$offset = 3;

for($i = 0; $i < $count; $i++) {
  $idx = ($offset + $i) % count
  echo $example[$idx]."
";
}
?>


text:
Q: Cannot read properties of the Dataset I have been scratching my head with this problem, it wont read the data inside the json file,
it says this error
Uncaught TypeError: Cannot read properties of undefined (reading 'Messages')
at showDataset (Week 11 Assignment.html:38)
at onload (Week 11 Assignment.html:83)

showDataset @ Week 11 Assignment.html:38
onload @ Week 11 Assignment.html:83

<!DOCTYPE html>

<meta charset="utf-8">

Example

Sample Text

<input type="text" name="userText" id="someText" onchange="createParagraph()">

This is the Json file dataset, it supposed to print out the time, note and username on the

Function ShowDataset()

I have no clue about this because all of the code i think is right, i am fairly new to javascript and codding

Messages : [
            { "Time" : "1", "Note" :"2" , "Username" : "3"},
            { "Time" : "11", "Note" :"21", "Username" : "31"}
            { "Time" : "12", "Note" :"22", "Username" : "32"}
           ]

A: The variable Quote is undefined and you tried to read the property Messages of undefined. That's why you have the Error. Now I can tell you you have this because when the body is loaded you immediatly trigger showDataset().
Instead you should do this in your html

Example

Sample Text

<input type="text" name="userText" id="someText" onchange="createParagraph()">

here you will load the json and you methode already call the good function when it's done ;)
else you tried to read data that hasn't be initiated.


text:
Q: Privacy with Ubuntu Phone I am very security conscious and am reluctant to use Google products, including android because of the data Google collect. For anyone interested, I've posted the joke that is the information they collect below. I've read the privacy policy that the Ubuntu phone steals from you & I am wondering if there is a way to disable every single piece of personally identifiable information to Ubuntu? Otherwise I just cannot purchase the device.
reasons not to use google andriod
things they record/take from your phone:
-youtube searches, youtube video's viewed
-your hardware model, operating system version, UUID (unique ID to identify your device, including your EMEI number)
-your phone number
-any search queries
-numbers called along with a timestamp & duration
-IP address
-hardware settings
-browser type & language, and any website you visit with a timestamp and date
-your GPS location when it's active
-Wifi Access points and nearby mobile towers
-personal information on your local storage within the phone

A: Sniffing through the source code and modifying lines of code related to GPS and other stuff and then re compiling the distro. I am pretty sure that there are some closed source drivers in use anyway, so I don't really see the point.
http://discourse.ubuntu.com/t/new-ubuntu-phone-won-t-truly-be-open-source-article/1574
Chances are, someone or something is watching unless you use a cardboard phone.


text:
Q: XML ElementTree - indexing tags I have a XML file:
<sentence id="en_BlueRibbonSushi_478218345:2">
   <text>It has great sushi and even better service.</text>
</sentence>
<sentence id="en_BlueRibbonSushi_478218345:3">
   <text>The entire staff was extremely accomodating and tended to my every need.</text>
</sentence>
<sentence id="en_BlueRibbonSushi_478218345:4">
   <text>I've been to this restaurant over a dozen times with no complaints to date.</text>
</sentence>

Using XML ElementTree, I would like to insert a tag <Opinion> that has an attribute category=. Say I have a list of chars list = ['a', 'b', 'c'], is it possible to incrementally asign them to each text so I have:
<sentence id="en_BlueRibbonSushi_478218345:2">
   <text>It has great sushi and even better service.</text>
   <Opinion category='a' />
</sentence>
<sentence id="en_BlueRibbonSushi_478218345:3">
   <text>The entire staff was extremely accomodating and tended to my every need.</text>
   <Opinion category='b' />
</sentence>
<sentence id="en_BlueRibbonSushi_478218345:4">
   <text>I've been to this restaurant over a dozen times with no complaints to date.</text>
   <Opinion category='c' />
</sentence>

I am aware I can use the sentence id attribute but this would require a lot of restructuring of my code. Basically, I'd like to be able to index each sentence entry to align with my list index.

A: You can use the SubElement factory function to add elements to the tree.
Assuming your XML data is in a variable called data, this will add the elements to your document tree:
import xml.etree.ElementTree as ET
tree = ET.XML(data)
for elem, category in zip(tree.findall('sentence'), ['a', 'b', 'c']):
    Opinion  = ET.SubElement(elem, 'Opinion')
    Opinion.set('category', category)

ET.dump(tree)  # prints the tree; tree.write('output.xml') is another option


text:
Q: Is g id needed in SVG This is a simple question but I can't find an answer that seems certain.
In an SVG where you'd see something like
<g id="Layer_3" data-name="Layer 3"><g id="Layer_3-1" data-name="Layer 1">

Is this something the SVG actually needs to have? They look the same when removed so I'm wondering if they're solely for identification?

A: No they are not required.
Even though if you are re-using same svg on a single page.
For example two SVG's with id="edit" it will cause ADA Compliance issue.


text:
Q: How to CMake compile a library as part of my app's source and not as static/shared library? I'd like to be able to debug my app at the same time as the library(ies) with VSCode and CLion using CMake.
.
+-- lib
|   +-- CMakeLists.txt
|   +-- lib.c
|   +-- lib.h
+-- app
|   +-- CMakeLists.txt
|   +-- app.c
|   +-- app.h

As an example, let's say I want to compile my app with the {fmt} library as part of the source of my app, to see the flow inside the fmt lib's codebase when I debug my code.
Obviously, I don't want to copy all the commands of the cmake file of the lib into my cmake file of my app, a way to link the CMakeLists.txt of the lib to my lib's one would be the best.
In the end, my app uses the static/shared library but there are already SO questions about that and some examples in the open-source world.
FYI, my app's source files use #include <lib.h>.
Edit:
I just wanted to clarify a point, using {fmt} as source is much easier since it can be used as a header-file-only library.

A: I think that cmake's add_subdirectory (https://cmake.org/cmake/help/latest/command/add_subdirectory.html) does exactly what you need.
It will include library's CMakeLists.txt to your project and you will be free to use its targets in functions like target_link_libraries.
Simple example: Let's assume that you checked out the fmt source code to fmt folder.
.
+-- fmt (fmt source code)
+-- CMakeLists.txt
+-- main.cpp

CMakeLists.txt:
cmake_minimum_required(VERSION 3.0)
project(example)

add_subdirectory(fmt)

add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} PUBLIC fmt)

main.cpp:
#include "fmt/core.h"
#include <iostream>

int main()
{
    std::cout << fmt::format("The answer is {}.", 42) << std::endl;
}

A: If you compile the library with debug information into either a static or a shared library you link against and not move the sources, I see no reason why you wouldn't be able to debug it as part as your larger app.
If you really want to compile "as part of the source" you may produce the object files and include them in your main build - you can use
add_library(dummy OBJECT <source files>)

to produce the object files. However I see no reason why you would like to do this.
Overall, looks like @luantkow's answer is the right way to do what you need.


text:
Q: Android Studio Run/Debug configuration error: Module not specified I am getting a 'Module not specified' error in my run config. I have no module showing in the drop down yet I can see my module no probs. The issue came about when I refactored my module name, changed the settings.gradle to new name.
Now when I go to project structure and select my module nothing shows in the screen, not even an error.
I'm not 100% sure, but the icon beside my module looks like a folder with a cup and not a folder with a phone.
My exact steps -

*

*Open in Android view

*Refactor directory name

*refactor module name

*change settings.gradle contents: name to new name

A: None of the existing answers worked in my case (Android studio 3.5.0). I had to

*

*close all android studio projects

*remove the project from the recent projects in android studio wizard

*restart android studio

*use import option (Import project- Gradle, Eclipse ADT, etc) instead of open an existing project AS project

*File -> Sync project with gradle files

A: I realized following line was missing in settings.gradle file
include ':app'

make sure you include ":app" module

A: never mind, i changed the name in settings.gradle and synced and then changed it back and synced again and it inexplicably worked this time.

A: Resync your project gradle files to add the app module through Gradle

*

*In the root folder of your project, open the settings.gradle file for editing.

*Cut line include ':app' from the file.

*On Android Studio, click on the File Menu, and select Sync Project  with Gradle files.

*After synchronisation, paste back line include ':app' to the settings.gradle file.

*Re-run Sync Project with Gradle files again.

A: check your build.gradle file and make sure that use apply plugin: 'com.android.application'
 istead of
apply plugin: 'com.android.library'
it worked for me

A: I struggled with this because I'm developing a library, and every now and then want to run it as an application.
From app/build.gradle, check that you have apply plugin: 'com.android.application' instead of apply plugin: 'com.android.library'.
You should also have this in app/build.gradle:
defaultConfig {
        applicationId "com.your_company.your_application"
        ...
}

Finally run Gradle sync.

A: If you can't find your settings.gradle file in your project directory

*

*Add settings.gradle file

*Add include ':app' inside the settings.gradle file

*Rebuild or sync your project
Your app module should appear in your configuration file.

A: I had the same issue after update on Android Studio 3.2.1 I had to re-import project, after that everything works

A: I would like to add some more information while I was facing this issue:
Ref: Answer from @Eli:

*

*Cut line include ':app' from the file.

*On Android Studio, click on the File Menu, and select Sync Project
with Gradle files.

*After synchronisation, paste back line include ':app' to the settings.gradle file.

*Re-run Sync Project with Gradle files again.

So, let's follow the instruction and try to keep one thing in mind, that what is showing in your build configuration. Make sure you are seeing the name of your configuration app like the image below:
If you are seeing anything else, then the steps mentioned by @Eli (the most accepted answer) will not work.
An alternative Solution
If you have a different name on the Run/Debug Configurations window and the above process is not working, please change the config name to 'app'

then -> hit Apply -> then Ok.

After that follow this:-

File->Sync project with gradle files (if needed).

Now check the issue will be resolved hopefully. I have faced this issue and I think it might help others as well.

A: This issue also may happen when you just installed new Android studio and importing some project, in the new Android studio only the latest sdk is downloaded(for example currently the latest is 30) and if your project target sdk is 29 you will not see your module in run configuring dialog.
So download the sdk that your app is targeted, then run Sync project with gradle files.

A: I had to select "Use classpath of module:" drop down option and choose my module.

A: I was trying to open an old GitHub project with the latest android studio that's why got this error. I tried almost all the way that mentions in this post but none of them is work.
In my case, I update my Gradle version with my latest project, and the issue resolved. Use your latest Gradle version to resolve the issue.

A: Sometimes the project doesn't load your sdk version.
so manually change the this in your build.gradle file module level to your own sdk version

*

*compileSdkVersion 28

*buildToolsVersion "28.0.3"

*targetSdkVersion 28

now re-sync the your project.

A: If no solution works then make sure that you opened the project from the right directory
For example, when I opened the project from app folder and from the root
I got

Module not specified

error, but when I opened it from todoapp the error had gone

A: Try to delete the app.iml in your project directory and restart android studio

A: You have 3 ways:

*

*Clean Project in Android Studio menu

Build -> Clean Project and use Build -> Rebuild

*Remove all the modules in settings.gradle

*

*Open settings.gradle project

*Remove include ':app' and other modules

*Sync gradle

*Add include ':app' and other modules

*Sync gradle again

*Remove all code in gradle.properties

*

*Open gradle.properties project

*Remove all code
org.gradle.daemon=true
org.gradle.configureondemand=true
org.gradle.parallel=true
android.enableBuildCache=true

*Sync gradle

*Add code again

*Sync gradle again

A: Check your minsdkversion, compilesdkversion and targetsdkversion and ensure that you installed all those from Tools -> SDKManager in Android Studio.
e.g if your targetsdkversion is 30 and minsdkversion is 28, ensure that you installed 28, 29, 30 sdks.

A: Remove from app gradle this code
android{
    defaultConfig.applicationId="com.storiebox"
}

A: We are currently recommending AS 3.3 for exercises.
These settings will work in the current 3.3 beta version with two small changes to your project:
In build.gradle (Project), change gradle version to 3.3.0-rc02
In menu go to File -> Project Structure. There you can change the gradle version to 4.10.0

A: in my case, when I added Fragment I git this error.
When I opened THe app build.gradle I saw id("kotlin-android") this plugin in plugins.
just remove it!

A: You can clean your project and and invalidate caches / restart. After that your project might be fixed.
This solution works for me.

A: For me the issue and solution:

*

*I am using Webrtc library module in my android project. I had updated the compile and targeted sdk version in my gradle for only app module have havent for the webrtc library gradle.

*Go to SDK Manager and confirm if the sdk version is installed (completely and not partially).

*After above steps Invalidate & Restart app.

*In project folder on your windows explorer within your project delete the .idea folder.

Note: Make sure to update your gradle for all module other than app module as well.

A: Run the app, it will show 'Edit Configuration' window.
Under Module - select the app (it would be <no module> ).
Then select the activity (under Launch Options)

A: If all above solution doesn't work then do try this solution, because in my case none of the above solution were working.
I too was facing this problem and after 5 hour of hard work I am able to tell you a solution.
If you are cloning project using git the I would recommend you to directly clone project using android studio.
It worked for me.


text:
Q: Execute java sql statements in sequence before another statements The error:
org.postgresql.util.PSQLException: ERROR: insert or update on table "food_order" violates foreign key constraint "food_order_invoice_id_fkey"
  Detail: Key (invoice_id)=(2) is not present in table "invoice".

First I insert my data to invoice table and then insert the id of that as reference for another. I want these statements executed sequentially.
This is my code:
public static void insertInvoice(Invoice invoice) throws SQLException {
    Connection connection = DatabaseConnectionPostgre.connection();
    Statement statement = connection.createStatement();
    PaymentType paymentType = invoice.getPaymentType();
    String query = null;
    switch (paymentType){
        case Cash:
            query = "insert into cash_invoice values(" +
                    "'" + invoice.getId() + "', " +
                    "'" + invoice.getDate() + "', " +
                    "'" + invoice.getTotalPrice() + "', " +
                    "'" + invoice.getCustomer().getId() + "', " +
                    "'" + invoice.getInvoiceStatus() + "', " +
                    "'" + ((CashInvoice) invoice).getDeliveryFee() + "' " +
                    ")";
            break;
        case Cashless:
            query = "insert into cash_invoice values(" +
                    "'" + invoice.getId() + "', " +
                    "'" + invoice.getDate() + "', " +
                    "'" + invoice.getTotalPrice() + "', " +
                    "'" + invoice.getCustomer().getId() + "', " +
                    "'" + invoice.getInvoiceStatus() + "', " +
                    "'" + ((CashlessInvoice) invoice).getPromo() + "' " +
                    ")";
            break;
    }
    statement.executeUpdate(query);
    for (Food food:
         invoice.getFoods()) {
        query = "insert into food_order( food_id, invoice_id) values(" +
                "'" + food.getId() + "', " +
                "'" + invoice.getId() + "' " +
                ")";
        statement.execute(query);
    }
    statement.close();
    connection.close();
}


text:
Q: Change isotope options on click I just want to change the value of isResizeBound from true to false on click after isotope plugin initialization.
Is there an easy way?
var $grid = $('.grid').isotope({
 isResizeBound: true
});

$(".aa").on("click", function() {
 $grid.isotope({ isResizeBound: false });
});

This is what I tried.
var trueorfalse = true;

var $grid = $('.grid').isotope({
    isResizeBound: trueorfalse
});

$(".aa").on("click", function() {
  trueorfalse = false;
  // trigger isotope again
  $grid.isotope('layout');
});


text:
Q: Help installing on Asus eeePad 1025c This is in regards to Ubuntu 12.10. I am not able to boot the live environment just gives me output then blanks out and stays at flashing cursor, I am however able to boot up the installer and connect to wifi and install the os no problem however it will not boot up and I'm not sure why is booting like normal printing out the list of starting services and what not then just stops and sits forever. I'm thinking it could be graphics related since the machine never starts X (i think). Any input will be greatly appreciated and I will be happy to provide more information to help solve the problem, thank you all.

A: Asus 1025c is a CedarView based netbook, which are known to boot to black screen both with 12.04 and 12.10.
IMHO, 12.10 is a bit heavy for a netbook anyway. Try 12.04, with Unity2d or another lightweight environment, and follow the [Poulsbo wiki](to work around the black screen problem).
Basically, if hit with a black screen when booting from USB, press ctrl-alt-f1 to switch to a tty, log in, and restart xserver with
sudo service lightdm restart

After the installation, run gksudo gedit /etc/default/grub, and add console=tty1 to the following line:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"

...the end result should look look like this
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash console=tty1"

Apply the GRUB configuration by running sudo update-grub (thanks to user32674 for pointing this out).
You could then also try searching for Additional Drivers in the Dash and install the CedarView driver.
Hope that works.


text:
Q: Need recommendations for ways to save data and have it be able to be looked up I'm making a personal project where I need to save a bunch of different instances of a class that I made that right now only contain ints and strings. I'm thinking of making a list of them and just saving that using the File.class methods. I'm not looking to do JSON yet, I'll figure that out later.
If you have any recommendations on how to move forward, I would greatly appreciate it.

A: Assuming you are working in Java, Object Serialization would work well for this. Your class can implement Serializable, and be written out to a file. Keep in mind that changes to your class in source code will render that serialized object unusable with the new code. For an example on how to serialize and write Java objects to a file, see Datsabk's article.


text:
Q: SVN move the contents of a directory into its parent I'm having trouble figuring out the svn commands needed to move the contents of a directory up one level into its parent and then deleting that directory. In unix I would do:
$ cd ~/parentdir/subdir
$ mv * ..
$ cd ..
$ rm -r subdir

Now all the files that were under subdir are now in parentdir and subdir is now gone. How would I do the same in SVN while maintaining the history of those files?

A: $ cd ~/parentdir/subdir
$ svn cp * ..
$ cd ..
$ svn rm subdir
$ svn ci -m"Copy parentdir/subdir/* into parentdir, remove subdir"

A: [this is really a comment, but i'm lacking the reputation for it]
use $ svn cp * .[^.]* .. instead if you want to copy dotfiles and .folders/, too.
found at Super User, which shows alternate ways to do the same.


text:
Q: Spring boot doesn't resolve a default value in a @Value property in a dependency Edit: Another thing I should note is I'm running this out of Eclipse. I wonder if that's somehow causing an issue.
Original post:
I'm having trouble getting a placeholder to resolve in Spring Boot.
Here is the placeholder I'm testing:
@Value("${influxdb.port:8086}")
private String port;

This above exists in what I'll call component Foo of the application.
Component Bar uses Foo as a dependency specified in pom.xml. It invokes a method from Foo as follows:
InfluxDBClient client = bipInfluxDBClientService.getInfluxClient();

However, Bar doesn't start due to an unresolved dependency:
2022/11/11 16:26:04.571 | ERROR | main | c.s.i.c.c.ApplicationErrorListener] | !!!!!! Something is not working as expected so the application is stopping. Error: Error creating bean with name 'influxUtilsService': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'influxdb.port' in value "${influxdb.port}" !!!!!!

If I include influxdb.port in the application.properties file of Bar, it works. Or if I include it in an external properties file that is read by Bar on startup, it also works.
However, I would like the default value to be specified in the code of Foo, not Bar.
Why is it not resolving this dependency?


text:
Q: Reserved word for rails application name? I created a new rails 3.2.3 application giving it a name - jquery.
rails new jquery

Right after I created it, "rails console" gives me the following error.
~/Temp/jquery$ r c
/Users/ssk/Temp/jquery/config/application.rb:13: uninitialized constant Jquery::Rails::Application (NameError)
    from /Users/ssk/.rvm/gems/ree-1.8.7-2011.03/gems/railties-3.2.3/lib/rails/commands.rb:39:in `require'
    from /Users/ssk/.rvm/gems/ree-1.8.7-2011.03/gems/railties-3.2.3/lib/rails/commands.rb:39
    from script/rails:6:in `require'
    from script/rails:6

If I create it with different name, it's ok.
So jquery is not allowed name?
If so, how do I know if a name is allowed or now before I create one?
Thanks.
Sam

A: Here is a list of Reserved Words for Rails you can check out.
http://oldwiki.rubyonrails.org/rails/pages/ReservedWords


text:
Q: FileUpload control upload video mp4 I use asp.net FileUpload to upload some file like mp4, mp3, jpg, png and psd. Every file work fine, but page just show me that the The connection to localhost is interrupted when I try to upload mp4 file. I don't know what is the error or problem. Please help.

A: There might be a problem with request size limit, as MP4 files tend to be big. Very big. Try changing the config in your web.config:
<configuration>
    <system.web>
        <httpRuntime maxRequestLength="65536" />
    </system.web>
</configuration>

And check the file size before uploading.


text:
Q: genetic algorithm c++ final stage I have written the code for a genetic algorithm and have the crossover function, mutation function, parent selector function and a function to transfer genes. Now I want to put it all together and would like to know if the following code is good programming practice or not.
Species Parents[popSize];
Species Children[popSize];

for(int gen = 0 ; gen < 100 ; gen++)
{
    for(int i = 0; i < popSize ; i ++)
    {
        int parentA = chooseParent(Parents);
        int parentB = chooseParent(Parents);
        crossOver(Parents[parentA] , Parents[parentB] , Children[i]);
        Children[i].mutate();
    }
    for(int i = 0; i < popSize ; i ++)
    {
        transfereGenes(Children[i], Parents[i]);
    }
}

A: It's a simple, clear, standard implementation of a genetic algorithm. It's enough for many application.
Anyway you could consider some points:

*

*using std::vector instead of arrays

*

*it's a way to gain flexibility without losing speed (e.g. there're some variations of the basic genetic algorithm that consider variable-size populations)

*it allows to swap Children and Parents via the swap function (faster for large populations)

*you can probably change the chooseParent function to extract a couple of individuals (and, in general, n individuals acting as parents) in a single "step". This is quite simple for tournament selection.

*you should add some control parameters (probability of mutation, crossover...). Many problems are very sensitive to these parameters and you can consider different values during evolution.

*for strictly C++ related points:

*

*you should avoid the postfix increment operator (gen++, i++)

*100 is a magic number


text:
Q: Content placeholder for preloading I need to make content placeholder for preloading like this :
http://cloudcannon.com/deconstructions/2014/11/15/facebook-content-placeholder-deconstruction.html
Is there a way to do this layout background animation in android?


text:
Q: How do I replace all instances in a string using regular expressions in Progress OpenEdge I would like to use a regular expression in OpenEdge to replace parts of a string.
In this case we want to replace SQL expressions with a symbol (now we use ?).
So what I have so far is this:
USING Progress.Lang.*.
USING System.Text.RegularExpressions.*.

BLOCK-LEVEL ON ERROR UNDO, THROW.

CLASS TOOLS.externals.TextSanitizer:

    CONSTRUCTOR PUBLIC TextSanitizer (  ):
        SUPER ().

    END CONSTRUCTOR.

    METHOD PUBLIC CHARACTER SanitizeSql( INPUT pInputText AS CHARACTER ):

        DEFINE VARIABLE RESULT AS CHARACTER NO-UNDO.
        DEFINE VARIABLE regexp AS Regex NO-UNDO.

        regexp = NEW Regex("^((INSERT)\s+(INTO).*((VALUES)|(SELECT))|(SELECT).*(FROM)|(UPDATE).*(SET)|(DELETE)\s+(FROM)|((CREATE)|(DROP)|(TRUNCATE)|(ALTER)|(MODIFY))\s+((INDEX)|(TABLE)|(DATABASE)|(COLUMN)|(VIEW)))$").

        RESULT = regexp:Replace(pInputText, "?").

        DELETE OBJECT regexp.

        RETURN RESULT.

    END METHOD.

END CLASS.

What I have tried to get mixed casing work:
regexp = NEW Regex("/^rest of the regex$/ig").

And I wrote a procedure to run some tests:
BLOCK-LEVEL ON ERROR UNDO, THROW.

USING TOOLS.externals.TextSanitizer.

DEFINE VARIABLE textSanitizer AS TextSanitizer NO-UNDO.

textSanitizer = NEW TextSanitizer().
MESSAGE textSanitizer:SanitizeSql("SELECT * FROM") VIEW-AS ALERT-BOX.

RETURN.

The tests I have run so far:

*

*SELECT * FROM --> This returns ? as expected

*select * from --> This returns the original string, so mixed casing does not work, not even when I added /i

*SELECT * FROM SELCT * FROM --> This also returned ?, while I would expect ? SELCT * FROM

*SELECT * FROM SELECT * FROM --> Returns ?, what I would expect is ? ?
Could someone help me out here?

A: First off, remove all brackets around words - they're useless noise (plus I feel like I'm back in a LISP tutorial).
If you're having trouble with case, try using the in-line flag (?i).
Your quantifiers are all greedy instead of reluctant: use .*? instead of .*.
Unless all you SWL fragments occupy the whole line, you should remove the end anchor $.
Applying the above proposed changes, try this:
regexp = NEW Regex("(?i)^(INSERT\s+INTO.*?VALUES|SELECT.*?FROM|UPDATE.*?SET|DELETE\s+FROM|(CREATE|DROP|TRUNCATE|ALTER|MODIFY)\s+(INDEX|TABLE|DATABASE|COLUMN|VIEW))").

I have fixed the issues as asked, but won't help you with expanding the regex so it matches every possible SQL statement. That is too big a task.

A: The point here is to filter out some SQL statements because some people here think that is the best way to prevent SQL injection. (I know)
This time I solved it this way:
METHOD PUBLIC CHARACTER SanitizeSql( INPUT pInputText AS CHARACTER ):
    DEFINE VARIABLE regexp AS Regex     NO-UNDO.
    regexp = NEW Regex("(?i)(INSERT\s+INTO.*?VALUES|SELECT.*?FROM|UPDATE.*?SET|DELETE\s+FROM|(CREATE|DROP|TRUNCATE|ALTER|MODIFY)\s+(INDEX|TABLE|DATABASE|COLUMN|VIEW))").

    DO WHILE regexp:IsMatch(pInputText) = TRUE:
        pInputText = regexp:Replace(pInputText, "?").
    END.

    DELETE OBJECT regexp.

    RETURN pInputText.

END METHOD.

First as @Bohemian suggested I added (?i) in front of the regex. That fixed the casing issue.
After that I removed the ^ and $ at the beginning and end of the regex string. That solved the issue with finding the beginning and end of a string.
Lastly I used IsMatch() in a DO WHILE loop to find all the instances and replace them.


text:
Q: What i have to use to repeat local notifications weekly in iOS 8? I'm new in ios developing and I'm trying to repeat a local notification weekly. I've looked at the documentation WeekCalendarUnit it's deprecated in ios 8. I've searched for a solution here and on the web but i can'f find anything. The only things not deprecated about "week" available in XCode 6 beta 4 are:
static var CalendarUnitWeekday: NSCalendarUnit { get }
static var CalendarUnitWeekdayOrdinal: NSCalendarUnit { get }
static var CalendarUnitWeekOfMonth: NSCalendarUnit { get }
static var CalendarUnitWeekOfYear: NSCalendarUnit { get }

but i don't think they do what WeekCalendarUnit did. Can i have an elucidation please?
All other answers here don't speak about deprecated unit in ios 8. Thanks.


text:
Q: Accessing foreign key attributes for arithmetics in django rest framework I'm trying to calculate the length of a house relative to some adjacent neighborhoods, such that, house_size / (neighborhood[0].length + neighborhood[1].length...):
class House(models.Model):
    house_id = models.CharField(max_length=256, primary_key=True)
    size = models.IntegerField()
    neighborhood = models.ManyToManyField('neighborhood', through='HouseNeighborhoodLink')

class Neighborhood(models.Model):
    length = models.IntegerField()

I created a table to assign several neighborhoods with a house. Also, houses can be assigned to several adjacent neighborhoods:
class HouseNeighborhoodLink(models.Model):
    house = models.ForeignKey(House, on_delete=models.DO_NOTHING)
    neighborhood = models.ForeignKey(Neighborhood, on_delete=models.DO_NOTHING)

Serializers:
class LengthFromNeighborhoodSerializer(serializers.ModelSerializer):
    class Meta:
        model = Neighborhood
        fields = ['length']

class HouseCoverageOfNeighborhood(serializers.ModelSerializer):
    Neighborhood = LengthFromNeighborhoodSerializer(read_only=True)

    class Meta:
        model = HouseNeighborhoodLink
        fields = ['house_id', 'Neighborhood']

I'm stuck in the three dots (...), where I want to access the length attribute of all neighborhoods and then calculate the proportion to a house. I'm not sure how to access the length of each neighborhood from HouseNeighborhoodLink table:
class HouseCoverageDetail(generics.ListAPIView):
    queryset = HouseNeighborhoodLink.objects.all()
    serializer_class = HouseCoverageOfNeighborhood

    def get_queryset(self):
        house_id = self.kwargs['house_id']
        neighborhood = self.queryset.filter(house_id=house_id)
        ...
        return result

A: Chack this
 class HouseCoverageOfNeighborhood(serializers.ModelSerializer):
    Neighborhood = LengthFromNeighborhoodSerializer(many=True,read_only=True)

    class Meta:
        model = HouseNeighborhoodLink
        fields = ['house_id', 'Neighborhood']


text:
Q: No platform available for current project Maybe someone has any idea why when I created new FireMonkey project, I am getting error: No platform available for current project.? I've installed Android SDK, but in Delphi options, under SDK Manager list is empty... and when I try to add new SDK, the lists in add dialog are empty... but the same error occures after trying to create VCL application, so the problem has to be somewhere else.
Rad Studio 10 Seattle Update 1, freshly installed.

A: I had this same issue a couple of times with different Delphi IDEs including latest Delphi 10.3.1 Rio, and that's how I got here.
Although I don't know what causes it, I suspect that something missing or corrupted in the registry regarding Delphi install.
I solved it opening RegEdit.exe, navigating to
HKEY_CURRENT_USER\Software\Embarcadero\BDS\20.0
(It might be also in HKEY_LOCAL_MACHINE and the number relates to the installed Delphi version. In this example, 20 = Delphi 10.3 Rio)
and renaming it to
HKEY_CURRENT_USER\Software\Embarcadero\BDS\20.0_OLD
which forces Delphi to recreate it next time it starts. The drawback is that you loose all your settings and installed components (but you can later export specific parts of the old corrupted key, edit it manually in notepad and import it again into the newly created key).
Anyway it is better than reinstalling Delphi. If this procedure doesn't solve the issue, you can restore the original key and have the IDE the way it was.

A: This is a year too late, and I can't find the Embarcadero forum entry where I read this, but the issue was solved by de-installing then re-installing Seattle, and the first time used, run as administrator.


text:
Q: How to handle back button on appBar of Scaffold layout in flutter module and navigate to previous page on the host app I have a question, I have to create a flutter module and integrate it directly into the host app. I want to handle the back button on flutter UI by clicking it and navigating to the previous page on the host app. I use go_router to handle navigation on the module and host app. I have never integrated it. I have no idea to handle the back button it works on the appBar inside the flutter module. In this case, I would like to handle it by method channel or not?
I want to get the solution for the handle back button on the appBar in the flutter module. It must to click and navigate from flutter module and goto previous page on the host app.

A: I just found a way. After setup the flutter module inside Android or iOS, We can use this code setup inside the AppBar to close the page.
            if(Platform.isAndroid){
              SystemNavigator.pop();
            } else {
              exit(0);
            }


text:
Q: Using browser-supplied 3rd party oauth2 token in nodejs I'm looking for a nodejs Express library for this:

*

*A 3rd party site Acme has a protected GET API https://example.com/getdata, and it's an OAuth2 server.

*My web app calls getdata, which forces it to authenticate.

*Afterwards, my web app POSTs some data to my own server.

*My server also needs to call Acme's getdata, impersonating the current user. I cannot trust the data from my web app.

*If the call to Acme's getdata fails on my nodejs server, it should redirect my web app to authenticate via a popup, and try again.

I'm building a nodejs express service that can make calls to a 3rd party using oauth2 token supplied by the client.  The client side code is already authenticated with the 3rd party, and calls my service the same way as it calls the 3rd party servers.
I am able to do a pass-through token validation using express-accesstoken-validation module, but that only tells me if supplied token is valid.  How would I make a GET request using that token?


text:
Q: static shared_ptr not keeping value across function calls I have an input.hpp (which I won't post for the sake of brevity) and an input.cpp file that looks like this (some things removed):
#include "details/macros.hpp"
#if defined(PLATFORM_WINDOWS)
    #include "details/win32/input.inl"
#else
    #error "No input implementation for this platform."
#endif

#define CHECK_INPUT_TYPE(type)      \
if (types[input_type_bits::type])   \
{                                   \
    auto res = poll_##type();       \
    if (res.code() != errors::ok)   \
        LOG(error) << res;          \
}

namespace input
{
        void poll_input(flagset<input_type_bits> types)
        {
            CHECK_INPUT_TYPE(keyboard)
            CHECK_INPUT_TYPE(mouse)
            CHECK_INPUT_TYPE(touch)
            CHECK_INPUT_TYPE(gesture)
            CHECK_INPUT_TYPE(gamepad)
        }
}

And an input.inl that looks like this (also cut down for brevity):
#ifndef WIN32_INPUT
#define WIN32_INPUT

#include <Windows.h>

namespace input
{
        static bool g_init = false;
        static std::shared_ptr<system::surface> g_surface = nullptr;

        static error<errors> poll_gamepad()
        {
            if (!g_init)
            {
                auto ptr = create_surface();
                g_surface = std::move(ptr);
                g_init = true;
            }

            HWND hwnd = reinterpret_cast<HWND>(g_surface->native_ptr());

            return MAKE_ERROR(errors::ok);
        }
}

#endif

However what is currently happening is that when I try to access g_surface's method, it works for the first call (in which g_init was false) but in the second time the poll_input function is called, according to Visual Studio's debugger, g_surface is empty and accessing the method throws an exception.
What gives? g_init was set to true successfully across calls and yet g_surface wasnt? If I move g_surface to be a static variable inside poll_gamepad it does work properly but that is something I'd like to avoid. Is there something about a static shared_ptr that I'm missing?

A: I found out the answer to this problem. I mistakingly (don't code while tired people!) had a call to the Win32 API GetKeyboardState that was using the wrong static variable as the output buffer and caused static memory corruption.
Thank you for everyone's help and I apologize for not giving much information to deal with. That was my bad!
Anyways, I'm glad it's working properly now, case closed.


text:
Q: Parsing JSON in Python and Converting to Excel I am attempting to parse this JSON and convert it to Excel and only print out certain columns using Python but I keep getting an TypeError: string indices must be integers. The JSON file continues to repeat what is inside "d" over and over again.
JSON:
{
    "d": [
        {
            "__type": "New Cust",
            "Description": "TV Purchase",
            "End": "/Date(1624962600000)/",
            "ID": 1,
            "Resources": [
                {
                    "Available": true,
                    "Key": "12345",
                    "Text": "John Doe",
                    "Type": "SalesProvider",
                    "CalendarID": "1234"
                }
            ],
            "Subject": "Meeting with Sam",
            "Visible": true,
            "AppStatus": "5",
            "StartTime": "06/01/2021 10:30:00",
            "AppID": "1",
            "ServiceID": "7",
            "NotesCount": "0",
            "CustomerID": "1",
            "AppType": "NNR",
            "IsEditedThis": "False",
            "BusinessPackageID": "0",
            "PopupNotesCount": "0",
            "EventType": "1",
            "SPName": "John Doe",
            "SPID": "12345",
            "EventCapacity": "0",
            "IsPaid": "False",
            "IsWorkShop": "False",
            "FormStatus": "0",
            "PaidType": "1",
            "AppComment": "",
            "CustName": "Sam Will",
            "ResourceID": "",
            "CssClass": "rsCategoryBlue",
            "ServiceName": "TV Sale",
            "NoOfAttendees": null,
            "StreamingNoOfAttendees": null,
            "StreamingStatus": "0",
            "StreamingEventCapacity": "",
            "Photo": "",
            "PersonalOffType": null,
            "ResourceName": null,
            "IsShowCheckIn": false,
            "PaymentStatus": 0
        },
        {
            "__type": "New Cust",
            "Description": "Receiver Purchase",
            "End": "/Date(1624962600000)/",
            "ID": 1,
            "Resources": [
                {
                    "Available": true,
                    "Key": "12345",
                    "Text": "John Doe",
                    "Type": "SalesProvider",
                    "CalendarID": "1234"
                }
            ],
            "Subject": "Meeting with Bill",
            "Visible": true,
            "AppStatus": "5",
            "StartTime": "07/02/2021 9:30:00",
            "AppID": "1",
            "ServiceID": "7",
            "NotesCount": "0",
            "CustomerID": "1",
            "AppType": "NNR",
            "IsEditedThis": "False",
            "BusinessPackageID": "0",
            "PopupNotesCount": "0",
            "EventType": "1",
            "SPName": "John Doe",
            "SPID": "12345",
            "EventCapacity": "0",
            "IsPaid": "False",
            "IsWorkShop": "False",
            "FormStatus": "0",
            "PaidType": "1",
            "AppComment": "",
            "CustName": "Bill Tom",
            "ResourceID": "",
            "CssClass": "rsCategoryBlue",
            "ServiceName": "Audio Sale",
            "NoOfAttendees": null,
            "StreamingNoOfAttendees": null,
            "StreamingStatus": "0",
            "StreamingEventCapacity": "",
            "Photo": "",
            "PersonalOffType": null,
            "ResourceName": null,
            "IsShowCheckIn": false,
            "PaymentStatus": 0
        }
    ]
}

Python Code:
import json
import pandas as pd

f = open('JSON.txt', 'r')
data = json.loads(f.read())
l = []
for profile in data['d']:
    l.append(profile["Subject"]["StartTime"]["IsPaid"]["CustName"]["ServiceName"])
df1 = pd.DataFrame(l)
print(df1)
df1.to_excel('df1.xlsx')

I do not need the "Resources": [] info I just need certain parameters outside it in the JSON object. I am having difficulty parsing the JSON any help would be appreciated.

A: you can use a combination of the json standard library and pd.json_normalize
import json
import pandas as pd

parsed_json = json.loads('JSON.txt')

df = pd.json_normalize(parsed_json['d'],record_path='Resources')

print(df)

   Available    Key      Text           Type CalendarID
0       True  12345  John Doe  SalesProvider       1234
1       True  12345  John Doe  SalesProvider       1234

then pass it to excel
df.to_excel(...,index=False)

Going back to your issues, it seems like your trying to grab a bunch of fields like a list, when in reality you're attempting to find an attribute from a single data type object.
print(data['d'][0]['Subject'])

'Meeting with Sam'

This has no other nested items so you'll  naturally get an error.
the error TypeError: string indices must be integers is telling you you can only slice this object with integers i.e
#reversing the string.
print(data['d'][0]['Subject'][::-1])
maS htiw gniteeM

or
#first two characters of the string.
print(data['d'][0]['Subject'][:2])
Me

if you want to grab only a subset of columns from the top level you could do :
cols = ['Subject', 'StartTime', 'IsPaid', 'CustName', 'ServiceName']

df = pd.json_normalize(parsed_json['d'],)[cols]

print(df)

             Subject            StartTime IsPaid  CustName ServiceName
0   Meeting with Sam  06/01/2021 10:30:00  False  Sam Will     TV Sale
1  Meeting with Bill   07/02/2021 9:30:00  False  Bill Tom  Audio Sale


text:
Q: Set width 100% to image in a animation I am trying to create a image swapper using only css, with the animation feature I was able to easily able to make the images swap.
However, due to the images themselves not being the perfect size, and using a div with a animation that changes background and sizing the div to fit the entire screen:
width: 100%;
height: auto;

to the images cannot be fitted in the screen like it is usually done with css if its done with the html img tag, therefore it creates various copies of the image to fill in the missing space.
How can I make the animation set the width of the images to 100%?

.animation {
    animation: imgswaper 10s infinite alternate;
    width: 100%;
    height: 300px;
}

@keyframes imgswaper {
    0% {
        background-image: url(https://www.collinsdictionary.com/images/full/apple_158989157.jpg);
    }
    1% {
        background-image: url(https://www.collinsdictionary.com/images/full/apple_158989157.jpg);
    }
    50% {
        background-image: url(https://www.apple.com/ac/structured-data/images/knowledge_graph_logo.png?202207110316);
    }
    51%{
        background-image: url(https://www.apple.com/ac/structured-data/images/knowledge_graph_logo.png?202207110316);
    }
    100% {
        background-image: url(https://www.collinsdictionary.com/images/full/apple_158989157.jpg);
    }
}
<!DOCTYPE html>

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

A: Add background-size and background-repeat to your css. background-image is only discretely animatable though so it will look pretty janky.
More info here

.animation {
  animation: imgswaper 10s infinite alternate;
  width: 100%;
  height: 300px;
  background-size: contain;
  background-repeat: no-repeat;
}

@keyframes imgswaper {
  0% {
    background-image: url(https://www.collinsdictionary.com/images/full/apple_158989157.jpg);
  }
  1% {
    background-image: url(https://www.collinsdictionary.com/images/full/apple_158989157.jpg);
  }
  50% {
    background-image: url(https://www.apple.com/ac/structured-data/images/knowledge_graph_logo.png?202207110316);
  }
  51% {
    background-image: url(https://www.apple.com/ac/structured-data/images/knowledge_graph_logo.png?202207110316);
  }
  100% {
    background-image: url(https://www.collinsdictionary.com/images/full/apple_158989157.jpg);
  }
}
<!DOCTYPE html>

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


text:
Q: UINavigationController: Title Jumps in Resize Animation I have an ipad app where i would like to hide and show a category list (kind of like the small view in a split view controller), and the main view which contains a UiNavigationController stack.
I would like to resize the UINavigationController view to fill the whole screen when the category list is hidden, and to shrink when i show the list.
I have it working, except the title of the navigation bar immediately jumps to its new offset when setting the frame within an animation begin/commit block.
Any ideas how to stop the jump of the title?

A: I used this for fixing those jumps in UINavigationBar for title and right button.
#import "UINavigationBar+My.h"

@implementation UINavigationBar (My)

- (void)layoutSubviews {
for (id obj in [self subviews]) {
    if ([NSStringFromClass([obj class]) isEqualToString:@"UINavigationItemView"])
        [(UIView *)obj setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin];
    else if ([NSStringFromClass([obj class]) isEqualToString:@"UIButton"]) {
        if ([(UIButton *)obj center].x < ([self center].x / 2))
            [(UIButton *)obj setAutoresizingMask:UIViewAutoresizingFlexibleRightMargin];
        else
            [(UIButton *)obj setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
    }
}

@end

I hope it will help you ;-)

A: I ran into a similar problem recently; I had a subview of the animating view that was jumping immediately to its new position. This was happening because -layoutSubviews was being called on that view as a result of me programmatically modifying it before the animation finished. Are you doing something like changing the text of the title or modifying it in some way that would cause -layoutSubviews to be called on it?

A: My solution, seems to cope with all scenarios I hit in my app.  Obviously still a bit of a hack, so no guarantees it will always work!
@implementation UINavigationBar (Nick)

- (void)layoutSubviews {
    [super layoutSubviews];
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        UIView* titleView = nil;
        CGFloat buttonWidths = 0;
        for (UIView* subview in [self subviews]) {

            if ([subview class] == NSClassFromString(@"UINavigationItemView")) {
                if (titleView) {
                    // Exit here - if there is more than one title, probably doing a pop
                    return;
                }
                titleView = subview;
            }
            else if ([subview class] == [UIView class] ||                           // bar button with custom view
                     [subview class] == NSClassFromString(@"UINavigationButton")) { // or ordinary bar button

                buttonWidths += subview.frame.size.width;
                // is it RHS?
                if (subview.frame.origin.x > subview.frame.size.width) {
                    [subview setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
                }
                else {
                    [subview setAutoresizingMask:UIViewAutoresizingFlexibleRightMargin];
                }
            }
            else if ([subview class] == NSClassFromString(@"UINavigationItemButtonView")) {
                // pretty sure this is always the back button
                buttonWidths += subview.frame.size.width;
                [subview setAutoresizingMask:UIViewAutoresizingFlexibleRightMargin];
            }
        }

        if (titleView) {
            buttonWidths += 20; // seems to be apple indentation
            CGRect rect = titleView.frame;
            if (rect.size.width > self.frame.size.width - buttonWidths) {
                rect.size.width = self.frame.size.width - buttonWidths;
                titleView.frame = rect;
            }

            titleView.center = self.center;
        }
    }
}

A: It worked fine for me when I included [self.navigationController.navigationBar layoutSubviews] in the animation block itself.
Here's the code example:
[UIView animateWithDuration:0.5
                 animations:^{
                     [self.navigationController.navigationBar setFrame:newFrame];
                     [self.navigationController.navigationBar layoutSubviews];
                 }];

I hope this is somehow helpful.


text:
Q: how to get bounding box [Xmax,Xmin,Ymax,Ymin] from tensorflow object detection I am new to artificial intelligence and I am using TensorFlow object detection API to detect a product on images, so it already detecting the object, but I want to get coordinates Xmax, Xmin, Ymax, and Ymin for each object in the images.
That is the image with an object detected, in this case, 2 objects were detected in the image.
Image:

We can see that I got the coordinates of the objects but its not clear, there are more than 3 coordinates in the output and I just want to get the amount of coordinates as the number of objects that are in the image.
This the code which provide the output
with detection_graph.as_default():
    with tf.Session(graph=detection_graph) as sess:
        image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
        detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
        detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
        detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
        num_detections = detection_graph.get_tensor_by_name('num_detections:0')

        print(detection_graph.get_tensor_by_name('detection_boxes:0'))

        for image_path in TEST_IMAGE_PATHS:
            boxes = detect_objects(image_path)
            print(boxes)

Output
Tensor("detection_boxes:0", dtype=float32)
[[[0.16593058 0.06630109 0.8009524  0.5019088 ]
  [0.15757088 0.5376015  0.8869156  0.9394863 ]
  [0.5966009  0.88420665 0.6564093  0.9339011 ]
  ...
  [0.         0.         0.         0.        ]
  [0.         0.         0.         0.        ]
  [0.         0.         0.         0.        ]]]

I want to get something like that, but only the coordinates of the Bounding Box. We are assuming that they are the coordinates of the objects.
[0.16593058 0.06630109 0.8009524  0.5019088 ]
[0.15757088 0.5376015  0.8869156  0.9394863 ]

A: You should be aware of two things:

*

*These are all the coordinates of all (usually 100) top detections.

*These are given in normalized coordinates.

Therefore, in order to filter the detections by score, use detection_scores in order to decide which indices to filter out (they're sorted), and you can multiply the normalized coordinates with the original image size in order to get the absolute coordinates. The normalized coordinates are given in the format of [ymin, xmin, ymax, xmax], therefore you should multiply the first and the third coordinates with y_size and the second and the fourth with x_size. You can compute x_size and y_size by evaluating the shape of image_tensor.

A: Code:
for box in boxes[0]:
    xmin, ymin, xmax, ymax =box
    bboxes.append([int(ymin *640),int(xmin*480) , int((ymax-ymin)*640), int((xmax-xmin)*480)])


text:
Q: Wiremock - "URL does not match" even though it is same I am facing an issue that Wiremock says my URLs don't match even though they are the same. Obviously I am missing something. What am I doing wrong?
WireMock.stubFor(WireMock.get(WireMock.urlPathEqualTo("/test/url?bookingCode=XYZ123&lastName=TEST"))
    .willReturn(WireMock.aResponse()
    .withStatus(200))
)

Below is the console log.
-----------------------------------------------------------------------------------------------------------------------
| Closest stub                                             | Request                                                  |
-----------------------------------------------------------------------------------------------------------------------
                                                           |
GET                                                        | GET
/test/url?bookingCode=XYZ123&lastName=TEST                 | /test/url?bookingCode=XYZ123&lastName=TEST            <<<<< URL does not match
                                                           |
                                                           |
-----------------------------------------------------------------------------------------------------------------------

Is it because I am not including Headers in the matchers?
If yes, how can I avoid matching the headers? I would like to get a response irrespective of what header I am sending.

A: Found the reason.. WireMock.urlPathEqualTo("/test/url?bookingCode=XYZ123&lastName=TEST") should not have query params.
Changing it to WireMock.urlPathEqualTo("/test/url") resolved the issue.
Documentation says it is allowed. Also, the log URL does not match was causing the confusion. Considering the match check is separate, wiremock could have added a separate log for query param.
Created issue : https://github.com/tomakehurst/wiremock/issues/1262

A: You can go with withQueryParam method for the parameters while keeping urlPathEqualTo method dedicated to URL path.
WireMock.stubFor(WireMock.get(WireMock.urlPathEqualTo("/test/url"))
         .withQueryParam("bookingCode", WireMock.equalTo("XYZ123"))
         .withQueryParam("lastName", WireMock.equalTo("TEST"))
         .willReturn(WireMock.aResponse()
         .withStatus(200))

For more information, please refer http://wiremock.org/docs/request-matching/


text:
Q: How to get product rating using object manager in magento 2 i want to get products rating using object manager i tried below mention code but its not working for me please guide me
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$reviewFactory = $objectManager->create('Magento\Review\Model\Review');

$storeId = $this->_storeManager->getStore()->getId();
$reviewFactory->getEntitySummary($product, $storeId);

$ratingSummary = $product->getRatingSummary()->getRatingSummary();

A: Try to use this below code :
Method 1 :
$product_id = '1';
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$rating = $objectManager->create('\Magento\Review\Model\Rating');
$review = $objectManager->create('\Magento\Review\Model\Review');
$storeManager = $objectManager->create("\Magento\Store\Model\StoreManagerInterface");
$_ratingSummary = $rating->getEntitySummary($product_id);
$ratingCollection = $review->getResourceCollection()
                    ->addStoreFilter($storeManager->getStore()->getId())
                    ->addStatusFilter(\Magento\Review\Model\Review::STATUS_APPROVED)
                    ->addEntityFilter('product', $product_id);
$review_count = count($ratingCollection); // How many review in that specific product
$product_rating = '';
if ($_ratingSummary->getSum() > 0 && $_ratingSummary->getCount() > 0) {
     $product_rating = $_ratingSummary->getSum() / $_ratingSummary->getCount(); // Product rating in percentage
}

Method 2 :
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $rating = $objectManager->create('\Magento\Review\Model\Rating');
    $storeManager = $objectManager->create("\Magento\Store\Model\StoreManagerInterface");
    $ratingCollection = $rating->getResourceCollection()->addEntityFilter(
        'product',$product_id
    )->setPositionOrder()->setStoreFilter(
        $storeManager->getStore()->getId()
    )->addRatingPerStoreName(
        $storeManager->getStore()->getId()
    )->load();
    echo "<pre>";print_r($ratingCollection->getData());

Output Like :
Array
(
    [0] => Array
        (
            [rating_id] => 3
            [entity_id] => 1
            [rating_code] => Rating
            [position] => 0
            [is_active] => 1
            [entity_code] => product
        )

)

Note : Avoid to use Object Manager Method. Use Factory Method Structure.
Reference