text:
Q: Typescript: Argument of type '(i: string[]) => any[]' is not assignable to parameter of type 'string[]' In my project, I am trying to add multiple emails as a chip. But I am facing a problem here, first time, when I paste multiple email values it gets inserted into the field, but second time when I copy some other values and paste them into the field, it replaces the previous values. to solve this added a line "setItem((i: string[]) => [...i, ...toBeAdded]);" inside "handlePaste". but this leads to another issue "Typescript: Argument of type '(i: string[]) => any[]' is not assignable to parameter of type 'string[]'."

type Props = {
  LabelName?: string;
  optional?: string;
  tooltip?: string;
  placeholder?: string;
  className?: string;
  upload?: boolean;
  items?: any;
  setItem: (items: string[]) => void;
};
const TagActions = (props: Props) => {
  // const [items, setItem] = useState<string[]>([]);
  const [value, setValue] = useState("");
  const [error, setError] = useState("");
  const divRef = useRef<HTMLDivElement>(null);
  const [flag, setFlag] = useState(false);

  const {
    LabelName,
    optional,
    tooltip,
    placeholder,
    className,
    upload,
    items,
    setItem,
  } = props;

  const handleDelete = (item: any) => {
    const result = items.filter((i: any) => i !== item);
    setItem(result);
  };

  const handleItemEdit = (item: any) => {
    const result = items.filter((i: any) => i !== item);
    setItem(result);
    setValue(item);
  };

  const handleKeyDown = (evt: any) => {
    if (["Enter", "Tab", ","].includes(evt.key)) {
      evt.preventDefault();

      const test = value.trim();

      if (test && isValid(test)) {
        items.push(test);
        setValue("");
      }
    }
  };

  const isValid = (email: any) => {
    let error = null;

    if (isInList(email)) {
      error = `${email} has already been added.`;
    }

    if (!validator.isEmail(email)) {
      setFlag(true);
    }

    if (error) {
      setError(error);

      return false;
    }

    return true;
  };

  const isInList = (email: any) => {
    return items.includes(email);
  };

  const handleChange = (evt: any) => {
    setValue(evt.target.value);
  };

  const handlePaste = (evt: any) => {
    evt.preventDefault();

    const paste = evt.clipboardData.getData("text");
    const emails = paste.match(/[\w\d\\.-]+@[\w\d\\.-]+\.[\w\d\\.-]+/g);

    if (emails) {
      const toBeAdded = emails.filter((email: any) => !isInList(email));

      console.log("items inside", items);
      console.log("toBeAdded", toBeAdded);

      setItem((i: string[]) => [...i, ...toBeAdded]);
      console.log("items after", items);
    }
  };

  return (
    <>

        {LabelName && (
          <div className={`control-label ${styles.label}`}>

                {LabelName}

              {upload && (

                  Upload CSV

              )}

              {optional && Optional}

              {tooltip && (

                  <FontAwesomeIcon icon={faCircleQuestion} size="xs" />

              )}

        )}
        <input
          type="file"
          accept=".csv"
          style={{ display: "none" }}
          id="uploadCSV"
        />

          <TextField
            className={` textfield-emailchip test ${className}`}
            InputProps={{
              startAdornment: items.map(
                (
                  item:
                    | boolean
                    | Key
                    | ReactElement<any, string | JSXElementConstructor<any>>
                    | ReactFragment
                    | null
                    | undefined
                    | any
                    | string
                ) => (
                  <Chip
                    className={
                      !validator.isEmail(item)
                        ? styles.chipTagError
                        : styles.chipTag
                    }
                    key={item}
                    tabIndex={-1}
                    label={item}
                    onDelete={() => handleDelete(item)}
                    onClick={() => handleItemEdit(item)}
                    deleteIcon={<FontAwesomeIcon icon={faXmark} size="xs" />}
                  />
                )
              ),
            }}
            ref={divRef}
            value={value}
            placeholder={placeholder}
            onKeyDown={(e) => handleKeyDown(e)}
            onChange={(e) => handleChange(e)}
            onPaste={(e) => handlePaste(e)}
          />

        {error &&
{error}
}

    </>
  );
};

export default TagActions;

Please give me a solution to fix this problem.

A: setItem is defined as having the type (items: string[]) => void. This definition means it is a function that accepts an array of strings, for example setItem(['a', 'b', 'c']) would be a valid invocation of a function with this type.
However, in the code setItem is then called differently, like this:
setItem((i: string[]) => [...i, ...toBeAdded]);
The argument (i: string[]) => [...i, ...toBeAdded] is not an array of strings; it is itself another function. TypeScript is saying this code is invalid because the argument given to setItem is a function, not an array of strings.
You can either change the invocation to pass an array of strings, or change the definition to say it's supposed to accept a function, depending on which matches your true intent for the code.


text:
Q: Difference between $\mathbb{T}^n$ and $S^n$ and applications to dynamics (Euler angles and configuration manifolds) I am struggling to see the difference between the $n$-sphere and the $n$-torus. We define $\mathbb{T}^n = S^1 \times S^1 \times \cdots \times S^1$, where the Cartesian product is taken $n$ times.
I guess we should start with low dimensions and work our way up. If $n=1$, then the two manifolds are not just topologically equivalent, but they are geometrically equivalent. They are the same mathematical object.
Now let $n=2$. Both the 2-sphere and the 2-torus may be charted out by two angular coordinates. The difference to me is that the torus has both angles going from $0$ to $2\pi$ while the sphere has one angle going from $0$ to $2\pi$ and another going from $0$ to $\pi$. Is there an example where one is more beneficial than the other?
In dynamics, if I have a 2-segment pendulum in the plane parametrized by two angles, then I may represent the configuration manifold as a 2-torus since both angles range up to $2\pi$. Would a single segment pendulum with two degrees of freedom be an example of a configuration manifld that is a 2-sphere?
Now let's investigate $n = 3$. Consider the topological group $SO(3)$. We may chart out $SO(3)$ with Euler angles. The first and last angles range from $0$ to $2\pi$ while the middle angle ranges from $0$ to $\pi$. What sort of a topological object would this be associated with?
I can see that if we make a cut around the 2-torus and throw out a ring from the middle, we may identify edges and get a 2-sphere. Can a similar thing be done with the 3-torus and the 3-sphere?
Thanks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: NSMutableArray Programmatically? I'm trying to allow the user to have multiple groups of data all in NSMutableArrays. I don't want to have to limit the amount of arrays they can create but I don't see how one could make multiple arrays with different names so they don't keep overwriting the same data. For example:
-(void)viewDidLoad {
mutableArray = [[NSMutableArray alloc]init];
}

and
-(IBAction)createNewArray {
[array addObject:first.text];
[array addObject:second.text];
[array addObject:third.text];
[array addObject:fourth.text];
//Add this set of data to a larger group which is all the arrays
[allArrays addObject:array];

}

The problem is that it would keep adding different data with the same name which would become useless because 1. I believe it would keep overwriting the same object and 2. There's no way to differentiate the objects.
My question: Is there any possible way to create multiple arrays with different names without having to put them in the .h first?

A: A NSDictionary of NSMutableArrays

A: If you don't wan't to worry about name collisions you can use an array of arrays,
Alternatively - If you want to generate unique names without collisions - have a try:
NSString *uniqueName = [[NSUUID UUID] UUIDString];


text:
Q: How to display an image in a Java application I want to display an image in my Java application. I found a code to download the image from the webserver and show it in the jframe.
I want to use a label to show the image or something else. It shouldn't be JFrame.
Here is my code:
Image image = null;
try {
    URL url = new URL(
        "http://www.personal.psu.edu/acr117/blogs/audrey/images/image-2.jpg");
    image = ImageIO.read(url);
} catch (IOException e) {
}

// Use a label to display the image
JFrame frame = new JFrame();

JLabel lblimage = new JLabel(new ImageIcon(image));
frame.getContentPane().add(lblimage, BorderLayout.CENTER);
frame.setSize(300, 400);
frame.setVisible(true);

Can someone help me?

A: Using the code you provided, you already have the image in a JLabel called lblimage. You can now add that to a panel or any other container object, like so:
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(lblimage);
// add more components here
frame.add(mainPanel);
frame.setVisible(true);

You can treat that label (lblimage) just like you would any normal component.

A: You could try doing this instead:
import javax.swing.ImageIcon;
...
JLabel image = new JLabel(new ImageIcon("imageName.png"));
...
frame.add(image);

I find it to be much easier to do :D
EDIT: Upon reading the question for the 4th time, I realized that this is exactly what you did in the question. Now, I'm having trouble figuring out what exactly you're asking for.

A: I would add two notes to the other useful answers:
1) Don't swallow exceptions; write to a log or at least print a stack trace.
catch (IOException e) { e.printStackTrace(); }

2) Instead of writing frame.setSize(300, 400), use pack(), which "Causes this Window to be sized to fit the preferred size and layouts of its subcomponents." In this way, the picture's original dimensions will be used. This is also the foundation of @camickr's suggestion to read about Layout Managers.

A:
and i want to add more and more items
  (buttons and labels ) to my GUI. can
  you please help me

Your question has nothing to do with labels and images. You need to understand how to use Layout Managers to organize the components you add to a frame.
So start by reading the Swing tutorial on Layout Managers. There are plenty of examples you can download and play with. Also you can nest different layout managers on different panels.

A: Your code already does what you need ( to display it in other than a JFrame - that's a JLabel - )
For what you say in your comments, to try to drag and drop and add more components I think what you need is to use a GUI BUilder to achieve what you want ( which is not only show the image but add other components )
I would recommend you yo use IntelliJ IDEA's GUI Builder
In order to have a complete overview on how Swing works and what can you with it, you can also take a look at: The swing tutorial

A: Try this:
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setIcon(new ImageIcon(MainMenu.class.getResource("/Images/Bugs.png")));


text:
Q: SFMC iOS SDK setup failed because encryption key could not be created or fetched with configuration I'm starting integration with the iOS SDK. I'm doing a very very basic config. My config has everything disabled, and I only populate the ApplicationId and AccessToken
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

  // configure the Marketing Cloud SDK
  NSError *error = nil;
  BOOL success = [[MarketingCloudSDK sharedInstance] sfmc_configure:&error];
  if (success == YES) {
      [[MarketingCloudSDK sharedInstance] sfmc_setDebugLoggingEnabled:YES];
  }
}

However I get the following output even with just this:
[foundation] SecItemDelete Exception. Error = -34018
 MarketingCloudSDKFoundation+DataUtils.m line: 262
