text:
Q: How to use multiple $splice on same collection with React Immutability Helpers All:
I am pretty new to React Immutability Helpers, when I try to use $splice like:

The doc of $splice is:
{$splice: array of arrays} for each item in arrays call splice() on
  the target with the parameters provided by the item.

var update = require('react-addons-update');
var collection = [1, 2, {a: [1,2,3,4,5,6]}];
var newCollection = update(collection, {
    2: {
        a: {
            $splice: [
            [1, 1, 33, 44],
            [3, 2, 55, 66],
            ]
        }
    }
});

I thought all operations in that $splice array, should be based on original target, take my code for example:
[1, 1, 33, 44] will replace 2 with 33, 44
[3, 2, 55, 66] will replace 4, 5 with 55 66
so the final reault should be [1, 33, 44, 3, 55, 66, 6]
But the actual result is [1, 33, 44, 55, 66, 5, 6] which seems those two operation is based on previous operation result array.
So I wonder how can I apply all operations on the original target?
Thanks

A: Not too sure about React Immutability Helpers but in JS usually you would use slice to keep the array to its original value. splice does actually modify the original array so any subsequent operation will be executed with the result of the previous.


text:
Q: Configuring a Genius GW-7200 Access Point I came across an access point we had a few years ago.
I'm now trying to get it set up to work on our network.
Here are a couple of pictures:

I have plugged this into our network via the network port on the back.
I set up a DHCP reservation, based on the MAC address on the back of the access point, however I cannot ping it, nor access the web interface.
I've held down the reset button for 10 seconds, to see if that would do anything.
Google doesn't come up with anything on the matter :-(

A: Generally, when i get a router of unknown providence i do the following -

*

*plug in power (and nothing else). There should be no blinking lights, and nothing should light up other than the power light

*Plug in a system to the lan port. If its windows, i'll run ipconfig, if its linux ifconfig. I'd note down the default gateway

*go to the default gateway's ip address to check if the router works.
If it does, then you probably can connect it to an existing wired router by setting a fixed ip address, and connecting the two routers by their lan ports.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Directory string interpolation for file creation I have created something that has flash drive insertion and removal events to generate a key to use for a USB drive authenticator.
Everything works perfectly upto when I try to create the key, I can't seem to interpolate the drive label.
string BID = Sys.GetBaseboardID();
string CID = Sys.GetMachineGuID();
string k = "32 char string"; // this is where my 256 bit key goes
string iv = "16 char string"; // this is where my 128 bit key goes
string bencr = AES.Encrypt(BID, k, iv); //sorry for my strange variable names
string cencr = AES.Encrypt(CID, k, iv);
string keydir = "{dName}:\b4nk.key"; // <-- Here is the problem

StreamWriter w_r;
w_r = File.CreateText(@keydir);
w_r.WriteLine("WARNING: TOUCHING THIS FILE WILL REMOVE YOUR AUTHENTICATION\n");
w_r.WriteLine(bencr);
w_r.WriteLine(cencr);
w_r.Close();
File.SetAttributes(@keydir, FileAttributes.Hidden | FileAttributes.ReadOnly);

As you can most likely imagine, the output of the keydir string is the following: {dName}:4nk.key
There are a couple problems:

*

*\b seems to act similarly to \n (I assume it is used for 'break' or something)

*I need it to be a directory, so it requires the @ character at the start.

*If I try to do something like: string keydir = dName + ":\b4nk.key" although it works, the \b problem remains.

Solution
thanks to @Joshua Robinson I have learned something really interesting, my recent usage of python had me confused here.
to fix this you can combine the $ and @ characters to get an interpolated, verbatim string literal:
string keydir = $@"{dName}:\b4nk.key";

A: Check out the documentation on string interpolation.

The $ special character identifies a string literal as an interpolated string. An interpolated string is a string literal that might contain interpolation expressions. When an interpolated string is resolved to a result string, items with interpolation expressions are replaced by the string representations of the expression results. This feature is available starting with C# 6.

So, in order to get an interpolated string, your string literal needs to begin with the $ character.
string keydir = $"{dName}:\b4nk.key";
You should also check out the documentation on verbatim strings. Specifically, the second item in the list which describes verbatim string literals.