[foundation] setup failed because encryption key could not be created or fetched with configuration {
    accesstoken = ...;
    appid = "...";
    etanalytics = 0;
    inbox = 0;
    location = 0;
    pianalytics = 0;
}.
error Error Domain=MarketingCloudSDKErrorDomain Code=9 "SecItemDelete Exception. Error = -34018" UserInfo={NSLocalizedDescription=SecItemDelete Exception. Error = -34018}
MarketingCloudSDKFoundation.m line: 229

Anyone know what might cause this? Why this might be? I've tried it also with the MID and server url populated, still the same output...

A: So this is to do with signing as mentioned by Jeff Sylvia's comment. This is because I was running it in the simulator, when you run it in a real iPhone you do not get this error.


text:
Q: Speed up explorer.exe boot time My computer's boot time is way longer than I want it to be, so I ran some checks to see what slows down the booting process. I found out that explorer.exe takes over 30 seconds of cpu time on boot. Is there a way I can make explorer boot faster?

A: Your problem is almost certainly not Explorer itself, rather it's a 3rd party program or shell extension that taking all that time.
The first port of call is using Autoruns from Sysinternals to both check what's running when your system starts up and disable things that you don't need.


text:
Q: Tradingview strategy, many orders are exiting when an order in the opposite direction is entered Might be a rookie question but I honestly don't know why this is happening. Pyramiding is default, so zero, but pyramiding only prevents more than one order in the same direction. I have a strategy written based on the Ichimoku Cloud and it can enter long and short. When I check the chart and strategy tester, a lot of these orders (but not all) are being exited when an order in another direction is entered. So a long's being exited when a short is entered, and vice versa.
I've included relevant code below.
//Variable for ATR, take profit/stop loss multipliers
ATR=atr(14)
TPmult = input(4, "Take Profit Multiplier (of ATR)", input.integer, minval=1, confirm=true, step=0.1)
SLmult = input(2, "Stop Loss Multiplier (of ATR)", input.integer, minval=1, confirm=true, step=0.1)

//Variables for entry conditions
enterlong=(leadLine1 > leadLine2) and (close > leadLine1 and leadLine2) and (conversionLine > baseLine)
entershort=(leadLine1 < leadLine2) and (close < leadLine1 and leadLine2) and (conversionLine < baseLine)

//Stop losses and take profits
long_stop_level = iff(enterlong, close - (ATR * SLmult), na)
long_profit_level = iff(enterlong, close + (ATR * TPmult), na)

short_stop_level = iff(entershort, close + (ATR * SLmult), na)
short_profit_level = iff(entershort, close - (ATR * TPmult), na)

//entries and exits
strategy.entry("Long Entry", long=true, when=enterlong)
strategy.exit("Long Exit", "Long Entry", stop=long_stop_level, limit=long_profit_level)

strategy.entry("Short Entry", long=false, when=entershort)
strategy.exit("Short Exit", "Short Entry", stop=short_stop_level, limit=short_profit_level)

Anyway I can fix this? Thanks in advance. I want a long and short order to be open at the same time. I've tried setting pyramiding to 1 and 2 and it didn't fix it.


text:
Q: parse dates with ordinal date fields In Golang how do I parse a date that has an ordinal day of the month? For example the following date:
"Sunday 23rd January 2033 04:38:25 AM"

For this particular date I could hardcode the rd and use this layout in time.Parse():
"Monday 02rd January 2006 15:04:05 PM"

But what if the day of the month was the 21st?
"Sunday 21st January 2033 04:38:25 AM"

(ignoring the fact that this date is incorrect)
The following would work for this case but is obviously wrong:
"Monday 02st January 2006 15:04:05 PM"

I've been reading the source code and haven't yet reached enlightenment.
(I'm aware that the lack of timezone also needs to be accounted for by program logic).

This come up in a set of questions I wrote myself, to improve my date parsing. See https://github.com/soniah/date_practice if you also need practice!

A: If you have a hammer, everything looks like a nail. If you have a computer programmer, everything looks like a function.

First, a map of ordinals function,
package main

import (
    "fmt"
    "strconv"
)

// generateOrdinalsMap generates map[ordinal]cardinal to stdout
// for the non-negative interval [min, max]
// as var name = map[string]string{}.
func generateOrdinalsMap(name string, min, max int) {
    fmt.Printf("\nvar " + name + " = map[string]string{ // map[ordinal]cardinal\n")
    for i := min; i >= 0 && i <= max; i++ {
        var o string
        switch i % 10 {
        case 1:
            o = "st"
        case 2:
            o = "nd"
        case 3:
            o = "rd"
        default:
            o = "th"
        }
        if 11 <= i && i <= 13 {
            o = "th"
        }
        c := strconv.Itoa(i)
        o = c + o
        fmt.Printf(`"%s": "%s", `, o, c)
        if (i)%5 == 0 || i == max {
            fmt.Printf("\n")
        }
    }
    fmt.Printf("}\n\n")
}

func main() {
    // Generate ordinal map for days.
    generateOrdinalsMap("dayOrdinals", 1, 31)
}

Playground: https://play.golang.org/p/W7Ad0pjjGu
Output:
var dayOrdinals = map[string]string{ // map[ordinal]cardinal
"1st": "1", "2nd": "2", "3rd": "3", "4th": "4", "5th": "5",
"6th": "6", "7th": "7", "8th": "8", "9th": "9", "10th": "10",
"11th": "11", "12th": "12", "13th": "13", "14th": "14", "15th": "15",
"16th": "16", "17th": "17", "18th": "18", "19th": "19", "20th": "20",
"21st": "21", "22nd": "22", "23rd": "23", "24th": "24", "25th": "25",
"26th": "26", "27th": "27", "28th": "28", "29th": "29", "30th": "30",
"31st": "31",
}

Second, a time.Parse wrapper function, which converts an ordinal day in the value to a cardinal day before parsing with a cardinal day layout,
package main

import (
    "fmt"
    "strconv"
    "strings"
    "time"
)

var dayOrdinals = map[string]string{ // map[ordinal]cardinal
    "1st": "1", "2nd": "2", "3rd": "3", "4th": "4", "5th": "5",
    "6th": "6", "7th": "7", "8th": "8", "9th": "9", "10th": "10",
    "11th": "11", "12th": "12", "13th": "13", "14th": "14", "15th": "15",
    "16th": "16", "17th": "17", "18th": "18", "19th": "19", "20th": "20",
    "21st": "21", "22nd": "22", "23rd": "23", "24th": "24", "25th": "25",
    "26th": "26", "27th": "27", "28th": "28", "29th": "29", "30th": "30",
    "31st": "31",
}

// parseOrdinalDate parses a string time value using an ordinary package time layout.
// Before parsing, an ordinal day, [1st, 31st], is converted to a cardinal day, [1, 31].
// For example, "1st August 2017" is converted to "1 August 2017" before parsing, and
// "August 1st, 2017" is converted to "August 1, 2017" before parsing.
func parseOrdinalDate(layout, value string) (time.Time, error) {
    const ( // day number
        cardMinLen = len("1")
        cardMaxLen = len("31")
        ordSfxLen  = len("th")
        ordMinLen  = cardMinLen + ordSfxLen
    )

    for k := 0; k < len(value)-ordMinLen; {
        // i number start
        for ; k < len(value) && (value[k] > '9' || value[k] < '0'); k++ {
        }
        i := k
        // j cardinal end
        for ; k < len(value) && (value[k] <= '9' && value[k] >= '0'); k++ {
        }
        j := k
        if j-i > cardMaxLen || j-i < cardMinLen {
            continue
        }
        // k ordinal end
        // ASCII Latin (uppercase | 0x20) = lowercase
        for ; k < len(value) && (value[k]|0x20 >= 'a' && value[k]|0x20 <= 'z'); k++ {
        }
        if k-j != ordSfxLen {
            continue
        }

        // day ordinal to cardinal
        for ; i < j-1 && (value[i] == '0'); i++ {
        }
        o := strings.ToLower(value[i:k])
        c, ok := dayOrdinals[o]
        if ok {
            value = value[:i] + c + value[k:]
            break
        }
    }

    return time.ParseInLocation(layout, value, defaultLocation)
}

// Times without a timezone are Hong Kong times.
var defaultLocation = func(name string) *time.Location {
    loc, err := time.LoadLocation(name)
    if err != nil {
        loc = time.UTC
    }
    return loc
}(`Asia/Hong_Kong`)

func main() {
    var dates = []struct {
        layout, value string
    }{
        {"Monday 02 January 2006 15:04:05 PM", "Friday 24th November 2017 13:14:07 PM"},
        {"2 January 2006", "1st August 2017"},   // ISO
        {"January 2, 2006", "August 1st, 2017"}, // USA
    }
    fmt.Println()
    for _, d := range dates {
        fmt.Printf("Layout: %q\n", d.layout)
        fmt.Printf("Value:  %q\n", d.value)
        t, err := parseOrdinalDate(d.layout, d.value)
        fmt.Printf("Time:   %v  Error: %v\n", t, err)
        fmt.Printf("Unix:   %v  Error: %v\n", t, err)
        fmt.Println()
    }
}

Playground: https://play.golang.org/p/5INR83e66T
Output:
Layout: "Monday 02 January 2006 15:04:05 PM"
Value:  "Friday 24th November 2017 13:14:07 PM"
Time:   2017-11-24 13:14:07 +0800 HKT  Error: <nil>
Unix:   2017-11-24 13:14:07 +0800 HKT  Error: <nil>

Layout: "2 January 2006"
Value:  "1st August 2017"
Time:   2017-08-01 00:00:00 +0800 HKT  Error: <nil>
Unix:   2017-08-01 00:00:00 +0800 HKT  Error: <nil>

Layout: "January 2, 2006"
Value:  "August 1st, 2017"
Time:   2017-08-01 00:00:00 +0800 HKT  Error: <nil>
Unix:   2017-08-01 00:00:00 +0800 HKT  Error: <nil>

Third, complete and run your date_practice tests,
{
    "wombat",
    "Sunday 23rd January 2033 04:38:25 AM",
    "Monday 2 January 2006 03:04:05 PM",
    1990039105,
    parseOrdinalDate,
    nil,
},

{
    "kangaroo",
    "Tuesday 7th November 2017 03:18:25 PM",
    "Monday 2 January 2006 03:04:05 PM",
    1510039105,
    parseOrdinalDate,
    nil,
},

A: If the input's format is consistent, here's a simple solution:
https://play.golang.org/p/EB-hruEGW5
package main

import (
    "fmt"
    "strings"
    "time"
)

func main() {
    input := []string{
        "Sunday 23rd January 2033 04:38:25 AM",
        "Sunday 21st January 2033 04:38:25 AM",
        "Sunday 04th January 2033 04:38:25 AM",
        "Sunday 02nd January 2033 04:38:25 AM",
        "Thursday 23rd November 2017 5:06:55 PM",
        "Friday 24th November 2017 08:10:30 AM",
    }
    ordinal := []string{"nd", "rd", "st", "th"}
    form := "Monday 02 January 2006 15:04:05 PM"

    for _, d := range input {
        for _, o := range ordinal {
            if strings.Index(d, o+" ") > -1 {
                d = strings.Replace(d, o+" ", " ", -1)
                break
            }
        }
        t, _ := time.Parse(form, d)
        fmt.Println(t.String())
    }
}


text:
Q: ViewHolder views must not be attached when created I'm trying to create a simple RV that will show a TextView.
This is my adapter:
public class MyRvAdapter extends RecyclerView.Adapter<MyRvAdapter.ViewHolder> {

private String[] mDataset;

public static class ViewHolder extends RecyclerView.ViewHolder {
    // each data item is just a string in this case
    public TextView mTextView;
    public ViewHolder(TextView v) {
        super(v);
        mTextView = v;
    }
}

public MyRvAdapter(String[] myDataset) {
    mDataset = myDataset;
}

@NonNull
@Override
public MyRvAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.text_row_item, parent, false);
    TextView userNameInList= v.findViewById(R.id.display_name);
    ViewHolder vh = new ViewHolder(userNameInList);
    return vh;
    }

@Override
public void onBindViewHolder(@NonNull MyRvAdapter.ViewHolder holder, int position) {
    holder.mTextView.setText(mDataset[position]);
}

@Override
public int getItemCount() {
    return mDataset.length;
}

}
text_row_item is just a FrameLayout with a TextView inside it("display_name").
This is the eror:
java.lang.IllegalStateException: ViewHolder views must not be attached when created. Ensure that you are not passing 'true' to the attachToRoot parameter of LayoutInflater.inflate(..., boolean attachToRoot)
    at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6687)
    at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5869)

Thank you very much!

A: Actually, your ViewHolder expects a View inflated from R.layout.text_row_item rather than a descendant of the latter. So, if you pass the inflated view the problem will be resolved.
So, you should correct your code to this:
public class MyRvAdapter extends RecyclerView.Adapter<MyRvAdapter.ViewHolder> {

    private String[] mDataset;

    public static class ViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        public TextView mTextView;
        public ViewHolder(View v) {
            super(v);
            mTextView = v.findViewById(r.id.display_name);
        }
    }

    public MyRvAdapter(String[] myDataset) {
        mDataset = myDataset;
    }

    @NonNull
    @Override
    public MyRvAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.text_row_item, parent, false);
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(@NonNull MyRvAdapter.ViewHolder holder, int position) {
        holder.mTextView.setText(mDataset[position]);
    }

    @Override
    public int getItemCount() {
        return mDataset.length;
    }
}

A: In my case, I fixed it changing this line
val view = parent.inflate(R.layout.your_item)

to
val view = parent.inflate(R.layout.your_item, false)

A: I know its too late but i want to add my answer, As it can help anybody who is facing this issue not due to above reason.
In My Case i was using "Data Binding Library" and my mistake was that my root element was not direct child of <layout>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">

        <data>

            <variable
                name="viewmodel"
                type="com.myapp.data.ViewModel" />
        </data>
        <!-- UI layout's root element -->
        <ConstraintLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <FrameLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
                <!-- By Mistake i was Making this element as Root -->
            </FrameLayout>
        </ConstraintLayout>

    </layout>

A: Wait till view is created before binding.
Remove TextView userNameInList= v.findViewById(R.id.display_name); from your MyRvAdapter.ViewHolder.
And bind in ViewHolder as mTextView = v.findViewById(r.id.display_name);.

A: try this
public class MyRvAdapter extends RecyclerView.Adapter<MyRvAdapter.MyViewHolder> {

private Context mContext;
private String[] mDataset;

public class MyViewHolder extends RecyclerView.ViewHolder {
    TextView title;

    MyViewHolder(View view) {
        super(view);
        title = (TextView) view.findViewById(R.id.display_name);
    }
}

public MyRvAdapter(Context mContext, String[] myDataset) {
    this.mContext = mContext;
    this.mDataset = myDataset;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.text_row_item, parent, false);
    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
    holder.title.setText(mDataset[position]);
}

@Override
public int getItemCount() {
    return mDataset.length;
}
}


text:
Q: Setting up a Like Counter on Rails from scratch Was trying to set up a ranking score for my users depending on their like counts.
I was able to get this to work for current_user.like.count but for some reason when I want it to be for user.like.count [so that its not the same one for everyone] my app crashes and gives me this error message: "Undefined method `likes' for nil:NilClass" I have put all my relevant code below as well as my github for this. Any help would be amazing.
Github Url: https://github.com/OmarZV/TY2
_rankings.html.erb
<% if current_user.likes.count >3 %>
A Ranking
<% elsif %>
<% current_user.likes.count == 2%>
B Ranking
<% else %>
C Ranking
<% end %>

users_controller.rb
class UsersController < ApplicationController
  before_action :authenticate_user!

  def index
    @users = User.all
  end

  def show
    @users = User.find(params[:id])
  end
end

routes.rb
Rails.application.routes.draw do
  devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
  resources :users, :controllers => "users_controller.rb"
  resources :users do
    resource :ranking, module: :users
  end
  resources :posts do
    resource :like, module: :posts
  end
  root to: "posts#index"
end

Index.html.erb

Platform Users

<% @users.each do |user| %>
<%=  user.username %>

<%= image_tag(user.avatar.url(:thumb)) %>

div id="user_<%= @user_id%>_rankings">
<%= render partial: "rankings", locals: {user: @user} %>

<% end %>

A: Moving comment to answer.
Id just loop through and not use a partial probably. But im  pretty sure you can just pass locals: {user: user} to use the variable from the loop and not the instance variable from your controller. checkout the docs on it for a bit more details http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials


text:
Q: How do I set first day of the week to Monday when using Week(Date) in PHP/MySQL? I am using the following code to build a Google Chart, to pull in all of entries in a MySQL table corresponding to the Week Numbers in a year.  At the moment the Week Numbers start on a Sunday, and I would like to change this so that they start on a Monday, but I'm not sure how to do this.
$i=1;
    while($i<=53)
       {
        $week_start = new DateTime();
        $week_start->setISODate(2013,$i+1);
        $date_display = $week_start->format('j M Y');

        $sessions = $wpdb->get_var($wpdb->prepare("SELECT Sum(Due) from patient_sessions WHERE Type='Session' AND Week(Date)='$i'"));

        $temp = array();

        $temp[] = array('v' => (string) $date_display);
        $temp[] = array('v' => (string) $sessions);
        $rows[] = array('c' => $temp);
        $i++;
    }

REVISED CODE
$sessions = $wpdb->get_results($wpdb->prepare("SELECT Due,Date from patient_sessions WHERE Type='Session'"));
$work_times = $wpdb->get_results($wpdb->prepare("SELECT Amount,Date from work_times"));
$expenses = $wpdb->get_results($wpdb->prepare("SELECT Amount,Date from expenses WHERE Client='Psychotherapy'"));

$i=1;
while($i<=53) {
    $week_start = new DateTime();
    $week_start->setISODate(2013,$i+1);
    $date_display = $week_start->format('j M Y');

    $session_total = 0;
    $work_time_total = 0;
    $expense_total = 0;

      foreach ($sessions as $session) {
    if (date("W", strtotime($session->Date)) == $i) {
    $session_total = ($session_total+$session->Due);
    }
    }

         foreach ($work_times as $work_time) {
    if (date("W", strtotime($work_time->Date)) == $i) {
    $work_time_total = ($work_time_total+$work_time->Amount);
    }
    }

          foreach ($expenses as $expense) {
    if (date("W", strtotime($expense->Date)) == $i) {
    $expense_total = ($expense_total+$expense->Amount);
    }
          }

    $balance = ($session_total + $work_time_total - $expense_total);

    $temp = array();

    $temp[] = array('v' => (string) $date_display);
    $temp[] = array('v' => (string) $balance);
    $rows[] = array('c' => $temp);
    $i++;
}

A: WEEK(date[mode]);

date = a date value.
mode = An integer indicating the starting of the week.

The default arugment is 0 which is sunday, setting this to 1 will be monday, 2 tuesday and so on.
week(date,1);

A: For it to work in your code, you should be able to change the query to:
"SELECT Sum(Due) FROM patient_sessions WHERE Type='Session' AND Week(Date,1)=$i"

However, I think I could go one step further and use the GROUP BY to make one sql call, and then iterate over the results;
"SELECT Week(Date,1), SUM(DUE) FROM patient_sessions WHERE Type='Session' GROUP BY Week(Date,1)"

Alternatively, you might need to use WEEK(Date,2) depending on how you want to handle weeks that span between years.


text:
Q: More than 1 dropdown filter working together I'm using the basic code from w3schools to filter a table using a dropdown. The problem is that is not filtering more than 1 dropdown. I have this questions:

*

*How can I make it work for 3 dropdowns and 1 search bar?

*How can I make it work using the value option from <option value="VALUE">VALUE</option> instead of the option <option>VALUE</option>

*Is there any way to put an 'all values' option? To show all the table entries.

This is the basic code I'm using
function myFunction() {
  var input, filter, table, tr, td, i;
  input = document.getElementById("mylist");
  filter = input.value.toUpperCase();
  table = document.getElementById("posts-table-1");
  tr = table.getElementsByTagName("tr");

  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[2];

    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      }
      else {
        tr[i].style.display = "none";
      }
    }
  }
}

Here is an example: https://jsfiddle.net/mdomfu/jpasqned/12/
Thanks.


text:
Q: how to set checked radio button by checking another radio button I have 2 seperate fields with 4 radio buttons each.
Field nr1 has radio button unchecked by using jquery, field nr2 has the first radio button checked by default.
What i need is, if in field nr1 a radio button is checked, then it checks the same radio button in field nr2.
Here is how my html looks like:

Piegādes veids *

<input type="radio" name="billing_piegadatajs" value="Pasta Stacija" class="radio" style="width:10%" checked="checked">Pasta Stacija

<input type="radio" name="billing_piegadatajs" value="Post24" class="radio" style="width:10%">Post 24

<input type="radio" name="billing_piegadatajs" value="Kurjerdienests" class="radio" style="width:10%">Kurjerdienests

<input type="radio" name="billing_piegadatajs" value="Saņemt uz vietas" class="radio" style="width:10%">Saņemt uz vietas ( Saldū )

Piegādes izmaksas

            <input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_flat_rate" value="flat_rate" checked="checked" class="shipping_method">
            Pasta Stacijas: € 3.50

            <input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_international_delivery" value="international_delivery" class="shipping_method">
            Post 24: € 3.50

            <input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_apg_shipping" value="apg_shipping" class="shipping_method">
            DLW Kurjeris: € 9.00

            <input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_local_pickup" value="local_pickup" class="shipping_method">
            Uz vietas - Saldū (Bez maksas)