To indicate that a string literal is to be interpreted verbatim. The @ character in this instance defines a verbatim string literal. Simple escape sequences (such as "\" for a backslash), hexadecimal escape sequences (such as "\x0041" for an uppercase A), and Unicode escape sequences (such as "\u0041" for an uppercase A) are interpreted literally. Only a quote escape sequence ("") is not interpreted literally; it produces one double quotation mark. Additionally, in case of a verbatim interpolated string brace escape sequences ({{ and }}) are not interpreted literally; they produce single brace characters. The following example defines two identical file paths, one by using a regular string literal and the other by using a verbatim string literal. This is one of the more common uses of verbatim string literals.

It appears you've added the special @ character to the name of your variable, keydir. Using the @ character at the beginning of a variable name would allow you to use a keyword as a variable name, for example if you wanted a variable named class you could name it @class. Placing @ at the start of the variable name will not cause it to be interpreted literally if it is a string, you have to place it at the front of the string literal.
You can combine the $ and @ characters to get an interpolated, verbatim string literal:
string keydir = $@"{dName}:\b4nk.key";

A: You´re mixing two things here: string-interpolation and a verbatim string.
The first one is indicated using the $ infront:
var myString = $"{ data }whateverComesNext";

The verbatim simply escapes any slahes. As you already assumed \b is an escape-sequence. You have to escape that sequence, e.g. by using \\b. Alternativly use both verbatim and interpolation:
var myString = $@"{ data }\banyothertext"`.

A: If you mean to have in file {dName}:\b4nk.key not {dName}:4nk.key
you can replace all '\' chars to '\\'. \ breaks another \ and it remains \ but without it's function or simply add @ before string
string a = "asdak\\nsa\\b"
Or string a = @"asdak\nsa\b";
I hope it helps


text: Q: ADXL 345 interfacing with either ATmega32 A or arduino well i'm working on ADXL345 and tried using ATmega32A as master. It din't turned out and i shifted to Arduino-uno. After connecting properly using I2C, i am getting 0 as acceleration values in all the 3 axis. I have tried the code mentioned in the main arduino forum. It worked for many others as of the posts are concerned. can anyone help me in this context?


text:
Q: How to go to next and previous object in JSON array returned by json_encode with jQuery? I'm currently trying to load some JSON image data from a PHP file with AJAX, and with jQuery cycle through the results on the click of a next/previous button. I can successfully load the data when I indicate a specified index (data.record[0].image;) but I want it to load the first index and nothing else, and go to the next JSON.object.image key/value pair ON CLICK, but I can't seem to get the next previous buttons to work. Here's what I have so far..
PHP:

    include('./connection.php');
    $query = "SELECT artist, title, year, image, description, ID FROM voting";
    $result = $mysqli->query($query);

    if (!$result) die($mysqli->error);
    $array = array();
    while ($row = $result->fetch_object()) {
        $array[] = $row;

    }
    echo json_encode(array('records' => $array), JSON_UNESCAPED_SLASHES);

JSON is in the following format:
{"records":[
            {
                "artist":"At The Drive In",
                "title":"Acrobatic Tenement ",
                "year":"1996",
                "image":"./img/atdi01.jpg",
                "description":"Arguably the the pioneering album of post-hardcore, Acrobatic Tenement is At The Drive In's seminal album. ",
                "ID":"1"
            }
    ]

script.js file:
      $("#get-data").click(function(){ //load JSON data...
        $.getJSON("api.php", //gets a JSON data from api.php
          function(data){     //callback function if request succeeds

            $.each(data.records, function(i,record){
              var current = 0;
              var img = $("<img/>").attr({
                id: "album_image",
                class: "album",
                src: data.records[i].image,
                });
              $("#content").html(img);
              $("#next-bt").click(function(){
                current + 1;
                return false;
              });
              $("#prev-bt").click(function(){
                current - 1;
                return false;
              });

            });
          });           //end of callback function and end of .getJSON statement
      });               //end of button.click function

Please help! I'm about to pull my hair out.

A: Your loop is not needed. In your Ajax handler move your data to a global data variable. Then call render(). Try something like this:
var records;
var current = 0;

$("#next-bt").click(next);
$("#prev-bt").click(prev);

$("#get-data").click(function(){ //load JSON data...
   $.getJSON("api.php", //gets a JSON data from api.php
      function(data){     //callback function if request succeeds
          var records = data.records;
          render();
   }); //end of callback function and end of .getJSON statement
 });
function render(){
    var img = $("<img/>").attr({
          id: "album_image",
           class: "album",
           src: records[current].image,
     });
    $("#content").html(img);
}
function next(){
    current++;
    render();
}
function prev(){
   current--;
   render();
}

Disclaimer: There should be error checking in this code to ensure we can't go past the boundaries of the array.


text:
Q: How can I change the background and font color of a selected item in list view? I tried to change the colors with the OnCustomDrawItem event but it has no effect.
procedure TForm1.RListCustomDrawItem(Sender: TCustomListView; Item: TListItem;
 State: TCustomDrawState; var DefaultDraw: Boolean);
begin
 if cdsSelected in State then begin
  Sender.Canvas.Brush.Color:=clRed;
  Sender.Canvas.Font.Color:=clYellow;
 end;
end;

I use the default TListView component with 3 columns an ViewStyle set to vsReport.

A: The font color only will work as shown in your code.
If you want to change the Background color you will have to Draw the Item and the SubItems on your own and set DefaultDraw to false.
This could look like:
procedure TMyForm.ListView1CustomDrawItem(Sender: TCustomListView; Item: TListItem
                 ; State: TCustomDrawState; var DefaultDraw: Boolean);
var
  rt, r: TRect;
  s: String;
  i: Integer;
  c:TCanvas;

  // Fit the rect used for TextRect
  Procedure PrepareTextRect;
  begin
    rt := r;
    rt.Left := rt.Left + 5;
    rt.Top := rt.Top + 1;
  end;

begin
  c := Sender.Canvas;
  if (cdsSelected in State) then
  begin
    c.Brush.Color := clRed;
    c.Font.Color := clYellow;
    // will get the rect for Item + Subitems in ViewStyle = vsReport
    r := Item.DisplayRect(drBounds);
    c.FillRect(r);
    // set width to get fitting rt for tfEndEllipsis
    r.Right := r.Left + TListView(Sender).Columns[0].Width;
    s := Item.Caption;
    PrepareTextRect;
    c.TextRect(rt, s, [tfSingleLine, tfEndEllipsis]);

    if TListView(Sender).ViewStyle = vsReport then
    begin // Paint the Subitems if ViewStyle = vsReport
      for i := 0 to Item.SubItems.Count - 1 do
      begin
        r.Left := r.Left + TListView(Sender).Columns.Items[i].Width;
        r.Right := r.Left + TListView(Sender).Columns.Items[i + 1].Width;
        PrepareTextRect;
        s := Item.SubItems[i];
        c.TextRect(rt, s, [tfSingleLine, tfEndEllipsis]);
      end;
    end;
    DefaultDraw := false;
  end;
end;

A: If you set ViewStyle to  vsList then you are up and running.


text:
Q: Saving controller state when html page is closed and restore again in AngularJs It is possible to save state of a controller when html page is closed and restore the state again when the page is open in AngularJs? If yes can you give me an example?
Thank you!


text:
Q: Epicycle and deferent with Tikz - Function syntax I want to build an epicyclic graph and found a useful trigonometric function on the web (URL is in comment in my MWE). My personal issue is that I can't write a complex function as a "plot" argument. I made several tries, mixing curved brackets, parenthesis and dollar, in various combinations (paying attention to pairs), it failed. The uncommented "plot" integrates sinus and cosinus and it works (indeed, it's just a small circle in the middle of the drawing). More complex - in comments - syntaxes fail and I don't understand why. I suspect that the function is handled by the PGF engine - not by TikZ - and that I'd mix the two syntaxes?
Any hint to have this working in a TikZ+LuaLaTeX environment? What are the parenthesis, curved brackets and dollar sign used for and in which combination?
\documentclass{article}
\usepackage{fontenc}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
% epicycle+deferent/epitrochoid - algorithm
% see http://www.malinc.se/math/trigonometry/spirographen.php
\def\ri{4}\def\re{1}\def\m{2} %radius internal-external, multiplicator
\draw [thick] (0,0) circle (\ri);
\foreach \a in {0,10,...,350} \draw (0,0)++(\a:\ri) circle (\re);
\draw[domain=0:360,smooth,samples=200,variable=\a] plot ({cos(\m*\a)},{sin(\m*\a)});
% \draw[domain=0:360,smooth,samples=200,variable=\a] plot ({$\ri*cos(\a)+\re*cos(\m*\a)$},{$\ri*sin(\a)+\re*sin(\m*\a)$});
% \draw[domain=0:360,smooth,samples=200,variable=\a] plot function {\ri*cos(\a)+\re*cos(\m*\a),\ri*sin(\a)+\re*sin(\m*\a)};
\end{tikzpicture}
\end{document}

A: Remove the $ pair and it should work
\documentclass{article}
\usepackage{fontenc}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
% epicycle+deferent/epitrochoid - algorithm
% see http://www.malinc.se/math/trigonometry/spirographen.php
\def\ri{4}\def\re{1}\def\m{2} %radius internal-external, multiplicator
\draw [thick] (0,0) circle (\ri);
\foreach \a in {0,10,...,350} \draw (0,0)++(\a:\ri) circle (\re);
%\draw[domain=0:360,smooth,samples=200,variable=\a] plot ({cos(\m*\a)},{sin(\m*\a)});
\draw[domain=0:360,smooth,samples=200,variable=\a] plot ({\ri*cos(\a)+\re*cos(\m*\a)},{\ri*sin(\a)+\re*sin(\m*\a)});
%\draw[domain=0:360,smooth,samples=200,variable=\a] plot function {\ri*cos(\a)+\re*cos(\m*\a),\ri*sin(\a)+\re*sin(\m*\a)};
\end{tikzpicture}
\end{document}


text:
Q: Plain Text Break Lines with Transchoice in Twig(Symfony2) I'm programming a Plain Text mail version for that I need \n for new lines.
Almost everything works but I have a problem with the transchoice filter, as I said before the break lines are being printed as text and not as break line
foo.twig.txt
{{ 'Foo.plain.intro'|transchoice(nr, {'%nr%': nr, '%name%': entity.name}) }}

messages.en
first try:
Foo.hello.test: '{1} Hello %name% \n there is one test found. \n See you later. | ]1,Inf[ Hello %name%, \n  there are %nr% tests found. \n See you later.'

After the first try the output for one element was:
Hello tester \n there is one test found. \n See you later.

Second try:
Foo.hello.test:  "{1} Hello %name% \n there is one test found. \n See you later. | ]1,Inf[ Hello %name%, \n  there are %nr% tests found. \n See you later."

Second output:
{1} Hello tester
there is one test found.
See you later.

Third try:
Foo.hello.test:  '{1} "Hello %name% \n there is one test found. \n See you later." | ]1,Inf[ "Hello %name%, \n  there are %nr% tests found. \n See you later."'

Third output:
"Hello tester \n there is one test found \n See you later."

I also tried changing the twig part including the raw filter:
{{ 'Foo.plain.intro'|transchoice(nr, {'%nr%': nr, '%name%': entity.name})|raw }}

For the third try, including the raw filter the output is:
"Hello tester \n there is one test found \n See you later."

Is there are form that something like that would work, for normal translation strings the translation has to have double quotes to recognize \n:
messages.en
Foo.hello: "Hello %name%, \n see you later"

A: You could use | to indicated the line breaks.
Foo.hello: |
  Hello %name%,
  see you later

Read yaml format.


text:
Q: Memory Leak in returning NSMutableArray from class I am quite new to Objective C for the iPhone, so I hope you wont kill me for asking a simple question.
I have made an App that works fine, except that Instruments reports memory leaks from the class below. I use it to store settings from one class and then retrieve them from another class. These settings are stored on a file so they can be retrieved every time the App is ran.
What can I do do release the "setting" and is there anything that can be done to call (use) the class in a smarter way?
Thanks
----- Below is Settings.m -----

#import "Settings.h"

@implementation Settings

@synthesize settings;

-(NSString *)dataFilePath  // Return path for settingfile, including filename
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    return [documentsDirectory stringByAppendingPathComponent:kUserSettingsFileName];
}

-(NSMutableArray *)getParameters  // Return settings from disk after checking if file exist (if not create with default values)
{
    NSString *filePath = [self dataFilePath];

    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) // Getting data from file
    {
        settings = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
    }

    else // Creating default settings

    {
        settings = [[NSMutableArray alloc] initWithObjects:
                        [NSNumber numberWithInteger:50],
                        [NSNumber numberWithInteger:50],
                        nil];

        [settings writeToFile:[self dataFilePath] atomically:YES];

    }
    return settings;
}

    ----- Below is my other class from where I call my Settings class -----

    // Get settings from file
    Settings *aSetting = [[Settings alloc] init];

    mySettings = [aSetting getParameters];
    [aSetting release];

A: In your -getParameters method you alloc/init an NSMutableArray ([[NSMutableArray alloc] initWithContentsOfFile:filePath] - i.e. retain count of 1) which you never release. You should autorelease your array before returning it: return [settings autorelease].
Note that if you need to put the setting parameters in your mySettings variable and want to keep it around, you should do mySettings = [[aSetting getParameters] retain]; so that the retain count does not drop to 0.

A: Or, better yet:

*

*declare the settings property as a retaining property, then

*use self.settings instead of settings in your -getParameters method, and finally

*call autorelease on your arrays right after alloc/initting them.

A: Managed to solve the Settings class by modifying two lines:
1: Using
    settings = [NSMutableArray arrayWithContentsOfFile:filePath]
instead of
    settings = [[NSMutableArray alloc] initWithContentsOfFile:filePath]
2: In a similar way using
     settings = [NSMutableArray arrayWithObjects:
instead of
     settings = [[NSMutableArray alloc] initWithObjects
Now I only have to solve the leak I have when I create these from another class. Any ideas how?


text:
Q: How to get MobX Decorators to work with Create-React-App v2?
Support for the experimental syntax 'decorators-legacy' isn't currently enabled

I tried adding the decorators-legacy babel plugin and @babel/plugin-proposal-decorators with { legacy: true } in .babelrc but no effect.
Anyone managed to get MobX decorators to work with CRA2?

A: Firstly, install dependencies:
yarn add react-app-rewired customize-cra @babel/plugin-proposal-decorators
Secondly, create config-overrides.js in root directory with following contents:
const {
    addDecoratorsLegacy,
    override,
    disableEsLint
} = require("customize-cra");

module.exports = {
    webpack: override(
        addDecoratorsLegacy(),
        disableEsLint()
    )
};

You should be able to use mobx + decorators now.
If you don't have mobx installed already, please run:
yarn add mobx mobx-react.
Now you can use decorators.

A: I had same issue and ended up with using mobx4 where Decorators can be used without decorator syntax.
class Store {
  //...
  @action empty() {
    this.data = []
  }

  @action add(e) {
    this.data.push(e)
  }
}

can be rewritten as
class Store {
      //...
       empty() {
        this.data = []
      }

      add(e) {
        this.data.push(e)
      }
    }

decorate(Store, {
  add: action,
  empty: action
})

You can use this feature out of the box from CRA2 and do not need to worry about transform decoracy plugin. Thanks Michel Weststrate  for this stuff
https://medium.com/@mweststrate/mobx-4-better-simpler-faster-smaller-c1fbc08008da

A: Option 1: Using decorators with CRA v2
If you refer to Mobx documentation, you can get Mobx decorators to work with CRAv2 by using Typescript:

Decorators are only supported out of the box when using TypeScript in create-react-app@^2.1.1.

However, in some cases, you might still face issues when using Mobx with other react frameworks. In that case:
Option 2: Don't use decorators
A detailed step by step guide is documented here.
If you previously defined your observer react component as:
@observer
export default class MyComponent extends React.Component

Change it to:
const MyComponent = observer(class MyComponent extends React.Component{
  /* ... */
});

export default MyComponent;

If you previously had:
@observable myElement = null;

You need to change it to:
myElement;

then:
decorate(MyComponent, {
  myElement: observable,
})

Hope this helps!

A: I did an example project of React App 2.0 with Babel 7 and Mobx(with decorators works) without eject! :
Links I used to create this project:
https://github.com/timarney/react-app-rewired/issues/348
https://github.com/arackaf/customize-cra#addbabelpluginsplugins
https://www.leighhalliday.com/mobx-create-react-app-without-ejecting

A: If you use babel 7 you have to add some config in babelrc. Install support for decorators:

npm i --save-dev @babel/plugin-proposal-class-properties @babel/plugin-proposal-decorators

And enable it in your .babelrc file:
    "plugins": [
        ["@babel/plugin-proposal-decorators", { "legacy": true}],
        ["@babel/plugin-proposal-class-properties", { "loose": true}]
    ]
}

or you can use MobX built-in utility like:
import { observable, computed, action, decorate } from "mobx";

class Timer {
  start = Date.now();
  current = Date.now();

  get elapsedTime() {
    return this.current - this.start + "milliseconds";
  }

  tick() {
    this.current = Date.now();
  }
}
decorate(Timer, {
  start: observable,
  current: observable,
  elapsedTime: computed,
  tick: action
});

I had the same problem and I used mobx-utility and every thing completely worked for me.

A: You don't have to use more packages, or change configurations.
1-  Use decorate in stores – for observable, computed :

import { observable, decorate } from "mobx"

class ToDoStore {
    todos= ["cat","dog"]
}
decorate(ToDoStore, {
    todos: observable,
  });

const store = new ToDoStore()

2-  For observer – use the follow class style:
import React from "react"
import { observer } from "mobx-react"

const TodoList = observer(class TodoList extends React.Component {
    render() {
        const {todos} = this.props.store;
        const todoL = todos.map(todo => (
{todo}
))
        return (

ToDo List

{todoL}

        );
    }
})
export default TodoList

A: While using CRA2, in order to use MOBX5 you must do following.
npm install -save mobx mobx-react

Now add following lines in your store file.
import {decorate, observable} from "mobx"
import {observer} from "mobx-react"

Now you can use something like this.
class Store {
  //...
}

decorate(Store, {
  list: observable
})

const appStore = new Store()`

A: although others answers are correct if you want to avoid boilerplate code, It's possible to use decorators in CRA2 without ejecting using https://github.com/timarney/react-app-rewired/ and https://github.com/arackaf/customize-cra

A: npm run eject
Add the bold line to /config/webpack.config.dev.js around line 162. Make sure to do the same on /config/webpack.config.prod.js otherwise the app won't build
plugins: ["@babel/plugin-proposal-decorators", { "legacy": true }],


text:
Q: Is spring rsocket thread effective? We know that the advantage of reactive programming (and thus spring-webflux) is the fact that only one thread is used to handle multiple client requests.
I want to make use of reactive programming with websockets instead of sse events, so I found that spring-boot-rsocket may be what I'm looking for.
It works but now I'm wondering what is happening under the hood: if more clients connect to my websocket server is only one thread handling the subscriptions? Or am I falling back to multiple threads?
My use case is a news feed, where clients keep a connection open and patiently wait for news they subscribed to. So, having one thread per client is a waste of resources and risks to put my application down.
In fact, suppose that on my production system I know I can afford a maximum number of x threads, let us say 200 for explaination sake. If each subscription request is in a thread and I have 200 clients connected at the same moment that means that the thread saturation will be reached!


text:
Q: Sentence about habit When we have a habit of doing something, how do we make a sentence?
He is habitual of drinking alcohol.
Does it sound fine?

A: Actually, there is a specific verb tense that implies a habit, the simple present.
Context plays an important role in this implied meaning, but on their own these sentences would certainly convey the idea that someone has a drinking habit:

He drinks a lot.
  He is a heavy drinker.
  or even
  He drinks.

A: Any of the following:

*

*He habitually drinks alcohol.

*He is in the habit of drinking alcohol.

*He has an alcohol habit. (Slightly unusual to use for this specific example, but still correct English.)

Or if it's more than a simple habit, and considered a problem:

*

*He's an alcoholic.

A: No the standard form is he has a drinking habit, or he has a habit of drinking. The latter being more kind while the former indicates alcohol abuse. And if that's the case one would simply say "he's an alcoholic". https://www.aa.org

A: "in the habit of," "habituated to":
He is in the habit of (or is habituated to) drinking alcohol.


text:
Q: Scaling Large Concurrent API Requests For Large Data Sets I am designing a component (component A) of a notification application that is integrating with a REST API (component B) which can accept a max of 10,000 concurrent requests. The data being sent is less than 1KB and will be stored in a NoSQL DB which will be read by component A and then sent to component B as concurrent as possible.  I would like to concurrently send 10,000 requests from component A to component B.  I'm planning on putting either rabbitmq or activemq between component A and B in order to control the thread counts and scale the concurrent processing in order to send a large number of concurrent requests (10,000).
Component A:
    -read all documents (less than 1kb each) from NoSQL database
    -create JMS message and push data to rabbitmq or activemq
    -the 10,000 rabbitmq or activemq listener/consumer threads will concurrently consume,
     transform NoSQL object graph to the request needed by component B and call component B
     and repeat until all messages are sent to component B

Component B:
-can't handle more than 10,000 concurrent requests
-wont support a bulk API

The data set can get into the millions and a million messages will need to be processed and sent from component A to component B as fast as possible. I'm looking into batching the messages together.
Any design ideas regarding scaling this would be greatly appreciated

A: it sounds like you're on the right path already
RabbitMQ can handle 100,000+ messages per minute, so it shouldn't have any issue hitting your 10K concurrent requests with Component B
As a message consumer, you can use a consumer prefetch setting to tell RabbitMQ how many messages it can handle at one time.
Set the prefetch to 10,000 (or less) for the code that reads from RabbitMQ, transforms the object graph and and posts to your REST api. With that in place, you should be good to go.


text:
Q: shell script issue may be because of quotes I am working on a shell script and I have to execute a MySQL query from one server to a remote DB Server. I have written this script. Script was working fine until I added

where socialr_host = "http://$NEW/"

I think this is an issue of "" inside ''. Please help me with this, I don't have much knowledge to shell scripting

SERVER_USER="root"
SERVER_HOST="192.168.0.13"
MYSQL_HOST="localhost"
MYSQL_PASS="pass"
MYSQL_USER="root"
CORES_DATABASE="/root/Desktop/cores.db"
CORES_FILESYSTEM="/root/Desktop/cores.disk"
DIFF_FILE="/root/Desktop/diff.txt"
CORES_PATH="/raid/solr/cores"
NEW="db6055.da2"

ssh $SERVER_USER@$SERVER_HOST " mysql -u $MYSQL_USER -p$MYSQL_PASS -e 'select coloumn_name from table_name where socialr_host = "http://$NEW/";' database" > $CORES_DATABASE

A: You need to escape double quotes within double quotes:
ssh $SERVER_USER@$SERVER_HOST " mysql -u $MYSQL_USER -p$MYSQL_PASS -e 'select coloumn_name from table_name where socialr_host = \"http://$NEW/\";' database" > $CORES_DATABASE

However, there are several other issues with your code, and I would avoid using Bash for something as complicated as this. If you insist on using Bash, please read up on at least quoting and SSH quoting.


text:
Q: Placing uint32_t into array of uint8_t So I have the following code:
uint32_t length = 1;
uint8_t buffer[5];

buffer[0] = htonl(length);

std::cout << (uint32_t)*buffer << std::endl;
std::cout << htonl(length) << std::endl;

The second to last line prints out 0, the last line prints out 16777216.....why....?

A: You are not actually putting the uint32_t in the array of uint8_ts. Instead, you are placing it in buffer[0]. Since length is much larger, only the lowest 8 byte will be stored. And since you've called htonl(length), the lowest 8 bytes are actually all 0 (at least if your host system is using a different byte-order than the network - and this seems to be the case here).
If you actually want to use the first four elements of buffer to be used to store length, you have to tell the compiler to re-interpret them as a uint32_t.
uint32_t length = 1;
uint8_t buffer[5];

(uint32_t&)*buffer = htonl(length);

std::cout << (uint32_t)*buffer << std::endl;
std::cout << htonl(length) << std::endl;

Not that it's a good idea to do, though ..

A: The second to last line prints out zero coincidentally -- you never stored anything in buffer. You set buffer[0] to a value that wouldn't fit there and left the rest uninitialized.
The last line prints out 16,777,216 because your platform is little-endian and htonl switches to big-endian format, so your 0,0,0,1 becomes 1,0,0,0. That's a one in the 256^3 place, and 1 * 256^3 = 16,777,216.


text:
Q: Expected number of collisions for balls and bins problem $n$ number of balls are thrown randomly to $m$ number of bins, standing in a row. The balls are labeled as $1,2,3,....n$ and bins are also labeled as $1,2,3,...,m$. The probability of $i_{th}$ ball enters in the $j_{th}$ bin is $p_{ij}$ where $\sum_{j=1}^{m}p_{ij}=1$ for all $i$. What is the expected number of collisions when all $n$ balls are thrown? Assume that balls enter into the bins are independent events (e.g the event 1st ball goes to the 5th bin and 3rd ball enters to the 5th bin are independent events).
Clarification:
Note that we count collisions over distinct and unordered pairs, that is, if three balls fall into one bin, three collisions are counted.

A: The chance that balls $i$ and $k$, $i\ne k$, enter the same bin $j$ is $p_{ij}p_{kj}$ because these balls are thrown independently.  Since they cannot collide in more than one distinct bin, and a collision must occur in some bin, the chance that these balls collide anywhere is the sum over bins of their chances of collision:
$$\Pr(i\text{ and }k\text{ collide}) = \sum_{j=1}^m p_{ij}p_{kj}.$$
This chance also is the expected number of collisions of balls $i$ and $k$.  Summing over all distinct balls gives the expected total number of collisions $N$ (because expectation is linear):
$$\mathbb{E}(N) = \sum_{1\le i\lt k \le n} \sum_{j=1}^m p_{ij}p_{kj}.$$
This can be written in matrix form in terms of the matrix $\mathbb{P} = (p_{ij})$ and the constant $n$-vector $\mathbf{1} = (1,1,\ldots, 1)^\prime$ as
$$\mathbb{E}(N) = \frac{1}{2}\left(\mathbf{1}^\prime \mathbb{P}\mathbb{P}^\prime\mathbf{1} - Tr(\mathbb{P}\mathbb{P}^\prime)\right).$$

Simulations support the correctness of this result.  For instance, the following R code simulates $10,000$ throws of $n=5$ balls into $m=8$ bins using randomly generated probabilities $p_{ij}$. (Note the implementation of the formula for $\mathbb{E}(N)$: it takes just two simple lines at the end where q and then the answer f are calculated.)  Its output is
   Mean      SE Formula       Z
 1.3489  0.0113  1.3487  0.0200

This states that the formula for $\mathbb{E}(N)$ is $1.3487$, whereas the average number of collisions observed is $1.3489\pm 0.0113$, which is just $Z=0.02$ standard errors away from the formula (indicating very close agreement).  Similarly close agreement is obtained when varying either $n$ or $m$.
#
# Generate a random transition matrix.
#
n <- 5
m <- 8
set.seed(17)
p <- matrix(rexp(n*m), n)
p <- p / rowSums(p)
#
# Throw balls into bins.
#
throw <- function(p) {
  sum(choose(table(sapply(1:nrow(p), function(i) sample(1:ncol(p), 1, prob=p[i, ]))), 2))
}
sim <- replicate(1e4, throw(p))
#
# Compare the results to the formula
#
mu <- mean(sim)
se <- sd(sim) / sqrt(length(sim))
q <- crossprod(t(p))
f <- sum(q[lower.tri(q)])
(round(c(Mean=mu, SE=se, Formula=f, Z=(mu-f)/se), 4))

A: If I understood well the problem, the answer should be the sum of binomial distributions.
Pick for example one bin. Being that every bin have the same probability of receive a ball, then the probability of a ball to fall in that chosen bin is 1/m. So you calculate the expectation of the binomial variable with n balls and p = 1/m of having more than 1 ball in a bin. And then make the sum over all the bins.
EDIT
To give you a formula. First, give that n can be big, it's better to calculate the probability of a ball not falling in the bin or only falling once. That is:
$$ P(x=0 \, or \, x=1) = (1-1/m)^n + n(1/m)(1-1/m)^{n-1} $$
so the probability of having n ball colliding should be
$$ P = m\left[1 - (1-1/m)^n - n(1/m)(1-1/m)^{n-1}\right] $$


text:
Q: Map numbered columns from a CSV file to an array with CsvHelper I have a CSV file with columns that follow a numbered logic:

So I want to store Leds values in an collection. To do so I created the following ClassMap:
public class EyeExcitation
{
    public int Dt { get; set; }
    public double[] Leds { get; set; } = new double[6];
}

sealed class EyeExcitationMap : ClassMap<EyeExcitation>
{
    public EyeExcitationMap()
    {
        Map(m => m.Dt).Name("Dt");
        Map(m => m.Leds[0]).Name("LED1 R");
        Map(m => m.Leds[1]).Name("LED2 R");
        Map(m => m.Leds[2]).Name("LED3 R");
        Map(m => m.Leds[3]).Name("LED4 R");
        Map(m => m.Leds[4]).Name("LED5 R");
        Map(m => m.Leds[5]).Name("LED6 R");
    }
}

But when I registerthe the ClassMap with
csv.Context.RegisterClassMap<EyeExcitationMap>();

I got this exception :

System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'
Inner Exception
InvalidOperationException: No members were found in expression '{expression}'.

I think it's because of the indexes.
Do you know how to do it?

A: You will need to use Convert.
sealed class EyeExcitationMap : ClassMap<EyeExcitation>
{
    public EyeExcitationMap()
    {
        Map(m => m.Dt).Name("Dt");
        Map(m => m.Leds).Convert( args => {
            var leds = new double[6];
            for (int i = 0; i < 6; i++)
            {
                leds[i] = args.Row.GetField<double>($"LED{i + 1} R");
            }
            return leds;
        });
    }
}

A: Not sure if it is the best way, but it works:
sealed class EyeExcitationMap : ClassMap<EyeExcitation>
{
    public EyeExcitationMap()
    {
        Map(m => m.Dt).Name("Dt");
        Map(m => m.Leds).Convert(args =>
        {
            double[] Leds = new double[6];
            Leds[0] = args.Row.GetField<double>("LED1 R");
            Leds[1] = args.Row.GetField<double>("LED2 R");
            Leds[2] = args.Row.GetField<double>("LED3 R");
            Leds[3] = args.Row.GetField<double>("LED4 R");
            Leds[4] = args.Row.GetField<double>("LED5 R");
            Leds[5] = args.Row.GetField<double>("LED6 R");
            return Leds;
        });
    }
}


text:
Q: how to find offset of a pattern from binary file (without grep -b) I want to get a byte offset of a string pattern from a binary file on embedded linux platform.
If I can use "grep -b" option, It would be best way but It is not supported on my machine.
machine does not support
ADDR=`grep -oba <pattern string> <file path> | cut -d ":" -f1`

Here the manual of grep command on the machine.
root# grep --help

BusyBox v1.29.3 () multi-call binary.

Usage: grep \[-HhnlLoqvsriwFE\] \[-m N\] \[-A/B/C N\] PATTERN/-e PATTERN.../-f FILE \[FILE\]...

Search for PATTERN in FILEs (or stdin)

        -H      Add 'filename:' prefix
        -h      Do not add 'filename:' prefix
        -n      Add 'line_no:' prefix
        -l      Show only names of files that match
        -L      Show only names of files that don't match
        -c      Show only count of matching lines
        -o      Show only the matching part of line
        -q      Quiet. Return 0 if PATTERN is found, 1 otherwise
        -v      Select non-matching lines
        -s      Suppress open and read errors
        -r      Recurse
        -i      Ignore case
        -w      Match whole words only
        -x      Match whole lines only
        -F      PATTERN is a literal (not regexp)
        -E      PATTERN is an extended regexp
        -m N    Match up to N times per file
        -A N    Print N lines of trailing context
        -B N    Print N lines of leading context
        -C N    Same as '-A N -B N'
        -e PTRN Pattern to match
        -f FILE Read pattern from file

Since that option isn't available, I'm looking for an alternative.
the combination of hexdump and  grep can be also useful
such as
ADDR=`hexdump <file path> -C | grep <pattern string> | cut -d' ' -f1`

But if pattren spans multiple lines, it will not be found.
Is there a way to find the byte offset of a specific pattern with a Linux command?

A: Something like this?
hexdump -C "$file" |
awk -v pattern="$pattern" 'residue { matched = ($0 ~ "\\|" residue)
  if (matched) print $1; residue = ""; if (matched) next }