I use this jquery to uncheck the field nr1 radio button when page is loaded.
jQuery(document).ready(function(){
jQuery('#billing_piegadatajs_field')
jQuery('#billing_piegadatajs_field').find('input[name="billing_piegadatajs"]').each(function() {
jQuery(this).prop('checked', false);
});
});

Here is a link to jsfiddle

A: You can acheive this in many many ways
One approach should be considering  2 set of radio
you have 2 sets already :
the first one share the class name 'radio'
the second one share the class name 'shipping_method'
The logic
1) add a click event on all radio of the first set
2) Get the order rank of the one we click on
3) force a click event on the radio button having the same index in the second set
// Track the click on the first set of radio
jQuery('.radio').on('click',function(){

    // Get the element index , which one we click on
    var indx = jQuery(this).index('.radio');

    // Trigger a click on the same index in the second radio set

    jQuery('.shipping_method')[indx].click();
})

there is the jsfiddle : http://jsfiddle.net/MMJRk/21/

A: First you need to find out which box is checked. The following link may help.
In jQuery, how do I select an element by its name attribute?
Then you need to loop through the next check boxes, comparing the value to the value you want for each box. When you find the one you want. Check that one.
Link for how to check box.
How to check a radio button with jQuery ?

A: Well, i have to admit it is not the most ideal way of getting what you want. But it does the trick: http://jsfiddle.net/veritas87/MMJRk/25/
jQuery('p.form-row input[type=radio]').on('change', function () {
        var radioNumber = $(this).index('.radio');
        $("ul#shipping_method input[type=radio]:eq(" + radioNumber + ")").prop('checked', true);
    });

In short, when a radiobutton changes in p.form-row it will get the index of the clicked radiobutton and it will set the radiobutton in the second list of radiobuttons to checked.

A: I've updated your jsfiddle and now it works.
Basically, I assigned to each input (and its counterpart), an index using custom data attributes (data-index). I attached an event handler to the first group of inputs, and, based on the index of the checked one, I check the correct radiobutton in the second group:
$('#billing_piegadatajs_field input[type="radio"]').on('change', function() {
   if (!this.checked) return;
   var index = this.getAttribute('data-index');
   $('#shipping_method input[data-index="' + index + '"]').prop('checked', true);
});


text:
Q: как на гитхаб пейджес получить данные из формы Как сделать на гитхаб пейджес получение из формы данных(форма на другой странице), допустим есть такой код, как это реализовать
<html>
<head>
<title>тест для входа</title>
</head>
<body>
<form action="страница назначения" method="post" id="pas">
Ваш пароль:<br>
<input type="text" size="40" required>
<input type="submit" vaule="отправить">
</form>
</body>
</html>

A: ответ дан Grundy(за что ему спасибо)
с методом post никак. Можно попробовать поменять на get и на новой странице доставать из строки запроса гет параметры.
например так: ru.stackoverflow.com/q/287469/186999


text:
Q: Python: Necessito obter a coordenada y dada a coordenada x Boa tarde!
x = [0, 5]
y = [2, 4]
plt.plot(x, y)
plt.show()
Obtenho a seguinte figura.

Como obtenho o valor da coordenada y para a coordenada x igual a 2.5?
Obrigado.

A: import matplotlib.pyplot as plt
from numpy import polyfit

Definindo X e Y conhecidos
X = [0, 5]
Y = [2, 4]

Calculando os coeficientes
m, b = polyfit(X, Y, deg=1)

Novo x para o calculo
x = 2.5

Equação da reta y = mx + b
y = m * x + b

Plotando
plt.plot(X,Y)
plt.plot(x, y, 'go')
plt.show()


text:
Q: Assign array in Linked List node I recently got into programming and I just learned about Linked Lists. I know how to assign individual elements like char or int in a node in a Linked List.
I was trying to assign a char array in a single node, and then for each node print the elements of the array.
Here is the part of my code in which I have tried to do the above:
node* ReadList() {
  node *head = NULL, *n, *m;
  char data[20], c;
  bool lmfao = false;
  int i;

  for (i=0; i<20; i++) {
    c = getchar();
    if (c == ' ') break;
    data[i] = c;
  }

  n = new node;
  n->next = NULL;
  n->info = data[];
  head = n;

  while (!lmfao) {

   for (i=0; i<20; i++) {
     c = getchar();
     if (c == ' ') break;
     if (c == EOF) lmfao = true;
     data[i] = c;
   }

   if (!lmfao) {
     m = new node;
     n->next = m;
     m->info = data[];
     m->next = NULL;
     n = m;

   }

   if (lmfao) {
     m = new node;
     n->next = m;
     m->info = data[];
     m->next = NULL;
   }
  }

  return head;
}

For the sake of this example lets say that the series of letters is not longer than 20 characters.
When I try to compile this I get the error message:
test.cpp:23:18: error: expected primary-expression before ']' token
test.cpp:38:21: error: expected primary-expression before ']' token
test.cpp:47:21: error: expected primary-expression before ']' token

I have tried to use data instead of data[] but then i get this:
test.cpp:36:16: error: invalid conversion from 'char*' to 'char' [-fpermissive]

which I totally understand, because I tried to convert a pointer to a char value.
Either way I have no clue as to what I can do to assign the
entire array in a single node.
Assigning a single element in each node would not work for what I'm trying to do.
Any suggestions?
Thanks in advance.


text:
Q: Survivor question badge? I think there is a value in those questions that are closed but later are re-opened because of popular demand.
Should these questions have some type of survivor/popular badge? Those ones when the community decides that it is worth to make an exception to the rules

A: Then we'd have a competition of people trying to create borderline questions.
Oh the inhumanity.

A: Some kind of reward would seem to indicate that these types of questions somehow have more value than other types of questions.  The reality is that a significant portion of the community thinks they have less.


text:
Q: Struggling with the rxjs `merge` interface I have an issue with the RxJs merge interface:
export function merge<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A[number]>;

So, based on this I created the following
const a$ = of('a').pipe(delay(1000));
const b$ = of('b');
const c$ = of('c').pipe(delay(10));

const y = merge<string[]>(d$, e$, f$) as Observable<string[number]>;

Nothing is complaining here. But when I use a little bit more complex interface
interface Foo<A = unknown, B = { id: string}> {
    input: A;
    output?: B;
}

const a$ = of({input: 'a'}).pipe(delay(1000));
const b$ = of({input: 'b'});
const c$ = of({input: 'c'}).pipe(delay(10));

const x = merge<Foo<string>[]>(a$, b$, c$) as Observable<Foo<string>[number]>;

It complains about number

Type 'Foo<string, { id: string; }>' has no matching index signature for type 'number'.

I must do something wrong here, any suggestions what my mistake is?

A: The merge will combine all observable into one, so the return type a union of all types.
In your first case : Observable<string>
and your second one : Observable<{input: string}>
And no need to specify the generic, the compiler can infer the type itself.

Lets decompose the type :
export function merge<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A[number]>;

A is generic with a constraint of Array<unknown>.
Knowing A, A[number] means every type of the array type A.
This means with Foo = [string, number];, Foo[number] equals string | number.


text:
Q: Run separate macros depending on checkbox value I would like to call a different macro depending on whether my checkbox (form control) is checked (true) or not (false).
Any idea on the syntax?
Thanks

A: Are you simply talking about an if statement?
If CheckBox1.Value = True Then
    RunSomeSub
Else
    RunSomeOtherSub
End IF


text:
Q: Mongoose geolocation inaccurate response this is my schema:
var onlineStatusSchema = mongoose.Schema({
    loc: {
        type: {},
        default:[]
    }
});
onlineStatusSchema.index({loc:'2d'});

and this is my query:
var query = onlineStatus.find({
     loc: {$nearSphere: [myLat,myLong], $maxDistance:10}});
query.exec(function (err,pros) {//response});

I am getting inaccurate data, i have tried changing 2d to 2dsphere also but it gives me all data which is within 10km or outside 10km

A: Try to divide the $maxDisatnce value with earth's radius ie, 6371 approx for KM.

$maxDistance:10/6371

This will help.


text:
Q: Integral form of $\Gamma (x)$ While trying to represent the poles and analytic continuation of $\Gamma (x)$ , the author uses the following equality:
$$\int\nolimits_{0}^{1}t^{x-1}e^{-t}dt=\sum_{n=0}^{+\infty}\frac{{(-1)}^{n}}{(n+x)n!}.$$
Any help in figuring out how?

A: In order to expand my comment: put for $0\leq t\leq 1$: $\displaystyle S_n(t)=\sum_{k=0}^n\frac{(-t)^k}{k!}$. We have
$$\sup_{0\leq t\leq 1}|\exp(-t)-S_n(t)| = \sup_{0\leq t\leq 1}\sum_{k=n+1}^{+\infty}\frac{(-t)^k}{k!}\leq \sum_{k=n+1}^{+\infty}\frac 1{k!},$$
and since the series $\displaystyle\sum_{k=0}^{+\infty}\frac 1{k!}$ is convergent, the sequence $\{S_n\}$ converges uniformly to $t\mapsto \exp (-t)$ on $\left[0,1\right]$. Therefore, we can switch the series and the integral for $x\geq 1$:
$\begin{align*}
\int_0^1t^{x-1}e^{-t}dt&=\int_0^1t^{x-1}\left(\sum_{k=0}^{+\infty}\frac{(-1)^kt^k}{k!}\right)dt\\
&=\sum_{k=0}^{+\infty}\frac{(-1)^k}{k!}\int_0^1 t^{x+k-1}dt\\
&=\sum_{k=0}^{+\infty}\frac{(-1)^k}{k!(x+k)}.
\end{align*}$
For $0<x<1$, we can use the dominated convergence theorem since $|t^{x-1}S_n(t)|\leq e\cdot t^{x-1}$ which is integrable on $\left[0,1\right]$ (we can use a more simple argument in the case $x\geq 1$).


text:
Q: Laravel 5 Cookie:get returns null if EncryptCookies turned on I'm trying to store some information in cookies in this way:
setcookie("o_favourites", serialize($fav_ids), time()+60*60*24*1825);

If EncryptCookies is turned on (by adding \App\Http\Middleware\EncryptCookies::class, presents in $middleware section of app/Http/Kernel.php) I recieved null when trying to get cookies:
$cookie = Cookie::get('o_favourites');

What could cause this behaviour?

BTW I use setcookies(), because Cookie::queue(Cookie::forever('o_favourites', serialize($fav_ids), null, null, false, false)); seems not working

A: It seems I need to use Cookie::queue("o_favourites", serialize($fav_ids), time()+60*60*24*1825); instead setcookie("o_favourites", serialize($fav_ids), time()+60*60*24*1825); to set a cookie with encription


text:
Q: docker npm install Error: getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443 I'm using docker version 1.10.1 on RHEL 7 and getting npm install error when using below Dockerfile. The Error: getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443. The same work with docker 1.91 on ubuntu 14.04. When I get bash and install inetutils-ping on container I noticed I can't ping anywhere
root@9deb4b274c1e:/home/nodexp#ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8): 56 data bytes
^C--- 8.8.8.8 ping statistics ---
4 packets transmitted, 0 packets received, 100% packet loss

Why is that ? Of course I can ping from RHEL
Dockerfile
FROM node:argon
# Create user nodexp in group nodexp
RUN groupadd -r nodexp \
    && useradd -m -r -g nodexp nodexp
WORKDIR /home/nodexp
# Install app dependencies
COPY package.json /home/nodexp
RUN npm install
# Bundle app source
COPY . /home/nodexp
EXPOSE 3000
CMD [ "npm", "start" ]

and package.json
{
  "name": "mp",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "~4.13.1"

  }
}

A: I ran into this same issue. My workaround was to attach docker build to a known working and accessible Docker network.
Workaround

*

*docker network ls

*Choose a known working network

*docker build --network=<known working network name>
By default, Docker uses the default network for building. Setting the network manually ensures the network can access the internet.

A: restarting docker with this command fixes it for me but I don't know why
sudo service docker restart

A: I fix this problem based on this article https://development.robinwinslow.uk/2016/06/23/fix-docker-networking-dns
actually, you could check the DNS if it fails or not while calling registry.npmjs.org
To check that thing, I did these steps to make it work
Step 1
Run this command on busybox image, I will use google.com to simulate the connection request
>> docker run busybox nslookup google.com
   Unable to find image 'busybox:latest' locally
   latest: Pulling from library/busybox
   f70adabe43c0: Pull complete
   Digest: sha256:58ac43b2cc92c687a32c8be6278e50a063579655fe3090125dcb2af0ff9e1a64
   Status: Downloaded newer image for busybox:latest
   nslookup: can't resolve 'google.com'
   Server:    8.8.8.8
   Address 1: 8.8.8.8

Step 2
As you can see from step 1 result, I got an error and cannot resolve connection to google.com, if you got a similar error then do this to check your current DNS route.
 >> nmcli dev show | grep 'IP4.DNS'
    IP4.DNS[1]:                             192.168.2.1

That command exposes your IP4 DNS which in this case 192.168.2.1, on this step you already know the DNS.
Step 3
Let's continue using busybox container to connect using this DNS by running
 >> docker run --dns 192.168.2.1 busybox nslookup google.com
    Server:    192.168.2.1
    Address 1: 192.168.2.1 giftcard.dyndns.org

    Name:      google.com
    Address 1: 2404:6800:4003:c03::65
    ....

Step 4
If your result is similar like on step 3, then your problem is docker couldn't connect because docker doesn't know the DNS will be used on, so we fix that by making daemon.json file and locate that in /etc/docker/daemon.json. these the content to put.
{
  "dns": ["192.168.2.1", "8.8.8.8"] // 192.168.2.1 is value of your dns
}

Step 5
Restart your docker service
>> sudo service docker restart

A: I tried everything above and nothing worked for me. A curiosity dockerd systemd script didn't start when adding the --dns parameter.
In my case the problem was that in ubuntu /etc/resolv.conf is generated automatically by systemd-resolved and points to a local ip 127.0.0.53, where a cache DNS is running, is crazy but with this information the containers where trying to resolve DNS with themselves in its loopack interface. Changing resolv.conf manually to our company DNS in the LAN fixed the issue, then modified systemd-resolved to do it permanently.

A: For me the problem was, that my swap-partition had problems after resizing my root partition and asked me for my passphrase for almost all system tasks (like apt get commands, re-/booting, etc.).

Please enter passphrase for disk … (cryptswap1) on none

Note
Only try this, if you are seeing the error above, too, and experience the problem described in the question when you try to execute npm install inside a docker container:

Error: getaddrinfo ENOTFOUND/EAI_AGAIN registry.npmjs.org registry.npmjs.org:443

The Solution

*

*Open GParted and check which where your swap partition is mounted, e.g. /dev/sda5 (referenced as "SWAP_PARTITION")

*Edit /etc/crypttab and replace UUID=**** to get the following pattern:
cryptswap1 /dev/SWAP_PARTITION/ /dev/urandom swap,**,cipher=****

*Reboot, if you are still asked for your passphrase, continue:

*Execute the command sudo dd if=/dev/zero of=/dev/SWAP_PARTITION/ bs=512 count=20480 and reboot. This fixed it for me.

source

A: I was following a tutorial. This error doesn't happen for me when I copy all my files:
# Specify base image
FROM node:alpine

WORKDIR /usr/app

# Install dependencies
COPY ./ ./
RUN npm install

# Default command
CMD ["npm", "start"]

It happens with me when I copy package.json first and then copy other files after npm install:
# Specify base image
FROM node:alpine

WORKDIR /usr/app

# Install dependencies
COPY ./package.json ./
RUN npm install

COPY ./ ./

# Default command
CMD ["npm", "start"]

A: If you are able to ping/curl to npm registry but still getting error with npm install, the error might likely be due to missing ca-certs package. Add the following line to Dockerfile before npm install and re-build the image.
FROM node:alpine

# Installing cert package will allow resolving the error to https://registry.npmjs.org/
RUN apk add --no-cache ca-certificates

RUN npm install
CMD ["npm", "start"]


text:
Q: SolrCloud connection timeout pool I have solr cloud cluster and it is throwing the following exception, it is happening when solr does something with the replicas
null:org.apache.solr.common.SolrException: org.apache.solr.client.solrj.SolrServerException: IOException occured when talking to server at: http://10.14.0.72:8080/solr/IE_big_index_shard1_0_replica2
    at org.apache.solr.handler.component.SearchHandler.handleRequestBody(SearchHandler.java:407)
    at org.apache.solr.handler.RequestHandlerBase.handleRequest(RequestHandlerBase.java:155)
    at org.apache.solr.core.SolrCore.execute(SolrCore.java:2033)
    at org.apache.solr.servlet.HttpSolrCall.execute(HttpSolrCall.java:652)
    at org.apache.solr.servlet.HttpSolrCall.call(HttpSolrCall.java:460)
    at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:229)
    at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:184)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1668)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:581)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1160)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1092)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:213)
    at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:119)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
    at org.eclipse.jetty.server.Server.handle(Server.java:518)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:308)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:244)
    at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273)
    at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
    at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceAndRun(ExecuteProduceConsume.java:246)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:156)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:654)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:572)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.solr.client.solrj.SolrServerException: IOException occured when talking to server at: http://10.14.0.72:8080/solr/IE_big_index_shard1_0_replica2
    at org.apache.solr.client.solrj.impl.HttpSolrClient.executeMethod(HttpSolrClient.java:591)
    at org.apache.solr.client.solrj.impl.HttpSolrClient.request(HttpSolrClient.java:241)
    at org.apache.solr.client.solrj.impl.HttpSolrClient.request(HttpSolrClient.java:230)
    at org.apache.solr.client.solrj.SolrClient.request(SolrClient.java:1219)
    at org.apache.solr.handler.component.HttpShardHandler$1.call(HttpShardHandler.java:198)
    at org.apache.solr.handler.component.HttpShardHandler$1.call(HttpShardHandler.java:163)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.apache.solr.common.util.ExecutorUtil$MDCAwareThreadPoolExecutor.lambda$execute$0(ExecutorUtil.java:229)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    ... 1 more
Caused by: org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
    at org.apache.http.impl.conn.PoolingClientConnectionManager.leaseConnection(PoolingClientConnectionManager.java:226)
    at org.apache.http.impl.conn.PoolingClientConnectionManager$1.getConnection(PoolingClientConnectionManager.java:195)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:423)
    at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:882)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
    at org.apache.solr.client.solrj.impl.HttpSolrClient.executeMethod(HttpSolrClient.java:482)
    ... 12 more


text:
Q: When is a subgroup the Weil restriction of another subgroup? I asked this question on Math.StackExchange, to no avail. I try my chance on this one.
Let $M/F$ be an extension of fields. Let $G$ be an algebraic group over $F$, and consider the $F$-group $H$ defined as the restriction of scalars (a la Weil) of $G$ from $M$ down to $F$, i.e. $H=\mathrm{Res}_{M/F} G$. If $T$ is a subgroup of $H$, under what circumstances/hypotheses is it true that there exists a subgroup $\tilde{T}\leq G$ such that $T=\mathrm{Res}_{M/F} \tilde{T}$? Any reference would be greatly appreciated.


text:
Q: Java ListIterator Robustness I hava a simple LinkedList in Java, that has, say, 10 elements. At that state, I get an ordinary ListIterator, say .listIterator(3). If I then insert/remove other elements into the list, without touching the element on which I have the ListIterator (nor the iterator), will the ListIterator still be valid?

A: If you modify a java.util.LinkedList outside of the ListIterator's own methods then the iterator is adulterated and will throw ConcurrentModificationException if you try to use it again.
This is covered in the javadoc for linked list:

The iterators returned by this class's iterator and listIterator
  methods are fail-fast: if the list is structurally modified at any
  time after the iterator is created, in any way except through the
  Iterator's own remove or add methods, the iterator will throw a
  ConcurrentModificationException. Thus, in the face of concurrent
  modification, the iterator fails quickly and cleanly, rather than
  risking arbitrary, non-deterministic behavior at an undetermined time
  in the future.


text:
Q: iOS table view - I don't know if this is even possible In table view with many rows, is it possible to have the top row (row[0]) "frozen",
while the rest of the rows 'scroll' up an down..  If you have any hints about this, it would be appreciated..

A: The only way to do this would be to use a section header as the top row. Otherwise, do the top row as a separate UI element.


text:
Q: XML - make element above of a element? I want to make text view above of list view like this :

This is my XML script :
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#FFFFFF"
     >

    <ListView
        android:id="@+id/lvVouchers"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

I am confusing for making textview above of list view...

A: Try this,
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >

<ListView
    android:id="@+id/listView1"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="0.8" >
</ListView>

<TextView
    android:id="@+id/text1"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="0.2">

</TextView>

But you have to set the text with \n  after each character as follows,
textView.setText("a" + "\n" + "b" + "\n" +"c" + "\n" +"d" + "\n" );

A:   <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#FFFFFF"
     >
  <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </TextView>

    <ListView
        android:id="@+id/lvVouchers"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>