$0 ~ pattern { print $1 }
{ for(i=length(pattern)-1; i>0; i--)
  if ($0 ~ substr(pattern, 1, i) "\\|$") { residue=substr(pattern, i+1); break } }'

The offset is just the first field from the hexdump output; if you need the precise location of the match, this requires some additional massaging to figure out the offset to add to the address, or subtract if it was wrapped.
Briefly tested in a clean-slate Busybox Docker container where hexdump -C output looks like this:
/ # hexdump -C /etc/resolv.conf
00000000  23 20 44 4e 53 20 72 65  71 75 65 73 74 73 20 61  |# DNS requests a|
00000010  72 65 20 66 6f 72 77 61  72 64 65 64 20 74 6f 20  |re forwarded to |
00000020  74 68 65 20 68 6f 73 74  2e 20 44 48 43 50 20 44  |the host. DHCP D|
00000030  4e 53 20 6f 70 74 69 6f  6e 73 20 61 72 65 20 69  |NS options are i|
00000040  67 6e 6f 72 65 64 2e 0a  6e 61 6d 65 73 65 72 76  |gnored..nameserv|
00000050  65 72 20 31 39 32 2e 31  36 38 2e 36 35 2e 35 0a  |er 192.168.65.5.|
00000060  20                                                | |

A: Set the pattern as the record separator in awk. The offset of the occurrence is the length of the first record. BusyBox awk treats RS as an extended regular expression, so add backslashes before any of .[]\*+?^$ in the pattern string.
<myfile.bin awk -v RS='pattern' '{print length($0); exit}'

If the pattern contains a null byte, you need a little extra work. Use tr to exchange null bytes with some byte value that doesn't appear in the pattern. For example, if the pattern's hex dump is 00002a61:
<myfile.bin tr '\0!' '!\0' | awk -v RS='!!-A' '{print length($0); exit}'

If the pattern is not found, this prints the length of the whole file. So if you aren't sure whether the pattern is present, you need again some extra work. Append some text that can't be part of a pattern match to the file, so that you know that if there's a match, it won't be at the very end of the file. Then, if the pattern is present, the file will contain at least two records. But if the pattern is not present, the file only contains the first record (without a record separator after it).
{ cat myfile.bin; echo garbage; } |
awk -v RS='pattern' '
    NR==1 {n = length($0)}
    NR==2 {print n; found = 1; exit}
    END {exit !found}
'


text:
Q: Way to forbid global variables in a C++ function? Is there any idiom or C++ feature that alerts or forbids the use of global variable in a function?
Maybe, there can be [[noglobal]] just like [[nodiscard]] attribute which makes warning when return value is not used...


text:
Q: How can I manage Twig inheritance across multiple bundles? I'm (still) a beginner with Symfony and have been reading about three-level inheritance with Twig.
If you define blocks in your bundle their names might be bundle specific and not match block names defined in your app base.html.twig or other bundles, or even the names could be the same but the usage could be different.

*

*Has anyone found this to be a problem?

*Are there ways to manage this, will overriding templates under app/ help?

*Are there any conventions for block names or anything else that will minimise maintenance problems?

A: Block names should have some sort of relation to whats going to place within the block. so if you have css styles within a block you would call it Stylesheets, and for javascript files call it JavaScript. As far bundles, create a layout.html.twig within the views folder and extend the base.html.twig.


text:
Q: Proper way to handle FTP over SSL with restrictive firewall rules? Without SSL, FTP works fine over a stateful Firewall, like netfilter (iptables) + the nf_conntrack_ftp kernel module like this:
# modprobe nf_conntrack_ftp
# iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
# iptables -A INPUT -p tcp --dport 21 -j ACCEPT

The problem is that, when SSL is used, the FTP connection tracking module cannot work because it is unable to spy on the session to discover the session-port chosen for data exchange. It is thus unable to open that port dynamically.
Is there a proper way to make a SSL-enabled FTP server work, without disabling the firewall?
For information, I use vsftpd with the ssl_enable=YES configuration option.

A: There are several modes with SSL and FTP:

*

*Implicit SSL, that is SSL from start (usually port 990) and never plain text. In this case you get no clear text information at the firewall about the dynamic data ports and thus cannot restrict communication to only these ports.

*Explicit SSL with "AUTH TLS" command before login to enable SSL but without CCC after login to disable SSL. Here you have the same problem as with implicit SSL, that is you cannot read which data ports are in use.

*Explicit SSL as before but with CCC command after login. In this case the login is protected by SSL, but the rest of the control connection uses plain text. The data transfer can still be protected by SSL. You must enable this mode at the client, like with ftp:ssl-use-ccc with lftp. There is no way to enforce this mode at the ftp server.

If you cannot get the exact data ports because the relevant commands are encrypted you could at least make the firewall a bit less restrictive:

*

*In active mode ftp the server will originate the data connections from port 20 so you can have an iptables rule allowing these connections, i.e. something like
iptables -A OUTPUT -p tcp --sport 20 -j ACCEPT and additionally accept established connections.

*In passive mode ftp you could restrict the port range offered by vsftpd with pasv_max_port and pasv_min_port settings and add a matching rule like iptables -A INPUT -p tcp --dport min_port:max_port -j ACCEPT. This is not very restrictive but at least more restrictive than disabling the firewall.


text:
Q: Converting floats to n-byte binary integer Given the following base 10 decimals
a)3.75
b)0.7
c)89.9
convert a) to integer binary 1 byte,
convert b) to integer binary 2 byte,
convert c) to integer binary 3 byte.
These questions are pretty confusing, but I have a guess as to the solution.
a = 37? With the 5 lost. I assume this is true because 375 couldn't be stored in one byte. Then if you divide by 10 you get 3.7 which brings you back to the original number, without the 5.
b = I have no idea...
c = I have no idea...
I would assume for b and c there would be repeating digits since they are fractions and there is a lot of room for precision since 2 bytes=65536 and 3 bytes=16777216. But I don't really have a guess as to how they would be represented. Maybe for b, there would be repeating 0s and for c, repeating 9s?
I would appreciate someone telling me if I am even on the right track here. If not, what is the question asking me to do? You don't have to give me all the answers, I would just appreciate some guidance.


text:
Q: Problems filtering columns that have many rows with a None value(Django database) I am filtering a certain column in PostgreSQL database.
 n = Database.objects.values(column).count()
        for i in range(0, n):
            name = list(Database.objects.all().values_list(column, flat=True))[i]

There are 105 lines. From line 86 onwards the values are None. However, when querying line 43, the returned value is None, although in the database this line is filled with a value.
Strangely, when I populate lines 86 onwards, the query on line 43 is correct and does not return a None value.
I want to know if there is any problem when filtering columns that have many None values and why this might be happening

A:
I want to know if there is any problem when filtering columns that have many None values

No, there is no problem with that.

A relational database contains sets of rows,
named "tables".
Sets are unordered. Yet you speak of values
starting at this or that offset, as though
we had a list of values where order matters.
I recommend that you order your result rows
so they appear in a reproducible sequence.
Use ORDER BY with the database,
and sorted( ... ) for python expressions.


text:
Q: Solve $\frac{d^2x}{dt^2}= 1-(ax)^4$ Can you help me solving this differential equation? I am at the beginning of studying them and I have many doubts about understanding the good method to choose.
Thanks!!
$$\frac{d^2x}{dt^2}= 1-(ax)^4$$

A: The trouble here is we need to get rid of the second derivative and replace it with a first. A standard trick is to multiply both sides by $dx/dt$ and integrate
$$\int  \frac{dx}{dt} \frac{d^2 x}{dt^2} \ dt = \int \left( 1 - (ax)^4 \right) \frac{dx}{dt} \ dt$$
$$\int v \frac{dv}{dt} \ dt = \int \left( 1 - (ax)^4 \right)  \ dx $$
where $v = dx/dt$. Hence
$$\int v  \ dv = \int \left( 1 - (ax)^4 \right)  \ dx $$
or
$$\frac{1}{2} \left( \frac{dx}{dt} \right)^2 \ = \ x - \frac{a^4}{5}x^5 + C$$
Take the square root and you now have a separable equation. The resulting integral is a bit ugly.