text:
Q: How to restrict admin access based on Role Created with IP? I have created 2 separate roles under Permission -> Roles.
1). For Employees
2). For Suppliers
I was wondering how to restrict Role: Employees to access admin area only from specific IP. We have static IP, which I believe would make this thing easier for us to restrict the admin access.
Or
Is there any other way to restrict some users from accessing admin area by IP only.
Please suggest if this is possible or not.
Thank you

A: What you could do is listen to the event admin_user_authenticate_after and check the ip if it matches.
This event is fired when a user is authenticated in the admin login process. It has the result passed in so you should be able to check the ip and if you want to limit the access simply set the result to false and thus the authentication will fail.
Mage::dispatchEvent('admin_user_authenticate_after', array(
    'username' => $username,
    'password' => $password,
    'user'     => $this,
    'result'   => $result,
));

A bit of a thought though sometimes people may want to do a bit of work from home and in this case they would not be able to use the site.


text:
Q: "Bug" in String.Format and Float i have a code that convert float to string
total  = quant * valUnit;

lb_total.setText(String.format(Locale.US,"%.2f", total));

if total = 56.025(7.5 * 7.47) > 56.02

if total = 71.025(7.5 * 9.47) > 71.03

Why the first not rounds up?
I find the solution for my problem, i create a class to make this correctly.
import java.lang.Math;

// iniF   = value to be rounded
// posIni = number of max houses(EX: 7.45 * 7.999, max houses for this operation is five)
// posFin = number of houses after rounded
// EX: xx*.xxxxx -> xx*.xx    posIni = 5, posFin = 2
public class MyMath {
    public Float MyRound(Float iniF, int posIni, int posFin){
        Float result     = 0.00f;
        int resultTmp    = 0;
        int nCasas       = (int) Math.pow(10, posIni - 1);
        Float arredondaF = iniF * nCasas;

        for(int p = posIni; p > posFin; p--){
            resultTmp  = Math.round(arredondaF);
            arredondaF = (float) resultTmp / 10;
        }

        result = arredondaF / 10;

        return result;
    }
}

A: It's due to internal precision difference, especially since those numbers are the result of a floating point operation. Internally, 56.025 is really something like 56.0249999998, and 71.025 is something like 71.025000000002. Floating point operations aren't exactly, mathematically precise in the computer due to binary/decimal conversion and bit resolution of values.
Here are examples taken from Ruby to illustrate:
irb(main):003:0> format("%.2f", 7.5 * 7.47)
=> "56.02"
irb(main):004:0> format("%.2f", 7.5 * 9.47)
=> "71.03"

Here I used much higher precision of the format, and you can see the what the values really are:
irb(main):007:0> format("%.15f", 7.5 * 9.47)
=> "71.025000000000006"
irb(main):008:0> format("%.15f", 7.5 * 7.47)
=> "56.024999999999999"

There are numerous posts on stackoverflow.com, in various forms, about this issue. Just do a form search on "floating point precision" or "floating point exact".


text:
Q: @nuxtjs/auth login method calls a user method upon completion I'm using the nuxtjs/auth module to authenticate a user, with the backend written in .NET Core
When configuring the nuxtjs/auth package, I add the following to nuxt.config.js
//nuxt.config.js
  .
  .

  auth: {
    strategies: {
      local: {
        endpoints: {
          login: { url: 'users/authenticate', method: 'post', propertyName: 'data.token' },
        }
      }
    }
  },

  .
  .

the login function called when clicking 'login' looks like this
  async login () {
    try {
      await this.$auth.loginWith('local', {
        data: {
          Username: this.username,
          Password: this.password
        }
      })

      this.$router.push('/')
    } catch (e) {
      console.log(e) <-------------------
      this.error = e.response.data.message
    }
  }

The console.log(e) returns the following message:
Error: Request failed with status code 404
    at createError (commons.app.js:565)
    at settle (commons.app.js:728)
    at XMLHttpRequest.handleLoad (commons.app.js:98)

And in the console I also get
GET https://example.com/api/api/auth/user 404 (Not Found)

So it would seem that upon completing the initial authentication request, the nuxtjs/auth module calls 'user' in the API.
My backend is written in NET Core
So my question is, am I supposed to write in the NET Core backend, because the documentation for the nuxtjs/api package does not seem to explain how the basic usage of the module works


text:
Q: URL with multiple parameters as a query string in ASP.NET In ASP.NET, I build a string redirectURL to redirect to ADFS form with multiple query string parameters. One such complex parameter is the returnURL with multiple parameters.
My problem is that only the first parameter of the returnURL is available when it actually return.
E.g. redirectURL =

https://aaa.aaa/adfs/Form.aspx

?DomainName=domain

&AccountName=account

&returnURL=https://bbb.bbb/MyPage.aspx?param1=111&param2=222

I know it complicates when identify the &amp symbol of actual parameters and parameters in returnURL. Please help me to fix this.
Thanks in advance.

A: You should use HttpUtility.UrlEncode when composing the link and HttpUtility.UrlDecode when resolving it.
For your case it should be something similar to:
"https://aaa.aaa/adfs/Form.aspx?DomainName=domain&AccountName=account&returnURL=" +
    HttpUtility.UrlEncode("https://bbb.bbb/MyPage.aspx?param1=111&param2=222")

And then at the target use:
HttpUtility.UrlDecode(Request.QueryString["returnURL"])


text:
Q: Cortana: Creating a skill that launches a local application I am currently working on a skill that, when invoked, will return the serial number of your PC. Trying to figure out how, or if it is even possible, for Cortana to run a local program on the users machine, take the data from the execution, then speak it out.
To find the serial number of your system, you can use wmic bios get serialnumber, and it'll provide a stdout with desired information. Goal is to allow a Cortana skill to launch said process and read it out to an end user. When published, any user should be able to ask, "Hey Cortana, ask Serial Number finder what my serial number is" and get back the serial number of their machine.

A: It is possible to do this, but it isn't straight forward.
To launch a local application from Cortana it needs to support portal activation (URL launching). Documentation on how to get Cortana to launch an app can be found here: https://learn.microsoft.com/en-us/cortana/tutorials/bot-skills/bot-entity-channel-data
From there you can have your app use the Bot Framework direct line to send the information you want to your bot service which can then pass that back to Cortana.


text:
Q: Opening a new Window from a separate project in C# WPF I am currently developing a C# WPF project. The solution has two projects, one called GUI which contains all the Windows and GUI controls of the program and a second project called coding which contains all the classes and logic to ensure that if I change the logic, it doesn't affect the working of the GUI.
In the GUI project I have added a reference to the coding project and said using Coding, and this allows me to access the logic classes from the GUI screens.
However, if in the Coding logic class project I want to load a new window from the GUI project how do I go about doing this. If I try and add a reference to the GUI project from the coding project it says that this can't be done as it creates a circular dependency.
How can I reference both the projects together so that GUI can access logic classes from the coding project and reference the gui project from the coding project so the coding logic class can open a new window from the gui project.
Thanks for any help you can provide.

A: You can decouple it by introducing the third project Common and move out Window and other shared classes into it. Then Gui and Coding projects can easily reference Common.
BTW, try to rethink your design because I'm worried that Coding project is aware of UI entities.
EDIT:
In WPF you can decouple UI stuff from a logic by using Commands, see whether yu can achieve this.

A: When we talk about WPF and SOC "Seperation of Concerns" , this lead us directly to MVVM , here a simple explanation


text:
Q: How i can ad a user a single role with a button Hi i want for my comment which will send 3 embeds and an Button when you click on the Button that you get the role "weeb"
(btw im starting bot coding im not a pro and i understand only the basics even when you can call these "basics")
btw the string text is german because it will be for a german server
The class with the Button:
import discord
from discord import ComponentInteraction
from discord.ext import commands