text:
Q: Python: TypeError: Value must be a sequence My code:
def write_excel(filename, sheetname, dataframe):
    with pd.ExcelWriter(filename, engine='openpyxl', mode='a') as writer:
        workBook = writer.book
        try:
            workBook.remove(workBook[sheetname])
        except:
            print("Worksheet does not exist")
        finally:
            dataframe.to_excel(writer, sheet_name=sheetname, index=False)
            writer.save()

write_excel(r"C:\Users\Harshad\Documents\Project\Files\Backtest.xlsx", '888', df_normalized)

Error at:
 write_excel(r"C:\Users\Harshad\Documents\Project\Files\Backtest.xlsx", '888', df_normalized)

I am getting at error as:
Traceback (most recent call last):
  File "C:/Users/Harshad/Documents/Project/Code/Step-4-Normalizing 888Sport Odds.py", line 66, in <module>
    write_excel(r"C:\Users\Harshad\Documents\Project\Files\Backtest.xlsx", '888', df_normalized)
  File "C:/Users/Harshad/Documents/Project/Code/Step-4-Normalizing 888Sport Odds.py", line 55, in write_excel
    with pd.ExcelWriter(filename, engine='openpyxl', mode='a') as writer:
  File "C:\Users\Harshad\PycharmProjects\Self Project\venv\lib\site-packages\pandas\io\excel\_openpyxl.py", line 25, in __init__
    book = load_workbook(self.path)
  File "C:\Users\Harshad\PycharmProjects\Self Project\venv\lib\site-packages\openpyxl\reader\excel.py", line 315, in load_workbook
    reader.read()
  File "C:\Users\Harshad\PycharmProjects\Self Project\venv\lib\site-packages\openpyxl\reader\excel.py", line 280, in read
    self.read_worksheets()
  File "C:\Users\Harshad\PycharmProjects\Self Project\venv\lib\site-packages\openpyxl\reader\excel.py", line 266, in read_worksheets
    pivot = TableDefinition.from_tree(tree)
  File "C:\Users\Harshad\PycharmProjects\Self Project\venv\lib\site-packages\openpyxl\descriptors\serialisable.py", line 83, in from_tree
    obj = desc.from_tree(el)
  File "C:\Users\Harshad\PycharmProjects\Self Project\venv\lib\site-packages\openpyxl\descriptors\sequence.py", line 85, in from_tree
    return [self.expected_type.from_tree(el) for el in node]
  File "C:\Users\Harshad\PycharmProjects\Self Project\venv\lib\site-packages\openpyxl\descriptors\sequence.py", line 85, in <listcomp>
    return [self.expected_type.from_tree(el) for el in node]
  File "C:\Users\Harshad\PycharmProjects\Self Project\venv\lib\site-packages\openpyxl\descriptors\serialisable.py", line 103, in from_tree
    return cls(**attrib)
  File "C:\Users\Harshad\PycharmProjects\Self Project\venv\lib\site-packages\openpyxl\pivot\table.py", line 601, in __init__
    self.x = x
  File "C:\Users\Harshad\PycharmProjects\Self Project\venv\lib\site-packages\openpyxl\descriptors\sequence.py", line 25, in __set__
    raise TypeError("Value must be a sequence")
TypeError: Value must be a sequence

This code worked till yesterday. How can I resolve it?
Thanks

A: Don't know if it will help, but the engine parameter is deprecated. This other answer looks promising though:
Solution: Pandas Excel Writer using Openpyxl with existing workbook
Docs:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.ExcelWriter.html

A: The problem was with openpyxl. The version I was running was 3.0.5.
It works perfectly with 3.0.4 but not with the later versions. I did not get a chance to test the 3.0.6 version though.
Downgrading to 3.0.4 helped and worked.


text:
Q: Some questions on how the review algorithms work exactly I would like to know how the review algorithm 'decides' that a late post need to be reviewed.
When a user fails a review audit, he gets this:

If the same user failed too many review audits, he gets this:

I would like to know the part of the algorithm that 'decides' the duration of the review suspension.
How does the algorithm decide that a user needs to be banned (definitively) from the review queues?

A: This answer does cover the duration aspect of your question. It's a rolling 30 day window - a fourth within 30 days is not possible:

3rd ban within the window -> duration: 30 days

As you're automatically in a new window when a 30 day ban has concluded, it rolled over again, and back to the beginning you go.
While this does include 30 day bans that moderators impose, they can in very rare circumstances impose longer periods back-to-back. Possible reasons for this might include:

*

*A history of rubber-stamping spam posts, or suggested edits that introduce spam

*A long history of failed audits with no demonstrated improvement and no decline in activity (usually accompanied with a "reviews don't seem to be your thing, please stop" message)

To your first question, the late answers queue picks up on any new user that posts an answer to an old question. What we're trying to catch here is:

*

*Thanks, this helped me!

*Buy discount Gucci socks on my sports blog

*I tried the above, but I still get this error...

*hakdjhsdlkjahadklfjhdlksjafhsldkjfhlsdkajfhlsdkfh

*A copy and paste of an existing answer in a bungled attempt to lift new user restrictions

We're not just looking at the answers here, folks also look at the question to see if there might be a reason why an old question continues to attract new answers (is it open-ended? does it need protecting? is it still on-topic by our standards today?)
This used to be accomplished just through the automatic 'churn' of old posts being bumped to the front page as a result of new activity, but our sheer volume these days demands something more comprehensive.
The algorithm itself is pretty simple, one in n items you review is likely to be an audit, but there's a random seed at play too - you could go n(2) iterations before seeing one in some circumstance. It's perfectly fine to fail one or two as long as you are paying attention - audits aren't perfect and can sometimes present you with a very subjective call to make; we take this into account.
Like most things designed to be remarkably simple, it's very difficult to game (well, except for some things that can make an audit obvious, but we're not out to catch folks that are actually, you know, paying attention :))


text:
Q: Facing Assertion failed: (thread_id_key != 0x7777), function find_thread_id_key, file ../src/coroutine.cc, line 134 when I do npm start When I did npm login, Got ERR! Code 426. So did
$npm cache clean --force
$rm -rf node_modules package-lock.json
$npm install
npm install did succeed with 200 OK.
When I do npm start, facing assertion failed(v16). When I googled it's asking to install earlier versions of node.js. I tried installing v14 - couldn't locate the .npmrc file and adding it didn't work. I tried installing v12 - Apple is not allowing to install & asking to install the later version. So any help would be appreciated.
[1] depict npm login error [2] depict assertion failed error
[1]: https://i.stack.imgur.com/DPNrt.png
[2]: https://i.stack.imgur.com/sUms0.png

A: Probably an issue with fibres in Node ^16.x, try :
npm uninstall fibers && rm package-lock.json && rm -R node_modules && npm install

A: I had the same issue, This works for me 'npm uninstall fibers && rm package-lock.json && rm -R node_modules && npm install'


text:
Q: How to move the WordPress webpage to other hosting servers? Crrently I am trying to moving my wordpress website to new paid hosting service godaddy. It is a wordpress managed hosting. I have gone throgh a lot on internet on moving wordpress from one host to other host. The suggested duplicator plugin was not working for me. Finally, I tried the follwing:-
Assume that my old website name is
www.old-site.org

My new (temperory) address is
www.new-site.org

I downloaded the entire website from www.old-site.org
Downloaded database backup from wordpress. Then edited the old wp-config.php replaced the database name, username and password with the new site's database details. Finally used filezilla to move the old site files to www.new-site.org/new location. After all done, typed www.new-site.org/new/wp-login.php in firefox. A login window appeared and asked for the password. It looks like all done. However, after login the site addreas goes to www.old-site.org/wp-admin/. What is the mistake I have done and how do I overcome this issue? Do I have to replace URL in any file?
Edit:-
Ok. I did the following now. Downloaded the old *.sql database. Used http://pixelentity.com/wordpress-search-replace-domain/ lik for changing old url with new one. Then I gone to godaddy phpAdmin --> import database and imported the modified Sql file. But the result is same. After login  the site is going back to old url.

A: *

*Place all the files from public_html folder of old server to the new public_html folder.

*Take the database backup from old server from php myadmin, go to import in it and import sql file.

*open the sql database file in editor such as notepad++ or anything and find siteurl where you will find old website address as something like http://www.oldsite.com you have to replace all such old url in to your new url so use ctrl+f and replace www.oldsite.com to www.newsite.com and save the sql file

*on your new server create new database and take note of its username, password and database name

*on your new server open phpmyadmin and export the sql file to the new database so created.

*open wp-config.php that will be in your public_html(root) folder in new server and replace database name, database user name and user name password (that you have noted in step 4).
if followed correctly it should work.

Alternatively for database URL replacement you can use wp migrate db plugin that takes care of serialized arrays..
Also for complete automatic migration you can use all-in-one wp migration plugin which is also good

A: You  must edit your wpconfig.php to contain the new "base url" and besides that, edit your database to have the right URL.
Otherwise it will always redirect you to your old site.
WPconfig:
define('WP_HOME','http://example.com');
define('WP_SITEURL','http://example.com');

Database:
Look for the table wp_options.
Find under option_name the "siteurl" and change the option_value to contain the new URL.
Might also want to look @ http://codex.wordpress.org/Changing_The_Site_URL

A: Please make sure in your 'wp_options' table the values for :
'siteurl' and 'home' should be => www.new-site.org

A: Please run these SQL queries in your database:
UPDATE wp_options
SET option_value = replace(option_value, 'www.old-site.org', 'www.new-site.org')
WHERE option_name = 'home' OR option_name = 'siteurl';

UPDATE wp_posts
SET guid = replace(guid, 'www.old-site.org', 'www.new-site.org');

UPDATE wp_posts
SET post_content = replace(post_content, 'www.old-site.org', 'www.new-site.org');

UPDATE wp_postmeta
SET meta_value = REPLACE (meta_value, 'www.old-site.org','www.new-site.org');

A: The database will contain references to the old url, to fix you can edit the .sql backup before reimporting it:
Delete the database on your new host.
Open the sql backup file from your old host in notepad or similar texteditor
Do a find and replace for www.old-site.org to www.new-site.org/new, save, and import into new hosting.

A: You need change all places where your old URL is recorded in database.
For that you can use this plugin: https://wordpress.org/plugins/search-and-replace/
Using this 'Search and Replace' look for 'www.old-site.org' and replace to 'www.new-site.org/new'.
In your wp-config is important find all old URL and replace to the new too.
I hope it helps!

A: As pointed out by the previous answers, the unique thing you have to do is to change the references to old url with references to the new ones.
To do this, you ha ve to change the configuration settings in your wp-config.php file as pointed out by Chilion:
define('WP_HOME','http://example.com');
define('WP_SITEURL','http://example.com');

Once you have done this, you have to change references also for slugs.
The URL of slugs are more complex to change, as they cannot be simply edited: they are serialized, so you need a dedicated script.
Here there are all the information you need: http://codex.wordpress.org/Moving_WordPress
Duplicator is really a great plugin to automate the migration: what didn't exactly work for you? Which is the problem?

A: For those of you missing the old tool by Pixelentity (that unfortunately has been shut down since) linked in the original post, I wanted to let you know there is an exact clone of that tool available at wordpress-search-replace.io


text:
Q: how to open multiple netcdf files stored in multiple folders Python right now I am able to open multiple netcdf files from a single folder using the command given below:
dsmerged = xarray.open_mfdataset('F:/netcdf/example/*.nc')

However, I am unable to open multiple netcdf files from different folders or directories using this command. Suppose I am having multiple netcdf files stored in multiple folders so how can I open together? Suggestions are appreciated.

A: From the docs, you can either pass in a glob string (like you have) or a list of explicit filenames to open. Therefore I would do the following:
import glob

# Get a list of all .nc files available in different folders
filenames = glob.glob("/parent/directory/*/*/*.nc")

dsmerged = xarray.open_mfdataset(filenames)

This works on Python 2.7 and 3.6.
Note you may have to run this a few times and concatenate the returned lists if not all files are in the same directory structure. I.e. if some .nc files are in /path/one/here/file.nc and others are in /path/here/file.nc


text:
Q: Solve $(3y^4-11x^2y^2-28x^4)\,dx-(4xy^3)\,dy=0$
I'm trying to solve the equation $$(3y^4-11x^2y^2-28x^4)\,dx-(4xy^3)\,dy=0$$

The equation is not exact i.e. $M_y \neq N_x$, also $\frac{M_y-N_x}{N}$ is not a function of $x$ alone , $\frac{N_x-M_y}{M}$ is not a function $y$ alone. If I separate the equation it becomes $$\frac{dy}{dx}=\frac34\frac yx-\frac{11}{4} \frac yx -7\frac{x^3}{y^3}$$
which after substituting $t=\frac yx$, we get $$ \frac{x dt}{dx} =-\frac{t}{4} -\frac{11}{4t}-\frac{7}{t^3}$$ which is quite difficult to integrate. I guess there should be a solution in implicit form.

A: The RHS is $\frac{-t^4-11 t^2-28}{4 t^3}$, so this is just
$$-\frac{4t^3}{t^4+11t^2+28}\,dt = \left(-\frac{16 t}{3 (t^2+4)}-\frac{28 t}{3 (t^2+7)}\right)\,dt = \frac{dx}{x}.$$

A: Yes you are going on right track. I'm continuing to solve from your last step.
$\begin{align}
\frac{xdt}{dx}&=-\frac{t^4+11t^2+28}{4t^3}\\
\int\frac{4t^3dt}{t^4+11t^2+28}&=-\int\frac{dx}{x}\\
\int\frac{2du}{u^2+11u^2+28}&=-\int\frac{dx}{x}\quad...(t^2=u)\\
\int\frac{2u+11-11}{(u+4)(u+7)}&=-\int\frac{dx}{x}
\end{align}$
Now, separate the terms on LHS by partial fraction.
$$\int\frac{1}{u+4}+\frac{1}{u+7}-\frac{11}{3}\left(\frac{1}{u+4}-\frac{1}{u+7}\right)dx=-ln(x)+c$$
I think you can proceed now by doing some elementary integrals.
Note:You can also write RHS as $-ln(xc)$ as $ln(c)$ is also a constant.


text:
Q: Custom wordpress category loop listing page I'm trying to build a wordpress theme for a magazine site I plan on launching and I'm kind of stuck on a certain issue.
I'm listing my posts in a 3 column layout and I'd like to create a page where I can list all my categories along with a category image in the same style. I was thinking that wordpress had a loop function for listing categories but I must have been mistaken.  Is this something that's possible?
I plan on having quite a few categories, and I have a custom post type with it's own taxonomy and I'd like to create a page that lists all the categories along with category descriptions.
I am very much a novice at coding.  Here's the html prototype for the design I'm building in wordpress: link
You can see how I have the posts laid out. What I'm looking to build is a custom page template that will list all my categories in the same format.
Any advice or direction anyone could give me would be awesome! I don't know any other web developers where I'm from.

A: Wordpress does have a built in function for getting your categories. You can use PHP to do this. If you want to do it dynamically, you could use either a foreach or a while loop. Since categories on wordpress are stored by numeric ID's (ex: home.php = 1). For the pictures part I would simply set the pictures name to the same ID as the category, and include something like /img + i + .jpg, where i is the current category your loop is on. You can find more info on how to set this all up here on the wordpress site, also you might find some of the info here useful.


text:
Q: catch http.call timeout exception This Meteor server code uses http@1.2.8, during slow internet connection it prints the below to the terminal:
response = HTTP.call(method, url, {
  timeout: 30000,
  headers: header,
  content: content,
  followRedirects: true
});

Exception in callback of async function: Error: ETIMEDOUT
   at Object.Future.wait (/abc/xyz/.meteor/packages/meteor-tool/.1.4.0.i9pn2o++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/dev_bundle/server-lib/node_modules/fibers/future.js:449:15)

How do I gracefully catch this error so that I can inform the client? Thanks

A: Just use a try catch
try{
    response = HTTP.call(method, url, {
        timeout: 30000,
        headers: header,
        content: content,
        followRedirects: true
    });
}
catch(e){
    if(e.code==="ETIMDOUT"){
        //alert the client
    }
}