class RuleAcceptButton(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.on_click(custom_id='rule-accept-btn')
    async def button1(self, ctx: ComponentInteraction, _):
        role_id = 1046854949373489203

def setup(bot):
    bot.add_cog(RuleAcceptButton(bot))

The class with the setup command:
    @commands.Cog.slash_command(base_name='setup', name='rules', description='Send a Embed of the Rules')
    async def setup_rules(self, ctx):
        embed_rules_1 = discord.Embed(description='sample text'
        embed_rules_1.set_author(name='§1 – Allgemeine Regeln')
        embed_rules_1.set_thumbnail(url='https://i.pinimg.com/originals/93/f0/00/93f0006c2d5da2f25de2951fb3f994bf.jpg')
        embed_rules_2 = discord.Embed(colour=16711680, description='sample text'
        # ab hier Embed2
        embed_rules_2.set_author(name='§2 – Zusätzliche Regeln für Voice-Chats/Voice-Channels')
        embed_rules_2.set_thumbnail(url='https://i.pinimg.com/originals/93/f0/00/93f0006c2d5da2f25de2951fb3f994bf.jpg')
        # ab hier Embed3
        embed_rules_3 = discord.Embed(colour=16711680, description='sample text'
        embed_rules_3.set_author(name='§3 – Zusätzliche Regeln für den Chat.')
        embed_rules_3.set_thumbnail(url='https://i.pinimg.com/originals/93/f0/00/93f0006c2d5da2f25de2951fb3f994bf.jpg')
        await ctx.respond(embed=embed_rules_1)
        await ctx.respond(embed=embed_rules_2)
        await ctx.respond(embed=embed_rules_3, components=[
            discord.Button(label='Accept Rules', custom_id='rule-accept-btn',style=discord.ButtonStyle.green)

i simply searched the whole internet and i didnt found anything


text:
Q: Translating a theme I am tryign to make my theme translatable so I am using the following command to output text. But its not outputting a default value i thought the __ did that automartically.
<?php __('PLAYER POINTS AT A GLANCE.','gogreensoccer');?>

I am using the above to display a translatable string to wordpress buts its empty.

<?php __('PLAYER POINTS AT A GLANCE.','gogreensoccer');?>

<?php  echo $player->display( 'points' ); ?>POINTS

<div id="circle" data-size="<?php  echo $player->display( 'points' ); ?>" data-thickness="35">

                        <button><?php __('VIEW MY TEAM MATES.','gogreensoccer');?></button>
                        <button><?php __('Player ID','gogreensoccer');?><?php echo $playerId;?></button>

But im not getting any text outputed obv I want a default value here if no translation exists i though __(string,themename) would achieve this.

A: You don't use the right function: __() returns the text or the translation if it exists. If you want to display it, you must use echo like this: echo __('some text', 'textdomain').
As an alternative, if you just want to print the text, you can use the _e() function which will echo the text (the one in parentheses or the translation if it exists). You can use it like this for example: _('some text', 'textdomain').

A: Use esc_html_e() function to escape your translatable text and output it.
_e() is a shorthand notation for echo __(), while __() just returns the translated string (not echoing it out).
Anyways, the best practice is to escape all things.


text:
Q: How to autoscale Python webjob based on Service Bus Queues in Azure? When a service bus queue contains any messages, I want my python webjob to scale out so the messages are processed faster.
I have a python webjob which feeds off a Service Bus Queue. The queue is populated each day at midnight and can have between 0 and around 400k messages added to it.
The bottleneck in the current processing is where some data needs to be downloaded, which means that scaling up the webjob won't help as much as parallelising it.
I scaled it up to 10 instances from 1 but that doesn't appear to affect the rate at which messages are consumed from the queue, which suggests that this isn't working the way I expect. When it was on 1 instance it processed ~1.53k in an hour. The hour since scaling out to 10 instances it processed ~1.5k messages (so basically, no difference.)
The code I'm using to interface with the queue is this (if there is a better way of doing this in Python please let me know!):
from azure.servicebus import ServiceBusService, Message, Queue

bus_service = ServiceBusService(
    service_namespace= <namespace>,
    shared_access_key_name='RootManageSharedAccessKey',
    shared_access_key_value=<key>)

while(1):

    msg = bus_service.receive_queue_message(<queue>, peek_lock=False, timeout=1)

    if msg.body is None:

        print("No messages in queue")
        time.sleep(5)
    else:

        number = int(msg.body.decode('utf-8'))
                print(number)

I know in C# there is a QueueTrigger attribute for webjobs but I don't know of anything similar for Python.
I would expect that the more instances running in the app service, the faster messages would be processed, so why isn't that what I see?

A: The bottleneck in the program was the database, which was at maximum. Adding more instances just increased the number of calls on the database and therefore slowed down each instance.
Scaling up the database and optimising the database calls improved performance and also now means that multiple instances can be spun up to further increase throughput.


text:
Q: How to Stop Automatic Scrolling of Image Slider on Touch Event I have created an automatic image slider using custom ViewPager Now i want to know how to stop the automatic sliding of images on touch and start the slider again from it was left when touch is released.
Here is my CustomViewPager.java :-
public class CustomViewPager extends ViewPager {

    private boolean isPagingEnabled = true;

    public CustomViewPager(Context context) {
        super(context);
    }

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        return this.isPagingEnabled && super.onTouchEvent(event);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        return this.isPagingEnabled && super.onInterceptTouchEvent(event);
    }

    public void setPagingEnabled(boolean b) {
        this.isPagingEnabled = b;
    }

}

Here is ImageAdapter.java :-
public  class SlidingImage_Adapter extends PagerAdapter {

    Context context;
    int images[];
    LayoutInflater inflater;

    public SlidingImage_Adapter(Context context, int images[]) {

        this.context = context;
        this.images = images;
        inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public int getCount() {
        return images.length;
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        View itemView = inflater.inflate(R.layout.sliding_images, container, false);

        final ImageView imageView = (ImageView) itemView
                .findViewById(R.id.image);

        imageView.setImageResource(images[position]);

        container.addView(itemView, 0);

        return itemView;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view.equals(object);
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

}

Here is Fragment.java where i am using this CustomViewPager :-
public class HomeFragment extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    TextView tv_slider, tv_button;
    RelativeLayout dummyView;
    CustomViewPager mViewPager;

    Timer timer;
    final long DELAY_MS = 1000;//delay in milliseconds before task is to be executed
    final long PERIOD_MS = 3000;

    private static int currentPage = 0;
    private static int NUM_PAGES = 0;
     int images[] = {R.drawable.ecommerce, R.drawable.digital_marketing, R.drawable.explainer, R.drawable.it_services,
            R.drawable.mobile_app, R.drawable.seo, R.drawable.software, R.drawable.webdesign};
    SlidingImage_Adapter imageAdapter;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public HomeFragment() {

    }

    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
         View v = inflater.inflate(R.layout.fragment_home, container, false);

         tv_slider=(TextView)v.findViewById(R.id.tv_slider);
         tv_slider.setTypeface(EasyFonts.robotoLight(this.getActivity()));
         tv_button=(TextView)v.findViewById(R.id.tv_button);
         tv_button.setTypeface(EasyFonts.robotoLight(this.getActivity()));

        mViewPager = (CustomViewPager) v.findViewById(R.id.pager);
        imageAdapter = new SlidingImage_Adapter(getActivity(),images);
        mViewPager.setAdapter(imageAdapter);

        final Handler handler = new Handler();
        final Runnable Update = new Runnable() {
           public void run() {
                if (currentPage == NUM_PAGES) {
                    currentPage = 0;
                }
                mViewPager.setCurrentItem(currentPage++, true);

            }
        };

                Timer swipeTimer = new Timer();
       swipeTimer.schedule(new TimerTask() {
            @Override
           public void run() {
               handler.post(Update);
           }
       }, DELAY_MS, PERIOD_MS);

        CirclePageIndicator indicator = (CirclePageIndicator)
                v.findViewById(R.id.indicator);

        indicator.setViewPager(mViewPager);

        final float density = getResources().getDisplayMetrics().density;

         //Set circle indicator radius
        indicator.setRadius(3 * density);

        NUM_PAGES =images.length;

        // Pager listener over indicator
        indicator.setOnPageChangeListener(new CustomViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                currentPage = position;

            }

            @Override
            public void onPageScrolled(int pos, float arg1, int arg2) {

                switch (pos){

                    case 0:
                        tv_slider.setText(getString(R.string.es_content));
                        break;

                    case 1:
                        tv_slider.setText(getString(R.string.dm_content));
                        break;

                    case 2:
                        tv_slider.setText(getString(R.string.ev_content));
                        break;

                    case 3:
                        tv_slider.setText(getString(R.string.it_content));
                        break;

                    case 4:
                        tv_slider.setText(getString(R.string.md_content));
                        break;

                    case 5:
                        tv_slider.setText(getString(R.string.seo_content));
                        break;

                    case 6:
                        tv_slider.setText(getString(R.string.sd_content));
                        break;

                    case 7:
                        tv_slider.setText(getString(R.string.wd_content));
                        break;

                }

            }

            @Override
            public void onPageScrollStateChanged(int pos) {

            }
        });

        return v;

    }

A: According to this documentation,  the onTouchEvent which you have already overridden is where to look at.
Now instead of calling super.onTouchEvent(event) again as you did in your method. implement your own custom action. by calling super, you're accepting the default behavior.

A: this is my example code it's working good =>
public class MainActivity extends AppCompatActivity {

    final long DELAY_MS = 1000;//delay in milliseconds before task is to be executed
    final long PERIOD_MS = 3000;
    int currentPage = 0;
    public Timer timer;
    public Timer swipeTimer;
    public static boolean startSlider = true;
    public TextView textView;
    public LinearLayout layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.textView);
        layout = (LinearLayout) findViewById(R.id.layout);

        final Handler handler = new Handler();
        final Runnable Update = new Runnable() {
            public void run() {

                if (currentPage == 6) {
                    currentPage = 0;
                }
                currentPage++;
                textView.setText(String.valueOf(currentPage));

            }
        };

        swipeTimer = new Timer();
        swipeTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (startSlider){
                    handler.post(Update);
                }

            }
        }, DELAY_MS, PERIOD_MS);

        layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (startSlider){
                    startSlider = false;
                }else {
                    startSlider = true;
                }
            }
        });

    }

}

A: i have found a third party library "Library Link" and it has built-in methods for starting and stopping the automatic scrolling.


text:
Q: Convert ISO 8601 to Date So I'm using Jackson to read JSON data. I then am creating a Java object. Then from that Java object I'm reading it and inserting it into a Cassandra table. I ran into issues. I am receiving the dates as such...
"demandDepositAccountOpenDate":"9999-01-01T05:00:00.000+0000"

That's the result of a JSONNode.get function
I need to insert that date into the Cassandra table as 9999-01-01 (this would be a yyyy-MM-dd format)
I don't know what type of variable to make my date field in the Java object. Date? LocalDate? I'm having difficulties. I'm trying DateTimeFormater. SimpleDateFormat. Nothing is working. I tried making the date fields in my java object as Strings but that won't work. Just looking for a clean simple solution.


text:
Q: How does sponge (from moreutils) work? sponge can "soak up" stdin and write it atomically to a file, enabling one to do cat f|sponge a. I want to know how exactly it accomplishes this. How does it know when the input is finished?

A: strace or similar will show the system calls used by sponge, which is probably to write(2) the input read(2) from standard input out to a temporary file, and then to rename(2) that temporary file to the desired output filename when the input ends. The input ends when a read(2) call fails or returns 0 (which indicates end-of-file) at which point sponge can do the rename.


text:
Q: Why does zcat throw "invalid compressed data" when decompressing a file compressed with GzipOutputStream? In C++, I use the GzipOutputStream to compress the data, which is a big string. At first, I have to convert the string to a proto message, like this:
syntax = "proto3";
package Serverlog_Compress;

message ServerlogMessage {
  string data = 1;
}

Then, in the code, I call the GzipOutputStream to compress the data, like:
google::protobuf::io::GzipOutputStream::Options options_;
options_.format = google::protobuf::io::GzipOutputStream::GZIP;
options_.compression_level = 9;

google::protobuf::io::FileOutputStream file_stream(fd);
google::protobuf::io::GzipOutputStream gzip_stream(&file_stream, options_);

auto *message = butil::get_object<Serverlog_Compress::ServerlogMessage>();
message->set_data(data);

int ret = 0;
{
  std::lock_guard<std::mutex> lock(file_mutex_);
  ret = message->SerializeToZeroCopyStream(&gzip_stream);
}
if (!ret) {
  LOG(ERROR) << "Failed to write the message, the ret is " << ret;
  message->Clear();
  butil::return_object(message);
  return -1;
}
message->Clear();
butil::return_object(message);

After I finish the compression, I got the compressed data file, but when I use the zcat to get the file data, I got this error:
gzip: 20200301_12: invalid compressed data--crc error
gzip: 20200301_12: invalid compressed data--length error

20200301_12 is the file name.