text:
Q: Manually deploy LetsEncrypt certificate to Kubernetes One of my systems (Rocky Linux 9) collects wildcard certificates from LetsEncrypt and distributes it to the various systems that require an SSL certificate.
I also have AWX running on Kubernetes (CentOS Stream 8) and I want to use the LetsEncrypt certificate for that system as well (So I DON'T want Kubernetes to manage the certificate)
How can I deploy the certificates to Kubernetes and which of the files cert.pem, chain.pem, fullchain.pem and privkey.pem are required?
Thanx in advance for your help


text:
Q: Image not displaying (but loading) in PDF generation using resource stream I created a PDF using PDFBOX. The entire PDF generates perfectly and even the images loaded while i was using
PDImageXObject ptabelle = PDImageXObject.createFromFile("src/main/resources/pdf/ptabelle.png", pdDocument);

But the project will need to go live sometime so I have to replace the static path with a class loader. After doing all that the PDF generates, the text is displayed, but not the image.
The interesting thing is that inside the PDF the "box" where the image should be is there, but not the image.

Here is the code for the stream generation.
ClassLoader classLoader = getClass().getClassLoader();
PDStream pdStream = new PDStream(pdDocument, classLoader.getResourceAsStream("pdf/ptabelle.png"));
PDResources pdResources = new PDResources();
PDImageXObject ptabelle = new PDImageXObject(pdStream, pdResources);

PDPageContentStream pdPageContentStream = new PDPageContentStream(pdDocument, page4);

And here is the call in the code, the length + width variables are defined in the code.
 pdPageContentStream.drawImage(ptabelle, TEXT_BEGIN, currentYCoord, 172, 107);

A: Instead of new PDImageXObject(pdStream, pdResources) which is for PDFBox internal use, please use the appropriate LosslessFactory method. So your code would look like this:
BufferedImage bim = ImageIO.read(classLoader.getResourceAsStream("pdf/ptabelle.png"));
PDImageXObject img = LosslessFactory.createFromImage(pdDocument, bim);

See also the javadoc of PDImageXObject.createFromFileByExtension, which explains what factory methods can be called instead.


text:
Q: Does Decorator pattern have a disadvantage for "bulky" classes with many fields? So we all know about the good 'ol Decorator pattern, especially I couldn't find any cons as such over Internet. But there is one big one I could think of:
If your base class happens to be bulky(holds like 50 fields) and you decide to decorate it:
public class BulkyBaseClass {

    // 50 fields
    //...
}

class Decorator extends BulkyBaseClass{

    private BulkyBaseClass mBase;

    public Decorator(BulkyBaseClass bulkyBaseClass){
        this.mBase = bulkyBaseClass;
    }

    // Some overrides to decorate the composed base class
}

Then, can't we see here that most of the fields of the decorator itself are useless and we are really only interested in the fields of the class being decorated and that leads to a big memory footprint?
To me, that's a big disadvantage. Isn't it?

A: Yes, direct use of decorator pattern does have a disadvantage for classes with multiple fields, because their majority remain unused in the derived class that wraps mBase instance.
However, the disadvantage stems from inheriting implementation, rather than inheriting an interface. Therefore, you can easily fix it by extracting an interface from BulkyBaseClass, and using it inside the Decorator class:
interface LeanInterface {
    void method1();
    int method2();
}
class BulkyBaseClass implements LeanInterface {
    ...
}
class Decorator implements LeanInterface {
    private BulkyBaseClass mBase;
    ...
}

A: That's not a problem of decorating, but yet another problem of inheritance.
Decorate through interfaces whenever you can, like this:
public interface Connection {
    void connect();

    void write(byte[] data) throws IOException;
}

public final class ReconnectingConnection implements Connection {
    private final Connection delegate;

    public ReconnectingConnection(Connection delegate) {
        this.delegate = delegate;
    }

    ...
    @Override
    public void write(byte[] data) {
        ...reconnect on exception from delegate.write()...
    }
}

Using own implementation on interfaces makes sure you're not actually coupling to a specific implementation, and also avoids problems with some implementations being too large.
When faced with external classes that you want to decorate this obviously is not always possible.


text:
Q: Почему при неверном четвертом элементе строки у меня выводится "Yes"? #include <iostream>
#include <string>
using namespace std;
int main ()
{
    int k;
    cin >> k;
    string arr[k];
    for (int i = 0;i < k ;i++)
    {
        cin >> arr[i];
    }
    for (int i = 0;i < k;i++)
    {
        string S;
        S = arr[i];
        cout << S[4];
        if (S[0] == 'A' || S[0] == 'B' || S[0] == 'C' || S[0] == 'E' || S[0] == 'H' || S[0] == 'K' || S[0] == 'M' || S[0] == 'O' || S[0] == 'P' || S[0] == 'T' || S[0] == 'X' || S[0] == 'Y' && S[1] >= 48 && S[1] <= 57 && S[2] >= 48 && S[2] <= 57 && S[3] >= 48 && S[3] <= 57 && S[4] == 'A' || S[4] == 'B' || S[4] == 'C' || S[4] == 'E' || S[4] == 'H' || S[4] == 'K' || S[4] == 'M' || S[4] == 'O' || S[4] == 'P' || S[4] == 'T' || S[4] == 'X' || S[4] == 'Y')
        cout << "Yes" << endl;
        else
        cout << "No" << endl;
                                                                                // A, B, C, E, H, K, M, O, P, T, X, Y.
    }
}

Однажды Вася очень долго просидел на остановке, прежде чем дождался своего автобуса. Чтобы как-то занять время, он решил записывать на листочке государственные регистрационные номера проходящих мимо автобусов, следующих по другому маршруту, нежели нужен был Васе. При этом производилась запись лишь основного номера, без учета региональной принадлежности. В итоге Васе удалось записать N таких номеров.
Основная часть государственного регистрационного номера состоит из 6 символов: трех букв и трех цифр. Сначала идет буква, затем 3 цифры и еще 2 буквы заканчивают запись. В качестве цифр могут использоваться любые цифры от 0 до 9, а в качестве букв только прописные буквы, обозначения которых присутствуют как в английском, так и в русском алфавите, т.е. только следующие символы: A, B, C, E, H, K, M, O, P, T, X, Y. Например, «P204BT» - правильный номер, а «X182YZ» и «ABC216» - нет.
Ваша задача заключается в проверке правильности проделанной Васей работы. А именно, нужно определить, какие из номеров соответствуют принятому стандарту, а какие нет.
Входные данные
Первая строка входного файла INPUT.TXT содержит единственное натуральное число N – количество записанных Васей номеров (N ≤ 50). Далее следует N строк с записями номеров автобусов. Длины строк от 1 до 300 и содержат только символы с кодами ASCII от 33 до 127 (не содержат пробелов, специальных и русских символов).
Выходные данные
В выходной файл OUTPUT.TXT выведите N строк, в i-й строке должно содержаться «Yes», если соответствующая i-я запись номера верна и «No» в противном случае.
Пример
№   INPUT.TXT
P204BT
X182YZ
a216bc
A216BC
ABC216

output.txt
Yes
No
No
Yes
No

A: Попробуйте такой вариант:
include <iostream>
#include <string>
using namespace std;
int main ()
{
    int k;
    cin >> k;
    string arr[k];
    for (int i = 0;i < k ;i++)
    {
        cin >> arr[i];
    }
    for (int i = 0;i < k;i++)
    {
        string S;
        S = arr[i];
        cout << S[4];
        if ((S[0] == 'A' || S[0] == 'B' || S[0] == 'C' || S[0] == 'E' ||
             S[0] == 'H' || S[0] == 'K' || S[0] == 'M' || S[0] == 'O' ||
             S[0] == 'P' || S[0] == 'T' || S[0] == 'X' || S[0] == 'Y')
         && (S[1] >= 48 && S[1] <= 57 && S[2] >= 48 &&
             S[2] <= 57 && S[3] >= 48 && S[3] <= 57)
         && (S[4] == 'A' || S[4] == 'B' || S[4] == 'C' || S[4] == 'E' ||
             S[4] == 'H' || S[4] == 'K' || S[4] == 'M' || S[4] == 'O' ||
             S[4] == 'P' || S[4] == 'T' ||  S[4] == 'X' || S[4] == 'Y'))
        cout << "Yes" << endl;
        else
        cout << "No" << endl;
                                                                                // A, B, C, E, H, K, M, O, P, T, X, Y.
    }
}


text:
Q: SPFx resolving dependency issues While following this training unit by Microsoft
Exercise - Use the SPFx PnP reusable property pane controls I encounter errors, any advice on how to resolve these issues?
Environment Info

*

*Platform: Windows

*nodeJS v16.18.1

*npm 8.19.2

*gulp CLI version: 2.3.0

*gulp Local version: 4.0.2

*yeoman 4.3.1

*@microsoft/generator-sharepoint@1.16.1

Problem
When I execute the following command
  npm install @pnp/spfx-property-controls --save --save-exact

I get this output:
    npm WARN ERESOLVE overriding peer dependency
    npm WARN While resolving: react-ace@5.8.0
    npm WARN Found: react@17.0.1
    npm WARN node_modules/@pnp/spfx-property-controls/node_modules/react
    npm WARN   react@"17.0.1" from @pnp/spfx-property-controls@3.11.0
    npm WARN   node_modules/@pnp/spfx-property-controls
    npm WARN     @pnp/spfx-property-controls@"*" from the root project
    npm WARN   6 more (@microsoft/sp-core-library, ...)
    npm WARN
    npm WARN Could not resolve dependency:
    npm WARN peer react@"^0.13.0 || ^0.14.0 || ^15.0.1 || ^16.0.0" from react-ace@5.8.0
    npm WARN node_modules/@pnp/spfx-property-controls/node_modules/react-ace
    npm WARN   react-ace@"5.8.0" from @pnp/spfx-property-controls@3.11.0
    npm WARN   node_modules/@pnp/spfx-property-controls
    npm WARN
    npm WARN Conflicting peer dependency: react@16.14.0
    npm WARN node_modules/react
    npm WARN   peer react@"^0.13.0 || ^0.14.0 || ^15.0.1 || ^16.0.0" from react-ace@5.8.0
    npm WARN   node_modules/@pnp/spfx-property-controls/node_modules/react-ace
    npm WARN     react-ace@"5.8.0" from @pnp/spfx-property-controls@3.11.0
    npm WARN     node_modules/@pnp/spfx-property-controls
    npm WARN ERESOLVE overriding peer dependency
    npm WARN While resolving: react-ace@5.8.0
    npm WARN Found: react-dom@17.0.1
    npm WARN node_modules/@pnp/spfx-property-controls/node_modules/react-dom
    npm WARN   react-dom@"17.0.1" from @pnp/spfx-property-controls@3.11.0
    npm WARN   node_modules/@pnp/spfx-property-controls
    npm WARN     @pnp/spfx-property-controls@"*" from the root project
    npm WARN   5 more (@microsoft/sp-core-library, ...)
    npm WARN
    npm WARN Could not resolve dependency:
    npm WARN peer react-dom@"^0.13.0 || ^0.14.0 || ^15.0.1 || ^16.0.0" from react-ace@5.8.0
    npm WARN node_modules/@pnp/spfx-property-controls/node_modules/react-ace
    npm WARN   react-ace@"5.8.0" from @pnp/spfx-property-controls@3.11.0
    npm WARN   node_modules/@pnp/spfx-property-controls
    npm WARN
    npm WARN Conflicting peer dependency: react-dom@16.14.0
    npm WARN node_modules/react-dom
    npm WARN   peer react-dom@"^0.13.0 || ^0.14.0 || ^15.0.1 || ^16.0.0" from react-ace@5.8.0
    npm WARN   node_modules/@pnp/spfx-property-controls/node_modules/react-ace
    npm WARN     react-ace@"5.8.0" from @pnp/spfx-property-controls@3.11.0
    npm WARN     node_modules/@pnp/spfx-property-controls

    added 50 packages, and audited 2693 packages in 53s

    171 packages are looking for funding
      run `npm fund` for details

    86 vulnerabilities (30 moderate, 47 high, 9 critical)

After performing the edits to the default project template as described in the tutorial gulp serve is successful - no errors, but the workbench displays an error (several other errors in dev tools as well)

The componentId
in message:
Manifest not found for component id "0d910c1c-13b9-4e1c-9aa4-b008c5e42d7d" and version "17.0.2". refers to react components.
    {
      "componentId": "0d910c1c-13b9-4e1c-9aa4-b008c5e42d7d",
      "componentName": "react",
      "componentVersion": "17.0.1",
      "isDirectDependency": false
    },
    {
      "componentId": "0d910c1c-13b9-4e1c-9aa4-b008c5e42d7d",
      "componentName": "react",
      "componentVersion": "17.0.2",
      "isDirectDependency": true
    }

Any help is appreciated.


text:
Q: How to do something on an specific position of a recyclerView adapter? I want to do something on position 0 of an adapter onBindViewHolder method.
The code is shown below:
@Override
    public void onBindViewHolder(final MyViewHolder myViewHolder, final int position) {
        if(position == 0)
        {
            myViewHolder.transparentBlackView.setVisibility(View.GONE);
        }
        Picasso.with(context).load(urlList.get(position)).into(myViewHolder.pictureImageView);
        transparentViewList.add(myViewHolder.transparentBlackView);
        myViewHolder.positionTextView.setText(position+"");
    }

But I don't know why code inside if block (myViewHolder.transparentBlackView.setVisibility(View.GONE);) runs on position 9 too?
Can someone help me?

A: You need to add else part too.
 public void onBindViewHolder(final MyViewHolder myViewHolder, final int position) {
    if(position == 0)
    {
        myViewHolder.transparentBlackView.setVisibility(View.GONE);
    }else{
   myViewHolder.transparentBlackView.setVisibility(View.VISIBLE);
    }
    Picasso.with(context).load(urlList.get(position)).into(myViewHolder.pictureImageView);
    transparentViewList.add(myViewHolder.transparentBlackView);
    myViewHolder.positionTextView.setText(position+"");
}


text:
Q: What parameters can be passed to Airflow @task decorator? I am using Airflow 2.4.0.
from airflow.decorators import task
from airflow import DAG

with DAG(
        "hello_world",
        start_date=datetime(2022, 1, 1),
        schedule_interval="@daily",
        catchup=False,
) as dag:
    @task()
    def get_name():
        return {
            'first_name': 'Hongbo',
            'last_name': 'Miao',
        }

    get_name()

Currently I am using @task(). Based on the document https://airflow.apache.org/docs/apache-airflow/stable/tutorial/taskflow.html, it seems I can also use
@task(multiple_outputs=True)
@task(retries=3)
@task(task_id="get_name")

However, it does not include the explanation.
When I use multiple_outputs=True or multiple_outputs=False, or not it, the task still runs well. So I am wondering what is the purposes of it.
Is there a document listing all parameters for @task decorator that I can use and their actual functions? Thanks!

A: Save the multiple_outputs optional argument declared in the task_decoratory_factory, every other option passed is forwarded to the underlying Airflow Operator.
When using task decorator as-is like
@task
def fn(): pass

the default operator is the PythonOperator.
You can explore the mandatory/optional parameters for the Airflow Operator encapsulated by the decorator to have a better idea of the signature for the specific task.


text:
Q: How to display the image to be in transparent and clickable? I have a transparent .png image file which I have attached it on my site, however the file has some background colour (grey) which I have no understanding why it is there. It's sure in transparent mode when I open it in any image editor or view, it has transparent background. Why when I link it, and when displaying on my site it isn't transparent ?
This is the method I'm using http://book.cakephp.org/#!/view/1441/image
I've tried embedding the image in CSS but find it a bit troublesome because I need the image to be clickable that links to my homepage.
Anyone can suggest any way to achieve the result I mentioned? ..perhaps some links or scripts that would work..I appreciate that.
:-)

A: It's possible there's some reprocessing going on. Do you have a link to the image, or better yet a link where we can see the markup / CSS as well?

A: I found a way to solve this not sure if it's the best but it works.
http://xavisys.com/css-trick-turning-a-background-image-into-a-clickable-link/

A: If you're using IE6, the grey background will be there because IE6 does not support alpha-transparency in images (without using behaviours or hacks).
This might help:
http://24ways.org/2007/supersleight-transparent-png-in-ie6


text:
Q: access form update multiple fields I'm using a form to update my table using ms access 2002, when I exit a field I would like access to duplicate the data to another field. For example, after typing address1 I would like the data to replicate to field address2. Saving time when most records have the same address in both fields.

A: I would suggest you run your code if the record is new, and ask if it is not. It is usually a good idea to rename controls on forms to ensure you are referring to the control, not the field, because by default, MS Access assigns the name of the field to the control.
Private Sub MyTextbox_AfterUpdate()
    If Me.NewRecord Then
        Me.OtherTextbox = Me.MyTextbox
    Else
        If MsgBox("Copy this?", vbYesNo) = vbYes Then
            Me.OtherTextbox = Me.MyTextbox
        End If
    End If
End Sub


text:
Q: TerminateProcess not working for specific processes I need to terminate some processes before my program can run, but whenever I run TerminateProcess(), GetLastError() returns 5. What I know so far is that this means that access is denied, I also know that to elevate my rights i need to use AdjustTokenPrivileges(), based on Rango's answer here and Microsoft's documentation here.
What i don't know is why it wont work. Based on what I've read, the following should work:
BOOL TerminateMyProcess(DWORD dwProcessId, UINT uExitCode)
{
    DWORD dwDesiredAccess = PROCESS_ALL_ACCESS;
    //DWORD dwDesiredAccess = ACCESS_SYSTEM_SECURITY;
    BOOL  bInheritHandle = FALSE;
    HANDLE hProcess = NULL;

    TOKEN_PRIVILEGES tp = { 0 };
    LUID luid;

    LookupPrivilegeValue(NULL, SE_SECURITY_NAME, &luid);

    tp.PrivilegeCount = 1;
    tp.Privileges[0].Luid = luid;
    tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    AdjustTokenPrivileges(hProcess, FALSE, &tp, 0, NULL, NULL);

    hProcess = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId);
    BOOL result = TerminateProcess(hProcess, uExitCode);

    CloseHandle(hProcess);

    return result;
}

As you can tell from the above, I am not sure which dwDesiredAccess I am supposed to use. PROCESS_ALL_ACCESS lets me terminate other simple processes, such as chrome.exe or notepad.exe, but not what i need to terminate. ACCESS_SYSTEM_SECURITY is whats' said to be used by microsoft, but then i cannot terminate any process at all.
Also, is this even close to what i need to do, if not can you please point me in the right direction.
UPDATE: Added UpdatePrivilege() function from here, and called it before calling OpenProcess() function, still no bite.
UPDATE 2: The process I need to terminate is the "afwServ.exe" process, i.e. Avast's firewall. I need to do this so that my firewall is the sole firewall used by Windows. This a requirement of my project.

A: I think you misunderstood the difference between right and privileges, this answer explains it.
In this case, your current user may not have permission to terminate the specified process. You may first need to use LogonUser and use administrator identity to simulate the process context.
What you want to terminate is a service, you can try using ControlService with SERVICE_CONTROL_STOP to stop the services. But you also need to switch to the user with permission first.


text:
Q: How can I retrieve my Google search history? In the Google Web History interface I can see all the search queries I have used over the years, and the pages I visited for a particular query. Is there a way I can retrieve this history using a computer program? I couldn't find a Google API that does it. Do you know of a tool that can do this, or suggest a way to achieve this?

A: The RSS feed in the accepted answer above does not exist anymore.  Google does not provide an API that allows you retrieve Google searches, but it does allow you to download an archive of all past searches, via google search history.  This download cannot be performed programmatically, as it saves the archive to the user's google drive.
A possible hacky workaround is using browser automation tools to scrape the history page, like this repository does.  Modifying this script would allow you to get the most recent searches.  I was able to use this for my project.

A: There's an RSS feed.
Update: the link is now broken.


text:
Q: Scrolling with ScrollView not working after adding views programmatically to hierarchy I´m adding programmatically Views to a LinearLayout, that is embedded in a ScrollView. The ScrollView however does not take into account that extended height, so scrolling won´t work. Calling invalidate() and requestLayout() on the ScrollView after adding the Views did not solve the problem. How it has to be done?
<ScrollView
    android:id="@+id/scrollView"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:fillViewport="true"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/pager">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp">

        <LinearLayout
            android:id="@+id/layout_to_which_views_are_added"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/label">

services.groupBy { it.category }.forEach { category ->
                val view = layoutInflater.inflate(R.layout.service_category, rootLayout, false)
                view.findViewById<TextView>(R.id.lblHeader).text = getStringArray(R.array.service_category_headers)[category.key]
                view.findViewById<TextView>(R.id.txtServices).text = category.value.joinToString(", ") { it.display }
                layout_to_which_views_are_added.addView(view)
            }
scrollView.invalidate()
scrollView.requestLayout()

A: Found the problem, the parenting layout of the ScrollView, a CoordinatorLayout, itself being parented by a ConstraintLayout, was missing the bottomToBottom-to-parent constraint, which would stretch it to the bottom, which then makes the ScrollView scrollable to whole content


text:
Q: Retrieve user defined properties (for Outlook emails) using Graph API I am working on an add-in for Outlook for Web using the Office JavaScript API. A requirement in my project is to read/update an existing User-Defined Property on emails. This property is needed by a legacy add-in for the desktop version of Outlook.
In the Outlook for Web add-in, I would like to be able to retrieve and update this User-Defined Property. Is there an API I can use that will support this functionality?
Additionally, I've had a look at Open and Schema Extension Properties in the Graph API, but I don't think these relate to the User-Defined Property, and I'm a bit confused.
Thanks!


text:
Q: what is the best way of giving the feedback to the user I'm using speech recognition and I want to show the users that when they click a button they should speak.
I was thinking about using a progress bar but i dont think its a good idea. Then i thought about putting a label saying whats going on.
Can someone suggest any more options. Please.

A: You could also use audio feedback. Something like:
"Speak clearly, if you speak at all; carve every word before you let it fall."
(Oliver Wendell Holmes)

A: I vote for visual and/or audio feedback in the form of

*

*Popup/Notification box showing "Please speak into your microphone now" which fades away after a few seconds

*An image appearing such as this one, visually suggesting you speak (possibly with a matching one suggesting now is not the time to speak)

*An audio tone, short and simple.  Get two tones though, one for "speak now" and one for "OK. you can stop speaking"

Possibly combine some of the above for dual feedback

A: I think that they clearest way to do this is to give them a pop-up with a stop recording button.  Also some kind of progress bar/time recorded seems useful to me too.  In general users like what they have experienced before.  Every user has used a simple tv remote or youtube progress bar.  My vote is for consistency.

A: thanks for the amazing replies. i was thinking about a messagebox too. AND thinking about putting a audible feed back too...


text:
Q: Not able to iterate HTMLCollection in jQuery extension I am working on form filler. Below code is working fine in Chrome console, but when I put the code in extension (form filler) it does not work.
jQuery Code:
var addressElement=$($('[data-name="selected-address"]')[0].children).filter(function(idx) {
    return this.innerHTML.indexOf('52') == 0;
});
addressElement[0].click();

Also tried JavaScript code
document.querySelectorAll('[ng-bind="address.formattedAddress"]');

HTML:

    30, test data
    52, test data2

Note: I have tried all the possible options in Google. However, the above selector does not return array list of a tags. Please note that it works in developer console.

A: i fixed the issue adding some delay in my code through setInterval

A: addressElement[0].click();

to
$(addressElement[0]).click();


text:
Q: how to insert HTML code into a table How can I insert a piece of HTML Code (containing " and ') into my MySQL database?
It's not that easy for me to simply escape all the " and ' with a backslash, so I'm looking for other solutions. All the solutions I have found are depended on some programming language, such as PHP, like in this example.
The programming language I'm using is Python, but I'd prefer a general mysql solution.
The piece of code I want to insert could e.g. look like this:

"mp3's"
"ogg's"

(this is just random code, not neccessarly senseful or working)
Thanks in advance!

A: Generally speaking:
You need to escape data before it is inserted into the mySQL query. The Python library that provides access to mySQL should provide an escaping function to do this, or escape the data automatically using prepared statements.
The reason why string data needs to be escaped is that quotes (" or ') can break the SQL statement that is used to enter the data.


text:
Q: Use subprocess module to run GDAL processes I am attempting to write a python script that will reproject & merge a series of .tif files then clip them to the boundaries of a .shp file. I have successfully used the subprocess module to do step 1, but am not sure how to use subprocess to run another second operation. Below is an example of what it might look like if I used subprocess/GDAL to reproject one set of files, then reproject a second set in another folder in the same script. Any ideas on why this won't work?
import os, gdal, subprocess, sys

cmd = ['gdalwarp', '-t_srs','+proj=longlat +ellps=WGS84','*.tif','new7.tif']
cmd2 = ['gdalwarp', '-t_srs','+proj=longlat +ellps=WGS84','newfolder/band4.tif','newfolder/band4_r.tif']
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
stdout,stderr=proc.communicate()
proc1 = subprocess1.Popen(cmd2,stdout1=subprocess1.PIPE,stderr1=subprocess1.PIPE)
stdout1,stderr1=proc.communicate()
exit_code=proc.wait()

I am new to python and subprocess, thus my code may be way off. Any ideas?

A: Unfortunately, your problem description leaves some desires. You really should specify more clearly what does not work and which error messages you receive and so forth. And usually it is best in case of errors to try one step after the other.
In your case I see some problems that may cause your script to "not work". First, you should specify the correct path to your programs and to your data. Working with relative paths is problematic, since your script may not work under the same shell environment as you do. So, your relative path newfolder/band4.tif may be the reason why the command does not work.
Second, you are fiddling too much with python commands you obviously do not understand well enough. If you want to continue to use the subprocess.Popen it's best to read the manual page and understand it.
Anyway, a few tipps now that should get you running.

*

*use the full path to gdalwarp, ie. /usr/local/bin/gdalwapr

*do not use subprocess.Popen, but use subprocess.check_call() instead 1)

*omit all those proc.communicate() stuff, you probably don't need it

*'+proj=longlat +ellps=WGS84' is equal to 'EPSG:4326'

1) subprocess.check_call() waits for the completion of the command before it continues in your script. Nice for seeing where your problem lies and vital if you want to treat the same data sequentially. You may substitute subprocess.check_call() with other subprocess commands after your program runs
A little example script:
def warp(args):
    """with a def you can easily change your subprocess call"""
    # command construction with binary and options
    options = ['/usr/bin/gdalwarp']
    options.extend(args)
    # call gdalwarp
    subprocess.check_call(options)

# just pass the list of commands without the gdalwarp command at the beginning, since it is added automatically
# this should run two commands of gdalwarp sequentially
warp(['-t_srs', 'EPSG:4326', '/home/user/maps/source.tif', '/home/user/maps/target.tif'])
warp(['-t_srs', 'EPSG:3857', '-of', 'AAIGrid', '/home/user/maps/source.tif', '/home/user/maps/target.xyz']))

I have a little script which you can examine. It creates a combined hillshade from SRTM data. It does not run well at the moment, due to other reasons though. There you can have a look how I've organized my workflow for lots of GDAL commands, and Imagemagick too.

A: Did you try Envoy library, a wrapper on top of Python subprocess?
It could help skip the issue.
To launch commands 1 and 2
import envoy

cmd1 = ['gdalwarp', '-t_srs','+proj=longlat +ellps=WGS84','*.tif','new7.tif']
cmd2 = ['gdalwarp', '-t_srs','+proj=longlat +ellps=WGS84','newfolder/band4.tif','newfolder/band4_r.tif']

r1 = envoy.run(' '.join(cmd1))
r2 = envoy.run(' '.join(cmd2))


text:
Q: Azure App Service to Key Vault - Managed Identity Access Issue using Python I have a setup as below.
Azure App Service connects to Azure Key Vault using Azure-Identity Python SDK. Azure KV's data plane has access policy enabled to include App Service's managed identity. I have used the following code to connect to KV from app service webjobs.
import os
import json
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.keyvault.secrets import SecretClient

keyVaultName = os.getenv('KeyVaultNm')
KVUri = f"https://{keyVaultName}.vault.azure.net"
credential = DefaultAzureCredential()
_sc = SecretClient(vault_url=KVUri, credential=credential)
srv = _sc.get_secret("server-nm").value
print(f'KV Secret: {srv}')

This setup had been working without any issues for almost a year to allow App service extract secrets from KV but over the last weekend, it started failing with the following error.
[08/29/2022 09:14:14 > 6f77be: ERR ] ManagedIdentityCredential.get_token failed: <urllib3.connection.HTTPConnection object at 0x00000234348D8AC8>: Failed to establish a new connection:
[WinError 10049] The requested address is not valid in its context
[08/29/2022 09:14:14 > 6f77be: ERR ] DefaultAzureCredential failed to retrieve a token from the included credentials.
[08/29/2022 09:14:14 > 6f77be: ERR ] Attempted credentials:

Any idea what's this error is regarding? Will this happen due to any firewall issue?
PS: The same code works well inside a VM using its managed identity and retrieves secrets from KV. The issue happens only when the code is run from Webjobs.