text:
Q: Pascal Object: how to do a typed forward declaration? I'm translating the great fmod C header to Pascal, and I'm stuck because of a forward declaration.
If I declare the function before the type, the error is "FMOD_CODEC_STATE: unknown", and if I declare the FMOD_CODEC_STATE before the function, the error is "FMOD_CODEC_METADATACALLBACK: unknown"
Any idea how I could solve this problem?
Thank you very much !
type
  FMOD_CODEC_STATE = Record
    numsubsounds: Integer;
    waveformat: array[0..0] of FMOD_CODEC_WAVEFORMAT;
    plugindata: Pointer;

    filehandle: Pointer;
    filesize: Cardinal;
    fileread: FMOD_FILE_READCALLBACK;
    fileseek: FMOD_FILE_SEEKCALLBACK;
    metadata: FMOD_CODEC_METADATACALLBACK;
  end;
  FMOD_CODEC_METADATACALLBACK    = function (codec_state: FMOD_CODEC_STATE; tagtype: FMOD_TAGTYPE; name: PChar; data: Pointer; datalen: Cardinal; datatype: FMOD_TAGDATATYPE; unique: Integer):FMOD_RESULT;

A: The record doesn't need to be passed by value. In fact, the original C code doesn't pass it by value anyway. It's passed by reference, with a pointer. Declare the pointer, then the function, and then the record:
type
  PFMOD_CODEC_STATE = ^FMOD_CODEC_STATE;
  FMOD_CODEC_METADATACALLBACK = function (codec_state: PFMOD_CODEC_STATE; tagtype: FMOD_TAGTYPE; name: PChar; data: Pointer; datalen: Cardinal; datatype: FMOD_TAGDATATYPE; unique: Integer):FMOD_RESULT;
  FMOD_CODEC_STATE = Record
    numsubsounds: Integer;
    waveformat: PFMOD_CODEC_WAVEFORMAT;
    plugindata: Pointer;

    filehandle: Pointer;
    filesize: Cardinal;
    fileread: FMOD_FILE_READCALLBACK;
    fileseek: FMOD_FILE_SEEKCALLBACK;
    metadata: FMOD_CODEC_METADATACALLBACK;
  end;

Yes, you're allowed to declare a pointer to something before you've declared the thing it points to. You're not allowed to forward-declare records, though, so the order given above is the only possible order for those three declarations.

A: Pascal has automatic forward type declaration for pointer classes, which is what I'm assuming that function actually takes. So simply changing your declarations to something like this (warning, I haven't used pascal in over 12 years) should work:
type
  PFMOD_CODEC_STATE=^FMOD_CODEC_STATE;
  FMOD_CODEC_METADATACALLBACK    = function (codec_state: PFMOD_CODEC_STATE; tagtype: FMOD_TAGTYPE; name: PChar; data: Pointer; datalen: Cardinal; datatype: FMOD_TAGDATATYPE; unique: Integer):FMOD_RESULT;

  FMOD_CODEC_STATE = Record
    numsubsounds: Integer;
    waveformat: array[0..0] of FMOD_CODEC_WAVEFORMAT;
    plugindata: Pointer;

    filehandle: Pointer;
    filesize: Cardinal;
    fileread: FMOD_FILE_READCALLBACK;
    fileseek: FMOD_FILE_SEEKCALLBACK;
    metadata: FMOD_CODEC_METADATACALLBACK;
  end;


text:
Q: How to delete specific piece of array? Okie dokie. Let's see if I can explain myself correctly. In two separate rows of my database, I have data that looks like this:
row1 (labeled "claimed") = Item1, Item2, Item3, Item4
row2 (labeled ctype) = Thing1, Thing2, Thing3, Thing4

I've pulled up the data so they group together like so:
Item1, Thing1
Item2, Thing2...

using this code:
<?php
$select=mysqli_query($connect, "SELECT * FROM `$table_members` WHERE email='$_SESSION[USR_LOGIN]'");
while($row1=mysqli_fetch_assoc($select)) {
    $name1=$row1['name'];
    $claim = $row1['claimed'];
    $type1 = $row1['ctype'];
    if ($claim != 'None') {
        $type2 = explode(', ', $type1);
        $decks = explode(', ', $claim);
        echo "

Name	Claimed	Type
";
        foreach(array_combine($decks, $type2) as $deck => $type3){
            echo "
";
            echo "$name1	";
            echo "$deck	";
            echo "$type3	";
        }
    }
}
?>

The problem now is that after a member submits a form I want to DELETE Item and Thing from the database based on their submission. So for example I have a dropdown showing
-Item1
-Item2...

They select Item2 and submit the form. Now I ONLY want to delete Item2 and Thing2 from my database, so now the rows would look like this:
row1 (labeled "claimed") = Item1, Item3, Item4
row2 (labeled ctype) = Thing1, Thing3, Thing4

I can't seem to figure out how to code it so that only the one particular instance is deleted.
I assume it's something like the following:
foreach(array_combine($decks, $type2) as $deck => $type3){
$gone = "DELETE FROM `$table_members` WHERE claimed='$deck' AND ctype='$type3'";
            mysqli_query($connect, $gone);
}

ETA: I've found a solution! For anybody looking for the same type of thing here's what I did:
$remove = $_POST['remove;']

$select1=mysqli_query($connect, "SELECT * FROM `$table_members` WHERE email='$_SESSION[USR_LOGIN]'");
while($row1=mysqli_fetch_assoc($select1)) {
    $claim = $row1['claimed'];
    $type1 = $row1['ctype'];
}
$type2 = explode(', ', $type1);
$decks = explode(', ', $claim);
for($i=0;$i<count($decks);$i++){
    if($decks[$i]===$remove){unset($decks[$i]); unset($type2[$i]);}
}
$decks = implode(', ',$decks);
$type2 = implode(', ',$type2);
$gone = "UPDATE `$table_members` set claimed='$decks', ctype='$type2' where email='$_SESSION[USR_LOGIN]'";
     mysqli_query($connect, $gone);

A: Let's see if I understand correctly your scenario.
The data in your table looks something like this:
 -------------------------------------------------------------------------
|  Name   |  ctype                          |  claimed                    |
--------------------------------------------------------------------------
|  Jhon   | Thing1, Thing2, Thing3, Thing4  |  Item1, Item2, Item3, Item4 |
 -------------------------------------------------------------------------

In that case if you just want to delete one item at the time, I think your best option will be:
$email = $_SESSION['USR_LOGIN'];
foreach(array_combine($decks, $type2) as $deck => $type3)
{
     $gone = "UPDATE `$table_members` set claimed=REPLACE(claimed,'$deck, ',''), ctype=REPLACE(ctype,'$type3, ', '') where email='$email'";
     mysqli_query($connect, $gone);
}

If you can post a sample of how the data is organized in your table I think I can provide a better example.


text:
Q: What is the easiest way to get the AAD application ID of MSI enabled app service I have a App service deployed with MSI enabled (with system assigned identity). This App service will use MSI to retrieve access token to an AAD protected web API. The web API will retrieve the appid from the token and check the appid against a pre-configured white list, if the appid is not in white list, the access is denied.
So to allow the MSI enabled app service to access the Web API, I need to know the application id of MSI app service and add it to the white list.
I know I can run following powershell script in my app service debug console to retrieve the token and get the appid by decoding the token.
$apiVersion = "2017-09-01"
$resourceURI = "<resource uri of AAD protected Web API>"
$tokenAuthURI = $env:MSI_ENDPOINT + "?resource=$resourceURI&api-version=$apiVersion"
$tokenResponse = Invoke-RestMethod -Method Get -Headers @{"Secret"="$env:MSI_SECRET"} -Uri $tokenAuthURI
$accessToken = $tokenResponse.access_token

But I am wondering if there is easier way to get the appid of MSI app service without retrieving a token.

A: You could use (Get-AzADServicePrincipal -ObjectId xxxx).ApplicationId, the object ID is easy to find when you check it on the web app portal.

You also could search the application in the Enterprise applications by the application ID.


text:
Q: Loading Seaside onto Pharo 2.0 Pharo 2.0 was released recently.  I downloaded it, and tried running this:
Gofer new
    squeaksource: 'MetacelloRepository';
    package: 'ConfigurationOfSeaside30';
    load.
(Smalltalk at: #ConfigurationOfSeaside30) load.

It completed but it didn't create a 'Seaside Control Panel' menu option in the Tools submenu of the World menu.
What are the next steps to take?

A: The control panel was built using OB, which is not available anymore for Pharo 2.0
Therefore, you need to start an adaptor programmatically. In Pharo 2.0, the default adaptor has become the Zinc adaptor. You can start it by executing the following expression:
ZnZincServerAdaptor startOn: 8080

This starts the adaptor on port 8080.


text:
Q: How to take user input like prompt() but in PHP? How can I make a PHP input thing like prompt('example prompt') in javascript?
Not like a form, like a prompt().

A: in php you better use form for inputs, however if you want you can use java script input and alert to read and display as follow.
echo "<script>input=prompt('Enter your name !'); alert(input);</script>";

A: Solution #1: Prompt for get input inside of anywhere code:
<?php
echo "What do you want to input? ";
$input = rtrim(fgets(STDIN));
echo "I got it:\n" . $input;

Sample output:
# php test.php
What do you want to input? Hello, I'm here!
I got it:
Hello, I'm here!

Solution #2: If you want get input in firstly inline when run php:
<?php
$input = $argv[1];
echo "I got it:\n" . $input;

Sample output:
# php test.php "Hello, I'm here!"
I got it:
Hello, I'm here!

Extra tips:
If you want to integrate CLI and WEB inputs, you can use this magic code:
<?php
if (PHP_SAPI === 'cli') parse_str(implode('&', array_slice($argv, 1)), $_GET);
var_dump($_GET);

And now write for use under CLI:
# php sample.php user=nabikaz website=nabi.ir

And follow the normal routine for the WEB:
http://localhost/sample.php?user=nabikaz&website=nabi.ir

Without defining the number and name of inputs.
Both have the same result. ;-)
array(2) {
  ["user"]=>
  string(7) "nabikaz"
  ["website"]=>
  string(7) "nabi.ir"
}

A: You can't take input in the middle of php execution since it finishes before the page is actually shown to the user.  However, you can get input using HTML and receive that using php.  Here's a really basic example:
<?php
    echo $_POST['value'];
?>
<form method="post" action="">
<input type="text" name="value">
<input type="submit">
</form>

It takes the user input and reloads the page.  Then, it echoes what the input was.


text:
Q: Php - When processes are executed I've this:
class A {
  public function __construct()
    include 'file.php';
  }
  bla bla...
  bla bla...
  bla bla...
  bla bla...
  bla bla...
  bla bla...
  bla bla...
}
new A();

The question is:
file.php is a very big data.file and I wanna know if it's loaded when PHP reads construct function or when construct function is called with "new A()";
It' the same for others processes?
It's the same for Javascript?
Thanks a lot

A: new A() is when that include will be evaluated.
It will happen for every instance of A you create.
If you wanted to ensure that it is only actually included one time, and not every time an A object is created, you can change it to include_once 'file.php';
See: http://php.net/include_once

A: With the current code that you display the file will be included everytime you call the constructor.
In other words, each time you call "new A();"